Merge remote-tracking branch 'origin/master' into feat/cua-mcp

This commit is contained in:
Yichen Jiang committed 2026-11-11 18:26:53 +08:00
commit c4dd37eb53
177 files changed
+2316 -540

No files matched your search

@@ -9,11 +9,11 @@
en: e736740546fb8219
zh: 46a16a7a633716ec
/agent-note-session-change-request-bindings/decision:
en: 2bbd058f4edc8bb5
zh: 5cc12bb0aa0864e2
en: 9aa6d0c9c1177aeb
zh: 0f0604176b02e82c
/agent-note-session-change-request-bindings/alternatives-considered:
en: 15fdaef4e432fc72
zh: 8d36c859bd89f403
en: 1e2239783738cec2
zh: 5f248eee47de376e
/agent-note-session-change-request-bindings/consequences:
en: a2960e50ec52c9b6
zh: fd23f4fe1137787d
@@ -12,7 +12,7 @@ A Session that opens or updates pull requests leaves them only in its shell outp
The experimental forge capability seam has three roles. [`dsh-experimental-forge`](../../../../packages/experimental/forge/README.md) defines provider-neutral repository and change request references, a provider registry, and shared polling: watchers of one change request share one loop, each forge has one batched fetch in flight, and the cadence follows check, mergeability, and lifecycle state. [`dsh-experimental-forge-github`](../../../../packages/experimental/forge-github/README.md) is the first provider; it reads GitHub through the GitHub CLI on the host, so credentials stay in that tool's own store and never enter Session execution worlds. [`dsh-experimental-forge-session`](../../../../packages/experimental/forge-session/README.md) binds change requests to Sessions.
Bindings derive from the Session log instead of a separate store. A Session projection reads `bash` and `pwsh` calls: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results record the branches they updated. Those three commands act on one change request, so only the URL given as their first argument and the URL their output prints for that change request count; links in a description name other change requests. Caller actions and discovery results are `plugin:forge-session/binding` records. Because every input is a log event, fork and resume carry bindings without new persistence, and the projection rebuilds them from any checkpoint. The printed URL or ref line is the evidence, not the exit status: an existing pull request reported by a failing `gh pr create` still binds, and a partially rejected push still records the branches it updated.
Bindings derive from the Session log instead of a separate store. A Session projection reads `bash` and `pwsh` calls, including calls a PTC program dispatches, whose `tool/ptc-dispatch` events log the arguments with the settled outcome: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results record the branches they updated. Those three commands act on one change request, so only the URL given as their first argument and the URL their output prints for that change request count; links in a description name other change requests. Caller actions and discovery results are `plugin:forge-session/binding` records. Because every input is a log event, fork and resume carry bindings without new persistence, and the projection rebuilds them from any checkpoint. The printed URL or ref line is the evidence, not the exit status: an existing pull request reported by a failing `gh pr create` still binds, and a partially rejected push still records the branches it updated.
After each push result, and when a caller such as the forge panel reports the branch a Session's checkout tracks, the service looks up open change requests for that branch through the provider and records the unbound ones. A dismissed binding stays hidden from discovery and returns only through `track`. Polled status is not logged; it is process-local state that exists while a watcher displays the Session. The projection's client view therefore carries bindings without status.
@@ -24,6 +24,8 @@ After each push result, and when a caller such as the forge panel reports the br
**Logging polled status in the Session.** Status changes independently of the conversation. Logging it would grow the log with every poll and expose stale snapshots to later readers.
**Recording PTC shell calls as `tool/call` and `tool/result` events, or observing the shell service.** Those events feed model history, so program sub-calls would re-enter model context; a shell-service hook would also see host lookups that no tool call made and would leave earlier PTC Sessions without bindings on replay. The dispatch events already log every sub-call outside model history.
**Running `gh` through the Session's subprocess provider.** Remote and sandboxed execution worlds would need GitHub credentials, and status would depend on the world a Session uses. The host CLI keeps one credential owner.
## Consequences
@@ -12,7 +12,7 @@ Status: implemented
实验性的 forge 能力 seam 由三个角色组成。[`dsh-experimental-forge`](../../../../packages/experimental/forge/README.zh.md) 定义提供方无关的仓库与变更请求引用、提供方注册表与共享轮询:同一变更请求的监听方共享一个循环,每个 forge 同时只有一次批量读取,轮询节奏随检查、可合并性与生命周期状态变化。[`dsh-experimental-forge-github`](../../../../packages/experimental/forge-github/README.zh.md) 是第一个提供方;它通过宿主上的 GitHub CLI 读取 GitHub,因此凭据保留在该工具自己的存储中,从不进入 Session 的执行环境。[`dsh-experimental-forge-session`](../../../../packages/experimental/forge-session/README.zh.md) 把变更请求绑定到 Session。
绑定从 Session 日志派生,而不是存放在单独的存储中。一个 Session 投影读取 `bash` 与 `pwsh` 调用:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果记录其更新的分支。这三个命令只操作一个变更请求,因此只计入作为第一个参数给出的 URL 和输出为该变更请求打印的 URL;描述正文里的链接指向的是其他变更请求。调用方操作与发现结果是 `plugin:forge-session/binding` 插件记录。由于所有输入都是日志事件,fork 与恢复无需新的持久化即可带上绑定,投影也能从任意检查点重建它们。证据是输出中的 URL 或 ref 行,而不是退出状态:失败的 `gh pr create` 报告的已有 pull request 仍会绑定,部分被拒绝的推送仍会记录它已更新的分支。
绑定从 Session 日志派生,而不是存放在单独的存储中。一个 Session 投影读取 `bash` 与 `pwsh` 调用,包括 PTC 程序分派的调用,其 `tool/ptc-dispatch` 事件记录参数与结算结果:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果记录其更新的分支。这三个命令只操作一个变更请求,因此只计入作为第一个参数给出的 URL 和输出为该变更请求打印的 URL;描述正文里的链接指向的是其他变更请求。调用方操作与发现结果是 `plugin:forge-session/binding` 插件记录。由于所有输入都是日志事件,fork 与恢复无需新的持久化即可带上绑定,投影也能从任意检查点重建它们。证据是输出中的 URL 或 ref 行,而不是退出状态:失败的 `gh pr create` 报告的已有 pull request 仍会绑定,部分被拒绝的推送仍会记录它已更新的分支。
每次推送结果之后,以及 forge 面板等调用方报告 Session 检出所跟踪的分支时,服务通过提供方为该分支查找打开状态的变更请求,并记录尚未绑定的那些。被隐藏的绑定不会被发现逻辑恢复,只能通过 `track` 恢复。轮询到的状态不写入日志;它是进程内状态,仅在有监听方展示该 Session 时存在。因此投影的客户端视图只带绑定,不带状态。
@@ -24,6 +24,8 @@ Status: implemented
**把轮询状态写入 Session 日志。** 状态的变化独立于对话。写入日志会让日志随每次轮询增长,并把过期快照暴露给后续读取方。
**把 PTC 内的 shell 调用记录为 `tool/call` 与 `tool/result` 事件,或观察 shell 服务。** 这两种事件会进入模型历史,程序的子调用将重新进入模型上下文;shell 服务钩子还会看到并非由工具调用发起的宿主查询,而且重放早先的 PTC Session 时仍没有绑定。分派事件已经在模型历史之外记录了每个子调用。
**通过 Session 的子进程提供方运行 `gh`。** 远端与沙箱执行环境将需要 GitHub 凭据,状态也会取决于 Session 使用的执行环境。宿主 CLI 让凭据只有一个所有者。
## Consequences
+4
View File
@@ -43,6 +43,10 @@ describe('dsh badge assembled snapshot', () => {
},
],
"error": {
"info": {
"code": "SKILL_NOT_FOUND",
"name": "SkillError",
},
"message": "skill "dsh-badge" is unknown or no longer available",
},
"isError": true,
+46 -15
View File
@@ -472,12 +472,12 @@ interface PanelLaunch {
/**
* Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace.
* @param failureShot - name of the screenshot saved when the test fails.
* @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup.
* @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup through `bash` or a PTC program.
* @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, and
* whether the extension fixture plugin loads.
* @returns the scaffold, page, and checkout.
*/
async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal',
async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' | 'ptc-reference' = 'normal',
options: {
desktop?: 'darwin' | 'win32'
branch?: string
@@ -510,9 +510,13 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
const override = join(root, 'replay.override.json')
// The borrowed scenario records one model call, so index 1 appends the reply to the follow-up.
if (scenario === 'follow-up') await writeFile(override, JSON.stringify({ patches: [{ at: 1, entry: { kind: 'chunks', chunks: textReply(FOLLOW_UP_REPLY) } }] }))
if (scenario === 'reference') {
const reference = scenario === 'reference' || scenario === 'ptc-reference'
if (reference) {
const command = `PATH=${JSON.stringify(`.fixture-bin:${process.env.PATH ?? ''}`)} gh pr view 7 --repo octo/demo --json number,title 2>&1 | head -200`
const call = { type: 'tool-call', id: 'view-pr', name: 'bash', arguments: JSON.stringify({ command, description: 'View PR metadata' }) }
const bash = { command, description: 'View PR metadata' }
const call = { type: 'tool-call', id: 'view-pr', ...scenario === 'reference'
? { name: 'bash', arguments: JSON.stringify(bash) }
: { name: 'run_code', arguments: JSON.stringify({ code: `await tools.bash(${JSON.stringify(bash)})`, description: 'View PR metadata' }) } }
await writeFile(override, JSON.stringify({ patches: [
{ at: 0, entry: { kind: 'chunks', chunks: [
{ type: 'block-start', index: 0, blockType: 'tool-call' },
@@ -545,7 +549,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
await git(project, 'branch', 'release')
await git(project, 'commit', '--quiet', '--allow-empty', '-m', 'main only')
if (options.branch !== undefined) await git(project, 'checkout', '--quiet', '-b', options.branch)
if (scenario === 'reference') {
if (reference) {
// The model's confined command must own the CLI double's writable call log.
const modelBin = join(project, '.fixture-bin')
await mkdir(modelBin)
@@ -584,6 +588,11 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
onTestFailed(async () => { await saveFailureShot(page, failureShot) })
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
if (scenario === 'ptc-reference') {
const [agent] = scaffold.ctx.agents.list()
if (agent === undefined) throw new Error('The connected workspace has no blank Session')
await scaffold.ctx.agentPresets.select(agent, 'ptc')
}
return { scaffold, page, root, project, tripwire }
}
@@ -701,16 +710,12 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie
expect(tripwire.warnings).toEqual([])
})
it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omits its URL', async () => {
const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-numbered-reference', 'reference')
const { settled } = await sendPrompt(page, scaffold)
const sessionId = await settled
const events = await readPersistedEvents(scaffold, sessionId)
const request = events.find(event => event.type === 'request/header')
expect(request?.data.header.tools?.filter(tool => tool.name === 'create_worktree')).toHaveLength(1)
const toolOutput = events.flatMap(event => event.type === 'tool/result'
? event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []) : []).join('\n')
expect(toolOutput).toContain('Add the pull request panel')
/**
* Expect the panel to show PR 7, which the model viewed by number without its URL in the output, and the lookup that resolved it.
* @param launch - the panel launched for a reference scenario.
* @param sessionId - Session whose binding records are read.
*/
async function expectNumberedReference({ scaffold, page, project, tripwire }: PanelLaunch, sessionId: SessionId): Promise<void> {
const header = page.locator('[data-forge-header]')
await expect.poll(() => header.getAttribute('aria-label'), { timeout: 20_000 }).toBe('本会话的变更请求需要处理')
await header.click()
@@ -731,6 +736,32 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url'])
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}
it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omits its URL', async () => {
const launch = await launchPanel('web-e2e-forge-numbered-reference', 'reference')
const { settled } = await sendPrompt(launch.page, launch.scaffold)
const sessionId = await settled
const events = await readPersistedEvents(launch.scaffold, sessionId)
const request = events.find(event => event.type === 'request/header')
expect(request?.data.header.tools?.filter(tool => tool.name === 'create_worktree')).toHaveLength(1)
const toolOutput = events.flatMap(event => event.type === 'tool/result'
? event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []) : []).join('\n')
expect(toolOutput).toContain('Add the pull request panel')
await expectNumberedReference(launch, sessionId)
})
it.skipIf(MODE === 'record')('automatically shows a numbered PR that a PTC program views when gh JSON omits its URL', async () => {
const launch = await launchPanel('web-e2e-forge-ptc-reference', 'ptc-reference')
const { settled } = await sendPrompt(launch.page, launch.scaffold)
const sessionId = await settled
const events = await readPersistedEvents(launch.scaffold, sessionId)
expect(events.find(event => event.type === 'request/header')?.data.header.tools?.map(tool => tool.name)).toEqual(['run_code'])
expect(events.flatMap(event => event.type === 'tool/call' ? [event.data.name] : [])).toEqual(['run_code'])
const dispatches = events.flatMap(event => event.type === 'tool/ptc-dispatch' ? [event.data] : [])
expect(dispatches.map(dispatch => [dispatch.name, dispatch.isError])).toEqual([['bash', false]])
expect(dispatches[0]?.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')).toContain('Add the pull request panel')
await expectNumberedReference(launch, sessionId)
})
it.skipIf(MODE === 'record')('starts a Session in a worktree before its first message, follows its change request, and restores the removed worktree', async () => {
+8 -8
View File
@@ -851,7 +851,7 @@ export interface ToolResultPruneConfig {
## `@deepseek-ai/dsh-cordis-host-runner`
- `inject`: `tools`
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:104`](../packages/extensions/cordis-host-runner/src/index.ts)
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts)
```ts config-catalog
/** Runner configuration. */
@@ -2436,7 +2436,7 @@ export interface LspLocalServerConfig {
## `@deepseek-ai/dsh-mcp-client`
- `inject`: `tools`
- `source`: [`packages/mcp/mcp-client/src/index.ts:138`](../packages/mcp/mcp-client/src/index.ts)
- `source`: [`packages/mcp/mcp-client/src/index.ts:140`](../packages/mcp/mcp-client/src/index.ts)
```ts config-catalog
/** Configuration for one stdio or Streamable HTTP MCP server. */
@@ -2740,7 +2740,7 @@ export interface PlanModeConfig {
- `inject`: `loader` · `profileContext`
- `refs`: [`NpmFileSource`](subsystems/boot.md)
- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts)
- `source`: [`packages/boot/plugin-manager/src/index.ts:56`](../packages/boot/plugin-manager/src/index.ts)
```ts config-catalog
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -2790,7 +2790,7 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:43`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
@@ -3435,7 +3435,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill`
- `source`: [`packages/skill/skill/src/index.ts:278`](../packages/skill/skill/src/index.ts)
- `source`: [`packages/skill/skill/src/index.ts:281`](../packages/skill/skill/src/index.ts)
```ts config-catalog
/** Skill registry configuration. */
@@ -3452,7 +3452,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill-filesystem`
- `inject`: `skills`
- `source`: [`packages/skill/skill-filesystem/src/index.ts:48`](../packages/skill/skill-filesystem/src/index.ts)
- `source`: [`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
```ts config-catalog
/** Local filesystem skill provider configuration. */
@@ -4500,7 +4500,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-skill`
- `inject`: `agents` · `tools` · `skills` · `workingDirectory`
- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts)
- `source`: [`packages/skill/tool-skill/src/index.ts:65`](../packages/skill/tool-skill/src/index.ts)
```ts config-catalog
/** Model-facing skill catalog configuration. */
@@ -4711,7 +4711,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-workspace-dependencies`
- `inject`: `tools`
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:15`](../packages/skill/tool-workspace-dependencies/src/index.ts)
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:18`](../packages/skill/tool-workspace-dependencies/src/index.ts)
```ts config-catalog
/** Payload location and optional installation directory. */
+8 -8
View File
@@ -853,7 +853,7 @@ export interface ToolResultPruneConfig {
## `@deepseek-ai/dsh-cordis-host-runner`
- `inject`: `tools`
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:104`](../packages/extensions/cordis-host-runner/src/index.ts)
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts)
```ts config-catalog
/** Runner configuration. */
@@ -2438,7 +2438,7 @@ export interface LspLocalServerConfig {
## `@deepseek-ai/dsh-mcp-client`
- `inject`: `tools`
- `source`: [`packages/mcp/mcp-client/src/index.ts:138`](../packages/mcp/mcp-client/src/index.ts)
- `source`: [`packages/mcp/mcp-client/src/index.ts:140`](../packages/mcp/mcp-client/src/index.ts)
```ts config-catalog
/** Configuration for one stdio or Streamable HTTP MCP server. */
@@ -2742,7 +2742,7 @@ export interface PlanModeConfig {
- `inject`: `loader` · `profileContext`
- `refs`: [`NpmFileSource`](subsystems/boot.zh.md)
- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts)
- `source`: [`packages/boot/plugin-manager/src/index.ts:56`](../packages/boot/plugin-manager/src/index.ts)
```ts config-catalog
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -2792,7 +2792,7 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.zh.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:43`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
@@ -3437,7 +3437,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill`
- `source`: [`packages/skill/skill/src/index.ts:278`](../packages/skill/skill/src/index.ts)
- `source`: [`packages/skill/skill/src/index.ts:281`](../packages/skill/skill/src/index.ts)
```ts config-catalog
/** Skill registry configuration. */
@@ -3454,7 +3454,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill-filesystem`
- `inject`: `skills`
- `source`: [`packages/skill/skill-filesystem/src/index.ts:48`](../packages/skill/skill-filesystem/src/index.ts)
- `source`: [`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
```ts config-catalog
/** Local filesystem skill provider configuration. */
@@ -4502,7 +4502,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-skill`
- `inject`: `agents` · `tools` · `skills` · `workingDirectory`
- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts)
- `source`: [`packages/skill/tool-skill/src/index.ts:65`](../packages/skill/tool-skill/src/index.ts)
```ts config-catalog
/** Model-facing skill catalog configuration. */
@@ -4713,7 +4713,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-workspace-dependencies`
- `inject`: `tools`
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:15`](../packages/skill/tool-workspace-dependencies/src/index.ts)
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:18`](../packages/skill/tool-workspace-dependencies/src/index.ts)
```ts config-catalog
/** Payload location and optional installation directory. */
+1 -1
View File
@@ -77,7 +77,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
+1 -1
View File
@@ -79,7 +79,7 @@
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
+23 -14
View File
@@ -488,6 +488,7 @@ flowchart TD
subgraph group_workspace["packages/workspace"]
pkg_workspace["workspace"]
end
pkg_atomic_write --> pkg_error
pkg_llm --> pkg_error
pkg_session --> pkg_scope
pkg_api_remotes --> pkg_scope
@@ -495,10 +496,6 @@ flowchart TD
pkg_app_boot --> pkg_home_paths
pkg_app_boot --> pkg_launch_environment
pkg_client_connection --> pkg_scope
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use
pkg_experimental_liveshare --> pkg_scope
pkg_anonymous_user_id --> pkg_brand
@@ -514,6 +511,7 @@ flowchart TD
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_error
pkg_skill --> pkg_llm
pkg_skill --> pkg_scope
pkg_web --> pkg_llm
@@ -526,6 +524,10 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_llm
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_cua_mcp --> pkg_app_boot
pkg_cua_mcp --> pkg_attachment
pkg_experimental_forge_github --> pkg_experimental_forge
@@ -585,6 +587,7 @@ flowchart TD
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_attachment
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -878,6 +881,7 @@ flowchart TD
pkg_tool_skill --> pkg_skill
pkg_tool_skill --> pkg_tools
pkg_tool_skill --> pkg_working_directory
pkg_tool_workspace_dependencies --> pkg_error
pkg_tool_workspace_dependencies --> pkg_tools
pkg_tool_web --> pkg_llm
pkg_tool_web --> pkg_system_prompt
@@ -995,6 +999,7 @@ flowchart TD
pkg_tool_terminal --> pkg_tools
pkg_tool_terminal --> pkg_working_directory
pkg_cordis_host_runner --> pkg_agent
pkg_cordis_host_runner --> pkg_error
pkg_cordis_host_runner --> pkg_llm
pkg_cordis_host_runner --> pkg_scope
pkg_cordis_host_runner --> pkg_session
@@ -1127,6 +1132,7 @@ flowchart TD
pkg_experimental_auto_review --> pkg_tools
pkg_experimental_auto_review --> pkg_working_directory
pkg_experimental_forge_session --> pkg_experimental_forge
pkg_experimental_forge_session --> pkg_llm
pkg_experimental_forge_session --> pkg_sandbox_policy
pkg_experimental_forge_session --> pkg_session
pkg_experimental_forge_session --> pkg_session_projection
@@ -1150,6 +1156,7 @@ flowchart TD
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_mcp_client --> pkg_attachment
pkg_mcp_client --> pkg_credentials
pkg_mcp_client --> pkg_error
pkg_mcp_client --> pkg_llm
pkg_mcp_client --> pkg_mcp_resources
pkg_mcp_client --> pkg_scope
@@ -1245,6 +1252,7 @@ flowchart TD
pkg_acp --> pkg_session_persistence
pkg_acp --> pkg_token_meter
pkg_acp --> pkg_user_approval
pkg_plugin_manager --> pkg_error
pkg_plugin_manager --> pkg_hmr
pkg_plugin_manager --> pkg_host_plugin_inventory
pkg_plugin_manager --> pkg_sandbox
@@ -1373,6 +1381,7 @@ flowchart TD
pkg_api_session_controller --> pkg_util_workspace_path
pkg_api_session_controller --> pkg_working_directory
pkg_api_session_controller --> pkg_workspace
pkg_plugin_market --> pkg_error
pkg_plugin_market --> pkg_plugin_manager
pkg_plugin_market --> pkg_settings
pkg_plugin_market --> pkg_subprocess
@@ -1537,7 +1546,6 @@ flowchart TD
<!-- BEGIN GENERATED module-graph:packages -->
| `package` | `group` | `peerDependencies` |
| --- | --- | --- |
| [`atomic-write`](../packages/util/atomic-write) | `util` | — |
| [`brand`](../packages/util/brand) | `util` | — |
| [`chunked-list`](../packages/util/chunked-list) | `util` | — |
| [`deque`](../packages/util/deque) | `util` | — |
@@ -1687,13 +1695,13 @@ flowchart TD
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — |
| [`typert-generator`](../packages/typert/generator) | `typert` | — |
| [`typert-registry`](../packages/typert/registry) | `typert` | — |
| [`atomic-write`](../packages/util/atomic-write) | `util` | [`error`](../packages/util/error) |
| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) |
| [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) |
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`error`](../packages/util/error) |
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) |
| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
@@ -1706,13 +1714,14 @@ flowchart TD
| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
| [`spill`](../packages/spill/spill) | `spill` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
@@ -1742,7 +1751,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
@@ -1808,7 +1817,7 @@ flowchart TD
| [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) |
| [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`error`](../packages/util/error), [`tools`](../packages/core/tools) |
| [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) |
| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
@@ -1831,7 +1840,7 @@ flowchart TD
| [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) |
| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) |
| [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) |
| [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
@@ -1857,11 +1866,11 @@ flowchart TD
| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) |
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
@@ -1874,7 +1883,7 @@ flowchart TD
| [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) |
| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) |
| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
@@ -1891,7 +1900,7 @@ flowchart TD
| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
+23 -14
View File
@@ -490,6 +490,7 @@ flowchart TD
subgraph group_workspace["packages/workspace"]
pkg_workspace["workspace"]
end
pkg_atomic_write --> pkg_error
pkg_llm --> pkg_error
pkg_session --> pkg_scope
pkg_api_remotes --> pkg_scope
@@ -497,10 +498,6 @@ flowchart TD
pkg_app_boot --> pkg_home_paths
pkg_app_boot --> pkg_launch_environment
pkg_client_connection --> pkg_scope
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use
pkg_experimental_liveshare --> pkg_scope
pkg_anonymous_user_id --> pkg_brand
@@ -516,6 +513,7 @@ flowchart TD
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_error
pkg_skill --> pkg_llm
pkg_skill --> pkg_scope
pkg_web --> pkg_llm
@@ -528,6 +526,10 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_llm
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_cua_mcp --> pkg_app_boot
pkg_cua_mcp --> pkg_attachment
pkg_experimental_forge_github --> pkg_experimental_forge
@@ -587,6 +589,7 @@ flowchart TD
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_attachment
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -880,6 +883,7 @@ flowchart TD
pkg_tool_skill --> pkg_skill
pkg_tool_skill --> pkg_tools
pkg_tool_skill --> pkg_working_directory
pkg_tool_workspace_dependencies --> pkg_error
pkg_tool_workspace_dependencies --> pkg_tools
pkg_tool_web --> pkg_llm
pkg_tool_web --> pkg_system_prompt
@@ -997,6 +1001,7 @@ flowchart TD
pkg_tool_terminal --> pkg_tools
pkg_tool_terminal --> pkg_working_directory
pkg_cordis_host_runner --> pkg_agent
pkg_cordis_host_runner --> pkg_error
pkg_cordis_host_runner --> pkg_llm
pkg_cordis_host_runner --> pkg_scope
pkg_cordis_host_runner --> pkg_session
@@ -1129,6 +1134,7 @@ flowchart TD
pkg_experimental_auto_review --> pkg_tools
pkg_experimental_auto_review --> pkg_working_directory
pkg_experimental_forge_session --> pkg_experimental_forge
pkg_experimental_forge_session --> pkg_llm
pkg_experimental_forge_session --> pkg_sandbox_policy
pkg_experimental_forge_session --> pkg_session
pkg_experimental_forge_session --> pkg_session_projection
@@ -1152,6 +1158,7 @@ flowchart TD
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_mcp_client --> pkg_attachment
pkg_mcp_client --> pkg_credentials
pkg_mcp_client --> pkg_error
pkg_mcp_client --> pkg_llm
pkg_mcp_client --> pkg_mcp_resources
pkg_mcp_client --> pkg_scope
@@ -1247,6 +1254,7 @@ flowchart TD
pkg_acp --> pkg_session_persistence
pkg_acp --> pkg_token_meter
pkg_acp --> pkg_user_approval
pkg_plugin_manager --> pkg_error
pkg_plugin_manager --> pkg_hmr
pkg_plugin_manager --> pkg_host_plugin_inventory
pkg_plugin_manager --> pkg_sandbox
@@ -1375,6 +1383,7 @@ flowchart TD
pkg_api_session_controller --> pkg_util_workspace_path
pkg_api_session_controller --> pkg_working_directory
pkg_api_session_controller --> pkg_workspace
pkg_plugin_market --> pkg_error
pkg_plugin_market --> pkg_plugin_manager
pkg_plugin_market --> pkg_settings
pkg_plugin_market --> pkg_subprocess
@@ -1539,7 +1548,6 @@ flowchart TD
<!-- BEGIN GENERATED module-graph:packages -->
| `package` | `group` | `peerDependencies` |
| --- | --- | --- |
| [`atomic-write`](../packages/util/atomic-write) | `util` | — |
| [`brand`](../packages/util/brand) | `util` | — |
| [`chunked-list`](../packages/util/chunked-list) | `util` | — |
| [`deque`](../packages/util/deque) | `util` | — |
@@ -1689,13 +1697,13 @@ flowchart TD
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — |
| [`typert-generator`](../packages/typert/generator) | `typert` | — |
| [`typert-registry`](../packages/typert/registry) | `typert` | — |
| [`atomic-write`](../packages/util/atomic-write) | `util` | [`error`](../packages/util/error) |
| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) |
| [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) |
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`error`](../packages/util/error) |
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) |
| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
@@ -1708,13 +1716,14 @@ flowchart TD
| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
| [`spill`](../packages/spill/spill) | `spill` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
@@ -1744,7 +1753,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
@@ -1810,7 +1819,7 @@ flowchart TD
| [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) |
| [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`error`](../packages/util/error), [`tools`](../packages/core/tools) |
| [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) |
| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
@@ -1833,7 +1842,7 @@ flowchart TD
| [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) |
| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) |
| [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) |
| [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
@@ -1859,11 +1868,11 @@ flowchart TD
| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) |
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
@@ -1876,7 +1885,7 @@ flowchart TD
| [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) |
| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) |
| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
@@ -1893,7 +1902,7 @@ flowchart TD
| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
+6 -6
View File
@@ -1239,11 +1239,11 @@
en: a7b8c3f842059eec
zh: 4b345faa13cc39f6
/session-persistence-event-catalog/resolved-persistence-types/skillcatalogsource:
en: 2c3148e4a9f0c8f9
zh: dab42cb485067bcd
en: 615f4a7645b94dab
zh: 9e93a88507f2bca4
/session-persistence-event-catalog/resolved-persistence-types/skillinvocationsource:
en: ecc15ebadb77afdf
zh: 97ac27d6a4175f6f
en: 29df35a8cc984e75
zh: 321b4e8bb0ad0850
/session-persistence-event-catalog/resolved-persistence-types/streamchunk:
en: 747e384b3176e0cb
zh: defbff408ea7c97c
@@ -1506,8 +1506,8 @@
en: 10a2d594b106f6fe
zh: 8408379e744ad987
/session-persistence-event-catalog/resolved-persistence-types/description-name:
en: 26072d80c066a334
zh: 48deed5b57fecba4
en: a09e74cd05d03b0e
zh: aa51b3c5db030513
/session-persistence-event-catalog/resolved-persistence-types/description-name~2:
en: a07969828eed2e6f
zh: e06893743af544b5
+3 -3
View File
@@ -4840,7 +4840,7 @@ Sources: [`packages/experimental/liveshare/src/host/viewer-principal.ts:24`](../
SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts)
Sources: [`packages/skill/tool-skill/src/index.ts:36`](../packages/skill/tool-skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
@@ -4860,7 +4860,7 @@ Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-sk
SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/index.ts)
Sources: [`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
@@ -6278,7 +6278,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:30`](../packages/llm/llm-retry/sr
SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693`
Sources: [`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts)
Sources: [`packages/skill/tool-skill/src/index.ts:44`](../packages/skill/tool-skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
+3 -3
View File
@@ -4842,7 +4842,7 @@ SHA-256: `4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b`
SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
来源:[`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts)
来源:[`packages/skill/tool-skill/src/index.ts:36`](../packages/skill/tool-skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -4862,7 +4862,7 @@ SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
来源:[`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/index.ts)
来源:[`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -6280,7 +6280,7 @@ SHA-256: `374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b`
SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693`
来源:[`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts)
来源:[`packages/skill/tool-skill/src/index.ts:44`](../packages/skill/tool-skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
+3 -3
View File
@@ -322,9 +322,9 @@
{"digest":"6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f","names":["packages/subagent/subagent/src/descriptor.ts#ContinuableSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:72"]},
{"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]},
{"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:34"]},
{"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]},
{"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]},
{"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]},
{"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:146"]},
{"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:149"]},
{"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:30"]},
{"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]},
{"digest":"688e853dc149f0d30b31765c12ec7e3be74169bdf1a4c6463a10b945d50cc1b8","names":[],"sources":[]},
@@ -392,7 +392,7 @@
{"digest":"824b1d4d4f007bdaa5eee7994a5db3ede7707c6cd2bf8e2509be176c7609e3bc","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]},
{"digest":"825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8","names":[],"sources":[]},
{"digest":"829a2fb3be6efd4ba36aef8ed2d381a4c6fb2a0aaf50c823a6f3f8290786b809","names":[],"sources":[]},
{"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:43"]},
{"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:44"]},
{"digest":"8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6","names":[],"sources":[]},
{"digest":"83d6916021eede8f2d83a1872716caa1efdec39a3681890996c55147187fdd12","names":[],"sources":[]},
{"digest":"83da72c6857601c75da11212ef847f57d457b9c99f0a82246dcdff3e26700239","names":["packages/context/agent-instructions/src/render.ts#AgentInstructionChange"],"sources":["packages/context/agent-instructions/src/render.ts:62"]},
+4
View File
@@ -233,6 +233,8 @@ Manage profile files and apply their declared reload lifecycle.
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote async listPlugins(): Promise<PluginInfo[]>
@@ -240,6 +242,8 @@ Manage profile files and apply their declared reload lifecycle.
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote listBundles(): Promise<BundleInfo[]>
+4
View File
@@ -233,6 +233,8 @@ Manage profile files and apply their declared reload lifecycle.
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote async listPlugins(): Promise<PluginInfo[]>
@@ -240,6 +242,8 @@ Manage profile files and apply their declared reload lifecycle.
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote listBundles(): Promise<BundleInfo[]>
+3
View File
@@ -48,6 +48,9 @@ list(): CordisInspectProviderView[]
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query( platform: CordisInspectPlatform, providerId: string, methodName: string, input: JsonValue | undefined, agent: Agent, signal: AbortSignal, ): Promise<JsonValue>
+3
View File
@@ -48,6 +48,9 @@ list(): CordisInspectProviderView[]
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query( platform: CordisInspectPlatform, providerId: string, methodName: string, input: JsonValue | undefined, agent: Agent, signal: AbortSignal, ): Promise<JsonValue>
+1 -1
View File
@@ -2066,7 +2066,7 @@ Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/ex
### `ctx.forgeSession` — `ForgeSessionService`
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
```ts cordis-catalog
/**
+1 -1
View File
@@ -2068,7 +2068,7 @@ Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/ex
### `ctx.forgeSession` — `ForgeSessionService`
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
```ts cordis-catalog
/**
+2 -2
View File
@@ -18,8 +18,8 @@
en: 9aa0df86a35e1a0e
zh: 58f5382ef3f11f06
/mcp/protocol-and-results:
en: 46e9b914f016b636
zh: e1e9ee92a22f2562
en: e935c5aaa53e0e81
zh: c86cea6be89bb1db
/mcp/resources-and-instructions:
en: df9cc13a5d6eb923
zh: 3276d65c19d4c446
+1 -1
View File
@@ -55,7 +55,7 @@ The [native Cua Driver provider](../../packages/experimental/computer-use-cua-dr
Both stdio and Streamable HTTP use the official SDK's negotiation, discovery, protocol validation, and cancellation. Tool-list changes trigger discovery through legacy notifications or a modern subscription. A failed refresh retains the previous tool generation; connection recovery follows the [client lifecycle](../../packages/mcp/mcp-client/README.md#use-this-package).
The result adapter retains canonical MCP JSON for programmatic callers and prepares ordinary tool content. Supported images use the attachment system; unsupported rich content produces explicit text diagnostics. The tool registry remains authoritative for policy failures and replaced results. The [tool contracts](tools.md) own recording and final presentation; the [client result reference](../../packages/mcp/mcp-client/README.md#use-this-package) owns MCP-specific projection details.
The result adapter retains canonical MCP JSON for programmatic callers and prepares ordinary tool content. Supported images use the attachment system; unsupported rich content produces explicit text diagnostics. Server `isError` results and request failures throw `McpToolError` with a code that tells the caller whether the request's outcome is known, such as `MCP_TOOL_ERROR`, `MCP_CONNECTION_CLOSED`, or `MCP_TIMEOUT`; the client README lists every code. The tool registry remains authoritative for policy failures and replaced results. The [tool contracts](tools.md) own recording and final presentation; the [client result reference](../../packages/mcp/mcp-client/README.md#use-this-package) owns MCP-specific projection details.
-----
+1 -1
View File
@@ -55,7 +55,7 @@ Web 与 Desktop profile 还统一挂载一次 [MCP 服务器管理器](../../pac
stdio 和 Streamable HTTP 都使用官方 SDK 的协商、发现、协议校验和取消机制。工具列表变化通过旧版通知或现代订阅触发发现。刷新失败时保留上一代工具;连接恢复遵循[客户端生命周期](../../packages/mcp/mcp-client/README.zh.md#use-this-package)。
结果适配器为程序化调用方保留规范 MCP JSON,并准备普通工具内容。受支持的图像使用附件系统;不受支持的富内容产生明确的文本诊断。工具注册表仍决定策略失败和结果替换。[工具契约](tools.zh.md) 维护记录和最终呈现规则;[客户端结果参考](../../packages/mcp/mcp-client/README.zh.md#use-this-package) 维护 MCP 特有的投影细节。
结果适配器为程序化调用方保留规范 MCP JSON,并准备普通工具内容。受支持的图像使用附件系统;不受支持的富内容产生明确的文本诊断。服务器 `isError` 结果与请求失败抛出 `McpToolError`,其 code 告诉调用方请求结果是否已知,例如 `MCP_TOOL_ERROR`、`MCP_CONNECTION_CLOSED` 或 `MCP_TIMEOUT`;客户端 README 列出全部 code。工具注册表仍决定策略失败和结果替换。[工具契约](tools.zh.md) 维护记录和最终呈现规则;[客户端结果参考](../../packages/mcp/mcp-client/README.zh.md#use-this-package) 维护 MCP 特有的投影细节。
-----
+2 -2
View File
@@ -250,7 +250,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
```ts cordis-catalog
/**
@@ -281,7 +281,7 @@ registerEnvironmentInitializer(program: string): () => Promise<void>
* Resolve supported options and provider defaults before execution.
* @param request - Program, bindings, cancellation and optional execution choices.
* @returns Complete directory, deadline and supported authority for run.
* @throws When an explicit choice is invalid or unsupported by this provider.
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
*/
abstract resolve(request: PtcRunRequest): PtcRunSpec
+2 -2
View File
@@ -250,7 +250,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
```ts cordis-catalog
/**
@@ -281,7 +281,7 @@ registerEnvironmentInitializer(program: string): () => Promise<void>
* Resolve supported options and provider defaults before execution.
* @param request - Program, bindings, cancellation and optional execution choices.
* @returns Complete directory, deadline and supported authority for run.
* @throws When an explicit choice is invalid or unsupported by this provider.
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
*/
abstract resolve(request: PtcRunRequest): PtcRunSpec
+2 -2
View File
@@ -6,8 +6,8 @@
en: ad77015352a17ed6
zh: 5c84933161845393
/skills/provider-registry:
en: abe338b6c6d1ebd1
zh: c604db2de10a23c4
en: 3fe1dff933bdb3f4
zh: b3f21b85a38bfaef
/skills/local-discovery-priority:
en: 390fc00bbccfb777
zh: 96ff7abfbd4b911b
+1 -1
View File
@@ -12,7 +12,7 @@ Source: [`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/ind
The registry is host+per-scope layered, the shape the [tools registry](tools.md) established over [dsh-scope](../../packages/core/scope): a registration files into the layer of its calling context's scope, so host rows and repository plugins land in the global layer while a plugin mounted by an agent preset's standing composition lands in that preset's layer, and provider names are unique per layer rather than process-wide. A read merges the global layer with the viewing scope's chain — the nearest layer's entry wins a duplicate skill name outright, and the rank order below decides duplicates only within one layer. Discovery caches are keyed by the resolved scope chain, so re-parenting a scope (a blank-session recompose) is visible to the next read without a registry mutation.
Within one layer, duplicate names resolve by rank, provider order, then local order; summaries sort by name. A rejected `list()` is logged and omitted from an incomplete observation, while an explicit incomplete observation contributes usable candidates without making the result cacheable; malformed candidates fail fast. Each provider factory receives a registration-scoped control whose `invalidate()` clears completed catalogs only while that exact registration remains active and whose signal aborts on failed registration or disposal. An in-flight discovery retries once when its provider generation changes; a second change returns the latest candidates incomplete and uncached. Provider and runtime mutations emit the unfiltered `skills/change` invalidation event; it carries no diff, so consumers refetch `snapshot()` with their own lookup options.
Within one layer, duplicate names resolve by rank, provider order, then local order; summaries sort by name. A rejected `list()` is logged and omitted from an incomplete observation, while an explicit incomplete observation contributes usable candidates without making the result cacheable; malformed candidates fail fast as `SkillError` with `SKILL_INVALID_DEFINITION`. Each provider factory receives a registration-scoped control whose `invalidate()` clears completed catalogs only while that exact registration remains active and whose signal aborts on failed registration or disposal. An in-flight discovery retries once when its provider generation changes; a second change returns the latest candidates incomplete and uncached. Provider and runtime mutations emit the unfiltered `skills/change` invalidation event; it carries no diff, so consumers refetch `snapshot()` with their own lookup options.
An array returned by `SkillProvider.list()` is complete-discovery shorthand. `SkillProviderObservation` lets a provider expose candidates that remain directly loadable while reporting that the observation is not authoritative.
+1 -1
View File
@@ -12,7 +12,7 @@
注册表采用宿主 + 按 scope 的分层结构,即[工具注册表](tools.zh.md)在 [dsh-scope](../../packages/core/scope) 之上确立的形态:注册会落入调用方上下文 scope 对应的层——宿主行与 repository 插件落入全局层,由 agent(智能体) preset 常驻组合挂载的插件落入该 preset 的层——提供方名称在每层内唯一,而非进程级唯一。读取时将全局层与观察 scope 的链合并:最近层的条目直接赢得重名 skill,下文的 rank 顺序只在单层内裁决重名。发现缓存以解析后的 scope 链为键,因此重设 scope 父级(空会话重组)无需注册表变更即可被下一次读取看到。
在单层内,重名项依次按 rank、提供方顺序和本地顺序确定优先级;摘要按名称排序。提供方的 `list()` 被拒绝时,系统会记录日志,并从不完整观测中省略该提供方的结果;显式的不完整观测会提供可用候选项,但不会使结果变得可缓存;格式错误的候选项快速失败。每个提供方工厂都会接收一项注册作用域内的控制能力;仅当该精确注册仍处于活动状态时,其 `invalidate()` 才会清除已完成目录;注册失败或 dispose(资源释放)时,其信号会中止。若提供方代次在发现进行期间发生变化,该发现会重试一次;若再次变化,则返回最新候选项,并将结果标为不完整且不予缓存。提供方和运行时变更会发出不带过滤条件的 `skills/change` 失效事件;该事件不携带 diff,因此消费方会使用自身的查找选项重新获取 `snapshot()`。
在单层内,重名项依次按 rank、提供方顺序和本地顺序确定优先级;摘要按名称排序。提供方的 `list()` 被拒绝时,系统会记录日志,并从不完整观测中省略该提供方的结果;显式的不完整观测会提供可用候选项,但不会使结果变得可缓存;格式错误的候选项以带 `SKILL_INVALID_DEFINITION` 的 `SkillError` 快速失败。每个提供方工厂都会接收一项注册作用域内的控制能力;仅当该精确注册仍处于活动状态时,其 `invalidate()` 才会清除已完成目录;注册失败或 dispose(资源释放)时,其信号会中止。若提供方代次在发现进行期间发生变化,该发现会重试一次;若再次变化,则返回最新候选项,并将结果标为不完整且不予缓存。提供方和运行时变更会发出不带过滤条件的 `skills/change` 失效事件;该事件不携带 diff,因此消费方会使用自身的查找选项重新获取 `snapshot()`。
`SkillProvider.list()` 返回的数组是完整发现的简写形式。`SkillProviderObservation` 允许提供方公开仍可直接加载的候选项,同时报告该观测不具权威性。
@@ -39,8 +39,8 @@
en: 1815ec6ce56c80d4
zh: 2d7ac75d3b25eb6b
/deepseek-ai-dsh-plugin-manager/model-experience/management-tool/what-the-model-sees:
en: b1dae91f98350290
zh: 802ae86d923ac6ce
en: 9bb316cf4b47ba60
zh: 1c719feedf36e2f3
/deepseek-ai-dsh-plugin-manager/model-experience/management-tool/token-effect:
en: bc70208bd361dbcd
zh: bb651d6066066c6c
+1 -1
View File
@@ -152,7 +152,7 @@ The `@deepseek-ai/dsh-plugin-manager/diagnostic` entry supplies Desktop Host and
#### What the model sees
The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. A change result that is not plainly applied adds `nextStep`, a sentence derived from its application status, refusal code, package-manager failure kind or restart reason that says what the model does next or tells the user. Management operations do not inject messages into Agents.
The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. A change result that is not plainly applied adds `nextStep`, a sentence derived from its application status, refusal code, package-manager failure kind or restart reason that says what the model does next or tells the user. Management operations do not inject messages into Agents. A missing or unbounded argument fails as `ToolArgsError` with `INVALID_ARGS`. A failure before a change starts or while reading the profile throws `PluginManagerError`: `PLUGIN_MANAGER_PROFILE_READ_FAILED` when a profile or installation manifest or the profile patches cannot be read, and `PLUGIN_MANAGER_UNAVAILABLE` after the manager is disposed; another writer holding the profile lock past `lockWaitMs` fails with the atomic-write `FileLockError` `FILE_LOCK_TIMEOUT`; other operation failures stay in the change result.
#### Token effect
+1 -1
View File
@@ -152,7 +152,7 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,
#### 模型看到什么
[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。未直接应用的变更结果会增加 `nextStep`,这是一句根据应用状态、拒绝代码、包管理器失败类型或重启原因生成的说明,指出模型下一步做什么或告诉用户什么。管理操作不会向 Agent 注入消息。
[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。未直接应用的变更结果会增加 `nextStep`,这是一句根据应用状态、拒绝代码、包管理器失败类型或重启原因生成的说明,指出模型下一步做什么或告诉用户什么。管理操作不会向 Agent 注入消息。缺少参数或参数越界时以带 `INVALID_ARGS` 的 `ToolArgsError` 失败。变更开始前或读取 profile 时的失败抛出 `PluginManagerError`:profile 或安装清单、profile 补丁无法读取时为 `PLUGIN_MANAGER_PROFILE_READ_FAILED`,管理器已卸载时为 `PLUGIN_MANAGER_UNAVAILABLE`;其他写入方持有 profile 锁超过 `lockWaitMs` 时以 atomic-write 的 `FileLockError` `FILE_LOCK_TIMEOUT` 失败;其他操作失败仍记录在变更结果中。
#### Token 影响
@@ -88,6 +88,7 @@
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-hmr": "workspace:*",
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
"@deepseek-ai/dsh-sandbox": "workspace:*",
@@ -113,6 +114,7 @@
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-system-prompt": "workspace:*",
"@deepseek-ai/dsh-hmr": "workspace:*",
"@deepseek-ai/cordis-plugin-timer": "workspace:~",
+47
View File
@@ -0,0 +1,47 @@
/** Typed failures thrown by plugin management calls rather than reported in a change result. */
import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every {@link PluginManagerError} code:
* - `PLUGIN_MANAGER_PROFILE_READ_FAILED`: the profile manifest, patches, version exemptions, or
* installation manifest could not be read or parsed; `cause` is the original error. Repair the
* profile files before retrying.
* - `PLUGIN_MANAGER_UNAVAILABLE`: the manager was disposed before the change started.
*/
export const PLUGIN_MANAGER_ERROR_CODES = [
'PLUGIN_MANAGER_PROFILE_READ_FAILED',
'PLUGIN_MANAGER_UNAVAILABLE',
] as const
/** One {@link PluginManagerError} code. */
export type PluginManagerErrorCode = typeof PLUGIN_MANAGER_ERROR_CODES[number]
/** Typed plugin management failure; `code` is one of {@link PLUGIN_MANAGER_ERROR_CODES}. */
export class PluginManagerError extends HarnessError {
override readonly code: PluginManagerErrorCode
constructor(message: string, code: PluginManagerErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginManagerError'
this.code = code
}
}
/**
* Run one synchronous profile read, converting its failure.
* @param read - reads and parses profile files.
* @returns the read value.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` with the original error as `cause`.
*/
export function readProfileState<T>(read: () => T): T {
try {
return read()
} catch (error) {
// Profile readers fail with filesystem, JSON, YAML, or validation Error instances.
throw new PluginManagerError(
`plugin-manager: failed to read the profile: ${(error as Error).message}`,
'PLUGIN_MANAGER_PROFILE_READ_FAILED', { cause: error },
)
}
}
+15 -5
View File
@@ -35,6 +35,7 @@ import { dependencySpec, InvalidInstallSpecError, parseInstallSpec, pinnedGitOri
import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } from './registry.ts'
import { flatten, writePluginEnabled } from './patch.ts'
import { incompatiblePlugin, ManagementFailure } from './failure.ts'
import { PluginManagerError, readProfileState } from './error.ts'
import { approveBuilds, recordPendingBuilds } from './build-approval.ts'
import { checkGitConnection, checkGithubConnection, type GithubConnectionFailure } from './github-connection.ts'
import { chooseGitTransport, sshGitSpec } from './git-transport.ts'
@@ -48,6 +49,7 @@ import type {
} from './types.ts'
export type * from './types.ts'
export { classifyInstallFailure, type InstallFailureFacts } from './install-failure.ts'
export { PluginManagerError, type PluginManagerErrorCode } from './error.ts'
export { InvalidInstallSpecError, parseInstallSpec, pinnedGitOrigin, type ParsedInstallSpec } from './install-spec.ts'
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -471,10 +473,12 @@ export class PluginManager extends TypertRemoteService {
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote
async listPlugins(): Promise<PluginInfo[]> {
const rows = flatten(composeEntries([readProfilePatches('dsh', this.profile)]))
const rows = readProfileState(() => flatten(composeEntries([readProfilePatches('dsh', this.profile)])))
const snapshot = await readPluginInventory(this.ctx)
return snapshot.entries.map((entry) => {
const actual = [...this.ctx.loader.entries()].find(row => row.id === entry.entryId)
@@ -495,6 +499,8 @@ export class PluginManager extends TypertRemoteService {
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote
listBundles(): Promise<BundleInfo[]> {
@@ -506,12 +512,14 @@ export class PluginManager extends TypertRemoteService {
/** The bundle inventory before update eligibility, which is derived from each listed bundle. */
private readBundles(): Omit<BundleInfo, 'update'>[] {
const manifest = readProfileManifest('dsh', this.profile.dir)
const exemptions = readProfileVersionExemptions(this.profile.dir)
const { manifest, exemptions, installation } = readProfileState(() => ({
manifest: readProfileManifest('dsh', this.profile.dir),
exemptions: readProfileVersionExemptions(this.profile.dir),
installation: JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest,
}))
const selected = bundleSelection(manifest)
const recorded = manifest.dependencies ?? {}
const dependencies = Object.keys(recorded)
const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest
const catalog = new Map(OFFICIAL_ON_DEMAND_CATALOG.map(entry => [entry.packageName, entry]))
const names = [...new Set([...selected, ...dependencies, ...Object.keys(installation.dependencies ?? {}), ...catalog.keys()])]
const bundles: Omit<BundleInfo, 'update'>[] = []
@@ -1375,7 +1383,9 @@ export class PluginManager extends TypertRemoteService {
let settled: ChangeResult
try {
settled = await withFileLock(join(this.profile.dir, 'package.json'), async () => {
this.abort.signal.throwIfAborted()
if (this.abort.signal.aborted) {
throw new PluginManagerError('plugin-manager: the manager is disposed; retry after the Host reloads it', 'PLUGIN_MANAGER_UNAVAILABLE')
}
const before = this.diskState()
const result: ChangeResult = { ...request, changed: false,
...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } }
+6 -6
View File
@@ -6,7 +6,7 @@ import type {} from '@deepseek-ai/dsh-sandbox-policy'
import type {} from '@deepseek-ai/dsh-user-approval'
import { approveEscalation } from '@deepseek-ai/dsh-sandbox'
import type { ChangeResult, ManagementError, PluginEntryId, PluginInstallFailureKind, RestartReason } from './types.ts'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
/** What the model does next for each refusal the manager reports. */
@@ -116,7 +116,7 @@ export function apply(ctx: Context): void {
return JSON.stringify({ runtimeVersion: getDshRuntimeVersion(), ...manager.listVersionExemptions() })
case 'set_version_exemption':
if (args.target === undefined || args.runtimeVersion === undefined || args.enabled === undefined) {
throw new Error('target package-name@version, runtimeVersion, and enabled are required')
throw new ToolArgsError(['target package-name@version, runtimeVersion, and enabled are required'])
}
return JSON.stringify(withNextStep(
await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk)))
@@ -125,7 +125,7 @@ export function apply(ctx: Context): void {
const offset = args.offset ?? 0
const limit = args.limit ?? 25
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100')
throw new ToolArgsError(['offset must be a non-negative integer and limit must be an integer from 1 to 100'])
}
const rows = args.action === 'list_plugins' ? await manager.listPlugins() : await manager.listBundles()
const entries = rows.slice(offset, offset + limit).map(({ meta: _meta, ...row }) =>
@@ -140,20 +140,20 @@ export function apply(ctx: Context): void {
}
case 'set_plugin':
case 'set_bundle': {
if (args.target === undefined || args.enabled === undefined) throw new Error('target and enabled are required')
if (args.target === undefined || args.enabled === undefined) throw new ToolArgsError(['target and enabled are required'])
return JSON.stringify(withNextStep(await (args.action === 'set_plugin'
? manager.setPluginEnabled(args.target as PluginEntryId, args.enabled)
: manager.setBundleEnabled(args.target, args.enabled))))
}
case 'install_bundle':
if (args.target === undefined) throw new Error('target package spec is required')
if (args.target === undefined) throw new ToolArgsError(['target package spec is required'])
return JSON.stringify(withNextStep(await manager.installBundle(args.target, {
...args.enabled === undefined ? {} : { enabled: args.enabled },
...args.approvedBuilds === undefined ? {} : { approvedBuilds: args.approvedBuilds },
...args.registry === undefined ? {} : { registry: args.registry },
})))
case 'remove_bundle':
if (args.target === undefined) throw new Error('target bundle name is required')
if (args.target === undefined) throw new ToolArgsError(['target bundle name is required'])
return JSON.stringify(withNextStep(await manager.removeBundle(args.target)))
/* v8 ignore next -- tool JSON validation rejects actions outside the declared enum */
default: return assertNever(args.action)
@@ -2522,3 +2522,27 @@ it('refuses an update whose target does not match where the copy was installed f
expect(view).not.toHaveBeenCalled()
expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before)
})
it('reports profile read, lock, and disposal failures with error codes', async () => {
const { ctx, manager, dir } = await fixture('startup', false, undefined, { lockWaitMs: 0 })
const manifest = join(dir, 'package.json')
const saved = readFileSync(manifest, 'utf8')
writeFileSync(manifest, '{')
const unreadable = Promise.resolve().then(() => manager.listBundles())
await expect(unreadable).rejects.toMatchObject({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_PROFILE_READ_FAILED' })
await expect(unreadable).rejects.toHaveProperty('cause', expect.any(SyntaxError))
writeFileSync(manifest, saved)
writeFileSync(`${manifest}.lock`, `${process.pid}\n`)
await expect(manager.setBundleEnabled('extra', false)).rejects.toMatchObject({
name: 'FileLockError', code: 'FILE_LOCK_TIMEOUT',
})
rmSync(`${manifest}.lock`)
const entry = [...ctx.loader.entries()].find(candidate => candidate.options.name === 'cordis:manager')
await entry?.fiber?.dispose()
await expect(manager.setBundleEnabled('extra', false)).rejects.toMatchObject({
name: 'PluginManagerError', code: 'PLUGIN_MANAGER_UNAVAILABLE',
})
expect(readFileSync(manifest, 'utf8')).toBe(saved)
})
@@ -16,6 +16,8 @@ import { expect, it, onTestFinished, vi } from 'vitest'
import type PluginManager from '../src/index.ts'
import type { BundleInfo } from '../src/types.ts'
import * as tool from '../src/tools.ts'
import { PluginManagerError } from '../src/error.ts'
import { FileLockError } from '@deepseek-ai/dsh-atomic-write'
function resultText(result: ToolExecutionResult): string {
if (typeof result.value !== 'string') throw new Error('Expected a serialized manager result')
@@ -275,7 +277,19 @@ it.each([
{ action: 'set_version_exemption', target: '[email protected]', runtimeVersion: '1.0.0' },
])('rejects incomplete or unbounded tool inputs: %j', async (args) => {
const { call } = await fixture()
expect((await call(args)).isError).toBe(true)
const result = await call(args)
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it('reports profile read, lock, and disposal failures with their error codes', async () => {
const { manager, call } = await fixture()
manager.listBundles.mockRejectedValueOnce(new PluginManagerError('plugin-manager: failed to read the profile: bad JSON', 'PLUGIN_MANAGER_PROFILE_READ_FAILED'))
manager.setBundleEnabled.mockRejectedValueOnce(new FileLockError('/profile/package.json.lock'))
manager.removeBundle.mockRejectedValueOnce(new PluginManagerError('plugin-manager: the manager is disposed', 'PLUGIN_MANAGER_UNAVAILABLE'))
expect((await call({ action: 'list_bundles' })).error?.info).toEqual({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_PROFILE_READ_FAILED' })
expect((await call({ action: 'set_bundle', target: 'bundle', enabled: false })).error?.info).toEqual({ name: 'FileLockError', code: 'FILE_LOCK_TIMEOUT' })
expect((await call({ action: 'remove_bundle', target: 'bundle' })).error?.info).toEqual({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_UNAVAILABLE' })
})
it('presents reads and changes distinctly and disposes its registration', async () => {
@@ -38,6 +38,9 @@
{
"path": "../../llm/llm"
},
{
"path": "../../util/error"
},
{
"path": "../../subprocess/subprocess"
},
+2 -2
View File
@@ -18,8 +18,8 @@
en: fef9850d643e327f
zh: c6e8cab773cf93b9
/deepseek-ai-dsh-plugin-market/use-this-package/plugin-detail-documents:
en: b5d96ca29cf76f31
zh: e5099b4f694cf4c9
en: 8a49fc923d4ebd95
zh: 44b9f020e8471458
/deepseek-ai-dsh-plugin-market/understand-the-implementation:
en: cb56b9191fc680a1
zh: eee0a1dfee9ea5bb
+1 -1
View File
@@ -80,7 +80,7 @@ A source that exists but cannot be read fails with `plugin-market/detail-unavail
Failures use `plugin-market/invalid-query`, `plugin-market/invalid-index-url`, `plugin-market/unknown-index`, `plugin-market/fetch-failed`, and `plugin-market/invalid-index`; the last carries the JSON path of the offending value.
The `plugin_market` tool lists the configured indexes, pages the plugins of one index in index order or, with a `query`, by best match, or pages one plugin's versions. It requires no approval because it reads only the sources the user configured and changes nothing; each version it returns carries the `target` and `registry` to pass to `plugin_manager`'s `install_bundle`, which keeps its own approval. The tool cannot change index sources. Creator mode keeps its row beside `plugin_manager`, and the row registers the tool only while `pluginMarket` is mounted; other presets keep it disabled.
The `plugin_market` tool lists the configured indexes, pages the plugins of one index in index order or, with a `query`, by best match, or pages one plugin's versions. It requires no approval because it reads only the sources the user configured and changes nothing; each version it returns carries the `target` and `registry` to pass to `plugin_manager`'s `install_bundle`, which keeps its own approval. The tool cannot change index sources. A missing argument or an out-of-range page fails as `ToolArgsError` with `INVALID_ARGS`. Market failures reach the tool registry as `PluginMarketError`, which keeps the service's message and its `RemoteError` as `cause`: for example `plugin-market/unknown-index` becomes `PLUGIN_MARKET_INDEX_NOT_FOUND`, `plugin-market/fetch-failed` becomes `PLUGIN_MARKET_FETCH_FAILED`, and an unlisted plugin is `PLUGIN_MARKET_PLUGIN_NOT_FOUND`; any other failure is `PLUGIN_MARKET_FAILED`. Creator mode keeps its row beside `plugin_manager`, and the row registers the tool only while `pluginMarket` is mounted; other presets keep it disabled.
-----
+1 -1
View File
@@ -81,7 +81,7 @@ Remote 方法如下:
失败使用 `plugin-market/invalid-query`、`plugin-market/invalid-index-url`、`plugin-market/unknown-index`、`plugin-market/fetch-failed` 和 `plugin-market/invalid-index`;最后一种携带违规值的 JSON 路径。
`plugin_market` 工具列出已配置的索引,按索引顺序分页列出某个索引的插件,或在给出 `query` 时按最佳匹配分页列出,或分页列出某个插件的版本。它不需要批准,因为它只读取用户配置的源且不做任何改动;它返回的每个版本都携带要传给 `plugin_manager` 的 `install_bundle` 的 `target` 和 `registry`,`install_bundle` 仍保留自己的批准要求。该工具不能修改索引源。Creator 模式在 `plugin_manager` 旁边保留它的行,该行只在 `pluginMarket` 已挂载时注册工具;其他预设保持禁用。
`plugin_market` 工具列出已配置的索引,按索引顺序分页列出某个索引的插件,或在给出 `query` 时按最佳匹配分页列出,或分页列出某个插件的版本。它不需要批准,因为它只读取用户配置的源且不做任何改动;它返回的每个版本都携带要传给 `plugin_manager` 的 `install_bundle` 的 `target` 和 `registry`,`install_bundle` 仍保留自己的批准要求。该工具不能修改索引源。缺少参数或分页越界时以带 `INVALID_ARGS` 的 `ToolArgsError` 失败。市场失败以 `PluginMarketError` 交给工具注册表,保留服务的 message,并把其 `RemoteError` 保留为 `cause`:例如 `plugin-market/unknown-index` 变为 `PLUGIN_MARKET_INDEX_NOT_FOUND`,`plugin-market/fetch-failed` 变为 `PLUGIN_MARKET_FETCH_FAILED`,未列出的插件为 `PLUGIN_MARKET_PLUGIN_NOT_FOUND`;其他失败为 `PLUGIN_MARKET_FAILED`。Creator 模式在 `plugin_manager` 旁边保留它的行,该行只在 `pluginMarket` 已挂载时注册工具;其他预设保持禁用。
-----
+2
View File
@@ -76,6 +76,7 @@
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*"
},
@@ -92,6 +93,7 @@
"@deepseek-ai/dsh-client-connection": "workspace:*",
"@deepseek-ai/dsh-config-editor": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
+68
View File
@@ -0,0 +1,68 @@
/** Typed `plugin_market` tool failures converted from the market service's Remote failures. */
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { RemoteErrorCode } from '@deepseek-ai/dsh-typert-protocol'
/**
* Every {@link PluginMarketError} code:
* - `PLUGIN_MARKET_INDEX_NOT_FOUND`: the URL is not a configured index source; call `list_indexes`.
* - `PLUGIN_MARKET_INVALID_INDEX_URL`: a configured index URL is invalid; only the user can fix the source.
* - `PLUGIN_MARKET_FETCH_FAILED`: the index could not be fetched (network, timeout, redirect, status, or size).
* - `PLUGIN_MARKET_INVALID_INDEX`: the fetched index document is invalid.
* - `PLUGIN_MARKET_PLUGIN_NOT_FOUND`: the index lists no plugin with the requested name.
* - `PLUGIN_MARKET_FAILED`: any other market failure; `cause` is the original error.
*/
export const PLUGIN_MARKET_ERROR_CODES = [
'PLUGIN_MARKET_INDEX_NOT_FOUND',
'PLUGIN_MARKET_INVALID_INDEX_URL',
'PLUGIN_MARKET_FETCH_FAILED',
'PLUGIN_MARKET_INVALID_INDEX',
'PLUGIN_MARKET_PLUGIN_NOT_FOUND',
'PLUGIN_MARKET_FAILED',
] as const
/** One {@link PluginMarketError} code. */
export type PluginMarketErrorCode = typeof PLUGIN_MARKET_ERROR_CODES[number]
/** Typed `plugin_market` failure; `code` is one of {@link PLUGIN_MARKET_ERROR_CODES}. */
export class PluginMarketError extends HarnessError {
override readonly code: PluginMarketErrorCode
constructor(message: string, code: PluginMarketErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginMarketError'
this.code = code
}
}
/**
* Remote failure codes `search` and `entry` reject with for a query the tool already validated;
* `invalid-query` cannot occur because the tool checks the same page bounds first.
*/
type ToolRemoteCode = Extract<RemoteErrorCode,
'plugin-market/unknown-index' | 'plugin-market/invalid-index-url' | 'plugin-market/fetch-failed' | 'plugin-market/invalid-index'>
/** Tool code for each Remote failure code the tool's market reads can reject with. */
const REMOTE_CODES: Readonly<Record<ToolRemoteCode, PluginMarketErrorCode>> = {
'plugin-market/unknown-index': 'PLUGIN_MARKET_INDEX_NOT_FOUND',
'plugin-market/invalid-index-url': 'PLUGIN_MARKET_INVALID_INDEX_URL',
'plugin-market/fetch-failed': 'PLUGIN_MARKET_FETCH_FAILED',
'plugin-market/invalid-index': 'PLUGIN_MARKET_INVALID_INDEX',
}
/**
* Convert a market failure for the tool registry. A market `RemoteError` with
* one of the codes `search` and `entry` reject with keeps its message and
* becomes the matching code with the Remote failure as `cause`; any other
* `HarnessError` keeps its identity; anything else is `PLUGIN_MARKET_FAILED`.
* @param error - the rejection of a market service call.
* @returns the failure to throw from the tool body.
*/
export function pluginMarketToolError(error: unknown): HarnessError {
if (error instanceof HarnessError) {
if (!Object.hasOwn(REMOTE_CODES, error.code)) return error
return new PluginMarketError(error.message, REMOTE_CODES[error.code as ToolRemoteCode], { cause: error })
}
const message = error instanceof Error ? error.message : String(error)
return new PluginMarketError(message, 'PLUGIN_MARKET_FAILED', { cause: error })
}
+1
View File
@@ -31,6 +31,7 @@ import type {
} from './types.ts'
export type * from './types.ts'
export { PluginMarketError, type PluginMarketErrorCode } from './error.ts'
declare module '@deepseek-ai/cordis' {
interface Context {
+24 -8
View File
@@ -2,8 +2,9 @@
import { assertNever } from '@deepseek-ai/dsh-util-values'
import type { Context } from '@deepseek-ai/cordis'
import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
import type { MarketListingVersion } from './index.ts'
import { PluginMarketError, pluginMarketToolError } from './error.ts'
/** Required services for the listing tool; `pluginMarket` is awaited inside `apply`. */
export const inject = ['tools']
@@ -17,6 +18,19 @@ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
})
}
/**
* Await one market read for a tool call: cancellation rethrows the signal's reason, and any other
* rejection becomes a coded {@link PluginMarketError} or keeps its `HarnessError` identity.
*/
async function marketRead<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
try {
return await untilAborted(promise, signal)
} catch (error) {
signal.throwIfAborted()
throw pluginMarketToolError(error)
}
}
/** Longest market-supplied title or description returned to the model, in UTF-16 code units. */
const MAX_TEXT = 300
@@ -46,7 +60,7 @@ interface Page {
function pageOf(offset: number | undefined, limit: number | undefined): Page {
const page = { offset: offset ?? 0, limit: limit ?? 25 }
if (!Number.isInteger(page.offset) || page.offset < 0 || !Number.isInteger(page.limit) || page.limit < 1 || page.limit > 100) {
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100')
throw new ToolArgsError(['offset must be a non-negative integer and limit must be an integer from 1 to 100'])
}
return page
}
@@ -94,11 +108,11 @@ function registerTool(ctx: Context): void {
})),
})
case 'list_plugins': {
if (args.target === undefined) throw new Error('target index URL is required')
if (args.target === undefined) throw new ToolArgsError(['target index URL is required'])
const page = pageOf(args.offset, args.limit)
const text = args.query ?? ''
// The read is shared with other callers, so cancelling this call stops waiting without aborting the fetch.
const result = await untilAborted(market.search(args.target, {
const result = await marketRead(market.search(args.target, {
text, sort: { kind: text.trim() === '' ? 'index' : 'relevance' }, offset: page.offset, limit: page.limit,
}), exec.signal)
const entries = result.entries.map((entry) => {
@@ -121,11 +135,13 @@ function registerTool(ctx: Context): void {
return JSON.stringify({ index: english(result.title), entries, total: result.total, nextOffset: result.nextOffset })
}
case 'list_versions': {
if (args.target === undefined) throw new Error('target index URL is required')
if (args.name === undefined) throw new Error('name is required')
if (args.target === undefined) throw new ToolArgsError(['target index URL is required'])
if (args.name === undefined) throw new ToolArgsError(['name is required'])
const page = pageOf(args.offset, args.limit)
const entry = await untilAborted(market.entry(args.target, args.name), exec.signal)
if (entry === undefined) throw new Error(`${args.name} is not listed in ${args.target}`)
const entry = await marketRead(market.entry(args.target, args.name), exec.signal)
if (entry === undefined) {
throw new PluginMarketError(`${args.name} is not listed in ${args.target}`, 'PLUGIN_MARKET_PLUGIN_NOT_FOUND')
}
const { slice, nextOffset } = paged(entry.versions, page)
return JSON.stringify({
name: entry.name, defaultVersion: entry.defaultVersion ?? null, versions: slice.map(versionResult),
@@ -3,7 +3,7 @@ import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import { Context, Service } from '@deepseek-ai/cordis'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import ToolRuntime, { ToolArgsError } from '@deepseek-ai/dsh-tools'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
@@ -23,7 +23,7 @@ function serve(document: unknown) {
return fetch
}
async function fixture() {
async function fixture(indexes: readonly string[] = [URL_A]) {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
class Manager extends Service {
@@ -32,7 +32,7 @@ async function fixture() {
listVersionExemptions() { return { exemptions: {}, warnings: [] } }
}
await ctx.plugin(Manager)
await ctx.plugin(PluginMarket, { indexes: [URL_A], detailCacheDir: UNUSED_CACHE })
await ctx.plugin(PluginMarket, { indexes: [...indexes], detailCacheDir: UNUSED_CACHE })
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
@@ -128,15 +128,57 @@ it.each([
{ action: 'list_plugins', target: URL_A, limit: 0 },
{ action: 'list_plugins', target: URL_A, limit: 101 },
{ action: 'list_plugins', target: URL_A, offset: 1.5 },
{ action: 'list_plugins', target: 'https://unknown.example/index.json' },
{ action: 'list_versions', name: 'dsh-a' },
{ action: 'list_versions', target: URL_A },
{ action: 'list_versions', target: URL_A, name: 'dsh-a', limit: 101 },
{ action: 'list_versions', target: URL_A, name: 'dsh-missing' },
])('rejects an incomplete, unbounded, or unconfigured request: %j', async (args) => {
])('rejects an incomplete or unbounded request as INVALID_ARGS: %j', async (args) => {
serve(document)
const { call } = await fixture()
expect((await call(args)).isError).toBe(true)
const result = await call(args)
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it.each([
[{ action: 'list_plugins', target: 'https://unknown.example/index.json' }, 'PLUGIN_MARKET_INDEX_NOT_FOUND', 'Not a configured index source: https://unknown.example/index.json'],
[{ action: 'list_versions', target: URL_A, name: 'dsh-missing' }, 'PLUGIN_MARKET_PLUGIN_NOT_FOUND', `dsh-missing is not listed in ${URL_A}`],
] as const)('rejects an unconfigured index or unlisted bundle with a PluginMarketError: %j', async (args, code, message) => {
serve(document)
const { call } = await fixture()
expect((await call(args)).error).toEqual({ message, info: { name: 'PluginMarketError', code } })
})
it.each([
['an unreachable index', () => Promise.reject(new TypeError('fetch failed')), 'PLUGIN_MARKET_FETCH_FAILED'],
['a non-2xx index', () => Promise.resolve(new Response('missing', { status: 404 })), 'PLUGIN_MARKET_FETCH_FAILED'],
['an invalid index document', () => Promise.resolve(new Response(JSON.stringify({ format: 2 }))), 'PLUGIN_MARKET_INVALID_INDEX'],
] as const)('converts the market Remote failure for %s', async (_label, respond, code) => {
vi.stubGlobal('fetch', vi.fn(respond))
const { call } = await fixture()
const result = await call({ action: 'list_plugins', target: URL_A })
expect(result.error?.info).toEqual({ name: 'PluginMarketError', code })
})
it('reports a configured index source with an invalid URL as PLUGIN_MARKET_INVALID_INDEX_URL', async () => {
serve(document)
const invalid = 'https://user:[email protected]/index.json'
const { call } = await fixture([URL_A, invalid])
const result = await call({ action: 'list_plugins', target: invalid })
expect(result.error?.info).toEqual({ name: 'PluginMarketError', code: 'PLUGIN_MARKET_INVALID_INDEX_URL' })
})
it('keeps a HarnessError from the market and classifies any other failure', async () => {
serve(document)
const { call, ctx } = await fixture()
const coded = new ToolArgsError(['limit must be small'])
const search = vi.spyOn(ctx.pluginMarket, 'search').mockRejectedValueOnce(coded)
expect((await call({ action: 'list_plugins', target: URL_A })).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
search.mockRejectedValueOnce(new Error('index cache broke'))
expect((await call({ action: 'list_plugins', target: URL_A })).error).toEqual({
message: 'index cache broke', info: { name: 'PluginMarketError', code: 'PLUGIN_MARKET_FAILED' },
})
search.mockRejectedValueOnce('bare failure')
expect((await call({ action: 'list_plugins', target: URL_A })).error?.message).toBe('bare failure')
})
it('presents a read and disposes its registration', async () => {
@@ -19,6 +19,7 @@
{ "path": "../../util/values" },
{ "path": "../../settings/settings" },
{ "path": "../../typert/protocol" },
{ "path": "../../util/error" },
{ "path": "../../core/tools" },
{ "path": "../../util/brand" },
{ "path": "../../subprocess/subprocess" },
@@ -21,8 +21,8 @@
en: 78708b3779d999a9
zh: ad6173f9f01630de
/deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode:
en: 7d0df521ba40881d
zh: 65d4738c69cbe0d4
en: 129e1a149bd42218
zh: 97aec4e64d26dd7f
/deepseek-ai-dsh-tool-executor-ptc/further-exploration:
en: ee69078c38c655a9
zh: fb0873407f23c8c5
+1 -1
View File
@@ -68,7 +68,7 @@ New sub-calls use `<parent>:ptc:<n>` ids. Consumers treat these ids as opaque an
TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution.
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. Cancellation can discard retained runtime state and does not undo completed tool effects.
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects.
`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls.
+1 -1
View File
@@ -68,7 +68,7 @@ PTC 执行器公开保留的 `run_code` 传输,以及按所加载运行时语
TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消所有 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。
+22 -8
View File
@@ -21,19 +21,33 @@ export class ToolCallLimitExceededError extends Error {
}
}
/**
* Every {@link CodeRunFailedError} code:
* - `CODE_RUN_FAILED`: the program run failed, or the runtime rejected it without its own error code.
* - `CODE_RUN_UNAVAILABLE`: the executor was disposed before the run started.
*/
export const CODE_RUN_ERROR_CODES = ['CODE_RUN_FAILED', 'CODE_RUN_UNAVAILABLE'] as const
/** One {@link CodeRunFailedError} code. */
export type CodeRunErrorCode = typeof CODE_RUN_ERROR_CODES[number]
/**
* Thrown by `run_code` when the program run itself failed — a program
* exception, a budget expiry, a runtime-local abort, or substrate death. Caller
* cancellation uses the shared `AbortError` / `ABORTED` tool outcome. Extends
* {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
* pipeline converts it into a structured `isError` result with the failure
* kind. Captured text and images accompany the original diagnostic;
* outer result replacements remain authoritative.
* exception, a budget expiry, a runtime-local abort, or substrate death — or
* could not start. Caller cancellation uses the shared `AbortError` /
* `ABORTED` tool outcome. Extends {@link HarnessError} with a code from
* {@link CODE_RUN_ERROR_CODES}; the registry's execution pipeline converts it
* into a structured `isError` result with the failure kind. Captured text and
* images accompany the original diagnostic; outer result replacements remain
* authoritative.
*/
export class CodeRunFailedError extends HarnessError {
constructor(message: string) {
super(message, 'CODE_RUN_FAILED')
override readonly code: CodeRunErrorCode
constructor(message: string, code: CodeRunErrorCode = 'CODE_RUN_FAILED', options?: ErrorOptions) {
super(message, code, options)
this.name = 'CodeRunFailedError'
this.code = code
}
}
@@ -94,6 +94,7 @@ export class PtcExecutor implements ToolExecutor {
export { Config } from './config.ts'
export { CodeRunFailedError, CodeResetFailedError } from './errors.ts'
export type { CodeRunErrorCode } from './errors.ts'
export type { PtcDispatchLog } from './runtime-types.ts'
export type { PtcDispatchStartEventData, PtcDispatchEventData } from './types.ts'
export { jsonSchemaToTs, renderToolsSdk, type ToolSdkSchema } from './ts-types.ts'
@@ -67,7 +67,7 @@ export class PtcCalls {
await Promise.all(pending.map(call => call.done))
}
signal.throwIfAborted()
if (this.disposed) throw new Error('PTC tool executor disposed')
if (this.disposed) throw new CodeRunFailedError('PTC tool executor disposed', 'CODE_RUN_UNAVAILABLE')
const controller = new AbortController()
const done = Promise.withResolvers<undefined>()
const currentSignal = AbortSignal.any([signal, controller.signal])
+22 -9
View File
@@ -22,7 +22,10 @@ import type {} from '@deepseek-ai/dsh-user-approval'
import type {} from '@deepseek-ai/dsh-working-directory'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
import { defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
import {
defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED, ToolArgsError,
ToolContextUnavailableError,
} from '@deepseek-ai/dsh-tools'
import type { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
@@ -84,7 +87,7 @@ const RUN_CODE_FLAVORS = {
export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
const runtime = ctx.get('ptcRuntime')
if (runtime === undefined) {
throw new Error('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
throw new ToolContextUnavailableError('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
}
return requireRuntimeLanguage(runtime)
}
@@ -93,7 +96,7 @@ export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
function requireRuntimeLanguage(runtime: PtcRuntime): SupportedPtcRuntime {
if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language)) {
const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ')
throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
throw new ToolContextUnavailableError(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
}
return runtime as SupportedPtcRuntime
}
@@ -254,6 +257,11 @@ function renderValue(value: JsonValue): string {
return typeof value === 'string' ? value : renderJsonValue(value)
}
/** Whether a rejection is the caller's cancellation rather than a failure of its own. */
function isCancellation(error: unknown, signal: AbortSignal): boolean {
return signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))
}
/** Canonical value returned by the outer PTC mode transport. */
type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: PtcRunSandbox }
@@ -288,14 +296,14 @@ function renderRunOutput(
async function resolveWorkingDirectory(ctx: Context, exec: ToolRunContext): Promise<string | undefined> {
if (exec.agent === undefined) return undefined
const directories = ctx.get('workingDirectory')
if (directories === undefined) throw new Error('dsh-tools: run_code with an Agent requires workingDirectory')
if (directories === undefined) throw new ToolContextUnavailableError('dsh-tools: run_code with an Agent requires workingDirectory')
return directories.ensure(exec.agent, exec.signal)
}
/** Resolve standing authority for a runtime that enforces file policy. */
function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecutionPolicy {
const policy = ctx.get('sandboxPolicy')
if (policy === undefined) throw new Error('dsh-tools: confined PTC runtime requires sandboxPolicy')
if (policy === undefined) throw new ToolContextUnavailableError('dsh-tools: confined PTC runtime requires sandboxPolicy')
return policy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
}
@@ -391,21 +399,21 @@ export function createRunCodeTransport(
},
async execute(args, exec): Promise<RunCodeOutput> {
if (args.description.trim().length === 0) {
throw new Error('invalid description: expected a non-empty string')
throw new ToolArgsError(['invalid description: expected a non-empty string'])
}
const runtime = getRuntime()
const run = async (callSignal: AbortSignal): Promise<RunCodeOutput> => {
validateEscalationArgs(args.sandbox_permissions, args.justification)
if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
throw new Error('timeoutMs is not available for this PTC runtime')
throw new ToolArgsError(['timeoutMs is not available for this PTC runtime'])
}
if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
throw new Error('invalid timeoutMs: expected a positive finite number')
throw new ToolArgsError(['invalid timeoutMs: expected a positive finite number'])
}
const standingPolicy = runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec)
let policy = standingPolicy
if (args.sandbox_permissions !== undefined && args.justification !== undefined) {
if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime')
if (standingPolicy === undefined) throw new ToolArgsError(['sandbox_permissions is not available for this PTC runtime'])
const approvedMode = await approveEscalation({
requestedMode: args.sandbox_permissions,
justification: args.justification,
@@ -761,6 +769,11 @@ export function createRunCodeTransport(
maxSubCalls = spec.timeoutMs === null ? Infinity
: Math.floor(spec.timeoutMs / 60_000 * maxSubCallsPerMinute)
result = await runtime.run(spec)
} catch (error) {
// Runtimes reject only contract misuse; a rejection without its own code becomes CODE_RUN_FAILED.
// The cancellation itself passes through for the registry to classify as ABORTED.
if (error instanceof HarnessError || isCancellation(error, callSignal)) throw error
throw new CodeRunFailedError(`code run failed: ${toolErrorMessage(error)}`, 'CODE_RUN_FAILED', { cause: error })
} finally {
// Abort sub-dispatches and drain every in-flight dispatch before
// closing the turn (queued-unstarted ones are abandoned unlogged).
@@ -87,6 +87,9 @@ it('unloads the executor only after calls stop and refuses late admission', asyn
await rejected
await disposed
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toThrow('PTC tool executor disposed')
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toMatchObject({
name: 'CodeRunFailedError', code: 'CODE_RUN_UNAVAILABLE',
})
} finally { cleanup.resolve(undefined); await first; await disposed }
})
@@ -14,7 +14,7 @@ import type { ToolSchema } from '@deepseek-ai/dsh-llm'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { Scope } from '@deepseek-ai/dsh-scope'
import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime'
import type { PtcRunFailure, PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
import ToolRuntime, { RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, defineTool } from '@deepseek-ai/dsh-tools'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
@@ -1945,6 +1945,7 @@ describe('the run_code dispatch bridge', () => {
const result = await runCode(ctx, 'program')
expect(result.isError).toBe(true)
expect((result.content[0] as { text: string }).text).toContain('requires a PTC runtime')
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
})
it('refuses an agent-owned program before dispatch when its directory owner is missing', async () => {
@@ -1968,6 +1969,7 @@ describe('the run_code dispatch bridge', () => {
expect(result.content).toEqual([{
type: 'text', text: 'Error: dsh-tools: run_code with an Agent requires workingDirectory',
}])
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
expect(runtime.lastRequest).toBeUndefined()
expect(calls).toEqual([])
expect(events).toEqual([])
@@ -1989,11 +1991,44 @@ describe('the run_code dispatch bridge', () => {
})
})
it('classifies runtime rejections, keeping a runtime error code', async () => {
const { ctx, runtime } = await setup({ mode: 'ptc' })
const misuse = new TypeError('runtime contract violated')
runtime.behavior = () => Promise.reject(misuse)
const failed = await runCode(ctx, 'return 1')
expect(failed.error).toEqual({
message: 'code run failed: runtime contract violated',
info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' },
})
runtime.behavior = () => Promise.reject(new PtcRuntimeError('ptc-runtime-node: run after disposal', 'PTC_RUNTIME_UNAVAILABLE'))
expect((await runCode(ctx, 'return 1')).error?.info).toEqual({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
})
it('keeps a distinct runtime rejection after cancellation and passes the cancellation through', async () => {
const { ctx, runtime } = await setup({ mode: 'ptc' })
const cancelled = async (rejection: (reason: unknown) => unknown) => {
const controller = new AbortController()
runtime.behavior = () => {
controller.abort(new Error('caller cancelled'))
// The cancellation case rejects with the signal's own reason.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
return Promise.reject(rejection(controller.signal.reason))
}
return (await runCode(ctx, 'return 1', { signal: controller.signal })).error
}
expect((await cancelled(() => new PtcRuntimeError('persistent PTC environment cleanup is incomplete', 'PTC_RUNTIME_UNAVAILABLE')))?.info)
.toEqual({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
expect((await cancelled(() => new TypeError('cleanup observation failed')))?.info)
.toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
expect((await cancelled(reason => reason))?.info).toEqual({ name: 'AbortError', code: 'ABORTED' })
})
it('rejects a whitespace-only description with a structured isError', async () => {
const { ctx } = await setup({ mode: 'ptc' })
const result = await runCode(ctx, 'return 1', { description: ' ' })
expect(result.isError).toBe(true)
expect((result.content[0] as { text: string }).text).toContain('invalid description')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it.each([
@@ -2720,6 +2755,7 @@ describe('PTC standing file policy and sandbox outcomes', () => {
const result = await runCode(ctx, 'return 1')
expect(result.isError).toBe(true)
expect(result.content).toEqual([{ type: 'text', text: 'Error: dsh-tools: confined PTC runtime requires sandboxPolicy' }])
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
expect((ctx.ptcRuntime as ConfinedFakeRuntime).lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -2839,6 +2875,7 @@ describe('per-program execution controls', () => {
arguments: { code: 'pass', description: 'Try unsupported timeout', timeoutMs: 5 },
})
expect(rejected.isError).toBe(true)
expect(rejected.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(python.runtime.lastRequest).toBeUndefined()
} finally { await python.ctx.fiber.dispose() }
})
@@ -2846,7 +2883,9 @@ describe('per-program execution controls', () => {
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, '1000', null])('rejects invalid timeout %s before runtime execution', async (timeoutMs) => {
const { ctx, runtime, execute } = await controlledSetup()
try {
expect((await execute({ timeoutMs })).isError).toBe(true)
const result = await execute({ timeoutMs })
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(runtime.lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -2860,6 +2899,7 @@ describe('per-program execution controls', () => {
})
expect(result.isError).toBe(true)
expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this PTC runtime')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(runtime.lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -9,17 +9,17 @@
en: b8c7e5c40e3c21a4
zh: 2360132d865b9d08
/deepseek-ai-dsh-experimental-forge-session/summary:
en: 6c46b2a70c2f4760
zh: 9425687e258412b4
en: 5aba678acbd32a39
zh: 2d46c826c60982e1
/deepseek-ai-dsh-experimental-forge-session/table-of-contents:
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-forge-session/use-this-package:
en: d9de38d0cc22c1bd
zh: 6116653176a9fea7
en: 28bc68989945466f
zh: 5e151236ead2764b
/deepseek-ai-dsh-experimental-forge-session/understand-the-implementation:
en: 46d6625f613e9c69
zh: 688ad6eb25570bc3
en: 1afa3f7214e5b7fd
zh: 396773f1cd4b0cee
/deepseek-ai-dsh-experimental-forge-session/further-exploration:
en: afd5ea387dc53920
zh: 1f2d48bdd1abeef7
@@ -30,8 +30,8 @@
en: 1bdaeb7d102c23d8
zh: 37a3f0bd58f68363
/deepseek-ai-dsh-experimental-forge-session/known-limitations-and-deferred-work:
en: 87c7672b6dc886a0
zh: 864ef4403a3e7fea
en: af600913828699f4
zh: d931fafc1324a80e
/deepseek-ai-dsh-experimental-forge-session/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
List the pull requests a Session is working on without a separate registry. A projection derives bindings from the Session's own `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` shell results and from binding records. After each push, and when a caller such as the forge panel reports the branch a Session works on, the service looks up open change requests for that branch and records the unbound ones. Watching a Session polls its bound change requests through `ctx.forge`. The Session summary carries the bindings to clients.
List the pull requests a Session is working on without a separate registry. A projection derives bindings from the Session's own `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` shell results, including shell calls inside PTC programs, and from binding records. After each push, and when a caller such as the forge panel reports the branch a Session works on, the service looks up open change requests for that branch and records the unbound ones. Watching a Session polls its bound change requests through `ctx.forge`. The Session summary carries the bindings to clients.
## Table of Contents
@@ -36,9 +36,9 @@ Mount the service with the forge registry, a provider, and the Session projectio
`ctx.forgeSession.changeRequests(session)` returns the visible bindings in first-recorded order. Each entry carries the URL, its `origin` (`created`, `referenced`, `discovered`, or `tracked`), the provider reference or `null` when no provider serves the URL, and the latest polling result or `null`. `watch(session, listener)` is an effect on the calling fiber: while a Session has a watcher, every visible binding that a provider serves is polled, and listeners receive the complete list after each later binding change, provider registration change, or polling result. Provider changes resynchronize existing watches, including URLs that were previously unserved. `track(session, url)` binds a URL under the provider's canonical form, or restores a dismissed binding, and throws when no provider recognizes the URL. `dismiss(session, url)` hides a visible binding; other URLs leave the log unchanged. `discoverBranch(session, remote, branch)` runs the lookup that follows a push for a branch on the remote at `remote` and resolves once it has recorded its bindings or failed; a remote that no provider serves changes nothing.
A `bash` or `pwsh` call binds evidence only from its first result, and only when the tool execution itself succeeded; the command's exit status does not matter. A command containing `gh pr create` or `gh pr new` binds every `/pull/<number>` URL in its text output. A command containing `gh pr view`, `gh pr edit`, or `gh pr checkout` binds, as `referenced`, a `/pull/<number>` URL selected by the command, or a numeric selector with an explicit repository and host, plus the URL its output prints for its own change request: gh's `url:` field or a URL alone on a line before the `--` line that starts a description, and JSON `url` members. Links in a description or in other fields do not bind, and a command that also contains `gh pr create` binds its URLs as `created`. A command containing `git push`, optionally with leading `-C`, `-c`, or long Git options, records each branch listed under a `To <remote>` line as created, updated, forced, or already up to date; rejected and deleted refs, new tags, and explicit refs outside `refs/heads/` are skipped. For each pushed branch whose remote a provider serves, the service runs `ctx.forge.findByHead` within `discoveryTimeoutMs` and appends a `discover` record for every returned change request that is not bound. Dismissed bindings remain bound and are skipped; only `track` restores them. Every push repeats the lookup; failures are logged as warnings. Closing a Session cancels its unfinished branch lookups without adding bindings. Reopening it does not repeat those lookups; another push, `discoverBranch`, or `track` can bind the change request. URLs that differ only in scheme, letter case, query, fragment, or trailing slashes name the same binding.
A `bash` or `pwsh` call binds evidence only from its first result, and only when the tool execution itself succeeded; the command's exit status does not matter. A `bash` or `pwsh` call inside a PTC program binds the same evidence from its `tool/ptc-dispatch` event, which logs the call's arguments with its settled outcome. A command containing `gh pr create` or `gh pr new` binds every `/pull/<number>` URL in its text output. A command containing `gh pr view`, `gh pr edit`, or `gh pr checkout` binds, as `referenced`, a `/pull/<number>` URL selected by the command, or a numeric selector with an explicit repository and host, plus the URL its output prints for its own change request: gh's `url:` field or a URL alone on a line before the `--` line that starts a description, and JSON `url` members. Links in a description or in other fields do not bind, and a command that also contains `gh pr create` binds its URLs as `created`. A command containing `git push`, optionally with leading `-C`, `-c`, or long Git options, records each branch listed under a `To <remote>` line as created, updated, forced, or already up to date; rejected and deleted refs, new tags, and explicit refs outside `refs/heads/` are skipped. For each pushed branch whose remote a provider serves, the service runs `ctx.forge.findByHead` within `discoveryTimeoutMs` and appends a `discover` record for every returned change request that is not bound. Dismissed bindings remain bound and are skipped; only `track` restores them. Every push repeats the lookup; failures are logged as warnings. Closing a Session cancels its unfinished branch lookups without adding bindings. Reopening it does not repeat those lookups; another push, `discoverBranch`, or `track` can bind the change request. URLs that differ only in scheme, letter case, query, fragment, or trailing slashes name the same binding.
Numeric `gh pr view`, `edit`, and `checkout` selectors accept `--repo OWNER/REPO`, `--repo=OWNER/REPO`, and `-R OWNER/REPO` in either argument order. A repository containing its host, or a literal `GH_HOST` assignment, supplies a URL directly. For a single command, optionally piped through `head`, `tail`, or `cat`, a completed foreground Bash call without a host runs a read-only `gh pr view <number> --repo <repository> --json url` through the same shell service, cwd, literal environment assignments, managed environment, and standing sandbox policy. The CLI resolves its configured host. A successful lookup appends a `reference` binding record; failures leave bindings unchanged and log a warning. This live observer requires `tools`, `shell`, and `shellEnv`; projection-only compositions still recover recorded URLs. Queries share `discoveryTimeoutMs`, stop on caller cancellation, and are aborted and awaited on service disposal.
Numeric `gh pr view`, `edit`, and `checkout` selectors accept `--repo OWNER/REPO`, `--repo=OWNER/REPO`, and `-R OWNER/REPO` in either argument order. A repository containing its host, or a literal `GH_HOST` assignment, supplies a URL directly. For a single command, optionally piped through `head`, `tail`, or `cat`, a completed foreground Bash call without a host runs a read-only `gh pr view <number> --repo <repository> --json url` through the same shell service, cwd, literal environment assignments, managed environment, and standing sandbox policy. The CLI resolves its configured host. A successful lookup appends a `reference` binding record; failures leave bindings unchanged and log a warning. A Bash call inside a PTC program runs its lookup after the enclosing root call settles, so the lookup follows that root call's cancellation. This live observer requires `tools`, `shell`, and `shellEnv`; projection-only compositions still recover recorded URLs. Queries share `discoveryTimeoutMs`, stop on caller cancellation, and are aborted and awaited on service disposal.
Binding actions are `plugin:forge-session/binding` records listed in the [experimental persistence catalog](../../../docs/experimental-persistence-catalog.md); fork and resume carry them with the shell events, so a fork starts with its parent's bindings. `discoveryTimeoutMs` is listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-session).
@@ -50,13 +50,14 @@ Binding actions are `plugin:forge-session/binding` records listed in the [experi
<details>
<summary>Implementation internals — click to expand</summary>
The `forgeChangeRequests` projection keeps shell calls awaiting their first result, every binding with its dismissal state, and each pushed branch with the sequence number of the latest result that reported it. Pending calls are dropped at `turn/end`. Its client view, which the Session summary carries, is every binding with its URL, origin, and dismissal state in first-recorded order, and it keeps its reference while only pending calls or pushes change. The service reacts to a `tool/result` event by discovering exactly the pushes whose sequence number equals the event's, and refreshes watchers when the bindings array changes. Disposing the service aborts lookups and drops their results.
The `forgeChangeRequests` projection keeps shell calls awaiting their first result, every binding with its dismissal state, and each pushed branch with the sequence number of the latest result that reported it. Pending calls are dropped at `turn/end`. Its client view, which the Session summary carries, is every binding with its URL, origin, and dismissal state in first-recorded order, and it keeps its reference while only pending calls or pushes change. The service reacts to a `tool/result` or `tool/ptc-dispatch` event by discovering exactly the pushes whose sequence number equals the event's, and refreshes watchers when the bindings array changes. Disposing the service aborts lookups and drops their results.
| Source | Responsibility |
|---|---|
| [`src/index.ts`](src/index.ts) | Discovery, track and dismiss records, and Session watches |
| [`src/projection.ts`](src/projection.ts) | Fold of shell calls, results, and binding records |
| [`src/projection.ts`](src/projection.ts) | Fold of shell calls, results, program dispatches, and binding records |
| [`src/commands.ts`](src/commands.ts) | Command classification and output parsing |
| [`src/reference-lookup.ts`](src/reference-lookup.ts) | Live lookup of numeric selectors without a host |
| [`src/types.ts`](src/types.ts) | Binding record, projection state, and entry types |
</details>
@@ -91,6 +92,7 @@ None. Binding records are ignorable plugin records outside the model-visible con
- **No model tool** — the model cannot read or change bindings yet.
- **Background output** — `run_in_background: true` returns a job id without binding evidence. A foreground command moved to the background contributes only the output in its first result; later job output does not add bindings. Use `track` for change requests missing from that result.
- **Unqualified tag updates** — a forced or up-to-date tag printed without `refs/tags/` is treated as a branch. Discovery may bind an open change request for a branch with the same name; use `dismiss` to hide an incorrect binding.
- **Shortened program output** — a shell call inside a PTC program binds from the logged copy of its output, which the spill policy can shorten. A URL only in the omitted part does not bind, and the live lookup, which reads the complete output, skips a call whose output prints its own URL; use `track`.
- **Per-Session bindings** — subagent Sessions keep their own bindings; a parent Session does not aggregate them.
- **Silent lookup failures** — lookup failures reach the host log only; neither the Session nor its watchers see them.
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
无需单独的登记簿,即可列出一个 Session 正在处理的 pull request。一个投影从 Session 自己的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` shell 结果以及绑定记录派生绑定。每次推送后,以及 forge 面板等调用方报告 Session 所在的分支时,服务为该分支查找打开状态的变更请求(change request,即 pull request 或 merge request),并记录尚未绑定的那些。监听一个 Session 时,会通过 `ctx.forge` 轮询其已绑定的变更请求。Session 摘要把绑定带给客户端。
无需单独的登记簿,即可列出一个 Session 正在处理的 pull request。一个投影从 Session 自己的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` shell 结果(包括 PTC 程序内的 shell 调用)以及绑定记录派生绑定。每次推送后,以及 forge 面板等调用方报告 Session 所在的分支时,服务为该分支查找打开状态的变更请求(change request,即 pull request 或 merge request),并记录尚未绑定的那些。监听一个 Session 时,会通过 `ctx.forge` 轮询其已绑定的变更请求。Session 摘要把绑定带给客户端。
## 目录
@@ -36,9 +36,9 @@ kind: "package-reference"
`ctx.forgeSession.changeRequests(session)` 按首次记录的顺序返回可见的绑定。每一项包含 URL、其 `origin`(`created`、`referenced`、`discovered` 或 `tracked`)、提供方引用(没有提供方服务该 URL 时为 `null`)以及最近一次轮询结果(尚无结果时为 `null`)。`watch(session, listener)` 是调用方 fiber 上的 effect:Session 有监听方期间,提供方服务的每个可见绑定都会被轮询;此后每次绑定变化、提供方注册变化或轮询结果到达时,监听方都会收到完整列表。提供方变化会重新同步已有监听,包括此前没有提供方服务的 URL。`track(session, url)` 以提供方的规范形式绑定 URL,或恢复已隐藏的绑定;没有提供方识别该 URL 时抛错。`dismiss(session, url)` 隐藏一个可见绑定;其他 URL 不会改变日志。`discoverBranch(session, remote, branch)` 为位于 `remote` 远端的分支执行推送之后的那次查找,记录完绑定或失败后 resolve;没有提供方服务的远端不会带来任何变化。
`bash` 或 `pwsh` 调用只从其第一个结果中提取证据,且仅当工具执行本身成功时才提取;命令的退出状态不影响结果。包含 `gh pr create` 或 `gh pr new` 的命令会绑定其文本输出中的每个 `/pull/<number>` URL。包含 `gh pr view`、`gh pr edit` 或 `gh pr checkout` 的命令以 `referenced` 绑定:命令选中的 `/pull/<number>` URL,或带有明确仓库和主机的数字编号,以及输出为它所操作的变更请求本身打印的 URL,即 gh 的 `url:` 字段、开始描述正文的 `--` 行之前单独成行的 URL,以及 JSON 的 `url` 成员。描述正文或其他字段里的链接不会绑定;同一命令里还包含 `gh pr create` 时,其 URL 以 `created` 绑定。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To <remote>` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `refs/heads/` 之外的引用会被跳过。对远端由提供方服务的每个被推送分支,服务在 `discoveryTimeoutMs` 内调用 `ctx.forge.findByHead`,并为返回的每个尚未绑定的变更请求追加一条 `discover` 记录。已隐藏的绑定仍视为已绑定而被跳过;只有 `track` 会恢复它们。每次推送都会重新查找;失败记录为警告日志。关闭 Session 会取消其未完成的分支查找,不追加绑定。重新打开不会补做这些查找;可再次推送、调用 `discoverBranch` 或用 `track` 绑定变更请求。仅在协议、大小写、查询、片段或末尾斜杠上不同的 URL 指向同一个绑定。
`bash` 或 `pwsh` 调用只从其第一个结果中提取证据,且仅当工具执行本身成功时才提取;命令的退出状态不影响结果。PTC 程序内的 `bash` 或 `pwsh` 调用从其 `tool/ptc-dispatch` 事件提取同样的证据,该事件记录调用的参数及其结算结果。包含 `gh pr create` 或 `gh pr new` 的命令会绑定其文本输出中的每个 `/pull/<number>` URL。包含 `gh pr view`、`gh pr edit` 或 `gh pr checkout` 的命令以 `referenced` 绑定:命令选中的 `/pull/<number>` URL,或带有明确仓库和主机的数字编号,以及输出为它所操作的变更请求本身打印的 URL,即 gh 的 `url:` 字段、开始描述正文的 `--` 行之前单独成行的 URL,以及 JSON 的 `url` 成员。描述正文或其他字段里的链接不会绑定;同一命令里还包含 `gh pr create` 时,其 URL 以 `created` 绑定。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To <remote>` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `refs/heads/` 之外的引用会被跳过。对远端由提供方服务的每个被推送分支,服务在 `discoveryTimeoutMs` 内调用 `ctx.forge.findByHead`,并为返回的每个尚未绑定的变更请求追加一条 `discover` 记录。已隐藏的绑定仍视为已绑定而被跳过;只有 `track` 会恢复它们。每次推送都会重新查找;失败记录为警告日志。关闭 Session 会取消其未完成的分支查找,不追加绑定。重新打开不会补做这些查找;可再次推送、调用 `discoverBranch` 或用 `track` 绑定变更请求。仅在协议、大小写、查询、片段或末尾斜杠上不同的 URL 指向同一个绑定。
`gh pr view`、`edit` 和 `checkout` 的数字编号支持 `--repo OWNER/REPO`、`--repo=OWNER/REPO` 和 `-R OWNER/REPO`,参数可位于编号前后。仓库参数中的主机或字面量 `GH_HOST` 赋值可直接确定 URL;对于单条命令(可通过管道传给 `head`、`tail` 或 `cat`),未写明主机且已完成的前台 Bash 调用会通过相同的 shell 服务、工作目录、字面量环境赋值、托管环境和常设沙箱策略,执行只读的 `gh pr view <number> --repo <repository> --json url` 查询,由 CLI 解析其配置的主机。查询成功后追加 `reference` 绑定记录;失败时保留现有绑定并记录警告。此实时观察器需要 `tools`、`shell` 和 `shellEnv`,仅含投影的组合仍可恢复已记录的 URL。查询共用 `discoveryTimeoutMs`,调用方取消会停止查询,销毁服务会中止并等待查询结束。
`gh pr view`、`edit` 和 `checkout` 的数字编号支持 `--repo OWNER/REPO`、`--repo=OWNER/REPO` 和 `-R OWNER/REPO`,参数可位于编号前后。仓库参数中的主机或字面量 `GH_HOST` 赋值可直接确定 URL;对于单条命令(可通过管道传给 `head`、`tail` 或 `cat`),未写明主机且已完成的前台 Bash 调用会通过相同的 shell 服务、工作目录、字面量环境赋值、托管环境和常设沙箱策略,执行只读的 `gh pr view <number> --repo <repository> --json url` 查询,由 CLI 解析其配置的主机。查询成功后追加 `reference` 绑定记录;失败时保留现有绑定并记录警告。PTC 程序内的 Bash 调用在外层根调用结算后才执行查询,因此查询随该根调用取消。此实时观察器需要 `tools`、`shell` 和 `shellEnv`,仅含投影的组合仍可恢复已记录的 URL。查询共用 `discoveryTimeoutMs`,调用方取消会停止查询,销毁服务会中止并等待查询结束。
绑定操作是 `plugin:forge-session/binding` 插件记录,列于[实验性持久化目录](../../../docs/experimental-persistence-catalog.zh.md);fork 与恢复会把它们与 shell 事件一同带上,因此 fork 出的 Session 从父 Session 的绑定开始。`discoveryTimeoutMs` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-session)。
@@ -50,13 +50,14 @@ kind: "package-reference"
<details>
<summary>实现细节——点击展开</summary>
`forgeChangeRequests` 投影保存等待第一个结果的 shell 调用、每个绑定及其隐藏状态,以及每个被推送分支和最近一次报告它的结果的序号。`turn/end` 会丢弃仍在等待的调用。它的客户端视图随 Session 摘要下发,按首次记录的顺序列出每个绑定的 URL、来源与隐藏状态;只有等待中的调用或推送变化时,视图保持同一引用。服务收到 `tool/result` 事件时,只对序号等于该事件序号的推送执行发现,并在绑定数组变化时刷新监听方。销毁服务会中止查找并丢弃其结果。
`forgeChangeRequests` 投影保存等待第一个结果的 shell 调用、每个绑定及其隐藏状态,以及每个被推送分支和最近一次报告它的结果的序号。`turn/end` 会丢弃仍在等待的调用。它的客户端视图随 Session 摘要下发,按首次记录的顺序列出每个绑定的 URL、来源与隐藏状态;只有等待中的调用或推送变化时,视图保持同一引用。服务收到 `tool/result` 或 `tool/ptc-dispatch` 事件时,只对序号等于该事件序号的推送执行发现,并在绑定数组变化时刷新监听方。销毁服务会中止查找并丢弃其结果。
| 源码 | 职责 |
|---|---|
| [`src/index.ts`](src/index.ts) | 发现、track 与 dismiss 记录以及 Session 监听 |
| [`src/projection.ts`](src/projection.ts) | 折叠 shell 调用、结果与绑定记录 |
| [`src/projection.ts`](src/projection.ts) | 折叠 shell 调用、结果、程序分派与绑定记录 |
| [`src/commands.ts`](src/commands.ts) | 命令分类与输出解析 |
| [`src/reference-lookup.ts`](src/reference-lookup.ts) | 实时查询未写明主机的数字编号 |
| [`src/types.ts`](src/types.ts) | 绑定记录、投影状态与条目类型 |
</details>
@@ -91,6 +92,7 @@ kind: "package-reference"
- **没有模型工具**——模型目前还不能读取或修改绑定。
- **后台输出**——`run_in_background: true` 只返回作业 id,不含绑定证据。转入后台的前台命令只贡献首个结果中的输出;后续作业输出不会补充绑定。首个结果中未出现的变更请求需用 `track` 绑定。
- **未带完整引用的标签更新**——强制更新或已是最新的标签,如果输出未带 `refs/tags/`,会被当成分支。发现过程可能绑定同名分支的打开状态变更请求;可用 `dismiss` 隐藏错误绑定。
- **程序输出被缩短**——PTC 程序内的 shell 调用从其输出的日志副本绑定,溢出策略可能缩短该副本。只出现在被省略部分的 URL 不会绑定;而读取完整输出的实时查询会跳过输出已打印其自身 URL 的调用;请使用 `track`。
- **按 Session 绑定**——subagent 的 Session 保有自己的绑定;父 Session 不会汇总它们。
- **查找失败不可见**——查找失败只写入宿主日志;Session 与其监听方都看不到。
@@ -43,6 +43,7 @@
},
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-experimental-forge": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-session-projection": "workspace:*",
@@ -73,7 +74,10 @@
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-working-directory": "workspace:*",
"@deepseek-ai/dsh-shell": "workspace:*",
"@deepseek-ai/dsh-sandbox-policy": "workspace:*"
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
"@deepseek-ai/dsh-tool-executor-ptc": "workspace:*",
"@deepseek-ai/dsh-ptc-runtime-node": "workspace:*",
"@deepseek-ai/dsh-sandbox-local": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/dsh-shell": {
@@ -33,9 +33,18 @@ export function commandOf(argumentsJson: string): string | undefined {
void error // Malformed arguments never ran a command.
return undefined
}
if (typeof parsed !== 'object' || parsed === null) return undefined
const command: unknown = (parsed as { command?: unknown }).command
return typeof command === 'string' ? command : undefined
return commandIn(parsed)
}
/**
* Read the command string of parsed `bash` or `pwsh` arguments, such as the
* arguments a program dispatch logs.
* @param args - parsed tool arguments.
* @returns the command, or undefined when the arguments carry no string `command`.
*/
export function commandIn(args: unknown): string | undefined {
if (typeof args !== 'object' || args === null || !('command' in args)) return undefined
return typeof args.command === 'string' ? args.command : undefined
}
/**
@@ -32,12 +32,12 @@ interface SessionWatch {
/**
* Session-scoped change request bindings. The `forgeChangeRequests`
* projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`,
* `gh pr checkout`, and `git push` results and from
* `plugin:forge-session/binding` records. After each push result, and when a
* caller reports the branch a Session works on, the service looks up open
* change requests whose head is that branch and records the unbound ones as
* discovered. Watching a Session polls its visible change requests through
* `ctx.forge`.
* `gh pr checkout`, and `git push` results, including those of shell calls
* inside PTC programs, and from `plugin:forge-session/binding` records.
* After each push result, and when a caller reports the branch a Session
* works on, the service looks up open change requests whose head is that
* branch and records the unbound ones as discovered. Watching a Session
* polls its visible change requests through `ctx.forge`.
*/
export class ForgeSessionService extends Service {
static inject = ['forge', 'sessions', 'sessionProjections']
@@ -192,7 +192,7 @@ export class ForgeSessionService extends Service {
/** Discover change requests for this result's pushes and refresh watchers after binding changes. */
private react(session: Session, event: SessionEvent): void {
if (event.type !== 'tool/result' && pluginRecordOf(event)?.type !== BINDING_RECORD) return
if (event.type !== 'tool/result' && event.type !== 'tool/ptc-dispatch' && pluginRecordOf(event)?.type !== BINDING_RECORD) return
const state = this.state(session)
for (const push of state.pushes) {
if (push.seq === event.seq) void this.discover(session, push.remote, push.branch)
@@ -1,13 +1,15 @@
/** Projection that folds shell results and binding records into one Session's change request bindings, and shows clients the bindings. */
/** Projection that folds shell results, program shell dispatches, and binding records into one Session's change request bindings. */
import { z } from 'zod'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session'
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { changeRequestUrls, commandEvidence, commandOf, ownChangeRequestUrls, pushedBranches, sameChangeRequestUrl } from './commands.ts'
import { changeRequestUrls, commandEvidence, commandIn, commandOf, ownChangeRequestUrls, pushedBranches, sameChangeRequestUrl } from './commands.ts'
import type { PushedRef } from './commands.ts'
import type { BindingOrigin, BindingRecord, BindingState, ForgeChangeRequestsState, PushedBranch } from './types.ts'
import type { BindingOrigin, BindingRecord, BindingState, CommandEvidence, ForgeChangeRequestsState, PushedBranch } from './types.ts'
/** Plugin record type of binding actions. */
export const BINDING_RECORD = 'plugin:forge-session/binding'
@@ -62,15 +64,18 @@ const stateSchema: z.ZodType<ForgeChangeRequestsState> = z.object({
* every pull request URL a `gh pr create` result prints; for the other `gh pr`
* commands it binds the URL the command names and the URL the output prints
* for its own change request; and it records the branches it reports as
* pushed. Failed tool executions bind nothing; a nonzero exit status does not
* matter, because the URL or ref line is the evidence. `turn/end` drops calls
* that never received a result. Binding records bind, restore, and hide URLs.
* Clients, including the Session summary, see the bindings; the array keeps
* its reference while only pending calls and pushes change.
* pushed. A `tool/ptc-dispatch` event of a `bash` or `pwsh` call inside a
* program carries the arguments and the settled outcome together, so it
* applies the same rules without a pending entry. Failed tool executions bind
* nothing; a nonzero exit status does not matter, because the URL or ref line
* is the evidence. `turn/end` drops calls that never received a result.
* Binding records bind, restore, and hide URLs. Clients, including the
* Session summary, see the bindings; the array keeps its reference while only
* pending calls and pushes change.
*/
export const forgeChangeRequestsProjection = {
key: 'forgeChangeRequests',
stateVersion: 3,
stateVersion: 4,
stateSchema,
init: () => EMPTY,
apply,
@@ -83,6 +88,8 @@ function apply(state: ForgeChangeRequestsState, event: SessionEvent): ForgeChang
return applyCall(state, event.data)
case 'tool/result':
return applyResult(state, event.data, event.seq)
case 'tool/ptc-dispatch':
return applyDispatch(state, event.data, event.seq)
case 'turn/end':
return state.pending.length === 0 ? state : { ...state, pending: EMPTY.pending }
// Every other event type, including plugin records, which sit outside SessionEventMap.
@@ -103,15 +110,30 @@ function applyResult(state: ForgeChangeRequestsState, result: SessionEventMap['t
const callId = result.message.toolCallId
const pending = state.pending.find(entry => entry.callId === callId)
if (pending === undefined) return state
const rest = state.pending.filter(entry => entry !== pending)
if (result.message.isError === true) return { ...state, pending: rest }
const text = result.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
const printed = pending.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text)
return {
pending: rest,
bindings: pending.urls === null ? state.bindings : bind(state.bindings, [...pending.named, ...printed], pending.urls),
pushes: pending.pushes ? recordPushes(state.pushes, pushedBranches(text), seq) : state.pushes,
}
const settled = { ...state, pending: state.pending.filter(entry => entry !== pending) }
if (result.message.isError === true) return settled
return settle(settled, pending, textOf(result.message.content), seq)
}
function applyDispatch(state: ForgeChangeRequestsState, dispatch: SessionEventMap['tool/ptc-dispatch'], seq: SessionSeq): ForgeChangeRequestsState {
if (!SHELL_TOOLS.has(dispatch.name) || dispatch.isError) return state
const command = commandIn(dispatch.arguments)
const evidence = command === undefined ? undefined : commandEvidence(command)
if (evidence === undefined) return state
return settle(state, evidence, textOf(dispatch.content), seq)
}
/** Text blocks of a rendered shell result, joined by newlines. */
function textOf(content: readonly ContentBlock[]): string {
return content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
}
/** Bind the URLs and record the pushes one successful shell result carries; returns the input state when nothing changes. */
function settle(state: ForgeChangeRequestsState, evidence: CommandEvidence, text: string, seq: SessionSeq): ForgeChangeRequestsState {
const printed = evidence.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text)
const bindings = evidence.urls === null ? state.bindings : bind(state.bindings, [...evidence.named, ...printed], evidence.urls)
const pushes = evidence.pushes ? recordPushes(state.pushes, pushedBranches(text), seq) : state.pushes
return bindings === state.bindings && pushes === state.pushes ? state : { ...state, bindings, pushes }
}
function applyRecord(state: ForgeChangeRequestsState, event: SessionEvent): ForgeChangeRequestsState {
@@ -2,7 +2,7 @@
import type { Context } from '@deepseek-ai/cordis'
import type { Session } from '@deepseek-ai/dsh-session'
import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
import type { ToolExecution, ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
import type {} from '@deepseek-ai/dsh-shell'
import type {} from '@deepseek-ai/dsh-shell-env'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
@@ -21,12 +21,24 @@ const completedShell = z.object({
const shellArguments = z.object({ command: z.string() })
const resolvedReference = z.object({ url: z.string().regex(/^https?:\/\/[^\s/]+\/[^\s/]+\/[^\s/]+\/pull\/[1-9]\d*\/?$/) })
/** One read-only lookup for a completed call that named a reference. */
interface Lookup {
/** Call whose shell execution world the lookup reuses. */
readonly exec: Readonly<ToolExecution>
readonly session: Session
readonly command: string
readonly cwd: string
}
/**
* Observe completed foreground Bash calls while tools and shell services exist.
* Queries use the same shell service, cwd, managed environment, and standing
* sandbox policy. Failed lookups leave bindings unchanged and log a warning.
* Cancellation leaves bindings unchanged; disposal aborts and awaits all queries.
* Replay performs no lookup.
* sandbox policy as the call. A call inside a program, which carries a
* `parent` token, queues its query until the root call that encloses it
* settles, so the query runs under that root call's cancellation after the
* program's dispatch events are logged. Failed lookups leave bindings
* unchanged and log a warning. Cancellation leaves bindings unchanged;
* disposal aborts and awaits all queries. Replay performs no lookup.
* @param ctx - owning plugin context.
* @param timeoutMs - shell deadline for one read-only lookup.
* @param record - persists a confirmed URL without restoring dismissed bindings.
@@ -35,48 +47,77 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess
ctx.inject(['tools', 'shell', 'shellEnv'], (scope) => {
const lifetime = new AbortController()
const tasks = new Set<Promise<void>>()
/**
* Lookups of settled program calls, keyed by the token of the call that
* encloses them. The tools pipeline publishes `tools/result` for every
* execution it completes, error and cancellation included, so an enclosing
* call takes its entries when it settles; scope disposal drops the rest.
*/
const queued = new Map<ToolExecutionToken, Lookup[]>()
scope.effect(() => async () => {
lifetime.abort()
await Promise.allSettled(tasks)
}, 'forge-session: stop reference lookups')
scope.on('tools/result', (exec, result) => {
const task = resolve(exec, result).catch((error: unknown) => {
if (lifetime.signal.aborted || exec.signal.aborted) return
scope.logger.warn(`forge-session: PR reference lookup failed; use a full PR URL to bind it: ${error instanceof Error ? error.message : String(error)}`)
})
const lookups = [...queued.get(exec.token) ?? [], ...prepare(exec, result)]
queued.delete(exec.token)
if (lookups.length === 0) return
if (exec.parent !== undefined) {
queued.set(exec.parent, [...queued.get(exec.parent) ?? [], ...lookups])
return
}
const task = run(lookups, AbortSignal.any([lifetime.signal, exec.signal]))
tasks.add(task)
void task.then(() => tasks.delete(task))
})
async function resolve(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): Promise<void> {
if (exec.name !== 'bash' || exec.agent === undefined || exec.parent !== undefined || result.isError) return
/**
* List the lookups one settled call needs, in command order: none unless
* it is a completed foreground Bash call of an Agent whose output prints
* no URL of its own change request.
*/
function prepare(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): Lookup[] {
if (exec.name !== 'bash' || exec.agent === undefined || result.isError) return []
const argumentsResult = shellArguments.safeParse(exec.arguments)
const shell = completedShell.safeParse(result.value)
if (!argumentsResult.success || !shell.success) return
if (!argumentsResult.success || !shell.success) return []
const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
if (ownChangeRequestUrls(printed).length > 0) return
const lookups = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup])
const agent = exec.agent
const signal = AbortSignal.any([lifetime.signal, exec.signal])
for (const command of lookups) {
signal.throwIfAborted()
const spec = scope.shell.resolve({
command,
workdir: shell.data.cwd,
timeoutMs,
signal,
dshEnv: scope.shellEnv.collect(exec),
sandboxPolicy: scope.get('sandboxPolicy')?.resolve({ session: agent.session }),
})
const process = await scope.shell.execute(spec)
const output = await process.result()
signal.throwIfAborted()
if (output.exitCode !== 0 || output.signal !== null || output.timedOut || output.aborted || output.stdout.truncated) {
throw new Error('gh did not return a complete successful reference lookup')
if (ownChangeRequestUrls(printed).length > 0) return []
const session = exec.agent.session
return ghReferences(argumentsResult.data.command)
.flatMap(reference => reference.lookup === null ? [] : [{ exec, session, command: reference.lookup, cwd: shell.data.cwd }])
}
/** Run lookups in call order; a failed lookup is logged and does not stop the next one. */
async function run(lookups: readonly Lookup[], signal: AbortSignal): Promise<void> {
for (const lookup of lookups) {
try {
await resolve(lookup, signal)
} catch (error: unknown) {
if (signal.aborted) return
scope.logger.warn(`forge-session: PR reference lookup failed; use a full PR URL to bind it: ${error instanceof Error ? error.message : String(error)}`)
}
const parsed = resolvedReference.parse(JSON.parse(output.stdout.text))
record(agent.session, parsed.url)
}
}
async function resolve(lookup: Lookup, signal: AbortSignal): Promise<void> {
signal.throwIfAborted()
const spec = scope.shell.resolve({
command: lookup.command,
workdir: lookup.cwd,
timeoutMs,
signal,
dshEnv: scope.shellEnv.collect(lookup.exec),
sandboxPolicy: scope.get('sandboxPolicy')?.resolve({ session: lookup.session }),
})
const process = await scope.shell.execute(spec)
const output = await process.result()
signal.throwIfAborted()
if (output.exitCode !== 0 || output.signal !== null || output.timedOut || output.aborted || output.stdout.truncated) {
throw new Error('gh did not return a complete successful reference lookup')
}
const parsed = resolvedReference.parse(JSON.parse(output.stdout.text))
record(lookup.session, parsed.url)
}
})
}
@@ -55,7 +55,7 @@ export interface PushedBranch {
readonly remote: string
/** Branch name on the remote. */
readonly branch: string
/** Sequence number of the latest `tool/result` event that reported this branch. */
/** Sequence number of the latest `tool/result` or `tool/ptc-dispatch` event that reported this branch. */
readonly seq: SessionSeq
}
@@ -8,6 +8,7 @@ import { createAssistantMessage, createToolResultMessage, type ToolCallId } from
import SessionStore from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types'
import ForgeSessionService from '../src/index.ts'
import type { Config } from '../src/index.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -195,6 +196,53 @@ export function shellTurn(session: Session, calls: readonly ShellCall[]): void {
session.append('turn/end', { turn, reason: { kind: 'completed' } })
}
/** One shell call inside a program, the text its settled dispatch carries, and its tool arguments. */
export interface ProgramCall extends Omit<ShellCall, 'callId'> {
/** Logged arguments; defaults to `{ command, description }`. */
readonly arguments?: unknown
}
/**
* Append one completed turn in which the model runs `calls` as tool calls inside one PTC `run_code` program.
* Each call logs a `tool/ptc-dispatch-start` and a `tool/ptc-dispatch` event inside the open `run_code` call.
* @param session - live Session receiving the events.
* @param callId - id of the `run_code` call.
* @param calls - nested calls with their settled text, numbered `<callId>:ptc:<n>`.
* @param programError - whether the `run_code` result itself fails after the nested calls settle.
*/
export function programTurn(session: Session, callId: string, calls: readonly ProgramCall[], programError = false): void {
const turn = (turns.get(session) ?? 0) + 1
turns.set(session, turn)
const step = 1
const rootCallId = brandString<ToolCallId>(callId)
const programArguments = JSON.stringify({ code: 'await tools.bash({ command })', description: 'Run the program' })
session.append('turn/start', { turn })
session.append('step/start', { turn, step })
session.append('assistant/message', {
turn,
step,
stream: [],
message: createAssistantMessage({
content: [{ type: 'tool-call' as const, id: rootCallId, name: 'run_code', arguments: programArguments }],
source: { provider: 'fixture', model: 'fixture' },
}),
}, { surfaceOp: 'append' })
session.append('tool/call', { turn, step, callId: rootCallId, name: 'run_code', arguments: programArguments })
for (const [index, call] of calls.entries()) {
const ids = { rootCallId, parentCallId: rootCallId, subCallId: brandString<ToolCallId>(`${callId}:ptc:${index + 1}`) }
const dispatched = { ...ids, name: call.tool ?? 'bash', arguments: 'arguments' in call ? call.arguments : { command: call.command, description: 'Run it' } }
session.append('tool/ptc-dispatch-start', dispatched)
session.append('tool/ptc-dispatch', { ...dispatched, isError: call.isError ?? false, content: [{ type: 'text', text: call.output }] })
}
session.append('tool/result', {
turn,
step,
message: createToolResultMessage({ callId: rootCallId, content: [{ type: 'text', text: programError ? 'Error: code run failed' : 'done' }], isError: programError }),
}, { surfaceOp: 'append' })
session.append('step/end', { turn, step })
session.append('turn/end', { turn, reason: { kind: 'completed' } })
}
/** Rendered `bash` result of a `git push` that created `branch` on the `fake.test:octo/demo.git` remote. */
export function pushOutput(branch: string, remote = 'fake.test:octo/demo.git'): string {
return [
@@ -15,14 +15,19 @@ import ForgeService from '@deepseek-ai/dsh-experimental-forge'
import * as ForgeGitHub from '@deepseek-ai/dsh-experimental-forge-github'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
import LlmRuntime, { createUserMessage, LlmAdapter, type ToolCallId } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk, ToolCallBlock } from '@deepseek-ai/dsh-llm'
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
import LocalSandbox from '@deepseek-ai/dsh-sandbox-local'
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
import SessionStore, { pluginRecordOf, type SessionId } from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import * as ShellEnv from '@deepseek-ai/dsh-shell-env'
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory'
import ForgeSessionService from '../src/index.ts'
@@ -116,10 +121,24 @@ const FAKE_GIT = `#!/bin/sh
printf 'To github.com:octo/demo.git\\n * [new branch] feat -> feat\\n' >&2
`
/** One scripted model step: the tool call it makes, or the final text when undefined. */
type ScriptedCall = Omit<ToolCallBlock, 'type' | 'id'> | undefined
/** A `bash` call running `command`. */
function bashCall(command: string): ScriptedCall {
return { name: 'bash', arguments: JSON.stringify({ command, description: 'Run the scripted command' }) }
}
/** A PTC `run_code` call whose TypeScript program runs `commands` through the `bash` binding in order. */
function programCall(commands: readonly string[]): ScriptedCall {
const code = `for (const command of ${JSON.stringify(commands)}) await tools.bash({ command, description: 'Run the scripted command' })`
return { name: 'run_code', arguments: JSON.stringify({ code, description: 'Run the scripted commands' }) }
}
class ScriptedModel extends LlmAdapter {
readonly requests: GenerateOptions[] = []
constructor(private readonly commands: readonly string[]) {
constructor(private readonly calls: readonly ScriptedCall[]) {
super()
}
@@ -129,9 +148,9 @@ class ScriptedModel extends LlmAdapter {
async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
this.requests.push(options)
const command = this.commands[this.requests.length - 1]
if (command !== undefined) {
const call = { type: 'tool-call' as const, id: brandString<ToolCallId>(`shell-${this.requests.length}`), name: 'bash', arguments: JSON.stringify({ command, description: 'Run the scripted command' }) }
const scripted = this.calls[this.requests.length - 1]
if (scripted !== undefined) {
const call = { type: 'tool-call' as const, id: brandString<ToolCallId>(`shell-${this.requests.length}`), ...scripted }
yield { type: 'block-start', index: 0, blockType: 'tool-call' }
yield { type: 'block-end', index: 0, block: call }
yield { type: 'finish', reason: { kind: 'tool-calls' } }
@@ -155,7 +174,19 @@ afterEach(async () => {
const suite = process.platform === 'win32' ? describe.skip : describe
async function load() {
/** Plugins that replace the native executor in PTC mode, in load order. */
const PTC_MODULES = [
['@deepseek-ai/dsh-sandbox-local', LocalSandbox],
['@deepseek-ai/dsh-sandbox-policy', SandboxPolicy],
['@deepseek-ai/dsh-ptc-runtime-node', NodeRuntime],
['@deepseek-ai/dsh-tool-executor-ptc', PtcToolExecutor],
] as const
/**
* Boot the composition through a test-only cordis.yml. `ptc` replaces the native executor with the PTC executor,
* the Node program runtime, and the sandbox services that runtime requires.
*/
async function load(mode: 'native' | 'ptc' = 'native') {
root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-forge-session-loader-')))
const bin = join(root, 'bin')
await mkdir(bin)
@@ -173,7 +204,7 @@ async function load() {
['@deepseek-ai/dsh-fs-local', LocalFileSystem],
['@deepseek-ai/dsh-working-directory', WorkingDirectoryService],
['@deepseek-ai/dsh-tools', ToolRuntime],
['@deepseek-ai/dsh-tool-executor-native', NativeToolExecutor],
...mode === 'native' ? [['@deepseek-ai/dsh-tool-executor-native', NativeToolExecutor] as const] : PTC_MODULES,
['@deepseek-ai/dsh-agent', AgentRegistry],
['@deepseek-ai/dsh-agent-loop', AgentLoop],
['@deepseek-ai/dsh-subprocess-local', LocalSubprocessRuntime],
@@ -187,6 +218,7 @@ async function load() {
const configs: Record<string, readonly string[]> = {
'@deepseek-ai/dsh-agent-loop': ['agents: []'],
'@deepseek-ai/dsh-shell-env': [`dshHome: ${JSON.stringify(join(root, 'dsh-home'))}`],
'@deepseek-ai/dsh-sandbox-policy': ['mode: danger-full-access'],
'@deepseek-ai/dsh-bash-local': ['timeoutMs: 20000'],
'@deepseek-ai/dsh-experimental-forge': ['activeIntervalMs: 600000', 'idleIntervalMs: 600000'],
'@deepseek-ai/dsh-experimental-forge-github': [`ghCommand: ${JSON.stringify(join(bin, 'gh'))}`],
@@ -244,6 +276,58 @@ async function observerFixture() {
return { ctx, path, exec, result, controller, entry, records, query, executeSpy, recorded }
}
/** Push `feat`, create PR 8, and view PR 9 by number without its URL in the output. */
function scriptedCommands(path: string): string[] {
return [
`${path} git push -u origin feat`,
`${path} gh pr create --fill --head other`,
`${path} gh pr view 9 --repo octo/demo --json number,title,body 2>&1 | head -200`,
]
}
/** Run one user turn of a scripted model in a new Agent and wait until the Agent is idle. */
async function runTurn(ctx: Context, root: string, sessionId: string, calls: readonly ScriptedCall[]) {
const model = new ScriptedModel(calls)
ctx.llm.registerAdapter(['fixture'], model)
const agent = await ctx.agentLoop.create(brandString<SessionId>(sessionId), { provider: 'fixture', model: 'fixture' }, { cwd: root })
const idle: PromiseWithResolvers<void> = Promise.withResolvers()
const stop = ctx.on('agent/status', ({ agent: subject, status }) => {
if (subject === agent && status === 'idle') idle.resolve()
})
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Push feat, open a pull request, and view PR 9.' }], source: { kind: 'user' } }))
await idle.promise
stop()
return { agent, model }
}
/** Arguments of every fake `gh` invocation in call order. */
async function ghCalls(root: string): Promise<string[][]> {
return (await readFile(join(root, 'gh.log'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
}
function byUrl(entries: readonly SessionChangeRequest[]): SessionChangeRequest[] {
return [...entries].sort((left, right) => left.url.localeCompare(right.url))
}
/** Expect the push to discover PR 7, the create to bind PR 8, and the numbered view to resolve PR 9 through `gh`. */
async function expectScriptedBindings(ctx: Context, session: Session, root: string): Promise<void> {
const records = () => session.snapshotEvents().flatMap((event) => {
const record = pluginRecordOf(event)
return record === undefined ? [] : [record.data]
})
await vi.waitFor(() => { expect(records()).toEqual(expect.arrayContaining([
{ action: 'discover', url: 'https://github.com/octo/demo/pull/7' },
{ action: 'reference', url: 'https://github.com/octo/demo/pull/9' },
])) })
const github = (number: number) => ({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number })
expect(byUrl(ctx.forgeSession.changeRequests(session))).toEqual([
{ url: 'https://github.com/octo/demo/pull/7', origin: 'discovered', ref: github(7), update: null },
{ url: 'https://github.com/octo/demo/pull/8', origin: 'created', ref: github(8), update: null },
{ url: 'https://github.com/octo/demo/pull/9', origin: 'referenced', ref: github(9), update: null },
])
expect(await ghCalls(root)).toContainEqual(['pr', 'view', '9', '--repo', 'octo/demo', '--json', 'url'])
}
suite('forge-session through a real cordis.yml Loader composition', () => {
it('uses the CLI environment to resolve an Enterprise host and retains a dismissal after another lookup', async () => {
const f = await observerFixture()
@@ -297,7 +381,6 @@ suite('forge-session through a real cordis.yml Loader composition', () => {
emit({ ...f.exec, name: 'pwsh' })
const { agent: _agent, ...withoutAgent } = f.exec
emit(withoutAgent)
emit({ ...f.exec, parent: f.exec.token })
emit(f.exec, { isError: true, error: { message: 'failed' }, content: [] })
emit({ ...f.exec, arguments: {} })
emit(f.exec, { isError: false, value: { kind: 'background' }, content: [] })
@@ -337,40 +420,12 @@ suite('forge-session through a real cordis.yml Loader composition', () => {
it('binds the pull requests that bash pushes discover, creates, and views, and polls them through the GitHub provider', async () => {
const { ctx, path, root } = await load()
const model = new ScriptedModel([
`${path} git push -u origin feat`,
`${path} gh pr create --fill --head other`,
`${path} gh pr view 9 --repo octo/demo --json number,title,body 2>&1 | head -200`,
])
ctx.llm.registerAdapter(['fixture'], model)
const agent = await ctx.agentLoop.create(brandString<SessionId>('forge-session-loader'), { provider: 'fixture', model: 'fixture' }, { cwd: root })
const idle: PromiseWithResolvers<void> = Promise.withResolvers()
const stop = ctx.on('agent/status', ({ agent: subject, status }) => {
if (subject === agent && status === 'idle') idle.resolve()
})
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Push feat and open a pull request.' }], source: { kind: 'user' } }))
await idle.promise
stop()
const { agent, model } = await runTurn(ctx, root, 'forge-session-loader', scriptedCommands(path).map(bashCall))
expect(model.requests).toHaveLength(4)
const github = (number: number) => ({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number })
const records = () => agent.session.snapshotEvents().flatMap((event) => {
const record = pluginRecordOf(event)
return record === undefined ? [] : [record.data]
})
await vi.waitFor(() => { expect(records()).toEqual(expect.arrayContaining([
{ action: 'discover', url: 'https://github.com/octo/demo/pull/7' },
{ action: 'reference', url: 'https://github.com/octo/demo/pull/9' },
])) })
const byUrl = (entries: readonly SessionChangeRequest[]) => [...entries].sort((left, right) => left.url.localeCompare(right.url))
expect(byUrl(ctx.forgeSession.changeRequests(agent.session))).toEqual([
{ url: 'https://github.com/octo/demo/pull/7', origin: 'discovered', ref: github(7), update: null },
{ url: 'https://github.com/octo/demo/pull/8', origin: 'created', ref: github(8), update: null },
{ url: 'https://github.com/octo/demo/pull/9', origin: 'referenced', ref: github(9), update: null },
])
const lookups = (await readFile(join(root, 'gh.log'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
await expectScriptedBindings(ctx, agent.session, root)
const lookups = await ghCalls(root)
expect(lookups.find(args => args.includes('branch=feat'))).toEqual(expect.arrayContaining(['--hostname', 'github.com', 'owner=octo', 'name=demo']))
expect(lookups).toContainEqual(['pr', 'view', '9', '--repo', 'octo/demo', '--json', 'url'])
const listener = vi.fn<SessionChangeRequestsListener>()
ctx.forgeSession.watch(agent.session, listener)
@@ -384,4 +439,18 @@ suite('forge-session through a real cordis.yml Loader composition', () => {
expect(ctx.sessionProjections.checkpoint(agent.session)).toHaveProperty('forgeChangeRequests', row)
expect(ctx.sessionProjections.checkpoint(ctx.sessions.create())).not.toHaveProperty('forgeChangeRequests')
}, 60_000)
it('binds the pull requests that shell calls inside a PTC program push, create, and view', async () => {
const { ctx, path, root } = await load('ptc')
const { agent, model } = await runTurn(ctx, root, 'forge-session-ptc', [programCall(scriptedCommands(path))])
expect(model.requests).toHaveLength(2)
expect(model.requests[0]?.tools?.map(tool => tool.name)).toEqual(['run_code'])
const events = agent.session.snapshotEvents()
expect(events.flatMap(event => event.type === 'tool/call' ? [event.data.name] : [])).toEqual(['run_code'])
expect(events.flatMap(event => event.type === 'tool/ptc-dispatch' ? [[event.data.name, event.data.isError]] : [])).toEqual([
['bash', false], ['bash', false], ['bash', false],
])
await expectScriptedBindings(ctx, agent.session, root)
}, 60_000)
})
@@ -4,7 +4,7 @@ import { createAssistantMessage, createToolResultMessage, type ToolCallId } from
import { appendPluginRecord, Session, type SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
import { forgeChangeRequestsProjection } from '../src/projection.ts'
import type { ForgeChangeRequestsState } from '../src/index.ts'
import { pullUrl, pushOutput, shellTurn } from './fixtures.ts'
import { programTurn, pullUrl, pushOutput, shellTurn } from './fixtures.ts'
const { apply, init, stateSchema } = forgeChangeRequestsProjection
@@ -246,6 +246,76 @@ describe('forgeChangeRequests projection', () => {
])
})
it('binds shell calls inside a PTC program by the rules of direct calls, from both shells and despite a failed program', () => {
const session = Session.create(brandString<SessionId>('program'))
programTurn(session, 'program', [
{ command: 'gh pr create --fill', output: created(1) },
{ command: 'gh pr view 7', output: ['title:\tAdd it', `url:\t${pullUrl(7)}`, '--', `Stacked on ${pullUrl(8)}`].join('\n') },
{ command: 'gh pr edit 4 --add-label bug', output: `${pullUrl(4)}\n`, tool: 'pwsh' },
{ command: `gh pr checkout ${pullUrl(5)}`, output: "Switched to branch 'feat'" },
{ command: 'gh pr view 6 --repo fake.test/octo/demo --json number', output: '{"number":6}' },
{ command: 'gh pr view 3 --repo octo/demo --json number,url', output: JSON.stringify({ number: 3, url: pullUrl(3) }) },
], true)
expect(fold(session)).toEqual({
pending: [],
bindings: [
{ url: pullUrl(1), origin: 'created', dismissed: false },
{ url: pullUrl(7), origin: 'referenced', dismissed: false },
{ url: pullUrl(4), origin: 'referenced', dismissed: false },
{ url: pullUrl(5), origin: 'referenced', dismissed: false },
{ url: pullUrl(6), origin: 'referenced', dismissed: false },
{ url: pullUrl(3), origin: 'referenced', dismissed: false },
],
pushes: [],
})
})
it('records branches a program pushes with the dispatch sequence number', () => {
const session = Session.create(brandString<SessionId>('program-push'))
programTurn(session, 'program', [
{ command: 'git push -u origin feat', output: pushOutput('feat') },
{ command: 'git push -u origin other', output: pushOutput('other') },
])
const dispatches = session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch').map(event => event.seq)
expect(fold(session).pushes).toEqual([
{ remote: 'fake.test:octo/demo.git', branch: 'feat', seq: dispatches[0] },
{ remote: 'fake.test:octo/demo.git', branch: 'other', seq: dispatches[1] },
])
})
it('keeps the state reference for program dispatches that fail, carry no evidence, or run other tools', () => {
const session = Session.create(brandString<SessionId>('program-unrelated'))
programTurn(session, 'program', [
{ command: 'gh pr create --fill', output: created(1), isError: true },
{ command: `gh pr checkout ${pullUrl(9)}`, output: 'boom', isError: true },
{ command: 'git push', output: pushOutput('feat'), isError: true },
{ command: 'gh pr create --fill', output: created(2), tool: 'read' },
{ command: 'ls', output: pullUrl(3) },
{ command: 'gh pr list --json url', output: pullUrl(3) },
{ command: 'gh pr view 9 --repo octo/demo --json number', output: '{"number":9}' },
{ command: '', output: created(4), arguments: { cmd: 'gh pr create' } },
{ command: '', output: created(4), arguments: 'gh pr create' },
{ command: '', output: created(4), arguments: null },
])
const state = fold(session)
expect(state).toEqual({ pending: [], bindings: [], pushes: [] })
for (const event of session.snapshotEvents()) expect(apply(state, event)).toBe(state)
})
it('keeps a dismissed binding hidden when a program references it again', () => {
const session = Session.create(brandString<SessionId>('program-dismissed'))
programTurn(session, 'first', [{ command: `gh pr view ${pullUrl(1)}`, output: `url:\t${pullUrl(1)}` }])
appendPluginRecord(session, 'plugin:forge-session/binding', { action: 'dismiss', url: pullUrl(1) })
const dismissed = fold(session)
programTurn(session, 'second', [{ command: `gh pr view ${pullUrl(1)}`, output: `url:\t${pullUrl(1)}` }])
expect(fold(session)).toEqual(dismissed)
expect(dismissed.bindings).toEqual([{ url: pullUrl(1), origin: 'referenced', dismissed: true }])
})
it('round-trips state through JSON and rejects malformed state', () => {
const session = Session.create(brandString<SessionId>('schema'))
shellTurn(session, [{ callId: 'push', command: 'git push', output: pushOutput('feat') }])
@@ -170,12 +170,11 @@ describe('PR reference lookup', () => {
expect(f.warn).not.toHaveBeenCalled()
})
it('skips unsupported, unsuccessful, already identified, nested, or cancelled calls', async () => {
it('skips unsupported, unsuccessful, already identified, or cancelled calls', async () => {
const f = await fixture()
f.emit({ ...f.exec, name: 'pwsh' })
const { agent: _agent, ...withoutAgent } = f.exec
f.emit(withoutAgent)
f.emit({ ...f.exec, parent: f.exec.token })
f.emit(f.exec, { isError: true, error: { message: 'failed' }, content: [] })
f.emit({ ...f.exec, arguments: {} })
f.emit(f.exec, { isError: false, value: { kind: 'background' }, content: [] })
@@ -189,4 +188,88 @@ describe('PR reference lookup', () => {
expect(f.records()).toEqual([])
expect(f.warn).not.toHaveBeenCalled()
})
describe('inside a PTC program', () => {
/** A `run_code` root call and nested `bash` calls whose run-scoped signal aborts when the program settles. */
function program(f: Awaited<ReturnType<typeof fixture>>) {
const rootController = new AbortController()
const root: ToolExecution = {
name: 'run_code', agent: f.agent,
callId: brandString<ToolCallId>('program'), rootCallId: brandString<ToolCallId>('program'), token: Symbol('program') as ToolExecutionToken,
arguments: { code: 'await tools.bash({ command })', description: 'Run it' }, signal: rootController.signal,
}
const run = new AbortController()
const nested = (n: number, command: string, cwd = process.cwd()): [ToolExecution, ToolExecutionResult] => [{
...f.exec,
callId: brandString<ToolCallId>(`program:ptc:${n}`), rootCallId: root.callId, token: Symbol(`nested ${n}`) as ToolExecutionToken,
parent: root.token, arguments: { command, description: 'View it' }, signal: run.signal,
}, { ...f.result, value: { kind: 'foreground', cwd, exitCode: 0, signal: null, timedOut: false, aborted: false } }]
const settle = (outcome: ToolExecutionResult = { isError: false, value: null, content: [{ type: 'text', text: 'done' }] }) => {
run.abort(new Error('run_code settled'))
f.emit(root, outcome)
}
return { root, rootController, nested, settle }
}
it('looks up after the root call settles, in each call\'s shell world, even when the program fails', async () => {
const f = await fixture()
const p = program(f)
const resolve = vi.spyOn(f.ctx.shell, 'resolve')
const [first, firstResult] = p.nested(1, 'gh pr view 9 -R octo/demo --json number', '/tmp/first')
const [second, secondResult] = p.nested(2, 'gh pr view 7 --repo octo/other', '/tmp/second')
f.emit(first, firstResult)
f.emit(second, secondResult)
expect(f.execute).not.toHaveBeenCalled()
p.settle({ isError: true, error: { message: 'code run failed' }, content: [] })
await vi.waitFor(() => { expect(f.execute).toHaveBeenCalledTimes(2) })
expect(resolve.mock.calls.map(([request]) => [request.command, request.workdir, request.dshEnv])).toEqual([
['env gh pr view 9 --repo octo/demo --json url', '/tmp/first', f.ctx.shellEnv.collect(first)],
['env gh pr view 7 --repo octo/other --json url', '/tmp/second', f.ctx.shellEnv.collect(second)],
])
expect(resolve.mock.calls.every(([request]) => request.signal?.aborted === false)).toBe(true)
await vi.waitFor(() => { expect(f.records()).toEqual([{ action: 'reference', url: pullUrl(9) }]) })
expect(f.warn).not.toHaveBeenCalled()
})
it('carries lookups through every enclosing call to the root call', async () => {
const f = await fixture()
const p = program(f)
const [inner, innerResult] = p.nested(1, 'gh pr view 9 -R octo/demo')
const middle: ToolExecution = { ...p.root, name: 'cua_run_code', callId: brandString<ToolCallId>('program:ptc:2'), token: Symbol('middle') as ToolExecutionToken, parent: p.root.token }
f.emit({ ...inner, parent: middle.token }, innerResult)
f.emit(middle, { isError: false, value: null, content: [] })
expect(f.execute).not.toHaveBeenCalled()
p.settle()
await vi.waitFor(() => { expect(f.records()).toEqual([{ action: 'reference', url: pullUrl(9) }]) })
})
it('continues with the next lookup after one fails', async () => {
const f = await fixture()
const p = program(f)
f.execute.mockResolvedValueOnce(execution(async () => output({ exitCode: 1 })))
for (const [call, outcome] of [p.nested(1, 'gh pr view 8 -R octo/demo'), p.nested(2, 'gh pr view 9 -R octo/demo')]) f.emit(call, outcome)
p.settle()
await vi.waitFor(() => { expect(f.records()).toEqual([{ action: 'reference', url: pullUrl(9) }]) })
expect(f.warn).toHaveBeenCalledTimes(1)
expect(f.warn).toHaveBeenCalledWith(expect.stringContaining('PR reference lookup failed'))
})
it('drops queued lookups when the root call is cancelled, and skips calls whose output names their own URL', async () => {
const f = await fixture()
const p = program(f)
f.emit(...p.nested(1, 'gh pr view 9 -R octo/demo'))
const [printed, printedResult] = p.nested(2, 'gh pr view 7 -R octo/demo --json url')
f.emit(printed, { ...printedResult, content: [{ type: 'text', text: JSON.stringify({ url: pullUrl(7) }) }] })
p.rootController.abort()
p.settle()
await f.service.dispose()
expect(f.execute).not.toHaveBeenCalled()
expect(f.records()).toEqual([])
expect(f.warn).not.toHaveBeenCalled()
})
})
})
@@ -7,7 +7,7 @@ import type { Session } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import ForgeSessionService from '../src/index.ts'
import type { Config, SessionChangeRequest, SessionChangeRequestsListener } from '../src/index.ts'
import { bench, demo, FakeProvider, pull, pullUrl, pushOutput, shellTurn, snapshot } from './fixtures.ts'
import { bench, demo, FakeProvider, programTurn, pull, pullUrl, pushOutput, shellTurn, snapshot } from './fixtures.ts'
import type { Bench } from './fixtures.ts'
const contexts: Context[] = []
@@ -37,6 +37,14 @@ function push(session: Session, callId: string, branch: string, remote?: string)
shellTurn(session, [{ callId, command: `git push -u origin ${branch}`, output: pushOutput(branch, remote) }])
}
/** Restore checkpoint rows over the Session log suffix that starts at `from`, as a cold read does. */
function restorer(ctx: Context, session: Session) {
const events = session.snapshotEvents()
return (checkpoints: ReturnType<Context['sessionProjections']['checkpoint']>, from: number) => ctx.sessionProjections.restore(
checkpoints, events.slice(from), SessionLogOffset(from), session.header, session.inheritedEventCount,
).checkpoint
}
async function settle(): Promise<void> {
await new Promise(resolve => setImmediate(resolve))
}
@@ -119,6 +127,16 @@ describe('forgeSession discovery', () => {
expect(ctx.forgeSession.changeRequests(session)).toEqual([{ url: pullUrl(7), origin: 'discovered', ref: pull(7), update: null }])
})
it('records change requests found for a branch that a PTC program pushes', async () => {
const { ctx, provider, session } = await open()
provider.heads.set('feat', [pull(7)])
programTurn(session, 'program', [{ command: 'git push -u origin feat', output: pushOutput('feat') }])
await vi.waitFor(() => { expect(records(session)).toEqual([{ action: 'discover', url: pullUrl(7) }]) })
expect(provider.lookups.map(lookup => [lookup.repository, lookup.branch])).toEqual([[demo, 'feat']])
expect(ctx.forgeSession.changeRequests(session)).toEqual([{ url: pullUrl(7), origin: 'discovered', ref: pull(7), update: null }])
})
it('skips remotes that no provider serves and change requests that are already bound', async () => {
const { provider, session } = await open()
provider.heads.set('feat', [pull(7)])
@@ -314,6 +332,18 @@ describe('forgeSession watch', () => {
expect(ctx.forgeSession.changeRequests(session)).toEqual(lastList(listener))
})
it('notifies watchers when a PTC program binds a change request', async () => {
const { ctx, session } = await open()
const listener = vi.fn<SessionChangeRequestsListener>()
ctx.forgeSession.watch(session, listener)
programTurn(session, 'program', [{ command: 'gh pr view 3 --repo fake.test/octo/demo --json number', output: '{"number":3}' }])
expect(listener).toHaveBeenCalledTimes(1)
expect(lastList(listener)).toEqual([{ url: pullUrl(3), origin: 'referenced', ref: pull(3), update: null }])
await vi.waitFor(() => { expect(lastList(listener)[0]?.update).toMatchObject({ snapshot: snapshot(pull(3)) }) })
})
it('does not notify for events that leave the bindings unchanged', async () => {
const { ctx, session } = await open()
create(session, 'create', pullUrl(1))
@@ -375,11 +405,8 @@ describe('forgeSession lifecycle', () => {
shellTurn(session, [{ callId: 'number', command: 'gh pr view 9 -R fake.test/octo/demo --json number', output: '{"number":9}' }])
appendPluginRecord(session, 'plugin:forge-session/binding', { action: 'reference', url: pullUrl(8) })
appendPluginRecord(session, 'plugin:forge-session/binding', { action: 'dismiss', url: pullUrl(9) })
const events = session.snapshotEvents()
const expected = ctx.sessionProjections.checkpoint(session)
const restore = (checkpoints: typeof rows, from: number) => ctx.sessionProjections.restore(
checkpoints, events.slice(from), SessionLogOffset(from), session.header, session.inheritedEventCount,
).checkpoint
const restore = restorer(ctx, session)
expect(restore({}, 0)).toEqual(expected)
expect(restore(rows, offset)).toEqual(expected)
const row = rows.forgeChangeRequests!
@@ -391,6 +418,24 @@ describe('forgeSession lifecycle', () => {
] })
})
it('refolds a checkpoint that predates program dispatches and matches full replay across a program suffix', async () => {
const { ctx, session } = await open()
programTurn(session, 'first', [{ command: 'gh pr create --fill', output: `${pullUrl(1)}\n` }])
const rows = ctx.sessionProjections.checkpoint(session)
const offset = session.snapshotEvents().length
programTurn(session, 'second', [{ command: 'gh pr view 2 --repo fake.test/octo/demo', output: 'title:\tChange 2' }])
const expected = ctx.sessionProjections.checkpoint(session)
const restore = restorer(ctx, session)
const row = rows.forgeChangeRequests!
expect(restore(rows, offset)).toEqual(expected)
// A row written before dispatches folded holds no binding for them; its version makes recovery refold the log.
expect(restore({ forgeChangeRequests: { ...row, ver: 3, val: { pending: [], bindings: [], pushes: [] } } }, 0)).toEqual(expected)
expect(expected.forgeChangeRequests?.val).toMatchObject({ bindings: [
{ url: pullUrl(1), origin: 'created', dismissed: false },
{ url: pullUrl(2), origin: 'referenced', dismissed: false },
] })
})
it('unregisters its projection and stops discovery when the service fiber is disposed', async () => {
const { ctx, provider, session, service } = await open()
create(session, 'create', pullUrl(1))
@@ -20,6 +20,9 @@
{
"path": "../forge"
},
{
"path": "../../llm/llm"
},
{
"path": "../../core/session"
},
@@ -43,6 +46,9 @@
},
{
"path": "../../sandbox/sandbox-policy"
},
{
"path": "../../core/tool-executor-ptc"
}
]
}
@@ -21,14 +21,14 @@
en: ca844fa88b307274
zh: da2032bfe3c1b792
/deepseek-ai-dsh-cordis-host-runner/use-this-package/client-inspection:
en: b4a2fe9e7aa9dee7
zh: 56f55558809970da
en: eb3187e43eec0872
zh: 096eef6a6d0c388b
/deepseek-ai-dsh-cordis-host-runner/use-this-package/what-a-run-does:
en: a3c86c081974a710
zh: 180e1b7824c070d4
/deepseek-ai-dsh-cordis-host-runner/use-this-package/what-happens-to-definitions:
en: d1a8777f171d22bb
zh: 7f6aa4c2680557b1
en: 29a5f9735bf562ec
zh: f762571af38fa99a
/deepseek-ai-dsh-cordis-host-runner/use-this-package/trust-stance:
en: af859a1591c02386
zh: 46d3c82713fa9055
@@ -49,6 +49,8 @@ When Gateway is mounted, a Client query with no live event stream fails before d
Client queries accept the first valid page response within `clientInspectTimeoutMs`. A failed page does not prevent another page from answering successfully. If no valid result arrives, the query rejects with the first Client failure or output-validation diagnostic; when no page answers, it asks the caller to open or reconnect the Harness page and retry. Cancellation and registry disposal also end pending queries. Reconnecting a page does not replay a missed request, so retry after the connection is restored. Host queries are unaffected by this timeout.
Query failures throw `InspectError`: `INSPECT_PROVIDER_NOT_FOUND`, `INSPECT_METHOD_NOT_FOUND`, and `INSPECT_INVALID_INPUT` reject the request before dispatch; `INSPECT_INVALID_OUTPUT` rejects a provider value; `INSPECT_CLIENT_UNAVAILABLE` reports a missing page or registry disposal; and `INSPECT_TIMEOUT` reports the Client deadline. A Host provider may throw its own `HarnessError`, such as `INSPECT_TARGET_NOT_FOUND`; any other provider failure becomes `INSPECT_FAILED` with the original error as `cause`. Cancellation rethrows the signal's reason.
### What a run does
Programmatic callers use `define`, `run`, `stop`, and `undefine`; the browser panel operates existing definitions. Host-only packages activate in this process. A package with a browser half waits for approval or cancellation, then loads Host before Client. `mode: "run"` starts the current version; `mode: "update"` replaces it. Stop disposes the live effects and retains the definition; undefine also forgets it.
@@ -57,6 +59,8 @@ Programmatic callers use `define`, `run`, `stop`, and `undefine`; the browser pa
Definitions are session-scoped and process-local: other sessions read them as absent, and restart clears them. Historical logs retain tool arguments and receipts but do not restore the registry. Reloading a browser page requires another explicit run to load its Client half.
A tool defined through `harness.defineTool` fails with `PluginToolError`: `PLUGIN_TOOL_FAILED` when `execute` throws, keeping the thrown message and any string `code` in `message`, and `PLUGIN_TOOL_INVALID_RESULT` when it returns a value that is not lossless JSON data. A thrown `HarnessError` and any failure after cancellation keep their own identity.
### Trust stance
The sandbox isolates globals but is not a security boundary: Node globals are absent or redirect to Cordis services (`ctx.fs`, `ctx.web`, `ctx.bash`, the timer helpers), and a host half receives a façade without framework internals, yet the services it declares reach the live runtime. Treat a dynamic package like bash access — see the [self-referential toolset reference](README.md).
@@ -49,6 +49,8 @@ kind: "package-reference"
Client 查询在 `clientInspectTimeoutMs` 内接受首个有效页面响应。某个页面失败不会阻止其他页面成功回答。若没有有效结果,查询返回首个 Client 错误或输出校验诊断;若没有页面回答,则提示调用方打开或重新连接 Harness 页面后重试。取消和注册表卸载也会结束待处理查询。页面重连不会重放错过的请求,因此需在连接恢复后重试。Host 查询不受此超时影响。
查询失败抛出 `InspectError`:`INSPECT_PROVIDER_NOT_FOUND`、`INSPECT_METHOD_NOT_FOUND` 与 `INSPECT_INVALID_INPUT` 在发送前拒绝请求;`INSPECT_INVALID_OUTPUT` 拒绝提供方返回值;`INSPECT_CLIENT_UNAVAILABLE` 表示没有页面或注册表已卸载;`INSPECT_TIMEOUT` 表示 Client 期限已到。Host 提供方可以抛出自己的 `HarnessError`,例如 `INSPECT_TARGET_NOT_FOUND`;其他提供方失败变为 `INSPECT_FAILED`,原始错误保留为 `cause`。取消时重新抛出信号的 reason。
### run 会做什么
程序调用方使用 `define`、`run`、`stop` 和 `undefine`;浏览器面板操作已有定义。仅含 Host 的包在本进程激活。带浏览器部分的包等待审批或取消,批准后先加载 Host 再加载 Client。`mode: "run"` 启动当前版本,`mode: "update"` 替换版本。Stop 释放运行中的 effect 并保留定义;undefine 还会移除定义。
@@ -57,6 +59,8 @@ Client 查询在 `clientInspectTimeoutMs` 内接受首个有效页面响应。
定义按会话隔离且仅在进程内存在:其他会话无法读取,重启会清空。历史日志保留工具参数和回执,但不会恢复注册表。浏览器页面重载后,需要再次显式运行才能加载 Client 部分。
通过 `harness.defineTool` 定义的工具以 `PluginToolError` 失败:`execute` 抛出时为 `PLUGIN_TOOL_FAILED`,`message` 保留抛出的消息及其字符串 `code`;返回值不是无损 JSON 数据时为 `PLUGIN_TOOL_INVALID_RESULT`。抛出的 `HarnessError` 与取消之后的任何失败保留其自身身份。
### 信任立场
沙箱隔离全局变量,但不是安全边界:Node 全局变量不存在,或重定向到 Cordis 服务(`ctx.fs`、`ctx.web`、`ctx.bash` 与定时器 helper),host 半收到的是不含框架内部机制的 façade,但它声明的服务仍会触达存活运行时。对待动态包要像对待 bash 访问一样,参见[自引用工具集 参考](README.zh.md)。
@@ -59,6 +59,7 @@
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
@@ -71,6 +72,7 @@
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
@@ -17,7 +17,9 @@ import { Context } from '@deepseek-ai/cordis'
import type { Plugin } from '@deepseek-ai/cordis'
import { scopeOf } from '@deepseek-ai/dsh-scope'
import { assertSupportedJsonSchema, defineTool } from '@deepseek-ai/dsh-tools'
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools'
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
@@ -539,12 +541,66 @@ function assertRenderedContent(value: JsonValue): ContentBlock[] {
)
}
/**
* Every {@link PluginToolError} code:
* - `PLUGIN_TOOL_FAILED`: a dynamic tool's `execute` threw or rejected with a value other than a
* `HarnessError`; `message` keeps the thrown message and any string `code` it carried, and `cause`
* is the thrown value.
* - `PLUGIN_TOOL_INVALID_RESULT`: `execute` resolved with a value that is not lossless JSON data.
*/
export const PLUGIN_TOOL_ERROR_CODES = ['PLUGIN_TOOL_FAILED', 'PLUGIN_TOOL_INVALID_RESULT'] as const
/** One {@link PluginToolError} code. */
export type PluginToolErrorCode = typeof PLUGIN_TOOL_ERROR_CODES[number]
/** Failure of a tool a dynamic plugin defined; `code` is one of {@link PLUGIN_TOOL_ERROR_CODES}. */
export class PluginToolError extends HarnessError {
override readonly code: PluginToolErrorCode
constructor(message: string, code: PluginToolErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginToolError'
this.code = code
}
}
/**
* Whether a value thrown by sandbox `execute` code is a `HarnessError` or the
* caller's cancellation. A Proxy whose traps throw is neither.
*/
function keepsIdentity(error: unknown, signal: AbortSignal): boolean {
try {
return error instanceof HarnessError
|| (signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError')))
} catch {
// A trapped prototype or `name` read identifies neither a coded failure nor a cancellation.
return false
}
}
/**
* Classify a value thrown by sandbox `execute` code. Sandbox errors come from
* another realm, so their fields are read structurally rather than through `instanceof`.
*/
function pluginToolFailure(error: unknown): PluginToolError {
const message = toolErrorMessage(error)
let code: unknown
try {
code = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined
} catch (_codeReadTrapped) {
// A trapped `code` read carries no usable code; the message alone describes the failure.
}
return new PluginToolError(typeof code === 'string' ? `${message} (code ${code})` : message, 'PLUGIN_TOOL_FAILED', { cause: error })
}
/**
* The `harness.defineTool` handed into the sandbox: the real DSL, with `parameters` normalized
* into a fresh host-realm ParameterSchemaSpec (raw object wrappers unwrapped,
* required arrays mapped, and explicit DSL object openness enforced) and the tool's `execute` return normalized into the host realm
* via a JSON round-trip. Non-JSON or wrong-shape output fails that call instead of poisoning
* the session log.
* via a JSON round-trip. Non-JSON or wrong-shape output fails that call with
* {@link PluginToolError} `PLUGIN_TOOL_INVALID_RESULT` instead of poisoning the session log, and a
* value thrown by `execute` fails it with `PLUGIN_TOOL_FAILED` unless it is a `HarnessError` or
* the caller's cancellation.
* @param options - the standard `defineTool` options; `parameters` may be the ParameterSchemaSpec DSL or a JSON-Schema-style wrapper.
* @returns the marker-tagged definition `harness.registerTool` (and the guarded `ctx.tools.register`) accepts.
*/
@@ -579,8 +635,21 @@ export function sandboxDefineTool(options: unknown): ToolDefinition {
},
} : {},
},
async execute(args: unknown, exec: unknown): Promise<JsonValue> {
return cloneJson(await rawExecute(args, exec), 'harness.defineTool execute result') as JsonValue
async execute(args: unknown, exec: ToolExecution): Promise<JsonValue> {
let result: unknown
try {
result = await rawExecute(args, exec)
} catch (error) {
// The cancellation and host services' coded failures keep their own identity.
if (keepsIdentity(error, exec.signal)) throw error
throw pluginToolFailure(error)
}
try {
return cloneJson(result, 'harness.defineTool execute result') as JsonValue
} catch (error) {
// Getters and Proxy traps on the returned value run during the clone and may throw any value.
throw new PluginToolError(toolErrorMessage(error), 'PLUGIN_TOOL_INVALID_RESULT', { cause: error })
}
},
})
const parameters = { ...tool.parameters, ...normalized.rootAnnotations }
@@ -44,8 +44,10 @@ export type {
DynamicCordisPackageInspection, DynamicCordisPlugin, DynamicCordisPluginInspection,
DynamicCordisReference, DynamicCordisRun,
} from './registry.ts'
export { CordisInspectRegistryService } from './inspect-registry.ts'
export type { HostCordisInspectProviderRegistration } from './inspect-registry.ts'
export { CordisInspectRegistryService, InspectError } from './inspect-registry.ts'
export type { HostCordisInspectProviderRegistration, InspectErrorCode } from './inspect-registry.ts'
export { PluginToolError } from './guard.ts'
export type { PluginToolErrorCode } from './guard.ts'
/**
* Brand a Host-minted Plugin ID.
@@ -3,6 +3,7 @@
import { Service } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { HarnessError } from '@deepseek-ai/dsh-error'
import type {} from '@deepseek-ai/dsh-api-gateway'
import { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
import { assertSupportedJsonSchema, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools'
@@ -13,6 +14,42 @@ import type {
CordisInspectRequestId, CordisInspectResolveAck,
} from './types.ts'
/**
* Every {@link InspectError} code:
* - `INSPECT_PROVIDER_NOT_FOUND`: no provider with the requested id is registered on the platform.
* - `INSPECT_METHOD_NOT_FOUND`: the provider declares no method with the requested name.
* - `INSPECT_TARGET_NOT_FOUND`: the query names a target, such as a Loader entry, that the provider does not have.
* - `INSPECT_INVALID_INPUT`: the input violates the method's input schema.
* - `INSPECT_INVALID_OUTPUT`: the provider returned a non-JSON value or a value outside its output schema.
* - `INSPECT_CLIENT_UNAVAILABLE`: no Harness page is connected to answer a Client query, or the registry was disposed while it waited.
* - `INSPECT_TIMEOUT`: no valid Client response arrived within the query timeout.
* - `INSPECT_FAILED`: a Host provider failed without its own error code; `cause` is the original error.
*/
export const INSPECT_ERROR_CODES = [
'INSPECT_PROVIDER_NOT_FOUND',
'INSPECT_METHOD_NOT_FOUND',
'INSPECT_TARGET_NOT_FOUND',
'INSPECT_INVALID_INPUT',
'INSPECT_INVALID_OUTPUT',
'INSPECT_CLIENT_UNAVAILABLE',
'INSPECT_TIMEOUT',
'INSPECT_FAILED',
] as const
/** One {@link InspectError} code. */
export type InspectErrorCode = typeof INSPECT_ERROR_CODES[number]
/** Typed Cordis inspect query failure; `code` is one of {@link INSPECT_ERROR_CODES}. */
export class InspectError extends HarnessError {
override readonly code: InspectErrorCode
constructor(message: string, code: InspectErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'InspectError'
this.code = code
}
}
/** Context supplied to a Host inspect query. */
export interface HostCordisInspectQueryContext {
/** Tool-call cancellation. */
@@ -115,6 +152,9 @@ export class CordisInspectRegistryService extends Service {
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query(
platform: CordisInspectPlatform,
@@ -126,11 +166,23 @@ export class CordisInspectRegistryService extends Service {
): Promise<JsonValue> {
if (platform === 'host') {
const registration = this.providers.get(providerId)
if (registration === undefined) throw new Error(`Host Cordis inspect provider "${providerId}" is not registered`)
if (registration === undefined) {
throw new InspectError(`Host Cordis inspect provider "${providerId}" is not registered`, 'INSPECT_PROVIDER_NOT_FOUND')
}
const method = findMethod(registration.manifest, methodName)
validateInput('Host', providerId, method, input)
signal.throwIfAborted()
const data = await registration.query(methodName, input, { agent, signal })
let data: JsonValue
try {
data = await registration.query(methodName, input, { agent, signal })
} catch (error) {
// The cancellation itself passes through for the tool registry to classify as ABORTED.
if (error instanceof HarnessError || isCancellation(error, signal)) throw error
throw new InspectError(
`Host Cordis inspect ${providerId}.${methodName} failed: ${error instanceof Error ? error.message : String(error)}`,
'INSPECT_FAILED', { cause: error },
)
}
signal.throwIfAborted()
return validateOutput('Host', providerId, method, data)
}
@@ -177,13 +229,18 @@ export class CordisInspectRegistryService extends Service {
signal: AbortSignal,
): Promise<JsonValue> {
const provider = this.clientManifest?.find(candidate => candidate.id === providerId)
if (provider === undefined) throw new Error(`Client Cordis inspect provider "${providerId}" is not registered`)
if (provider === undefined) {
throw new InspectError(`Client Cordis inspect provider "${providerId}" is not registered`, 'INSPECT_PROVIDER_NOT_FOUND')
}
const method = findMethod(provider, methodName)
validateInput('Client', providerId, method, input)
signal.throwIfAborted()
const gateway = this.ctx.get('typertGateway')
if (gateway !== undefined && !gateway.hasLiveClient()) {
throw new Error(`Client inspect query ${providerId}.${methodName} has no connected Harness page. Open or reconnect the Harness page, then retry.`)
throw new InspectError(
`Client inspect query ${providerId}.${methodName} has no connected Harness page. Open or reconnect the Harness page, then retry.`,
'INSPECT_CLIENT_UNAVAILABLE',
)
}
const requestId = `inspect-${this.nextRequest++}` as CordisInspectRequestId
const request: CordisInspectQueryRequest = {
@@ -232,7 +289,12 @@ export class CordisInspectRegistryService extends Service {
if (signal.aborted) onAbort()
else this.ctx.emit('cordis/inspect-query', request)
const resolution = await result
if (!resolution.ok) throw new Error(`${providerId}.${methodName}: ${resolution.message}`)
if (!resolution.ok) {
signal.throwIfAborted()
// Locally settled failures: the response deadline, or registry disposal reported as cancellation.
const code = resolution.reason === 'cancelled' ? 'INSPECT_CLIENT_UNAVAILABLE' : 'INSPECT_TIMEOUT'
throw new InspectError(`${providerId}.${methodName}: ${resolution.message}`, code)
}
return resolution.data
} finally {
clearTimeout(timer)
@@ -242,6 +304,11 @@ export class CordisInspectRegistryService extends Service {
}
}
/** Whether a rejection is the caller's cancellation rather than a failure of its own. */
function isCancellation(error: unknown, signal: AbortSignal): boolean {
return signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))
}
function view(platform: CordisInspectPlatform, manifest: CordisInspectProviderManifest): CordisInspectProviderView {
return { platform, ...manifest, methods: [...manifest.methods] }
}
@@ -264,7 +331,7 @@ function validateManifest(manifest: CordisInspectProviderManifest): CordisInspec
function findMethod(manifest: CordisInspectProviderManifest, name: string): CordisInspectMethodManifest {
const method = manifest.methods.find(candidate => candidate.name === name)
if (method === undefined) throw new Error(`Cordis inspect provider "${manifest.id}" has no method "${name}"`)
if (method === undefined) throw new InspectError(`Cordis inspect provider "${manifest.id}" has no method "${name}"`, 'INSPECT_METHOD_NOT_FOUND')
return method
}
@@ -275,7 +342,9 @@ function validateInput(
input: JsonValue | undefined,
): void {
const violations = validateJsonSchemaValue(method.inputSchema as JsonSchemaNode, input ?? {}, 'input')
if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} rejected input: ${violations.join('; ')}`)
if (violations.length > 0) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} rejected input: ${violations.join('; ')}`, 'INSPECT_INVALID_INPUT')
}
}
function validateOutput(
@@ -285,8 +354,12 @@ function validateOutput(
data: JsonValue,
): JsonValue {
const snapshot = snapshotJsonValue(data)
if (snapshot === undefined) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned a non-JSON value`)
if (snapshot === undefined) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} returned a non-JSON value`, 'INSPECT_INVALID_OUTPUT')
}
const violations = validateJsonSchemaValue(method.outputSchema as JsonSchemaNode, snapshot, 'output')
if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned invalid output: ${violations.join('; ')}`)
if (violations.length > 0) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} returned invalid output: ${violations.join('; ')}`, 'INSPECT_INVALID_OUTPUT')
}
return snapshot
}
@@ -6,7 +6,7 @@ import type { PeerId, PeerScope } from '@deepseek-ai/dsh-typert-protocol'
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import DynamicCordisRunnerService from '../src/index.ts'
import { CordisInspectRegistryService } from '../src/inspect-registry.ts'
import { CordisInspectRegistryService, InspectError } from '../src/inspect-registry.ts'
import type { CordisInspectProviderManifest, CordisInspectQueryRequest, CordisInspectRequestId } from '../src/types.ts'
import { AGENT_A, AGENT_B } from './helpers.ts'
@@ -20,7 +20,7 @@ const manifest: CordisInspectProviderManifest = {
outputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
}],
}
const timeout = 'Error: Service.listService: Client inspect query Service.listService timed out after 100ms. '
const timeout = 'InspectError: Service.listService: Client inspect query Service.listService timed out after 100ms. '
const failure = { ok: false, reason: 'provider-error', message: 'page failed' } as const
let ctx: Context
@@ -67,7 +67,11 @@ function start() {
let settled = false
const result = registry.query('client', 'Service', 'listService', { service: 'remote' }, AGENT_A, controller.signal).then(
(value) => { settled = true; return { value } },
(error: unknown) => { settled = true; return { error: String(error) } },
(error: unknown) => {
settled = true
const code = (error as { code?: unknown }).code
return { error: String(error), ...typeof code === 'string' ? { code } : {} }
},
)
results.push(result)
return { controller, result, request: requests.at(-1)!, settled: () => settled }
@@ -116,7 +120,8 @@ describe('Client inspect completion', () => {
expect(requests).toEqual([])
expect(vi.getTimerCount()).toBe(0)
expect(await query.result).toEqual({
error: 'Error: Client inspect query Service.listService has no connected Harness page. Open or reconnect the Harness page, then retry.',
error: 'InspectError: Client inspect query Service.listService has no connected Harness page. Open or reconnect the Harness page, then retry.',
code: 'INSPECT_CLIENT_UNAVAILABLE',
})
expect(registry.list()).toHaveLength(1)
})
@@ -130,7 +135,7 @@ describe('Client inspect completion', () => {
await vi.advanceTimersByTimeAsync(99)
expect(query.settled()).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
expect(answer(query)).toEqual({ accepted: false })
expect(vi.getTimerCount()).toBe(0)
})
@@ -143,7 +148,7 @@ describe('Client inspect completion', () => {
await vi.advanceTimersByTimeAsync(99)
expect(query.settled()).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: no catalogued Service named "remote"' })
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: no catalogued Service named "remote"', code: 'INSPECT_TIMEOUT' })
expect(resolved).toEqual([query.request.requestId])
expect(answer(query)).toEqual({ accepted: false })
expect(vi.getTimerCount()).toBe(0)
@@ -165,7 +170,7 @@ describe('Client inspect completion', () => {
registry.resolveClientQuery(AGENT_A, query.request.requestId, failure)
registry.resolveClientQuery(AGENT_A, query.request.requestId, { ...failure, message: 'second failure' })
await vi.advanceTimersByTimeAsync(100)
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: page failed' })
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: page failed', code: 'INSPECT_TIMEOUT' })
})
it('retains output validation errors for timeout diagnostics', async () => {
@@ -187,7 +192,7 @@ describe('Client inspect completion', () => {
const query = start()
expect(registry.resolveClientQuery(AGENT_B, query.request.requestId, failure)).toEqual({ accepted: false })
await vi.advanceTimersByTimeAsync(100)
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
})
it('ends unanswered requests and accepts a fresh retry after manifest publication', async () => {
@@ -195,7 +200,7 @@ describe('Client inspect completion', () => {
registry.syncClientManifest([manifest])
expect(requests).toHaveLength(1)
await vi.advanceTimersByTimeAsync(100)
expect(await first.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await first.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
const retry = start()
expect(retry.request.requestId).not.toBe(first.request.requestId)
expect(answer(first)).toEqual({ accepted: false })
@@ -208,7 +213,7 @@ describe('Client inspect completion', () => {
const query = start()
const remove = vi.spyOn(query.controller.signal, 'removeEventListener')
query.controller.abort()
expect(await query.result).toEqual({ error: 'Error: Service.listService: Client inspect query Service.listService was cancelled' })
expect(await query.result).toEqual({ error: 'AbortError: This operation was aborted' })
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function))
expect(vi.getTimerCount()).toBe(0)
expect(answer(query)).toEqual({ accepted: false })
@@ -229,7 +234,7 @@ describe('Client inspect completion', () => {
const second = start()
await fiber.dispose()
for (const query of [first, second]) {
expect(await query.result).toEqual({ error: 'Error: Service.listService: Client inspect registry was disposed' })
expect(await query.result).toEqual({ error: 'InspectError: Service.listService: Client inspect registry was disposed', code: 'INSPECT_CLIENT_UNAVAILABLE' })
expect(answer(query)).toEqual({ accepted: false })
}
expect(resolved).toEqual([first.request.requestId, second.request.requestId])
@@ -262,6 +267,53 @@ describe('Client inspect completion', () => {
})
})
describe('Inspect query failure codes', () => {
const signal = new AbortController().signal
const host = (provider: string, method: string, input: unknown = {}) =>
registry.query('host', provider, method, input as never, AGENT_A, signal)
it('classifies unknown names, schema violations, and Host provider failures', async () => {
let result: unknown = {}
const providerFailure = new Error('provider exploded')
disposers.push(registry.register({ manifest, query: async () => {
if (result === providerFailure) throw providerFailure
return result as never
} }))
await expect(host('Missing', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_PROVIDER_NOT_FOUND' })
await expect(registry.query('client', 'Missing', 'listService', {}, AGENT_A, signal))
.rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_PROVIDER_NOT_FOUND' })
await expect(host('Service', 'missing')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' })
await expect(host('Service', 'listService', { extra: true })).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_INPUT' })
await expect(host('Service', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_OUTPUT' })
result = undefined
await expect(host('Service', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_OUTPUT' })
result = providerFailure
await expect(host('Service', 'listService')).rejects.toMatchObject({
name: 'InspectError', code: 'INSPECT_FAILED', message: 'Host Cordis inspect Service.listService failed: provider exploded', cause: providerFailure,
})
})
it('keeps a Host provider HarnessError and its cancellation, and still classifies a distinct late failure', async () => {
const coded = new InspectError('unknown entry id "x"', 'INSPECT_TARGET_NOT_FOUND')
const reason = new Error('caller cancelled')
const late = new Error('cleanup failed')
let controller = new AbortController()
let thrown: unknown = coded
disposers.push(registry.register({ manifest, query: async () => {
if (thrown !== coded) controller.abort(reason)
throw thrown
} }))
await expect(host('Service', 'listService')).rejects.toBe(coded)
thrown = reason
await expect(registry.query('host', 'Service', 'listService', {}, AGENT_A, controller.signal)).rejects.toBe(reason)
controller = new AbortController()
thrown = late
await expect(registry.query('host', 'Service', 'listService', {}, AGENT_A, controller.signal)).rejects.toMatchObject({
name: 'InspectError', code: 'INSPECT_FAILED', cause: late,
})
})
})
describe('Client inspect timeout configuration', () => {
it('defaults to ten seconds and accepts both timer limits', () => {
expect(DynamicCordisRunnerService.Config({}).clientInspectTimeoutMs).toBe(10_000)
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import { HarnessError } from '@deepseek-ai/dsh-error'
import { sandboxDefineTool } from '../src/guard.ts'
import { syntaxErrorContext } from '../src/sandbox.ts'
import { AGENT_A, call, CONTENT_OUTPUT_CODE, mount, setup, text, running } from './helpers.ts'
@@ -41,6 +42,59 @@ describe('dynamic tool declaration boundary', () => {
})
})
describe('dynamic tool execution failures', () => {
const tool = (execute: () => Promise<unknown>) => sandboxDefineTool({
name: 'failing', description: 'failing tool', parameters: {},
output: { schema: { type: 'json' }, render: () => [] },
execute,
})
const run = (execute: () => Promise<unknown>, signal = new AbortController().signal) =>
tool(execute).execute({}, { signal } as never)
it('classifies thrown values and non-JSON results as PluginToolError', async () => {
const thrown = Object.assign(new Error('quota exhausted'), { code: 'QUOTA' })
await expect(run(() => Promise.reject(thrown))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'quota exhausted (code QUOTA)', cause: thrown,
})
// Sandbox code may reject with any value, not only an Error.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject('bare failure'))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'bare failure',
})
const trapped = new Proxy({}, { get: (_target, key) => { if (key === 'code') throw new Error('trap'); return undefined } })
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject(trapped))).rejects.toMatchObject({ name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED' })
await expect(run(() => Promise.resolve(new Map()))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_INVALID_RESULT',
})
})
it('keeps a HarnessError and a failure after cancellation unchanged', async () => {
const coded = new HarnessError('service failed', 'SERVICE_FAILED')
await expect(run(() => Promise.reject(coded))).rejects.toBe(coded)
const controller = new AbortController()
const reason = new Error('cancelled')
controller.abort(reason)
await expect(run(() => Promise.reject(reason), controller.signal)).rejects.toBe(reason)
await expect(run(() => Promise.reject(new Error('cleanup failed')), controller.signal)).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'cleanup failed',
})
})
it('classifies hostile thrown values and results that throw during the clone', async () => {
const revocable = Proxy.revocable({}, {})
revocable.revoke()
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject(revocable.proxy))).rejects.toMatchObject({ name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED' })
for (const thrown of ['getter failed', null]) {
const value = { get broken(): never { throw thrown } }
await expect(run(() => Promise.resolve(value))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_INVALID_RESULT', message: String(thrown),
})
}
})
})
describe('sandbox isolation and Node-API traps', () => {
it('isolates sandbox globals: no process/Buffer, and globalThis writes do not leak to the host', async () => {
const harness = await setup()
@@ -41,6 +41,9 @@
{
"path": "../../llm/llm"
},
{
"path": "../../util/error"
},
{
"path": "../../typert/protocol"
}
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 3a2f21ff0dc3420d
/deepseek-ai-dsh-tool-cordis/use-this-package:
en: e8c90b0ad037513c
zh: 563454508c30d9b0
en: 5a6ab053010461c6
zh: 4d04f2ff1abb5ffd
/deepseek-ai-dsh-tool-cordis/understand-the-implementation:
en: ff959016d633c6c0
zh: d84dfa7e9d73532f
+1 -1
View File
@@ -25,7 +25,7 @@ Inspect Host and Client runtime APIs before writing plugin code. Creator mode pr
<a id="use-this-package"></a>
## Use this package
Creator mode includes this toolset. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tools; a preset row alone registers no Host providers. Call `cordis_inspect_list` to discover providers, then `cordis_inspect_query` for a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
Creator mode includes this toolset. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tools; a preset row alone registers no Host providers. Call `cordis_inspect_list` to discover providers, then `cordis_inspect_query` for a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
-----
+1 -1
View File
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
创造模式包含这组工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这些工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect_list` 发现 provider,再用 `cordis_inspect_query` 查询其具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
创造模式包含这组工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这些工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect_list` 发现 provider,再用 `cordis_inspect_query` 查询其具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
-----
@@ -1646,7 +1646,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
{
key: 'forgeSession',
summary: 'Session-scoped change request bindings.',
description: 'Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.',
description: 'Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.',
methods: [
{
signature: 'changeRequests(session: Session): SessionChangeRequest[]',
@@ -2509,12 +2509,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
description: 'Read current plugins, including why a row cannot be changed through the profile patch.',
parameters: [],
returns: 'Current runtime entries with persistent patch targets.',
throws: ['{PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches cannot be read; Remote callers receive `gateway/internal`.'],
},
{
signature: '@Remote listBundles(): Promise<BundleInfo[]>',
description: 'Read installed, installation-provided, and offline Official catalog bundles, plus selected non-bundle names. A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.',
parameters: [],
returns: 'Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional display metadata, activation selections, whether the installation offers the bundle, and removal availability.',
throws: ['{PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or installation manifest cannot be read; Remote callers receive `gateway/internal`.'],
},
{
signature: '@Remote async registries(): Promise<PluginRegistries>',
@@ -2712,7 +2714,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
{
key: 'ptcRuntime',
summary: 'Registers one `ctx.ptcRuntime` implementation.',
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
methods: [
{
signature: 'abstract readonly language: string',
@@ -2743,7 +2745,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
description: 'Resolve supported options and provider defaults before execution.',
parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }],
returns: 'Complete directory, deadline and supported authority for run.',
throws: ['When an explicit choice is invalid or unsupported by this provider.'],
throws: ['When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.'],
},
{
signature: 'abstract run(spec: PtcRunSpec): Promise<PtcRunResult>',
+12 -6
View File
@@ -5,6 +5,8 @@ import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
// Declares `Context.pluginPackages`, the profile package lookup that resolves an entry's package directory.
import { createConfigProjector, isNativeConfigSchema, LOADER_EXPRESSION_SCHEMA, type NativeConfigSchema } from '@deepseek-ai/dsh-app-boot'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { InspectError } from '@deepseek-ai/dsh-cordis-host-runner'
import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
/**
* `schema`: the running plugin declares a native Schemastery Config. `absent`: it runs without one.
@@ -57,14 +59,14 @@ function parseQuery(input: JsonValue | undefined): ConfigQuery {
const text = (key: string): string | undefined => {
const value = fields[key]
if (value === undefined) return undefined
if (typeof value !== 'string' || value === '') throw new Error(`${key} must be a non-empty string`)
if (typeof value !== 'string' || value === '') throw new ToolArgsError([`${key} must be a non-empty string`])
return value
}
const offset = fields.offset ?? 0
const limit = fields.limit ?? DEFAULT_LIMIT
if (!Number.isInteger(offset) || typeof offset !== 'number' || offset < 0) throw new Error('offset must be a non-negative integer')
if (!Number.isInteger(offset) || typeof offset !== 'number' || offset < 0) throw new ToolArgsError(['offset must be a non-negative integer'])
if (!Number.isInteger(limit) || typeof limit !== 'number' || limit < 1 || limit > MAX_LIMIT) {
throw new Error(`limit must be an integer from 1 to ${MAX_LIMIT}`)
throw new ToolArgsError([`limit must be an integer from 1 to ${MAX_LIMIT}`])
}
return { entry: text('entry'), name: text('name'), offset, limit }
}
@@ -93,11 +95,15 @@ function toJson(value: object): JsonValue {
* @param ctx - Host context; its `loader`, when the profile was mounted by one, owns the entry tree.
* @param input - model-supplied query: `entry` (Loader entry id), or `name`, `offset` (default 0), and `limit` (1 to 100, default 25).
* @returns one directory page, or one entry's status and projected schema.
* @throws when no Loader mounted this Host, when a query field is malformed, or when the entry id matches no live entry.
* @throws {ToolContextUnavailableError} when no Loader mounted this Host.
* @throws {ToolArgsError} when a query field is malformed.
* @throws {InspectError} `INSPECT_TARGET_NOT_FOUND` when the entry id matches no live entry.
*/
export async function queryLiveConfig(ctx: Context, input: JsonValue | undefined): Promise<JsonValue> {
const loader = ctx.get('loader')
if (loader === undefined) throw new Error('Config inspection requires the Loader that mounted this profile; this Host was composed without one')
if (loader === undefined) {
throw new ToolContextUnavailableError('Config inspection requires the Loader that mounted this profile; this Host was composed without one')
}
const query = parseQuery(input)
const entries = [...loader.entries()].map(liveConfig)
if (query.entry === undefined) {
@@ -107,7 +113,7 @@ export async function queryLiveConfig(ctx: Context, input: JsonValue | undefined
return { entries: page, total: matching.length, nextOffset: end < matching.length ? end : null }
}
const entry = entries.find(candidate => candidate.id === query.entry)
if (entry === undefined) throw new Error(`unknown entry id ${JSON.stringify(query.entry)}`)
if (entry === undefined) throw new InspectError(`unknown entry id ${JSON.stringify(query.entry)}`, 'INSPECT_TARGET_NOT_FOUND')
const listed = { ...listing(entry), ...packageDir(ctx, loader.resolve(query.entry)) }
if (entry.native === undefined) return listed
const project = await createConfigProjector()
+2 -2
View File
@@ -2,7 +2,7 @@
import type { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
import { presentInspectListCall, presentInspectQueryCall } from './present.ts'
@@ -10,7 +10,7 @@ export const name = 'tool-cordis'
export const inject = ['tools', 'cordisInspect']
function requireAgent(exec: ToolExecution): Agent {
if (exec.agent === undefined) throw new Error('Cordis inspection requires an Agent-backed session')
if (exec.agent === undefined) throw new ToolContextUnavailableError('Cordis inspection requires an Agent-backed session')
return exec.agent
}
@@ -1,7 +1,7 @@
/** First-party Host inspect providers registered by the Cordis tool package. */
import type { Context } from '@deepseek-ai/cordis'
import type { HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner'
import { InspectError, type HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { EVENT_API, queryEventApi, queryServiceApi } from './api-catalog.ts'
import { queryLiveConfig } from './config.ts'
@@ -74,7 +74,7 @@ export function hostInspectProviders(ctx: Context): HostCordisInspectProviderReg
}],
},
query(method, _input, context) {
if (method !== 'listTools') throw new Error(`unknown Tool inspect method "${method}"`)
if (method !== 'listTools') throw new InspectError(`unknown Tool inspect method "${method}"`, 'INSPECT_METHOD_NOT_FOUND')
return Promise.resolve({ tools: ctx.tools.schemas(context.agent) } as unknown as JsonValue)
},
},
@@ -101,7 +101,7 @@ function registration(
}],
},
async query(requested, input) {
if (requested !== method) throw new Error(`unknown ${id} inspect method "${requested}"`)
if (requested !== method) throw new InspectError(`unknown ${id} inspect method "${requested}"`, 'INSPECT_METHOD_NOT_FOUND')
return await query(input)
},
}
@@ -89,6 +89,9 @@ describe('the Config inspect provider', () => {
await expect(queryLiveConfig(ctx, { limit: 0 })).rejects.toThrow('limit must be an integer from 1 to 100')
await expect(queryLiveConfig(ctx, { offset: -1 })).rejects.toThrow('offset must be a non-negative integer')
await expect(queryLiveConfig(ctx, { name: '' })).rejects.toThrow('name must be a non-empty string')
for (const input of [{ limit: 0 }, { offset: -1 }, { name: '' }]) {
await expect(queryLiveConfig(ctx, input)).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
}
await ctx.fiber.dispose()
})
@@ -119,10 +122,14 @@ describe('the Config inspect provider', () => {
expect(await queryLiveConfig(ctx, { entry: ids.noConfig })).not.toHaveProperty('packageDir')
expect(await queryLiveConfig(ctx, { entry: ids.group })).toEqual({ id: ids.group, patchId: ids.group, name: 'cordis:group', status: 'tree' })
await expect(queryLiveConfig(ctx, { entry: 'missing' })).rejects.toThrow('unknown entry id "missing"')
await expect(queryLiveConfig(ctx, { entry: 'missing' })).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_TARGET_NOT_FOUND' })
await ctx.fiber.dispose()
})
it('rejects a Host composed without a Loader', async () => {
await expect(queryLiveConfig(new Context(), undefined)).rejects.toThrow('requires the Loader')
await expect(queryLiveConfig(new Context(), undefined)).rejects.toMatchObject({
name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE',
})
})
})
@@ -6,6 +6,7 @@ import ToolRegistry from '@deepseek-ai/dsh-tools'
import { describe, expect, it } from 'vitest'
import * as CordisInspectProviders from '../src/host.ts'
import * as CordisInspectTools from '../src/index.ts'
import { hostInspectProviders } from '../src/providers.ts'
/**
* The Host inspect providers are one process-global set: the host entry
@@ -35,6 +36,22 @@ describe('the cordis-inspect-providers host entry', () => {
await fiber.dispose()
expect(ctx.cordisInspect.list()).toEqual([])
})
it('reports a missing Agent and an undeclared provider method with error codes', async () => {
const ctx = await host()
await ctx.plugin(CordisInspectProviders)
await ctx.plugin(CordisInspectTools)
const signal = new AbortController().signal
const query = ctx.tools.get('cordis_inspect_query')
await expect(query?.execute({ platform: 'host', provider: 'Tool', method: 'listTools' }, { signal } as never)).rejects.toMatchObject({
name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE', message: 'Cordis inspection requires an Agent-backed session',
})
for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Tool'].includes(candidate.manifest.id))) {
await expect(Promise.resolve().then(() => provider.query('undeclared', undefined, { agent: undefined as never, signal })))
.rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' })
}
await ctx.fiber.dispose()
})
})
describe('the cordis inspect tools', () => {
+4 -4
View File
@@ -30,8 +30,8 @@
en: 213d2d67088beccc
zh: 1e3ff5454c937f11
/deepseek-ai-dsh-mcp-client/use-this-package/runtime-templates-and-credentials:
en: 255e8f48e5981b52
zh: 7b4ad77794c6b7fc
en: fd04dfbe231924e4
zh: ace0b0786bf16d0f
/deepseek-ai-dsh-mcp-client/understand-the-implementation:
en: d33ddd080880b3f5
zh: 64328f5239c26752
@@ -45,8 +45,8 @@
en: 1793a89464c70cec
zh: fcf7b9c2eb343ce3
/deepseek-ai-dsh-mcp-client/understand-the-implementation/tool-execution-internals:
en: bb161208cc002746
zh: 3ab0588ca71effe5
en: c0abd2f870cfeb65
zh: 15b7ba2564dace9a
/deepseek-ai-dsh-mcp-client/understand-the-implementation/environment-scrubbing-stdio:
en: fef482a6f8cc789f
zh: 08f4c594ec83b4a1
+2 -2
View File
@@ -102,7 +102,7 @@ With `expandTemplates: true`, `command`, `args`, `env` values, `cwd`, `url`, and
Credential notifications rebuild the connection only when the resolved values change; same-value notifications preserve the connection and its reconnect budget. The old connection must close and finish local cleanup before a replacement starts. Incomplete cleanup blocks replacement until the Host restarts.
With template expansion enabled, failure diagnostics, tool-call failures, and MCP `isError` tool-result text keep upstream messages but replace every value the instance resolved, including earlier rotations and URL-encoded forms, with `[redacted]`. Successful tool results retain their content.
With template expansion enabled, failure diagnostics, tool-call failures, and MCP `isError` tool-result text keep upstream messages but replace every value the instance resolved, including earlier rotations and URL-encoded forms, with `[redacted]`; the failure keeps its `name` and `code`. Successful tool results retain their content.
-----
@@ -154,7 +154,7 @@ With `expandTemplates` enabled, failure diagnostics name the operation and keep
### Tool execution internals
A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation, advertised output-schema validation, and modern request headers. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws before image persistence. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. For a server that does not advertise `resources`, resource and template lists return empty pages without calling the SDK, whose fallback writes a diagnostic to stdout, where the ACP profile carries JSON-RPC.
A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation and modern request headers. The bridge checks structured content against the advertised output schema itself, with the SDK's Node Ajv validator, because the SDK reports its own check as a `ProtocolError` that cannot be told apart from a server's JSON-RPC error. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws `McpToolError` with `MCP_TOOL_ERROR` before image persistence. Other tool and resource request failures throw `McpToolError`: after `MCP_CONNECTION_CLOSED` or `MCP_TIMEOUT` the request's outcome is unknown, `MCP_SERVER_UNAVAILABLE` means the request was not sent, `MCP_INVALID_RESULT` rejects a result that violates the MCP result schema or the advertised output schema, or an output schema that cannot be compiled, `MCP_UNSUPPORTED_TASK_EXECUTION` rejects the tool, and `MCP_REQUEST_FAILED` carries the JSON-RPC or SDK code in its message. Closure of the connection generation surfaces as `McpLocalError` with `MCP_CONNECTION_CLOSED`, and caller cancellation as the tool registry's `ABORTED`. `McpLocalError` codes also report local connection failures: `MCP_TIMEOUT`, `MCP_CREDENTIALS_UNAVAILABLE`, `MCP_CREDENTIAL_NOT_FOUND`, `MCP_INSTRUCTIONS_TOO_LARGE`, and `MCP_TOOL_REGISTRATION_FAILED`. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. For a server that does not advertise `resources`, resource and template lists return empty pages without calling the SDK, whose fallback writes a diagnostic to stdout, where the ACP profile carries JSON-RPC.
### Environment scrubbing (stdio)
+2 -2
View File
@@ -102,7 +102,7 @@ kind: "package-reference"
凭据通知只有在解析值变化时才重建连接;值相同的通知保留连接及其重连预算。替代连接启动前,旧连接必须关闭并完成本地清理。清理未完成会阻止替换,直到宿主重启。
启用模板展开时,失败诊断、工具调用失败与 MCP `isError` 工具结果文本保留上游消息,但会把本实例解析过的每个值(包括此前轮换的值及其 URL 编码形式)替换为 `[redacted]`。成功工具结果保留原始内容。
启用模板展开时,失败诊断、工具调用失败与 MCP `isError` 工具结果文本保留上游消息,但会把本实例解析过的每个值(包括此前轮换的值及其 URL 编码形式)替换为 `[redacted]`,失败的 `name` 与 `code` 保持不变。成功工具结果保留原始内容。
-----
@@ -154,7 +154,7 @@ SDK 通过旧版通知或现代协议订阅接收工具列表变化。监督器
### 工具执行内部细节
工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验、已声明输出 schema 的校验和现代协议请求 header。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。对未声明 `resources` 能力的服务器,资源列表与模板列表直接返回空页而不调用 SDK,因为 SDK 的兜底逻辑会把诊断写到 stdout,而 ACP 配置档在 stdout 上传输 JSON-RPC。
工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验和现代协议请求 header。结构化内容是否符合已声明的输出 schema 由桥接器自己用 SDK 在 Node 上的 Ajv 校验器检查,因为 SDK 把自己的检查结果报告为 `ProtocolError`,与服务端的 JSON-RPC 错误无法区分。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出带 `MCP_TOOL_ERROR` 的 `McpToolError`。其他工具与资源请求失败抛出 `McpToolError`:`MCP_CONNECTION_CLOSED` 或 `MCP_TIMEOUT` 之后请求结果未知,`MCP_SERVER_UNAVAILABLE` 表示请求未发送,`MCP_INVALID_RESULT` 拒绝违反 MCP 结果 schema 或已声明输出 schema 的结果,以及无法编译的输出 schema,`MCP_UNSUPPORTED_TASK_EXECUTION` 拒绝该工具,`MCP_REQUEST_FAILED` 在 message 中携带 JSON-RPC 或 SDK code。连接代关闭表现为带 `MCP_CONNECTION_CLOSED` 的 `McpLocalError`,调用方取消表现为工具注册表的 `ABORTED`。`McpLocalError` 的 code 也报告本地连接失败:`MCP_TIMEOUT`、`MCP_CREDENTIALS_UNAVAILABLE`、`MCP_CREDENTIAL_NOT_FOUND`、`MCP_INSTRUCTIONS_TOO_LARGE` 与 `MCP_TOOL_REGISTRATION_FAILED`。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。对未声明 `resources` 能力的服务器,资源列表与模板列表直接返回空页而不调用 SDK,因为 SDK 的兜底逻辑会把诊断写到 stdout,而 ACP 配置档在 stdout 上传输 JSON-RPC。
### 环境清洗(stdio)
+2
View File
@@ -39,6 +39,7 @@
"peerDependencies": {
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
@@ -58,6 +59,7 @@
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-attachment-local": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
+5 -5
View File
@@ -21,7 +21,7 @@ import { assertNever, deepEqualJson, type JsonValue } from '@deepseek-ai/dsh-uti
import type { ServerContext } from './server-context.ts'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import { withDeadline } from './deadline.ts'
import { McpLocalError } from './diagnostic.ts'
import { McpLocalError, mcpRequestError, McpToolError } from './diagnostic.ts'
import type { McpStatusCell } from './status.ts'
import type { McpCloseResult } from './types.ts'
import { McpGeneration } from './generation.ts'
@@ -316,7 +316,7 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
const text = client.getInstructions()?.trimEnd() ?? ''
const instructions = text ? `### MCP server: ${config.serverName}\n\n${text}` : ''
const maxInstructionBytes = config.maxInstructionBytes ?? DEFAULT_MAX_INSTRUCTION_BYTES
if (Buffer.byteLength(instructions) > maxInstructionBytes) throw new McpLocalError(`${label}: server instructions exceed maxInstructionBytes (${maxInstructionBytes})`)
if (Buffer.byteLength(instructions) > maxInstructionBytes) throw new McpLocalError(`${label}: server instructions exceed maxInstructionBytes (${maxInstructionBytes})`, 'MCP_INSTRUCTIONS_TOO_LARGE')
const sync = enqueueSync(record)
const budget = remaining()
await (budget === undefined ? sync : withDeadline(sync, budget, `${label}: startup timed out`))
@@ -351,7 +351,7 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
resources: {
async request(request, exec): Promise<JsonValue> {
const record = current
if (record?.connectedAt === undefined) throw new Error(`${label}: server is disconnected`)
if (record?.connectedAt === undefined) throw new McpToolError(`${label}: server is disconnected`, 'MCP_SERVER_UNAVAILABLE')
try {
return await record.wire.run(async (signal) => {
const options = { signal: AbortSignal.any([signal, exec.signal]), timeout: config.toolCallTimeoutMs }
@@ -378,8 +378,8 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
}
})
} catch (error) {
if (config.expandTemplates) throw new Error(diagnostic(error, request.method))
throw error
exec.signal.throwIfAborted()
throw mcpRequestError(error, request.method, config.expandTemplates ? text => binding.redact(text) : undefined)
}
},
},
+2 -2
View File
@@ -21,7 +21,7 @@ export class McpTemplateBinding {
if (config.expandTemplates) {
for (const value of strings) assertTemplateSyntax(value, `mcp-client(${config.serverName})`)
if (this.refs.size > 0 && ctx.get('credentials') === undefined) {
throw new McpLocalError('MCP credential templates require a credentials provider')
throw new McpLocalError('MCP credential templates require a credentials provider', 'MCP_CREDENTIALS_UNAVAILABLE')
}
}
}
@@ -60,7 +60,7 @@ export class McpTemplateBinding {
let value = values.get(ref)
if (value === undefined) {
const provider = this.ctx.get('credentials')
if (provider === undefined) throw new McpLocalError('MCP credential templates require a credentials provider')
if (provider === undefined) throw new McpLocalError('MCP credential templates require a credentials provider', 'MCP_CREDENTIALS_UNAVAILABLE')
value = provider.resolve(ref as CredentialRef).then((result) => {
if (result !== undefined && result.value !== '') this.secrets.add(result.value).add(encodeURIComponent(result.value))
return result?.value
+3 -3
View File
@@ -3,8 +3,8 @@
import { McpLocalError } from './diagnostic.ts'
/**
* Settle with `promise`, or reject with `timeoutMessage` once `remainingMs`
* elapses first. The timer never holds the process open, and a non-Error
* Settle with `promise`, or reject with an `MCP_TIMEOUT` {@link McpLocalError}
* carrying `timeoutMessage` once `remainingMs` elapses first. The timer never holds the process open, and a non-Error
* rejection is wrapped so callers always observe an Error.
* @param promise - operation the deadline bounds.
* @param remainingMs - remaining budget in milliseconds (clamped to at least 1).
@@ -14,7 +14,7 @@ import { McpLocalError } from './diagnostic.ts'
export function withDeadline<T>(promise: Promise<T>, remainingMs: number, timeoutMessage: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new McpLocalError(timeoutMessage))
reject(new McpLocalError(timeoutMessage, 'MCP_TIMEOUT'))
}, Math.max(1, remainingMs))
timer.unref()
promise.then(
+114 -2
View File
@@ -3,8 +3,120 @@
* secrets replace every known secret value before text leaves the instance.
*/
/** Local failure whose message contains no expanded configuration or upstream text. */
export class McpLocalError extends Error {}
import { ProtocolError, SdkError, SdkErrorCode } from '@modelcontextprotocol/client'
import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every {@link McpLocalError} code:
* - `MCP_CONNECTION_CLOSED`: the connection generation closed; outcomes of requests in flight are unknown.
* - `MCP_TIMEOUT`: a startup, operation, or cleanup budget elapsed.
* - `MCP_CREDENTIALS_UNAVAILABLE`: credential templates are configured but no credentials provider is mounted.
* - `MCP_CREDENTIAL_NOT_FOUND`: a referenced credential has no configured value.
* - `MCP_INSTRUCTIONS_TOO_LARGE`: server instructions exceed `maxInstructionBytes`.
* - `MCP_TOOL_REGISTRATION_FAILED`: a foreign registration occupies the server's tool namespace.
*/
export const MCP_LOCAL_ERROR_CODES = [
'MCP_CONNECTION_CLOSED',
'MCP_TIMEOUT',
'MCP_CREDENTIALS_UNAVAILABLE',
'MCP_CREDENTIAL_NOT_FOUND',
'MCP_INSTRUCTIONS_TOO_LARGE',
'MCP_TOOL_REGISTRATION_FAILED',
] as const
/** One {@link McpLocalError} code. */
export type McpLocalErrorCode = typeof MCP_LOCAL_ERROR_CODES[number]
/**
* Local failure whose message contains no expanded configuration or upstream
* text; `code` is one of {@link MCP_LOCAL_ERROR_CODES}.
*/
export class McpLocalError extends HarnessError {
override readonly code: McpLocalErrorCode
constructor(message: string, code: McpLocalErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'McpLocalError'
this.code = code
}
}
/**
* Every {@link McpToolError} code:
* - `MCP_TOOL_ERROR`: the server answered the tool call with an `isError` result; the model may adjust its input.
* - `MCP_UNSUPPORTED_TASK_EXECUTION`: the tool requires task-based execution, which the bridge does not support.
* - `MCP_INVALID_RESULT`: the server's result violates the MCP result schema or the tool's advertised output
* schema, or that output schema cannot be compiled.
* - `MCP_CONNECTION_CLOSED`: the connection closed while the request was in flight; its outcome is unknown.
* - `MCP_TIMEOUT`: the request exceeded its deadline; its outcome is unknown.
* - `MCP_SERVER_UNAVAILABLE`: the server was not connected, so the request was not sent.
* - `MCP_REQUEST_FAILED`: any other protocol or SDK failure; `message` carries the JSON-RPC or SDK code.
*/
export const MCP_TOOL_ERROR_CODES = [
'MCP_TOOL_ERROR',
'MCP_UNSUPPORTED_TASK_EXECUTION',
'MCP_INVALID_RESULT',
'MCP_CONNECTION_CLOSED',
'MCP_TIMEOUT',
'MCP_SERVER_UNAVAILABLE',
'MCP_REQUEST_FAILED',
] as const
/** One {@link McpToolError} code. */
export type McpToolErrorCode = typeof MCP_TOOL_ERROR_CODES[number]
/**
* Failure of one MCP tool or resource request; `code` is one of
* {@link MCP_TOOL_ERROR_CODES}. `message` may contain upstream text, redacted
* when the instance resolves credential templates.
*/
export class McpToolError extends HarnessError {
override readonly code: McpToolErrorCode
constructor(message: string, code: McpToolErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'McpToolError'
this.code = code
}
}
/** Codes for SDK-local failures whose consumer action differs from a generic request failure. */
const SDK_ERROR_CODES: Partial<Record<SdkErrorCode, McpToolErrorCode>> = {
[SdkErrorCode.ConnectionClosed]: 'MCP_CONNECTION_CLOSED',
[SdkErrorCode.RequestTimeout]: 'MCP_TIMEOUT',
[SdkErrorCode.NotConnected]: 'MCP_SERVER_UNAVAILABLE',
[SdkErrorCode.InvalidResult]: 'MCP_INVALID_RESULT',
}
/**
* Classify one failed MCP request. An {@link McpLocalError}, such as the
* generation's closure reason, keeps its identity; any other failure becomes
* an {@link McpToolError} whose `message` carries the JSON-RPC or SDK code.
* Without `redact` the original failure is the `cause`; with `redact` no
* `cause` is attached, because the original text may contain secret values.
* @param error - the request's rejection.
* @param operation - names the request, such as `tool "echo"` or `resources/read`.
* @param redact - removes secret values from the message when templates are enabled.
* @returns the classified failure to throw.
*/
export function mcpRequestError(
error: unknown,
operation: string,
redact?: (text: string) => string,
): HarnessError {
if (error instanceof McpLocalError) return error
let code: McpToolErrorCode = 'MCP_REQUEST_FAILED'
let detail = describeError(error)
if (ProtocolError.isInstance(error)) detail = `JSON-RPC error ${error.code}: ${error.message}`
else if (SdkError.isInstance(error)) {
code = SDK_ERROR_CODES[error.code] ?? code
detail = `${error.code}: ${error.message}`
}
const message = `MCP ${operation} failed: ${detail}`
return redact === undefined
? new McpToolError(message, code, { cause: error })
: new McpToolError(redact(message), code)
}
/** Placeholder written in place of a known secret value. */
const REDACTED = '[redacted]'
+2 -2
View File
@@ -57,7 +57,7 @@ export class McpGeneration {
/** Reject when this generation was cancelled or its transport reported closure. */
assertOpen(): void {
this.lifetime.signal.throwIfAborted()
if (this.closeObserved) throw new McpLocalError('MCP transport closed')
if (this.closeObserved) throw new McpLocalError('MCP transport closed', 'MCP_CONNECTION_CLOSED')
}
/**
@@ -92,7 +92,7 @@ export class McpGeneration {
}
private async finish(): Promise<McpCloseResult> {
this.lifetime.abort(new McpLocalError('MCP connection closed'))
this.lifetime.abort(new McpLocalError('MCP connection closed', 'MCP_CONNECTION_CLOSED'))
let cleanupError: string | undefined
const work = async (): Promise<void> => {
try {
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more