diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml new file mode 100644 index 0000000000..121a9d669b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-06-connector-account-registry.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts: + en: 3950421fb526f6b7 + zh: 47c5f6cc4b735058 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/problem: + en: 2a7b59cd509a0b9a + zh: 38130ce17829342d +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/decision: + en: d96b43106a1ba837 + zh: 97bc8f9436ec07d0 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/alternatives-considered: + en: ee0aa3f9ea40ef15 + zh: fded69a6dcc8ca87 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/consequences: + en: 5228f32becfbdec3 + zh: 013f1073e70d46f7 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md new file mode 100644 index 0000000000..93138b065e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md @@ -0,0 +1,42 @@ +# Agent Note: One Host registry and one browser half for connector accounts + +Status: implemented + +English | [中文](2026-11-06-connector-account-registry.zh.md) + +## Problem + +Connector plugins show an account section on the Plugins page. CLI app plugins keep the account in their vendor CLI; MCP connectors keep an OAuth grant through the MCP manager. Both kinds need the same surfaces: a bundle's section, title tag, and activation prompt, a confirmation before an action that changes the account outside DSH, and a notice in the browser that started the operation. A client plugin cannot share runtime code with another feature plugin ([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) rule 3), so one browser half per connector kind duplicates the same code and lets the copies drift. When the browser decides an account's state or relays an identifier from one Remote to another, the Host can no longer run the flow without the browser. + +## Decision + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.md) provides one Host registry, `ctx.connectorAccounts`, one `connectorAccounts` Remote, and one browser half for every connector kind. + +| Part | Contract | +|---|---| +| Registration | `register({ key, packageName?, source, operations, copy, present })` returns the disposer that withdraws the account | +| Key | Unique among registered accounts and independent of the package, so an account that no bundle owns, such as a server configured in Settings, registers too | +| Package | Decides which bundle page carries the section and tag; a package carries at most one account | +| Source | The registrant's account: `snapshot`, `observe`, `refresh`, `start`, and `cancel` | +| Display | `present(view)` on the Host gives the phase, status text, title tag, buttons and their commands, confirmations, failure, and the operation the activation prompt starts | +| Remote | `watch`, plus `start(key, operation)` and `cancel(key, id)`, which route by key to the account's source | + +The Host decides everything except opening the authorization page. The browser never learns how an account connects: it receives only the display, the operation in progress with its authorization page, and the latest result with its success text. The browser half keeps only what belongs to one browser: the operations it started, so their authorization pages open and their success is reported only there; the latest notice; and whether its stream is delivering. Buttons call `start` and `cancel` on the Remote themselves, and each surface keeps its own pending state. + +The page registers one title tag entry and one notice entry. It also registers a section and an activation prompt for each account that names a package, because those two slots are keyed by package. + +## Alternatives considered + +**Two registries behind one browser half.** Rejected: the browser would follow both Remotes and choose which one each button calls, which relays between Host services again, and the two Host registries would hold the same code. + +**One browser half per connector kind.** Rejected: client plugins cannot import each other's values, so the shared surfaces would be written twice and diverge. + +**Share the browser half through `PLATFORM_MODULES` or a browser-side service.** Rejected: the module table is reserved for shell-seeded and static infrastructure libraries, and a browser-side service would keep the registrations in the browser, which only repeat what the Host knows. + +**Let the browser derive an account's phase and actions from the registrant's raw state.** Rejected: the rules for which actions apply would live where the Host cannot test or run them, and the browser would need the registrant's own Remote. + +## Consequences + +The registry and browser half exist once. A new connector kind writes a source and `present` on the Host and needs no browser code. The account rules live beside the services that own them, and the Host can run every operation without a browser. + +Registrants map their account states onto five phases (checking, connecting, connected, disconnected, unavailable); a state outside them shows through its status text and detail. The Web and Desktop compositions load the registry whether or not a connector plugin is installed. An authorization page that opens after the start call answers can be blocked by the browser; the section's open button shows it again. diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md new file mode 100644 index 0000000000..e2c7a56b41 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md @@ -0,0 +1,42 @@ +# Agent Note:连接器账号使用一个 Host 注册表和一个浏览器一半 + +Status: implemented + +[English](2026-11-06-connector-account-registry.md) | 中文 + +## 问题 + +连接器插件会在插件页显示账号区块。CLI 应用插件的账号保存在厂商 CLI 中;MCP 连接器通过 MCP 管理器保存 OAuth 授权。两类插件需要同样的界面:插件包的区块、标题旁标签和开启引导,在会改变 DSH 之外账号状态的操作前确认,以及只在发起操作的浏览器中显示的提示。客户端插件不能与其他功能插件共享运行时代码([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) 第 3 条),因此每类连接器各有一个浏览器一半,就会把同样的代码写两遍,副本还会逐渐不一致。如果由浏览器决定账号状态,或在两个 Remote 之间转发标识,Host 就无法在没有浏览器的情况下完成流程。 + +## 决定 + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.zh.md) 为所有连接器类型提供一个 Host 注册表 `ctx.connectorAccounts`、一个 `connectorAccounts` Remote 和一个浏览器一半。 + +| 部分 | 约定 | +|---|---| +| 注册 | `register({ key, packageName?, source, operations, copy, present })` 返回撤下账号的销毁函数 | +| 键 | 在已注册账号中唯一,且与包无关,因此没有插件包承载的账号(如在 Settings 中配置的服务器)也能注册 | +| 包 | 决定由哪个插件包页面承载区块和标签;一个包最多承载一个账号 | +| 来源 | 注册方的账号:`snapshot`、`observe`、`refresh`、`start` 和 `cancel` | +| 展示 | Host 上的 `present(view)` 给出阶段、状态文字、标题旁标签、按钮及其命令、确认、失败信息,以及开启引导启动的操作 | +| Remote | `watch`,以及按键路由到账号来源的 `start(key, operation)` 和 `cancel(key, id)` | + +除了打开授权页,其余都由 Host 决定。浏览器不知道账号如何连接:它只收到展示内容、进行中的操作及其授权页,以及带成功文本的最新结果。浏览器一半只保存属于本浏览器的东西:它发起的操作(授权页只在这里打开,成功只在这里报告)、最新提示,以及它的流是否在推送。按钮自己调用 Remote 的 `start` 和 `cancel`,每个界面自己保存未完成状态。 + +页面只注册一个标题旁标签条目和一个提示条目;对每个带包名的账号,再注册一个区块和一个开启引导,因为这两个插槽以包为键。 + +## 考虑过的替代方案 + +**一个浏览器一半背后有两个注册表。** 否决:浏览器要同时跟随两个 Remote,并为每个按钮选择调用哪一个,这又是在 Host 服务之间转发;两个 Host 注册表的代码也会相同。 + +**每类连接器各有一个浏览器一半。** 否决:客户端插件不能导入彼此的值,共用界面就要写两遍,并逐渐不一致。 + +**通过 `PLATFORM_MODULES` 或浏览器端服务共享浏览器一半。** 否决:模块表只留给由 shell 预置的基础设施和静态库;浏览器端服务会把注册留在浏览器中,而这些注册只是重复 Host 已知的信息。 + +**由浏览器根据注册方的原始状态推算账号阶段和操作。** 否决:哪些操作可用的规则会放在 Host 无法测试和执行的地方,浏览器还需要注册方自己的 Remote。 + +## 后果 + +注册表和浏览器一半只有一份。新的连接器类型只需在 Host 上编写来源和 `present`,不需要浏览器代码。账号规则与拥有它们的服务在一起,Host 不依赖浏览器就能执行每个操作。 + +注册方需要把账号状态映射到五个阶段(检查中、连接中、已连接、未连接、不可用);超出这些阶段的状态通过状态文字和说明表达。无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml new file mode 100644 index 0000000000..db0702f47e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-13-draft-attachments-across-session-switches.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +/agent-note-draft-attachments-across-session-switches: + en: 2a1645c8c80d6dff + zh: 59277c3754231479 +/agent-note-draft-attachments-across-session-switches/problem: + en: 3f4030763e1f0105 + zh: c8a0bc5641d7bed4 +/agent-note-draft-attachments-across-session-switches/decision: + en: 40697e88c2ed6ca8 + zh: eeb363374b25c3a2 +/agent-note-draft-attachments-across-session-switches/alternatives-considered: + en: 2c43ad479f4a3577 + zh: 07743f45870eb0fe +/agent-note-draft-attachments-across-session-switches/consequences: + en: 6ac6defa552ea040 + zh: aa64a3c3e54dbebc diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md new file mode 100644 index 0000000000..8c33335f55 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -0,0 +1,25 @@ +# Agent Note: Draft attachments across Session switches + +Status: implemented + +English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md) + +## Problem + +Switching to another Session and back emptied the composer's attachment rail while its text survived (issue #5070). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. + +## Decision + +**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A message the Host accepts leaves that ownership at once, while the registry keeps its attachments until the echo settles them. A retiring composer releases its attachments only when its Session was removed or a message or command was already submitted, because the Client cannot tell whether a submitted command consumed them; an aborted slash-line adjudication keeps them. Otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. + +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. + +## Alternatives considered + +**Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart. + +**Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again. + +## Consequences + +Switching never touches the Host, so a weak network cannot lose a draft attachment there. A reload or crash still discards attachments; a crash writes no mark and so shows no notice. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md new file mode 100644 index 0000000000..645a79c881 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -0,0 +1,25 @@ +# Agent Note:草稿附件跨会话切换 + +Status: implemented + +[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文 + +## 问题 + +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在(issue #5070)。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 + +## 决策 + +**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。Host 接受消息时,这些附件立即退出会话归属,注册表则保留它们直到回显结算。退役的输入框只在其会话已被删除、或消息与命令已经提交时释放附件,因为客户端无法判断已提交的命令是否用掉了附件;被中止的斜杠行裁决会保留附件。其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 + +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 + +## 考虑过的替代方案 + +**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 + +**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 + +## 影响 + +切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..fb625e0d85 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -1,29 +1,36 @@ /** - * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * Daily stale pull-request reminders and closing for the `Stale pull requests` workflow. * * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross - * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow - * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` - * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the + * workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after + * the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days' + * notice, including for pull requests that were already inactive when the workflow started. Activity, including + * reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither + * reminded nor closed. * * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` - * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed * pull request is reported and skipped. */ -/** Label that exempts a pull request from reminders. */ +/** Label that exempts a pull request from reminders and closing. */ export const EXEMPT_LABEL = 'DO_NOT_CLOSE' /** Days without activity after which each reminder is posted, in ascending order. */ export const REMINDER_DAYS = [7, 14] +/** Days without activity after which a pull request is closed. */ +export const CLOSE_DAYS = 21 + const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 const MAX_COMMENTS_PER_RUN = 100 -const MARKER = // +// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored. +const MARKER = // // Review bots that use ordinary user accounts. const BOT_LOGINS = new Set(['ds-review-bot']) @@ -55,39 +62,46 @@ function activityTimes(event) { } /** - * Selects the reminder a pull request is due for. + * Selects the reminder or closing a pull request is due for. * @param {object} options * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + * @returns {{ days: number, comment: boolean } | undefined} Due stage in days, `CLOSE_DAYS` for closing, and whether its + * comment is still unposted; `undefined` when nothing is due. A closing whose comment was posted but whose close failed + * is due again without a comment. */ -export function dueReminder({ createdAt, timeline, now }) { +export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) const lastActivity = Math.max(...times) - const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined const sent = timeline .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) - .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) - return sent.some(days => days >= due) ? undefined : due + .map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) })) + const finalReminder = REMINDER_DAYS.at(-1) + const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS + if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { + return { days: CLOSE_DAYS, comment: !sent.some(({ days }) => days === CLOSE_DAYS) } + } + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined || sent.some(({ days }) => days >= due)) return undefined + return { days: due, comment: true } } /** - * Builds the reminder comment. + * Builds the reminder or closing comment. * @param {string} author Pull-request author login. - * @param {number} days Reminder stage in days. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. * @returns {string} Comment body. */ -export function reminderBody(author, days) { - return [ - ``, - `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, - ].join('\n') +export function stageBody(author, days) { + const text = days === CLOSE_DAYS + ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` + : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` + return `\n${text}` } /** - * Posts every due reminder on open pull requests of the workflow repository. + * Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository. * @param {object} options * @param {object} options.github Authenticated Octokit client from `actions/github-script`. * @param {object} options.context Workflow context from `actions/github-script`. @@ -96,7 +110,7 @@ export function reminderBody(author, days) { * @param {(ms: number) => Promise} [options.sleep] Delay between comments. * @returns {Promise} */ -export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { +export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { const { owner, repo } = context.repo const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) let posted = 0 @@ -107,12 +121,16 @@ export async function remindStalePullRequests({ github, context, core, now = new if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueReminder({ createdAt: pull.created_at, timeline, now }) - if (days === undefined) continue - if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) - posted++ - core.info(`#${pull.number}: posted the ${days}-day reminder`) + const stage = dueStage({ createdAt: pull.created_at, timeline, now }) + if (stage === undefined) continue + const { days } = stage + if (stage.comment) { + if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) + posted++ + } + if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) + core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..c6033e1fc5 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,47 +1,67 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' +import { dueStage as dueAction, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) -const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) +const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) +const dueStage = options => dueAction(options)?.days test('no reminder is due within 7 days of the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) }) test('the latest due stage is posted once after the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined) +}) + +test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => { + assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21) + // A pull request that was already inactive gets the 14-day reminder first and 7 days' notice. + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) + // A 14-day reminder from before the last activity gives no notice. + assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) + // Reminders posted before closing existed announce no closing. + const legacy = comment(bot, 10, '\n@author This pull request has had no activity for 14 days.') + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [legacy], now }), 14) +}) + +test('a closing whose comment was posted retries the close without another comment', () => { + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14)], now }), { days: 21, comment: true }) + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14), reminder(1, 21)], now }), { days: 21, comment: false }) }) test('human activity restarts the cycle and bot activity does not', () => { const sentBefore = [reminder(30, 7), reminder(23, 14)] - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21) }) test('mentions, labels and cross references are not activity', () => { const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) // GitHub records a `mentioned` event for the author right after each reminder. - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) }) -test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { +test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => { const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) const pulls = [ pull(1), @@ -51,12 +71,21 @@ test('reminders mention the author and skip exempt and bot-authored pull request pull(4, { updated_at: daysAgo(1) }), pull(6), pull(5), + pull(7, { created_at: daysAgo(30) }), + pull(8, { created_at: daysAgo(30) }), ] const comments = [] + const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls' }, + pulls: { + list: 'pulls', + update: async params => { + if (params.pull_number === 8) throw new Error('close failed') + closed.push(params) + }, + }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -68,20 +97,23 @@ test('reminders mention the author and skip exempt and bot-authored pull request paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return [] + return [7, 8].includes(params.issue_number) ? [reminder(9, 14)] : [] }, } const sleeps = [] const warnings = [] const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5]) - assert.deepEqual(warnings, ['#6: locked']) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) + // A failed close after its comment is retried on the next run without another comment. + assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) - assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.deepEqual(sleeps, [1000, 1000, 1000]) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7, 8]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { @@ -91,6 +123,6 @@ test('a run posts at most 100 reminders', async () => { rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, paginate: async method => method === 'pulls' ? pulls : [], } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) assert.equal(comments, 100) }) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -1,4 +1,4 @@ -# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days. # Rules: .github/stale-pull-requests/remind.mjs. name: Stale pull requests @@ -16,7 +16,7 @@ concurrency: jobs: remind: - name: Remind stale pull requests + name: Remind and close stale pull requests runs-on: ubuntu-latest permissions: contents: read @@ -27,9 +27,9 @@ jobs: with: sparse-checkout: .github/stale-pull-requests persist-credentials: false - - name: Post due reminders + - name: Post due reminders and close stale pull requests uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 with: script: | - const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) - await remindStalePullRequests({ github, context, core }) + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core }) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index c7ef7c99e1..ea7301ee1b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -31,10 +31,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -48,6 +52,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index 23df1c78fb..9e3ec3e15c 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index 7fd42a7bc1..498fb3440a 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/web/tests/draft-attachment-session-switch.e2e.ts b/apps/web/tests/draft-attachment-session-switch.e2e.ts new file mode 100644 index 0000000000..3fff0f980b --- /dev/null +++ b/apps/web/tests/draft-attachment-session-switch.e2e.ts @@ -0,0 +1,99 @@ +// Web e2e scenario: a composer draft's pasted image survives a sidebar session +// switch. The reported defect spans the whole chain — sidebar row click, Session +// scope retirement, the input shell's teardown, and the rail's rebuild — so only +// the real composition can pin it. Units cover each link separately (hub/shell/ +// service specs); this covers the assembled path and the rail the user sees. +// +// Zero model calls: a seeded session is non-blank (so the sidebar can create a +// second one instead of reusing it) and the scenario never submits. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const MODE = webSnapshotMode() +const SEED_ID = 'draft-attachment-switch-a' +const PEER_ID = 'draft-attachment-switch-b' +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const PNG = fileURLToPath(new URL('../../../snapshots/session/read-image/workspace/red.png', import.meta.url)) +const DRAFT_TEXT = 'draft text that survives the switch' + +/** The composer's pending-attachment rail, present only while it holds items. */ +const RAIL = '[role="group"][aria-label="Pending attachments"]' + +/** + * Paste one real PNG into the composer through a genuine clipboard event, the + * same intake a user's screenshot paste performs. + * @param page - page holding the composer. + * @param bytes - PNG bytes. + */ +async function pasteImage(page: Page, bytes: Uint8Array): Promise { + await page.locator('[data-composer-input]').first().evaluate((surface, data) => { + const transfer = new DataTransfer() + transfer.items.add(new File([new Uint8Array(data)], 'draft.png', { type: 'image/png' })) + surface.dispatchEvent(new ClipboardEvent('paste', { + clipboardData: transfer, bubbles: true, cancelable: true, + })) + }, [...bytes]) +} + +describe.skipIf(MODE === 'record')('web e2e: draft attachment across a session switch', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + const log = await readFile(FIXTURE, 'utf8') + await seedSession(scaffold, log, SEED_ID) + await seedSession(scaffold, log, PEER_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + // Expand the workspace group and open the seeded session. + const groupRow = page.locator('[role="treeitem"]').first() + await groupRow.waitFor({ timeout: 15_000 }) + await groupRow.click() + const sessionRow = page.locator(`[data-row-key="session:${SEED_ID}"]`) + await sessionRow.waitFor({ timeout: 15_000 }) + await sessionRow.click() + await page.locator('[data-composer-input]').first().waitFor({ timeout: 15_000 }) + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('keeps the pasted image and the typed draft when the sidebar leaves and returns', async () => { + onTestFailed(() => saveFailureShot(page, 'draft-attachment-session-switch')) + // (a) paste an image, then type text into the seeded session's composer. + await pasteImage(page, await readFile(PNG)) + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await page.locator('[data-composer-input]').first().click() + await page.keyboard.type(DRAFT_TEXT, { delay: 5 }) + await expect.poll(() => page.locator(RAIL).locator('img').count(), { timeout: 10_000 }).toBe(1) + + // (b) leave through the sidebar: switching to another session retires this + // one's Session scope. + await page.locator(`[data-row-key="session:${PEER_ID}"]`).click() + await expect.poll(() => page.locator(RAIL).count(), { timeout: 15_000 }).toBe(0) + + // (c) return: the rebuilt composer must show the image AND the text. + await page.locator(`[data-row-key="session:${SEED_ID}"]`).click() + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await expect.poll( + () => page.locator('[data-composer-input]').first().innerText(), + { timeout: 10_000 }, + ).toContain(DRAFT_TEXT) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md index 57a00d021e..a51962831d 100644 --- a/apps/web/tests/expected/schedule-recommendations-en.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 + - listitem: + - button "Weekly review": Weekly review Your work in the workspace this week, with loose ends and what to do first next week. Fridays at {{clock}} - listitem: - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} - listitem: diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md index 68c90f0426..2bf44e32c5 100644 --- a/apps/web/tests/expected/schedule-recommendations-zh.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 + - listitem: + - button "每周回顾": 每周回顾 回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。 周五 {{clock}} - listitem: - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} - listitem: diff --git a/apps/web/tests/schedule-manual.e2e.ts b/apps/web/tests/schedule-manual.e2e.ts index abf438f7e8..46b52df29f 100644 --- a/apps/web/tests/schedule-manual.e2e.ts +++ b/apps/web/tests/schedule-manual.e2e.ts @@ -71,7 +71,7 @@ it.each([ const recommendations = manager.getByRole('region', { name: copy.heading, exact: true }) const recommendation = recommendations.getByRole('button', { name: copy.title, exact: true }) await recommendation.waitFor() - expect(await recommendations.getByRole('button').count()).toBe(7) + expect(await recommendations.getByRole('button').count()).toBe(8) if (draft === '') { expect(await recommendationColumns(recommendations)).toBe(2) await compareOrRefreshGolden( diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4b9010be09..02033a002f 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -184,6 +184,7 @@ "tests/present-after-closing-reply.e2e.ts", "tests/autolink-cjk-punctuation.e2e.ts", "tests/composer-draft-scroll.e2e.ts", + "tests/draft-attachment-session-switch.e2e.ts", "tests/composer-focus.e2e.ts", "tests/composer-placeholder.e2e.ts", "tests/context-meter.e2e.ts", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 1aabe526a0..ad096eb295 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 7372ec4217b1beb4 - zh: 183ca2544b406d10 + en: 15d626593d746219 + zh: 332d2135597249b8 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index f5972e3a93..3f755e9995 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -29,6 +29,8 @@ flowchart LR svc_pluginRegistryProbe["ctx.pluginRegistryProbe
Host registry response comparison"] pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -355,6 +357,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback @@ -683,6 +686,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 8bff9c115a..82a2f1bac5 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -31,6 +31,8 @@ flowchart LR svc_pluginRegistryProbe["ctx.pluginRegistryProbe
Host registry response comparison"] pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -357,6 +359,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback @@ -685,6 +688,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | 保存 CLI 应用插件和 MCP 连接器注册的账号,并通过一个 Remote 把 Host 算好的展示内容提供给插件页;授权页和提示只出现在发起操作的浏览器中。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 执行来源策略与共享 HTTP 请求分发;凭据验证归 ConnectionAuthentication,API 适配器注册端点和流。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index e0dcf2f1ed..a0fac211e0 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1127,7 +1127,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1727,7 +1727,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1775,7 +1775,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:54`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1814,7 +1814,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:53`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3327,7 +3327,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) @@ -3375,7 +3375,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog @@ -3446,7 +3446,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3468,7 +3468,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:30`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3488,7 +3488,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:30`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4774,7 +4774,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ @@ -5024,7 +5024,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:57`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -5245,6 +5245,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | @@ -5340,6 +5341,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 05e4472734..c686396ec4 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1129,7 +1129,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1729,7 +1729,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1777,7 +1777,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:54`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1816,7 +1816,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:53`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3329,7 +3329,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) @@ -3377,7 +3377,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog @@ -3448,7 +3448,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3470,7 +3470,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:30`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3490,7 +3490,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:30`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4776,7 +4776,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ @@ -5026,7 +5026,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:57`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -5247,6 +5247,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | @@ -5342,6 +5343,7 @@ export interface Config { | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 0c63cd86ff..a9a23bd55e 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -23,11 +23,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | @@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:81`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 5b9dd3a373..ace6545632 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -25,11 +25,11 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | @@ -62,7 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:81`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index c1d4295469..841bd04a8b 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -112,6 +112,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -173,6 +174,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1263,6 +1265,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1373,12 +1382,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1506,6 +1509,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1632,6 +1642,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | @@ -1920,6 +1931,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`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) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`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), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`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` | [`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) | @@ -1938,7 +1950,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`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` | [`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) | @@ -1954,6 +1965,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a179dbe473..3ba8a5b08e 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -114,6 +114,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -175,6 +176,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1265,6 +1267,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1375,12 +1384,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1508,6 +1511,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1634,6 +1644,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | @@ -1922,6 +1933,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`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) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`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), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`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` | [`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) | @@ -1940,7 +1952,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`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` | [`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) | @@ -1956,6 +1967,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index ecbeab9bf4..dce520c25f 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -183,8 +183,8 @@ en: 20645a60e921f012 zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: - en: 6c6a27578dff5828 - zh: 9a5add2bc0df2d0a + en: 5775e52a72c0ce94 + zh: fa211a35b4660c10 /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: en: 59b02baa2be32ca0 zh: 3637c99652ca89cf @@ -1371,8 +1371,8 @@ en: 7660c41e4129b466 zh: bcbb1b15cb872214 /session-persistence-event-catalog/resolved-persistence-types/string: - en: 0bd8cec4019a5ad5 - zh: c6cc79ce5aa844c4 + en: 0c7d65a7628869fb + zh: be140c5bd89db538 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1764,8 +1764,8 @@ en: f58bccca3df9c2ad zh: 5c92b6edeb7ce020 /session-persistence-event-catalog/resolved-persistence-types/kind-retry: - en: c628d0575f81407a - zh: d9a70ce1e05dcce8 + en: 898f27c058097895 + zh: bbbcf08ad8ba3a32 /session-persistence-event-catalog/resolved-persistence-types/kind-runtime-context: en: 68b5598e21cf8ba2 zh: 95ef1685af64a5f4 @@ -1905,8 +1905,8 @@ en: 4e102391d685eff5 zh: 9762243a13014f3d /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 808d28208287e843 - zh: 18a8d63978c984a7 + en: 156e57c019aa1b28 + zh: a1629b267f7cc713 /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index fda2cd4809..180ac5a9dd 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/ Types: [SessionTitleEventData](subsystems/session-title.md) -Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5666,7 +5666,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:22`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:9`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:14`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:22`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:9`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:14`](../packages/workflow/workflow/src/types.ts) `string` @@ -7312,7 +7312,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -Sources: [`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7845,7 +7845,7 @@ Sources: [`packages/core/tools/src/index.ts:28`](../packages/core/tools/src/inde SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -Sources: [`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index b8ed2e8252..fca86d65cc 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -867,7 +867,7 @@ export type SessionEvent = { 类型:[SessionTitleEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5668,7 +5668,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:22`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:9`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:14`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:22`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:9`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:14`](../packages/workflow/workflow/src/types.ts) `string` @@ -7314,7 +7314,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -来源:[`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7847,7 +7847,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -来源:[`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index f53c42b5b2..9b1d1081fe 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -263,7 +263,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:172"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:22","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:9","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:14"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:383","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:22","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:9","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:14"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, @@ -427,7 +427,7 @@ {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, {"digest":"8e8155594e07812356b67d732196dda894b0f9c91a5969d51612cf490b0a016d","names":[],"sources":[]}, {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:213"]}, - {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:402"]}, + {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:394"]}, {"digest":"8f324cea3916c0517261e88167def8efb3a9994c1135e23d40ed9fd48f8c7bd4","names":[],"sources":[]}, {"digest":"8f6d609794bf5afc01d7ccf3e03811d32f4b8047f58a2c9a98db0154c2ad7cb9","names":[],"sources":[]}, {"digest":"8faed5b52ab2d2df40b94a926d0f0faa75280bddcc4b17b6bdd9c8bfed7c34b5","names":[],"sources":[]}, @@ -481,7 +481,7 @@ {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, {"digest":"a3edd1efd1fef21b72c55e213c8a8b24196b091abde2b89db52be0b2aaae3cfa","names":[],"sources":[]}, {"digest":"a43327a1739c3fa477f32981071fef7d8ba6ae5f32a84fd70f547b2eee59e93e","names":[],"sources":[]}, - {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:400"]}, + {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:392"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 56c72978b6..3c48fc6333 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote async start(key: string, operation: string): Promise + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index a8001bd417..9887071680 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote async start(key: string, operation: string): Promise + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/docs/subsystems/session-query.md b/docs/subsystems/session-query.md index 94e7eae55b..5dca82b24c 100644 --- a/docs/subsystems/session-query.md +++ b/docs/subsystems/session-query.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/session-query.zh.md b/docs/subsystems/session-query.zh.md index 7d33c1946c..40605385c1 100644 --- a/docs/subsystems/session-query.zh.md +++ b/docs/subsystems/session-query.zh.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index bf01196282..86c2f01cb1 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md /workspaces: - en: 183fd2f466e3279c - zh: 6e79009b7294c240 + en: 70865308120d0b14 + zh: fe5d7406141657e1 /workspaces/identity: en: d61a7e78bbc1fb56 zh: 8397869f70cd5b28 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 046f0b9924..eda76426f7 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -2,7 +2,7 @@ English | [中文](workspace.zh.md) -A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and invisible to models (no tools, no prompt text, no session events). It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). +A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and adds no model-visible surface of its own (no tools, no prompt text, no session events); the optional [listing tools](../../packages/session-query/tool-session-list) expose Workspace IDs, titles, and paths to models that are granted them. It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). Source: [`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) @@ -63,6 +63,12 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. + */ + getSessionHeaders(): readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 95983eb846..e800d15107 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -2,7 +2,7 @@ [English](workspace.md) | 中文 -工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且对模型不可见(没有工具、没有提示词文本、没有会话事件)。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 +工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且自身不增加模型可见内容(没有工具、没有提示词文本、没有会话事件);可选的[列表工具](../../packages/session-query/tool-session-list)会把 Workspace ID、标题与路径提供给获准使用它们的模型。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 源码:[`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) @@ -63,6 +63,12 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. + */ + getSessionHeaders(): readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 2f947d20f8..295d316f5a 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 789c9c7932024257 - zh: 6d0465e0463b321c + en: 9a75613dfc69ce8b + zh: 5f52b86658f1dff7 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -234,8 +234,17 @@ en: 927a5ac0974b7642 zh: 927a5ac0974b7642 /tool-schema-catalog/deepseek-ai-dsh-tool-skill/skill: - en: 9b159d5831855afb - zh: 275ee82af0e0f59a + en: c1124b6642c57712 + zh: ede0a9f1479b4ecd +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list: + en: 6d68942100dd76e7 + zh: 6d68942100dd76e7 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-session: + en: 8a04c79a2d8ef256 + zh: 06e93b69aa95c6e9 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-workspace: + en: 7b1f0bed364dfcd2 + zh: c907d8ff78f54268 /tool-schema-catalog/deepseek-ai-dsh-tool-session-query: en: eac1dff4b6d9e195 zh: eac1dff4b6d9e195 @@ -309,8 +318,8 @@ en: 8001eda7e9ff6a25 zh: 2414761029f21404 /tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-update: - en: 9acd1c5b2fac9853 - zh: 3bd81e9cd1f1c28d + en: 3c25013abbe19446 + zh: 9552eaab1a25adb2 /tool-schema-catalog/deepseek-ai-dsh-tool-todo: en: dea62d26fb18ff68 zh: dea62d26fb18ff68 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index dd30a3d823..1cfadcda2b 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -40,12 +40,13 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`, `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-stdio`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflowEngine`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`, `ctx.tools`, `ctx.agents`, `ctx.skills` | `tool/call`, `tool/result`, `user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`, `list_workspace` | `ctx.tools`, `ctx.sessions`, `ctx.sessionQuery`, `ctx.workspaceRegistry`, `ctx.sessionProjections` | `tool/call`, `tool/result` | - | Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `ctx.agents`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | The subagent_oar tool selects among configured aliases for external providers. This catalog shows Codex and Claude Code aliases; each deployment chooses its providers. Native model and permission settings belong to the selected provider configuration. | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child's name promptly; local children accept follow-ups, while external backends report their single execution automatically. | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message`, `wait_agent` | `ctx.tools`, `ctx.subagents`, `ctx.agents` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The shared control tools discover and contact agents in the subagent tree, interrupt owned descendants, and wait for input in the caller’s inbox. Provider-bound `tool-subagent` instances supply delegation tools. | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | Reads or changes the calling Session directory. Existing shells and processes retain their own directories; origin metadata and permission roots stay fixed. | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout. | @@ -1909,6 +1910,64 @@ Load the full instructions for a skill. Call it before acting on a task that nam Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times. + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. + ## `@deepseek-ai/dsh-tool-session-query` @@ -2587,7 +2646,7 @@ Compare-and-set a shared task action using the latest revision from team_task_ge Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. +Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 80929e113d..b5a6441be7 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -44,12 +44,13 @@ | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`、`ctx.tools`、`ctx.lsp`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后,因此其模型可见 schema 在更换提供方时保持稳定。运行时要求已注册提供方,例如 `@deepseek-ai/dsh-lsp-stdio`;如果没有提供方,查询会返回结构化 `LSP_UNAVAILABLE` 错误,而不会改变 schema。 | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`、`ctx.workflowEngine`、`ctx.subagents`、`ctx.systemPrompt`、`a calling Agent (exec.agent parents every fresh round)` | `tool/call`、`tool/result`、`workflow and child session events during execution` | - | 固定的前台工作流会在每个 Round 启动一个全新的结构化子级;模型只能选择不可变目标和可选的 Round 上限。 | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`、`ctx.tools`、`ctx.agents`、`ctx.skills` | `tool/call`、`tool/result`、`user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`、`list_workspace` | `ctx.tools`、`ctx.sessions`、`ctx.sessionQuery`、`ctx.workspaceRegistry`、`ctx.sessionProjections` | `tool/call`、`tool/result` | - | 选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`、`session_event_search`、`session_event_trace`、`session_search`、`session_trace` | `ctx.tools`、`ctx.systemPrompt`、`ctx.sessionQuery`、`a calling Agent for workspace authority` | `tool/call`、`tool/result` | - | 这 5 个只读工具会隐藏提供方游标,并根据不可变的调用 agent 会话为每个结果授权。该包需要选择启用;需要强制截止时间或限制行内输出的组合还会挂载通用超时或 spill 策略。 | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | subagent_oar 工具在为外部提供方配置的别名之间选择。本目录展示 Codex 和 Claude Code 别名;每个部署自行选择提供方。原生模型和权限设置由所选提供方的配置决定。 | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理的名称;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message`、`wait_agent` | `ctx.tools`、`ctx.subagents`、`ctx.agents` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 共享控制工具发现并联系 subagent 树中的 Agent,中断有权控制的后代,并等待调用者收件箱中的输入。绑定提供方的 `tool-subagent` 实例提供委派工具。 | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响。 | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | 读取或改变调用方 Session 的目录。已有 shell 和进程保留自己的目录;原始元数据和权限根目录保持不变。 | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | 在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。离开时保留分支与检出目录。 | @@ -1915,6 +1916,64 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, 来源:[`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +按最近人工提示词时间从新到旧列出非 subagent 会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +按注册表顺序列出工作区,包括空工作区。返回 ID、标题、路径以及创建时间和更新时间。 + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 + ## `@deepseek-ai/dsh-tool-session-query` @@ -2593,7 +2652,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响。 +四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 diff --git a/package.json b/package.json index 044355f600..b723e9cdf6 100644 --- a/package.json +++ b/package.json @@ -314,6 +314,7 @@ "@deepseek-ai/dsh-experimental-forge-github": "workspace:*", "@deepseek-ai/dsh-forge-gitlab": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-action-cards": "workspace:*" + "@deepseek-ai/dsh-action-cards": "workspace:*", + "@deepseek-ai/dsh-tool-session-list": "workspace:*" } } diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index 4178adfa26..b05bc795e0 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -15,8 +15,8 @@ en: a7a78c6d1aeebeb3 zh: 4bb69f32d8b05ba3 /deepseek-ai-dsh-api-remotes/use-this-package: - en: 5e5770cc1cbf49db - zh: b9ee3c309d0cd93c + en: d8622091b217f050 + zh: c36cb87f10e7802a /deepseek-ai-dsh-api-remotes/forwarded-host-events: en: 1dea001229f8c06a zh: 3acb1fa1c5d24f8c diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 71e5dc385f..a01a776f3e 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -29,7 +29,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package selects and mounts that generated Session contribution without a direct runtime dependency on `@deepseek-ai/dsh-session`; activation policy stays with Session Controller. -The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, connector accounts, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index 5bef7cb29c..cc3c407f49 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包选择并挂载生成的会话 contribution,无需直接依赖 `@deepseek-ai/dsh-session` 的运行时;激活策略由会话控制器负责。 -Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、连接器账号、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 9ff3b1d910..b97c97cf57 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -98,6 +98,7 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-plugin-market": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 5efb7dbeb7..f53f229635 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -19,6 +19,7 @@ import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote' import mcpManagerRemote from '@deepseek-ai/dsh-mcp-manager/remote' import toolResultsRemote from '@deepseek-ai/dsh-client-ui-trajectory/remote' import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +import connectorAccountsRemote from '@deepseek-ai/dsh-client-ui-connector-account/remote' import pluginMarketRemote from '@deepseek-ai/dsh-plugin-market/remote' import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote' import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote' @@ -50,6 +51,7 @@ export type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/ export type {} from '@deepseek-ai/dsh-plugin-manager/remote' export type {} from '@deepseek-ai/dsh-mcp-manager/remote' export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +export type {} from '@deepseek-ai/dsh-client-ui-connector-account/remote' export type {} from '@deepseek-ai/dsh-client-ui-trajectory/remote' export type {} from '@deepseek-ai/dsh-plugin-market/remote' export type { @@ -202,6 +204,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, scheduleRemote, pluginInventoryRemote, pluginManagerRemote, mcpManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote, + connectorAccountsRemote, toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 94482498be..5f99650f2f 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 50fa3dd0a2ce79c8 - zh: 88bd7ea6058d2122 + en: 15d6cb30e1e7f5e2 + zh: 21fe7028a4ed4aef /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index f414ce78ef..7c71dea39e 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -43,7 +43,7 @@ Every Remote endpoint is access-controlled: a Peer whose principal is not the ow List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. -Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the `sessionListMetadata` projection handle, and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. +Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through [`sessionQuery.getListMetadata`](../../session-query/session-query/README.md#session-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 2a83f4504d..1749a99c4a 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -43,7 +43,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 -Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过 `sessionListMetadata` 投影句柄读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 +Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[`sessionQuery.getListMetadata`](../../session-query/session-query/README.zh.md#session-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index 830ebe21a9..e49a59fcd5 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -5,8 +5,8 @@ import { scheduler } from 'node:timers/promises' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' -import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import type { ProjectionHandle, ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' +import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' @@ -24,11 +24,6 @@ const SEARCH_PROVIDER_CALL_LIMIT = 100 const SESSION_SEARCH_QUERY_MAX_CHARS = 500 const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']) -const sessionListMetadataSchema: z.ZodType = z.object({ - blank: z.boolean(), - lastPromptAt: z.number().nullable(), -}) - const imageLimitsSchema = z.object({ maxImageBytes: z.number().int().positive(), maxImagesPerMessage: z.number().int().positive(), @@ -38,25 +33,6 @@ const imageLimitsSchema = z.object({ mediaTypes: z.array(z.string()), }) as unknown as z.ZodType -/** - * Advance the Session-list metadata projection by one committed event. - * @param state - metadata before the event. - * @param event - next committed Session event. - * @returns the original or advanced metadata value. - */ -export function applySessionListMetadata( - state: SessionListMetadata, - event: SessionEvent, -): SessionListMetadata { - const blank = state.blank && event.type !== 'turn/start' - const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' - ? event.time - : state.lastPromptAt - return blank === state.blank && lastPromptAt === state.lastPromptAt - ? state - : { blank, lastPromptAt } -} - /** * Return the longest prefix containing at most `maximum` Unicode code points. * @param value - source text. @@ -76,8 +52,6 @@ export function truncateUnicodeCodePoints(value: string, maximum: number): strin /** Owns list projection registration, bounded cold summaries, and authorized search. */ export class ApiSessionList { - private listMetadata!: ProjectionHandle - /** * @param ctx - Host context carrying Session, query, persistence, and projection services. * @param workSliceMs - Resolved positive integral list-work budget in milliseconds. @@ -89,14 +63,6 @@ export class ApiSessionList { * @returns when all required registrations are ready. */ async initialize(): Promise { - this.listMetadata = await this.ctx.sessionProjections.register<'sessionListMetadata', SessionListMetadata>({ - key: 'sessionListMetadata', - stateSchema: sessionListMetadataSchema, - init: () => ({ blank: true, lastPromptAt: null }), - apply: applySessionListMetadata, - wire: { viewSchema: sessionListMetadataSchema, view: state => state }, - stateVersion: 1, - }) await this.ctx.sessionProjections.register<'imageLimits', null>({ key: 'imageLimits', stateSchema: z.null(), @@ -113,17 +79,17 @@ export class ApiSessionList { /** * Build one current attached-Session summary. - * Blankness and recency come from the `sessionListMetadata` handle; projection + * Blankness and recency come from `sessionQuery.getListMetadata`; projection * hints carry every summary key computed through `snapshot`. The first call * for a Session computes these projections over its whole in-memory log, and - * later calls advance them incrementally. The handle read and the hint with - * the same key come from one cell; the handle read does not depend on any + * later calls advance them incrementally. The metadata read and the hint with + * the same key come from one cell; the metadata read does not depend on any * other unit's view. * @param session - attached Session to summarize. * @returns current list metadata and available projections. */ summaryFor(session: Session): SessionSummary { - const metadata = this.listMetadata.stateOf(session) + const metadata = this.ctx.sessionQuery.getListMetadata(session) const projections = this.projectionsFor(session.header, session) return { sessionId: session.id, diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 1b8ede4c70..6adc036941 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -14,12 +14,12 @@ import type { Principal } from '@deepseek-ai/dsh-typert-protocol' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' +export type { SessionListMetadata } from '@deepseek-ai/dsh-session-query/types' + declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { /** Eligible latest failed turn/end for an empty prompt, or null. */ conversationContinuation: SessionSeq | null - /** Persisted facts used to summarize a Session without activating it. */ - sessionListMetadata: SessionListMetadata /** * Image-intake limits enforced by the Session prompt endpoint. Boot * constant, excluded from Session summary payloads: every Session shares @@ -29,14 +29,6 @@ declare module '@deepseek-ai/dsh-session-projection/types' { } } -/** Persisted hints used to summarize a cold Session. */ -export interface SessionListMetadata { - /** Whether the folded prefix contains no turn. */ - readonly blank: boolean - /** Latest human-authored prompt time in the folded prefix. */ - readonly lastPromptAt: number | null -} - /** * Summary wire values a Session-list row carries. A `sequenced` block carries * every summary key computed at its `asOfSeq`; a `cached` block carries the diff --git a/packages/api/session-controller/tests/agent.host.spec.ts b/packages/api/session-controller/tests/agent.host.spec.ts index af502032df..d374cc842b 100644 --- a/packages/api/session-controller/tests/agent.host.spec.ts +++ b/packages/api/session-controller/tests/agent.host.spec.ts @@ -36,7 +36,7 @@ async function harness(): Promise<{ ctx: Context; agents: ApiSessionAgentControl await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(agentPresetProjectionDefinition) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), diff --git a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts index fcf65e8f97..f61c1f4645 100644 --- a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts +++ b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts @@ -51,7 +51,7 @@ async function baseContext(): Promise { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), saveSelection: () => Promise.resolve(), diff --git a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts index 060b93357f..cfa5eb627c 100644 --- a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts +++ b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts @@ -44,7 +44,7 @@ async function commandHarness( await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(TypertRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) const sessionId = brandString('commands-session') const ancestor = Session.create(brandString('ancestor')) diff --git a/packages/api/session-controller/tests/controller.host.spec.ts b/packages/api/session-controller/tests/controller.host.spec.ts index 5d1a26c479..8c3a899a3a 100644 --- a/packages/api/session-controller/tests/controller.host.spec.ts +++ b/packages/api/session-controller/tests/controller.host.spec.ts @@ -39,7 +39,7 @@ describe('SessionController facade', () => { const original = ctx.sessionProjections.register.bind(ctx.sessionProjections) let first = true vi.spyOn(ctx.sessionProjections, 'register').mockImplementation(async (...args: Parameters) => { - if (first) { + if (first && args[0].key === 'imageLimits') { first = false entered.resolve(undefined) await gate.promise diff --git a/packages/api/session-controller/tests/history-controller.host.spec.ts b/packages/api/session-controller/tests/history-controller.host.spec.ts index 8bcf9c0599..60339915a3 100644 --- a/packages/api/session-controller/tests/history-controller.host.spec.ts +++ b/packages/api/session-controller/tests/history-controller.host.spec.ts @@ -18,7 +18,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const history = new HistoryController(ctx) const web = new WebController(ctx, history, (observation) => { observation[Symbol.dispose]() }) const session = ctx.sessions.create(brandString('history-target'), { meta: { cwd: '/history-test' } }) diff --git a/packages/api/session-controller/tests/list-scheduling.host.spec.ts b/packages/api/session-controller/tests/list-scheduling.host.spec.ts index b9e4dd0d13..7e2855f754 100644 --- a/packages/api/session-controller/tests/list-scheduling.host.spec.ts +++ b/packages/api/session-controller/tests/list-scheduling.host.spec.ts @@ -85,7 +85,8 @@ async function harness(rows: readonly Row[], summaryMs = 8, workSliceMs = 8) { return { header: session.header, live: row.phase === 'live', persisted: true } }) const listSessions = vi.fn(async (_signal?: AbortSignal) => records) - ctx.provide('sessionQuery', { listSessions } as never) + const getListMetadata = () => ({ blank: true, lastPromptAt: null }) + ctx.provide('sessionQuery', { listSessions, getListMetadata } as never) ctx.provide('sessionProjectionCache', { cachedSnapshot: (header: SessionRecord['header']) => { recordSummary('cold', header.id) diff --git a/packages/api/session-controller/tests/listeners.host.spec.ts b/packages/api/session-controller/tests/listeners.host.spec.ts index 8ae97fb63b..e885db4873 100644 --- a/packages/api/session-controller/tests/listeners.host.spec.ts +++ b/packages/api/session-controller/tests/listeners.host.spec.ts @@ -25,7 +25,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(brandString('listener-target'), { meta: { cwd: '/listeners' } }) const abort = cancellation() const partial: Partial = { id: session.id, session } diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index 84f0eb2cf3..d669ba9dbd 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -35,7 +35,7 @@ async function composed(workspaces: readonly Workspace[] = []): Promise await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('workspaceRegistry', { list: () => workspaces, archivedSessionIds: [] } as never) ctx.agents.setFactory({ createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise => { diff --git a/packages/api/session-controller/tests/session-history-journal.host.spec.ts b/packages/api/session-controller/tests/session-history-journal.host.spec.ts index 28c2a41bc9..816a5eb15b 100644 --- a/packages/api/session-controller/tests/session-history-journal.host.spec.ts +++ b/packages/api/session-controller/tests/session-history-journal.host.spec.ts @@ -55,7 +55,7 @@ async function harness(): Promise<{ ctx: Context }> { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) return { ctx } } diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index abe6e0efc7..d6bea0c4b7 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -541,7 +541,7 @@ describe('session.list projections column', () => { const row = response.value.items.find(item => item.sessionId === session.id) expect(row?.projections?.kind).toBe('sequenced') expect(Object.keys(row?.projections?.values ?? {})).toEqual([...ctx.sessionProjections.summaryKeys()]) - expect(Object.keys(row?.projections?.values ?? {})).toEqual(['conversationContinuation', 'sessionListMetadata']) + expect(Object.keys(row?.projections?.values ?? {})).toEqual(['sessionListMetadata', 'conversationContinuation']) expect(row?.projections?.values.conversationContinuation).toBeNull() }) @@ -797,8 +797,8 @@ describe('Session control projection frames', () => { { type: 'projection', sessionId: session.id, seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, { @@ -838,8 +838,8 @@ describe('Session control projection frames', () => { value: { type: 'projection', seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, }) diff --git a/packages/api/session-controller/tests/session-search.host.spec.ts b/packages/api/session-controller/tests/session-search.host.spec.ts index 9b14011fbe..2d7c944867 100644 --- a/packages/api/session-controller/tests/session-search.host.spec.ts +++ b/packages/api/session-controller/tests/session-search.host.spec.ts @@ -5,7 +5,7 @@ */ import { describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session' @@ -73,6 +73,10 @@ class SearchSessionQuery extends SessionQueryEngine { super(ctx) } + initialize(): Promise { + return this[Service.init]() + } + override searchSessions( ...args: Parameters ): ReturnType { @@ -89,8 +93,8 @@ function installSearchQuery( searchSessions: ( ...args: Parameters ) => Promise, -): void { - new SearchSessionQuery(ctx, searchSessions) +): Promise { + return new SearchSessionQuery(ctx, searchSessions).initialize() } describe('session.search', () => { @@ -152,7 +156,7 @@ describe('session.search', () => { }, ], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const signal = new AbortController().signal @@ -188,7 +192,7 @@ describe('session.search', () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) for (const query of ['', ' ', 'contains\0nul', 'x'.repeat(501)]) { @@ -202,7 +206,7 @@ describe('session.search', () => { it('returns an empty page without invoking the index when no session is visible', async () => { const ctx = await baseContext() const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const response = await remote.search( @@ -228,7 +232,7 @@ describe('session.search', () => { const base = hit('visible', index) return { ...base, bestMatch: { ...base.bestMatch, ...bestMatch } } } - installSearchQuery(ctx, () => Promise.resolve({ + await installSearchQuery(ctx, () => Promise.resolve({ items: [ withBestMatch(0, { sessionId: sid('hidden') }), withBestMatch(1, { surface: 'shadowed' }), @@ -263,7 +267,7 @@ describe('session.search', () => { nextCursor: 'page-2', }) .mockResolvedValueOnce({ items: items.slice(19) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('match'), new AbortController().signal, @@ -303,7 +307,7 @@ describe('session.search', () => { ...end < items.length ? { nextCursor: `offset-${end}` } : {}, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adaptive-page-limit'), @@ -346,7 +350,7 @@ describe('session.search', () => { nextCursor: `page-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('endless-pages'), @@ -411,7 +415,7 @@ describe('session.search', () => { return Promise.reject(new Error('unexpected provider call')) } }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-restart'), @@ -450,7 +454,7 @@ describe('session.search', () => { nextCursor: `cursor-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-churn'), @@ -479,7 +483,7 @@ describe('session.search', () => { controller.abort() return Promise.reject(stale) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-stale'), @@ -500,7 +504,7 @@ describe('session.search', () => { 'provider generation changed before paging', 'SESSION_QUERY_STALE_CURSOR', ))) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('first-page-stale'), @@ -524,7 +528,7 @@ describe('session.search', () => { 'continuation limit is invalid', 'SESSION_QUERY_INVALID_LIMIT', )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('continuation-invalid-limit'), @@ -551,7 +555,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', ), )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('minimum-page-limit'), @@ -577,7 +581,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', )) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-invalid-limit'), @@ -596,7 +600,7 @@ describe('session.search', () => { ctx.sessions.create(sid('visible'), { meta: header('visible') }) const oversized = Array.from({ length: 21 }, (_, index) => hit(`oversized-${index}`)) const searchSessions = vi.fn(() => Promise.resolve({ items: oversized })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('oversized-page'), @@ -622,7 +626,7 @@ describe('session.search', () => { } return Promise.resolve({ items: oversized }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adapted-oversized-page'), @@ -648,7 +652,7 @@ describe('session.search', () => { snippet: `${expected}${'y'.repeat(10_000)}`, }, } - installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) + await installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('bounded-snippet'), @@ -670,7 +674,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-cursor'), @@ -693,7 +697,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: items.slice(20), nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-lookahead-cursor'), @@ -720,7 +724,7 @@ describe('session.search', () => { .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-2' }) .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-3' }) .mockResolvedValueOnce({ items: items.slice(20) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('duplicate-pages'), @@ -748,7 +752,7 @@ describe('session.search', () => { controller.abort() return Promise.resolve({ items: [] }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-continuation'), @@ -777,7 +781,7 @@ describe('session.search', () => { const searchSessions = vi.fn((_request: SessionSearchRequest) => Promise.resolve({ items: [hit('cold-32750')], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('large corpus'), @@ -813,7 +817,7 @@ describe('session.search', () => { }, }) as never) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-during-visibility'), @@ -840,7 +844,7 @@ describe('session.search', () => { inspect, }) as never) const searchSessions = vi.fn(() => Promise.resolve({ items: [] })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('header-only-visibility'), @@ -876,7 +880,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockRejectedValueOnce(aborted) .mockRejectedValueOnce(new Error('database unavailable')) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const cancelled = await remote.search( diff --git a/packages/api/session-controller/tests/state-controller.host.spec.ts b/packages/api/session-controller/tests/state-controller.host.spec.ts index d327804239..11eaeccad7 100644 --- a/packages/api/session-controller/tests/state-controller.host.spec.ts +++ b/packages/api/session-controller/tests/state-controller.host.spec.ts @@ -47,7 +47,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(brandString('state-target'), { meta: { cwd: '/state-test' } }) let agent: Agent | undefined const get = vi.fn(() => agent) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 366db2a0cc..0233bab686 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -59,7 +59,7 @@ async function bench() { sessionId === PARENT ? { meta: header, events } : undefined, ), }) as never) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) provideWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) const controller = await createSessionTestController(ctx, defaults) @@ -201,7 +201,7 @@ describe('SessionController subagent catalog', () => { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const controller = await createSessionTestController(ctx, defaults) const session = ctx.sessions.create(PARENT, { meta: { cwd: '/workspace' } }) const expected = ctx.sessionProjections.snapshot(session) diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index da476f2f49..fe804db76d 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -222,6 +222,10 @@ export function testSessionPersistence( /** Concrete point-read query used by Session Controller tests that do not exercise search. */ class TestSessionQuery extends SessionQueryEngine { + initialize(): Promise { + return this[Service.init]() + } + override searchSessions(): Promise { return Promise.reject(new Error('session search is not configured in this test')) } @@ -231,10 +235,14 @@ class TestSessionQuery extends SessionQueryEngine { } } -/** Install the required projection and point-query services for direct controller tests. */ -export function installSessionReadTestServices(ctx: Context): void { +/** + * Install the required projection and point-query services for direct controller tests. + * @param ctx - test context that receives missing services. + * @returns when the installed query service has registered its projections. + */ +export async function installSessionReadTestServices(ctx: Context): Promise { if (ctx.get('sessionProjections') === undefined) new SessionProjectionRegistry(ctx) - if (ctx.get('sessionQuery') === undefined) new TestSessionQuery(ctx) + if (ctx.get('sessionQuery') === undefined) await new TestSessionQuery(ctx).initialize() } async function installControllers( @@ -295,7 +303,7 @@ async function installControllers( retirePrompt: () => {}, } as never) } - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx) const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd) class TestController extends SessionController { diff --git a/packages/api/session-controller/tests/transport.host.spec.ts b/packages/api/session-controller/tests/transport.host.spec.ts index af297f86c0..00266e5ed3 100644 --- a/packages/api/session-controller/tests/transport.host.spec.ts +++ b/packages/api/session-controller/tests/transport.host.spec.ts @@ -87,7 +87,6 @@ function controllers( web: WebController } { roots.add(ctx[Context.root]) - installSessionReadTestServices(ctx) const history = new HistoryController(ctx) return { history, web: new WebController(ctx, history, promote) } } @@ -95,7 +94,7 @@ function controllers( async function setup(): Promise<{ ctx: Context; history: HistoryController; web: WebController }> { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) return { ctx, ...controllers(ctx) } } @@ -131,7 +130,7 @@ describe('Session history and Web follow', () => { it('ends active followers when the owning Controller unloads', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController const owner = ctx.plugin(Object.assign( (inner: Context) => { @@ -274,7 +273,7 @@ describe('Session history and Web follow', () => { it('bridges the unpublished end-seed boundary when a cold source attaches', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController let agentCtx!: Context await ctx.plugin(Object.assign( diff --git a/packages/api/session-controller/tsconfig.client.json b/packages/api/session-controller/tsconfig.client.json index a1375420ca..6b64356246 100644 --- a/packages/api/session-controller/tsconfig.client.json +++ b/packages/api/session-controller/tsconfig.client.json @@ -23,6 +23,7 @@ { "path": "../../llm/llm" }, { "path": "../../session/session-projection" }, { "path": "../../session/session-title" }, + { "path": "../../session-query/session-query" }, { "path": "../../subagent/subagent" }, { "path": "../../util/brand" }, { "path": "../../util/crypto" }, diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index bc98d7ae6b..69b40ac06a 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { assertNever } from '@deepseek-ai/dsh-util-values' @@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome { } if (!started) continue if (event.type === 'assistant/message') { - const joined = event.data.message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') + const joined = extractTextContent(event.data.message.content) if (joined !== '') text = joined } if (event.type === 'turn/end') reason = event.data.reason diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 810f2cb6f5..7d977cb888 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -348,6 +348,11 @@ - id: ui-plugin-manager name: '@deepseek-ai/dsh-client-ui-plugin-manager' + # Connector account sections on the Plugins page; CLI app plugins and MCP + # connectors register their accounts with `ctx.connectorAccounts`. + - id: ui-connector-account + name: '@deepseek-ai/dsh-client-ui-connector-account' + - id: ui-conversation name: '@deepseek-ai/dsh-client-ui-conversation' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 8ad0dbefe9..c23ebfb9cc 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -87,6 +87,7 @@ "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-commands": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-cordis": "workspace:*", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 3cb0445b68..8cde7a221a 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 77ed389434202e77 - zh: b82d32cf95253760 + en: d358ff0c7eb9d370 + zh: 4eed67d9e3a5aef0 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 6f655cfb5f..649ee7b492 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -84,6 +84,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-settings-subagent/`](ui-settings-subagent/README.md) | Provides the Subagent settings page on the Plugins page | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.md) | Provides the web search and fetch settings page on the Plugins page | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.md) | Contributes the sidebar Plugins panel: install, enable, disable, retry, and compose installed packages | — | +| [`ui-connector-account/`](ui-connector-account/README.md) | Holds the accounts connector plugins register on the Host and shows each bundle's account section, tag, activation prompt, confirmations, and notices on the Plugins page | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.md) | Adds region-local More menus that pin or unpin plugin launchers and start a plugin draft | — | | [`ui-plugin-market/`](ui-plugin-market/README.md) | Contributes the Discover tab to the Plugins page: browse market indexes and install their bundles | — | | [`ui-deliverables/`](ui-deliverables/README.md) | Produces the changed-files card with its comparison tabs, delivery cards, and clickable final-response file references | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 9ce1181967..bc557473c2 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -84,6 +84,7 @@ kind: "package-group" | [`ui-settings-subagent/`](ui-settings-subagent/README.zh.md) | 在插件页提供子智能体设置页 | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.zh.md) | 在插件页提供网页搜索与获取设置页 | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.zh.md) | 贡献侧栏的“插件”面板:安装、启用、停用、重试与组合已安装的包 | — | +| [`ui-connector-account/`](ui-connector-account/README.zh.md) | 保存连接器插件在 Host 上注册的账号,并在插件页显示每个插件包的账号区块、标签、开启引导、确认和提示 | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.zh.md) | 添加分区域的“更多”菜单,固定或收起插件入口,并开始创建插件的草稿 | — | | [`ui-plugin-market/`](ui-plugin-market/README.zh.md) | 为“插件”页面贡献“发现”标签页:浏览市场索引并安装其中的组合包 | — | | [`ui-deliverables/`](ui-deliverables/README.zh.md) | 生成改动文件卡片及其对比 tab、交付文件卡片与可点击的最终响应文件引用 | — | diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml new file mode 100644 index 0000000000..175dc891ee --- /dev/null +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -0,0 +1,49 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-connector-account/README.md +/: + en: f09638e4097c52fb + zh: 2fb344b05a189ad0 +/deepseek-ai-dsh-client-ui-connector-account: + en: bdb528546ec26353 + zh: 0dd55dbc0c8e837a +/deepseek-ai-dsh-client-ui-connector-account/summary: + en: b25fc16fb18a63c1 + zh: 4508e8a44745b08d +/deepseek-ai-dsh-client-ui-connector-account/table-of-contents: + en: d152484eb41ac6b4 + zh: 5b6bd00fce5371c3 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package: + en: 9d8d49a0b1b3ce24 + zh: 8eba3710036afa00 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/register-an-account: + en: e618281ea7721daf + zh: a5d5f5e307ea3435 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: + en: fcbc46fc932ed5c8 + zh: 2f1cce21453bced6 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: + en: 0f6140d7ed6427b9 + zh: feadef500ee4fd98 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: + en: 353a48db7e7dd0f7 + zh: 653f3d983d3fd572 +/deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: + en: 6bfc9077699bd3cd + zh: ead092e865285eee +/deepseek-ai-dsh-client-ui-connector-account/further-exploration: + en: 029949903a73d283 + zh: 6f9a8c2f7620de69 +/deepseek-ai-dsh-client-ui-connector-account/model-experience: + en: bdbc56a07884f8d6 + zh: 22ca2ee613472c0b +/deepseek-ai-dsh-client-ui-connector-account/model-experience/kv-cache-effect: + en: 4cd0965a7997970e + zh: 690e5a9d945f7f6e +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work: + en: d2c5f54b80b86b15 + zh: 8b637f97ac1d0223 +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work/dev-note: + en: 2ab3c4acae06850c + zh: bd2093ba1fdd6860 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md new file mode 100644 index 0000000000..e30ecb7bd6 --- /dev/null +++ b/packages/client/ui-connector-account/README.md @@ -0,0 +1,138 @@ +--- +description: "Register a connector plugin's account on the Host with `ctx.connectorAccounts` and show its section, title tag, activation prompt, confirmations, and notices on the Plugins page through one `connectorAccounts` Remote, with the registrant's own text and the shared copy of this package." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +English | [中文](README.zh.md) + +## Summary + +Connector plugins register their account on the Host with `ctx.connectorAccounts` to show it on the Plugins page: CLI app plugins register the account their vendor CLI keeps, and MCP connectors their OAuth server's account. The Host decides what the page shows and does: each registrant maps its account to a display, and the registry starts or cancels only the operations the account lists. The browser half renders each bundle's section, title tag, and activation prompt, and opens authorization pages and reports notices only in the browser that started the operation. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +A registrant's Host row registers its account once; the registrant ships no browser code for the account. + +### Register an account + +The registrant's Host row registers its account source while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` identifies the account in the Remote; the page passes it back to start and cancel operations. A second registration with the same key throws. +- `packageName` is the npm package whose bundle page carries the section and tag; a package carries at most one account. An account without one, such as a server configured in Settings, appears on no bundle page. +- `source` is the account: its current view, change observation, a check, and starting and cancelling operations. +- `operations` lists the kinds a page button may start, each with the optional text its success reports in the browser that started it; the registry rejects any other kind. +- `copy` holds the section title, the hint under it, and the activation prompt's title, body, and Connect label. + +The registrant imports the registry's types with `import type` from the package root or `./types`. The returned disposer withdraws the account from every page. + +### Present the section + +`present(view)` maps the account view to a `ConnectorAccountDisplay`: the phase, the status line, the optional title tag, buttons, the operation Connect starts in the activation prompt, detail, notes, and failure with its untranslated diagnostic items. The registry calls it for every stream on each change, so it only maps the view. Every string is `LocalizedText`, which each browser resolves in its active language. A button carries a command: `start` with one of the registered operation kinds, `cancel` for the operation in progress, which the source ignores in a phase that is not cancellable, or `open` to reopen its authorization page. A button with `confirm` asks first and runs only after the user accepts. + +| Surface | Behavior | +|---|---| +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons, including a confirmation's, are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | +| Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one, and is disabled while the Host stream is down. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | +| Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | + +### Following operations + +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. The stream reconnects after a lost connection; when it fails for good, the sections keep the last accounts with their buttons disabled until the page reloads. Unloading the browser half closes the stream; Host-owned operations keep running. + +### Shared copy + +The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Later, the diagnostic label, and the failure notice. Every other string comes from the registrant. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. + +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The surfaces receive `start` and `cancel` callbacks that call the Remote and return its result; the buttons report the operation of a successful start to `BrowserAccounts`, and a failed result or a rejected call as the failure notice. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | The `ctx.connectorAccounts` registry and its Remote | +| [`src/types.ts`](src/types.ts) | Registration, source, view, display, and entry types | +| [`src/client/index.ts`](src/client/index.ts) | The browser entry: the dictionary and the slot registrations | +| [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | +| [`src/client/components.tsx`](src/client/components.tsx) | The slot entries of each surface and the buttons' Remote calls | +| [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, and face types | + +
+ +----- + + +## Further Exploration + +- [Plugin manager page](../ui-plugin-manager/README.md) — the Plugins page and its bundle slots. +- [Client package map](../README.md) — adjacent browser UI packages. + +----- + + +## Model Experience + +None, as the registry and its surfaces are Plugins page UI and add no model input. Each registrant documents the tools and skills its account enables. + +#### KV Cache effect + +None; registering or removing an account changes no model-visible text. + +## Known Limitations and Deferred Work + + + +- The five display phases are fixed; a registrant maps any further account state onto one of them. +- A registrant whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. +- Each browser that loads the Web app starts a check of every idle account. +- The Web and Desktop compositions load the registry whether or not a connector plugin is installed. +- An authorization page that opens after the call answers can be blocked by the browser; the section's open button shows it again. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs drive the registry with fake account sources. Client specs drive `BrowserAccounts` with a fake Remote stream, render the surfaces with the Chinese dictionary and a fake Remote, and mount the browser half against a real slot registry and locale runtime. + +
diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md new file mode 100644 index 0000000000..9c1569dfc8 --- /dev/null +++ b/packages/client/ui-connector-account/README.zh.md @@ -0,0 +1,138 @@ +--- +description: "通过 `ctx.connectorAccounts` 在 Host 上注册连接器插件的账号,并经由一个 `connectorAccounts` Remote 在插件页显示其区块、标题旁标签、开启引导、确认和提示,文案来自注册方自己的文本和本包的共用文案。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +[English](README.md) | 中文 + +## 概述 + +连接器插件在 Host 上通过 `ctx.connectorAccounts` 注册账号,在插件页显示账号:CLI 应用插件注册其厂商 CLI 保存的账号,MCP 连接器注册其 OAuth 服务器的账号。页面显示什么、能做什么由 Host 决定:每个注册方把自己的账号映射为展示内容,注册表只启动或取消该账号列出的操作。浏览器一半渲染每个插件包的区块、标题旁标签和开启引导,并且只在发起操作的浏览器中打开授权页、报告提示。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两半。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [延伸阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +注册方的 Host 行注册一次账号;注册方不为账号提供任何浏览器代码。 + +### 注册账号 + +注册方的 Host 行在注册表运行时注册其账号来源,因此没有注册表的组合(如 headless profile)会跳过注册: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` 在 Remote 中标识该账号;页面启动和取消操作时把它传回。用同一个键再次注册会抛出异常。 +- `packageName` 是其插件包页面承载区块和标签的 npm 包;一个包最多承载一个账号。没有包名的账号(如在 Settings 中配置的服务器)不出现在任何插件包页面上。 +- `source` 是账号:其当前视图、变化观察、检查,以及启动和取消操作。 +- `operations` 列出页面按钮可以启动的操作类型,每项可带该操作成功时在发起它的浏览器中报告的文本;注册表拒绝其他类型。 +- `copy` 包含区块标题、区块下方的提示,以及开启引导的标题、正文和连接按钮文案。 + +注册方用 `import type` 从包根或 `./types` 导入注册表的类型。返回的销毁函数会把账号从所有页面撤下。 + +### 展示区块 + +`present(view)` 把账号视图映射为 `ConnectorAccountDisplay`:阶段、状态行、可选的标题旁标签、按钮、开启引导中“连接”启动的操作、说明、附加行,以及带不翻译诊断项的失败信息。注册表在每次变化时为每条流调用它,因此它只做视图映射。所有文案都是 `LocalizedText`,由各浏览器按当前语言解析。按钮携带一个命令:`start` 启动某个已注册的操作类型,`cancel` 取消进行中的操作(处于不可取消的阶段时来源会忽略),`open` 重新打开其授权页。带 `confirm` 的按钮会先询问,用户确认后才执行。 + +| 界面 | 行为 | +|---|---| +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮(包括确认框的按钮)不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作;Host 流中断时它不可用。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | +| 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | + +### 跟随操作 + +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。连接断开后流会自动重连;流永久失败时,区块保留最后的账号,按钮不可用,直到页面重新加载。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 + +### 共用文案 + +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、稍后、排障信息标签和失败提示。其余文案都来自注册方。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 + +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote 并返回其结果;按钮把启动成功时返回的操作报告给 `BrowserAccounts`,结果为失败或调用被 reject 时报告失败提示。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | `ctx.connectorAccounts` 注册表及其 Remote | +| [`src/types.ts`](src/types.ts) | 注册、来源、视图、display 和条目类型 | +| [`src/client/index.ts`](src/client/index.ts) | 浏览器入口:字典和插槽注册 | +| [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面的插槽条目,以及按钮的 Remote 调用 | +| [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示和 face 类型 | + +
+ +----- + + +## 延伸阅读 + +- [插件管理页](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 +- [客户端包地图](../README.zh.md)——相邻的浏览器 UI 包。 + +----- + + +## 模型体验 + +无,注册表及其界面属于插件页 UI,不增加模型输入。各注册方自行说明其账号启用的工具和技能。 + +#### KV Cache 影响 + +无;注册或移除账号不改变任何模型可见文本。 + +## 已知限制与后续工作 + + + +- 五个显示阶段固定不变;注册方需把其他账号状态映射到其中之一。 +- Host 行加载失败的注册方不显示账号区块;插件页仍会列出该插件包及其加载失败。 +- 每个加载 Web 应用的浏览器都会触发一次对所有空闲账号的检查。 +- 无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。 +- 调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 测试用假的账号来源驱动注册表。客户端测试用假的 Remote 流驱动 `BrowserAccounts`,用中文字典和假的 Remote 渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一半。 + +
diff --git a/packages/client/ui-connector-account/locale/de.json b/packages/client/ui-connector-account/locale/de.json new file mode 100644 index 0000000000..98f0f64dea --- /dev/null +++ b/packages/client/ui-connector-account/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector-Kontoverbindung", + "description": "Kontobereich, Titel-Tag, Aktivierungshinweis und Benachrichtigungen auf der Seite „Plugins“ für Connector-Plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/en.json b/packages/client/ui-connector-account/locale/en.json new file mode 100644 index 0000000000..f0d6ca2f20 --- /dev/null +++ b/packages/client/ui-connector-account/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector account connection", + "description": "Account section, title tag, activation prompt, and notices on the Plugins page for connector plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/es.json b/packages/client/ui-connector-account/locale/es.json new file mode 100644 index 0000000000..90e3835555 --- /dev/null +++ b/packages/client/ui-connector-account/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexión de cuenta de conectores", + "description": "Sección de cuenta, etiqueta del título, aviso de activación y notificaciones en la página Complementos para los complementos de conectores." + } +} diff --git a/packages/client/ui-connector-account/locale/fr.json b/packages/client/ui-connector-account/locale/fr.json new file mode 100644 index 0000000000..6aa61577ee --- /dev/null +++ b/packages/client/ui-connector-account/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connexion de compte de connecteur", + "description": "Section de compte, étiquette de titre, invite d’activation et notifications sur la page Plugins pour les plugins de connecteur." + } +} diff --git a/packages/client/ui-connector-account/locale/ja.json b/packages/client/ui-connector-account/locale/ja.json new file mode 100644 index 0000000000..d8a18a8135 --- /dev/null +++ b/packages/client/ui-connector-account/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "コネクターアカウント接続", + "description": "コネクタープラグイン向けに、「プラグイン」ページでのアカウントセクション、タイトルタグ、有効化時の案内、通知を提供します。" + } +} diff --git a/packages/client/ui-connector-account/locale/pt.json b/packages/client/ui-connector-account/locale/pt.json new file mode 100644 index 0000000000..abec0eafe9 --- /dev/null +++ b/packages/client/ui-connector-account/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexão de conta de conector", + "description": "Seção da conta, etiqueta do título, aviso de ativação e notificações na página Plug-ins para plugins de conector." + } +} diff --git a/packages/client/ui-connector-account/locale/ru.json b/packages/client/ui-connector-account/locale/ru.json new file mode 100644 index 0000000000..be0914f34b --- /dev/null +++ b/packages/client/ui-connector-account/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Подключение аккаунта коннектора", + "description": "Раздел аккаунта, метка у заголовка, подсказка при включении и уведомления на странице «Плагины» для плагинов-коннекторов." + } +} diff --git a/packages/client/ui-connector-account/locale/zh.json b/packages/client/ui-connector-account/locale/zh.json new file mode 100644 index 0000000000..af4aade6f6 --- /dev/null +++ b/packages/client/ui-connector-account/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "连接器账号连接", + "description": "在插件页为连接器插件提供账号区块、标题标签、开启引导与提示。" + } +} diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json new file mode 100644 index 0000000000..cb95fb0c25 --- /dev/null +++ b/packages/client/ui-connector-account/package.json @@ -0,0 +1,96 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-connector-account", + "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", + "version": "0.2.2-rc.3", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-connector-account" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./types": { + "types": "./lib/types/types.d.ts" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-ui-plugin-manager" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.6.6" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-package-manifest": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@testing-library/react": "^16.3.3", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css new file mode 100644 index 0000000000..0ad221ae6f --- /dev/null +++ b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css @@ -0,0 +1,56 @@ +.section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.title { + margin: 0 0 4px; + font-size: 14px; + line-height: 20px; + font-weight: 500; +} + +.status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + min-height: 28px; +} + +.label { + flex: 1 1 auto; + min-width: 0; + overflow-wrap: anywhere; + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-left: auto; +} + +.detail, +.hint, +.failure { + margin: 0; + font-size: 13px; + line-height: 20px; +} + +.detail { + color: var(--dsw-alias-label-secondary); +} + +.hint { + color: var(--dsw-alias-label-tertiary); +} + +.failure { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx new file mode 100644 index 0000000000..d931d4bb9a --- /dev/null +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -0,0 +1,223 @@ +/** + * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section with the + * confirmation a button asks for, the title tag, the activation prompt, and the notice. Each is the slot entry that reads + * this browser's state and calls the Host through the injected callbacks. + */ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' +import css from './ConnectorAccount.module.css' +import type { ConnectorAccountKey } from './locales.ts' +import { openAuthorizationPage } from './state.ts' +import type { ConnectorAccountFace, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' + +type FaceProps = InjectFace & { t: Translate } +type BundleFaceProps = InjectFace & { t: Translate } + +const TONE: Record = { + checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', +} + +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', +} + +/** + * Run a button's command against the Host: start and cancel call the face's callbacks, and open shows the + * operation's authorization page again in this browser. + * @param face - the Host callbacks and the browser state the commands read and report to. + * @returns whether a call this surface made has not answered, whether the Host stream is delivering, and the runner of + * one account's command. + */ +function useAccountCommand( + face: Pick, +): { + readonly busy: boolean + readonly linked: boolean + readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void +} { + const linked = face.useConnectorAccounts(state => state.linked) + const [busy, setBusy] = useState(false) + // A second click before the re-render still finds the first call pending. + const pending = useRef(false) + // `operation` resolves to whether the Host accepted the call. + const call = (operation: () => Promise): void => { + if (pending.current) return + pending.current = true + setBusy(true) + // The Host keeps the diagnostic; the page reports one retryable outcome. + void operation() + .then((accepted) => { if (!accepted) face.failed() }) + .catch(() => { face.failed() }) + .finally(() => { pending.current = false; setBusy(false) }) + } + const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { + const { key } = entry + switch (command.kind) { + case 'start': + call(async () => { + const started = await face.start(key, command.operation) + if (started.ok) face.follow(key, started.value) + return started.ok + }) + return + case 'cancel': { + const operation = entry.operation + if (operation !== undefined) call(async () => (await face.cancel(key, operation.id)).ok) + return + } + case 'open': + openAuthorizationPage(entry.operation?.authorizationUrl) + return + /* v8 ignore next -- closed command union */ + default: assertNever(command) + } + } + return { busy, linked, run } +} + +/** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ +function Confirm(props: { + readonly t: Translate + readonly title: string + readonly body: string + readonly label: string + readonly disabled: boolean + readonly onClose: () => void + readonly onConfirm: () => void +}): ReactNode { + const { t, title, body, label, disabled, onClose, onConfirm } = props + return ( + + + + }> +

