diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml index 5f8577a2b1..ef48218d09 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md index 3c767fde01..cec7b0e81b 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md index caa153fe79..e422428a20 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md @@ -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 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 389d5a5d8c..98a8ceed8e 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -470,11 +470,11 @@ 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, and diff output limit. * @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; hasTouch?: boolean; missingSandbox?: boolean; maxDiffBytes?: number } = {}): Promise { const { desktop } = options const resources: { scaffold?: WebScaffold; browser?: Browser } = {} @@ -500,9 +500,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' }, @@ -535,7 +539,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) @@ -574,6 +578,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 } } @@ -691,16 +700,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 { const header = page.locator('[data-forge-header]') await expect.poll(() => header.getAttribute('aria-label'), { timeout: 20_000 }).toBe('本会话的变更请求需要处理') await header.click() @@ -721,6 +726,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 () => { diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index a84fb124a9..d153e4f634 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -1892,7 +1892,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 /** diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 6ef0264108..707adff7b9 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -1894,7 +1894,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 /** diff --git a/packages/experimental/forge-session/README.i18n.yaml b/packages/experimental/forge-session/README.i18n.yaml index 6118085d8d..8e6c53e7b4 100644 --- a/packages/experimental/forge-session/README.i18n.yaml +++ b/packages/experimental/forge-session/README.i18n.yaml @@ -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 diff --git a/packages/experimental/forge-session/README.md b/packages/experimental/forge-session/README.md index 4da9c19859..be4e4a09b6 100644 --- a/packages/experimental/forge-session/README.md +++ b/packages/experimental/forge-session/README.md @@ -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/` URL in its text output. A command containing `gh pr view`, `gh pr edit`, or `gh pr checkout` binds, as `referenced`, a `/pull/` 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 ` 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/` URL in its text output. A command containing `gh pr view`, `gh pr edit`, or `gh pr checkout` binds, as `referenced`, a `/pull/` 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 ` 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 --repo --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 --repo --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
Implementation internals — click to expand -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 |
@@ -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. diff --git a/packages/experimental/forge-session/README.zh.md b/packages/experimental/forge-session/README.zh.md index 5818317163..cfeb7dbab1 100644 --- a/packages/experimental/forge-session/README.zh.md +++ b/packages/experimental/forge-session/README.zh.md @@ -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/` URL。包含 `gh pr view`、`gh pr edit` 或 `gh pr checkout` 的命令以 `referenced` 绑定:命令选中的 `/pull/` URL,或带有明确仓库和主机的数字编号,以及输出为它所操作的变更请求本身打印的 URL,即 gh 的 `url:` 字段、开始描述正文的 `--` 行之前单独成行的 URL,以及 JSON 的 `url` 成员。描述正文或其他字段里的链接不会绑定;同一命令里还包含 `gh pr create` 时,其 URL 以 `created` 绑定。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To ` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `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/` URL。包含 `gh pr view`、`gh pr edit` 或 `gh pr checkout` 的命令以 `referenced` 绑定:命令选中的 `/pull/` URL,或带有明确仓库和主机的数字编号,以及输出为它所操作的变更请求本身打印的 URL,即 gh 的 `url:` 字段、开始描述正文的 `--` 行之前单独成行的 URL,以及 JSON 的 `url` 成员。描述正文或其他字段里的链接不会绑定;同一命令里还包含 `gh pr create` 时,其 URL 以 `created` 绑定。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To ` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `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 --repo --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 --repo --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"
实现细节——点击展开 -`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) | 绑定记录、投影状态与条目类型 |
@@ -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 与其监听方都看不到。 diff --git a/packages/experimental/forge-session/package.json b/packages/experimental/forge-session/package.json index 18d8274446..de63f1a2d2 100644 --- a/packages/experimental/forge-session/package.json +++ b/packages/experimental/forge-session/package.json @@ -72,7 +72,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": { diff --git a/packages/experimental/forge-session/src/commands.ts b/packages/experimental/forge-session/src/commands.ts index a942fbe873..8e381d714f 100644 --- a/packages/experimental/forge-session/src/commands.ts +++ b/packages/experimental/forge-session/src/commands.ts @@ -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 } /** diff --git a/packages/experimental/forge-session/src/index.ts b/packages/experimental/forge-session/src/index.ts index 4db49b65fc..0800ef85ad 100644 --- a/packages/experimental/forge-session/src/index.ts +++ b/packages/experimental/forge-session/src/index.ts @@ -32,8 +32,8 @@ 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 + * `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 @@ -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) diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index 1f1ab54a43..2ab52b0817 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -1,13 +1,14 @@ -/** 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 { 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 +63,18 @@ const stateSchema: z.ZodType = 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 +87,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 +109,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): 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 { diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 7cce3eb6dc..edb99ff93c 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -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 + 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,68 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess ctx.inject(['tools', 'shell', 'shellEnv'], (scope) => { const lifetime = new AbortController() const tasks = new Set>() + /** Lookups of settled program calls, keyed by the token of the call that encloses them. */ + const queued = new Map() 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) ?? [] + queued.delete(exec.token) + const own = prepare(exec, result) + if (own !== undefined) lookups.push(own) + 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, result: Readonly): Promise { - if (exec.name !== 'bash' || exec.agent === undefined || exec.parent !== undefined || result.isError) return + function prepare(exec: Readonly, result: Readonly): Lookup | undefined { + if (exec.name !== 'bash' || exec.agent === undefined || result.isError) return undefined const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) - if (!argumentsResult.success || !shell.success) return + if (!argumentsResult.success || !shell.success) return undefined 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 undefined + const [command] = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup]) + return command === undefined ? undefined : { exec, session: exec.agent.session, command, 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 { + 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 { + 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) + } }) } diff --git a/packages/experimental/forge-session/src/types.ts b/packages/experimental/forge-session/src/types.ts index 3aecc92d8a..56fcbd7c6e 100644 --- a/packages/experimental/forge-session/src/types.ts +++ b/packages/experimental/forge-session/src/types.ts @@ -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 } diff --git a/packages/experimental/forge-session/tests/fixtures.ts b/packages/experimental/forge-session/tests/fixtures.ts index cd05bf0cea..f633af6034 100644 --- a/packages/experimental/forge-session/tests/fixtures.ts +++ b/packages/experimental/forge-session/tests/fixtures.ts @@ -8,6 +8,7 @@ import { createAssistantMessage, createToolResultMessage, ToolCallId } from '@de 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' @@ -194,6 +195,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 { + /** 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 `:ptc:`. + * @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 = 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: 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 [ diff --git a/packages/experimental/forge-session/tests/loader-composition.spec.ts b/packages/experimental/forge-session/tests/loader-composition.spec.ts index cb6161766c..152f839a6f 100644 --- a/packages/experimental/forge-session/tests/loader-composition.spec.ts +++ b/packages/experimental/forge-session/tests/loader-composition.spec.ts @@ -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, 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, 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' @@ -115,10 +120,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 | 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() } @@ -128,9 +147,9 @@ class ScriptedModel extends LlmAdapter { async * stream(options: GenerateOptions): AsyncIterable { this.requests.push(options) - const command = this.commands[this.requests.length - 1] - if (command !== undefined) { - const call = { type: 'tool-call' as const, id: 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: 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' } } @@ -154,7 +173,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) @@ -172,7 +203,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], @@ -186,6 +217,7 @@ async function load() { const configs: Record = { '@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'))}`], @@ -243,6 +275,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(SessionId(sessionId), { provider: 'fixture', model: 'fixture' }, { cwd: root }) + const idle: PromiseWithResolvers = 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 { + 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 { + 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() @@ -296,7 +380,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: [] }) @@ -336,40 +419,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(SessionId('forge-session-loader'), { provider: 'fixture', model: 'fixture' }, { cwd: root }) - const idle: PromiseWithResolvers = 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() ctx.forgeSession.watch(agent.session, listener) @@ -383,4 +438,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) }) diff --git a/packages/experimental/forge-session/tests/projection.spec.ts b/packages/experimental/forge-session/tests/projection.spec.ts index dfc0309833..ff9fb61592 100644 --- a/packages/experimental/forge-session/tests/projection.spec.ts +++ b/packages/experimental/forge-session/tests/projection.spec.ts @@ -3,7 +3,7 @@ import { createAssistantMessage, createToolResultMessage, ToolCallId } from '@de import { appendPluginRecord, Session, 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 @@ -245,6 +245,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(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(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(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(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(SessionId('schema')) shellTurn(session, [{ callId: 'push', command: 'git push', output: pushOutput('feat') }]) diff --git a/packages/experimental/forge-session/tests/reference-lookup.spec.ts b/packages/experimental/forge-session/tests/reference-lookup.spec.ts index bfbee34916..89022144b2 100644 --- a/packages/experimental/forge-session/tests/reference-lookup.spec.ts +++ b/packages/experimental/forge-session/tests/reference-lookup.spec.ts @@ -169,12 +169,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: [] }) @@ -188,4 +187,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>) { + const rootController = new AbortController() + const root: ToolExecution = { + name: 'run_code', agent: f.agent, + callId: ToolCallId('program'), rootCallId: 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: 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: 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() + }) + }) }) diff --git a/packages/experimental/forge-session/tests/service.spec.ts b/packages/experimental/forge-session/tests/service.spec.ts index ee13cc3341..566837ec12 100644 --- a/packages/experimental/forge-session/tests/service.spec.ts +++ b/packages/experimental/forge-session/tests/service.spec.ts @@ -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, from: number) => ctx.sessionProjections.restore( + checkpoints, events.slice(from), SessionLogOffset(from), session.header, session.inheritedEventCount, + ).checkpoint +} + async function settle(): Promise { 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() + 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)) diff --git a/packages/experimental/forge-session/tsconfig.json b/packages/experimental/forge-session/tsconfig.json index a939ef56e9..048d2f0b45 100644 --- a/packages/experimental/forge-session/tsconfig.json +++ b/packages/experimental/forge-session/tsconfig.json @@ -43,6 +43,9 @@ }, { "path": "../../sandbox/sandbox-policy" + }, + { + "path": "../../core/tool-executor-ptc" } ] } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index dd596070e2..46b1adec53 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1599,7 +1599,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[]', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 004153b3bf..c6fdd161be 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10376,6 +10376,12 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm + '@deepseek-ai/dsh-ptc-runtime-node': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime-node + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:* + version: link:../../sandbox/sandbox-local '@deepseek-ai/dsh-sandbox-policy': specifier: workspace:* version: link:../../sandbox/sandbox-policy @@ -10403,6 +10409,9 @@ importers: '@deepseek-ai/dsh-tool-executor-native': specifier: workspace:* version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tool-executor-ptc': + specifier: workspace:* + version: link:../../core/tool-executor-ptc '@deepseek-ai/dsh-tools': specifier: workspace:* version: link:../../core/tools