{body}

+
+ ) +} + +/** + * The `plugins.bundle.config` entry: the account section on its bundle's page. + * @param props - the bundle's face and the translator. + * @returns the title, status line, buttons, detail, notes, failure, hint, and the confirmation a button asked for, or + * null before the Host lists the account. + */ +export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { + const { useConnectorAccounts, account, resolveText, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const { busy, linked, run } = useAccountCommand(props) + const disabled = busy || !linked + const [confirming, setConfirming] = useState() + if (entry === undefined) return null + const { display } = entry + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } + return + } + const details = display.failure?.details ?? [] + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {resolveText(display.status)} +
{display.buttons.map(button)}
+
+ {display.detail === undefined ? null :

{resolveText(display.detail)}

} + {display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {display.failure === undefined ? null : ( +

+ {resolveText(display.failure.text)} + {details.length === 0 ? null : <> {t('failure.details', { details: details.join(' · ') })}} +

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + )} +
+ ) +} + +function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { + for (const entry of state.accounts.values()) if (entry.packageName === packageName) return entry + return undefined +} + +/** + * The `plugins.detail.badge` entry shared by every bundle that owns an account. + * @param props - the open detail page's subject and the face. + * @returns the display's tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + */ +export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { + const { useConnectorAccounts, resolveText, subject } = props + const packageName = subject.kind === 'item' || !subject.pkg.enabled ? undefined : subject.pkg.name + const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) + const badge = entry?.display.badge + return entry === undefined || badge === undefined ? null : {resolveText(badge)} +} + +/** + * The `plugins.bundle.activation` entry: guidance after the user switches a bundle on while its account is not + * connected. Connect opens the bundle page and starts the display's `connect` command. + * @param props - activation callbacks, the bundle's face, and the translator. + * @returns a prompt shown while disconnected, or null before the Host lists the account. It waits while the account is + * checking or connecting, which may still end disconnected, and dismisses itself once the account is connected or + * unavailable. + */ +export function ConnectorAccountActivationEntry( + props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, +): ReactNode { + const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const { linked, run } = useAccountCommand(props) + const phase = entry?.display.phase + useEffect(() => { + if (phase === 'connected' || phase === 'unavailable') onDismiss() + }, [phase, onDismiss]) + if (entry === undefined) return null + const { activation } = entry.copy + const { connect } = entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(entry, connect) + } + return ( + + + + }> +

{resolveText(activation.body)}

+
+ ) +} + +/** + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. + * @param props - the face and the translator. + * @returns the toast for the latest notice, or null. + */ +export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { + const notice = useConnectorAccounts(state => state.notice) + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..e0e30d6285 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,91 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const remote = ctx.remote.connectorAccounts + const browser = new BrowserAccounts(ctx, remote) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + start: (key, operation) => remote.start(key, operation), + cancel: (key, id) => remote.cancel(key, id), + resolveText: text => ctx.locale.resolveText(text), + follow: (key, id) => { browser.follow(key, id) }, + failed: () => { browser.failed() }, + dismissNotice: () => { browser.dismissNotice() }, + } + ctx.effect(function* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..c0a30b7555 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,86 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', +} + +/** Every key the shared account surfaces translate. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..7a061d98dc --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,142 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +export class BrowserAccounts { + /** The accounts, stream state, and notice every surface on the page reads. */ + readonly state: SnapshotStore = createSnapshotStore({ + accounts: new Map(), linked: true, notice: undefined, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private readonly stream: RemoteStream + private readonly observing: Promise + + /** + * @param ctx - the browser context carrying the Remote client. + * @param remote - the `connectorAccounts` Remote. + */ + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + this.patch({ notice: undefined }) + } + + /** + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private async observe(): Promise { + try { + for await (const item of this.stream) { + // An item the stream yielded just before disposal must not reach the disposed page. + if (this.disposed) return + this.show(item.value.accounts) + item.accept() + } + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) + } + } + + private show(entries: readonly ConnectorAccountEntry[]): void { + const accounts = new Map(entries.map(entry => [entry.key, entry])) + for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) + this.patch({ accounts, linked: true }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..afff7bc9ad --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,44 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + readonly accounts: ReadonlyMap + /** Whether the Host stream is delivering. */ + readonly linked: boolean + readonly notice: ConnectorAccountNotice | undefined +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** + * Start an operation of an account on the Host. The Remote result carries the operation the Host started, or the + * failure when the Host refuses or the call does not answer. + */ + readonly start: ClientRemote['connectorAccounts']['start'] + /** Cancel an account's operation on the Host; the Remote result carries a failure like `start`. */ + readonly cancel: ClientRemote['connectorAccounts']['cancel'] + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + readonly follow: (key: string, id: ConnectorOperationId) => void + /** Report that a Remote call this browser made did not finish. */ + readonly failed: () => void + readonly dismissNotice: () => void +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..aa7ec1d6d4 --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId | Promise + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..debd04d302 --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..4dda30bb1c --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,163 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function') + assert(typeof value.start === 'function' && typeof value.cancel === 'function') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + const cancel = vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ({ ok: true, value: undefined })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, cancel, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + expect(await face.start(FIXTURE, 'connect')).toEqual({ ok: true, value: OP }) + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + expect(await face.cancel(FIXTURE, OP)).toEqual({ ok: true, value: undefined }) + expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) + // A refusal reaches the buttons as the Remote's result. + const refused: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } + b.start.mockResolvedValueOnce(refused) + expect(await face.start(FIXTURE, 'connect')).toBe(refused) + face.follow(FIXTURE, OP) + face.failed() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) + face.dismissNotice() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() + + // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { + expect(b.ctx.slots.entries(slot)).toEqual([]) + } + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') + expect(b.closeStream).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..8e645a7bc4 --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,246 @@ +// @vitest-environment jsdom +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Host callbacks. */ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountFace, ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +const STARTED: RemoteResult = { ok: true, value: OP } +const REFUSED: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en +const button = (name: string) => screen.getByRole('button', { name }) +const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } + +const DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { + const current: ConnectorAccountsState = { + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + start: vi.fn(async () => STARTED), + cancel: vi.fn(async () => ({ ok: true, value: undefined })), + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, + } +} + +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation on the Host', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { + const props = face() + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render() + fireEvent.click(button('连接演示')) + expect(disabled()).toEqual([true]) + await act(async () => { answer.resolve(STARTED) }) + expect(disabled()).toEqual([false]) + expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it('disables an open confirmation and the activation prompt\'s Connect while the Host stream is down', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { rerender } = render() + fireEvent.click(button('退出登录')) + // The stream drops while the confirmation is open. + const down = sectionOf(display, { linked: false }) + rerender() + fireEvent.click(button('确认退出')) + expect((button('确认退出') as HTMLButtonElement).disabled).toBe(true) + expect(down.start).not.toHaveBeenCalled() + cleanup() + const offline = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }, { linked: false }) + render(prompt(offline)) + fireEvent.click(button('连接演示')) + expect((button('连接演示') as HTMLButtonElement).disabled).toBe(true) + expect(offline.start).not.toHaveBeenCalled() +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('reports a start whose result is a failure or whose call rejected, without following it', async () => { + const props = face() + props.start.mockResolvedValueOnce(REFUSED).mockRejectedValueOnce(new Error('Remote method is no longer mounted')) + render() + await click('连接演示') + expect(props.failed).toHaveBeenCalledOnce() + expect(disabled()).toEqual([false]) + await click('连接演示') + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await click('取消') + expect(props.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.failed).not.toHaveBeenCalled() + props.cancel.mockResolvedValueOnce(REFUSED) + await click('取消') + expect(props.failed).toHaveBeenCalledOnce() + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = sectionOf(display) + render() + await click('取消') + expect(idle.cancel).not.toHaveBeenCalled() +}) + +it('renders nothing for a bundle whose account the Host has not listed', () => { + render() + render(prompt(face({}, []))) + expect(document.body.textContent).toBe('') +}) + +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { + const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) + const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) + const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face(), row)) + expect(screen.getByText('未连接')).toBeTruthy() + for (const [props, subject] of [ + [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + +it('connects from the prompt through the operation the display names, or only opens the page', async () => { + const onOpenDetails = vi.fn() + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, vi.fn(), onOpenDetails)) + fireEvent.click(button('连接演示')) + expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.start).not.toHaveBeenCalled() +}) + +it('starts once for a second click before the first call answers', async () => { + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(STARTED) }) + expect(props.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..ee8e24276f --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,170 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..4c11668ac2 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserAccounts(ctx, remote) + onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + ctx, browser, remote, open: windowOpen, streams, options: () => options, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { + const b = fixture() + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) + expect(b.state().linked).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.state().linked).toBe(true) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { + const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) + await b.publish(entry(FIXTURE)) + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) +}) + +it('opens nothing and reports nothing after disposal', async () => { + const b = fixture() + await b.browser.dispose() + b.browser.follow(FIXTURE, OP) + b.browser.failed() + expect(b.state().notice).toBeUndefined() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state().linked).toBe(true) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-connector-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json new file mode 100644 index 0000000000..115af386fd --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json new file mode 100644 index 0000000000..564ba19f3b --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json new file mode 100644 index 0000000000..2eca820546 --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.host.json" + }, + { + "path": "./tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-connector-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts new file mode 100644 index 0000000000..620261533c --- /dev/null +++ b/packages/client/ui-connector-account/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 83044eef74..89ea06d3e0 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: dcbdef97e4532896 - zh: 23d6840c89f66bab + en: 4919c08c24d2453b + zh: 45566252950a1ed1 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c8323c1986c1be46 - zh: 6151492c67d4cb88 + en: c65789c64093eb47 + zh: b58cccbeea767849 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 24077e4a55..528c8e368c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. @@ -225,6 +225,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index a2d6b994cb..c43343c7be 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 @@ -225,6 +225,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f6e9ce4183..8944d91981 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -52,11 +52,41 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] + draftAttachmentSessions(): readonly SessionId[] + releaseDraftSession(sessionId: SessionId): void +} + +/** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ +const UNLOAD_MARK_PREFIX = 'dsh.composer-draft-attachments-unloaded' + +/** Record that an unloading page held draft attachments for these Sessions. */ +function writeUnloadMarks(sessionIds: readonly SessionId[]): void { + try { + for (const sessionId of sessionIds) localStorage.setItem(`${UNLOAD_MARK_PREFIX}.${sessionId}`, '1') + } catch (error) { + console.error('conversation draft attachment unload marks could not be saved; a reload cannot report the loss', error) + } +} + +/** Remove one Session's unload marker. @returns whether the marker was present. */ +function takeUnloadMark(sessionId: SessionId): boolean { + try { + const key = `${UNLOAD_MARK_PREFIX}.${sessionId}` + const marked = localStorage.getItem(key) !== null + localStorage.removeItem(key) + return marked + } catch (error) { + console.error('conversation draft attachment unload mark could not be read', error) + return false + } } /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() + private knownSessionIds: Set | undefined + private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -168,10 +198,24 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() + // Snapshot the phase before dispose resets the machine. + const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) + if (conversation === undefined) return + if (binding.session.getSnapshot().removed) { + conversation.releaseDraftSession(binding.sessionId) + return + } + // Teardown aborts adjudication before any message leaves, so those attachments stay with the draft. + // A message or command already submitted cannot settle through its retirement path after teardown, + // and the Client cannot tell whether a submitted command consumed its attachments, so both release + // here rather than risk a duplicate submission; every other draft attachment stays registered for + // the Session's next composer. + if (phaseAtTeardown === 'sending' || phaseAtTeardown === 'submitting') { + for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) + } } }, 'conversation.input: session shell') actx.inject(['inputTriggers'], (scope) => { @@ -181,9 +225,64 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + this.ensureLifecycleWatch() + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] + // A Session switch keeps the draft's attachments registered; this composer re-adopts them. + if (retained.length > 0) shell.addAttachments(retained) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Install the root-lifetime watchers once: a Session removed while no composer + * is mounted releases its draft attachments, and an unloading page marks the + * Sessions whose attachments it discards. + */ + private ensureLifecycleWatch(): void { + if (this.lifecycleWatchInstalled) return + this.lifecycleWatchInstalled = true + const sessions = this.sessions() + this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) + this.rootCtx.effect(() => { + const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) + const conversation = (): ConversationAttachmentFace | undefined => + this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } + // A back-forward cache restore keeps the registry, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + stop() + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + this.knownSessionIds = undefined + this.lifecycleWatchInstalled = false + } + }, 'conversation.input: draft attachment lifecycle') + } + + /** Release draft attachments and unload marks for every Session removed from the catalog. */ + private cleanupRemovedSessions(): void { + const known = this.knownSessionIds + /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ + if (known === undefined) return + const liveIds = new Set(this.sessions().list.getSnapshot().ids) + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + for (const id of [...known]) { + if (liveIds.has(id)) continue + known.delete(id) + conversation?.releaseDraftSession(id) + takeUnloadMark(id) + } + for (const id of liveIds) known.add(id) + } + /** * Resident shell by session id (service-face path; the provide channel has * normally created it already — this covers direct id-addressed access). diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 192446b712..2186b0e80c 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -41,6 +41,7 @@ export const zh = { 'attachment.pathUnavailable': '无法获取文件夹路径,请重新拖入', 'attachment.pathUnsupported': '路径含有无法引用的字符,请改名后再试', 'image.pending': '待发送图片', + 'attachments.unavailable': '部分草稿附件已失效,请重新添加', 'image.openOriginal': '查看原图', 'image.openOriginalLabel': '{label},点击查看原图', 'image.remove': '移除图片 {name}', @@ -447,6 +448,7 @@ export const en = { 'attachment.pathUnavailable': 'Could not obtain the folder path; drag it in again', 'attachment.pathUnsupported': 'The path contains characters a reference cannot carry; rename it and try again', 'image.pending': 'Pending images', + 'attachments.unavailable': 'Some draft attachments are no longer available; add them again', 'image.openOriginal': 'View original', 'image.openOriginalLabel': '{label}, click to view original', 'image.remove': 'Remove image {name}', @@ -852,6 +854,7 @@ export const ja = { 'attachment.pathUnavailable': 'フォルダのパスを取得できませんでした。もう一度ドラッグしてください', 'attachment.pathUnsupported': 'パスに参照できない文字が含まれています。名前を変更して再試行してください', 'image.pending': '保留中の画像', + 'attachments.unavailable': '一部の下書き添付ファイルは利用できなくなりました。再度追加してください', 'image.openOriginal': '元の画像を表示', 'image.openOriginalLabel': '{label}、クリックで元の画像を表示', 'image.remove': '画像{name}を削除', @@ -1255,6 +1258,7 @@ export const es = { 'attachment.pathUnavailable': 'No se pudo obtener la ruta de la carpeta; arrástralo de nuevo', 'attachment.pathUnsupported': 'La ruta contiene caracteres que una referencia no puede contener; cámbiale el nombre y vuelve a intentarlo.', 'image.pending': 'Imágenes pendientes', + 'attachments.unavailable': 'Algunos adjuntos del borrador ya no están disponibles; vuelve a añadirlos', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, haga clic para ver el original', 'image.remove': 'Eliminar imagen {name}', @@ -1660,6 +1664,7 @@ export const fr = { 'attachment.pathUnavailable': "Impossible d'obtenir le chemin du dossier ; fais-le glisser à nouveau", 'attachment.pathUnsupported': "Le chemin contient des caractères qu'une référence ne peut pas transporter ; renommez-le et réessayez", 'image.pending': 'Images en attente', + 'attachments.unavailable': 'Certaines pièces jointes du brouillon ne sont plus disponibles ; ajoutez-les à nouveau', 'image.openOriginal': "Voir l'original", 'image.openOriginalLabel': "{label}, cliquez pour voir l'original", 'image.remove': "Supprimer l'image {name}", @@ -2065,6 +2070,7 @@ export const de = { 'attachment.pathUnavailable': 'Der Ordnerpfad konnte nicht abgerufen werden; Ziehen Sie es erneut hinein', 'attachment.pathUnsupported': 'Der Pfad enthält Zeichen, die eine Referenz nicht enthalten kann; Benennen Sie es um und versuchen Sie es erneut', 'image.pending': 'Ausstehende Bilder', + 'attachments.unavailable': 'Einige Entwurfsanhänge sind nicht mehr verfügbar; füge sie erneut hinzu', 'image.openOriginal': 'Original ansehen', 'image.openOriginalLabel': '{label}, klicken Sie, um das Original anzuzeigen', 'image.remove': 'Bild {name} entfernen', @@ -2470,6 +2476,7 @@ export const ru = { 'attachment.pathUnavailable': 'Не удалось получить путь к папке; перетащите это снова', 'attachment.pathUnsupported': 'Путь содержит символы, которые не может содержать ссылка; переименуй его и попробуй еще раз', 'image.pending': 'Ожидающие изображения', + 'attachments.unavailable': 'Некоторые вложения черновика больше недоступны; добавьте их снова', 'image.openOriginal': 'Посмотреть оригинал', 'image.openOriginalLabel': '{label}, нажмите, чтобы посмотреть оригинал', 'image.remove': 'Удалить изображение {name}', @@ -2875,6 +2882,7 @@ export const pt = { 'attachment.pathUnavailable': 'Não foi possível obter o caminho da pasta; arraste-o novamente', 'attachment.pathUnsupported': 'O caminho contém caracteres que uma referência não pode transportar; renomeie-o e tente novamente', 'image.pending': 'Imagens pendentes', + 'attachments.unavailable': 'Alguns anexos do rascunho não estão mais disponíveis; adicione-os novamente', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, clique para ver o original', 'image.remove': 'Remover imagem {name}', diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index b0907447c6..efbf311ef6 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 27cae036db..98454ba0f0 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -158,6 +158,10 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() + /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ + private readonly sessionDraftIds = new Map>() + /** Reverse ownership lookup for release and Workspace rebinding. */ + private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -196,6 +200,8 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() + this.sessionDraftIds.clear() + this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -279,6 +285,11 @@ export class ConversationController extends Service implements IConversation { ) // The composer owns the attachments until the Host accepts the prompt. const ownership = { accepted: false, retiredUnobserved: false } + // An accepted message's attachments leave the draft: a later composer must not re-adopt them, while + // the registry keeps them until the echo settles their previews or an unobserved retirement releases them. + const disownAccepted = (): void => { + for (const attachment of attachments) this.forgetDraftAttachment(attachment.id) + } const acceptance = Promise.withResolvers() const submission = session.beginSubmission({ mode, @@ -286,6 +297,7 @@ export class ConversationController extends Service implements IConversation { attachments: pendingAttachments, onAccept: () => { ownership.accepted = true + disownAccepted() accept?.() acceptance.resolve(undefined) }, @@ -309,6 +321,7 @@ export class ConversationController extends Service implements IConversation { const result = await Promise.race([session.prompt(content, mode, signal, submission.requestId), acceptance.promise]) if (result !== undefined && !result.ok) return { kind: 'error' } ownership.accepted = true + disownAccepted() // An accepted prompt whose echo already retired unobserved, as when its queue entry was removed. if (ownership.retiredUnobserved) this.releaseDraftAttachments(attachments) return { kind: 'success' } @@ -332,6 +345,7 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -342,6 +356,7 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -369,6 +384,7 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue + this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -504,11 +520,59 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) + this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } + /** + * Draft attachment ids a Session still owns after its composer retired. + * @param sessionId - owning Session identity. + * @returns registered ids in registration order. + */ + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { + return [...this.sessionDraftIds.get(sessionId) ?? []] + } + + /** + * Sessions that still own registered draft attachments. + * @returns Session identities with at least one registered attachment. + */ + draftAttachmentSessions(): readonly SessionId[] { + return [...this.sessionDraftIds.keys()] + } + + /** + * Release every draft attachment one removed Session owns. + * @param sessionId - removed Session identity. + */ + releaseDraftSession(sessionId: SessionId): void { + for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) + } + + /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ + private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { + this.forgetDraftAttachment(id) + this.draftAttachmentSession.set(id, sessionId) + let ids = this.sessionDraftIds.get(sessionId) + if (ids === undefined) { + ids = new Set() + this.sessionDraftIds.set(sessionId, ids) + } + ids.add(id) + } + + /** Forget one draft attachment's owning Session. */ + private forgetDraftAttachment(id: DraftAttachmentId): void { + const sessionId = this.draftAttachmentSession.get(id) + if (sessionId === undefined) return + this.draftAttachmentSession.delete(id) + const ids = this.sessionDraftIds.get(sessionId) + ids?.delete(id) + if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) + } + /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -605,6 +669,7 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) + this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts new file mode 100644 index 0000000000..f758d2def7 --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,312 @@ +// @vitest-environment jsdom +// Draft attachments outlive their Session's composer: a switch keeps them registered, +// a removed Session releases them, and a page unload reports what it discarded. +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' +import { InputHub } from '../src/client/input/hub.ts' +import { ConversationController } from '../src/client/service.ts' +import { zh } from '../src/client/locales.ts' + +const SESSION = 's1' +const UNLOAD_MARK = `dsh.composer-draft-attachments-unloaded.${SESSION}` + +function sessionId(): SessionId { + return brandString(SESSION) +} + +function uploadValue(name: string): FileUploadValue { + return { + receiptId: brandString(`receipt-${name}`), + file: { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), name, bytes: 3 }, + } +} + +interface UploadBehavior { + uploadFile?: (...input: unknown[]) => Promise +} + +/** One retained Session with the production Conversation service and its input hub. */ +async function bench(prepare?: () => void) { + const runtime = await SlotTestRuntime.create() + const upload = vi.fn((id: SessionId, ...args: unknown[]) => { + const behavior = runtime.sessions.behavior(id) as UploadBehavior + if (behavior.uploadFile === undefined) throw new Error('test file upload has no Session override') + return behavior.uploadFile(...args) + }) + runtime.fileUpload.upload = upload + runtime.fileUpload.uploadImage = vi.fn(() => Promise.resolve({ ok: true as const, value: { + receiptId: brandString('receipt-image'), + image: { attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 }, + } })) + await runtime.sessions.add({ + id: SESSION, + session: { + prompt: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + updateQueue: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + cancel: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + loadOlder: vi.fn(() => Promise.resolve()), + }, + }) + prepare?.() + let reference = runtime.sessions.retain(sessionId()) + await reference.ready + const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + await runtime.ctx.plugin(ConversationController, { + input: hub, + blocks: new ComposerBlockRegistry(), + maxConcurrentFileUploads: 2, + }).await() + const root = runtime.ctx.get('conversation') as ConversationController + const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) + const shell = shellNow() + const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior + /** Retire the Session's composer, as a switch to another Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + expect(runtime.sessions.binding(SESSION)).toBeUndefined() + } + /** Mount a fresh composer for the Session again. */ + const switchBack = async () => { + reference = runtime.sessions.retain(sessionId()) + await reference.ready + return shellNow() + } + return { runtime, hub, root, shell, upload, behavior, switchAway, switchBack } +} + +function draftFile(name = 'notes.txt'): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'text/plain' }) +} + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { vi.restoreAllMocks() }) + +describe('draft attachments across a Session switch', () => { + it('re-adopts settled files and images without uploading them again', async () => { + const b = await bench() + const revoked = vi.spyOn(URL, 'revokeObjectURL') + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const drafts = b.root.createDrafts(sessionId(), [draftFile(), new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + expect(b.shell.addAttachments(drafts.map(draft => draft.id))).toBe(true) + await vi.waitFor(() => { + for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') + }) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) + expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) + expect(b.upload).toHaveBeenCalledOnce() + expect(revoked).not.toHaveBeenCalled() + expect(back.notices.getSnapshot()).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps an upload running while the Session is switched away', async () => { + const b = await bench() + try { + let finish!: (value: unknown) => void + b.behavior().uploadFile = vi.fn((...args: unknown[]) => new Promise((resolve) => { + finish = resolve + ;(args[2] as AbortSignal).addEventListener('abort', () => { resolve({ ok: false, error: new Error('aborted') }) }) + })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('uploading') }) + await b.switchAway() + finish({ ok: true, value: uploadValue('big.bin') }) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.upload).toHaveBeenCalledOnce() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a failed upload so it can be retried in place after returning', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.reject(new Error('network lost'))) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('error') }) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('big.bin') })) + b.root.retryFileUpload(sessionId(), draft.id) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('removed Sessions', () => { + it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + localStorage.setItem(UNLOAD_MARK, '1') + await b.runtime.sessions.remove(SESSION) + await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.runtime.sessions.remove(SESSION) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('page unload report', () => { + it('marks Sessions whose attachments an unload discards, and reports them on the next page', async () => { + const first = await bench() + try { + first.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = first.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + first.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + } finally { + await first.runtime.dispose() + } + // A reload starts with an empty registry; the saved mark survives in browser storage. + const second = await bench(() => { localStorage.setItem(UNLOAD_MARK, '1') }) + try { + expect(second.shell.notices.getSnapshot()).toMatchObject({ level: 'error', text: zh['attachments.unavailable'] }) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await second.runtime.dispose() + } + }) + + it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + const restore = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(restore, 'persisted', { value: false }) + window.dispatchEvent(restore) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + const cached = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(cached, 'persisted', { value: true }) + window.dispatchEvent(cached) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + localStorage.setItem(UNLOAD_MARK, '1') + await b.switchAway() + const back = await b.switchBack() + expect(back.notices.getSnapshot()).toBeNull() + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const b = await bench() + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + window.dispatchEvent(new Event('pagehide')) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('submitted attachments', () => { + it('does not re-adopt or report attachments of an accepted message whose echo has not retired', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + b.shell.setDraft('send with file') + b.shell.submit('queue', 'click') + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + await b.runtime.flush() + // The registry still holds the attachment for the echo; the draft no longer owns it. + expect(b.root.resolveDraftAttachments([draft.id])).toHaveLength(1) + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + expect(b.root.draftAttachmentSessions()).toEqual([]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) + + it('keeps the attachments of a slash line whose adjudication a switch aborted', async () => { + const adjudicate = vi.fn(() => new Promise(() => undefined)) + const b = await bench() + try { + const lexicon = { getSnapshot: () => new Map<'/' | '@', readonly string[]>(), subscribe: () => () => undefined } + const triggers = { adjudicate, lexicon, track: vi.fn() } + b.runtime.ctx.provide('inputTriggers', { sessionOf: () => triggers } as never) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + b.shell.setDraft('/review this file') + b.shell.submit('queue', 'enter') + expect(b.shell.snapshot.phase).toBe('adjudicating') + expect(adjudicate).toHaveBeenCalledOnce() + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([draft.id]) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + } finally { + await b.runtime.dispose() + } + }) +}) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index e29bf0a8e0..9b93ef4240 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -138,7 +138,7 @@ describe('ConversationController', () => { await b.runtime.dispose() }) - it('releases draft previews when their session scope is disposed', async () => { + it('keeps draft previews registered when their session scope is disposed and re-adopts them on return', async () => { const b = await bench() const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:draft-1') const revoked = vi.spyOn(URL, 'revokeObjectURL').mockReturnValue(undefined) @@ -150,8 +150,11 @@ describe('ConversationController', () => { b.root.input.for(b.runtime.sessions.scope('s1')!).addAttachments([attachment.id]) b.reference.release() await b.runtime.flush() - expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([]) - expect(revoked).toHaveBeenCalledWith('blob:draft-1') + expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([attachment]) + expect(revoked).not.toHaveBeenCalled() + const again = b.runtime.sessions.retain('s1' as SessionId) + await again.ready + expect(b.hub.shellFor(b.runtime.sessions.binding('s1')!).snapshot.attachmentIds).toEqual([attachment.id]) } finally { created.mockRestore() revoked.mockRestore() diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 3745e445aa..e851c470e1 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: ff9e353f9330cf8d - zh: 61b0656261a69d4d + en: ac56ad367cd6624f + zh: 47642dc177dd0b58 /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index b313e1e810..0776f904f4 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -27,7 +27,7 @@ The Automation tasks page and right Sidebar task tab use the same editor for tas Below 768px, the task list uses 20px horizontal insets, matching the Plugins page. -The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, seven built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. +The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, eight built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens its editable Rules / Records page. Save is enabled only for valid, meaningful changes and sends only changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. The fields stay editable after saving. Unsaved drafts survive navigation between tasks and away from the page. A conflict retains the whole draft and disables Save. Review with my edits reapplies the changed field groups to the latest values for review before saving; Discard replaces the draft with the latest stored values. For a new task, Discard closes the editor. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari. diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 3e108eb805..775887d4e7 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" 宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。 -发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出七个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 +发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出八个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 “已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。 diff --git a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx index 909ec2f016..0c5ad0ebde 100644 --- a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx +++ b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx @@ -38,6 +38,23 @@ export function SunriseGlyph(props: TileGlyphProps): ReactNode { ) } +/** + * Calendar page with a check: a week in review. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function CalendarCheckGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + /** * Open-issue mark: a ring with a center dot. * @param props - class of the root SVG. diff --git a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx index b130a538a4..8f3accdd29 100644 --- a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx +++ b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx @@ -3,13 +3,14 @@ import { useId, type ReactNode } from 'react' import { Button, IconClockOutlineRegular, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { TaskManagerKey } from './task-manager-locales.ts' import { - BranchGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, + BranchGlyph, CalendarCheckGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, SunriseGlyph, type TileGlyphProps, } from './RecommendationArtwork.tsx' import css from './TaskManagerPage.module.css' const RECOMMENDATIONS = [ { id: 'dailyBrief', Glyph: SunriseGlyph }, + { id: 'weeklyReview', Glyph: CalendarCheckGlyph }, { id: 'issueScan', Glyph: IssueGlyph }, { id: 'pluginCompat', Glyph: PluginCheckGlyph }, { id: 'topicTracking', Glyph: NewspaperGlyph }, diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts index ec965a647a..c7c685dac7 100644 --- a/packages/client/ui-schedule/src/client/recommendation-locales.ts +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -7,6 +7,10 @@ export const recommendationEn = { 'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.', 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', + 'recommend.weeklyReview.title': 'Weekly review', + 'recommend.weeklyReview.description': 'Your work in the workspace this week, with loose ends and what to do first next week.', + 'recommend.weeklyReview.schedule': 'Fridays at 16:00', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review what I did in the current workspace this week and list what is still unfinished and what to do first next week; when the workspace is a code repository, look only at my commits this week and the pull requests I opened that were merged this week or are still open. Summarize here only; do not change files in the workspace.', 'recommend.issueScan.title': 'Issue scan', 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', 'recommend.issueScan.schedule': 'Weekdays at 10:00', @@ -40,6 +44,10 @@ export const recommendationZh: Record = { 'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。', 'recommend.dailyBrief.schedule': '工作日 9:00', 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', + 'recommend.weeklyReview.title': '每周回顾', + 'recommend.weeklyReview.description': '回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.schedule': '周五 16:00', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾我这一周在当前工作区做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,只看我这周的提交,以及我提的、这周合入或还开着的 PR。只在这里汇总,不改工作区里的文件。', 'recommend.issueScan.title': 'Issue 扫描', 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', 'recommend.issueScan.schedule': '工作日 10:00', @@ -73,6 +81,10 @@ export const recommendationJa: Record = { 'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。', 'recommend.dailyBrief.schedule': '平日 9:00', 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', + 'recommend.weeklyReview.title': '週次レビュー', + 'recommend.weeklyReview.description': '今週ワークスペースで自分がしたことを振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、今週私が現在のワークスペースでしたことを振り返り、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週の私のコミットと、私が作成したプルリクエストのうち今週マージされたものとまだオープンのものだけを確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', 'recommend.issueScan.title': 'Issue スキャン', 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', 'recommend.issueScan.schedule': '平日 10:00', @@ -106,6 +118,10 @@ export const recommendationEs: Record = { 'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.', 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', + 'recommend.weeklyReview.title': 'Revisión semanal', + 'recommend.weeklyReview.description': 'Tu trabajo de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa lo que hice esta semana en el espacio de trabajo actual y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, revisa solo mis commits de esta semana y los pull requests que abrí que se fusionaron esta semana o siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', 'recommend.issueScan.title': 'Revisión de issues', 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', @@ -139,6 +155,10 @@ export const recommendationFr: Record = { 'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.', 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', + 'recommend.weeklyReview.title': 'Bilan hebdomadaire', + 'recommend.weeklyReview.description': 'Votre travail de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue ce que j\'ai fait cette semaine dans l\'espace de travail actuel et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, ne regarde que mes commits de la semaine et les pull requests que j\'ai ouvertes qui ont été fusionnées cette semaine ou sont encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', 'recommend.issueScan.title': 'Analyse des issues', 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', @@ -172,6 +192,10 @@ export const recommendationDe: Record = { 'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.', 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', + 'recommend.weeklyReview.title': 'Wochenrückblick', + 'recommend.weeklyReview.description': 'Die eigene Arbeit dieser Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.schedule': 'Freitags um 16:00', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr darauf zurück, was ich diese Woche im aktuellen Arbeitsbereich gemacht habe, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige nur meine Commits dieser Woche und die von mir eröffneten Pull Requests, die diese Woche gemergt wurden oder noch offen sind. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', 'recommend.issueScan.title': 'Issue-Sichtung', 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', @@ -205,6 +229,10 @@ export const recommendationRu: Record = { 'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.', 'recommend.dailyBrief.schedule': 'По будням в 9:00', 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', + 'recommend.weeklyReview.title': 'Еженедельный обзор', + 'recommend.weeklyReview.description': 'Ваша работа за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай мою работу за эту неделю в текущем рабочем пространстве и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай только мои коммиты за неделю и мои пул-реквесты, слитые на этой неделе или ещё открытые. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', 'recommend.issueScan.title': 'Обзор issues', 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', 'recommend.issueScan.schedule': 'По будням в 10:00', @@ -238,6 +266,10 @@ export const recommendationPt: Record = { 'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.', 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', + 'recommend.weeklyReview.title': 'Revisão semanal', + 'recommend.weeklyReview.description': 'Seu trabalho da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.schedule': 'Sextas às 16:00', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise o que eu fiz esta semana no espaço de trabalho atual e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, veja só os meus commits da semana e os pull requests que eu abri que foram mesclados esta semana ou continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', 'recommend.issueScan.title': 'Varredura de issues', 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', diff --git a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts index b3a9ef6d76..acc5f78520 100644 --- a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts @@ -461,14 +461,14 @@ describe('ui-schedule browser half', () => { const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected for (const dictionary of Object.values(managerLocales)) { const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt')) - expect(prompts).toHaveLength(7) + expect(prompts).toHaveLength(8) for (const [, prompt] of prompts) { expect(prompt).not.toContain('\n') panel.onUseRecommendation(prompt) expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' }) } } - expect(startSession).toHaveBeenCalledTimes(56) + expect(startSession).toHaveBeenCalledTimes(64) } finally { await fiber.dispose() owner() @@ -479,7 +479,7 @@ describe('ui-schedule browser half', () => { it('states each recommendation\'s shown run time in its request in every language', () => { for (const dictionary of Object.values(managerLocales)) { const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule')) - expect(schedules).toHaveLength(7) + expect(schedules).toHaveLength(8) for (const [key, schedule] of schedules) { const times = schedule.match(/\d{1,2}:\d{2}/g) expect(times).toHaveLength(1) diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 33eb9e2628..cc26dccb0d 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -840,8 +840,8 @@ describe('Task manager catalog', () => { expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) }) - const RECOMMENDATION_IDS = ['dailyBrief', 'issueScan', 'pluginCompat', 'topicTracking', 'branchCleanup', - 'weather', 'workout'] as const + const RECOMMENDATION_IDS = ['dailyBrief', 'weeklyReview', 'issueScan', 'pluginCompat', 'topicTracking', + 'branchCleanup', 'weather', 'workout'] as const function recommendations(dictionary: Dictionary = en): HTMLElement | null { return screen.queryByRole('region', { name: dictionary['recommend.heading'] }) diff --git a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx index e52ff7d10f..c3e14750fe 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx @@ -1,6 +1,7 @@ // Office toolview links target the input, not the temporary output. Rows show the // result's text blocks; rendered page images reach the model but are not displayed. +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '@deepseek-ai/cordis' import { toolFileInject } from '../file-menu.ts' @@ -26,7 +27,7 @@ export function OfficeRow({ const row = toolRowModel(toolName, block, cwd, home) // Image blocks flatten to JSON attachment references, so a settled result with only images shows no body. const output = 'kind' in block - ? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null + ? extractTextContent(block.content, { separator: '\n' }) || null : row.output const path = office.filePath return ( diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index b9f83f8140..4864b7d1c1 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -105,7 +105,7 @@ function candidateKeys({ record, label, displayTitle }: LabelledCandidate): Sear /** Exact-read consumer that prepares immutable cross-session message context. */ export class SessionReferenceResolver extends TypertRemoteService { - static inject = ['sessionQuery'] + static inject = ['sessionQuery', 'sessions', 'sessionProjections'] static Config: z = z.object({ maxReferences: z.number().step(1).min(1).max(MAX_REFERENCES).default(MAX_REFERENCES), candidateLimit: z.number().step(1).min(1).default(DEFAULT_CANDIDATE_LIMIT), @@ -272,17 +272,13 @@ export class SessionReferenceResolver extends TypertRemoteService { private projectedLabels( items: readonly T[], ): Array { - const projections = this.ctx.get('sessionProjections') - const sessions = this.ctx.get('sessions') - // An attached session answers from its live cut only while the registry is mounted. - const attached = new Map(sessions === undefined || projections === undefined - ? undefined - : sessions.list().map(session => [session.id, session])) + const projections = this.ctx.sessionProjections + const attached = new Map(this.ctx.sessions.list().map(session => [session.id, session])) const cache = this.ctx.get('sessionProjectionCache') const cachedSnapshot = cache?.cachedSnapshot.bind(cache) return items.map((item) => { const session = attached.get(item.record.header.id) - const snapshot = session !== undefined && projections !== undefined + const snapshot = session !== undefined ? projections.snapshot(session, LABEL_KEYS) : cachedSnapshot?.(item.record.header, LABEL_KEYS) const label = titleOf(snapshot) ?? item.record.header.id diff --git a/packages/context/session-reference/src/projection.ts b/packages/context/session-reference/src/projection.ts index 196c75b4e1..f747f242c3 100644 --- a/packages/context/session-reference/src/projection.ts +++ b/packages/context/session-reference/src/projection.ts @@ -1,5 +1,7 @@ /** Current-surface projection and byte-bounded rendering. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction' import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected case 'user/message': { const checkpoint = isCompactCheckpointSource(event.data.source) if (!checkpoint && event.data.source.kind !== 'user') break - const text = textContent(event.data.content) + const text = extractTextContent(event.data.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 }) break } case 'assistant/message': { - const text = textContent(event.data.message.content) + const text = extractTextContent(event.data.message.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 }) break } @@ -145,10 +147,6 @@ export function retainReferencedSession( } } -function textContent(content: readonly { type: string; text?: string }[]): string { - return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n') -} - function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } { /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */ if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 } diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index 65971a21c7..db9fc4e870 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -493,6 +493,7 @@ describe('model-relative reference budgets', () => { const ctx = new Context() contexts.push(ctx) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) const resolverFiber = ctx.plugin(SessionReferenceResolver, config) await resolverFiber @@ -820,9 +821,10 @@ describe('session reference discovery and preparation', () => { vi.restoreAllMocks() }) - it('labels every session by id when no projection face is composed', async () => { + it('labels every session by id when no title projection is registered', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) await ctx.plugin(SessionReferenceResolver) const target = ctx.sessions.create(brandString('target'), { meta: { cwd: '/same' } }) @@ -1317,18 +1319,21 @@ describe('session reference discovery and preparation', () => { it('rejects direct invalid configuration before service publication', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(ctx, { maxReferences: 0 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const oversizedCtx = new Context() await oversizedCtx.plugin(SessionStore) + await oversizedCtx.plugin(SessionProjectionRegistry) await oversizedCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(oversizedCtx, { maxReferences: 4 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const defaultCtx = new Context() await defaultCtx.plugin(SessionStore) + await defaultCtx.plugin(SessionProjectionRegistry) await defaultCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(defaultCtx)).not.toThrow() }) diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 9cffc34185..ac1a7000e6 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' @@ -621,7 +622,7 @@ export function createRunCodeTransport( if (first !== undefined && images.length === 1) return programImage(first.attachment) if (outcome.imageRemoved) { throw new Error('Image output was removed by a tool output policy.\n' - + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + + extractTextContent(outcome.content, { separator: '\n' })) } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index 9ba715bf16..ce84b76250 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -30,8 +30,8 @@ describe('gen-tool-catalog collectToolCatalog', () => { 'apply_patch', 'ask_user_question', 'bash', 'bash', 'cordis_inspect', 'create_goal', 'create_worktree', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', - 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', - 'list_subagent_models', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', + 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', 'list_session', + 'list_subagent_models', 'list_workspace', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', 'read', 'read_image', 'read_mcp_resource', 'run_code', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index e91e618dbb..dba7fbda86 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -17,6 +17,7 @@ import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' import { brandString } from '@deepseek-ai/dsh-brand' import { HarnessError } from '@deepseek-ai/dsh-error' import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' import type { WorkingDirectoryService } from '@deepseek-ai/dsh-working-directory' @@ -116,17 +117,13 @@ function requireAgent(context: OpContext, op: string): Agent { return agent } -function textOf(content: readonly ContentBlock[]): string { - return content.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** * Project one tool outcome onto Claude Code's `tool.call` result. * @param result - the harness tool outcome. * @returns its text as `result`, with `isError` on a failure. */ export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult { - return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) } + return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) } } /** The model's raw JSON arguments as an object; an unparsable string is an empty input. */ @@ -146,7 +143,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases) const toolUses = message.content .filter((block): block is Extract => block.type === 'tool-call') .map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) })) - out.push({ role: message.role, text: textOf(message.content), toolUses }) + out.push({ role: message.role, text: extractTextContent(message.content), toolUses }) } return out } diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index 38821d2366..08398f4b0b 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-working-directory' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -78,10 +79,6 @@ function assertPositive(field: string, value: number): void { if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`) } -function textOf(blocks: readonly ContentBlock[]): string { - return blocks.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */ function promptMessages(claimed: readonly UserMessage[]): UserMessage[] { return claimed.filter(message => message.source.kind === 'user') @@ -141,7 +138,7 @@ interface TurnRecord { /** Fold one committed assistant message into the turn's answer and usage. */ function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void { - turnRecord.answer = textOf(data.message.content) + turnRecord.answer = extractTextContent(data.message.content) if (data.usage === undefined) return const { model } = data.message.source const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model } @@ -349,7 +346,7 @@ export class ClaudeCodeMods extends TypertRemoteService { const first = !started.has(turn) started.add(turn) const prompt = promptMessages(messages) - const text = textOf(prompt.flatMap(message => message.content)) + const text = extractTextContent(prompt.flatMap(message => message.content)) let submitted: PromptSubmitResult = { text } // A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts. if (prompt.length > 0) { diff --git a/packages/experimental/client-ui-stats/src/client/stats-fold.ts b/packages/experimental/client-ui-stats/src/client/stats-fold.ts index 365a7873f1..fd7c6d78e8 100644 --- a/packages/experimental/client-ui-stats/src/client/stats-fold.ts +++ b/packages/experimental/client-ui-stats/src/client/stats-fold.ts @@ -1,5 +1,6 @@ /** Event folding and per-step metric derivation for the Statistics table. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm' @@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9 export function triggerSenderOf(message: UserMessage): string | null { const kind: string = message.source.kind if (kind !== 'agent-message' && kind !== 'team-message') return null - let text = '' - for (const block of message.content) { - if (block.type === 'text') text += block.text - } + const text = extractTextContent(message.content) const team = TEAM_MESSAGE_PREFIX.exec(text) /* v8 ignore next -- a matched capture group is always present. */ if (team !== null) return team[1]?.trim() ?? null @@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): { body: string truncated: boolean } | null { - const parts: string[] = [] - for (const block of message.content) { - if (block.type === 'text') parts.push(block.text) - } - const text = parts.join('\n').trim() + const text = extractTextContent(message.content, { separator: '\n' }).trim() if (text === '') return null return { preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text, diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 39e9f04e49..a7317d8e38 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -30,6 +30,7 @@ enum NativeProtocol { "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ @@ -40,5 +41,6 @@ enum NativeProtocol { "requestPermission": ["permission": ["accessibility", "screenRecording"]], "selectText": ["selectionType": ["cursor_after", "cursor_before", "text"]], "sendKeyEvent": ["direction": ["down", "up"]], + "toggleMouse": ["direction": ["down", "up"], "mouseButton": ["left", "middle", "right"]], ] } diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 801414e010..472c3f3b80 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 332d36f163..20f5257334 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,6 +13,7 @@ function operationGuidance(treeAdvice: string): string { ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], + ['toggleMouse', 'Not implemented on macOS.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f31ca9e6b7..3fb53d70e3 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,4 +1,4 @@ -/** Model-facing guidance enumerates the full available object API without unavailable operations. */ +/** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' @@ -9,7 +9,7 @@ const accessibilityNames: Array> = [ 'getAccessibilityTree', 'listActions', 'invoke', 'performAction', 'setValue', 'selectText', ] const appNames: Array = ['appHandle', 'activate', 'getWindows', 'getWindow'] -const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'click', 'scroll', 'drag'] +const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'toggleMouse', 'click', 'scroll', 'drag'] it('keeps file-tool instructions in PTC and limits the program guidance to available bindings', () => { for (const name of ['tools.write', 'tools.grep', 'tools.read']) { @@ -20,11 +20,13 @@ it('keeps file-tool instructions in PTC and limits the program guidance to avail expect(PROGRAM_GUIDANCE).toContain('session’s file tools') }) -it('keeps exactly three ordered operation headings', () => { - const heads = COMMON_GUIDANCE.match(/^## .+$/gm) - expect(heads).toEqual(['## Accessibility tree', '## Simulated mouse', '## Simulated keyboard']) - expect(COMMON_GUIDANCE.indexOf('## Accessibility tree')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated mouse')) - expect(COMMON_GUIDANCE.indexOf('## Simulated mouse')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated keyboard')) +it('places observation chapters before simulated input with screenshots in their own chapter', () => { + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog.match(/^## .+$/gm)).toEqual(['## Accessibility tree', '## Screenshots', '## Simulated mouse', '## Simulated keyboard']) + const screenshots = catalog.slice(catalog.indexOf('## Screenshots'), catalog.indexOf('## Simulated mouse')) + expect(screenshots).toContain('- getScreenshot() -> Image') + expect(catalog.slice(catalog.indexOf('## Simulated mouse'))).not.toContain('- getScreenshot(') + } }) it('prefixes concise platform guidance before the shared catalog', () => { @@ -67,7 +69,23 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { } }) -it('enumerates every available method once in its catalog entry', () => { +it('documents explicit mouse-button events immediately after mouseMove', () => { + const lines = COMMON_GUIDANCE.split('\n') + const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) + expect(lines[index - 1]).toMatch(/^- mouseMove\(/) + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) + expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) +}) + +it.each([GUIDANCE, PROGRAM_GUIDANCE])('marks toggleMouse as unavailable in the macOS method entry', (catalog) => { + const shared = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- toggleMouse(')) + const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(entry).toBe(`${shared} Not implemented on macOS.`) + expect(PLATFORM_GUIDANCE).not.toContain('toggleMouse') +}) + +it('enumerates every public method once in its catalog entry', () => { const signatures = [ ...apiNames.map(name => `cua.${name}(`), ...appNames.filter(name => name !== 'appHandle').map(name => `app.${name}(`), @@ -79,8 +97,8 @@ it('enumerates every available method once in its catalog entry', () => { for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { for (const signature of signatures) expect(catalog.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) } - expect(signatures).toHaveLength(25) - expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(24) + expect(signatures).toHaveLength(26) + expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(25) expect(COMMON_GUIDANCE).toContain('app.appHandle') expect(COMMON_GUIDANCE).toContain('window.windowId') }) @@ -128,7 +146,8 @@ it('references Modifier without defining its members in shared guidance', () => }) it('states platform-dependent levels without qualifying grouped method names', () => { - expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for screenshots and pointer input.') + expect(COMMON_GUIDANCE).toContain('## Screenshots\nUse an explicit window for screenshots.') + expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for pointer input.') for (const heading of ['Accessibility tree', 'Simulated keyboard']) { expect(COMMON_GUIDANCE).toContain(`## ${heading}\nAvailable at app or window level depending on the platform.`) } @@ -139,6 +158,15 @@ it('states platform-dependent levels without qualifying grouped method names', ( expect(COMMON_GUIDANCE).toContain('from: [number, number]') }) +it('guides complex input combinations through platform-supported primitive operations', () => { + const advice = 'click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.' + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog).toContain(advice) + expect(catalog.indexOf(advice)).toBeGreaterThan(catalog.indexOf('- sendKeyEvent(')) + expect(catalog.indexOf(advice)).toBeLessThan(catalog.indexOf('Raw tools use { method, params }')) + } +}) + it('keeps consent, lock, observation, and no-replay rules', () => { expect(COMMON_GUIDANCE).toContain('consent') expect(COMMON_GUIDANCE).toContain('SESSION_LOCKED') @@ -159,6 +187,6 @@ it('documents explicit inspection and separate key arguments', () => { expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) -it('omits stale names and unavailable platform operations', () => { - for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) +it('omits stale names and unrelated operations', () => { + for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs']) expect(GUIDANCE).not.toContain(stale) }) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 58421dec24..3371433909 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,7 @@ internal sealed class FixtureForm : Form internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; + private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); internal FixtureForm(string title) @@ -22,13 +23,55 @@ internal sealed class FixtureForm : Form Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; + button.MouseDown += (_, e) => Count(e.Button, down: true); + button.MouseUp += (_, e) => Count(e.Button, down: false); + Editor.MouseDown += (_, e) => Count(e.Button, down: true); + Editor.MouseUp += (_, e) => Count(e.Button, down: false); tooltip.SetToolTip(button, "CUA hover is retained"); } + private void Count(MouseButtons pressed, bool down) + { + switch (pressed) + { + case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; + case MouseButtons.Right: if (down) rightDowns++; else rightUps++; break; + case MouseButtons.Middle: if (down) middleDowns++; else middleUps++; break; + } + } + + internal void PointAtButton() => Cursor.Position = button.PointToScreen(new Point(button.Width / 2, button.Height / 2)); + + internal void PointOutside() + { + var bounds = RectangleToScreen(ClientRectangle); + Cursor.Position = new Point(bounds.Right + 40, bounds.Top + 20); + } + + internal void Cover(FixtureForm cover) + { + cover.Bounds = Bounds; + cover.TopMost = true; + cover.Show(); + Activate(); + PointAtButton(); + } + + internal void Uncover(FixtureForm cover) + { + if (cover.Visible) cover.Hide(); + cover.TopMost = false; + Activate(); + PointAtButton(); + } + internal object Inspect() => new { text = Editor.Text, clicks, window = Handle.ToString(CultureInfo.InvariantCulture), foreground = GetForegroundWindow().ToString(CultureInfo.InvariantCulture), cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + under = GetAncestor(WindowFromPoint(Cursor.Position), 2).ToString(CultureInfo.InvariantCulture), + downs = new { left = leftDowns, right = rightDowns, middle = middleDowns }, + ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, @@ -41,12 +84,31 @@ internal sealed class FixtureForm : Form } [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); } internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + private static void ReleaseButtons() + { + var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } + .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) + { + Console.Error.WriteLine("Fixture could not release every mouse button"); + Environment.ExitCode = 1; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct MouseInput { public int X, Y; public uint Data, Flags, Time; public nuint ExtraInfo; } + + [StructLayout(LayoutKind.Sequential)] + private struct Input { public uint Type; public MouseInput Data; } + [STAThread] private static void Main() { @@ -68,6 +130,11 @@ internal static class Program case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "pointer": form.PointAtButton(); Write(form.Inspect()); break; + case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; + case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; + case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; + case "release-input": ReleaseButtons(); Write(form.Inspect()); break; case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; case "hide": form.Hide(); Write(form.Inspect()); break; case "resize": form.Width += 50; Write(form.Inspect()); break; @@ -93,4 +160,7 @@ internal static class Program [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool AllowSetForegroundWindow(uint processId); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint SendInput(uint count, [In] Input[] inputs, int size); } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 666bd9c48a..6af36d042f 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -169,6 +169,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } + case "toggleMouse": + { + var target = Selected(app, parameters, context); + Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); + return ActionResult(foreground); + } case "scroll": { var target = Coordinate(app, parameters, context); diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 7493acc990..9d186055d5 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -162,6 +162,18 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } + internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + { + var flags = Button(button); + if (direction == "down") + { + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + } + else Windows.RequireForeground(app, window, context); + Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + } + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) { if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index bb03a5a331..22763d1b61 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 1a76604edb..520a805ab6 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -56,6 +56,28 @@ foreach (var method in new[] { "listActions", "performAction", "invoke", "mouseM }))); Check(operation.Params.GetProperty("elementId").GetString() == "42/-7/9", "Element operations preserve slash-separated RuntimeIds: " + method); } +foreach (var mouseButton in new[] { "left", "right", "middle" }) +foreach (var direction in new[] { "down", "up" }) +{ + var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new + { + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, + }))); + Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton + && toggle.Params.GetProperty("direction").GetString() == direction, + "Mouse-button events retain the explicit button and direction"); +} +foreach (var invalid in new[] +{ + """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","windowId":"1","direction":"down"}""", + """{"appHandle":"app","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", +}) + Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); + var launch = NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")); Check(launch.Method == "launchApp" && launch.Params.GetProperty("appHandle").GetString() == "pending", "Host launch continuation retains the selected application handle"); diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 8e63904c91..3be20956f5 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -14,7 +14,7 @@ const CAPABILITIES: CuaStartupCapabilities = { platform: 'windows', methods: [ 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', - 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'toggleMouse', 'click', 'setValue', 'selectText', 'typeText', 'paste', 'pressKey', 'sendKeyEvent', 'scroll', 'drag', 'screenshot', ], appLevelAccessibility: false, diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts new file mode 100644 index 0000000000..25a37bb8e2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -0,0 +1,145 @@ +/** Opt-in real Windows mouse-button toggles through the native helper. */ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { createInterface } from 'node:readline' +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const fixturePath = process.env.DSH_CUA_DESKTOP_TEST_FIXTURE +const Counts = z.object({ left: z.number().int(), right: z.number().int(), middle: z.number().int() }) +const FixtureState = z.object({ + window: z.string(), foreground: z.string(), + cursor: z.object({ x: z.number().int(), y: z.number().int() }), + under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, +}) +const Initial = z.object({ pid: z.number().int(), state: FixtureState }) +const Cover = z.object({ form: FixtureState, sibling: FixtureState }) +const App = z.object({ appHandle: z.string(), running: z.boolean() }) +const Windows = z.array(z.object({ windowId: z.string(), title: z.string() })) +const ToggleResult = z.object({ dispatched: z.boolean() }) + +interface Fixture { + readonly child: ChildProcessWithoutNullStreams + readonly exit: Promise + read(schema: z.ZodType): Promise + command(text: string, schema: z.ZodType): Promise +} + +function fixtureProcess(path: string): Fixture { + const child = spawn(path, [], { windowsHide: true }) + child.stderr.pipe(process.stderr) + const reader = createInterface({ input: child.stdout }) + const iterator = reader[Symbol.asyncIterator]() + const exit = new Promise((resolve) => { + child.once('error', (error) => { reader.close(); resolve(error) }) + child.once('exit', (code, signal) => { + reader.close() + resolve(code === 0 ? undefined : new Error(`Fixture exited with code ${code}, signal ${signal}`)) + }) + }) + const read = async (schema: z.ZodType): Promise => { + const next = await iterator.next() + if (next.done) throw new Error('The fixture exited before replying') + return schema.parse(JSON.parse(next.value)) + } + return { child, exit, read, command: async (text, schema) => { child.stdin.write(text + '\n'); return read(schema) } } +} + +async function releaseAndClose(fixture: Fixture): Promise { + let forced = false + const timer = setTimeout(() => { forced = true; fixture.child.kill() }, 5000) + try { + if (fixture.child.exitCode === null && fixture.child.signalCode === null && fixture.child.pid !== undefined) { + // The fixture processes release before close even if an earlier inspection is still awaiting its reply. + fixture.child.stdin.end('release-input\nclose\n') + } + const error = await fixture.exit + if (forced) throw new Error('Fixture shutdown timed out; mouse-button release could not be confirmed', { cause: error }) + if (error) throw error + } finally { clearTimeout(timer) } +} + +it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( + 'toggles mouse buttons without movement, observation, or implicit release', + async ({ onTestFinished, signal }) => { + const fixture = fixtureProcess(fixturePath!) + const ctx = new Context() + const cleanups: Array<() => Promise> = [] + onTestFinished(async () => { + const errors: unknown[] = [] + for (const cleanup of [ + () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ]) { + try { await cleanup() } catch (error) { errors.push(error) } + } + if (errors.length > 0) throw new AggregateError(errors, 'Desktop mouse test cleanup failed') + }) + const inspect = () => fixture.command('inspect', FixtureState) + const observed = async (expected: object) => { + let state = await inspect() + await expect.poll(async () => { state = await inspect(); return state }, { timeout: 5000, interval: 25 }).toMatchObject(expected) + return state + } + const initial = await fixture.read(Initial) + const focused = await fixture.command('focus', FixtureState) + expect(focused.window).toBe(initial.state.window) + expect(focused.foreground, 'Windows denied foreground to the private fixture').toBe(focused.window) + expect(focused.buttons).toBe('None') + + await ctx.plugin(LocalSubprocessRuntime) + const nativeRuntime = new WindowsNativeRuntime(ctx, 25, 1000, 'pipe') + cleanups.push(() => nativeRuntime.dispose()) + const native = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => native.dispose()) + const app = App.parse(await native.request('getApp', { selector: fixturePath! }, signal)) + expect(app.running).toBe(true) + const windows = Windows.parse(await native.request('listWindows', { appHandle: app.appHandle }, signal)) + const windowId = initial.state.window + expect(windows.some(window => window.windowId === windowId)).toBe(true) + const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) + + const { cursor } = await fixture.command('pointer', FixtureState) + for (const mouseButton of ['left', 'right', 'middle'] as const) { + const before = await inspect() + expect((await toggle(mouseButton, 'down')).dispatched).toBe(true) + const down = await observed({ cursor, buttons: { left: 'Left', right: 'Right', middle: 'Middle' }[mouseButton], + downs: { [mouseButton]: before.downs[mouseButton] + 1 }, ups: before.ups }) + await native.request('getCapabilities', {}, signal) + expect(await inspect()).toMatchObject({ cursor, buttons: down.buttons, ups: down.ups }) + expect((await toggle(mouseButton, 'up')).dispatched).toBe(true) + await observed({ cursor, buttons: 'None', ups: { [mouseButton]: down.ups[mouseButton] + 1 }, + clicks: down.clicks + (mouseButton === 'left' ? 1 : 0) }) + } + + const sibling = await fixture.command('sibling', FixtureState) + expect(sibling.foreground).toBe(sibling.window) + const background = await inspect() + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'FOREGROUND_REQUIRED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: background.downs }) + const restored = await fixture.command('focus', FixtureState) + expect(restored.foreground).toBe(restored.window) + + const cover = await fixture.command('cover', Cover) + expect(cover.form.foreground).toBe(cover.form.window) + expect(cover.form.under).toBe(cover.sibling.window) + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'WINDOW_OBSCURED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: cover.form.downs }) + const uncovered = await fixture.command('uncover', FixtureState) + expect(uncovered.foreground).toBe(uncovered.window) + + expect((await toggle('left', 'down')).dispatched).toBe(true) + const pressed = await observed({ buttons: 'Left', downs: { left: uncovered.downs.left + 1 } }) + const outside = await fixture.command('pointer-outside', FixtureState) + expect(outside.cursor).not.toEqual(pressed.cursor) + expect(outside.foreground).toBe(outside.window) + expect(outside.under).not.toBe(outside.window) + expect((await toggle('left', 'up')).dispatched).toBe(true) + await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index 3f2dc48b47..e90acbbf49 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,6 +31,12 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text + .split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") + expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') + expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') const batch = await ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString('invalid-window'), name: 'cua', diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 9e8c2601bf..dcee6fa104 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -49,6 +49,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.permissionParameters('requestPermission', 'accessibility', 'en')).toEqual({ permission: 'accessibility' }) expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') + expect(backend.capabilities.methods).toContain('toggleMouse') expect(backend.sendKeyEvent).toBeUndefined() const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 319b2888f6..7e98c2a041 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -191,6 +191,9 @@ function createCuaObjects(call: ReturnType): { const [x, y] = targetPoint return HoverResult.parse(await base.call('mouseMove', { ...coordinateParams(appHandle, windowId), x, y, ...relative }, options)) }, + async toggleMouse(mouseButton, direction) { + return base.action('toggleMouse', { mouseButton, direction }) + }, async click(targetPoint, options) { const mouseButton = options?.mouseButton ?? 'left' const clickCount = options?.clickCount ?? 1 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 35524cf70d..de995fa93e 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -36,10 +36,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -53,6 +57,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` /** diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 081ff2adc4..7ee5d6f017 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -72,6 +72,7 @@ function requestSchema(hover: H, drag: operation('listActions', snapshot), operation('performAction', { ...snapshot, action: z.string().min(1), argument: jsonValue.optional() }), operation('invoke', snapshot), + operation('toggleMouse', { ...window, mouseButton: pointer.mouseButton.unwrap(), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('mouseMove'), params: hover }).strict(), z.object({ method: z.literal('click'), params: z.union([ z.object({ ...snapshot, ...click }).strict(), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 4c6d173c24..b38229c220 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -62,7 +62,7 @@ export interface CuaCoordinateOptions { export type CuaShowResult = z.output /** Modifiers attached to a window-directed pointer gesture. */ export type CuaPointerModifier = NonNullable['modifiers']>[number] -/** Buttons supported by window-directed clicks and drags. */ +/** Buttons supported by window-directed mouse input. */ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. @@ -191,6 +191,14 @@ export interface CuaWindow extends CuaSurface { */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise + /** + * Send one mouse-button down or up event without moving the pointer. + * Does not send the opposite event; callers explicitly release a pressed button. + * @param mouseButton - Mouse button to press or release. + * @param direction - Explicit event direction. + * @returns Whether the provider successfully executed the requested operation. + */ + toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up'): Promise /** * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index c17a0ea7b7..de8325bfb2 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -953,6 +953,38 @@ describe('input actions', () => { expect(windowFixture.dispatch).not.toHaveBeenCalled() }) + it.each(['left', 'right', 'middle'] as const)('dispatches one %s mouse-button event without an observation', async (mouseButton) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow('23') + expect(app).not.toHaveProperty('toggleMouse') + expectTypeOf().not.toHaveProperty('toggleMouse') + expectTypeOf().parameters.toEqualTypeOf<[ + mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', + ]>() + for (const direction of ['down', 'up'] as const) { + f.dispatch.mockClear() + await expect(window.toggleMouse(mouseButton, direction)).resolves.toEqual(delivered) + expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ method: 'toggleMouse', params: { + appHandle: 'app-17', windowId: '23', mouseButton, direction, + } }) + } + }) + + it('preserves mouse-button dispatch failures without retries or an opposite event', async () => { + const f = fixture() + const window = await (await f.api.getApp('Editor')).getWindow('23') + f.dispatch.mockClear() + f.dispatch.mockResolvedValueOnce({ dispatched: false }) + await expect(window.toggleMouse('left', 'down')).resolves.toEqual({ dispatched: false }) + const failure = new Error('Mouse-button input is not supported') + f.dispatch.mockRejectedValueOnce(failure) + await expect(window.toggleMouse('left', 'up')).rejects.toBe(failure) + f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) + await expect(window.toggleMouse('right', 'up')).rejects.toThrow() + expect(f.dispatch).toHaveBeenCalledTimes(3) + }) + it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/packages/experimental/cua/tests/native-schema.spec.ts b/packages/experimental/cua/tests/native-schema.spec.ts index eca0803ce5..68689e2a16 100644 --- a/packages/experimental/cua/tests/native-schema.spec.ts +++ b/packages/experimental/cua/tests/native-schema.spec.ts @@ -57,6 +57,13 @@ it('admits key events with only an explicit direction enum', () => { expect(native.enums.get('sendKeyEvent')?.has('key') ?? false).toBe(false) }) +it('admits mouse-button events with explicit button and direction enums and no coordinates', () => { + const native = nativeProtocol() + expect(native.fields.get('toggleMouse')).toEqual(new Set(['appHandle', 'windowId', 'mouseButton', 'direction'])) + expect(native.enums.get('toggleMouse')?.get('mouseButton')).toEqual(new Set(['left', 'right', 'middle'])) + expect(native.enums.get('toggleMouse')?.get('direction')).toEqual(new Set(['down', 'up'])) +}) + it('accepts a parameter-free object schema without a properties dictionary', () => { replacements.values.set(0, { properties: { method: { const: 'getCapabilities' }, params: { type: 'object' } } }) expect(nativeProtocol().fields.get('getCapabilities')).toEqual(new Set()) diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 8067bb10c4..9716a5ff5e 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -71,6 +71,28 @@ it('admits arbitrary key names with an explicit key-event direction', () => { expect(Request.parse(request)).toEqual(request) }) +it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events without coordinates', (mouseButton) => { + for (const schema of [Request, SystemPointerRequest]) { + for (const direction of ['down', 'up']) { + const request = { method: 'toggleMouse', params: { appHandle: 'app', windowId: '23', mouseButton, direction } } + expect(schema.parse(request)).toEqual(request) + } + } +}) + +it.each([ + { mouseButton: undefined }, { mouseButton: 'back' }, + { direction: undefined }, { direction: 'press' }, + { appHandle: undefined }, { windowId: undefined }, + { x: 1 }, { y: 2 }, { relative: true }, { elementId: '0' }, { snapshotId: 'snapshot' }, + { modifiers: [] }, { useSystemPointer: true }, +])('rejects invalid mouse-button event parameters %j', (invalid) => { + const params = { appHandle: 'app', windowId: '23', mouseButton: 'left', direction: 'down', ...invalid } + for (const schema of [Request, SystemPointerRequest]) { + expect(schema.safeParse({ method: 'toggleMouse', params }).success).toBe(false) + } +}) + it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, { appHandle: 'app', windowId: '23', x: 1, y: 2 }, diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index d7a775baa0..0ebfd6e839 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -4,7 +4,7 @@ */ import { z } from 'zod' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' 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' @@ -104,7 +104,7 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR if (pending === undefined) return state 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) + return settle(settled, pending, extractTextContent(result.message.content, { separator: '\n' }), seq) } const applyDispatch = ( @@ -114,7 +114,7 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR const command = commandIn(dispatch.arguments) const evidence = command === undefined || !rules.hint.test(command) ? undefined : rules.evidence(command) if (evidence === undefined) return state - return settle(state, evidence, textOf(dispatch.content), seq) + return settle(state, evidence, extractTextContent(dispatch.content, { separator: '\n' }), seq) } /** Bind the URLs and record the pushes one successful shell result carries; returns the input state when nothing changes. */ @@ -136,11 +136,6 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR } } -/** 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') -} - function applyRecord(state: ForgeChangeRequestsState, event: SessionEvent): ForgeChangeRequestsState { const record = pluginRecordOf(event) if (record?.type !== BINDING_RECORD) return state diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 4be8924b32..e138e673f2 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -1,6 +1,7 @@ /** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */ import type { Context } from '@deepseek-ai/cordis' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Session } from '@deepseek-ai/dsh-session' import type { ToolExecution, ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-shell' @@ -89,7 +90,7 @@ export function observeReferences( const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) if (!argumentsResult.success || !shell.success) return [] - const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const printed = extractTextContent(result.content, { separator: '\n' }) const current = rules() const { command } = argumentsResult.data const evidence = current.evidence(command) diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 19f957ddca..6b35228784 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -327,11 +328,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number { return ctx.agents.turnBoundaryOf(agent.session).lastTurn } -/** Flatten content blocks to the text a hook payload carries (the common case). */ -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} - function base(agent: Agent | undefined, event: string): Record { return { session_id: agent?.session.header.id ?? '', @@ -346,13 +342,13 @@ function sessionStartPayload(agent: Agent, source: string): Record { - return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) } + return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) } } function preToolPayload(exec: ToolExecution): Record { return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId } } function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record { - return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } function stopPayload(agent: Agent): Record { return { ...base(agent, 'Stop'), stop_hook_active: false } diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 4a04055c20..86c4d17aa1 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -206,7 +207,7 @@ export function apply(ctx: Context, config: Config): void { const payload = { ...base(agent, 'UserPromptSubmit', model), turn_id: String(turn), - prompt: blocksToText(messages.flatMap(message => message.content)), + prompt: extractTextContent(messages.flatMap(message => message.content)), } const merged = await runPoint('UserPromptSubmit', '', payload, { agent, turn, plainStdoutAsContext: true, signal, @@ -283,17 +284,12 @@ export function apply(ctx: Context, config: Config): void { // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on // turn-scoped events. --- -// These small payload helpers intentionally remain next to the dialect shape; -// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol. +// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge. /* jscpd:ignore-start */ function lastTurn(ctx: Context, agent: Agent | undefined): number { if (!agent) return 0 return ctx.agents.turnBoundaryOf(agent.session).lastTurn } - -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} /* jscpd:ignore-end */ /** Base fields on every Codex payload (no turn_id). */ @@ -332,5 +328,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor } function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record { - return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index 38e8bedaa9..7d5a6129cf 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -181,6 +181,9 @@ export const VIEWER_ENDPOINT_CLASSES = { 'pluginMarket/search': 'owner-only', // owner plugin market 'pluginMarket/setIndexes': 'owner-only', // owner plugin market 'pluginRegistryProbe/fastest': 'owner-only', // owner plugin registry probe + 'connectorAccounts/cancel': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/start': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/watch': 'owner-only', // owner connector accounts on the Plugins page 'officeKit/generation': 'owner-only', // owner document export 'officeKit/render': 'owner-only', // owner document export 'speech/configure': 'owner-only', // owner voice input diff --git a/packages/experimental/session-title-all-prompts-llm/src/index.ts b/packages/experimental/session-title-all-prompts-llm/src/index.ts index 042267bc49..f2623be0c4 100644 --- a/packages/experimental/session-title-all-prompts-llm/src/index.ts +++ b/packages/experimental/session-title-all-prompts-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -137,10 +138,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/experimental/translator/package.json b/packages/experimental/translator/package.json index a8b5ac641f..b30925db07 100644 --- a/packages/experimental/translator/package.json +++ b/packages/experimental/translator/package.json @@ -69,6 +69,7 @@ "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-session-log-deepseek": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-session-query-sqlite": "workspace:*" } } diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 3db4f73334..9dbc1c44a4 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -4,6 +4,7 @@ import { boot } from '@deepseek-ai/dsh-app-boot' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, type SessionId, SessionSeq, type Session, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' @@ -136,6 +137,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: { id: 'account-custom-id', name: '@deepseek-ai/dsh-llm-deepseek-account', disabled: !withNativeOwners, config: { baseURL } }, { id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config: translator }, ...options.withSessionQuery === true ? [ + { id: 'projections', name: '@deepseek-ai/dsh-session-projection' }, { id: 'query', name: '@deepseek-ai/dsh-session-query-sqlite', config: { path: join(root, 'query.sqlite'), openAt: 'never' } }, ] : [], ...options.withSessionLog === true ? [ @@ -147,6 +149,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: const modules = new Map([ ['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore], ['@deepseek-ai/dsh-session-persistence-jsonl', JsonlPersistence], ['@deepseek-ai/dsh-session-query-sqlite', SqliteSessionQuery], + ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry], [options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', Official], ['@deepseek-ai/dsh-llm-deepseek-account', Account], ['@deepseek-ai/dsh-experimental-translator', Translator], ['@deepseek-ai/dsh-deepseek-llm-api-extensions', DeepSeekLlmApiExtensionRegistry], diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index c878484faf..be9916a03f 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -3417,6 +3417,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountActivationEntry', 'experimental-client-ui-voice-input VoiceSetupPrompt key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionSetup key \'@deepseek-ai/dsh-cua-bundle\'', ], @@ -3461,6 +3462,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountSectionEntry', 'experimental-client-ui-cot-translation TranslationSettings key \'@deepseek-ai/dsh-experimental-cot-translation-bundle\'', 'experimental-client-ui-voice-input VoicePreparation key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionPanel key \'@deepseek-ai/dsh-cua-bundle\'', @@ -3571,7 +3573,9 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ hookContext: '', slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', - occupants: [], + occupants: [ + 'client-ui-connector-account ConnectorAccountBadgeEntry id \'connector-account.badge\'', + ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.badge\', () => ctx.slots.register(\n { name: \'plugins.detail.badge\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:178', @@ -4586,6 +4590,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [ 'client-ui-agent-team TeamDisableConfirmation id \'agent-team.disable\'', 'client-ui-chat QuotaNoticeHost id \'chat.quota-notice\'', + 'client-ui-connector-account ConnectorAccountToastEntry id \'connector-account.notice\'', 'client-ui-context-menu MenuOverlay id \'context-menu\'', 'client-ui-file-drag FileDragFeedback id \'file-drag.feedback\'', 'client-ui-open-in-app OpenInAppToast id \'open-in-app.toast\'', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index c0b9c2efa9..713f994bef 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -812,6 +812,40 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'connectorAccounts', + summary: 'Holds the registered accounts and serves them to the Plugins page.', + description: 'Holds the registered accounts and serves them to the Plugins page.', + methods: [ + { + signature: 'register(registration: ConnectorAccountRegistration): () => void', + description: 'Show one account on the Plugins page for as long as the returned disposer has not run.', + parameters: [{ name: 'registration', description: 'the account key, its bundle package, the account source, the page operations, and the presentation.' }], + returns: 'an idempotent disposer that withdraws the account.', + throws: ['when another account already uses the key or the package.'], + }, + { + signature: '@Remote({ mode: \'stream\' }) async *watch(signal: AbortSignal): AsyncIterable', + description: 'Follow every registered account; each new subscriber starts a check of each account that runs no operation.', + parameters: [{ name: 'signal', description: 'the Client\'s observation lifetime; disposal also ends the stream.' }], + returns: 'the current accounts, then each changed set, coalescing changes that arrive before the next read.', + }, + { + signature: '@Remote async start(key: string, operation: string): Promise', + description: 'Start one of the operations the account registered as page actions.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'operation', description: 'the operation kind.' }], + returns: 'the operation identity once the account\'s source has started it.', + throws: ['for an unknown account or operation, or whatever the account\'s source refuses, such as a second operation.'], + }, + { + signature: '@Remote cancel(key: string, id: ConnectorOperationId): Promise', + description: 'Cancel one operation while its phase is cancellable, and wait for it to settle.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'id', description: 'the operation to cancel; a finished one or a phase that is not cancellable is ignored.' }], + returns: 'after the operation settles, or at once when nothing is cancelled.', + throws: ['for an unknown account.'], + }, + ], + }, { key: 'cotTranslation', summary: 'Optional reasoning translation delegates Session-bound storage to the translator.', @@ -3342,6 +3376,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ summary: 'Unified live-preferred session query service.', description: 'Unified live-preferred session query service.\n\nExact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service.', methods: [ + { + signature: 'getListMetadata(session: Session): SessionListMetadata', + description: 'Read the metadata that summarizes one live or prepared Session in a Session list.', + parameters: [{ name: 'session', description: 'live or prepared Session to summarize.' }], + returns: 'whether the Session has no turn, and its latest human-authored prompt time.', + }, { signature: 'observeSession( sessionId: SessionId, options: SessionObservationOptions = {}, ): Promise', description: 'Observe one exact live or prepared Session without a persistence listing preflight.', @@ -6068,6 +6108,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AnonymousTranslationSpec', declaration: 'export interface AnonymousTranslationSpec extends TranslationSpecFields {\n readonly provider: AnonymousTranslationProvider;\n}', }, + { + name: 'AnyConnectorAccountView', + declaration: 'export type AnyConnectorAccountView = ConnectorAccountView;', + }, { name: 'AnyHook', declaration: 'export type AnyHook = ModHook;', @@ -6504,6 +6548,78 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ConnectionTrustRequest', declaration: 'export interface ConnectionTrustRequest {\n readonly headers: Headers | Readonly>;\n readonly signal?: AbortSignal | undefined;\n readonly socket?: {\n readonly destroyed: boolean;\n } | undefined;\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n}', }, + { + name: 'ConnectorAccountButton', + declaration: 'export interface ConnectorAccountButton {\n readonly label: LocalizedText;\n readonly command: ConnectorAccountCommand;\n readonly variant?: \'primary\' | \'ghost\';\n readonly confirm?: ConnectorAccountConfirmation;\n}', + }, + { + name: 'ConnectorAccountCommand', + declaration: 'export type ConnectorAccountCommand = {\n readonly kind: \'start\';\n readonly operation: string;\n} | {\n readonly kind: \'cancel\';\n} | {\n readonly kind: \'open\';\n};', + }, + { + name: 'ConnectorAccountConfirmation', + declaration: 'export interface ConnectorAccountConfirmation {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly label: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountCopy', + declaration: 'export interface ConnectorAccountCopy {\n readonly title: LocalizedText;\n readonly hint: LocalizedText;\n readonly activation: {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly connect: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountDisplay', + declaration: 'export interface ConnectorAccountDisplay {\n readonly phase: ConnectorAccountPhase;\n readonly status: LocalizedText;\n readonly badge?: LocalizedText;\n readonly buttons: readonly ConnectorAccountButton[];\n readonly connect?: Extract;\n readonly detail?: LocalizedText;\n readonly notes: readonly ConnectorAccountNote[];\n readonly failure?: ConnectorAccountFailure;\n}', + }, + { + name: 'ConnectorAccountEntry', + declaration: 'export interface ConnectorAccountEntry {\n readonly key: string;\n readonly packageName?: string;\n readonly copy: ConnectorAccountCopy;\n readonly display: ConnectorAccountDisplay;\n readonly operation?: {\n readonly id: ConnectorOperationId;\n readonly authorizationUrl?: string;\n };\n readonly result?: {\n readonly id: ConnectorOperationId;\n readonly notice?: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountFailure', + declaration: 'export interface ConnectorAccountFailure {\n readonly text: LocalizedText;\n readonly details?: readonly string[];\n}', + }, + { + name: 'ConnectorAccountNote', + declaration: 'export interface ConnectorAccountNote {\n readonly text: LocalizedText;\n readonly button?: ConnectorAccountButton;\n}', + }, + { + name: 'ConnectorAccountOperation', + declaration: 'export interface ConnectorAccountOperation {\n readonly kind: Kind;\n readonly notice?: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountPhase', + declaration: 'export type ConnectorAccountPhase = \'checking\' | \'connecting\' | \'connected\' | \'disconnected\' | \'unavailable\';', + }, + { + name: 'ConnectorAccountRegistration', + declaration: 'export interface ConnectorAccountRegistration {\n readonly key: string;\n readonly packageName?: string;\n readonly source: ConnectorAccountSource;\n readonly operations: readonly ConnectorAccountOperation>[];\n readonly copy: ConnectorAccountCopy;\n readonly present: (view: View) => ConnectorAccountDisplay;\n}', + }, + { + name: 'ConnectorAccountSource', + declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise;\n cancel(id: ConnectorOperationId): Promise;\n}', + }, + { + name: 'ConnectorAccountsView', + declaration: 'export interface ConnectorAccountsView {\n readonly accounts: readonly ConnectorAccountEntry[];\n}', + }, + { + name: 'ConnectorAccountView', + declaration: 'export interface ConnectorAccountView {\n readonly account: Account;\n readonly operation?: ConnectorOperation;\n readonly result?: ConnectorOperationResult;\n}', + }, + { + name: 'ConnectorOperation', + declaration: 'export interface ConnectorOperation {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly phase: Phase;\n readonly cancellable: boolean;\n readonly authorizationUrl?: string;\n}', + }, + { + name: 'ConnectorOperationId', + declaration: 'export type ConnectorOperationId = Branded<\'ConnectorOperationId\'>;', + }, + { + name: 'ConnectorOperationKindOf', + declaration: 'export type ConnectorOperationKindOf = NonNullable[\'kind\'];', + }, + { + name: 'ConnectorOperationResult', + declaration: 'export interface ConnectorOperationResult {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly outcome: \'succeeded\' | \'cancelled\' | \'failed\';\n readonly failure?: Failure;\n}', + }, { name: 'ContentBlockMap', declaration: 'export interface ContentBlockMap {\n \'text\': TextBlock;\n \'reasoning\': ReasoningBlock;\n \'image\': ImageBlock;\n \'file\': FileBlock;\n \'tool-call\': ToolCallBlock;\n \'tool-addition\': ToolAdditionBlock;\n \'tool-removal\': ToolRemovalBlock;\n}', @@ -9268,6 +9384,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionLineageTrace', declaration: 'export type SessionLineageTrace = {\n target: SessionRecord;\n ancestors: SessionRecord[];\n descendants: SessionLineageNode[];\n} & ({\n complete: true;\n root: SessionRecord;\n} | {\n complete: false;\n unresolvedParentId: SessionId;\n});', }, + { + name: 'SessionListMetadata', + declaration: 'export interface SessionListMetadata {\n readonly blank: boolean;\n readonly lastPromptAt: number | null;\n}', + }, { name: 'SessionListRequest', declaration: 'export interface SessionListRequest {\n readonly cursor?: string;\n}', @@ -10982,7 +11102,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n getSessionHeaders(): readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, { name: 'WorkspaceArchiveSessionRequest', diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index f08412c0e9..ab5e0f75d7 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -1,5 +1,6 @@ /** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' @@ -104,9 +105,8 @@ export function serialize( return unsupported('tool-change blocks outside developer messages') } if (message.role === 'system') { - const texts = message.content.filter(block => block.type === 'text') - if (texts.length !== message.content.length) return unsupported('non-text system message') - const text = texts.map(block => block.text).join('') + if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message') + const text = extractTextContent(message.content) if (inHistory && messages.length > 0) { if (text.length === 0) return unsupported('empty in-history system update') systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] }) diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index d8a657d4e6..fa8b833d43 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -5,6 +5,7 @@ */ import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' @@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts' import { requestImageDimensions } from '@deepseek-ai/dsh-attachment' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts' -/** Join the text blocks of a harness message. */ -function flattenText(message: RequestMessage): string { - return message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') -} - - /** Recover the pi-ai toolResult message for one harness tool-role message. */ function toolResultOf( message: Extract, @@ -94,7 +86,7 @@ function userContent( break } } - if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('') + if (content.every(block => block.type === 'text')) return extractTextContent(content) return content } @@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit { let end = 0 for (const message of options.messages) { if (message.role !== 'system') break - text.push(flattenText(message)) + text.push(extractTextContent(message.content)) end++ } const systemPrompt = text.filter(Boolean).join('\n\n') @@ -230,7 +222,7 @@ function appendSharedHistory( return true } if (message.role === 'system') { - const content = flattenText(message) + const content = extractTextContent(message.content) if (content.length > 0) { if (supportsMidConvoSystemMessages) { messages.push({ role: 'system', content, timestamp: 0 }) @@ -264,10 +256,10 @@ function textOnlyContext( } if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue if (message.role === 'tool') { - messages.push(toolResultOf(message, toolNames, flattenText(message))) + messages.push(toolResultOf(message, toolNames, extractTextContent(message.content))) continue } - messages.push({ role: 'user', content: flattenText(message), timestamp: 0 }) + messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 }) } return piContext(split.systemPrompt, options, messages) } diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index 1bc7dd7016..ee9b1d0bd5 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -24,8 +24,8 @@ en: cf221d60fb42a278 zh: 0ea17503495d386b /deepseek-ai-dsh-llm/use-this-package/what-you-can-do: - en: dc61eb86585f6e0d - zh: 9c0d6b240dfd2cda + en: cb9f0c6ee3203ab3 + zh: 8513340a40192513 /deepseek-ai-dsh-llm/use-this-package/failures-and-recovery: en: 47f4dab3c377a4cd zh: 49ac1c366de19136 @@ -36,8 +36,8 @@ en: 12d0444c18a397c7 zh: 9d4a5468b4bb7fcd /deepseek-ai-dsh-llm/understand-the-implementation/source-map: - en: ae1618577f4e8364 - zh: a6e8ab1563c08dfb + en: 8ec1ca8903e09bc0 + zh: 77c7bc3413cbab1c /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: en: c95d4947745e39bb zh: ec37b969f27629e2 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index e5d2838586..1419acbe3b 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### What you can do +- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist. - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`. - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`. - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter. @@ -116,7 +117,7 @@ The service is built on one separation: **the logical contract is provider-neutr |---|---| | [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary | | [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary | -| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests | +| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers | | [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing | diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 21e2b778ba..777d877ff0 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 你可以做什么 +- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。 @@ -116,7 +117,7 @@ const configure = (maxTokens: number): ConfigureCall => |---|---| | [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 | | [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 | -| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 | +| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 | | [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 | diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index bcc94686db..d354188c30 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -50,7 +50,11 @@ export * from './api-key.ts' export type * from './types.ts' export * from './content.ts' export * from './assistant-stream.ts' -export * from './message.ts' +export type * from './message.ts' +export { + CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage, + createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage, +} from './message.ts' export * from './retry-policy.ts' export { BlockAssembler } from './assembler.ts' export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts' diff --git a/packages/llm/llm/src/message.ts b/packages/llm/llm/src/message.ts index 0138452426..fc43cbadbc 100644 --- a/packages/llm/llm/src/message.ts +++ b/packages/llm/llm/src/message.ts @@ -1,4 +1,4 @@ -/** Message value types, identity, and immutable construction helpers. */ +/** Message value types, content text extraction, identity, and immutable construction helpers. */ import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { brandString } from '@deepseek-ai/dsh-brand' @@ -304,3 +304,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu isError: input.isError, }) } + +/** + * Extract and join only text blocks in content order, preserving their whitespace. + * Non-text blocks contribute neither text nor separators; content is not modified. + * Import from `@deepseek-ai/dsh-llm/message` in Host and browser code. + * @param content - source blocks to read in their existing order. + * @param options - optional text extraction settings. + * @param options.separator - text inserted between text blocks; defaults to an empty string. + * @returns joined text, or an empty string when no text blocks are present. + */ +export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string { + return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '') +} diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index d3e3ba995e..f70710672e 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' +import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { type ToolCallId, boundContextSummary, @@ -12,6 +13,46 @@ import { freezeMessage, type MessageId, } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + +describe('extractTextContent', () => { + it('preserves whitespace and empty text blocks while omitting non-text blocks', () => { + const message = createUserMessage({ + source: { kind: 'test' }, + content: [ + { type: 'text', text: ' \talpha\n' }, + { type: 'reasoning', text: 'private reasoning' }, + { type: 'image', attachment: { + attachmentId: brandString(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + } }, + { type: 'tool-call', id: brandString('call'), name: 'tool', arguments: '{}' }, + { type: 'text', text: '' }, + { type: 'tool-removal', toolName: 'removed' }, + { type: 'text', text: 'β \r\n' }, + ], + }) + expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n') + expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n') + expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n') + expect(Object.isFrozen(message.content)).toBe(true) + expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' }) + }) + + it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => { + expect(extractTextContent([])).toBe('') + expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('') + expect(extractTextContent([ + { type: 'text', text: '' }, + { type: 'reasoning', text: 'ignored' }, + { type: 'text', text: '' }, + ], { separator: '\n' })).toBe('\n') + }) +}) describe('message construction', () => { it('detaches and freezes developer tool names without copying their definitions', () => { diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 06e1a3411b..b5448ee883 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -82,6 +82,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-brand-official` | no | Official DeepSeek Harness brand artwork and click-triggered home background | | `@deepseek-ai/dsh-client-ui-chat` | no | Chat Conversation target, node definitions, renderers, and details surface | | `@deepseek-ai/dsh-client-ui-commands` | no | Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry | +| `@deepseek-ai/dsh-client-ui-connector-account` | no | Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote | | `@deepseek-ai/dsh-client-ui-context-menu` | no | Typed, plugin-extensible context menus with captured targets and shared Web presentation | | `@deepseek-ai/dsh-client-ui-conversation` | no | Target-neutral Conversation assembly, shell, composer, queue, and view navigation | | `@deepseek-ai/dsh-client-ui-deliverables` | no | Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web | @@ -416,6 +417,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-session-log-export` | yes | Web Session-log ZIP export and Session Markdown copy | | `@deepseek-ai/dsh-session-query-sqlite` | yes | Concrete ctx.sessionQuery backend with SQLite FTS5 search | +| `@deepseek-ai/dsh-tool-session-list` | no | Read-only paginated Workspace and Session metadata tools | ## settings diff --git a/packages/sdk/server/src/query-activity.ts b/packages/sdk/server/src/query-activity.ts index 17a4fc9148..7bf4c8b7bf 100644 --- a/packages/sdk/server/src/query-activity.ts +++ b/packages/sdk/server/src/query-activity.ts @@ -1,5 +1,7 @@ /** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { GoalView } from '@deepseek-ai/dsh-goal' @@ -63,7 +65,7 @@ export class QueryActivity { } if (this.input || this.goalId !== undefined) { if (event.type === 'assistant/message') { - this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + this.response = extractTextContent(event.data.message.content) } if (event.type === 'turn/end') this.turnReason = event.data.reason.kind } diff --git a/packages/session-query/README.i18n.yaml b/packages/session-query/README.i18n.yaml index e391a1291c..6113794d2b 100644 --- a/packages/session-query/README.i18n.yaml +++ b/packages/session-query/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /session-query-session-retrieval-capability-family/packages: - en: 03f48fd85e12934a - zh: 4fb3f345f5d91572 + en: 474c97ed08ca68c8 + zh: af8114e7219d8938 /session-query-session-retrieval-capability-family/related-documentation: en: aa03439fc68a285d zh: eb074a3318b92024 diff --git a/packages/session-query/README.md b/packages/session-query/README.md index 240076d95b..4e0b88decc 100644 --- a/packages/session-query/README.md +++ b/packages/session-query/README.md @@ -28,6 +28,7 @@ Each package README describes what you can do with its part of the family. |---|---|---| | [`session-query/`](session-query/README.md) | Unified session-history query service: exact reads, relationship traces, and filters | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.md) | Full-text search across session history backed by a SQLite FTS5 index | registers on `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.md) | Optional read-only Workspace and Session metadata tools | — | | [`session-log-export/`](session-log-export/README.md) | Web `/export` command and browser download of a session ZIP | `ctx.sessionLogDownload` (browser) | ----- diff --git a/packages/session-query/README.zh.md b/packages/session-query/README.zh.md index f443ff7ee4..3367b6271a 100644 --- a/packages/session-query/README.zh.md +++ b/packages/session-query/README.zh.md @@ -28,6 +28,7 @@ kind: "package-group" |---|---|---| | [`session-query/`](session-query/README.zh.md) | 统一的会话历史查询服务:精确读取、关系追踪与过滤 | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.zh.md) | 基于 SQLite FTS5 索引的会话历史全文搜索 | 注册到 `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.zh.md) | 可选的只读 Workspace 和 Session 元数据工具 | — | | [`session-log-export/`](session-log-export/README.zh.md) | Web `/export` 命令与浏览器下载会话 ZIP | `ctx.sessionLogDownload`(浏览器) | ----- diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 0f7f9bfbdc..7b22a21b36 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -201,7 +201,7 @@ interface CursorPayload { /** Concrete SQLite owner of the combined `ctx.sessionQuery` service. */ export class SqliteSessionQueryEngine extends SessionQueryEngine { - static override inject = ['sessions'] + static override inject = ['sessions', 'sessionProjections'] static Config: z = z.object({ path: z.string().required(), @@ -261,7 +261,8 @@ export class SqliteSessionQueryEngine extends SessionQueryEngine { } /** Open eagerly only when activation owns the configured readiness boundary. */ - protected async [Service.init](): Promise { + protected override async [Service.init](): Promise { + await super[Service.init]() if (this.config.openAt === 'startup') await this._ensureReady(undefined) } diff --git a/packages/session-query/session-query/README.i18n.yaml b/packages/session-query/session-query/README.i18n.yaml index 9928994e13..48d79d6d6a 100644 --- a/packages/session-query/session-query/README.i18n.yaml +++ b/packages/session-query/session-query/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-session-query/use-this-package: - en: cc9eb8f214c57137 - zh: 76723633d0faee5d + en: dfc90afac9ef47be + zh: 0a5aa60a34f24e61 /deepseek-ai-dsh-session-query/use-this-package/what-you-can-do: - en: 608cd6d4c5cf2c35 - zh: 23d3c5a7374b5283 + en: f0baf912893e2edd + zh: b71f2d1df02a8d2a /deepseek-ai-dsh-session-query/use-this-package/filters: en: 1b95403461947ca1 zh: cffa21b03df9f0ad @@ -36,11 +36,14 @@ en: b34fb0d209192ff4 zh: 455bdb024d04f16a /deepseek-ai-dsh-session-query/understand-the-implementation/source-map: - en: c58f4f086e3d0728 - zh: 7d66b688c7f54c87 + en: fa54846e5df84028 + zh: de31ff744819413e /deepseek-ai-dsh-session-query/understand-the-implementation/corpus-resolution: - en: efa560c55a869c71 - zh: 451eb107825856ac + en: 3254f25af5734621 + zh: 3f8e8e0bbb83095e +/deepseek-ai-dsh-session-query/understand-the-implementation/session-list-metadata: + en: a46a831dce49d0ba + zh: 840d4982f059b41b /deepseek-ai-dsh-session-query/understand-the-implementation/observation-cache: en: 16d4a29af5b2ac07 zh: 7ec4a91f97697d2e diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 6110432284..6321321296 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -25,13 +25,14 @@ English | [中文](README.zh.md) ## Use this package -Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. Everything below is available on `ctx.sessionQuery` once a backend is composed. +Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. The query operations below are available on `ctx.sessionQuery` once a backend is composed. ### What you can do | Operation | What you get | |---|---| | `listSessions()` | Every logical session, newest first, with `live` and `persisted` availability flags and optional `formatStatus` | +| `getListMetadata(session)` | Whether a live or prepared Session has no turn, and its latest human-authored prompt time | | `readSession(id)` | The complete replay-validated raw event log, without making the session live | | `filterSessions(filters)` | Sessions matching ANDed metadata and availability predicates | | `filterEvents(id, filters)` | Semantic event documents matching metadata and literal-text predicates | @@ -92,6 +93,7 @@ The decision history lives in the [unified service decision](../../../.agents/no | [`src/index.ts`](src/index.ts) | Service definition: the abstract `SessionQueryEngine`, concrete reads, config validation | | [`src/corpus.ts`](src/corpus.ts) | Live-preferred corpus resolution, optional persistence binding, batch projections | | [`src/observation.ts`](src/observation.ts) | Live-preferred point observations with a bounded revision-keyed prepared-Session cache | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session-list blankness and human-prompt recency projection definition | | [`src/cold-read.ts`](src/cold-read.ts) | Handle-based cold log read with in-memory interrupted-turn closers | | [`src/types.ts`](src/types.ts) | Public records, filters, requests, and page types | | [`src/config.ts`](src/config.ts) | Inherited config and the closed `SessionQueryError` taxonomy | @@ -105,6 +107,11 @@ The decision history lives in the [unified service decision](../../../.agents/no `SessionCorpus` binds optional `ctx.sessionPersistence` through a fiber and resolves each read live-first: a known live target is snapshotted without consulting persistence; otherwise the session is listed, read completely through a short-lived read handle, and re-checked for a live attachment before cloning. A cold log whose writer crashed mid-turn is balanced in memory with `interruptedTurnClosers` — persistence is never mutated by a read. Header compatibility is asserted between listed and loaded observations. Batch title reads run one metadata listing and bounded-concurrency reads, isolating per-session failures while cancellation rejects the whole batch. + +### Session-list metadata + +The service registers the `sessionListMetadata` projection for Session blankness and the latest human-authored prompt time when it starts, and its disposal releases that registration; it therefore requires `sessionProjections`. `getListMetadata(session)` reads the projection synchronously for a live or prepared Session. The Session API and optional [listing tools](../tool-session-list/README.md) read it through `ctx.sessionQuery`. + ### Observation cache `observeSession` builds point observations without a listing preflight. A live observation fixes its cut as the current log length and materializes `events` on first read, so header-, cursor-, or projection-only consumers never copy the log; the log only appends, so a late first read still yields exactly that prefix. The cold path stats the stored session first and consults its own bounded cache keyed by the persistence instance and the `stat` revision: an unchanged revision reuses the restored unpublished Session without re-reading the log; a changed revision, or a replaced persistence instance, reloads through the handle seam and replaces the entry. The cache holds `preparedSessionCacheSize` entries with least-recently-used eviction, entries pinned by active observation leases are never evicted, and a session that goes live mid-read retries the live path. diff --git a/packages/session-query/session-query/README.zh.md b/packages/session-query/session-query/README.zh.md index 3c9bfb329a..550c62d349 100644 --- a/packages/session-query/session-query/README.zh.md +++ b/packages/session-query/session-query/README.zh.md @@ -25,13 +25,14 @@ kind: "package-reference" ## 使用本包 -当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下全部能力都可在 `ctx.sessionQuery` 上使用。 +当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下查询操作都可在 `ctx.sessionQuery` 上使用。 ### 你可以做什么 | 操作 | 你得到什么 | |---|---| | `listSessions()` | 每个逻辑会话,最新的在前,带 `live` 与 `persisted` 可用性标志及可选 `formatStatus` | +| `getListMetadata(session)` | 实时或已准备的 Session 是否还没有 turn,及其最近一条人工提示词的时间 | | `readSession(id)` | 经过回放校验的完整原始事件日志,且不会让该会话变为实时 | | `filterSessions(filters)` | 匹配 AND 连接的元数据与可用性谓词的会话 | | `filterEvents(id, filters)` | 匹配元数据与字面文本谓词的语义事件文档 | @@ -92,6 +93,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `SessionQueryEngine`、具体读取、配置校验 | | [`src/corpus.ts`](src/corpus.ts) | 实时优先的语料库解析、可选持久化绑定、批量投影 | | [`src/observation.ts`](src/observation.ts) | 实时优先的定点观察,带按修订键控的有界 prepared-Session 缓存 | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session 列表空白状态与人工提示词活动时间投影定义 | | [`src/cold-read.ts`](src/cold-read.ts) | 基于句柄的冷日志读取,附内存中的中断轮次闭合事件 | | [`src/types.ts`](src/types.ts) | 公共记录、过滤器、请求与分页类型 | | [`src/config.ts`](src/config.ts) | 继承配置与封闭的 `SessionQueryError` 分类体系 | @@ -105,6 +107,11 @@ kind: "package-reference" `SessionCorpus` 通过 fiber 绑定可选的 `ctx.sessionPersistence`,并实时优先解析每次读取:已知实时目标直接快照,不查询持久化;否则先列出会话,再通过短生命周期的读取句柄完整读出日志,并在克隆前重新检查是否出现实时挂载。写入者在轮次中途崩溃的冷日志用 `interruptedTurnClosers` 在内存中补齐——读取从不修改持久化。列表与加载观察之间会断言 header 兼容性。批量标题读取执行一次元数据列表与有界并发读取,把逐会话失败隔离,而取消会拒绝整个批次。 + +### Session 列表元数据 + +服务启动时注册记录 Session 空白状态与最近人工提示词时间的 `sessionListMetadata` 投影,释放服务时移除该注册;因此服务依赖 `sessionProjections`。`getListMetadata(session)` 同步读取实时或已准备 Session 的该投影。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)通过 `ctx.sessionQuery` 读取。 + ### 观察缓存 `observeSession` 不经过列表预检直接构建定点观察。实时观察以当前日志长度固定 cut,并在首次读取时才物化 `events`,因此只需要 header、cursor 或 projection 的消费者永远不会复制日志;日志只会追加,所以延后的首次读取得到的仍然正好是该前缀。冷路径先对存储会话执行 `stat`,再查询自有的有界缓存,缓存键为持久化实例加 `stat` 修订:修订未变则复用已恢复的未发布 Session,不再重读日志;修订变化或持久化实例被替换则经句柄 seam 重新加载并替换条目。缓存保留 `preparedSessionCacheSize` 个条目并按最久未用淘汰,被活跃观察租约钉住的条目从不被淘汰;读取中途转为实时的会话会重试实时路径。 diff --git a/packages/session-query/session-query/package.json b/packages/session-query/session-query/package.json index fbd651796b..81cc144767 100644 --- a/packages/session-query/session-query/package.json +++ b/packages/session-query/session-query/package.json @@ -18,11 +18,16 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", @@ -43,9 +48,6 @@ "@deepseek-ai/dsh-session-persistence": { "optional": true }, - "@deepseek-ai/dsh-session-projection": { - "optional": true - }, "@deepseek-ai/dsh-session-projection-cache": { "optional": true } @@ -62,6 +64,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "dependencies": { - "@deepseek-ai/dsh-session-format-catalog": "workspace:*" + "@deepseek-ai/dsh-session-format-catalog": "workspace:*", + "zod": "4.6.6" } } diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index dfb11fec65..21d924f971 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -13,6 +13,7 @@ import { type SessionId, type SessionSeq as SessionSeqType, } from '@deepseek-ai/dsh-session' +import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' import type { @@ -32,6 +33,7 @@ import type { SessionSearchExecContext, SessionSearchHit, SessionSearchPage, + SessionListMetadata, SessionSearchRequest, SessionSurfaceSnapshot, SessionTitleObservation, @@ -45,6 +47,7 @@ import { type Config, } from './config.ts' import { SessionCorpus } from './corpus.ts' +import { sessionListMetadataDefinition } from './list-metadata.ts' import { SessionObservationReader, type SessionObservation, @@ -96,9 +99,10 @@ declare module '@deepseek-ai/cordis' { * generations, and query execution on the same `ctx.sessionQuery` service. */ export abstract class SessionQueryEngine extends Service { - static inject = ['sessions'] + static inject = ['sessions', 'sessionProjections'] private readonly _readWindowMax: number + private _listMetadata!: ProjectionHandle private readonly _corpus: SessionCorpus private readonly _observations: SessionObservationReader @@ -131,6 +135,20 @@ export abstract class SessionQueryEngine extends Service { this._observations = new SessionObservationReader(ctx, preparedSessionCacheSize) } + /** Register the Session-list metadata projection for this service's lifetime. */ + protected async [Service.init](): Promise { + this._listMetadata = await this.ctx.sessionProjections.register(sessionListMetadataDefinition) + } + + /** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ + getListMetadata(session: Session): SessionListMetadata { + return this._listMetadata.stateOf(session) + } + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/packages/session-query/session-query/src/list-metadata.ts b/packages/session-query/session-query/src/list-metadata.ts new file mode 100644 index 0000000000..2a4c3fce71 --- /dev/null +++ b/packages/session-query/session-query/src/list-metadata.ts @@ -0,0 +1,35 @@ +/** Session-list metadata projection definition registered by `SessionQueryEngine`. */ + +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import { z } from 'zod' +import type { SessionListMetadata } from './types.ts' + +const sessionListMetadataSchema: z.ZodType = z.object({ + blank: z.boolean(), + lastPromptAt: z.number().nullable(), +}) + +/** Advance blankness and human-prompt recency without retaining history. */ +function applySessionListMetadata( + state: SessionListMetadata, + event: SessionEvent, +): SessionListMetadata { + const blank = state.blank && event.type !== 'turn/start' + const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' + ? event.time + : state.lastPromptAt + return blank === state.blank && lastPromptAt === state.lastPromptAt + ? state + : { blank, lastPromptAt } +} + +/** Blankness and latest human-prompt time folded per Session; persisted at state version 1. */ +export const sessionListMetadataDefinition = { + key: 'sessionListMetadata', + stateSchema: sessionListMetadataSchema, + init: () => ({ blank: true, lastPromptAt: null }), + apply: applySessionListMetadata, + wire: { viewSchema: sessionListMetadataSchema, view: state => state }, + stateVersion: 1, +} satisfies ProjectionDefinition<'sessionListMetadata', SessionListMetadata> diff --git a/packages/session-query/session-query/src/types.ts b/packages/session-query/session-query/src/types.ts index cca5b2283e..8be1b4bfc6 100644 --- a/packages/session-query/session-query/src/types.ts +++ b/packages/session-query/session-query/src/types.ts @@ -14,12 +14,27 @@ import type { SessionSeq, OptionalSessionSeq, SurfaceEvent, -} from '@deepseek-ai/dsh-session' -import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' +} from '@deepseek-ai/dsh-session/types' +import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title/types' import type { SessionSearchCursor } from './cursor.ts' export type { SessionSearchCursor } from './cursor.ts' +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** Persisted facts used to summarize a Session without activating it. */ + sessionListMetadata: SessionListMetadata + } +} + +/** Persisted hints used to summarize a cold Session. */ +export interface SessionListMetadata { + /** Whether the folded prefix contains no turn. */ + readonly blank: boolean + /** Latest human-authored prompt time in the folded prefix. */ + readonly lastPromptAt: number | null +} + /** Whether an event is current model context, replaced context, or raw-log-only. */ export type SessionEventSurface = 'current' | 'shadowed' | 'log-only' diff --git a/packages/session-query/session-query/tests/list-metadata.spec.ts b/packages/session-query/session-query/tests/list-metadata.spec.ts new file mode 100644 index 0000000000..14b75460d9 --- /dev/null +++ b/packages/session-query/session-query/tests/list-metadata.spec.ts @@ -0,0 +1,75 @@ +/** Session-list metadata is registered and read through the query service lifecycle. */ + +import { Context } from '@deepseek-ai/cordis' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { describe, expect, it, onTestFinished } from 'vitest' +import { TestSessionQueryEngine } from './test-service.ts' + +async function setup() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + return ctx +} + +function prompt(session: Session) { + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Continue the task.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +describe('Session-list metadata', () => { + it('tracks human prompts and turns while preserving unchanged state references', async () => { + const ctx = await setup() + await ctx.plugin(TestSessionQueryEngine) + const read = (session: Session) => ctx.sessionQuery.getListMetadata(session) + const session = ctx.sessions.create() + const initial = read(session) + expect(initial).toEqual({ blank: true, lastPromptAt: null }) + + session.append('session/title', { title: 'Task', messageSeqs: [], source: { kind: 'user' } }) + expect(read(session)).toBe(initial) + const first = prompt(session) + expect(read(session)).toEqual({ blank: true, lastPromptAt: first.time }) + session.append('turn/start', { turn: 1 }) + const active = read(session) + expect(active).toEqual({ blank: false, lastPromptAt: first.time }) + session.append('turn/start', { turn: 2 }) + expect(read(session)).toBe(active) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Context refresh.' }], + source: { kind: 'system-prompt' }, + }), { surfaceOp: 'append' }) + expect(read(session)).toBe(active) + const latest = prompt(session) + expect(read(session)).toEqual({ blank: false, lastPromptAt: latest.time }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(read(session)) + expect(ctx.sessionProjections.checkpoint(session).sessionListMetadata?.ver).toBe(1) + }) + + it('releases the projection registration when the query service is disposed', async () => { + const ctx = await setup() + const fiber = await ctx.plugin(TestSessionQueryEngine) + const session = ctx.sessions.create() + session.append('turn/start', { turn: 1 }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata) + .toEqual({ blank: false, lastPromptAt: null }) + + await fiber.dispose() + expect(ctx.sessionProjections.snapshot(session).values).not.toHaveProperty('sessionListMetadata') + }) + + it('folds existing live history when the query service starts', async () => { + const ctx = await setup() + const session = ctx.sessions.create() + session.append('turn/start', { turn: 1 }) + const event = prompt(session) + await ctx.plugin(TestSessionQueryEngine) + expect(ctx.sessionQuery.getListMetadata(session)).toEqual({ blank: false, lastPromptAt: event.time }) + }) +}) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml new file mode 100644 index 0000000000..2c3d1b503c --- /dev/null +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -0,0 +1,55 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session-query/tool-session-list/README.md +/: + en: 3475319e48226347 + zh: 68361c3ff00d966f +/deepseek-ai-dsh-tool-session-list: + en: 963f03d1ba483ea9 + zh: 4809b66477752fe9 +/deepseek-ai-dsh-tool-session-list/summary: + en: e4e61ecb4f56e250 + zh: 815fd87f03e766f1 +/deepseek-ai-dsh-tool-session-list/table-of-contents: + en: d152484eb41ac6b4 + zh: 5acc0d3807846b6e +/deepseek-ai-dsh-tool-session-list/use-this-package: + en: 388849d88b975263 + zh: df6db1e31c9bba7c +/deepseek-ai-dsh-tool-session-list/use-this-package/access-and-composition: + en: 0bf65fbc8660134a + zh: f4f7b3a0049d3196 +/deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: + en: bd85d03043393832 + zh: 9c57bdd92461c1e1 +/deepseek-ai-dsh-tool-session-list/use-this-package/failures: + en: 95ee3e3c0ecedadd + zh: 933d267402ceec74 +/deepseek-ai-dsh-tool-session-list/understand-the-implementation: + en: ac9f08e72d3f7e64 + zh: 231196ddbb82b779 +/deepseek-ai-dsh-tool-session-list/further-exploration: + en: 06d8fa5cb2d63b6b + zh: 2635b93fccf3dbc9 +/deepseek-ai-dsh-tool-session-list/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results: + en: cadc497841430a21 + zh: af4cc374d7d16917 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/what-the-model-sees: + en: 6ffb21f59acadc4e + zh: 258cded3677be923 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/token-effect: + en: e699317cafee83d9 + zh: 912c0ce1a9f3957f +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/kv-cache-effect: + en: 0e201fbbe37798d8 + zh: fd4bd41e7393c234 +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: + en: 2c53c1fc603e0ff2 + zh: 99a58f1e0e3c27fc +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md new file mode 100644 index 0000000000..f487684915 --- /dev/null +++ b/packages/session-query/tool-session-list/README.md @@ -0,0 +1,126 @@ +--- +description: "List Workspace and Session metadata through optional read-only tools, with pagination and cached titles and activity times." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +English | [中文](README.zh.md) + +## Summary + +Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or list archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this optional plugin where the intended callers receive tools. It has no configuration fields and is absent from the default profiles. + +### Access and composition + +Granting these tools grants read access to every Workspace and Session in the mounted runtime. Tool availability is the access control; there is no per-agent Workspace ACL or implicit restriction to the caller's working directory. LiveShare's tool allowlist does not include these tools. + +The plugin requires `tools`, `sessions`, `sessionQuery`, `workspaceRegistry`, and `sessionProjections`. A projection cache supplies metadata for cold sessions; without it, cold rows use the documented missing-metadata values. In a headless profile, the base bundle supplies the other dependencies; add the Workspace registry and this plugin in a profile patch: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +When the composition already mounts `workspaceRegistry`, add only the tool row. Workspace initialization follows the [registry's existing history bootstrap](../../workspace/workspace/README.md); listing calls do not create or attach sessions or change registry records. + +### Listing behavior + +Both tools return an array directly. The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) defines arguments. Pagination follows filtering and ordering; each call defaults to 20 entries, accepts at most 100, and starts at offset zero. Increase the offset by the number of returned entries to continue; an empty array ends the traversal. + +`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` never returns subagent sessions. It includes unarchived sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. Archival matches each Session's own ID. + +Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. + +With `workspace_id`, the call reads its members' headers from the Workspace registry index without persistence I/O, so its work grows with the member count. Without `workspace_id`, it first enumerates every stored and live Session header. Filtering, metadata reads, and sorting then run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. + +### Failures + +Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +A Workspace selection reads `Workspace.getSessionHeaders()`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. Live rows read blankness and prompt recency through `ctx.sessionQuery.getListMetadata`, the same projection the Session API reads. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Tool schemas, registration, JSON result rendering, and generic tool cards | +| [`src/list.ts`](src/list.ts) | Pagination, membership selection, and live or cached metadata reads | + +
+ +----- + + +## Further Exploration + +- [Workspace registry](../../workspace/workspace/README.md) — recorded membership, registry order, and archival. +- [Session query](../session-query/README.md) — corpus header enumeration and the shared list metadata reader. +- [Session projection cache](../../session/session-projection-cache/README.md) — persisted metadata and cache availability. +- [Session query package map](../README.md) — adjacent retrieval capabilities. + +----- + + +## Model Experience + +### Tool schemas and results + +#### What the model sees + +The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) owns the `list_workspace` and `list_session` schemas. Each result renders as a JSON array. The plugin adds no separate system-prompt section. + +#### Token effect + +Available tool schemas contribute request tokens; each invocation adds its arguments and returned metadata. The page limit bounds the number of returned entries, while title and path lengths still affect result size. + +#### KV Cache effect + +The schemas remain stable while tool availability is unchanged. Calls append ordinary tool call and result history without replacing prior messages; enabling or disabling the tools changes the schema prefix. + +## Known Limitations and Deferred Work + + + +These constraints affect consumers of the lists. + +- **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. +- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing reads every candidate before selecting a page, so the page size does not bound total work; an unscoped call scales with the Session count. +- **Blank sessions are listed** — a Session without a turn, such as a Workspace's unused new Session, is a regular result; its `updated_at` equals `created_at` and its title is usually `null`. +- **Unscoped listing has unit coverage only** — the recorded headless replay passes `workspace_id` on every `list_session` call, so enumeration without a Workspace runs only in unit tests. +- **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md new file mode 100644 index 0000000000..e11f949f77 --- /dev/null +++ b/packages/session-query/tool-session-list/README.zh.md @@ -0,0 +1,126 @@ +--- +description: "通过可选的只读工具列出 Workspace 和 Session 元数据,支持分页以及缓存中的标题和活动时间。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +[English](README.md) | 中文 + +## 概述 + +无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或列出已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与待办工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在预期调用者获取工具的作用域中挂载此可选插件。它没有配置字段,默认配置方案不包含它。 + +### 访问范围与组合 + +授予这些工具即授予读取已挂载运行时中全部 Workspace 和 Session 的权限。工具可用性就是访问控制;没有逐 agent 的 Workspace ACL,也不会隐式限制到调用者的工作目录。LiveShare 的工具允许列表不包含这些工具。 + +插件需要 `tools`、`sessions`、`sessionQuery`、`workspaceRegistry` 和 `sessionProjections`。投影缓存为冷会话提供元数据;没有缓存时,冷条目使用下文规定的元数据缺失值。在 headless 配置方案中,基础 bundle 已提供其他依赖;在配置方案补丁中添加 Workspace 注册表和此插件: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +如果组合已经挂载 `workspaceRegistry`,只添加工具条目。Workspace 初始化遵循[注册表现有的历史引导行为](../../workspace/workspace/README.zh.md);列表调用不会创建或接入会话,也不会修改注册表记录。 + +### 列表行为 + +两个工具都直接返回数组。[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)定义参数。先过滤和排序,再分页;每次调用默认返回 20 条,最多接受 100 条,起始偏移为零。继续遍历时,将偏移增加已返回的条目数;空数组表示遍历结束。 + +`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 从不返回 subagent 会话。它默认包含未归档会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。归档筛选匹配每个 Session 自身的 ID。 + +会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 + +指定 `workspace_id` 时,调用从 Workspace 注册表索引读取成员 header,不做持久化 I/O,因此工作量随成员数增长。不指定 `workspace_id` 时,先枚举所有已存储和 live Session 的 header。随后的筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 + +### 失败 + +无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +选定 Workspace 时读取 `Workspace.getSessionHeaders()`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。实时条目通过 `ctx.sessionQuery.getListMetadata` 读取空白状态与提示词活动时间,与 Session API 读取同一个投影。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 工具 schema、注册、JSON 结果渲染与通用工具卡片 | +| [`src/list.ts`](src/list.ts) | 分页、成员筛选以及实时或缓存元数据读取 | + +
+ +----- + + +## 进一步探索 + +- [Workspace 注册表](../../workspace/workspace/README.zh.md)——已记录的成员关系、注册表顺序与归档。 +- [Session 查询](../session-query/README.zh.md)——全量 header 枚举与共享列表元数据读取函数。 +- [Session 投影缓存](../../session/session-projection-cache/README.zh.md)——持久化元数据与缓存可用性。 +- [Session 查询包映射](../README.zh.md)——相邻的检索能力。 + +----- + + +## 模型体验 + +### 工具 schema 与结果 + +#### 模型可见内容 + +[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)拥有 `list_workspace` 和 `list_session` 的 schema。每个结果渲染为 JSON 数组。插件不增加独立的系统提示词段落。 + +#### Token 影响 + +可用工具的 schema 占用请求 token;每次调用增加其参数和返回的元数据。每页上限限制返回的条目数,标题和路径长度仍会影响结果大小。 + +#### KV Cache 影响 + +工具可用性不变时,schema 保持稳定。调用追加普通工具调用与结果历史,不替换之前的消息;启用或禁用工具会改变 schema 前缀。 + +## 已知限制与待办工作 + + + +以下约束影响列表消费方。 + +- **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 +- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先读取全部候选项,再选取一页,因此每页大小不限制总工作量;不指定范围的调用随 Session 总数增长。 +- **空白会话也会列出**——还没有 turn 的 Session(例如 Workspace 中未使用的新 Session)是普通结果;它的 `updated_at` 等于 `created_at`,标题通常为 `null`。 +- **不指定范围的列表只有单测覆盖**——录制的 headless 回放中每次 `list_session` 调用都带 `workspace_id`,因此不指定 Workspace 的枚举只在单元测试中运行。 +- **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/session-query/tool-session-list/locale/de.json b/packages/session-query/tool-session-list/locale/de.json new file mode 100644 index 0000000000..ef94863e4f --- /dev/null +++ b/packages/session-query/tool-session-list/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Werkzeuge zur Sitzungsauflistung", + "description": "Listet Arbeitsbereiche und Sitzungen auf, ohne Agenten fortzusetzen." + } +} diff --git a/packages/session-query/tool-session-list/locale/en.json b/packages/session-query/tool-session-list/locale/en.json new file mode 100644 index 0000000000..8b3e1ef64a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Session listing tools", + "description": "List workspaces and sessions without resuming agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/es.json b/packages/session-query/tool-session-list/locale/es.json new file mode 100644 index 0000000000..985fd3aff1 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Herramientas de listado de sesiones", + "description": "Lista espacios de trabajo y sesiones sin reanudar los agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/fr.json b/packages/session-query/tool-session-list/locale/fr.json new file mode 100644 index 0000000000..7e6ec40d8d --- /dev/null +++ b/packages/session-query/tool-session-list/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Outils de liste des sessions", + "description": "Liste les espaces de travail et les sessions sans relancer les agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/ja.json b/packages/session-query/tool-session-list/locale/ja.json new file mode 100644 index 0000000000..43bcd18644 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "セッション一覧ツール", + "description": "エージェントを再開せずにワークスペースとセッションを一覧表示します。" + } +} diff --git a/packages/session-query/tool-session-list/locale/pt.json b/packages/session-query/tool-session-list/locale/pt.json new file mode 100644 index 0000000000..43bdfa3130 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ferramentas de listagem de sessões", + "description": "Lista espaços de trabalho e sessões sem retomar os agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/ru.json b/packages/session-query/tool-session-list/locale/ru.json new file mode 100644 index 0000000000..7cbeb022f3 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Инструменты списка сеансов", + "description": "Показывает рабочие пространства и сеансы без возобновления работы агентов." + } +} diff --git a/packages/session-query/tool-session-list/locale/zh.json b/packages/session-query/tool-session-list/locale/zh.json new file mode 100644 index 0000000000..3588c3e15a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话列表工具", + "description": "列出工作区和会话,无需恢复智能体运行。" + } +} diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json new file mode 100644 index 0000000000..392a8f22ac --- /dev/null +++ b/packages/session-query/tool-session-list/package.json @@ -0,0 +1,71 @@ +{ + "name": "@deepseek-ai/dsh-tool-session-list", + "description": "Read-only paginated Workspace and Session metadata tools", + "version": "0.2.2-rc.3", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session-query/tool-session-list" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./locale/*.json": "./locale/*.json", + "./package.json": "./package.json" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-storage": "workspace:*", + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*", + "@deepseek-ai/dsh-storage-json": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-session-projection-cache": { + "optional": true + }, + "@deepseek-ai/dsh-session-title": { + "optional": true + } + } +} diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts new file mode 100644 index 0000000000..96d2c315f7 --- /dev/null +++ b/packages/session-query/tool-session-list/src/index.ts @@ -0,0 +1,78 @@ +/** + * Opt-in read-only Workspace and Session metadata tools for the mounted runtime. + * @module @deepseek-ai/dsh-tool-session-list + */ + +import type { Context } from '@deepseek-ai/cordis' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { DEFAULT_PAGE_LIMIT, listSessions, listWorkspaces, MAX_PAGE_LIMIT } from './list.ts' + +/** Cordis plugin identity. */ +export const name = 'tool-session-list' +/** Services needed for header-only listing and live metadata. */ +export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] + +const pagination = { + limit: { type: 'integer', description: `Maximum entries to return, from 1 to ${String(MAX_PAGE_LIMIT)}. Defaults to ${String(DEFAULT_PAGE_LIMIT)}.` }, + offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, +} as const + +/** + * Grant tools access to all Workspace and Session metadata in this runtime. + * @param ctx - scoped context granting these tools to its callers. + */ +export function apply(ctx: Context): void { + ctx.tools.register(defineTool({ + name: 'list_workspace', + description: 'List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.', + parameters: pagination, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + workspace_id: { type: 'string', required: true }, + title: { type: 'string', required: true }, + path: { type: 'string', required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 update time.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), + presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), + })) + ctx.tools.register(defineTool({ + name: 'list_session', + description: 'List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', + parameters: { + workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces.' }, + archived: { type: 'boolean', description: 'Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false.' }, + ...pagination, + }, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + session_id: { type: 'string', required: true }, + title: { oneOf: [{ type: 'string' }, { type: 'null' }], required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 latest human prompt time, or creation time when unavailable.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => listSessions(ctx, args, exec.signal), + presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args }), + })) +} diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts new file mode 100644 index 0000000000..6f8e9b3175 --- /dev/null +++ b/packages/session-query/tool-session-list/src/list.ts @@ -0,0 +1,145 @@ +/** Header-only selection and cached metadata for the read-only listing tools. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-query' +import type {} from '@deepseek-ai/dsh-session-projection-cache' +import type {} from '@deepseek-ai/dsh-session-title' +import { ToolArgsError } from '@deepseek-ai/dsh-tools' +import { WorkspaceId } from '@deepseek-ai/dsh-workspace' + +/** Optional model pagination arguments. */ +export interface PageInput { + readonly limit?: number + readonly offset?: number +} + +/** Optional Session selection arguments. */ +export interface SessionListInput extends PageInput { + readonly workspace_id?: string + readonly archived?: boolean +} + +interface WorkspaceListItem { + workspace_id: WorkspaceId + title: string + path: string + created_at: string + updated_at: string +} + +interface SessionListItem { + session_id: SessionId + title: string | null + created_at: string + updated_at: string +} + +/** Entries per page when the model passes no `limit`; part of the model-visible schema. */ +export const DEFAULT_PAGE_LIMIT = 20 +/** Largest accepted `limit`; part of the model-visible schema. */ +export const MAX_PAGE_LIMIT = 100 + +/** + * Resolve pagination before reading any registry or persistence data. + * @param input - model pagination arguments. + * @returns the validated count and starting index. + */ +export function resolvePage(input: PageInput): { limit: number; offset: number } { + const limit = input.limit ?? DEFAULT_PAGE_LIMIT + const offset = input.offset ?? 0 + if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) { + throw new ToolArgsError([`limit must be an integer from 1 to ${String(MAX_PAGE_LIMIT)}`]) + } + if (!Number.isSafeInteger(offset) || offset < 0) { + throw new ToolArgsError(['offset must be a non-negative safe integer']) + } + return { limit, offset } +} + +/** + * Read one page of the authoritative Workspace order, including empty records. + * @param ctx - context providing the Workspace registry. + * @param input - pagination arguments. + * @param signal - caller cancellation. + * @returns Workspace metadata with ISO timestamps. + */ +export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSignal): WorkspaceListItem[] { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + return ctx.workspaceRegistry.list().slice(offset, offset + limit).map(workspace => ({ + workspace_id: workspace.id, + title: workspace.title, + path: workspace.path, + created_at: workspace.createdAt, + updated_at: workspace.updatedAt, + })) +} + +/** + * List live and persisted Session metadata without opening cold logs or activating Agents. + * A Workspace selection reads only its members' indexed headers; an unscoped call enumerates + * the corpus headers. Subagent Sessions are excluded. + * @param ctx - context providing query, Workspace, and projection services. + * @param input - filters and pagination arguments. + * @param signal - caller cancellation, forwarded to the corpus listing. + * @returns filtered Session metadata ordered by activity, then identity. + */ +export async function listSessions( + ctx: Context, + input: SessionListInput, + signal: AbortSignal, +): Promise { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + let headers: readonly SessionHeader[] + if (input.workspace_id === undefined) { + headers = (await ctx.sessionQuery.listSessions(signal)).map(record => record.header) + signal.throwIfAborted() + } else { + const workspace = ctx.workspaceRegistry.get(WorkspaceId(input.workspace_id)) + if (workspace === undefined) { + throw new ToolArgsError([`workspace_id ${JSON.stringify(input.workspace_id)} is not registered; use list_workspace to find a workspace`]) + } + headers = workspace.getSessionHeaders() + } + const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) + const items: Array & { updatedAt: number }> = [] + for (const header of headers) { + if (header.origin === 'subagent') continue + if (archived.has(header.id) !== (input.archived ?? false)) continue + const metadata = readListMetadata(ctx, header) + items.push({ + session_id: header.id, + title: metadata.title, + created_at: new Date(header.createdAt).toISOString(), + updatedAt: Math.max(header.createdAt, metadata.lastPromptAt ?? 0), + }) + } + items.sort((left, right) => right.updatedAt - left.updatedAt + || (left.session_id < right.session_id ? -1 : 1)) + return items.slice(offset, offset + limit).map(({ updatedAt, ...item }) => ({ + ...item, + updated_at: new Date(updatedAt).toISOString(), + })) +} + +function readListMetadata( + ctx: Context, + header: SessionHeader, +): { title: string | null; lastPromptAt: number | null } { + const live = ctx.sessions.get(header.id) + if (live !== undefined) { + return { + title: ctx.sessionProjections.snapshot(live, ['title']).values.title ?? null, + lastPromptAt: ctx.sessionQuery.getListMetadata(live).lastPromptAt, + } + } + const cache = ctx.get('sessionProjectionCache') + const snapshot = cache?.cachedSnapshot(header, ['title', 'sessionListMetadata']) + ?? cache?.cachedPredecessorTitle(header) + return { + title: snapshot?.values.title ?? null, + lastPromptAt: snapshot?.values.sessionListMetadata?.lastPromptAt ?? null, + } +} diff --git a/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts new file mode 100644 index 0000000000..77e9986ed6 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts @@ -0,0 +1,65 @@ +/** Deterministic Session and Workspace inputs for the shipped headless list tools. */ + +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import type {} from '@deepseek-ai/dsh-storage-domain' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' + +/** Loader fixture identity. */ +export const name = 'session-list-seed' +/** Real services used to prepare the scenario's durable registry and attached Sessions. */ +export const inject = ['sessions', 'sessionPersistence', 'storageDomain'] + +/** + * Seed stable list inputs before the Workspace registry becomes available. + * These attached Sessions have no Agent, so the agent-loop persistence owner never publishes them. + * @param ctx - fixture lifetime and the shipped storage and Session services. + * @returns when the actual Workspace registry has opened the seeded domain. + */ +export async function apply(ctx: Context): Promise { + const cwd = process.cwd() + const emptyPath = join(cwd, '.dsh', 'empty-workspace') + await mkdir(emptyPath, { recursive: true }) + const alpha = ctx.sessions.create(SessionId('list-alpha'), { meta: { cwd, createdAt: 1_000 } }) + alpha.append('session/title', { title: 'Alpha', messageSeqs: [], source: { kind: 'user' } }) + ctx.sessions.create(SessionId('list-beta'), { meta: { cwd, createdAt: 2_000 } }) + ctx.sessions.create(SessionId('list-archived'), { meta: { cwd, createdAt: 3_000 } }) + ctx.sessions.create(SessionId('list-child'), { + meta: { cwd, createdAt: 4_000, parentSession: alpha.id, origin: 'subagent', delegationDepth: 1 }, + }) + // Matching cwd alone does not make this Session a member of the stored Workspace. + ctx.sessions.create(SessionId('list-unaffiliated'), { meta: { cwd, createdAt: 5_000 } }) + + const workspaceId = WorkspaceId('list-workspace') + const emptyId = WorkspaceId('list-empty') + const domain = await ctx.storageDomain.open(workspaceDomainSpec) + try { + const table = domain.table('workspaces') + await table.put(workspaceId, { + path: cwd, + title: 'List fixture', + sessionIds: [alpha.id, SessionId('list-beta'), SessionId('list-archived')], + createdAt: '2000-01-01T00:00:00.000Z', + updatedAt: '2000-01-02T00:00:00.000Z', + }) + await table.put(emptyId, { + path: emptyPath, + title: 'Empty workspace', + sessionIds: [], + createdAt: '2000-01-03T00:00:00.000Z', + updatedAt: '2000-01-04T00:00:00.000Z', + }) + await domain.global.set({ + initialized: true, + workspaceIds: [workspaceId, emptyId], + archivedSessionIds: [SessionId('list-archived')], + pinnedSessionIds: [], + }) + } finally { + await domain.close() + } + await ctx.plugin(WorkspaceRegistry) +} diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts new file mode 100644 index 0000000000..b9d54912f0 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -0,0 +1,336 @@ +import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' +import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' +import type { SessionHandle, SessionPersistenceListOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' +import type { CheckpointRecord } from '@deepseek-ai/dsh-session-projection-cache' +import SessionQueryEngine from '@deepseek-ai/dsh-session-query' +import type { SessionEventSearchPage, SessionSearchHit, SessionSearchPage } from '@deepseek-ai/dsh-session-query' +import { titleProjectionDefinition } from '@deepseek-ai/dsh-session-title' +import Storage from '@deepseek-ai/dsh-storage' +import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' +import * as StorageJson from '@deepseek-ai/dsh-storage-json' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' +import type { WorkspaceRecord } from '@deepseek-ai/dsh-workspace' +import { afterEach, describe, expect, it, vi } from 'vitest' +import * as ToolSessionList from '../src/index.ts' + +const contexts: Context[] = [] +const roots: string[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) +}) + +class HeaderPersistence extends SessionPersistence { + readonly headers: SessionHeader[] + + constructor(ctx: Context, config: { headers: SessionHeader[] }) { + super(ctx) + this.headers = config.headers + } + + override create = vi.fn((): Promise => Promise.reject(new Error('listing must not create a stored Session'))) + override open = vi.fn((): Promise => Promise.reject(new Error('listing must not open an event log'))) + override flush = vi.fn((): Promise => Promise.resolve()) + override stat = vi.fn((): Promise => Promise.reject(new Error('listing must not stat each Session'))) + override list = vi.fn((options?: SessionPersistenceListOptions): Promise => { + options?.signal?.throwIfAborted() + return Promise.resolve(this.headers.map(header => ({ header, revision: SessionPersistenceRevision(`rev-${header.id}`) }))) + }) +} + +class ListingQuery extends SessionQueryEngine { + override searchSessions(): Promise> { + return Promise.reject(new Error('listing must not search Session contents')) + } + + override searchEvents(): Promise { + return Promise.reject(new Error('listing must not search event contents')) + } +} + +function header(id: string, createdAt: number, options: Partial> = {}): SessionHeader { + return { id: SessionId(id), version: SESSION_FORMAT_VERSION, createdAt, isSeeded: false, ...options } +} + +function workspace(path: string, sessionIds: string[] = [], title = 'Workspace'): WorkspaceRecord { + return { + path, + title, + sessionIds: sessionIds.map(SessionId), + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-02T00:00:00.000Z', + } +} + +function checkpoint(meta: SessionHeader, title: string | null, lastPromptAt: number | null): CheckpointRecord { + return { + identity: { + formatVersion: meta.version, + createdAt: meta.createdAt, + isSeeded: false, + inheritedEventCount: SessionLogOffset(0), + ...meta.cwd === undefined ? {} : { cwd: meta.cwd }, + }, + rows: { + title: { ver: 1, seq: -1, val: title }, + sessionListMetadata: { ver: 1, seq: -1, val: { blank: false, lastPromptAt } }, + }, + } +} + +async function directory(): Promise { + const root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-session-list-'))) + roots.push(root) + return root +} + +async function mount(options: { + headers?: SessionHeader[] + workspaces?: Array<[string, WorkspaceRecord]> + archived?: string[] + cached?: Array<[string, CheckpointRecord]> + cache?: boolean +} = {}) { + const workspaces = options.workspaces ?? [] + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(Storage) + await ctx.plugin(StorageJson, { root: await directory() }) + await ctx.plugin(StorageDomain, { backend: 'json' }) + const workspaceDomain = await ctx.storageDomain.open(workspaceDomainSpec) + for (const [id, record] of workspaces) await workspaceDomain.table('workspaces').put(WorkspaceId(id), record) + await workspaceDomain.global.set({ + initialized: true, + workspaceIds: workspaces.map(([id]) => WorkspaceId(id)), + archivedSessionIds: (options.archived ?? []).map(SessionId), + pinnedSessionIds: [], + }) + await workspaceDomain.close() + const cacheDomain = await ctx.storageDomain.open(projectionCacheDomainSpec) + for (const [id, record] of options.cached ?? []) await cacheDomain.table('sessions').put(SessionId(id), record) + await cacheDomain.close() + await ctx.plugin(HeaderPersistence, { headers: options.headers ?? [] }) + await ctx.plugin(WorkspaceRegistry) + if (options.cache !== false) { + await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 1000, writeIntervalMs: 60_000 }) + } + await ctx.sessionProjections.register(titleProjectionDefinition) + await ctx.plugin(ListingQuery) + const fiber = await ctx.plugin(ToolSessionList) + const read = vi.spyOn(ctx.sessionQuery, 'readSession') + const titles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') + const open = vi.spyOn(ctx.sessionPersistence, 'open') + let callId = 0 + return { + ctx, + fiber, + read, + titles, + open, + call: (name: string, args: unknown = {}, signal = new AbortController().signal) => executeToolFixture(ctx, { + name, arguments: args, callId: ToolCallId(`list-${++callId}`), signal, + }), + } +} + +function value(result: ToolExecutionResult) { + if (result.isError) throw new Error(result.error.message) + return result.value +} + +function item(id: string, createdAt: number, updatedAt = createdAt, title: string | null = null) { + return { session_id: id, title, created_at: new Date(createdAt).toISOString(), updated_at: new Date(updatedAt).toISOString() } +} + +function prompt(session: Session) { + session.append('turn/start', { turn: 1 }) + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Human prompt' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +describe('read-only Session list tools', () => { + it('lists empty Workspaces in registry order and applies offset after that order', async () => { + const path = await directory() + const secondPath = join(path, 'second') + await mkdir(secondPath) + const first = workspace(path, [], 'First') + const second = workspace(secondPath, [], 'Second') + const mounted = await mount({ workspaces: [['z-workspace', first], ['a-workspace', second]] }) + const rows = [first, second].map((record, index) => ({ + workspace_id: index === 0 ? 'z-workspace' : 'a-workspace', + title: record.title, path: record.path, created_at: record.createdAt, updated_at: record.updatedAt, + })) + expect(value(await mounted.call('list_workspace'))).toEqual(rows) + expect(value(await mounted.call('list_workspace', { limit: 1, offset: 1 }))).toEqual([rows[1]]) + expect(value(await mounted.call('list_workspace', { offset: 2 }))).toEqual([]) + expect(value(await mounted.call('list_session'))).toEqual([]) + }) + + it('uses current live metadata, cached cold metadata, and creation time for cache misses without opening logs', async () => { + const cold = header('cold', 10) + const live = header('live', 20) + const missing = header('missing', 30) + const mounted = await mount({ + headers: [cold, live, missing], + cached: [['cold', checkpoint(cold, 'Cold title', 100)], ['live', checkpoint(live, 'Old title', 90)]], + }) + const session = mounted.ctx.sessions.create(live.id, { meta: { createdAt: live.createdAt } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('cold', 10, 100, 'Cold title'), item('missing', 30), item('live', 20), + ]) + const human = prompt(session) + session.append('session/title', { title: 'Live title', messageSeqs: [], source: { kind: 'user' } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('live', 20, human.time, 'Live title'), item('cold', 10, 100, 'Cold title'), item('missing', 30), + ]) + expect(mounted.ctx.agents.list()).toEqual([]) + expect(mounted.ctx.sessions.list()).toEqual([session]) + expect(mounted.read).not.toHaveBeenCalled() + expect(mounted.titles).not.toHaveBeenCalled() + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('uses creation time and null titles when the optional projection cache is not mounted', async () => { + const mounted = await mount({ headers: [header('cold', 10)], cache: false }) + expect(value(await mounted.call('list_session'))).toEqual([item('cold', 10)]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('keeps the title hint of a predecessor cache without using its activity metadata', async () => { + const cold = header('predecessor', 10) + const old = checkpoint(cold, 'Prior title', 100) + old.identity.formatVersion = SESSION_FORMAT_VERSION - 1 + const mounted = await mount({ headers: [cold], cached: [[cold.id, old]] }) + expect(value(await mounted.call('list_session'))).toEqual([item('predecessor', 10, 10, 'Prior title')]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('filters archive status and subagents before sorting and pagination; pins do not reorder results', async () => { + const mounted = await mount({ + headers: [header('z', 100), header('b', 100), header('a', 100), header('archived', 500), header('child', 200, { origin: 'subagent', parentSession: SessionId('z') })], + archived: ['archived'], + }) + await mounted.ctx.workspaceRegistry.pinSession(SessionId('z')) + expect(value(await mounted.call('list_session', { limit: 1, offset: 1 }))).toEqual([item('b', 100)]) + expect(value(await mounted.call('list_session'))).toEqual([item('a', 100), item('b', 100), item('z', 100)]) + expect(value(await mounted.call('list_session', { archived: true }))).toEqual([item('archived', 500)]) + expect(value(await mounted.call('list_session', { archived: true, offset: 1 }))).toEqual([]) + }) + + it('breaks cached-activity ties by ID even when creation order differs', async () => { + const headers = [header('a', 10), header('b', 20), header('z', 30)] + const mounted = await mount({ headers, cached: headers.map(meta => [meta.id, checkpoint(meta, null, 100)]) }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('a', 10, 100), item('b', 20, 100), item('z', 30, 100), + ]) + }) + + it('lists recorded non-subagent Workspace members from indexed headers without enumerating the corpus', async () => { + const path = await directory() + const otherPath = join(path, 'other') + await mkdir(otherPath) + const mounted = await mount({ + headers: [ + header('parent', 10, { cwd: path }), + header('member', 20, { cwd: path }), + header('same-cwd', 30, { cwd: path }), + header('child', 40, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('assigned-child', 50, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('other-member', 60, { cwd: otherPath }), + ], + workspaces: [ + ['primary', workspace(path, ['parent', 'member', 'assigned-child'])], + ['other', workspace(otherPath, ['other-member'])], + ], + archived: ['parent'], + }) + const corpus = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions') + // Registry startup already listed the stored headers; only later listings matter. + const stored = vi.spyOn(mounted.ctx.sessionPersistence, 'list') + stored.mockClear() + expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([item('member', 20)]) + expect(value(await mounted.call('list_session', { workspace_id: 'primary', archived: true }))).toEqual([item('parent', 10)]) + expect(value(await mounted.call('list_session', { workspace_id: 'other' }))).toEqual([item('other-member', 60)]) + expect(corpus).not.toHaveBeenCalled() + expect(stored).not.toHaveBeenCalled() + expect(value(await mounted.call('list_session'))).toEqual([item('other-member', 60), item('same-cwd', 30), item('member', 20)]) + expect(corpus).toHaveBeenCalledOnce() + }) + + it('defaults to twenty rows and accepts the upper page limit', async () => { + const headers = Array.from({ length: 101 }, (_, index) => header(`session-${String(index).padStart(3, '0')}`, index)) + const mounted = await mount({ headers }) + expect(value(await mounted.call('list_session'))).toHaveLength(20) + expect(value(await mounted.call('list_session', { limit: 100 }))).toHaveLength(100) + expect(value(await mounted.call('list_session', { limit: 100, offset: 100 }))).toEqual([item('session-000', 0)]) + }) + + it.each(['list_workspace', 'list_session'])('rejects invalid pagination for %s with INVALID_ARGS', async (name) => { + const mounted = await mount() + const invalid = [{ limit: 0 }, { limit: 101 }, { limit: 1.5 }, { offset: -1 }, { offset: 1.5 }, { offset: Number.MAX_SAFE_INTEGER + 1 }] + for (const args of invalid) { + const result = await mounted.call(name, args) + expect(result.isError).toBe(true) + expect(result.error?.info).toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + } + }) + + it('rejects an unknown Workspace with a typed failure', async () => { + const mounted = await mount() + expect((await mounted.call('list_session', { workspace_id: 'absent' })).error?.info) + .toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('propagates cancellation during corpus discovery without reading metadata or activating Agents', async () => { + const mounted = await mount({ headers: [header('cold', 10)] }) + const controller = new AbortController() + const list = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions').mockImplementation(async (signal) => { + expect(signal).toBe(controller.signal) + controller.abort(new Error('list cancelled')) + return [] + }) + const result = await mounted.call('list_session', {}, controller.signal) + expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + expect(list).toHaveBeenCalledOnce() + expect(mounted.open).not.toHaveBeenCalled() + expect(mounted.ctx.agents.list()).toEqual([]) + }) + + it('registers concurrency-safe generic presentation and releases both tools on disposal', async () => { + const mounted = await mount() + for (const name of ['list_workspace', 'list_session']) { + const tool = mounted.ctx.tools.get(name) + expect(tool?.isConcurrencySafe?.({})).toBe(true) + expect(tool?.presentCall?.({})).toMatchObject({ card: 'generic', kind: 'read' }) + } + const page = { limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_workspace')?.presentCall?.(page)).toMatchObject({ rawInput: page }) + const filters = { workspace_id: 'w1', archived: true, limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_session')?.presentCall?.(filters)).toMatchObject({ rawInput: filters }) + await mounted.fiber.dispose() + expect(mounted.ctx.tools.get('list_workspace')).toBeUndefined() + expect(mounted.ctx.tools.get('list_session')).toBeUndefined() + }) +}) diff --git a/packages/session-query/tool-session-list/tsconfig.json b/packages/session-query/tool-session-list/tsconfig.json new file mode 100644 index 0000000000..d2eabc4754 --- /dev/null +++ b/packages/session-query/tool-session-list/tsconfig.json @@ -0,0 +1,39 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-query" + }, + { + "path": "../../session/session-projection" + }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/session-title" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/packages/session/session-title-first-prompt-llm/src/index.ts b/packages/session/session-title-first-prompt-llm/src/index.ts index 7515630a88..099cf3c830 100644 --- a/packages/session/session-title-first-prompt-llm/src/index.ts +++ b/packages/session/session-title-first-prompt-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -128,10 +129,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/session/session-title/src/index.ts b/packages/session/session-title/src/index.ts index c80ae7e830..9917187dba 100644 --- a/packages/session/session-title/src/index.ts +++ b/packages/session/session-title/src/index.ts @@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Branded } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values' @@ -137,10 +138,7 @@ export interface SessionTitleProvider { function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined const content = event.data.content - const text = content - .filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join('\n') + const text = extractTextContent(content, { separator: '\n' }) if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined return { seq: event.seq, text } } diff --git a/packages/subagent/tool-subagent-control/README.i18n.yaml b/packages/subagent/tool-subagent-control/README.i18n.yaml index 36dc72bfa8..49fcadff0b 100644 --- a/packages/subagent/tool-subagent-control/README.i18n.yaml +++ b/packages/subagent/tool-subagent-control/README.i18n.yaml @@ -69,8 +69,8 @@ en: fc88c8ffb8ebc083 zh: 0baf2e5df37d813e /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees: - en: 3f59216388405b66 - zh: 70672463706bc5c5 + en: 2398af9e6e80f928 + zh: 4585ff2e63441896 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees/subagent-identity: en: fc2b3383d52ded16 zh: d5074e59b79c7afd @@ -78,8 +78,8 @@ en: 37a7eed766856ea0 zh: 4a564f74e08a3252 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/kv-cache-effect: - en: 49dc6a07ae9640e3 - zh: 465fcd7cfe452ad2 + en: 8879c43a533f66da + zh: 75f30ae42ea19311 /deepseek-ai-dsh-tool-subagent-control/model-experience/interrupt-result: en: d64e936e83e89a2b zh: b9905c33af6cca45 diff --git a/packages/subagent/tool-subagent-control/README.md b/packages/subagent/tool-subagent-control/README.md index a66d8ce145..6b3bde77fb 100644 --- a/packages/subagent/tool-subagent-control/README.md +++ b/packages/subagent/tool-subagent-control/README.md @@ -125,7 +125,7 @@ Prefix-stable; the schemas do not change at runtime, and a parent and its contin #### What the model sees -Required `subagent:identity` runtime context identifies each agent by name. It is independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. The root sees `You are the root agent. Your name is "lead".` followed by the same guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: +Required `subagent:identity` runtime context identifies each agent by name. Its identity lines are independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. While Team mode is off, a subagent with `send_message` is also told to send a self-contained result to the agent that delegated it when it finishes, and to message any agent as soon as a finding changes what that agent should do next. The root sees `You are the root agent. Your name is "lead".` followed by the same messaging and discovery guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: ##### Subagent identity @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ One short context entry per agent, independent of tree size; full names lengthen #### KV Cache effect -Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Team mode does not change it. +Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Switching Team mode adds or removes the report instruction for delegated children, which appends one runtime-context snapshot on the next request. ### Interrupt result diff --git a/packages/subagent/tool-subagent-control/README.zh.md b/packages/subagent/tool-subagent-control/README.zh.md index 2b5a505be5..7dfcd3fda6 100644 --- a/packages/subagent/tool-subagent-control/README.zh.md +++ b/packages/subagent/tool-subagent-control/README.zh.md @@ -125,7 +125,7 @@ kind: "package-reference" #### 模型看到什么 -必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。该上下文独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。根看到 `You are the root agent. Your name is "lead".`,后接相同指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: +必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。其中的身份行独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。Team 模式关闭时,获准 `send_message` 的 subagent 还会被要求在完成时把自包含结果发送给委派它的 agent,并在某项发现改变任一 agent 的下一步行动时立即通知该 agent。根看到 `You are the root agent. Your name is "lead".`,后接相同的通信与发现指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: ##### Subagent 身份 @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ Use list_agents({}) to find your collaborator agents and their names. #### KV Cache 影响 -身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。Team 模式不会改变它。 +身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。切换 Team 模式会为委派子级增删汇报要求,并在下一次请求时追加一份运行时上下文快照。 ### 中断结果 diff --git a/packages/subagent/tool-subagent-control/package.json b/packages/subagent/tool-subagent-control/package.json index d5aaeebdb1..190f43675d 100644 --- a/packages/subagent/tool-subagent-control/package.json +++ b/packages/subagent/tool-subagent-control/package.json @@ -38,9 +38,16 @@ "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-agent-team": { + "optional": true + } }, "devDependencies": { + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index 8f9ecc95ba..4e59ff8e28 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -14,6 +14,7 @@ import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { ROOT_AGENT_NAME } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-agent-team' import { registerListAgents } from './list-agents.ts' import { registerWaitAgent } from './wait-agent.ts' @@ -99,6 +100,11 @@ export function apply(ctx: Context, config: Config = {}): void { const guidance: string[] = [] if (ctx.tools.get(sendMessage.name, scope, toolSet) === sendMessage) { guidance.push('To message other agents, use send_message({ agent: "", message: "..." }).') + // Team mode coordinates results through shared tasks, so only plain delegation asks for a report. + if (names.parent !== undefined && ctx.get('agentTeams')?.isEnabled(agent) !== true) { + guidance.push('When you finish, use send_message to send a self-contained result to the agent that delegated you. ' + + 'Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.') + } } if (ctx.tools.get(listAgents.name, scope, toolSet) === listAgents) { guidance.push('Use list_agents({}) to find your collaborator agents and their names.') diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index a6b5b08860..868aec9da5 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -16,6 +16,7 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import type { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentRuntime, { SubagentError } from '@deepseek-ai/dsh-subagent' +import TeamService from '@deepseek-ai/dsh-agent-team' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -203,9 +204,10 @@ describe('dsh-tool-subagent-control', () => { }) it.each([ + { name: 'send_message', instruction: 'use send_message to send a self-contained result to the agent that delegated you', other: 'Use list_agents' }, { name: 'send_message', instruction: 'To message other agents', other: 'Use list_agents' }, { name: 'list_agents', instruction: 'Use list_agents', other: 'To message other agents' }, - ])('gates $name guidance independently in an agent scope', async ({ name, instruction, other }) => { + ])('gates $name guidance "$instruction" independently in an agent scope', async ({ name, instruction, other }) => { const { ctx, parent } = await setup([]) const { agent: child } = await ctx.agents.create({ sessionId: brandString('communication-child'), @@ -233,6 +235,26 @@ describe('dsh-tool-subagent-control', () => { toolSet.dispose() }) + it('asks a delegated agent to report with send_message only while Team mode is off', async () => { + const { ctx, parent } = await setup([]) + await ctx.plugin(TeamService) + const { agent: child } = await ctx.agents.create({ + sessionId: brandString('team-child'), + meta: { origin: 'subagent', parentSession: parent.id }, + setup: (_ctx, agent) => { bindSubagentActivation(ctx, agent, parent) }, + }) + const report = 'When you finish, use send_message to send a self-contained result to the agent that delegated you.' + const communication = async () => renderContextSnapshot(await ctx.systemPrompt.assemble({ agent: child, scope: child })) + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + await ctx.agentTeams.setEnabled(parent, true) + const team = await communication() + expect(team).not.toContain(report) + expect(team).toContain('To message other agents') + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + }) + it('keeps collaboration instructions when controls are mounted in an agent scope', async () => { const { ctx, parent, controlFiber } = await setup([]) await controlFiber.dispose() diff --git a/packages/subagent/tool-subagent-control/tsconfig.json b/packages/subagent/tool-subagent-control/tsconfig.json index 78c8a11d76..34b7189834 100644 --- a/packages/subagent/tool-subagent-control/tsconfig.json +++ b/packages/subagent/tool-subagent-control/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../core/system-prompt" + }, + { + "path": "../../team/agent-team" } ] } diff --git a/packages/team/tool-agent-team/README.i18n.yaml b/packages/team/tool-agent-team/README.i18n.yaml index 02c1529c0b..fa9b648aeb 100644 --- a/packages/team/tool-agent-team/README.i18n.yaml +++ b/packages/team/tool-agent-team/README.i18n.yaml @@ -39,8 +39,8 @@ en: 3b906bae9ec19393 zh: 42c8dd145c704cb3 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/policy-and-tools: - en: 79c000a90c6c05a4 - zh: 610e2cebc2431674 + en: c251c8ea9e0eb835 + zh: fe99017a1714ac16 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/scoped-registration-and-teardown: en: ee8db166c0bc8a9b zh: 6bfe192220e931a6 diff --git a/packages/team/tool-agent-team/README.md b/packages/team/tool-agent-team/README.md index a4d69ef4b3..be1ffa05fa 100644 --- a/packages/team/tool-agent-team/README.md +++ b/packages/team/tool-agent-team/README.md @@ -89,7 +89,7 @@ The [subagent teammates Agent Note](../../../.agents/notes/implemented/architect ### Policy and tools -One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and remain unchanged when Team mode switches. The subagent runtime delivers final results. +One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and keep that ownership when Team mode switches; enabling Team mode removes only their result report instruction. The subagent runtime delivers final results. ### Scoped registration and teardown diff --git a/packages/team/tool-agent-team/README.zh.md b/packages/team/tool-agent-team/README.zh.md index 063fbcbd26..f8fe783cbc 100644 --- a/packages/team/tool-agent-team/README.zh.md +++ b/packages/team/tool-agent-team/README.zh.md @@ -89,7 +89,7 @@ kind: "package-reference" ### 策略与工具 -一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),在切换 Team 模式时保持不变。subagent 运行时负责投递最终结果。 +一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),切换 Team 模式时归属不变;开启 Team 模式只会去掉其中的结果汇报要求。subagent 运行时负责投递最终结果。 ### 按作用域注册与拆除 diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index 585ecc185e..52002d2829 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -61,5 +61,7 @@ export const remoteDefaultResponses: RemoteTable = { 'remoteAccess/follow': openStream([{ type: 'baseline', owner: true }]), // ui-sidebar-terminal header entry `agent-terminals`: the displayed Session's terminal roster, then open. 'terminal/watch': openStream([[]]), + // ui-connector-account `apply`: the registered connector accounts, none in a default composition, then open. + 'connectorAccounts/watch': openStream([{ accounts: [] }]), }, } diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 88f972c641..53da7fdbdf 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -23,6 +23,7 @@ import { credentialRef, credentialRefConfigured, resolveCredentialRef, type Cred import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { assertUsableApiKey, type LlmCredentialKind } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -157,7 +158,7 @@ const CAPABILITY = { function latestUserQuestion(session: Session | undefined): string | undefined { const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user') if (prompt === undefined) return undefined - return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + return extractTextContent(prompt.content, { separator: '\n' }) } /** diff --git a/packages/workflow/workflow-ptc/src/guest-source.ts b/packages/workflow/workflow-ptc/src/guest-source.ts index ff57ab8e8f..86ae9078ed 100644 --- a/packages/workflow/workflow-ptc/src/guest-source.ts +++ b/packages/workflow/workflow-ptc/src/guest-source.ts @@ -1,4 +1,4 @@ /** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */ /** Self-contained ESM guest transported into the mounted PTC runtime. */ -export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn outputText(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" +export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/llm/llm/src/message.ts\n/**\n* Extract and join only text blocks in content order, preserving their whitespace.\n* Non-text blocks contribute neither text nor separators; content is not modified.\n* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.\n* @param content - source blocks to read in their existing order.\n* @param options - optional text extraction settings.\n* @param options.separator - text inserted between text blocks; defaults to an empty string.\n* @returns joined text, or an empty string when no text blocks are present.\n*/\nfunction extractTextContent(content, options) {\n\treturn content.filter((block) => block.type === \"text\").map((block) => block.text).join(options?.separator ?? \"\");\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn extractTextContent(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" diff --git a/packages/workflow/workflow-ptc/src/runtime.ts b/packages/workflow/workflow-ptc/src/runtime.ts index b99424420b..ca79b2f3fb 100644 --- a/packages/workflow/workflow-ptc/src/runtime.ts +++ b/packages/workflow/workflow-ptc/src/runtime.ts @@ -7,7 +7,7 @@ import * as vm from 'node:vm' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' @@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', /** Deferred Claude Code options we name explicitly in the rejection message. */ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType']) -/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */ -function outputText(blocks: ContentBlock[]): string { - return blocks - .filter((block): block is Extract => block.type === 'text') - .map(block => block.text) - .join('') -} - /** A short display label derived from the prompt when the script passes none. */ function defaultLabel(prompt: string): string { const newline = prompt.indexOf('\n') @@ -222,7 +214,7 @@ export class WorkflowExecution { return result.structured } this.observer.agentEnd({ ...info, outcome: 'completed' }) - return outputText(result.output) + return extractTextContent(result.output) } this.observer.agentEnd({ ...info, outcome: 'failed' }) return null diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index d90b57b56d..1f922bc5f3 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -9,8 +9,8 @@ en: 7a12adba4e7766e3 zh: f6d5c8374f4512c8 /deepseek-ai-dsh-workspace/summary: - en: 30aea62cabd8e8a8 - zh: b22b30ef08fd4713 + en: 587ea2786e0c12a6 + zh: 6bb61ba4379886b4 /deepseek-ai-dsh-workspace/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -39,8 +39,8 @@ en: 447ced401b3b14a8 zh: 3ce2105605223945 /deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy: - en: e969314497b99389 - zh: 82eafc832617a1eb + en: 9e06dc2424613790 + zh: 806bf45f13ebcc72 /deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior: en: 8fcd81ee32f3c01e zh: 08ac92d085bb8147 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index bafe861a81..2237c64c31 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it is invisible to models and adds no prompt or request-context cost, but requires session persistence and storage backends. +Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it adds no model-visible surface or prompt or request-context cost of its own (the optional [listing tools](../../session-query/tool-session-list/README.md) expose Workspace metadata to models), but requires session persistence and storage backends. ## Table of Contents @@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the ### Design philosophy - **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths. -- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. The strict canonical-path index used for history bootstrap includes existing directories only. +- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `getSessionHeaders()` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. - **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded. - **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption. - **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot. diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index c894d3264a..9bbff74562 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它对模型不可见,不增加提示词或请求上下文成本,但需要会话持久化与存储后端。 +使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它自身不增加模型可见内容,也不增加提示词或请求上下文成本(可选的[列表工具](../../session-query/tool-session-list/README.zh.md)会向模型提供 Workspace 元数据),但需要会话持久化与存储后端。 ## 目录 @@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操 ### 设计理念 - **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。 -- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。历史引导使用的严格规范路径索引只包含现存目录。 +- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`getSessionHeaders()` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 - **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。 - **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。 - **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。 diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index 0d687e8c94..7bf2ea5727 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -29,7 +29,8 @@ export class WorkspaceMoveInvalidError extends Error { /** * The registry-owned machinery an entity mutates through. Entities never see * the registry itself — only the open table, the canonical session-path - * index backing the `sessionIds` projection, and attach-time header reads. + * index backing the `sessionIds` projection, its header index, and + * attach-time header reads. */ export interface WorkspaceEntityHost { /** @@ -55,6 +56,13 @@ export interface WorkspaceEntityHost { */ readSessionHeader(id: SessionId): Promise + /** + * Read the indexed header of a session that {@link candidateMatches} accepted. + * @param id - Session currently returned by `sessionIds`. + * @returns the immutable indexed header. + */ + sessionHeader(id: SessionId): SessionHeader + /** * Publish a successfully validated canonical cwd to the projection index. * @param id - Validated session id. @@ -103,6 +111,11 @@ export class WorkspaceEntity implements Workspace { return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path)) } + /** Reads the registry's startup and attach-time header index without persistence I/O. */ + getSessionHeaders(): readonly SessionHeader[] { + return this.sessionIds.map(id => this.host.sessionHeader(id)) + } + async setTitle(title: string): Promise { await this.mutate(record => ({ ...record, title })) } diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 1210cae33d..5bf51e3e0b 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -201,6 +201,14 @@ export class WorkspaceRegistry extends Service { table: () => this.requireTable(), candidateMatches: (id, path) => this.sessionPaths.get(id) === path || this.missingSessionPaths.has(id), readSessionHeader: id => this.readSessionHeader(id), + sessionHeader: (id) => { + const header = this.headers.get(id) + /* v8 ignore next 3 -- every path that admits a candidate indexes its header first. */ + if (header === undefined) { + throw new Error(`workspace member '${id}' has no indexed session header`) + } + return header + }, rememberSessionPath: (id, path) => { this.sessionPaths.set(id, path) this.missingSessionPaths.delete(id) diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index 1b09bef969..aa47a38627 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -6,7 +6,7 @@ */ import type { Branded } from '@deepseek-ai/dsh-brand' -import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session/types' import type { TypertResource } from '@deepseek-ai/dsh-typert-protocol' /** @@ -99,6 +99,12 @@ export interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. + */ + getSessionHeaders(): readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index fcaf99d914..427e53337d 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -668,9 +668,25 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(brandString('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) + it('includes a newly created and attached Session in later header lists', async () => { + const dir = await makeDir('attach-headers') + const result = await harness() + result.setSessions([header('s1', dir, 1)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(brandString('s1')) + const before = workspace.getSessionHeaders() + expect(before).toEqual([header('s1', dir, 1)]) + + result.setSessions([header('s1', dir, 1), header('s2', dir, 2)]) + await workspace.attachSession(brandString('s2')) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) + expect(before).toEqual([header('s1', dir, 1)]) + }) + it('moves one id before an anchor or to the end, durably', async () => { const dir = await makeDir('insert-before') const result = await harness() @@ -891,6 +907,7 @@ describe('header-validated membership projection', () => { onTestFinished(() => result.ctx.fiber.dispose()) const workspace = result.registry.get(id)! expect(workspace.sessionIds).toEqual(['missing-dir']) + expect(workspace.getSessionHeaders()).toEqual([header('missing-dir', missing)]) await workspace.setTitle('Validated') expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir']) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 77b878965a..368c03c86b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -132,6 +132,9 @@ importers: '@deepseek-ai/dsh-tool-ralph': specifier: workspace:* version: link:packages/experimental/tool-ralph + '@deepseek-ai/dsh-tool-session-list': + specifier: workspace:* + version: link:packages/session-query/tool-session-list '@deepseek-ai/dsh-tool-session-query': specifier: workspace:* version: link:packages/experimental/tool-session-query @@ -1609,6 +1612,9 @@ importers: '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../client/product-analytics + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-plugin-manager': specifier: workspace:* version: link:../../client/ui-plugin-manager @@ -3137,6 +3143,9 @@ importers: '@deepseek-ai/dsh-client-ui-commands': specifier: workspace:* version: link:../../client/ui-commands + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-context-menu': specifier: workspace:* version: link:../../client/ui-context-menu @@ -4380,6 +4389,67 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-connector-account: + dependencies: + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../locale + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-layout': + specifier: workspace:* + version: link:../ui-layout + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:* + version: link:../ui-plugin-manager + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-package-manifest': + specifier: workspace:* + version: link:../../util/package-manifest + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + packages/client/ui-context-menu: devDependencies: '@deepseek-ai/cordis': @@ -12606,6 +12676,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:* version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection '@deepseek-ai/dsh-session-query-sqlite': specifier: workspace:* version: link:../../session-query/session-query-sqlite @@ -15811,6 +15884,9 @@ importers: '@deepseek-ai/dsh-session-format-catalog': specifier: workspace:* version: link:../../session/session-format-catalog + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -15871,6 +15947,60 @@ importers: specifier: workspace:* version: link:../session-query + packages/session-query/tool-session-list: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:* + version: link:../../session/session-persistence + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-session-projection-cache': + specifier: workspace:* + version: link:../../session/session-projection-cache + '@deepseek-ai/dsh-session-query': + specifier: workspace:* + version: link:../session-query + '@deepseek-ai/dsh-session-title': + specifier: workspace:* + version: link:../../session/session-title + '@deepseek-ai/dsh-storage': + specifier: workspace:* + version: link:../../storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:* + version: link:../../storage/storage-domain + '@deepseek-ai/dsh-storage-json': + specifier: workspace:* + version: link:../../storage/storage-json + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-executor-native': + specifier: workspace:* + version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tool-testkit': + specifier: workspace:* + version: link:../../test-support/tool-testkit + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-workspace': + specifier: workspace:* + version: link:../../workspace/workspace + packages/session/message-quotes: devDependencies: '@deepseek-ai/cordis': @@ -18239,6 +18369,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-agent-team': + specifier: workspace:* + version: link:../../team/agent-team '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 0d6adaeb9e..dfa2b4b516 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -64,6 +64,7 @@ export const SERVICE_PAGE: Record = { actionCards: 'boot.md', pluginRecommendations: 'boot.md', pluginMarket: 'boot.md', + connectorAccounts: 'boot.md', pluginRegistryProbe: 'boot.md', configEditor: 'boot.md', profileContext: 'boot.md', @@ -757,6 +758,7 @@ export const LINK_MAP: Readonly> = { SessionEventTraceRequest: 'session-query.md', SessionEventWindow: 'session-query.md', SessionLineageTrace: 'session-query.md', + SessionListMetadata: 'session-query.md', SessionObservation: 'session-query.md', SessionObservationOptions: 'session-query.md', SessionRecord: 'session-query.md', @@ -1059,6 +1061,10 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ /** Project types deliberately documented outside the subsystems catalog. */ export const TYPE_LINK_EXEMPTIONS: Readonly> = { + AnyConnectorAccountView: 'generic connector account view is owned by packages/client/ui-connector-account/README.md', + ConnectorAccountRegistration: 'Plugins page account registration is owned by packages/client/ui-connector-account/README.md', + ConnectorAccountsView: 'registered account stream item is owned by packages/client/ui-connector-account/README.md', + ConnectorOperationId: 'account operation id is owned by packages/client/ui-connector-account/README.md', ActionCardDecision: 'packages/experimental/action-cards/README.md', ActionCardKind: 'packages/experimental/action-cards/README.md', ActionCardResult: 'packages/experimental/action-cards/README.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index ec39c6ac2d..21449ee8d8 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -177,6 +177,13 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['plugin-manager'], note: 'Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers.', }, + { + key: 'connectorAccounts', + pkg: 'client-ui-connector-account', + title: 'Connector accounts on the Plugins page', + mode: 'service', + note: 'Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation.', + }, { key: 'pluginMarket', pkg: 'plugin-market', diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index fda6ce6d8e..e77077aacb 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -8,7 +8,7 @@ import { globSync, readFileSync, writeFileSync } from 'node:fs' import { basename, dirname, resolve } from 'node:path' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import LlmRuntime from '@deepseek-ai/dsh-llm' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -71,6 +71,8 @@ import Lsp from '@deepseek-ai/dsh-lsp' import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import * as ToolSkill from '@deepseek-ai/dsh-tool-skill' import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' +import * as ToolSessionList from '@deepseek-ai/dsh-tool-session-list' +import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' import * as ToolJobs from '@deepseek-ai/dsh-tool-jobs' import BrowserUseRegistry from '@deepseek-ai/dsh-browser-use' import * as StagehandBrowserTools from '@deepseek-ai/dsh-experimental-browser-use-stagehand-native' @@ -137,6 +139,13 @@ class CatalogSessionPersistence extends SessionPersistence { list = unavailableCatalogPersistence } +/** Schema collection does not read Workspace records or open their durable domain. */ +class CatalogWorkspaceRegistry extends WorkspaceRegistry { + static override inject = [] + + protected override async [Service.init](): Promise {} +} + /** Storage operations are unreachable during schema collection. */ function unavailableCatalogPersistence(): never { throw new Error('gen-tool-catalog: persistence access is unavailable during schema harvest') @@ -571,6 +580,20 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolSkill) }, }, + { + pkg: '@deepseek-ai/dsh-tool-session-list', + dir: 'tool-session-list', + source: 'packages/session-query/tool-session-list/src/index.ts', + requires: ['ctx.tools', 'ctx.sessions', 'ctx.sessionQuery', 'ctx.workspaceRegistry', 'ctx.sessionProjections'], + writes: ['tool/call', 'tool/result'], + async mount(ctx) { + await ctx.plugin(SessionStore) + await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:' }) + await ctx.plugin(CatalogWorkspaceRegistry) + await ctx.plugin(ToolSessionList) + }, + note: 'Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated.', + }, { pkg: '@deepseek-ai/dsh-tool-session-query', dir: 'tool-session-query', @@ -683,7 +706,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ }, scope: ctx => catalogChildScopes.get(ctx) as Agent, note: - 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode.', + 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off.', }, { pkg: '@deepseek-ai/dsh-tool-todo', diff --git a/scripts/product-package-policy.ts b/scripts/product-package-policy.ts index ecdc81f3b9..ffdaf762f4 100644 --- a/scripts/product-package-policy.ts +++ b/scripts/product-package-policy.ts @@ -16,6 +16,7 @@ export interface ProductPackagePolicy { * Optional integrations may be reached by an optional bundle without becoming default capabilities. */ export const PRODUCT_PACKAGE_POLICY: Readonly> = { + 'packages/session-query/tool-session-list': { category: 'optional', reason: 'Explicitly grants model callers read access to runtime Workspace and Session metadata.' }, 'packages/host/authentication-desktop': { category: 'optional', reason: 'Mounted by the private Desktop Host with its parent-process credential, outside default Web profiles.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/client/script-realm': { category: 'optional', reason: 'Script environment provider registry for explicitly selected Client integrations.' }, diff --git a/scripts/rescope-vendor.spec.ts b/scripts/rescope-vendor.spec.ts index 4f43ef08fe..0eb3b530f8 100644 --- a/scripts/rescope-vendor.spec.ts +++ b/scripts/rescope-vendor.spec.ts @@ -87,6 +87,7 @@ describe('product identifiers', () => { it.each([ 'apps/cli/tests/optional-bundle-transitions.e2e.ts', 'apps/web/tests/agent-preset-selection.e2e.ts', + 'apps/web/tests/creator-persona.e2e.ts', 'apps/web/tests/developer-tools-settings.e2e.ts', 'docs/subsystems/extensions.md', 'docs/subsystems/extensions.zh.md', @@ -98,6 +99,8 @@ describe('product identifiers', () => { 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', 'docs/user/guide/schedule.md', 'docs/user/guide/schedule.zh.md', 'packages/bundle/web-app/cordis.patch.yml', @@ -132,6 +135,17 @@ describe('product identifiers', () => { expect(rescopeText(scoped, file, true)).toEqual({ text, lines: 2 }) }) + it.each([ + 'apps/web/tests/creator-persona.e2e.ts', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', + ])('still rewrites package imports in %s', (file) => { + const source = "const preset = 'cordis'\nimport { Context } from 'cordis'\n" + const text = file.endsWith('.md') ? `The \`cordis\` preset.\n\`\`\`ts\n${source}\`\`\`\n` : source + const scoped = text.replace("from 'cordis'", "from '@deepseek-ai/cordis'") + expectRoundTrip(file, text, scoped, 1) + }) + it('keeps unlisted package references subject to residue detection', () => { const file = 'packages/example/src/index.ts' const text = "import { Context } from 'cordis'\nimport type Schema from 'schemastery'\n" diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 28944a2a0a..c3eead9523 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -101,7 +101,9 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/cli/tests/web-agent-presets.e2e.ts', upstream: ['cordis'] }, { file: 'apps/cli/tests/profiles/web/tests/fixtures/creator-plugin-manager.mjs', upstream: ['cordis'] }, { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] }, + { file: 'apps/web/tests/creator-persona.e2e.ts', upstream: ['cordis'] }, { file: 'packages/preset/agent-preset-registry/tests/session.spec.ts', upstream: ['cordis'] }, + { file: 'packages/experimental/cua/tests/agent-scopes.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/src/index.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/creation.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/loader-composition.spec.ts', upstream: ['cordis'] }, @@ -113,6 +115,8 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'docs/tool-catalog.zh.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', upstream: ['cordis'] }, { file: 'scripts/gen-tool-catalog.ts', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.zh.md', upstream: ['cordis'] }, diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index bdc5db0b51..5976155c79 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -158,6 +158,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' }, 'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' }, 'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' }, + 'packages/client/ui-connector-account': { kind: 'none', reason: 'Plugins page account surfaces over Host-registered accounts; each registrant documents the tools and skills its account enables.' }, 'packages/client/ui-message-feedback': { kind: 'none', reason: 'Browser-side controls over log-only message feedback; ratings and notes never enter model context or change model-input tokens.' }, 'packages/client/ui-tool': { kind: 'none', reason: 'Browser-side Tool presentation layer; renders logged calls without changing model context.' }, 'packages/client/ui-schedule': { kind: 'none', reason: 'Browser-side catalog, editing, and deletion of Host Schedule records; dsh-schedule owns storage and delivery, and dsh-tool-schedule contributes the model-facing tools in a preset that mounts it.' }, diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 92190be4ef..db7bd43972 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -65,10 +65,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -82,6 +86,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl index c3cc7b9594..7268d60b9b 100644 --- a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:13}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_OK."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl index b3cd7ec92c..29891b60f4 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl index 96eeb690e2..49eb1a6479 100644 --- a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl @@ -12,7 +12,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:20}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:21}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:21}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl index 19d523aa3a..a4f658304c 100644 --- a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."},{"type":"text","text":"MARMALADE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34},"stream":[{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796126253,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," remember"," the"," project"," cod","ew","ord"," \"","M","ARM","AL","ADE","\""," and"," now"," they","'re"," asking"," what"," it"," is","."," I"," should"," just"," reply"," with"," that"," word","."]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796126253,"index":1,"dt":[0,0,0],"texts":["M","ARM","AL","ADE"]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"MARMALADE"}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"usage","usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl index c2ddc6ba54..3f07ed2107 100644 --- a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl index d2a0c54601..70de7c510f 100644 --- a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl index 38cea8dd55..a88ecf5174 100644 --- a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:19}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."},{"type":"text","text":"SAFFRON"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31},"stream":[{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796127698,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," is"," asking"," me"," to"," recall"," the"," project"," cod","ew","ord"," that"," was"," mentioned"," earlier"," in"," the"," conversation","."," I"," was"," told"," to"," remember"," it",":"," SA","FF","RON","."]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796127698,"index":1,"dt":[0,0],"texts":["SA","FF","RON"]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SAFFRON"}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"usage","usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl index d2decca80d..5c9f47fad3 100644 --- a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:14}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl index 5feb3241f3..d9b754e40a 100644 --- a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl @@ -24,7 +24,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":10,"time":0,"data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":12,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} diff --git a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl index 42a8cca90a..3a765d41c2 100644 --- a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl index 0459818119..a2fdb349d2 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl index 5f04bbd358..b324dd8ca4 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:19}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain/session.1.v4.jsonl b/snapshots/session/advanced-toolchain/session.1.v4.jsonl index c76902452a..5448dc8976 100644 --- a/snapshots/session/advanced-toolchain/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:21}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain/session.2.v4.jsonl b/snapshots/session/advanced-toolchain/session.2.v4.jsonl index c023e2862b..4aeef9e8c1 100644 --- a/snapshots/session/advanced-toolchain/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:25}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:24}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:26}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:26}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 572b8f2eb0..3cc3ebd954 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -66,12 +66,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -85,6 +89,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 1afadeca68..ec3478d7c2 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -462,6 +462,55 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ff53e75417..e081a0a66c 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 893532843c..bb4eb419d5 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -66,10 +66,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -83,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 1545776e2c..a194b2db34 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -64,10 +64,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -81,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 0b31f65856..c2333aa706 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/ralph-loop/session.1.v4.jsonl b/snapshots/session/ralph-loop/session.1.v4.jsonl index 1fc1bef3f1..82a097c2e3 100644 --- a/snapshots/session/ralph-loop/session.1.v4.jsonl +++ b/snapshots/session/ralph-loop/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/ralph-loop/session.2.v4.jsonl b/snapshots/session/ralph-loop/session.2.v4.jsonl index 8bcd71e4f5..c73c2a1649 100644 --- a/snapshots/session/ralph-loop/session.2.v4.jsonl +++ b/snapshots/session/ralph-loop/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:13}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/session-list-tools/cordis.snapshot.yml b/snapshots/session/session-list-tools/cordis.snapshot.yml new file mode 100644 index 0000000000..d7b301ee86 --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.snapshot.yml @@ -0,0 +1,52 @@ +# Replay patch shared by the ordinary headless snapshot composition. The model +# script comes from the scenario's committed session JSONL. + +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek-api-key' + disabled: true + +- id: plugin-package-inventory-deepseek + disabled: true + +- id: session-title-llm + disabled: true + +- id: session-persistence-jsonl + name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: !!js dshHomePath('sessions') + compression: none + +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' + config: + runnerCommand: + - bash + - -c + - while [ "$1" != "--" ]; do shift; done; shift; exec "$@" + - passthrough-runner + runnerFailureSignatures: + - 'passthrough-runner: profile rejected' + +- insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + - id: deepseek-messages + name: DeepSeek Messages + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/cordis.yml b/snapshots/session/session-list-tools/cordis.yml new file mode 100644 index 0000000000..35f941fe6d --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.yml @@ -0,0 +1,6 @@ +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/session.v4.jsonl b/snapshots/session/session-list-tools/session.v4.jsonl new file mode 100644 index 0000000000..bd34f510b8 --- /dev/null +++ b/snapshots/session/session-list-tools/session.v4.jsonl @@ -0,0 +1,57 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"List the fixture workspaces and","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-1","name":"list_workspace","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-1","name":"list_workspace","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"list-1","name":"list_workspace","arguments":"{}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-1"},"toolCallId":"list-1","content":[{"type":"text","text":"[{\"workspace_id\":\"list-workspace\",\"title\":\"List fixture\",\"path\":\"{{cwd}}\",\"created_at\":\"2000-01-01T00:00:00.000Z\",\"updated_at\":\"2000-01-02T00:00:00.000Z\"},{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"list-2"},"toolCallId":"list-2","content":[{"type":"text","text":"[{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"step/start","data":{"turn":1,"step":3}} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":3,"callId":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"list-3"},"toolCallId":"list-3","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"},{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":3}} +{"type":"step/start","data":{"turn":1,"step":4}} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":4}} +{"type":"step/start","data":{"turn":1,"step":5}} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":5,"callId":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"list-5"},"toolCallId":"list-5","content":[{"type":"text","text":"[{\"session_id\":\"list-archived\",\"title\":null,\"created_at\":\"1970-01-01T00:00:03.000Z\",\"updated_at\":\"1970-01-01T00:00:03.000Z\"}]"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":5}} +{"type":"step/start","data":{"turn":1,"step":6}} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":6,"callId":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"list-6"},"toolCallId":"list-6","content":[{"type":"text","text":"[{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":6}} +{"type":"step/start","data":{"turn":1,"step":7}} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":7,"callId":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}} +{"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"list-7"},"toolCallId":"list-7","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":7}} +{"type":"step/start","data":{"turn":1,"step":8}} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":8,"callId":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"list-8"},"toolCallId":"list-8","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":8}} +{"type":"step/start","data":{"turn":1,"step":9}} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"text","text":"SESSION_LIST_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"SESSION_LIST_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":9}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/session-list-tools/snapshot.yml b/snapshots/session/session-list-tools/snapshot.yml new file mode 100644 index 0000000000..a1d5d12a41 --- /dev/null +++ b/snapshots/session/session-list-tools/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: session-list-tools +profile: headless +composition: session-list-tools +recording: authored +header: + class: session-list-tools + pin: true + systemPromptSource: text-turn diff --git a/snapshots/session/session-list-tools/tool-schemas.expected.json b/snapshots/session/session-list-tools/tool-schemas.expected.json new file mode 100644 index 0000000000..a7f800a4ac --- /dev/null +++ b/snapshots/session/session-list-tools/tool-schemas.expected.json @@ -0,0 +1,685 @@ +{ + "initial": [ + { + "name": "apply_patch", + "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", + "parameters": { + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "input" + ] + } + }, + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "description", + "command" + ] + } + }, + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "list_session", + "description": "List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", + "parameters": { + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "list_workspace", + "description": "List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", + "parameters": { + "type": "object", + "properties": { + "agent": { + "type": "string", + "description": "The name of another agent in your subagent tree, as shown by list_agents." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." + } + }, + "required": [ + "agent", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "wait_agent", + "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", + "parameters": { + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–10 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "working_directory", + "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", + "parameters": { + "type": "object", + "properties": { + "cd": { + "type": "string", + "description": "Existing directory to enter. Omit to read the current directory." + } + } + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl index b23559714e..62bf1c479e 100644 --- a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl +++ b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl index c29300ad07..ba37cda623 100644 --- a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl index 5244e25c40..a1127c04f6 100644 --- a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl index bba60d00bc..99c7c7736b 100644 --- a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Call ask_user_question once to ask","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl index 0f3435e07c..311b781f19 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Call subagent once. Ask that","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl index dfa91ecadc..8ee62bf7c6 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl index f2650839c3..eeba0b0a5e 100644 --- a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl +++ b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Write the words 'partial one',","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-multi/writer.1.expected.jsonl b/snapshots/session/subagent-multi/writer.1.expected.jsonl index b075fda0c0..dcd07b256c 100644 --- a/snapshots/session/subagent-multi/writer.1.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.1.expected.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-multi/writer.2.expected.jsonl b/snapshots/session/subagent-multi/writer.2.expected.jsonl index 37b742eec6..e45c4a496e 100644 --- a/snapshots/session/subagent-multi/writer.2.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.2.expected.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word BETA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-parallel/session.1.v4.jsonl b/snapshots/session/subagent-parallel/session.1.v4.jsonl index c131526718..7e2d815ada 100644 --- a/snapshots/session/subagent-parallel/session.1.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-parallel/session.2.v4.jsonl b/snapshots/session/subagent-parallel/session.2.v4.jsonl index 6525354d1e..28708982d9 100644 --- a/snapshots/session/subagent-parallel/session.2.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl index f074f5e678..e68b196770 100644 --- a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 9f3180e9f2..73fd031599 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:9}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Submit answer 41 through structured_output."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:10}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:10}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Submit answer 41 through structured_outp","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl index 9c2e91a3aa..5bc7d5d835 100644 --- a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl +++ b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/workflow-run/session.1.v4.jsonl b/snapshots/session/workflow-run/session.1.v4.jsonl index 5085aaa87e..c7a7977247 100644 --- a/snapshots/session/workflow-run/session.1.v4.jsonl +++ b/snapshots/session/workflow-run/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word WF_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl index 4e79a3846a..12daf4b503 100644 --- a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"},{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"},{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"},{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":0,"dt":[],"id":"call_schedule_create","name":"schedule_create","args":["{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":1,"dt":[],"id":"call_schedule_list","name":"schedule_list","args":["{}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":2,"dt":[],"id":"call_schedule_update","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":3,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":3,"dt":[],"id":"call_schedule_delete","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"delete\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":3,"block":{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}} diff --git a/tsconfig.base.json b/tsconfig.base.json index 25ae008407..d3ccf119b1 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -176,6 +176,7 @@ "@deepseek-ai/dsh-session/chunk-rows": ["./packages/core/session/src/chunk-rows.ts"], "@deepseek-ai/dsh-session/surface": ["./packages/core/session/src/surface.ts"], "@deepseek-ai/dsh-session/fork": ["./packages/core/session/src/fork.ts"], + "@deepseek-ai/dsh-session-query/types": ["./packages/session-query/session-query/src/types.ts"], "@deepseek-ai/dsh-session-projection/types": ["./packages/session/session-projection/src/types.ts"], "@deepseek-ai/dsh-tool-todo/types": ["./packages/todo/tool-todo/src/types.ts"], "@deepseek-ai/dsh-tool-todo/client": ["./packages/todo/tool-todo/src/client.ts"], @@ -336,6 +337,8 @@ "@deepseek-ai/dsh-client-ui-input-trigger": ["./packages/client/ui-input-trigger/src"], "@deepseek-ai/dsh-client-ui-reference": ["./packages/client/ui-reference/src"], "@deepseek-ai/dsh-client-ui-commands": ["./packages/client/ui-commands/src"], + "@deepseek-ai/dsh-client-ui-connector-account": ["./packages/client/ui-connector-account/src"], + "@deepseek-ai/dsh-client-ui-connector-account/types": ["./packages/client/ui-connector-account/src/types.ts"], "@deepseek-ai/dsh-client-ui-model-selection": ["./packages/client/ui-model-selection/src"], "@deepseek-ai/dsh-client-ui-goal": ["./packages/client/ui-goal/src"], "@deepseek-ai/dsh-client-ui-message-feedback": ["./packages/client/ui-message-feedback/src"], @@ -618,6 +621,7 @@ "@deepseek-ai/dsh-tool-pwsh-persistent": ["./packages/shell/tool-pwsh-persistent/src"], "@deepseek-ai/dsh-tool-ralph": ["./packages/experimental/tool-ralph/src"], "@deepseek-ai/dsh-tool-schedule": ["./packages/schedule/tool-schedule/src"], + "@deepseek-ai/dsh-tool-session-list": ["./packages/session-query/tool-session-list/src"], "@deepseek-ai/dsh-tool-session-query": ["./packages/experimental/tool-session-query/src"], "@deepseek-ai/dsh-tool-skill": ["./packages/skill/tool-skill/src"], "@deepseek-ai/dsh-tool-str-replace-editor": ["./packages/fs/tool-str-replace-editor/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index e682fef56f..e9970cfac2 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -145,6 +145,7 @@ { "path": "./packages/client/ui-directory-picker-native" }, { "path": "./packages/client/ui-goal" }, { "path": "./packages/client/ui-message-feedback" }, + { "path": "./packages/client/ui-connector-account/tsconfig.client.json" }, { "path": "./packages/client/ui-model-selection" }, { "path": "./packages/client/ui-agent-preset" }, { "path": "./packages/client/ui-permission-presets" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index ea2316d36e..073c589776 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -173,6 +173,7 @@ "apps/web/tests/present-after-closing-reply.e2e.ts", "apps/web/tests/autolink-cjk-punctuation.e2e.ts", "apps/web/tests/composer-draft-scroll.e2e.ts", + "apps/web/tests/draft-attachment-session-switch.e2e.ts", "apps/web/tests/composer-focus.e2e.ts", "apps/web/tests/composer-placeholder.e2e.ts", "apps/web/tests/context-meter.e2e.ts", @@ -316,6 +317,7 @@ { "path": "./packages/client/ui-theme/tsconfig.host.json" }, { "path": "./packages/client/ui-chat/tsconfig.host.json" }, { "path": "./packages/client/ui-conversation/tsconfig.host.json" }, + { "path": "./packages/client/ui-connector-account/tsconfig.host.json" }, { "path": "./packages/client/ui-settings/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, @@ -441,6 +443,7 @@ { "path": "./packages/experimental/forge-bundle" }, { "path": "./packages/experimental/client-ui-forge/tsconfig.host.json" }, { "path": "./packages/session/tool-working-directory" }, + { "path": "./packages/session-query/tool-session-list" }, { "path": "./packages/session/session-title-llm" }, { "path": "./packages/session/session-title-first-prompt-llm" }, { "path": "./packages/experimental/session-title-all-prompts-llm" },