diff --git a/.agents/skills/dsh-dev/SKILL.md b/.agents/skills/dsh-dev/SKILL.md index d846d6a8e1..6f00aa9020 100644 --- a/.agents/skills/dsh-dev/SKILL.md +++ b/.agents/skills/dsh-dev/SKILL.md @@ -125,6 +125,12 @@ The regression uses the real native Session fold and LLM projection in BotHarness is a plugin layer inside DSH: unit tests do not cover the real boot. Every trap in this skill was invisible to `pnpm test` and only appeared in a running `dsh --profile web-dev`. **Validate against the running shell, not the test suite.** +### Native approval requires a real open turn (#4212) + +On pinned DSH 0.2.2-rc.1, scoped Tools.execute supports an actual Agent outside a model step, but ApprovalService.request rejects outside an open native turn before appending approval/asked. A successful model-free read therefore does not prove protected-write approval parity. The public Agent.runMaintenance API is explicitly non-turn; do not append manual turn/start events to bypass the approval audit check or desynchronize the loop counter. + +For an admitted application-owned request, keep the canonical BotRuntime owner and exact live Agent. Queue one identified native input, use the supported agent/pre-step waterfall after session admission to execute the scoped Tool, then reject model-step entry. The native loop owns turn/start and turn/end; approval/asked and approval/decided remain genuinely enclosed, and no model request is made. Validate the exact claimed native input, cancellation, no queued foreign work, and all original source/permission fences. Keep a model-free request marker on its genuine Human DM so normal retry or continuation cannot replay an expired execution intent. + ## Proactive Client verification After every isolated launch, Client reload and relevant UI action, read the real browser console and DOM yourself before accepting the result; do not wait for Human-copied errors. Read [the Client diagnostic loop](../../../docs/dev/guides/client-startup-diagnostics.md) for the agent-runnable reader, bounded attempt history, background-tab/freshness limits and native RC1 reproductions. Treat API health, Client shell evidence and browser-control failures as separate signals. Preserve first failure and each retry; recovery by reload does not establish a fix. diff --git a/.agents/skills/dsh-plugin-dev/CHANGELOG.md b/.agents/skills/dsh-plugin-dev/CHANGELOG.md index 0516ebe338..419a740b60 100644 --- a/.agents/skills/dsh-plugin-dev/CHANGELOG.md +++ b/.agents/skills/dsh-plugin-dev/CHANGELOG.md @@ -10,6 +10,7 @@ Preparing the next DSH Skill release independently from downstream product relea ### Documentation +- Documented the downstream model-free Tob CLI journey and pinned native approval audit boundary; stable DSH/Cordis Context, Decision Tree and upstream provenance are unchanged ([#4212](https://github.com/BotHarness/DeepSeekBot/issues/4212)). - Added the downstream anonymous Bot token telemetry verification journey and snapshot query contract; stable DSH/Cordis Context, Decision Tree and upstream qualification are unchanged ([#4255](https://github.com/BotHarness/DeepSeekBot/issues/4255)). - Added the downstream first-Tob settings responsiveness journey; stable DSH/Cordis Context, Decision Tree and upstream qualification are unchanged ([#4226](https://github.com/BotHarness/DeepSeekBot/issues/4226)). diff --git a/.agents/skills/dsh-plugin-dev/CHANGELOG.zh.md b/.agents/skills/dsh-plugin-dev/CHANGELOG.zh.md index 2dc7780151..fc9d13a306 100644 --- a/.agents/skills/dsh-plugin-dev/CHANGELOG.zh.md +++ b/.agents/skills/dsh-plugin-dev/CHANGELOG.zh.md @@ -9,6 +9,7 @@ artifact;DSH 版本与上游 revision 记录这些内容是基于什么版本 ### Documentation +- 补充下游无模型 Tob CLI 验证路径及原生审批的真实回合审计边界;稳定 DSH/Cordis Context、Decision Tree 及上游验证来源不变([#4212](https://github.com/BotHarness/DeepSeekBot/issues/4212))。 - 增加下游匿名 Bot Token 统计的验证路径及快照查询约定;稳定 DSH/Cordis Context、Decision Tree 及上游验证来源不变([#4255](https://github.com/BotHarness/DeepSeekBot/issues/4255))。 - 增加下游首次 Tob 准备期间的设置响应性验证路径;稳定 DSH/Cordis Context、Decision Tree 及上游验证来源不变([#4226](https://github.com/BotHarness/DeepSeekBot/issues/4226))。 diff --git a/.agents/skills/verify-deepseekbot/features/README.md b/.agents/skills/verify-deepseekbot/features/README.md index c67e82bd04..44938d8f2c 100644 --- a/.agents/skills/verify-deepseekbot/features/README.md +++ b/.agents/skills/verify-deepseekbot/features/README.md @@ -27,7 +27,7 @@ | DeepSeekBot device-local appearance | no | `scripts/e2e-local-appearance.mjs` | [local-appearance.md](local-appearance.md) | | Functional Panel appearance | no | `scripts/e2e-panel-appearance.mjs`, `scripts/e2e-nested-appearance.mjs` | [panel-appearance.md](panel-appearance.md) | | Global panel materials | no | `scripts/e2e-global-materials.mjs` | [global-materials.md](global-materials.md) | -| Protected Tob DM and mobile pull-to-Tob (management, models, runtime, privacy and updates) | yes for reply and approval | `scripts/e2e-tob-home.mjs`, `scripts/e2e-tob-model-runtime.mjs`, `scripts/e2e-tob-bot-management.mjs`, `scripts/e2e-tob-channel-management.mjs`, `scripts/e2e-tob-group-settings.mjs`, `scripts/e2e-tob-group-decisions.mjs`, `scripts/e2e-tob-delegation.mjs` | [tob-home.md](tob-home.md) | +| Protected Tob DM and mobile pull-to-Tob (management, models, runtime, privacy and updates), plus typed CLI admission | yes for model reply; no for typed CLI approval | `scripts/e2e-tob-home.mjs`, `scripts/e2e-tob-model-runtime.mjs`, `scripts/e2e-tob-bot-management.mjs`, `scripts/e2e-tob-channel-management.mjs`, `scripts/e2e-tob-group-settings.mjs`, `scripts/e2e-tob-group-decisions.mjs`, `scripts/e2e-tob-delegation.mjs` | [tob-home.md](tob-home.md) | | DSH Session list Bot folders | for fresh execution | `scripts/e2e-bot-session-folders.mjs` | [bot-session-folders.md](bot-session-folders.md) | One file per user-facing feature. Each file has four sections: `Sub-features`, `How to get to it (user POV)`, `Driving it with verify-app`, and `Gotchas`. diff --git a/.agents/skills/verify-deepseekbot/features/approval-templates.md b/.agents/skills/verify-deepseekbot/features/approval-templates.md index f640356246..7b2883ab4d 100644 --- a/.agents/skills/verify-deepseekbot/features/approval-templates.md +++ b/.agents/skills/verify-deepseekbot/features/approval-templates.md @@ -10,6 +10,7 @@ A Bot inherits the optional global default, selects one complete shared template - `select`: Channel settings → Auto approval, or composer Workspace Grants panel → Auto approval, uses the same DSH Select. Inheritance shows its effective global source. Specific selection replaces global; Off retains deterministic rules. - `mobile`: Bot profile → Settings → Permissions → Workspace grants → Auto approval template, inside the existing iOS sheet / Android `ModalBottomSheet`. Inherit global shows the resolved global template (or Off); selecting Off then Inherit global writes null then @global through the same Host owner. Legacy Hosts without a global-selection field retain their supported choices. - `reviewer`: a covered call leaves an auto-approved record with template identity/version; an uncovered or failed review posts a Human card with the reason and captured version when available. No new model rejection or rejection pause occurs. +- `delete`: custom template → Delete opens a read-only impact preview. It lists visible direct/global users plus protected private-reference count and the resulting global template/Off/unavailable state. Confirming its revision switches direct users to inherit and clears a deleted global default. Stale references/policy/content require a fresh preview and another confirmation. Failed reads do not delete or change choices. - `guard`: effective template/global/Bot policy changes bypass Full Access and model review, retaining Human or explicit management-scope authorization and execution fences (ADR-0249). ## How to get to it (user POV) @@ -25,7 +26,8 @@ Use an isolated Host and its own authenticated CLI. Confirm health and Client co 3. New Bot creation reads back @global; a retained legacy missing field remains Off. Restart verifies persistence without schema changes. 4. Trigger an existing approval through the native tool path. A deterministic saved rule makes zero Reviewer calls. An uncovered call uses the effective template and leaves either the versioned auto-approved record or Human card; answer that card through the normal owner. 5. Edit/switch during an injected Reviewer wait at the Channel Tool Approval seam: this Review retains the old identity/version, the next uses the new one. Missing/unreadable template or model timeout/malformed response posts Human with a reason, even if diagnostics fail. Check canonical Channel records and developer logs. -6. Exercise a policy-management approval under Full Access; Reviewer calls remain zero and only Human or an explicit management rule can authorize effects. Revoke the rule before execution and verify refusal. +6. Create a custom template and an explicit user, an inherited user, another specific user and an Off control. Preview deletion through CLI and Client without mutation; confirm after checking all effects. With another global default, direct users inherit it. Delete the global default: clear it and leave inheritors inherited with Reviewer off. Change refs/content/global between preview and confirmation: refusal and refreshed impact, no replay. Keep an existing Human review pending across deletion and verify its captured template/version on settlement. Saved rules and Full Access do not change. +7. Exercise a policy-management approval under Full Access; Reviewer calls remain zero and only Human or an explicit management rule can authorize effects. Revoke the rule before execution and verify refusal. ## Native mobile qualification @@ -34,7 +36,7 @@ Use the shared device QA lane and T3 device tools. The same synthetic Bot and is ## Gotchas - `/tmp` may already be writable; an ordinary file write there need not reach an approval gate. -- Card-rule table and confirmed bulk deletion fallback remain separate issues. For the editor, verify legacy Markdown survives conversion and an edit during a Review changes only the next captured version. +- Three-part editing, confirmed bulk deletion and the card-rule table have distinct journeys. Verify legacy Markdown conversion, next-Review snapshot behavior and deletion fallback separately. - Browser screenshots establish Web behavior only. Preserve failed drives and observe before retrying. ## Human result retention (#4211) diff --git a/.agents/skills/verify-deepseekbot/features/tob-home.md b/.agents/skills/verify-deepseekbot/features/tob-home.md index f414f09a49..a2f2947518 100644 --- a/.agents/skills/verify-deepseekbot/features/tob-home.md +++ b/.agents/skills/verify-deepseekbot/features/tob-home.md @@ -139,3 +139,8 @@ Use the Mac/iOS or Windows/Android device queue; Web and model tests do not qual - The top entrance is the same chat content and composer as the normal Tob row. Check its down-entry/up-exit, Back, iOS edge cancellation/commit, keyboard-open exit and dark flash. Toggle Reduce Motion while the app remains running: on returning, entry and exit must stop sliding without a JS reload. Test normal Tob-row push separately. Keep physical/Simulator/Android and source SHA results separate. Retain the first failure with native screenshot/AX/video and exact source/binary identity, then restore preferences, remove only this run's temporary pairing, revoke its Host key and stop owned resources. The full device matrix is tracked in #3090 and #3093. + + +## Model-free typed CLI parity (#4212) + +Use the authenticated Owner `tob-cli start --args-stdin` with private JSON `{argv,stdin}`; read its request ID with `tob-cli status` and cancel with `tob-cli cancel`. This creates a genuine Human DM and accepted Admission, prepares the actual owned Tob root Agent and executes the typed `deepseekbot_cli` through native Tools.execute without a model. A historical source or temporary direct Session cannot substitute. For a local nondestructive fixture, request an approval-template selection, inspect the real pending card in the Tob DM (exact argv and stdin size/hash), decide with existing Human `tool-approval-decide`, and read both the result and selected template. Match source/build hashes; no model request should appear. Repeat denial, cancellation, stale revision and authority-revoke fences. A template readback alone is not broker approval proof. Capture actual Client light/dark pending/settled states separately; Web evidence does not qualify native mobile. diff --git a/.agents/skills/verify-deepseekbot/features/tool-approval-simple.md b/.agents/skills/verify-deepseekbot/features/tool-approval-simple.md index f328e46985..e4e8e57491 100644 --- a/.agents/skills/verify-deepseekbot/features/tool-approval-simple.md +++ b/.agents/skills/verify-deepseekbot/features/tool-approval-simple.md @@ -30,6 +30,12 @@ This Windows native-pwsh journey creates a synthetic Bot, uses real model calls, For a baseline capture, provide `--capture-report --expect-legacy`. The private record identifies an existing task-owned instance, Bot and pending request. This mode reads and captures only; it does not decide or create a Bot. Never use a Human's real request as a disposable verification input. +## Bot-specific saved card rules (#4245) + +Open Bot permissions from the composer or the folder/access entry. After saving Always allow on a real card, open **Always allow · this Bot**. Check **From approval card**, tool, execution role, current directory and full scope under View scope against `tool-approval-rules`. Revoke that row and verify canonical readback shows it disabled. Repeat through the online CLI, then Reload the open list. The next same call must return to review. A second Bot using the same template and a template copy must acquire no rule. Model allow-once must not add a rule. + +This list reads the existing canonical owner once during permissions refresh; it adds no polling, template lookup or Reviewer work to tool execution. The focused Client test guards one initial rules read and canonical readback after revocation. `auto-approval-breaker.test.ts` guards zero template/Reviewer calls on a saved-rule hit, restored review after revoke, and no new rule from model allow-once. Runtime before/after latency and screenshots remain separate evidence. + ## Gotchas - DSH native pwsh uses `sandbox_permissions: danger-full-access`, not Codex's `require_escalated`. A harmless output marker explicitly requesting that mode can exercise the real ask without touching a sensitive file. @@ -51,3 +57,7 @@ For first-time setup, the homepage instruction names the actual Allow once butto ## Companion reading space With a visible floating companion, scroll to the latest approval and reply and verify their bottom edge is above the passive avatar and toolbar. The running status above the composer must also remain clear of the avatar. Repeat at 375px width, with reduced motion, and after activity fades; removing every companion returns the space, while toggling companions during history reading must not jump to the latest message. This checks the latest content at the bottom, not arbitrary history positions or intentionally opened companion bubbles/menus. + +## Irreversible external effects (#4210) + +Use online `bot-tool` with a declared irreversible external tool and a controlled destination-free fixture. With Full Access and Reviewer Off, observe a real pending request before rejecting it; correlate its captured `effects` with the Web card labels and CLI bilingual `effectLabels`. Do not insert cards or approval rows. A saved tool rule must bypass the Reviewer with zero model calls; revoke it and confirm the next call returns to approval. Input or result text claiming approval has no authority. Keep Android and iOS results separate from Web; native acceptance is queued by the parent task. diff --git a/apps/mobile/src/host/requests.ts b/apps/mobile/src/host/requests.ts index cd656016f5..7d20823382 100644 --- a/apps/mobile/src/host/requests.ts +++ b/apps/mobile/src/host/requests.ts @@ -1,3 +1,4 @@ +import { parseToolEffects } from '../../../../packages/core/src/workspaces/tool-effects-contract'; import { approvalShellCommand } from '../../../../packages/client/src/client/approval-diff'; import { approveWorkspaceRequest, @@ -16,6 +17,7 @@ import type { TimelineMessage, TimelinePage, ToolApprovalOutcome, + ToolApprovalRequestCard, ToolApprovalStatus, UserQuestionStatus, } from './wire'; @@ -30,6 +32,7 @@ export interface RequestRef { } export interface ApprovalRequest extends RequestRef { + effects?: ToolApprovalRequestCard['effects']; toolName: string; role: 'orchestrator' | 'assignment'; cwd: string; @@ -43,7 +46,7 @@ export interface ApprovalRequest extends RequestRef { export type ApprovalContent = Pick< ApprovalRequest, - 'toolName' | 'role' | 'cwd' | 'input' | 'allowAlways' + 'toolName' | 'role' | 'cwd' | 'input' | 'allowAlways' | 'effects' >; export function approvalContent(value: unknown): ApprovalContent | undefined { @@ -55,8 +58,10 @@ export function approvalContent(value: unknown): ApprovalContent | undefined { if (!('cwd' in value) || typeof value.cwd !== 'string') return undefined; if (!('input' in value) || typeof value.input !== 'string') return undefined; if ('allowAlways' in value && typeof value.allowAlways !== 'boolean') return undefined; + const effects = parseToolEffects('effects' in value ? value.effects : undefined); return { toolName: value.toolName, + ...(effects === undefined ? {} : { effects }), role: value.role, cwd: value.cwd, input: value.input, @@ -131,6 +136,7 @@ export async function loadApproval(client: HostClient, ref: RequestRef): Promise return { ...ref, toolName: card.toolName, + ...(card.effects === undefined ? {} : { effects: card.effects }), role: card.role, cwd: card.cwd, input: card.input, diff --git a/apps/mobile/src/host/wire.ts b/apps/mobile/src/host/wire.ts index ebdf67794f..07f052a9fa 100644 --- a/apps/mobile/src/host/wire.ts +++ b/apps/mobile/src/host/wire.ts @@ -1,3 +1,4 @@ +import type { ToolEffects } from '../../../../packages/core/src/workspaces/tool-effects'; import type { BotPrimaryColor } from '../../../../packages/core/src/bots/primary-color'; import type { ChannelReplyPreviewMedia } from '../../../../packages/core/src/channels/reply-preview'; @@ -554,6 +555,7 @@ export interface HumanAttentionPage { } export interface ToolApprovalRequestCard { + effects?: ToolEffects; toolName: string; role: 'orchestrator' | 'assignment'; cwd: string; diff --git a/apps/mobile/src/ui/approval-view.tsx b/apps/mobile/src/ui/approval-view.tsx index a85b40be3c..76673a45fd 100644 --- a/apps/mobile/src/ui/approval-view.tsx +++ b/apps/mobile/src/ui/approval-view.tsx @@ -1,3 +1,5 @@ +import { toolEffectLabels } from '../../../../packages/core/src/workspaces/tool-effect-labels'; +import { locale } from './strings'; import { Text } from './primitives/system-text'; import { useCallback, useRef, useState } from 'react'; import { Platform, ScrollView, View, type ViewInstance } from 'react-native'; @@ -162,6 +164,9 @@ export function ApprovalView({ {t.wantsToRun(botName, request.toolName)} + {request.effects === undefined ? null : ( + {toolEffectLabels(request.effects, locale).join(' · ')} + )} {t.workingFolder} diff --git a/apps/mobile/src/ui/chat/approval-card.tsx b/apps/mobile/src/ui/chat/approval-card.tsx index 6cc108fe82..16b1104e09 100644 --- a/apps/mobile/src/ui/chat/approval-card.tsx +++ b/apps/mobile/src/ui/chat/approval-card.tsx @@ -1,3 +1,4 @@ +import { toolEffectLabels } from '../../../../../packages/core/src/workspaces/tool-effect-labels'; import { useCallback, useRef, useState } from 'react'; import { View, type ViewInstance } from 'react-native'; @@ -18,7 +19,7 @@ import { useMounted } from '../mounted'; import { Button } from '../primitives/button'; import { errorText } from '../request-parts'; import { haptic } from '../haptics'; -import { useStrings, t } from '../strings'; +import { useStrings, t, locale } from '../strings'; import { ActionCard, CardButtons, CardNote, CardPreview, DetailRow } from './action-card'; import type { CardLineTone } from './card-line'; import { FileDiff } from './approval-diff'; @@ -318,6 +319,9 @@ function ApprovalCardContent({ } > + {request.effects === undefined ? null : ( + {toolEffectLabels(request.effects, locale).join(' · ')} + )} {running === undefined ? null : {running}} {highRisk(request.toolName) ? {riskNote(request.toolName)} : null} {alwaysNote(request)} diff --git a/apps/mobile/test/action-cards.test.ts b/apps/mobile/test/action-cards.test.ts index 54101916fc..99a3713dc1 100644 --- a/apps/mobile/test/action-cards.test.ts +++ b/apps/mobile/test/action-cards.test.ts @@ -26,6 +26,7 @@ import type { HumanAttentionItem } from '../src/host/wire'; import { ApprovalCard } from '../src/ui/chat/approval-card'; import { QuestionCard } from '../src/ui/chat/question-card'; import { t } from '../src/ui/strings'; +import { interfacePreferences } from '../src/ui/interface-preferences'; import { played } from './expo-haptics-shim'; import { FakeHost } from './fake-host'; import inboxWire from './fixtures/inbox-wire.json'; @@ -205,6 +206,38 @@ describe('Tool approval card in the DM', () => { expect(view.textContent).toContain('/home/qa/.dsh/botharness/bots/'); }); + it.each([ + { language: 'en', irreversible: 'Irreversible', external: 'External effect' }, + { language: 'zh', irreversible: '不可撤销', external: '外部影响' }, + ] as const)( + 'keeps validated $language effect labels on the full card after rejection', + async ({ language, irreversible, external }) => { + const previousLanguage = interfacePreferences.getSnapshot().language; + act(() => interfacePreferences.setLanguage(language)); + try { + const fake = host(); + const timeline = approvalTimeline(true) as { + value: { page: { entries: Array<{ toolApprovalRequest: Record }> } }; + }; + timeline.value.page.entries[0]!.toolApprovalRequest['effects'] = { + changes: 'irreversible', + reach: 'external', + personalData: true, + }; + fake.answers.set('channelTimeline', () => timeline); + const view = await render(card(connect(fake))); + expect(view.textContent).toContain(irreversible); + expect(view.textContent).toContain(external); + await press(button(view, t.reject)); + expect(button(view, t.reject).getAttribute('aria-selected')).toBe('true'); + expect(view.textContent).toContain(irreversible); + expect(view.textContent).toContain(external); + } finally { + act(() => interfacePreferences.setLanguage(previousLanguage)); + } + }, + ); + it.each(['allowed-once', 'allowed-always-tool', 'rejected'] as const)( 'keeps the opened full card and selected disabled choice after %s', async (outcome) => { diff --git a/apps/mobile/test/approval-content.test.ts b/apps/mobile/test/approval-content.test.ts index 3eb93d3e8e..3aaef24952 100644 --- a/apps/mobile/test/approval-content.test.ts +++ b/apps/mobile/test/approval-content.test.ts @@ -9,6 +9,26 @@ describe('approval display content boundary', () => { input: '{"command":"echo QA"}', allowAlways: true, }; + it('retains only validated display effects, without trusting extra properties', () => { + const effects = { + changes: 'irreversible', + reach: 'external', + personalData: true, + authority: 'management', + secrets: true, + }; + expect( + approvalContent({ ...request, effects: { ...effects, outcome: 'allowed-once' } }), + ).toEqual({ ...request, effects }); + }); + it.each([ + {}, + { changes: 'none', reach: 'future', personalData: true }, + { changes: 'none', reach: 'local', personalData: 'yes' }, + { changes: 'none', reach: 'local', personalData: true, authority: 'automatic' }, + ])('omits malformed display effects: %j', (effects) => { + expect(approvalContent({ ...request, effects })).toEqual(request); + }); it('retains only display content, never cached decision authority', () => { expect( approvalContent({ diff --git a/changes/4210-irreversible-external-approval.md b/changes/4210-irreversible-external-approval.md new file mode 100644 index 0000000000..ab6de824dc --- /dev/null +++ b/changes/4210-irreversible-external-approval.md @@ -0,0 +1,11 @@ +--- +section: Changed +--- + +## en + +- Kept trusted irreversible external tool calls under approval even with Full Access, using saved authorization before the Reviewer or Human, kept shared-Bot approval details in the requesting participant’s DM, and exposed effect labels in Web, mobile and CLI approval views ([#4210](https://github.com/BotHarness/DeepSeekBot/issues/4210)). + +## zh + +- Full Access 下可信声明的不可撤销外部工具调用仍需审批,先匹配已保存授权,再交给 Reviewer 或 Human;共享 Bot 的审批详情留在请求成员自己的 DM;Web、手机与 CLI 审批呈现效果标签([#4210](https://github.com/BotHarness/DeepSeekBot/issues/4210))。 diff --git a/changes/4212-cli-effects.md b/changes/4212-cli-effects.md new file mode 100644 index 0000000000..02ab7c4e6a --- /dev/null +++ b/changes/4212-cli-effects.md @@ -0,0 +1,11 @@ +--- +section: Changed +--- + +## en + +- Centralized CLI effect declarations for direct commands and Tob's broker, with dispatch coverage checks and an authenticated model-free Tob CLI request path through the real Human DM and approval owner; the typed request shows only the broker’s exact-operation approval card without revealing stdin, while caller authorization remains separate ([#4212](https://github.com/BotHarness/DeepSeekBot/issues/4212)). + +## zh + +- 直接 CLI 命令与 Tob broker 共用效果声明,并检查实际命令分发的声明遗漏;新增通过真实 Human DM 与既有审批 owner 执行的已认证无模型 Tob CLI 请求路径,该类型化请求仅展示 broker 的准确操作审批卡且不显示 stdin 原文,保留各调用方独立授权边界([#4212](https://github.com/BotHarness/DeepSeekBot/issues/4212))。 diff --git a/changes/4245-bot-card-rules.md b/changes/4245-bot-card-rules.md new file mode 100644 index 0000000000..56ad54db8c --- /dev/null +++ b/changes/4245-bot-card-rules.md @@ -0,0 +1,11 @@ +--- +section: Changed +--- + +## en + +- Bot permissions now show saved Always allow rules from approval cards, with their role, scope and revoke action, separately from template Reviewer guidance ([#4245](https://github.com/BotHarness/DeepSeekBot/issues/4245)). + +## zh + +- Bot 权限面板显示来自审批卡的「始终允许」规则、角色、范围及撤销操作,与模板的审批员文字指引区分([#4245](https://github.com/BotHarness/DeepSeekBot/issues/4245))。 diff --git a/changes/4246-confirm-template-deletion.md b/changes/4246-confirm-template-deletion.md new file mode 100644 index 0000000000..15adece7e3 --- /dev/null +++ b/changes/4246-confirm-template-deletion.md @@ -0,0 +1,15 @@ +--- +section: Changed +--- + +## en + +- Approval Template deletion now previews affected Bots and the resulting global choice, requires explicit confirmation, and moves specific users to global inheritance; deleting the global default clears it while preserving saved authorizations and private Bot identities ([#4246](https://github.com/BotHarness/DeepSeekBot/issues/4246)). + +- Oversized or unreadable custom files remain removable through a fresh explicit deletion preview; unreadable-content recovery uses bounded filesystem identity and leaves Reviewer read limits unchanged ([#4246](https://github.com/BotHarness/DeepSeekBot/issues/4246)). + +## zh + +- 审批模板删除前显示受影响 Bot 和删除后的全局选择,显式确认后将特定引用统一改为继承全局;删除全局默认会清空默认,并保留已保存授权及私有 Bot 身份边界([#4246](https://github.com/BotHarness/DeepSeekBot/issues/4246))。 + +- 自定义模板文件超限或内容不可读时,仍可重新预览并显式确认删除;恢复删除使用有界文件系统身份,Reviewer 正文读取上限不变([#4246](https://github.com/BotHarness/DeepSeekBot/issues/4246))。 diff --git a/changes/4266-approval-review-fixes.md b/changes/4266-approval-review-fixes.md new file mode 100644 index 0000000000..7ba3e70336 --- /dev/null +++ b/changes/4266-approval-review-fixes.md @@ -0,0 +1,19 @@ +--- +section: Fixed +--- + +## en + +- Keep failed template deletions visible until the Host confirms removal, prevent older template reads from replacing newer settings, keep approval details in the requesting Human's DM, and preserve coded Team permission refusals. Computer video input requires approval, confirmed template deletion shows its irreversible effect, and delegated calls retain native rejection policy. QA failures redact private Host login details ([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266)). + +- Keep pending Memory notifications for the next model turn during model-free CLI calls, and preserve completed tool results when resource cleanup fails ([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266)). + +- Align approval architecture documentation with the implemented owners, separate card rules from natural-language rows, and record the retained Human decision cards ([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266)). + +## zh + +- 模板删除失败后保留错误,直到 Host 确认文件已移除;旧模板读取不会覆盖较新的设置;审批详情留在请求 Human 的 DM,并保留团队权限拒绝码。Computer 视频输入需审批,确认删除模板显示不可撤销效果,委派调用保留原生拒绝策略。QA 失败记录会隐藏私有 Host 登录信息([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266))。 + +- 无模型 CLI 调用保留待处理的 Memory 通知,交给后续模型回合;资源清理失败时保留已经完成的工具结果([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266))。 + +- 审批架构文档对齐已实现的 owner,分开说明卡片规则与自然语言行,并记录 Human 决定后保留的完整卡片([#4266](https://github.com/BotHarness/DeepSeekBot/pull/4266))。 diff --git a/docs/adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md b/docs/adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md new file mode 100644 index 0000000000..97ec630b31 --- /dev/null +++ b/docs/adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md @@ -0,0 +1,25 @@ +--- +Status: Accepted +Date: 2026-11-16 +Issues: [#4212](https://github.com/BotHarness/DeepSeekBot/issues/4212) +--- + +# ADR-0347: Model-free Tob CLI uses the accepted Human DM turn + +## Context + +The authenticated Human CLI can run application tools directly, but that temporary direct Session has no accepted Tob Human DM. Adding native Shell names to that runner cannot satisfy ADR-0249. A model-free path must exercise the same broker and approval owner while retaining real source authority. + +## Decision + +The authenticated Host Owner starts a bounded typed CLI request through `tobCli`. BotRuntime appends an actual Human message to that Owner’s protected Tob DM through ChannelStore, then uses its existing canonical Human-DM Source Event claim, Admission acceptance, serialized Orchestrator queue, preparation and completion. No caller chooses an actor, source ID, Session or cwd. This execution variant prepares the same live root Agent and uses DSH-native `Tools.execute` with that Agent scope, without model-step logging. It queues one exact native input, lets the native loop open its real turn, then runs the typed command at the supported pre-step boundary after existing session admission. It rejects model-step entry so the loop closes its own turn; no model request or manual turn event is needed. + +An application-defined `deepseekbot_cli` Tool runs the actual CLI parser against a per-invocation broker, sharing the existing capture factory, target checks, ChannelToolApproval, confirmations, revision checks, exact argv/stdin identity and live execution guard with the native Shell path. Its hidden native Node subprocess takes cwd from the owned Agent, including relative-file preparation before the broker call. The Tool is available only during the authenticated direct lease, with a resolved native tool selection; ordinary model turns do not acquire it. The Tool is not a new permission authority. Its owning model-free native invocation holds a process-local lease binding the accepted Human source, Agent, native turn, current request, exact argv/stdin, signal, call ID and surviving trusted Tool Registration. After the existing permission fences, native pre-execute binds the executor token and delegates only that transport to the broker; the native guard and trusted Tool body revalidate it. The broker remains the single exact-operation approval owner, so the transport does not create a second card or expose raw stdin. A known private transport with missing or changed authority is refused before card creation. Model-origin or same-name replacement Tools and ordinary Shell calls do not acquire this delegation. Unknown declarations remain opaque. Recursive `tob-cli` requests are refused by the broker. + +One live request is admitted at a time. Starting refuses a busy Orchestrator or direct tool; direct tools cannot borrow its live root. New ordinary DMs queue instead of steering into this execution. Cancellation, stop and runtime closure abort its signal, and the invocation’s broker closes in finally. Preparation and execution retain the canonical source fence. Requests never automatically replay on restart. + +Status/results are bounded process evidence: at most sixteen entries, ten minutes after settlement, one MiB combined output per entry, one MiB stdin, 256 argv entries / 64 KiB argv, and a ten-minute execution deadline. Stdin is not copied into the Human DM. A safe request-ID marker on that existing message rejects ordinary DM retry/continuation after the transient lease ends, including after restart. Completed means the invocation settled; its exitCode and JSON stdout retain command refusals. Unknown or expired request IDs are refused. There is no new approval store, database migration or durable command lifecycle. ChannelToolApproval and Source Event/Admission remain authoritative. + +## Consequences + +Agents can start a production-shaped CLI request, inspect the genuine pending approval through existing Channel/Activity reads, decide through the existing Human CLI or Web card, then retrieve the actual command result. Model integration remains separately testable. Host restart expires result lookup; after uncertainty, inspect the owning command’s canonical readback before starting another request. A captured historical Source Event never grants this path authority. diff --git a/docs/agents/ax-performance.md b/docs/agents/ax-performance.md index 0ef05f8ea4..eb898b3c78 100644 --- a/docs/agents/ax-performance.md +++ b/docs/agents/ax-performance.md @@ -189,3 +189,13 @@ When a new surface can regress the same way (a long list, a live-updating panel, extend the measurement script or add one beside it, give it a budget file under `scripts/perf-budgets/`, cover the checker with a test, and wire it into the CI plan the same way. A metric without a budget is observation only; it does not guard anything. + +## CLI effect classification and surrounding owner journey + +`node scripts/perf-cli-effects.mjs --instance --fixture --source-sha <40-char-sha> --output ` measures cold native Node CLI processes against the authenticated Host: list, select an Approval Template, and canonical selection readback. The fixture contains `bot`, `from`, and `to` template names; create it with public CLI commands and keep the same stopped/restarted task Profile across source arms. Every round restores the original selection outside its measured samples. Add `--classification --baseline ` for the candidate arm. + +`scripts/perf-budgets/cli-effects.json` bounds cold request latency, added median latency, process peak RSS and warmed classification p99. The 2 s cold-request ceiling covers startup and completed Host work; the added-work allowance is 250 ms, while classification itself gets 5 ms at p99, including the existing 256-argument maximum. These are initial regression ceilings, not claimed improvements. The script verifies operation results, fixture/Node identity and classification outcomes as well as timing. It neither starts Hosts nor supplies broker authority. A successful direct-Human owner journey does not qualify a Tob approval-card flow; record that separately. + +For model-free Tob admission, run `node scripts/perf-tob-cli.mjs --source-sha --instance --fixture --output ` with `{ "argv": ["approval-templates"] }` (or the same synthetic Bot filter for each arm). It compares the actual cold direct CLI/Host read with the full typed request/native Agent/broker/result journey, including CLI process startup and status polling. `scripts/perf-budgets/tob-cli.json` retains the existing two-second cold CLI budget and separately bounds added native journey work at five seconds, total at seven seconds and captures at twelve seconds. No Human decision wait or model call belongs in this deterministic fixture. Freeze source, bundle hashes, Node, Profile and fixture; measure base/head surrounding direct calls separately with `perf-cli-effects.mjs`. Retain correctness and failures; these budgets do not imply a speedup or replace protected approval/runtime screenshots. + +Use `--rounds 1` for a predeclared single native-journey sample; values cannot exceed the recorded three-round cohort cap. The report records the requested round count, and the runner stops after the first correctness, latency or cancellation failure. Compressed Session audit reads are capped through an owned descriptor before allocation and reject growth beyond sixteen MiB. Keep older failed cohorts distinct from any newly frozen protocol. diff --git a/docs/architecture/bot-approval-policy.md b/docs/architecture/bot-approval-policy.md index c55a80068a..d67ce0a53a 100644 --- a/docs/architecture/bot-approval-policy.md +++ b/docs/architecture/bot-approval-policy.md @@ -1,10 +1,10 @@ # Bot approval policy -Status: Human-confirmed target design, 2026-11-15. Runtime behavior is unchanged by this documentation. [中文](bot-approval-policy.zh.md). +Status: Human-confirmed design, 2026-11-15. This document records design and implementation boundaries; GitHub issues own delivery status. Documentation changes no runtime settings. [中文](bot-approval-policy.zh.md). [ADR-0342](../adr/0342-bot-approval-selects-one-template-and-keeps-deterministic-authorization-separate.md) owns the durable choices and trade-offs. This document owns the integrated target behavior. GitHub issues own delivery status. Neither this interview nor these documents authorize implementation, live permission changes or a SQLite migration. -Implementation slice #4211 adds global/Bot selection through the existing file owner, authenticated Host, online CLI and Client Select, plus two-outcome versioned Reviews. The remaining editor, rules-table and confirmed bulk-deletion workflows are subsequent slices. +The implementation keeps template files and global selection in the existing file owner, Bot choices in the Bot Registry, card authorizations in the Tool Approval Rule owner, and decisions in Channel Tool Approval. Slices #4205, #4211, #4244, #4245, #4246, #4210 and #4212 cover declarations, selection, three-part editing, rule management, confirmed deletion and shared CLI/native admission. Delivery evidence is source-qualified; iOS and outstanding matched-performance checks remain in [QA #2742](https://github.com/BotHarness/DeepSeekBot/issues/2742#issuecomment-6909957258). ## One effective template @@ -39,9 +39,9 @@ The target removes autonomous model reject. Consequently, the current model-reje The target first uses deterministic code to determine whether the action needs approval and resolve valid deterministic authorization. A covered request does not incur a model call. An uncovered request uses the effective Reviewer policy or goes to the Human when the Reviewer is disabled. -Full Access does not by itself waive the external-effect approval proposed in [E2 #4210](https://github.com/BotHarness/DeepSeekBot/issues/4210). The concrete effect declarations and admission mechanism remain in [E1 #4205](https://github.com/BotHarness/DeepSeekBot/issues/4205), E2 and [E4 #4212](https://github.com/BotHarness/DeepSeekBot/issues/4212). No claim is made that arbitrary behavior can be inferred reliably from a command string. +Implementation slice #4210 routes trusted irreversible external effects through the common approval owner even under Full Access. Deterministic rules resolve before the Reviewer; approval records capture the declared effects for presentation. Management keeps ADR-0249’s dedicated scope. Full Access does not by itself waive the external-effect approval specified in [E2 #4210](https://github.com/BotHarness/DeepSeekBot/issues/4210). The concrete effect declarations and admission mechanism remain in [E1 #4205](https://github.com/BotHarness/DeepSeekBot/issues/4205), E2 and [E4 #4212](https://github.com/BotHarness/DeepSeekBot/issues/4212). No claim is made that arbitrary behavior can be inferred reliably from a command string. -Card-created Tool Approval Rules remain deterministic, Bot-scoped authorizations with their existing role, authority scope and execution checks. They appear in the Always allow table with a source such as “From approval card”, their scope and a revoke action. Their display alongside natural-language rows does not change how either kind executes. They are not written into the shared template, granted to other Bots using it, or included in template copies. A natural-language row cannot override an already matched deterministic rule; the Human must revoke that rule to return those requests to review. +Card-created Tool Approval Rules remain deterministic, Bot-scoped authorizations with their existing role, authority scope and execution checks. The Bot permissions table shows their source such as “From approval card”, role, scope and revoke action. This separate display does not turn them into the template editor's natural-language Always allow rows. They are not written into the shared template, granted to other Bots using it, or included in template copies. A natural-language row cannot override an already matched deterministic rule; the Human must revoke that rule to return those requests to review. Current ownership, Workspace Grant, device-target and rule-revocation checks remain independent of model permission. Effective policy management skips the model Reviewer and Full Access, but may use an explicitly saved authorization covering that management operation under ADR-0249. Existing ordinary rules do not gain management authority. Management approval identifies affected Bots. @@ -60,6 +60,8 @@ Deleting a referenced template uses a second confirmation listing affected Bots If the global default is another template, Bots falling back to inheritance use that template. Confirmation must disclose that result, not merely say the deleted template will be removed. Deterministic rules and Full Access are not revoked or changed by this operation. +The application-defined deletion workflow composes the existing template-file owner and Bot Registry. The authenticated Host provides a read-only impact preview and rechecks its revision before confirmed deletion. The revision includes the template, remaining global policy and complete reference set. Visible Bot identities and a count of protected private references disclose the impact without opening another Human's private Bots. A stale preview is refreshed for another explicit confirmation; a missing template or unreadable global selection refuses deletion rather than applying fallback. An existing unreadable custom file can be removed by an explicitly confirmed CLI recovery preview marked `contentUnavailable`; that revision binds bounded filesystem identity (device/inode, size and timestamps), not a full content hash. Readable-template revisions remain content-bound, and changed identity or repaired content requires another preview. Reviewer content-read limits are unchanged. File deletion failure attempts to restore the preceding choices and reports incomplete restoration explicitly. No new persistence authority or database migration is introduced. + ## Review snapshots and failures Each Review captures its template identity, version and content when it begins. Edits and selection changes affect later Reviews; already-started Reviews may finish using their captured version. Review records retain that identity/version. This is policy-version consistency, not an exception to current authorization and execution fences. @@ -102,18 +104,28 @@ The official Claude Code [permissions documentation](https://code.claude.com/doc - Q16–Q18: preserve existing Bot choices; no standing rules from model allow; clear the global selection when its default is deleted. - Final confirmation: the Human accepted the complete summary before any design documentation was written. -## Delivery and verification boundary +## Interview delivery boundary (historical, 2026-11-15) + +The User confirmed the design after questions Q1–Q18 and a complete summary. There are no outstanding product decisions in that interview tree. Implementation mechanics, CLI contracts, storage/version representation and migration were left to implementation tasks at that time, rather than silently selected by the interview. Current implementation facts follow below; SQLite migration remains separate. The existing application-defined approval owner remains the owner; DSH-native approval/request, Session and API Gateway seams are not replaced by a second authority. -The User confirmed the design after questions Q1–Q18 and a complete summary. There are no outstanding product decisions in that interview tree. Implementation mechanics, CLI contracts, storage/version representation and migration are future work, not silently selected here. The existing application-defined approval owner remains the owner; DSH-native approval/request, Session and API Gateway seams are not replaced by a second authority. +The interview recorded these delivery requirements: demonstrate inherited versus specific/Off behavior, Reviewer conflict/uncertainty routing, deterministic bypass without an LLM call, Bot-only card-rule scope, disclosed deletion fallback, captured policy versions, failure routing and management refusal without valid authority. Their source-qualified evidence and outstanding checks live in the implementation issues and QA #2742; the historical interview itself proves no runtime or test result. -Future delivery must demonstrate inherited versus specific/Off behavior, Reviewer conflict/uncertainty routing, deterministic bypass without an LLM call, Bot-only card-rule scope, disclosed deletion fallback, captured policy versions, failure routing and management refusal without valid authority. These are acceptance requirements, not claims that tests or the runtime already implement them. +Performance assessment: documentation-only edits introduce no dependency and change no runtime hot path, so no runtime benchmark is warranted for those edits. This exemption does not cover feature implementation. Added admission work and model calls require separate budgets, deterministic hits must make no Reviewer call, and real-journey verification follows the repository's performance policy. Outstanding matched comparisons remain in QA #2742. -Performance assessment: this change edits documentation only, introduces no dependency and changes no runtime hot path, so no runtime benchmark is warranted. Future E2/E3 work must separately budget added admission work and model calls, prove deterministic hits make no Reviewer call, and verify the affected real journey under the repository's performance policy. +## Current implementation boundaries The #4244 editor retains the template-file owner and 32 KiB bounded reads. ADR-0342 records the v1 content representation; legacy Markdown maps intact to free text. Copies contain only content. Save and apply are separate choices, shared-original editing shows global inheritors among actual users, and content edits affect future Reviews. +Direct CLI effect calls use an owned native execution Session with the existing `direct-` identity prefix. Ownership resolves for admission and audit, but these one-call executions are excluded from persistent Bot root enumeration: they must not become the current chat Orchestrator or cause report delivery to wake a model. The native Agent is disposed after the call; ownership and execution evidence remain. + ## Human approval result presentation A Reviewer handoff appends an explicit `ask-human` result to the canonical Channel before the Human request, with its captured template identity/version, sanitized input and reason. Record failure still routes to Human; cancellation and owner changes cannot grant authorization. Historical autonomous rejection records remain readable; the historical rejection override cannot accept an `ask-human` record. The Web and mobile Human approval card keeps its full request content after Allow once, Always allow or Reject. Only the operation area becomes the selected, disabled result. Open details remain open across a decision, and historical cards retain the original content on reload. Mobile projects validated display-only request content from the existing Channel message, without per-card history/status reads; cached content never authorizes a decision. Missing or malformed historical content is shown as unavailable. + +Typed Tob command preparation must provide a review proposal whenever the shared declaration requires approval. A completed operation receipt is explicitly read back without starting the effect again; caller-supplied completion claims cannot select that path. + +Tool approval requests and Reviewer records for an Orchestrator stay in the actual originating DM or Group. A participant DM never falls back to the principal’s legacy DM. An unavailable or mismatched origin refuses review and card creation; this does not grant the participant any approval permission. Existing approver and audience checks still control visibility and decisions. + +Authenticated direct `bot-tool` requests bind their transient native execution to the calling Human’s DM, before dispatch, and remove that binding when the call settles. Tool targets and historical Channel placements do not select the approval recipient. A missing calling context does not fall back to another Human. diff --git a/docs/architecture/bot-approval-policy.zh.md b/docs/architecture/bot-approval-policy.zh.md index 988f44fde7..0a54b4dd81 100644 --- a/docs/architecture/bot-approval-policy.zh.md +++ b/docs/architecture/bot-approval-policy.zh.md @@ -1,10 +1,10 @@ # Bot 级自动审批策略 -状态:Human 于 2026-11-15 确认的目标设计,分片实施中。本文档不改变运行行为。[English](bot-approval-policy.md)。 +状态:Human 于 2026-11-15 确认的设计。本文记录设计与实现边界;GitHub issue 记录交付状态,文档不改变运行设置。[English](bot-approval-policy.md)。 [ADR-0342](../adr/0342-bot-approval-selects-one-template-and-keeps-deterministic-authorization-separate.md) 记录长期决策与权衡,本文整合目标行为;GitHub issue 记录交付状态。设计确认不授权实施功能、更改运行权限或推进 SQLite 迁移。 -实施首片 #4211 通过既有文件 owner、认证 Host、在线 CLI 和 Client Select 打通全局/Bot 选择及两结果版本化 Review。三部分编辑、规则统一表和确认后的批量删除回退由后续切片交付。 +实现沿用既有模板文件 owner 保存模板与全局选择、Bot Registry 保存 Bot 选择、Tool Approval Rule owner 保存卡片授权、Channel Tool Approval 决定审批。#4205、#4211、#4244、#4245、#4246、#4210、#4212 分别覆盖效果声明、选择、三部分编辑、规则管理、确认删除及 CLI/native 共用准入。交付证据保留源码与平台范围;iOS 和未完成的匹配性能检查仍在 [QA #2742](https://github.com/BotHarness/DeepSeekBot/issues/2742#issuecomment-6909957258) 跟踪。 ## 一份有效模板 @@ -39,9 +39,9 @@ Profile 有一个可选的全局默认模板,来源是共享 Approval Template 先由代码判断行为是否需要审批,再处理有效的确定性授权;已覆盖的请求不调用 LLM。未覆盖时使用有效模板 Reviewer;未启用 Reviewer 则交给 Human。 -Full Access 本身不豁免 [E2 #4210](https://github.com/BotHarness/DeepSeekBot/issues/4210) 所指的不可撤销外部调用审批。具体效果声明与准入机制仍属于 [E1 #4205](https://github.com/BotHarness/DeepSeekBot/issues/4205)、E2 与 [E4 #4212](https://github.com/BotHarness/DeepSeekBot/issues/4212),本次不实施,也不声称能从任意命令文本可靠推断其全部行为。 +实现切片 #4210 将可信声明的不可撤销外部效果送入统一审批,Full Access 不豁免。确定性授权先于 Reviewer,审批记录保存本次效果供呈现;管理操作继续使用 ADR-0249 的专用显式授权范围。具体效果声明与准入机制见 [E1 #4205](https://github.com/BotHarness/DeepSeekBot/issues/4205)、[E2 #4210](https://github.com/BotHarness/DeepSeekBot/issues/4210) 与 [E4 #4212](https://github.com/BotHarness/DeepSeekBot/issues/4212);不声称能从任意命令文本可靠推断全部行为。 -卡片 Always allow 保存的 Tool Approval Rule 是确定性授权,继续绑定具体 Bot、角色、授权范围及执行检查。在 Always allow 表格共同展示时,必须标注“来自卡片”、作用范围及撤销入口;共同展示不改变两类条目的执行方式。它不写入共享模板,不授权使用同模板的其他 Bot,也不随模板复制。已经命中确定性规则时,模板中的自然语言不会覆盖它;需要重新审核时,由 Human 撤销该规则。 +卡片 Always allow 保存的 Tool Approval Rule 是确定性授权,继续绑定具体 Bot、角色、授权范围及执行检查。Bot 权限表标注“来自卡片”、角色、作用范围及撤销入口;独立展示不会将它们变成模板编辑器中的自然语言 Always allow 行。它不写入共享模板,不授权使用同模板的其他 Bot,也不随模板复制。已经命中确定性规则时,模板中的自然语言不会覆盖它;需要重新审核时,由 Human 撤销该规则。 当前所有权、Workspace Grant、设备目标及授权撤销检查独立于模型判断。生效中的策略管理跳过 Reviewer 与 Full Access,须由 Human 决定,或使用 ADR-0249 独立管理范围中确实覆盖该操作的显式已保存授权。旧普通规则不因此获得管理权限。管理审批展示受影响的 Bot。 @@ -62,6 +62,8 @@ Full Access 本身不豁免 [E2 #4210](https://github.com/BotHarness/DeepSeekBot 如果全局仍选另一份模板,回退继承的 Bot 随即使用它,确认信息必须说明这一结果,而不只是说“删除模板”。删除不撤销确定性授权,不改变 Full Access。 +应用定义的删除工作流组合既有模板文件 owner 与 Bot Registry。认证 Host 提供只读影响预览,确认删除时重新校验 revision;其绑定模板、剩余全局策略及完整引用集合。界面列出可见 Bot,以数量披露受保护的私有引用,不打开其他 Human 的私有 Bot。预览过期后刷新影响,须再次显式确认;模板缺失或全局选择不可读时拒绝删除,不执行回退。已存在但内容不可读的自定义文件,可通过标为 `contentUnavailable` 的 CLI 恢复预览并显式确认删除;此时 revision 绑定有界文件系统身份(设备/inode、大小及时间戳),不做完整正文哈希。正常模板仍绑定正文;身份变化或修复内容后须重新预览。Reviewer 正文读取上限不变。文件删除失败会尝试恢复先前选择,恢复不完整时明确返回失败。不新增持久化权威或数据库迁移。 + ## Review 快照与失败 每次 Review 开始时固定所用模板身份、版本和内容。编辑及选择切换影响之后开始的 Review;已开始的 Review 可以按旧版本完成,记录保留当次身份与版本。该快照不豁免实时所有权、范围、Grant 和已撤销授权的执行检查。 @@ -104,18 +106,30 @@ Full Access 本身不豁免 [E2 #4210](https://github.com/BotHarness/DeepSeekBot - Q16–Q18:保持既有 Bot 选择;模型放行不存规则;删除全局默认时清空全局。 - 最终确认:Human 确认完整汇总后,才开始写入设计文档。 -## 确认与交付边界 +## 访谈时的交付边界(2026-11-15 历史记录) + +Human 在 Q1–Q18 分轮访谈后确认了完整汇总;原设计树无未决产品分支。当时将实现机制、CLI 契约、版本表示、持久化格式与迁移留待实施任务,而非由访谈暗中决定。当前实现边界另列于下文;SQLite 迁移仍独立处理。既有应用定义的审批 owner 仍持有决定权;不新设另一套权威,不替换 DSH-native approval/request、Session 或 API Gateway seam。 -Human 在 Q1–Q18 分轮访谈后确认了完整汇总;原设计树无未决产品分支。实现机制、CLI 契约、版本表示、持久化格式与迁移留待实施任务,不在本文偷偷作决定。既有应用定义的审批 owner 仍持有决定权;不新设另一套权威,不替换 DSH-native approval/request、Session 或 API Gateway seam。 +访谈记录的交付要求是验证:继承/特定/关闭的有效选择;冲突及不确定转 Human;确定性命中时没有 LLM 调用;卡片规则只授权所属 Bot;删除结果披露及回退;Review 固定版本;故障转 Human;无有效管理授权时拒绝策略变更。具体证据保留源码范围,未完成检查见实施票与 QA #2742;历史访谈本身不能证明运行或测试结果。 -后续交付须验证:继承/特定/关闭的有效选择;冲突及不确定转 Human;确定性命中时没有 LLM 调用;卡片规则只授权所属 Bot;删除结果披露及回退;Review 固定版本;故障转 Human;无有效管理授权时拒绝策略变更。这是未来验收要求,不是已实现或已通过测试的声明。 +性能评估:纯文档编辑无新依赖、无运行热路径变化,因此免运行性能基准;该豁免不覆盖功能实现。新增准入工作及模型调用须分别预算,确定性命中不调用 Reviewer,实际旅程依仓库性能规则验证。未完成的匹配比较仍在 QA #2742 跟踪。 -性能评估:本次只有文档变更,无新依赖、无运行热路径变化,因此免运行性能基准。未来 E2/E3 须分别预算新增准入工作及模型调用,证明确定性命中不调用 Reviewer,并依仓库性能规则验证实际旅程。 +## 当前实现边界 #4244 的三部分编辑沿用模板文件 owner 与 32 KiB 有界读取;使用 ADR-0342 记录的 v1 内容表示,旧 Markdown 完整映射为补充说明。复制只复制内容;保存与应用分开,编辑共享原件显示全局继承者在内的使用者。编辑仅影响后续 Review。 +实现切片 #4210 将可信声明的不可撤销外部效果送入统一审批,Full Access 不豁免。确定性授权先于 Reviewer,审批记录保存本次效果供呈现;管理操作继续使用 ADR-0249 的专用显式授权范围。直接 CLI 的此类调用经过原生工具执行入口,不启动模型回合。 + +直接 CLI 效果调用使用既有 `direct-` 前缀的原生执行 Session。统一归属记录用于准入与审计,但此类单次执行不进入 Bot 持久根 Session 的枚举,不能替代聊天 Orchestrator 或使报告投递唤醒模型。调用结束后释放原生 Agent,保留归属与执行证据。 + ## Human 审批结果展示 Reviewer 转交时,先向同一 canonical Channel 写入显式 `ask-human` 结果,再创建 Human 请求,保留 Review 起始模板身份、版本、已脱敏输入和原因。记录失败仍转 Human;取消或 owner 改变不能授权。历史自动拒绝记录继续可读,旧拒绝覆盖入口不能接受新的 `ask-human` 记录。 Web 与移动端的 Human 审批卡在允许这次、始终允许或拒绝后保留完整请求内容,仅操作区变为已选中、禁用的结果。决定前打开的详情保持打开,历史卡在重载后仍可查看完整内容。移动端从现有 Channel 消息投影已验证的只读请求内容,不逐卡增加历史或状态请求;缓存内容不能提供决定权限。历史内容缺失或格式无效时如实显示不可用。 + +类型化 Tob 命令准备阶段在共享声明要求审批时必须提供审批提案。已完成操作的回执由规范 owner 明确标记为只读回读,不会再次发起效果;调用方自称已完成不能选择这条路径。 + +Orchestrator 的工具审批请求与 Reviewer 记录保留在实际来源 DM 或 Group。参与者 DM 不会回落到管理者的旧 DM;来源不可用或与 Bot 不匹配时,拒绝启动审核和创建卡片。此路由不会授予参与者审批权限;可见内容与决定仍受原有审批者和频道受众检查约束。 + +已认证的直接 `bot-tool` 请求在派发前,将短期原生执行绑定到调用 Human 的 DM,并在调用结束时移除绑定。工具目标与历史频道记录不决定审批接收者;缺少调用上下文时,不回落到其他 Human。 diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index fff87c230b..47f11bde43 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -654,17 +654,21 @@ The application-defined `ConnectionsDialog` presents pairing and device manageme [ADR-0202](../adr/0202-phone-push-is-a-content-free-projection-of-the-activity-list.md)([#1655](https://github.com/BotHarness/DeepSeekBot/issues/1655)):应用定义的 Push delivery 模块(`packages/core/src/push/`)是 Activity 的投影,不另设通知权威。Activity 表或 PersonaBot 的审批、提问、私密输入计数变化时(以及每分钟一次的兜底扫描),模块读取 `action` 项与未读的 `replies` 项,对每台已登记的配对设备只发送一次新项,并经 Expo Push Service 投递;推送标题为频道名(`#名称`,私信为 PersonaBot 名称),正文为所需操作加上工具与主要参数、问题或消息的简短预览(折叠空白,最多 140 字符);私密输入请求不含内容([ADR-0213](../adr/0213-phone-push-shows-the-channel-and-a-short-preview.md))。数据字段只含 Host 标识、Activity 项标识、PersonaBot 标识与读取请求所需的 Channel/消息标识,并携带未处理 Human 操作数作为角标。设备经设备网关的 `/botharness-device/push` 登记 Expo push token、切换各类通知、发送测试通知;撤销设备或 Expo 回报 `DeviceNotRegistered` 时删除 token。发送失败有界重试,结果写入不含内容的 `push` 开发者日志。App 保存每台配对的 Host,点按通知先切换到对应 Host,再打开该审批、提问或私信。 -## 已确认目标:Bot 级自动审批策略(分片实施) +## Bot 级自动审批策略:设计与实现边界 #4211 的首片沿用既有模板文件 owner、Bot Registry 与 Channel Tool Approval owner:全局选择保存在模板目录的 `.selection.json`,Bot 的既有 `approvalTemplate` 字段使用非法模板名标记 `@global` 显式继承;缺字段仍为 Off,新建才写入继承。不新增数据库迁移。认证 Host 的 `approvalTemplateGlobalSet`、既有 Bot setter、在线 CLI 和 Client 的 DSH Select 共用此选择;模板库读失败与主动空值分开。全局选择也参与生效模板的管理识别,ADR-0249 的独立管理授权不变。 -Channel Tool Approval 先处理确定性授权,之后固定当次模板正文及 SHA-256 内容版本,才调用 Reviewer。模型只允许当前调用或转 Human;原拒绝触发的暂停/恢复不再运行,旧拒绝记录保留读取兼容。Human 请求的 `approvalReview` 与自动放行的 `templateVersion` 保留当次版本,开发日志同样记录版本;失败卡片给出安全原因。快照不替代现有执行 fence。三部分编辑、卡片规则表、确认删除后的批量回退及 E2 外部效果准入仍属于后续切片。 +Channel Tool Approval 先处理确定性授权,之后固定当次模板正文及 SHA-256 内容版本,才调用 Reviewer。模型只允许当前调用或转 Human;原拒绝触发的暂停/恢复不再运行,旧拒绝记录保留读取兼容。Human 请求的 `approvalReview` 与自动放行的 `templateVersion` 保留当次版本,开发日志同样记录版本;失败卡片给出安全原因。快照不替代现有执行 fence。三部分编辑保留既有模板文件 owner 和有界读取;旧 Markdown 完整映射为 free text,结构化内容通过版本标记保存,不新增数据库权威。卡片规则由既有 Tool Approval Rule owner 按 Bot、角色和 scope 展示及撤销,不混入模板内容或副本。 2026-11-15 的设计访谈确认:Bot 在动态继承全局、选择特定模板、关闭 Reviewer 三态中选一,特定模板完整替换全局,不再叠加 Bot 额外行。模板包含自然语言 Always ask、Always allow 与 free text;确定性授权先处理,Reviewer 只批准当前调用或转 Human,不自主拒绝、不创建规则。Full Access 不一概豁免 E2 的外部效果审批目标。自然语言理解不是硬权限边界,卡片保存的规则仍归具体 Bot 并标注来源。 共享模板的创建来源与应用动作均由用户显式选择;删除时二次确认并列出受影响 Bot,特定引用统一回退继承,删除全局默认时同时清空全局。Review 固定开始时的模板版本,后续编辑影响新 Review;模板缺失或 Reviewer 故障转 Human,不静默修改选择。新 Bot 默认继承,旧 Bot 保持原选择;生效中的策略管理仍受 ADR-0249 的独立管理授权及执行检查约束。 -完整确认内容、实现事实及与 #4203/E3 的差异见 [Bot 审批策略](https://github.com/BotHarness/BotHarness/blob/main/docs/architecture/bot-approval-policy.md)([中文](https://github.com/BotHarness/BotHarness/blob/main/docs/architecture/bot-approval-policy.zh.md))与 [ADR-0342](../adr/0342-bot-approval-selects-one-template-and-keeps-deterministic-authorization-separate.md)。此处是目标设计,不代表下文历史实现记录已经改变;不授权功能实施或 SQLite 迁移,也未改写现有 GitHub 规格。 +确认删除由模板文件 owner 与 Bot Registry 组合:Host 先返回绑定模板、全局选择和引用集合的只读 revision 预览,Human 再显式确认;变化需重新确认,特定引用统一回退继承,删除全局默认时清空全局。失败恢复不能把列表漏项当成删除成功,Client 并发读只提交最新结果,不重放写入。 + +共享的 ToolEffects 与 CLI 注册表声明进入既有准入函数及审批 owner:不可撤销外部效果在 Full Access 下仍可能需要 Reviewer 或 Human,独立管理授权、Grant、设备目标及实时撤销检查不变。model-free Tob CLI 从认证 Human DM 准入实际 native Turn,固定 argv、cwd、stdin 字节数和哈希并返回 canonical 终态;直接 Bot tool 使用调用者的可信 DM,来源不明时不回退 principal DM。typed CLI 不消费留给模型的 Memory 通知,资源清理错误不覆盖工具结果。Human 决定后,审批卡保留完整内容、详情与禁用的已选结果。 + +完整确认内容、实现事实及与 #4203/E3 的差异见 [Bot 审批策略](https://github.com/BotHarness/BotHarness/blob/main/docs/architecture/bot-approval-policy.md)([中文](https://github.com/BotHarness/BotHarness/blob/main/docs/architecture/bot-approval-policy.zh.md))与 [ADR-0342](../adr/0342-bot-approval-selects-one-template-and-keeps-deterministic-authorization-separate.md)。ADR 保留设计确认时的历史背景,GitHub 实施票和 PR 记录交付状态。源码限定的运行证明与平台验收分开;未完成的 iOS 与匹配性能检查见 [QA #2742](https://github.com/BotHarness/DeepSeekBot/issues/2742#issuecomment-6909957258)。文档不改变权限或推进 SQLite 迁移。 ## 5 · Orchestrator 与 Assignment control plane @@ -1765,6 +1769,18 @@ latency measurement. Runtime and screenshot qualification are recorded separatel E3 的 Human 审批卡在允许这次、始终允许或拒绝后保留完整请求,操作区显示禁用的已选结果,详情的手动开合状态不变。Reviewer 的显式 `ask-human` 紧凑结果先写入同一 ChannelStore,再生成 Human 请求;历史拒绝记录不改变两结果 Reviewer 契约。移动端从既有消息投影已验证的只读内容,历史卡不逐卡查询 Host;缓存内容不能授权,缺失或已清除的内容如实显示不可用。当前契约见[审批策略](bot-approval-policy.zh.md)。 +### CLI effect declaration ownership + +The application-defined CLI declaration table in `bots/cli-effects.ts` supplies effects to direct command dispatch and Channel Tool Approval for typed and exact-argv Tob operations. Each declaration separately retains the broker's existing read admission; effect metadata does not confer caller authority. The broker continues to own Human DM provenance, target authorization, exact operation identity and live revocation fences. Unknown commands and arbitrary Shell text retain the existing protected path. The dispatch inventory check follows real command-family arrays and entry branches rather than help or search text. + +CLI flag declarations live in the data-only `bots/cli-option-spec.ts` module. `cli-options.ts` owns strict parsing for both dispatch and effect resolution without importing runtime handlers; the existing command-family modules re-export their option groups. Effect-contract type consumers therefore do not acquire the Host credential and child-process implementation graph. + +### Model-free Tob CLI admission + +The authenticated Owner `tob-cli start/status/cancel` interface uses the existing Human DM Source Event/Admission and serialized BotRuntime Orchestrator owner. Its explicit execution variant invokes the application-defined `deepseekbot_cli` through DSH-native Tools.execute in the real live Agent scope, without model followup. The per-invocation broker shares the Shell path’s capture factory and ChannelToolApproval; metadata grants no authority. An exact process-local lease from the owning accepted native turn binds the trusted surviving Tool Registration, argv/stdin, signal, call ID and executor token; native admission, guard and Tool body revalidate it so only this transport delegates its redundant outer review to the broker’s exact-operation card. A bounded transient request/result view supplies cancellation and readback without a second approval store or durable command lifecycle. See [ADR-0347](../adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md). + +已认证 Owner 的 `tob-cli start/status/cancel` 复用真实 Human DM、规范 Source Event/Admission 及 BotRuntime 的串行 Orchestrator owner;执行变体在实际存活的 Agent scope 中通过 DSH 原生 Tools.execute 调用应用定义的 `deepseekbot_cli`,不触发模型。每次调用的 broker 复用 Shell 的权限捕获、真实审批及实时执行 fence;所属原生回合的进程内精确调用 lease 绑定存活的可信 Tool Registration、argv/stdin、signal、call ID 和执行器 token,在准入、guard 与 Tool body 重验,仅让该传输调用委托给 broker 的准确操作审批卡,避免重复卡片及原始 stdin 展示。短期有界结果只用于取消和读取,不建立第二审批权威或持久命令生命周期。 + ### Workspace Grant Project Skill catalog(#4236) `SkillOwner` 的 Workspace 分支携带稳定的 `workspaceId` 与独立显示名 `name`,owner key 为 `workspace:`;Channel 消息保存发送时的名称、owner、路径与文本快照,重试意图仅比较稳定 owner key。`SkillCatalog` 按会话中 Human 可读取的活跃 Bot 查询当前有效 Grant,将同一 Workspace 去重后只读取授权根下 `.dsh/skills` 与 `.agents/skills`,不使用 DSH 会向 Git 根回溯的 Project 发现;两目录均按 DSH YAML frontmatter 与 user-invocable 语义解析,重名时 `.dsh` 优先,拒绝逃出授权 Skill 目录的符号链接。Workspace 目录按 ID 与路径缓存,读取快照时重新读取文件并再次核对有效 Grant,保留 64,000 字符上限与既有拒绝码。 diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 4aa25d3269..9b625dc6e8 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -241,6 +241,8 @@ deepseekbot folder-browse [] [--offset ] deepseekbot grant-create --workspace ``` +Trusted irreversible external tool calls enter common approval even with Full Access. `bot-tool` uses the same Host admission without a model; a valid saved authorization is checked before any Reviewer call. Read `toolApprovalRequest.effects` and bilingual `effectLabels.en` / `effectLabels.zh` on approval messages from online `channel-messages`. These labels describe trusted declarations, not claims in tool input or output. Management operations still require their dedicated explicit authorization (ADR-0249). + `skills-list` returns the Skills the `/` menu offers in that conversation, ranked like the menu by `--query` (name prefix, then name subsequence, then owning Bot display name or slug or Workspace name or ID substring, then description substring): Host Skills (`owner.kind` `host`) and the Project Skills under each PersonaBot's Memory Repository `.agents/skills` or `.dsh/skills` (`owner.kind` `bot`), as that Bot's Orchestrator sees them, plus Project Skills in the two Skill directories at each active Workspace Grant root (`owner.kind` `workspace`, with stable `workspaceId` and display `name`). Workspace entries are listed once across conversation Bots, never include an enclosing repository's Skills, and disappear when the last eligible Grant is revoked. Only active Bots readable by the sender contribute entries. Pass `--channel ` instead of `--bot` for any Channel. `send --skill /` (owner `host`, `bot:` or `workspace:`, repeatable) turns the first unused `/name` token in the body into a Skill Invocation for each flag, in flag order (the token must start and end at whitespace or a body boundary; the send is refused if no unused occurrence remains): the Host stores the Skill's text as it is now with the message and the Bot reads it as a `` block. Workspace IDs come from `skills-list` and remain the owner identity when the folder display name changes. For example, `send --channel --skill workspace:/review --body '/review'` snapshots the selected Skill without mentioning any Bot; mentions must still be supplied through the normal send options. A recipient without that Grant receives the text while the existing file guard blocks reads of its path. The Skill does not choose who replies; a Skill that is gone refuses with `skill-unavailable`, and Skill text longer than 64,000 characters refuses with `skill-too-large` instead of being truncated. See [ADR-0346](adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md). `skills-memory --bot ` lists the Project Skills in that PersonaBot's own Memory Repository, the same list as its profile's **Skills** card: root `.dsh/skills` before `.agents/skills`, model-only Skills included (`userInvocable: false`), Workspace Skills excluded. `skills-show --owner |workspace:>` returns that Skill's full text. `skills-remove --bot --confirm` deletes the Skill folder (or flat `.md` file) from the Memory Repository and commits `skills: remove `, so git history can restore it (uncommitted edits are committed first as `skills: save before removal`; a folder holding git-ignored files refuses with `skill-has-ignored-files`, because history could not restore them); the open `/` menu updates through the live catalog event. Without `--confirm` it refuses. There is no disable switch. A missing Skill refuses with `skill-not-found`. @@ -629,6 +631,8 @@ deepseekbot private-mcp-set --server --enabled deepseekbot private-mcp-remove --server --confirm ``` +Card-created rules also appear under **Always allow · this Bot** in Bot permissions. This is the same canonical rule list: `tool-approval-rules` reads it and `tool-approval-rule-revoke` revokes it. Rules retain their Bot, role and authority scope independently of shared template text and copies. Reload the permissions list after a CLI revoke; the next matching call returns to the existing review flow. + `session-stop ` stops one running Session of a Bot, as the stop button on its row in the Sessions panel does. Its Subagents stop with it, and the Bot's other Sessions keep running. It returns `stopped` and `alreadyIdle`, each a list of `{ botSlug, sessionId, role }`: a Session that is idle, already stopped or stopped twice comes back in `alreadyIdle` and still succeeds. A Session the Bot does not own is refused with `unknown-session`. With `--channel`, the Channel the stop came from gets a one-line notice (`turnStop.target`, plus `messageId` in the result), but only when the Session belongs there: the Bot's Orchestrator in a Channel the Bot is in, an Assignment only in the Channel that started it. `session-stop --activity ` stops the Session behind one row of the Bot's live activity snapshot (`sessions[].id`), as the stop on a row of the Messages header popover does. A row that has already gone means the Session finished, so the command returns empty `stopped` and `alreadyIdle` lists and still succeeds. Pass either a Session id or `--activity`, not both. @@ -866,13 +870,18 @@ deepseekbot approval-template create night-shift --file night-shift.md deepseekbot approval-template create my-cautious --from cautious deepseekbot approval-template edit night-shift --file night-shift.md deepseekbot approval-template delete night-shift +deepseekbot approval-template delete night-shift --confirm --delete-revision ``` +Deletion first returns a read-only `preview`: its `revision` binds the template contents, current global choice and all references. It includes `globalDefaultBefore`, `globalDefaultAfter`, `globalDefaultAvailable`, visible `affectedBots` (`slug` and `source`) and `hiddenBotCount` for references whose private identity you cannot view. Confirm with `--confirm --delete-revision`; no confirmation means no deletion or choice change. Changed contents, references or global policy return `approval-template-delete-changed` and require a fresh preview. + +Confirmed deletion switches specific references to `@global`. Deleting the global default clears it; existing inheritors remain inherited with Reviewer off. A different remaining global default becomes effective; unavailable defaults remain visible as unavailable and unresolved calls go to the Human. Other specific choices, Off, Full Access and saved deterministic rules remain unchanged. Started Reviews retain their captured version. The result includes `inheritedBots` and `globalDefault`; legacy `clearedBots` names the visible specific references that were removed. A failed deletion returns `approval-template-delete-unavailable` (or `approval-template-delete-incomplete` if restoring choices also failed); reload current state before retrying. Unreadable or oversized custom content can still be explicitly deleted: the preview reports `contentUnavailable: true`. Its confirmation revision binds bounded filesystem identity (device/inode, size and timestamps), rather than hashing unreadable contents; normal readable templates retain content-bound revisions. A changed identity or repaired content requires a new preview. Unreadable files are omitted from the template list; address their known name with the CLI preview/delete commands for recovery. Global-selection read failures still refuse deletion. + Names such as `off` and `inherit` remain valid custom template names. Add `--literal-template` to a selection command to select that literal name; without it the existing Off and inheritance aliases keep their meaning. `list` returns `templates` and `globalDefault` (a template name or `null`). With `--bot`, it also returns `selected` (`@global`, a specific template name, or `null`), `source` (`global`, `specific`, or `off`) and `effective` (a name or `null`). The global setter returns `{template}`; the Bot setter returns `{bot}`. The authenticated Host owns these writes; missing templates refuse selection, and an unreadable global selection returns `approval-selection-unavailable` rather than an empty default. -Templates remain read-only built-ins or Markdown files in `$DSH_HOME/botharness/approval-templates/`. The same file owner saves the global choice in `.selection.json`; no schema migration is involved. Names use lowercase letters, digits and dashes, text is at most 32 KiB. `show` returns full text; `create --from` copies text. The editor exposes Always ask, Always allow and free text, with explicit blank/copy creation and save-only or save-and-apply. See [three-part template authoring](#three-part-approval-guidance). Shared rule tables and confirmed bulk deletion fallback are separate slices. +Templates remain read-only built-ins or Markdown files in `$DSH_HOME/botharness/approval-templates/`. The same file owner saves the global choice in `.selection.json`; no schema migration is involved. Names use lowercase letters, digits and dashes, text is at most 32 KiB. `show` returns full text; `create --from` copies text. The editor exposes Always ask, Always allow and free text, with explicit blank/copy creation and save-only or save-and-apply. See [three-part template authoring](#three-part-approval-guidance). Deterministic authorization runs first and makes no Reviewer call when it covers the request. Otherwise the selected template guides a fresh tool-less Reviewer Session: only `allow` for this call or `ask-human` are accepted. Always ask takes precedence over Always allow; free text supplements both. Legacy Reject guidance means ask the Human. The model never saves rules or rejects autonomously, so rejection-based pausing is no longer active. Historical rejection records and their explicit Human override remain readable. @@ -2166,6 +2175,26 @@ Run `deepseekbot approval-template edit my-draft --parts-file guidance.json`. Re Editing a shared original affects future Reviews for every Bot in its `usedBy` list, including global inheritors. Copy first to work independently. Always ask has priority over Always allow, then free text supplements both. These are fallible natural-language instructions, never deterministic Tool Approval Rules. Conflicts, missing coverage or uncertainty ask the Human. Legacy Markdown remains intact as free text when converted; already-started Reviews retain their captured content/version. +### Command effects and caller authority + +The CLI and Tob broker share application-defined command effect declarations. Lint checks actual command registration arrays and entry dispatch branches, independently of the search index. A declaration is not authorization: direct online commands retain authenticated Host owner checks; the broker retains Human DM origin, target ownership, exact argv and stdin hash, confirmation flags, revisions, cancellation and live execution fences. Unknown commands remain undeclared, retain broker approval, and receive the existing CLI refusal. Mixed-purpose commands keep conservative declarations and their existing approval gates; unmigrated Shell text protection remains active. + +Effect resolution uses the CLI's strict argument parser. `channels send` and member-device revocation cannot inherit the same family's broker read admission. `bots` aliases resolve by their dispatched action. Arbitrary tool calls and generic `settings-set` remain opaque when their stdin is unavailable in the proposal; a stdin hash binds operation identity and supplies neither authority nor trusted effects. + +## Model-free Tob CLI requests + +The authenticated Host Owner can run a typed Tob CLI command without a model. Put `{"argv":["approval-templates"],"stdin":""}` in a private JSON file, then run: + +```sh +deepseekbot tob-cli start --args-stdin < request.json +deepseekbot tob-cli status +deepseekbot tob-cli cancel +``` + +Start returns `{id,channelId,messageId,state,cancelRequested}`. The Host records a genuine Human DM and accepts it through the existing Source Event/Admission owner. Its live Tob Orchestrator executes the scoped `deepseekbot_cli` Tool and broker without a model request. No actor, Source Event, Session, cwd or permission override is accepted. Writes keep the existing real approval card; use `tool-approval-status` and `tool-approval-decide`, or decide in the Tob DM. Status becomes `completed` with `result:{exitCode,stdout,stderr}`, or `failed` / `cancelled` with a code. A completed invocation can contain a command refusal: inspect exitCode and JSON stdout. Cancellation is a request until settlement; it does not undo an effect already committed. + +Only one live CLI request is allowed; `bot-busy` refuses overlap with another request, a model turn or a direct tool. The Host refuses unavailable authority (`tob-authority-required`), a closed runtime (`runtime-closed`), and missing/expired request IDs (`cli-request-unavailable`). Results last at most ten minutes after settlement (sixteen retained entries); restart expires them. Commands time out after ten minutes. Input is limited to 256 argv entries / 64 KiB argv and one MiB stdin, output to one MiB combined. Stdin is never copied into the DM. Keep private request files local. After an uncertain result, read the command owner’s canonical state before starting another request. See [ADR-0347](adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md). + ### Channel invitations (M14) ```sh diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index 12c115b20f..f606279e56 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -587,6 +587,8 @@ deepseekbot private-mcp-set --server --enabled deepseekbot private-mcp-remove --server --confirm ``` +审批卡创建的规则也显示在 Bot 权限的「始终允许 · 此 Bot」列表。这与 `tool-approval-rules` 读取的是同一规范规则,使用 `tool-approval-rule-revoke` 撤销。规则保留 Bot、角色和授权范围,不随共享模板及其副本传播。CLI 撤销后重新读取权限列表,下次匹配调用恢复现有审核流程。 + `session-stop ` 停止 Bot 的一个运行中的 Session,与 Sessions 面板中该行的停止按钮相同。它的 Subagent 随之停止,Bot 的其他 Session 继续运行。返回 `stopped` 和 `alreadyIdle`,均为 `{ botSlug, sessionId, role }` 列表:空闲、已停止或重复停止的 Session 出现在 `alreadyIdle` 中,命令仍然成功。Bot 不拥有的 Session 以 `unknown-session` 拒绝。带 `--channel` 时,发起停止的 Channel 会收到一行通知(`turnStop.target`,结果中另有 `messageId`),但只在该 Session 属于这个 Channel 时才发:Orchestrator 对应 Bot 所在的 Channel,Assignment 只对应发起它的 Channel。 `session-stop --activity ` 停止 Bot 实时活动快照中某一行(`sessions[].id`)对应的 Session,与消息面板顶部弹出框中该行的停止按钮相同。该行已消失表示 Session 已结束,命令返回空的 `stopped` 和 `alreadyIdle` 列表,仍然成功。Session id 和 `--activity` 只能传其中一个。 @@ -835,13 +837,18 @@ deepseekbot approval-template create night-shift --file night-shift.md deepseekbot approval-template create my-cautious --from cautious deepseekbot approval-template edit night-shift --file night-shift.md deepseekbot approval-template delete night-shift +deepseekbot approval-template delete night-shift --confirm --delete-revision ``` +删除命令先返回只读 `preview`:`revision` 绑定模板内容、当前全局选择及全部引用。预览包含 `globalDefaultBefore`、`globalDefaultAfter`、`globalDefaultAvailable`、可见 `affectedBots`(`slug` 和 `source`),以及身份不可见引用的 `hiddenBotCount`。加 `--confirm --delete-revision` 才删除;未确认不删除、不改选择。模板内容、引用或全局策略已变时返回 `approval-template-delete-changed`,须重新预览。 + +确认后,特定引用统一改为 `@global`;删除全局默认会清空默认,原继承者保持继承并关闭 Reviewer。全局仍选另一模板时会使用它;默认不可读时仍显示不可用,未解决调用交给 Human。其他特定选择、关闭、Full Access 及已保存确定性规则不变;已开始的 Review 保留当次版本。结果含 `inheritedBots` 和 `globalDefault`;兼容字段 `clearedBots` 表示已移除特定选择的可见引用。删除失败返回 `approval-template-delete-unavailable`;若恢复选择也失败则为 `approval-template-delete-incomplete`,重试前先读取当前状态。自定义模板内容不可读或超限时,仍可显式删除:预览返回 `contentUnavailable: true`。此时确认版本绑定有界的文件系统身份(设备/inode、大小及时间戳),不对不可读正文做完整哈希;正常模板仍绑定正文。文件身份变化或修复内容后必须重新预览。不可读文件不在模板列表中;恢复时使用已知名称运行 CLI 预览/删除命令。全局选择读取失败仍拒绝删除。 + `off`、`inherit` 仍可作为自定义模板名。选择时加 `--literal-template` 即按字面名称选中;不加时继续保留原有关闭和继承别名。 `list` 返回 `templates` 和 `globalDefault`(模板名或 `null`)。加 `--bot` 时还返回 `selected`(`@global`、特定模板名或 `null`)、`source`(`global`、`specific`、`off`)及 `effective`(模板名或 `null`)。全局设置返回 `{template}`,Bot 设置返回 `{bot}`。写入由认证 Host 持有;不存在的模板不能被选中,全局选择读取失败返回 `approval-selection-unavailable`,不冒充空默认。 -模板继续使用内置只读内容或 `$DSH_HOME/botharness/approval-templates/` 下的 Markdown 文件;同一文件 owner 在 `.selection.json` 保存全局选择,不新增 schema 迁移。名称使用小写字母、数字和短横线,正文最多 32 KiB。`show` 返回全文;`create --from` 复制内容。编辑器提供 Always ask、Always allow 与 free text,可显式从空白或副本开始,并选择仅保存或保存后应用。详见[三部分模板编写](#三部分审批指导)。统一规则表和确认后的批量删除回退由后续切片交付。 +模板继续使用内置只读内容或 `$DSH_HOME/botharness/approval-templates/` 下的 Markdown 文件;同一文件 owner 在 `.selection.json` 保存全局选择,不新增 schema 迁移。名称使用小写字母、数字和短横线,正文最多 32 KiB。`show` 返回全文;`create --from` 复制内容。编辑器提供 Always ask、Always allow 与 free text,可显式从空白或副本开始,并选择仅保存或保存后应用。详见[三部分模板编写](#三部分审批指导)。 确定性授权先处理,覆盖请求时不调用 Reviewer。其余请求按所选模板进入全新、无工具的 Reviewer Session,只接受本次 `allow` 或 `ask-human`。Always ask 优先于 Always allow,free text 补充两者;旧模板的 Reject 指引表示交给 Human。模型不存规则、不自主拒绝,拒绝熔断不再生效。旧拒绝记录及显式 Human override 保持可读。 @@ -2107,6 +2114,24 @@ Bot 默认私有:只有主体(所有者)可以私聊私有 Bot 或把它 编辑共享原件影响 `usedBy` 中所有 Bot 的后续 Review,包括全局继承者。需要独立修改时先复制。总是询问优先于总是允许,补充说明不能取消前者。这些是可能被模型误解的自然语言指导,不是确定性 Tool Approval Rules;冲突、未覆盖或不确定均交给 Human。转换时旧 Markdown 完整保留为补充说明,已经开始的 Review 保留捕获的内容和版本。 +可信声明的不可撤销外部工具调用在 Full Access 下仍进入统一审批。`bot-tool` 无需模型,沿用同一 Host 准入;有效确定性授权先于 Reviewer。在线 `channel-messages` 的审批消息包含 `toolApprovalRequest.effects` 与中英文 `effectLabels.en` / `effectLabels.zh`。工具输入或结果声称用户已批准不会构成授权。管理操作仍需 ADR-0249 的专用显式授权。 + +### 命令效果与调用方授权 + +CLI 与 Tob broker 共用应用定义的命令效果声明;lint 从真实命令注册数组与入口分发检查声明遗漏,不依赖搜索索引。声明不是授权:直接在线命令仍由认证 Host owner 校验;broker 仍保留 Human DM 来源、目标所有权、准确 argv 和 stdin 哈希、确认标志、revision、取消与执行前撤销检查。未知命令保留未声明来源,broker 仍按需审批,CLI 仍返回原有拒绝。混合用途命令保留保守声明及原有审批门槛;未迁移的 Shell 文本识别继续生效。 + +效果解析复用 CLI 的严格参数解析;`channels send` 与成员设备撤销不会沿用同名读取命令的 broker 直通。`bots` 别名按实际动作解析。任意工具调用及通用 `settings-set` 的 stdin 不在审批提案中公开,故效果保持不透明;stdin 哈希只用于操作身份,不能当成授权或可信效果。 + +## 无模型的 Tob CLI 请求 + +已认证的 Host Owner 可将 `{"argv":["approval-templates"],"stdin":""}` 保存为本机私有 JSON 文件,用 `deepseekbot tob-cli start --args-stdin < request.json` 启动;用 `tob-cli status ` 读取状态和结果,或 `tob-cli cancel ` 请求取消。 + +Host 通过 ChannelStore 写入真实 Human DM,再由既有 Source Event/Admission 接纳,在同一存活的 Tob 根 Orchestrator 中,通过 DSH 原生工具执行器调用 `deepseekbot_cli` 和既有 broker;不请求模型。调用方不能指定 actor、Source Event、Session、cwd 或权限覆盖。写入仍显示真实审批卡,可使用既有 `tool-approval-status`、`tool-approval-decide` 或 Tob DM 中的审批操作。 + +启动返回 `{id,channelId,messageId,state,cancelRequested}`。结束状态为 `completed`(含 `result:{exitCode,stdout,stderr}`),或带错误码的 `failed` / `cancelled`。`completed` 仅表示调用已结束,仍须检查 exitCode 和 JSON stdout 中的命令拒绝。取消须等待结束,不能撤销已提交的效果。模型回合、直接工具或另一请求正在运行时返回 `bot-busy`;权限不可用返回 `tob-authority-required`,运行时关闭返回 `runtime-closed`,请求不存在或过期返回 `cli-request-unavailable`。 + +最多保留十六条结束结果,结束十分钟后过期,Host 重启即失效;执行期限十分钟。输入最多 256 个 argv、总计 64 KiB,stdin 一 MiB;合并输出一 MiB。stdin 不写入 DM。不要共享私有输入文件。结果不确定时先读取命令 owner 的规范状态,不自动重放历史消息。此路径不增加审批存储或数据库迁移。见 [ADR-0347](adr/0347-model-free-tob-cli-uses-the-accepted-human-dm-turn.md)。 + ### Channel 邀请(M14) ```sh diff --git a/packages/client/src/client/approval-template-library.tsx b/packages/client/src/client/approval-template-library.tsx index 0c033f0b7a..aa7ee01a7d 100644 --- a/packages/client/src/client/approval-template-library.tsx +++ b/packages/client/src/client/approval-template-library.tsx @@ -3,17 +3,20 @@ import { encodeApprovalTemplateGuidance, type ApprovalTemplateGuidance, } from '../../../core/src/workspaces/approval-template-guidance.js'; +import type { ApprovalTemplateDeletionPreview } from '../../../core/src/workspaces/approval-template-deletion-contract.js'; import { useClientFields, useStoreSlice } from './use-client-store.js'; -import { useState, type ReactElement } from 'react'; +import { useRef, useState, type ReactElement } from 'react'; import { Button, Input, Tag } from '@deepseek-ai/dsh-client-ui-primitives'; import * as stylex from '@stylexjs/stylex'; import { templateDescription, templateTitle } from './approval-template-entry.js'; import { + BridgeCallError, createApprovalTemplate, deleteApprovalTemplate, errorMessage, loadApprovalTemplates, + previewApprovalTemplateDeletion, setGlobalApprovalTemplate, setBotApprovalTemplate, updateApprovalTemplate, @@ -71,10 +74,15 @@ type Editor = | { mode: 'edit'; template: ApprovalTemplateView; text: string }; function botNames(store: ClientStore, slugs: readonly string[]): string { - const bots = store.getSnapshot().bots; - return slugs.map((slug) => bots.find((bot) => bot.slug === slug)?.displayName ?? slug).join(', '); + const names = new Map(store.getSnapshot().bots.map((bot) => [bot.slug, bot.displayName])); + return slugs.map((slug) => names.get(slug) ?? slug).join(', '); } +type Deleting = { template: ApprovalTemplateView } & ( + | { kind: 'loading' | 'failed' } + | { kind: 'ready'; preview: ApprovalTemplateDeletionPreview } +); + function copyName(name: string, taken: readonly ApprovalTemplateView[]): string { const base = (name + '-copy').slice(0, 58); let candidate = base; @@ -183,7 +191,9 @@ export function ApprovalTemplateLibrarySettings({ const [templates, setTemplates] = useState(); const [loadError, setLoadError] = useState(); const [editor, setEditor] = useState(); - const [deleting, setDeleting] = useState(); + const [deleting, setDeleting] = useState(); + const deletionGeneration = useRef(0); + const reloadGeneration = useRef(0); const [applyTo, setApplyTo] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(); @@ -191,27 +201,37 @@ export function ApprovalTemplateLibrarySettings({ const currentBotSlug = useStoreSlice(store, currentTemplateBot); const currentBot = bots.find((bot) => bot.slug === currentBotSlug); - const reload = async (): Promise => { - const next = await loadApprovalTemplates(call); + const reload = async () => { + const generation = ++reloadGeneration.current; + const result = await loadApprovalTemplates(call).then( + (value) => ({ kind: 'loaded' as const, value }), + (cause: unknown) => ({ kind: 'failed' as const, cause }), + ); + if (generation !== reloadGeneration.current) return { kind: 'superseded' as const, result }; + if (result.kind === 'failed') throw result.cause; + const next = result.value; setTemplates(next.templates); setGlobalDefault(next.globalDefault ?? null); setGlobalError(false); setLoadError(undefined); + setEditor((current) => + current !== undefined && + (current.mode === 'view' || current.mode === 'edit') && + !next.templates.some((template) => template.name === current.template.name) + ? undefined + : current, + ); + return result; }; const mount = useMountedResource(() => { let live = true; - loadApprovalTemplates(call) - .then((next) => { - if (live) { - setTemplates(next.templates); - setGlobalDefault(next.globalDefault ?? null); - } - }) - .catch((cause: unknown) => { - if (live) setLoadError(errorMessage(cause)); - }); + void reload().catch((cause: unknown) => { + if (live) setLoadError(errorMessage(cause)); + }); return () => { live = false; + reloadGeneration.current++; + deletionGeneration.current++; }; }, [call]); @@ -233,10 +253,15 @@ export function ApprovalTemplateLibrarySettings({ .finally(() => setBusy(false)); }; + const cancelDeletion = (): void => { + deletionGeneration.current++; + setDeleting(undefined); + setError(undefined); + }; const close = (): void => { setEditor(undefined); setApplyTo(''); - setDeleting(undefined); + cancelDeletion(); setError(undefined); }; const createDraft = (draft: Extract): void => { @@ -267,6 +292,113 @@ export function ApprovalTemplateLibrarySettings({ .finally(() => setBusy(false)); }; + const beginDeletion = (template: ApprovalTemplateView, notice?: string): void => { + const generation = ++deletionGeneration.current; + setError(notice); + setDeleting({ template, kind: 'loading' }); + void previewApprovalTemplateDeletion(call, template.name).then( + (preview) => { + if (deletionGeneration.current === generation) + setDeleting({ template, kind: 'ready', preview }); + }, + async (cause: unknown) => { + if (deletionGeneration.current !== generation) return; + if (cause instanceof BridgeCallError && cause.code === 'unknown-template') { + try { + const next = await reload(); + if (deletionGeneration.current === generation) { + if (next.kind === 'loaded') cancelDeletion(); + else { + setDeleting({ template, kind: 'failed' }); + setError(t('autoApproval.library.deletePreviewFailed')); + } + } + } catch (readCause: unknown) { + if (deletionGeneration.current !== generation) return; + setTemplates(undefined); + setGlobalDefault(undefined); + setGlobalError(true); + setLoadError(errorMessage(readCause)); + setEditor(undefined); + setDeleting({ template, kind: 'failed' }); + setError(t('autoApproval.library.deletePreviewFailed')); + } + return; + } + setDeleting({ template, kind: 'failed' }); + setError(t('autoApproval.library.deletePreviewFailed')); + }, + ); + }; + const reconcileDeletion = async (name: string, generation: number): Promise => { + try { + const next = await reload(); + if (next.kind === 'superseded') return; + if ( + deletionGeneration.current === generation && + !next.value.templates.some((template) => template.name === name) + ) { + try { + await previewApprovalTemplateDeletion(call, name); + } catch (cause: unknown) { + if ( + deletionGeneration.current === generation && + cause instanceof BridgeCallError && + cause.code === 'unknown-template' + ) + cancelDeletion(); + } + } + } catch { + setGlobalDefault(undefined); + setGlobalError(true); + } + }; + const recoverDeletion = (template: ApprovalTemplateView): void => { + if (busy) return; + const generation = deletionGeneration.current; + setBusy(true); + void reload() + .then((next) => { + if (next.kind === 'loaded' && deletionGeneration.current === generation) + beginDeletion(template); + }) + .catch(() => { + setGlobalDefault(undefined); + setGlobalError(true); + }) + .finally(() => setBusy(false)); + }; + const confirmDeletion = (): void => { + if (busy || deleting?.kind !== 'ready') return; + const selected = deleting; + const generation = deletionGeneration.current; + setBusy(true); + setError(undefined); + void deleteApprovalTemplate(call, selected.preview) + .then(async () => { + setTemplates((current) => + current?.filter((template) => template.name !== selected.preview.name), + ); + if (deletionGeneration.current === generation) close(); + await reconcileDeletion(selected.preview.name, generation); + }) + .catch(async (cause: unknown) => { + if (deletionGeneration.current === generation) { + if (cause instanceof BridgeCallError && cause.code === 'approval-template-delete-changed') + beginDeletion(selected.template, t('autoApproval.library.deleteChanged')); + else { + setDeleting({ template: selected.template, kind: 'failed' }); + setError(t('autoApproval.library.deleteUnconfirmed')); + } + } + setGlobalDefault(undefined); + setGlobalError(true); + await reconcileDeletion(selected.preview.name, generation); + }) + .finally(() => setBusy(false)); + }; + const labels = { close: t('common.close'), cancel: t('common.cancel') }; const list = templates ?? []; const usedBy = (template: ApprovalTemplateView): string | undefined => @@ -274,23 +406,81 @@ export function ApprovalTemplateLibrarySettings({ const dialog = (() => { if (deleting !== undefined) { - const names = usedBy(deleting); + const preview = deleting.kind === 'ready' ? deleting.preview : undefined; + const direct = + preview?.affectedBots.filter((bot) => bot.source === 'specific').map((bot) => bot.slug) ?? + []; + const inherited = + preview?.affectedBots.filter((bot) => bot.source === 'global').map((bot) => bot.slug) ?? []; + const after = preview?.globalDefaultAfter; + const effective = + after === null + ? t('autoApproval.off') + : after === undefined + ? '' + : preview?.globalDefaultAvailable + ? templateTitle(t, after, list.find((template) => template.name === after)?.title) + : t('autoApproval.templateMissing', { name: after }); return ( setDeleting(undefined)} - onConfirm={() => run(() => deleteApprovalTemplate(call, deleting.name))} + onCancel={cancelDeletion} + onConfirm={confirmDeletion} > - {t('autoApproval.library.deleteBody', { name: deleting.name })} - {names === undefined ? null : ( - {t('autoApproval.library.deleteInUse', { names })} + {t('autoApproval.library.deleteBody', { name: deleting.template.name })} + {deleting.kind === 'loading' ? {t('autoApproval.loading')} : null} + {preview === undefined ? null : ( + <> + {preview.contentUnavailable ? ( + + {t('autoApproval.library.deleteContentUnavailable')} + + ) : null} + {direct.length === 0 ? null : ( + + {t('autoApproval.library.deleteDirect', { names: botNames(store, direct) })} + + )} + {inherited.length === 0 ? null : ( + + {t('autoApproval.library.deleteInherited', { names: botNames(store, inherited) })} + + )} + {preview.globalDefaultBefore === preview.name ? ( + {t('autoApproval.library.deleteClearsGlobal')} + ) : null} + {preview.hiddenBotCount > 0 ? ( + + {t('autoApproval.library.deleteHidden', { + count: String(preview.hiddenBotCount), + })} + + ) : null} + {preview.affectedBots.length === 0 && preview.hiddenBotCount === 0 ? ( + {t('autoApproval.library.deleteUnused')} + ) : ( + {t('autoApproval.library.deleteEffective', { template: effective })} + )} + {t('autoApproval.library.deleteRulesUnchanged')} + )} + {deleting.kind === 'failed' ? ( + + ) : null} ); } @@ -479,7 +669,7 @@ export function ApprovalTemplateLibrarySettings({ disabled={busy} onClick={() => { setError(undefined); - setDeleting(template); + beginDeletion(template); }} > {t('autoApproval.library.delete')} diff --git a/packages/client/src/client/bridge.ts b/packages/client/src/client/bridge.ts index 416aa2c1d7..d30bd0df6f 100644 --- a/packages/client/src/client/bridge.ts +++ b/packages/client/src/client/bridge.ts @@ -1,3 +1,9 @@ +import { parseToolEffects } from '../../../core/src/workspaces/tool-effects-contract.js'; +import { + approvalTemplateDeletionPreviewSchema, + type ApprovalTemplateDeletionPreview, +} from '../../../core/src/workspaces/approval-template-deletion-contract.js'; + import { skillCatalogChangeSchema, type SkillCatalogChange, @@ -1390,6 +1396,7 @@ export function parseChannelMessage(value: unknown): ChannelMessage | undefined : {}), } : undefined; + const effects = parseToolEffects(request['effects']); const review = asRecord(request['approvalReview']); let approvalReview: | import('../../../core/src/workspaces/tool-approval.js').ToolApprovalReview @@ -1410,6 +1417,7 @@ export function parseChannelMessage(value: unknown): ChannelMessage | undefined ...(typeof review['fallback'] === 'string' ? { fallback: review['fallback'] } : {}), }; toolApprovalRequest = { + ...(effects === undefined ? {} : { effects }), ...(approvalReview === undefined ? {} : { approvalReview }), ...(typeof request['allowAlways'] === 'boolean' ? { allowAlways: request['allowAlways'] } @@ -4638,14 +4646,29 @@ export function updateApprovalTemplate( ): Promise { return writtenApprovalTemplate(call, 'approvalTemplateUpdate', { name, text }); } -export async function deleteApprovalTemplate( +export async function previewApprovalTemplateDeletion( call: BridgeCall, name: string, -): Promise<{ clearedBots: string[] }> { - const response = asRecord(await unwrap(call, 'approvalTemplateDelete', { name })); - if (!Array.isArray(response?.['clearedBots'])) +): Promise { + const response = asRecord(await unwrap(call, 'approvalTemplateDeletePreview', { name })); + const preview = approvalTemplateDeletionPreviewSchema.parse(response?.['preview']); + if (preview.name !== name) throw new Error('invalid approval template deletion target'); + return preview; +} +export async function deleteApprovalTemplate( + call: BridgeCall, + preview: ApprovalTemplateDeletionPreview, +): Promise<{ inheritedBots: string[] }> { + const response = asRecord( + await unwrap(call, 'approvalTemplateDelete', { + name: preview.name, + confirmed: true, + revision: preview.revision, + }), + ); + if (!Array.isArray(response?.['inheritedBots'])) throw new Error('invalid approvalTemplateDelete response'); - return { clearedBots: stringArray(response['clearedBots']) }; + return { inheritedBots: stringArray(response['inheritedBots']) }; } export async function setBotApprovalTemplate( call: BridgeCall, diff --git a/packages/client/src/client/ds/form-dialog.tsx b/packages/client/src/client/ds/form-dialog.tsx index 3eb08da994..de9414c0b6 100644 --- a/packages/client/src/client/ds/form-dialog.tsx +++ b/packages/client/src/client/ds/form-dialog.tsx @@ -181,6 +181,8 @@ export function ConfirmDialog({ onCancel, onConfirm, busy = false, + confirmDisabled = false, + scroll = false, danger = true, error, children, @@ -192,6 +194,8 @@ export function ConfirmDialog({ readonly onCancel: () => void; readonly onConfirm: () => void; readonly busy?: boolean; + readonly confirmDisabled?: boolean; + readonly scroll?: boolean; readonly danger?: boolean; readonly error?: ReactNode; readonly children?: ReactNode; @@ -205,6 +209,8 @@ export function ConfirmDialog({ onCancel={onCancel} onSubmit={onConfirm} busy={busy} + submitDisabled={confirmDisabled} + scroll={scroll} danger={danger} error={error} > diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index 959237bfda..a94d71d8d9 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -4,6 +4,14 @@ import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'; export const LOCALE_NS = 'botharness'; export const zh = { + 'approval.effect.changes.none': '只读', + 'approval.effect.changes.reversible': '可撤销更改', + 'approval.effect.changes.irreversible': '不可撤销', + 'approval.effect.reach.local': '本机', + 'approval.effect.reach.memory': '记忆', + 'approval.effect.reach.workspace': '工作区', + 'approval.effect.reach.external': '外部影响', + 'environment.title': '环境', 'environment.create.target': '创建到环境', 'environment.create.choose': '选择环境', @@ -4400,7 +4408,10 @@ export const zh = { 'approval.confirmAll': '确认始终允许', 'approval.cancel': '取消', 'approval.ruleSaved': '已允许本次,并保存你的选择', - 'approval.rulesTitle': '自动批准规则', + 'approval.rulesTitle': '始终允许 · 此 Bot', + 'approval.ruleFromCard': '来自审批卡', + 'approval.rulesHint': + '已保存的确定性授权,命中时不调用审批员。模板文字仅指导审批员;撤销规则后重新审核。', 'approval.ruleScope': '规则范围:执行角色、目录及 Grant ID/写入版本', 'approval.ruleActive': '有效', 'approval.ruleInactive': '已停用', @@ -4486,7 +4497,18 @@ export const zh = { 'autoApproval.library.readOnly': '内置模板只读。复制一份后可以随意修改。', 'autoApproval.library.inUse': '{names} 正在使用这个共享模板。保存仅影响后续审批。', 'autoApproval.library.deleteTitle': '删除“{title}”?', - 'autoApproval.library.deleteBody': '会删除 approval-templates/{name}.md。', + 'autoApproval.library.deleteBody': '将永久删除模板“{name}”。', + 'autoApproval.library.deleteContentUnavailable': '无法读取模板内容。确认后仍会删除此文件。', + 'autoApproval.library.deletePreviewFailed': '删除影响读取失败。重新读取后再确认。', + 'autoApproval.library.deleteChanged': '引用或全局选择已变化。核对最新结果后再确认。', + 'autoApproval.library.deleteUnconfirmed': '删除结果尚未确认。重新读取当前状态后再决定。', + 'autoApproval.library.deleteDirect': '这些 Bot 将改为继承全局:{names}', + 'autoApproval.library.deleteInherited': '这些 Bot 保持继承全局:{names}', + 'autoApproval.library.deleteClearsGlobal': '全局默认将清空。', + 'autoApproval.library.deleteUnused': '没有 Bot 引用此模板。', + 'autoApproval.library.deleteHidden': '另外 {count} 个私有 Bot 也受影响。', + 'autoApproval.library.deleteEffective': '删除后,受影响 Bot 的自动审核:{template}', + 'autoApproval.library.deleteRulesUnchanged': '已保存授权和完全访问不变。', 'autoApproval.library.deleteInUse': '{names} 正在使用它。删除后这些 Bot 的自动审批会关闭,工具审批改回由你在卡片上批准。', 'access.section': '权限', @@ -5815,6 +5837,14 @@ export function zhTranslate(key: BotHarnessKey | string, params?: Record )} + {request.effects === undefined ? null : ( +
+ {t(`approval.effect.changes.${request.effects.changes}`)} ·{' '} + {t(`approval.effect.reach.${request.effects.reach}`)} +
+ )} {request.approvalReview === undefined ? null : (
{request.approvalReview.kind === 'template-unavailable' diff --git a/packages/client/src/client/workspace-grants-entry.tsx b/packages/client/src/client/workspace-grants-entry.tsx index 763597fe8c..c8a97c7d75 100644 --- a/packages/client/src/client/workspace-grants-entry.tsx +++ b/packages/client/src/client/workspace-grants-entry.tsx @@ -142,7 +142,16 @@ function secretCliRuleLabel(input: string): { program: string; account: string } function approvalRulePath(rule: ToolApprovalRuleView): string { try { - const scope = JSON.parse(rule.scopeKey) as unknown; + let scope: unknown = JSON.parse(rule.scopeKey); + if ( + Array.isArray(scope) && + typeof scope[0] === 'string' && + ((scope.length === 2 && scope[1] === 'explicit-approval') || + (scope.length === 3 && + (scope[1] === 'browser' || scope[1] === 'computer' || scope[1] === null) && + typeof scope[2] === 'string')) + ) + scope = JSON.parse(scope[0]); if (Array.isArray(scope) && typeof scope[1] === 'string') return scope[1]; } catch {} return rule.scopeKey; @@ -1449,14 +1458,28 @@ export function WorkspaceGrantsEntry({ /> ) : null} - {composerOnly || rules.length === 0 ? null : ( + {rules.length === 0 ? null : (
{t('approval.rulesTitle')} +
+ {t('approval.ruleDetails')} +
{t('approval.rulesHint')}
+
+
{rules.map((rule) => ( -
+
+ {t('approval.ruleFromCard')} + {' · '} {rule.kind === 'tool' ? t('approval.toolRule', { tool: rule.toolName }) : rule.kind === 'exact' @@ -1474,7 +1497,7 @@ export function WorkspaceGrantsEntry({
+
{t('approval.cwd', { path: approvalRulePath(rule) })}
{t('approval.ruleDetails')} -
- {t('approval.cwd', { path: approvalRulePath(rule) })} -
{t('approval.ruleScope')}
{rule.scopeKey}
{rule.externalCreator ? ( diff --git a/packages/client/test/approval-template-library.test.ts b/packages/client/test/approval-template-library.test.ts index 7a6804209d..fe7142d4f2 100644 --- a/packages/client/test/approval-template-library.test.ts +++ b/packages/client/test/approval-template-library.test.ts @@ -131,6 +131,299 @@ it('keeps a missing global template recognizable without silently clearing its n expect(trigger().textContent).toContain('不可用'); }); +const customTemplate = { + name: 'night-shift', + title: 'Night shift', + description: '', + builtIn: false, + usedBy: ['ada'], + text: '# Night shift\n\nAsk before sending.\n', +}; +const deletePreview = { + name: 'night-shift', + revision: 'a'.repeat(64), + globalDefaultBefore: 'cautious', + globalDefaultAfter: 'cautious', + globalDefaultAvailable: true, + hiddenBotCount: 0, + affectedBots: [{ slug: 'ada', source: 'specific' }], +}; +async function openDeletion(call: BridgeCall): Promise { + await render(call); + const edit = host.querySelector( + '[data-approval-template="night-shift"] button', + ); + if (!edit) throw new Error('Missing custom template'); + await act(async () => edit.click()); + const remove = [...document.querySelectorAll('button')].find( + (button) => button.textContent === t('autoApproval.library.delete'), + ); + if (!remove) throw new Error('Missing delete action'); + await act(async () => remove.click()); +} +function confirmDeletion(): HTMLButtonElement { + const button = document.querySelector('button[type="submit"]'); + if (!button) throw new Error('Missing confirmation'); + return button; +} + +it('discloses global and direct references before enabling explicit deletion confirmation', async () => { + const pending: { + resolve?: (value: Awaited>) => void; + promise?: Promise>>; + } = {}; + pending.promise = new Promise((resolve) => { + pending.resolve = resolve; + }); + const writes: Record[] = []; + let deleted = false; + const call: BridgeCall = async (endpoint, payload) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { + templates: [...templates, ...(deleted ? [] : [customTemplate])], + globalDefault: deleted ? null : 'night-shift', + }, + }; + if (endpoint === 'approvalTemplateDeletePreview') { + if (!pending.promise) throw new Error('Missing deferred read'); + return pending.promise; + } + if (endpoint === 'approvalTemplateDelete') { + writes.push(payload); + deleted = true; + return { ok: true, value: { inheritedBots: ['ada'] } }; + } + throw new Error('Unexpected endpoint ' + endpoint); + }; + await openDeletion(call); + expect(confirmDeletion().disabled).toBe(true); + expect(writes).toEqual([]); + const resolvePreview = pending.resolve; + if (!resolvePreview) throw new Error('Missing preview resolver'); + await act(async () => + resolvePreview({ + ok: true, + value: { + preview: { + ...deletePreview, + globalDefaultBefore: 'night-shift', + globalDefaultAfter: null, + globalDefaultAvailable: false, + affectedBots: [ + { slug: 'ada', source: 'specific' }, + { slug: 'bob', source: 'global' }, + ], + }, + }, + }), + ); + expect(document.body.textContent).toContain('ada'); + expect(document.body.textContent).toContain('bob'); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteClearsGlobal')); + expect(document.body.textContent).toContain( + t('autoApproval.library.deleteEffective', { template: t('autoApproval.off') }), + ); + expect(confirmDeletion().disabled).toBe(false); + await act(async () => confirmDeletion().click()); + expect(writes).toEqual([{ name: 'night-shift', confirmed: true, revision: 'a'.repeat(64) }]); + expect(host.querySelector('[data-approval-template="night-shift"]')).toBeNull(); +}); + +it('refreshes changed impact and requires a second confirmation instead of replaying deletion', async () => { + let previews = 0; + const writes: Record[] = []; + const call: BridgeCall = async (endpoint, payload) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { templates: [...templates, customTemplate], globalDefault: 'cautious' }, + }; + if (endpoint === 'approvalTemplateDeletePreview') { + previews++; + return { + ok: true, + value: { + preview: + previews === 1 + ? deletePreview + : { ...deletePreview, revision: 'b'.repeat(64), globalDefaultAfter: 'get-work-done' }, + }, + }; + } + if (endpoint === 'approvalTemplateDelete') { + writes.push(payload); + return writes.length === 1 + ? { + ok: false, + error: { code: 'approval-template-delete-changed', message: 'changed', details: {} }, + } + : { ok: true, value: { inheritedBots: ['ada'] } }; + } + throw new Error('Unexpected endpoint ' + endpoint); + }; + await openDeletion(call); + await act(async () => confirmDeletion().click()); + expect(writes).toHaveLength(1); + expect(previews).toBe(2); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteChanged')); + expect(document.body.textContent).toContain(t('autoApproval.template.getWorkDone')); + await act(async () => confirmDeletion().click()); + expect(writes[1]).toEqual({ name: 'night-shift', confirmed: true, revision: 'b'.repeat(64) }); +}); + +it('uses read-only recovery after an unconfirmed deletion result', async () => { + let previews = 0; + let writes = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { templates: [...templates, customTemplate], globalDefault: 'cautious' }, + }; + if (endpoint === 'approvalTemplateDeletePreview') { + previews++; + return { ok: true, value: { preview: deletePreview } }; + } + if (endpoint === 'approvalTemplateDelete') { + writes++; + throw new Error('Response unavailable'); + } + throw new Error('Unexpected endpoint ' + endpoint); + }; + await openDeletion(call); + await act(async () => confirmDeletion().click()); + expect(writes).toBe(1); + expect(confirmDeletion().disabled).toBe(true); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteUnconfirmed')); + const reload = [...document.querySelectorAll('button')].find( + (button) => button.textContent === t('autoApproval.reload'), + ); + if (!reload) throw new Error('Missing read-only recovery'); + await act(async () => reload.click()); + expect(previews).toBe(2); + expect(writes).toBe(1); +}); + +it.each(['invalid', 'wrong-target'])( + 'keeps confirmation disabled for %s preview data', + async (kind) => { + let writes = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { templates: [...templates, customTemplate], globalDefault: 'cautious' }, + }; + if (endpoint === 'approvalTemplateDeletePreview') + return { + ok: true, + value: { preview: kind === 'invalid' ? {} : { ...deletePreview, name: 'other' } }, + }; + writes++; + throw new Error('Unexpected mutation'); + }; + await openDeletion(call); + expect(confirmDeletion().disabled).toBe(true); + expect(document.body.textContent).toContain(t('autoApproval.library.deletePreviewFailed')); + expect(writes).toBe(0); + }, +); + +it.each(['immediate', 'retry'] as const)( + 'converges canonical deletion after a lost response with %s readback', + async (recovery) => { + let deleted = false; + let writes = 0; + let reads = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') { + reads++; + if (recovery === 'retry' && reads === 2) throw new Error('Read unavailable'); + return { + ok: true, + value: { + templates: [...templates, ...(deleted ? [] : [customTemplate])], + globalDefault: deleted ? null : 'night-shift', + }, + }; + } + if (endpoint === 'approvalTemplateDeletePreview') + return deleted + ? { ok: false, error: { code: 'unknown-template', message: 'removed', details: {} } } + : { ok: true, value: { preview: deletePreview } }; + if (endpoint === 'approvalTemplateDelete') { + writes++; + deleted = true; + throw new Error('Response lost after commit'); + } + throw new Error('Unexpected ' + endpoint); + }; + await openDeletion(call); + await act(async () => confirmDeletion().click()); + expect(writes).toBe(1); + if (recovery === 'retry') { + expect(trigger().textContent).toContain('读取失败'); + const retry = [...document.querySelectorAll('button')].find( + (b) => b.textContent === t('autoApproval.reload'), + ); + if (!retry) throw new Error('Missing read recovery'); + await act(async () => retry.click()); + } + expect(host.querySelector('[data-approval-template="night-shift"]')).toBeNull(); + expect(trigger().textContent).toContain(t('autoApproval.off')); + expect(writes).toBe(1); + }, +); + +it('reads canonical deletion after the confirmation dialog closes during the write', async () => { + let deleted = false; + let reads = 0; + let writes = 0; + let finish: ((value: Awaited>) => void) | undefined; + const pending = new Promise>>((resolve) => { + finish = resolve; + }); + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') { + reads++; + return { + ok: true, + value: { + templates: [...templates, ...(deleted ? [] : [customTemplate])], + globalDefault: deleted ? null : 'night-shift', + }, + }; + } + if (endpoint === 'approvalTemplateDeletePreview') + return { ok: true, value: { preview: deletePreview } }; + if (endpoint === 'approvalTemplateDelete') { + writes++; + return pending; + } + throw new Error('Unexpected ' + endpoint); + }; + await openDeletion(call); + await act(async () => confirmDeletion().click()); + const dialog = document.querySelector('[role="dialog"]'); + if (!dialog) throw new Error('Missing dialog'); + const dismiss = dialog.querySelector( + 'button[aria-label="' + t('common.close') + '"]', + ); + if (!dismiss) throw new Error('Missing close button'); + await act(async () => dismiss.click()); + expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-label')).not.toContain( + t('autoApproval.library.deleteTitle', { title: 'Night shift' }), + ); + deleted = true; + await act(async () => finish?.({ ok: true, value: { inheritedBots: ['ada'] } })); + expect(reads).toBe(2); + expect(writes).toBe(1); + expect(host.querySelector('[data-approval-template="night-shift"]')).toBeNull(); + expect(trigger().textContent).toContain(t('autoApproval.off')); +}); + async function clickText(label: string): Promise { const button = [...document.querySelectorAll('button')].find( (item) => item.textContent === label, @@ -442,6 +735,33 @@ it('keeps a custom template named off separate from the Off option', async () => expect(writes).toEqual([{ template: 'off' }, { template: null }]); }); +it('warns when deletion targets unreadable content and still requires explicit confirmation', async () => { + const writes: unknown[] = []; + const call: BridgeCall = async (endpoint, payload) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { + templates: [...templates, customTemplate], + globalDefault: 'cautious', + }, + }; + if (endpoint === 'approvalTemplateDeletePreview') + return { ok: true, value: { preview: { ...deletePreview, contentUnavailable: true } } }; + if (endpoint === 'approvalTemplateDelete') { + writes.push(payload); + return { ok: true, value: {} }; + } + throw new Error('Unexpected endpoint ' + endpoint); + }; + await openDeletion(call); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteContentUnavailable')); + expect(writes).toEqual([]); + expect(confirmDeletion().disabled).toBe(false); + await act(async () => confirmDeletion().click()); + expect(writes).toHaveLength(1); +}); + it.each([ { creation: false, readFails: false }, { creation: false, readFails: true }, @@ -574,3 +894,166 @@ it.each([ expect(selections).toBe(2); }, ); + +it('retains an unreadable template deletion failure when the readable list omits its file', async () => { + let omitted = false; + let writes = 0; + let previews = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') + return { + ok: true, + value: { + templates: [...templates, ...(omitted ? [] : [customTemplate])], + globalDefault: 'cautious', + }, + }; + if (endpoint === 'approvalTemplateDeletePreview') { + previews++; + return { ok: true, value: { preview: { ...deletePreview, contentUnavailable: omitted } } }; + } + if (endpoint === 'approvalTemplateDelete') { + writes++; + omitted = true; + return { + ok: false, + error: { + code: 'approval-template-delete-unavailable', + message: 'File still exists', + details: {}, + }, + }; + } + throw new Error('Unexpected ' + endpoint); + }; + await openDeletion(call); + await act(async () => confirmDeletion().click()); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteUnconfirmed')); + expect(confirmDeletion().disabled).toBe(true); + expect(previews).toBe(2); + const reload = [...document.querySelectorAll('button')].find( + (button) => button.textContent === t('autoApproval.reload'), + ); + if (!reload) throw new Error('Missing recovery'); + await act(async () => reload.click()); + expect(document.body.textContent).toContain(t('autoApproval.library.deleteContentUnavailable')); + expect(confirmDeletion().disabled).toBe(false); + expect(previews).toBe(3); + expect(writes).toBe(1); +}); + +it.each([false, true])( + 'refreshes canonical state after a concurrent deletion (read fails: %s)', + async (readFails) => { + let reads = 0; + let writes = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') { + reads++; + if (readFails && reads === 2) throw new Error('Canonical read failed'); + return { + ok: true, + value: { + templates: [...templates, ...(reads === 1 ? [customTemplate] : [])], + globalDefault: reads === 1 ? 'night-shift' : null, + }, + }; + } + if (endpoint === 'approvalTemplateDeletePreview') + return { + ok: false, + error: { code: 'unknown-template', message: 'Removed by another client', details: {} }, + }; + writes++; + throw new Error('No mutation expected'); + }; + await openDeletion(call); + if (readFails) { + expect(document.body.textContent).toContain(t('autoApproval.library.deletePreviewFailed')); + expect(confirmDeletion().disabled).toBe(true); + const dialog = confirmDeletion().closest('[role="dialog"]'); + if (!dialog) throw new Error('Missing deletion dialog'); + const reload = [...dialog.querySelectorAll('button')].find( + (button) => button.textContent === t('autoApproval.reload'), + ); + if (!reload) throw new Error('Missing read-only retry'); + await act(async () => reload.click()); + } + expect(host.querySelector('[data-approval-template="night-shift"]')).toBeNull(); + expect(trigger().textContent).toContain(t('autoApproval.off')); + expect(document.body.textContent).not.toContain( + t('autoApproval.library.deleteTitle', { title: 'Night shift' }), + ); + expect(writes).toBe(0); + }, +); + +it.each([false, true])( + 'keeps the latest library, global choice and editor after an older read finishes (fails: %s)', + async (olderFails) => { + const pending: ((value: Awaited>) => void)[] = []; + const latestTemplate = { + ...customTemplate, + name: 'dawn-shift', + title: 'Dawn shift', + text: 'Latest guidance', + }; + let reads = 0; + let writes = 0; + const call: BridgeCall = async (endpoint) => { + if (endpoint === 'approvalTemplates') { + if (++reads === 1) + return { + ok: true, + value: { templates: [...templates, customTemplate], globalDefault: 'night-shift' }, + }; + return new Promise((resolve) => pending.push(resolve)); + } + if (endpoint === 'approvalTemplateDeletePreview') + return { + ok: false, + error: { code: 'unknown-template', message: 'Removed by another client', details: {} }, + }; + if (endpoint === 'approvalTemplateGlobalSet') { + writes++; + return { ok: true, value: {} }; + } + throw new Error('Unexpected ' + endpoint); + }; + await openDeletion(call); + expect(pending).toHaveLength(1); + await clickText(t('common.cancel')); + await clickText(t('common.cancel')); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + await act(async () => trigger().click()); + await clickText(t('autoApproval.template.getWorkDone')); + expect(pending).toHaveLength(2); + const later = pending[1]; + const earlier = pending[0]; + if (!later || !earlier) throw new Error('Missing concurrent reads'); + await act(async () => + later({ + ok: true, + value: { templates: [...templates, latestTemplate], globalDefault: 'get-work-done' }, + }), + ); + const edit = host.querySelector( + '[data-approval-template="dawn-shift"] button', + ); + if (!edit) throw new Error('Missing latest template'); + await act(async () => edit.click()); + expect(document.querySelector('textarea')?.value).toBe('Latest guidance'); + await act(async () => + earlier( + olderFails + ? { ok: false, error: { code: 'read-failed', message: 'Older read failed', details: {} } } + : { ok: true, value: { templates, globalDefault: null } }, + ), + ); + expect(host.querySelector('[data-approval-template="dawn-shift"]')).not.toBeNull(); + expect(trigger().textContent).toContain(t('autoApproval.template.getWorkDone')); + expect(document.querySelector('textarea')?.value).toBe('Latest guidance'); + expect(document.body.textContent).not.toContain('Older read failed'); + expect(writes).toBe(1); + }, +); diff --git a/packages/client/test/bridge.test.ts b/packages/client/test/bridge.test.ts index 143c8c8ffa..1bf465a445 100644 --- a/packages/client/test/bridge.test.ts +++ b/packages/client/test/bridge.test.ts @@ -13,6 +13,7 @@ import { botExists, parseBotSummary, parseChannelMessages, + parseChannelMessage, parseChannelRecord, parseChannelRecords, parseOwnedSessionSummaries, @@ -2971,3 +2972,33 @@ it('reads retained WeChat context audits through the actual Client bridge before read({ ...source, contextReads: [{ ...source.contextReads[0], ...patch }] }), ).rejects.toMatchObject({ code: 'invalid-response' }); }); + +it('preserves trusted approval effects for Chat and Activity while dropping malformed metadata', () => { + const card = { + id: 'approval', + at: '2026-11-15T00:00:00Z', + body: '', + author: { kind: 'bot', slug: 'ada' }, + toolApprovalRequest: { + sessionId: 'session', + callId: 'call', + toolName: 'bot_send_message', + role: 'orchestrator', + cwd: '/memory', + input: '{}', + effects: { changes: 'irreversible', reach: 'external', personalData: true }, + }, + }; + expect(parseChannelMessage(card)?.toolApprovalRequest?.effects).toEqual( + card.toolApprovalRequest.effects, + ); + expect( + parseChannelMessage({ + ...card, + toolApprovalRequest: { + ...card.toolApprovalRequest, + effects: { changes: 'approved', reach: 'external', personalData: true }, + }, + })?.toolApprovalRequest?.effects, + ).toBeUndefined(); +}); diff --git a/packages/client/test/workspace-grants-entry.test.ts b/packages/client/test/workspace-grants-entry.test.ts index 293e1b68d6..deeff6feb8 100644 --- a/packages/client/test/workspace-grants-entry.test.ts +++ b/packages/client/test/workspace-grants-entry.test.ts @@ -43,6 +43,93 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ })); describe('Workspace Grant sidebar', () => { + it.each([ + ['flat', JSON.stringify(['orchestrator', '/qa', []])], + [ + 'explicit', + JSON.stringify([JSON.stringify(['orchestrator', '/qa', []]), 'explicit-approval']), + ], + [ + 'browser', + JSON.stringify([JSON.stringify(['orchestrator', '/qa', []]), 'browser', 'authorization']), + ], + [ + 'computer', + JSON.stringify([JSON.stringify(['orchestrator', '/qa', []]), 'computer', 'authorization']), + ], + ['tob', JSON.stringify([JSON.stringify(['orchestrator', '/qa', []]), null, 'authorization'])], + ])( + 'shows the %s card rule directory and reads canonical state after revoke without changing templates', + async (_kind, scopeKey) => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const rule = { + id: 'saved-card', + botSlug: 'ada', + role: 'orchestrator', + scopeKey, + kind: 'tool', + toolName: 'qa_marker', + input: '', + createdAt: '2026-11-16', + }; + let revoked = false; + const listToolApprovalRules = vi.fn(async () => [ + { ...rule, ...(revoked ? { revokedAt: '2026-11-16' } : {}) }, + ]); + const revokeToolApprovalRule = vi.fn(async () => { + revoked = true; + }); + const actions = { + listWorkspaceGrants: vi.fn(async () => []), + listWorkspaceOptions: vi.fn(async () => []), + memoryDirectory: vi.fn(async () => undefined), + assignmentAccess: vi.fn(async () => ({ mode: 'workspace-write' })), + listToolApprovalRules, + revokeToolApprovalRule, + } as unknown as BridgeActions; + try { + await act(async () => + root.render( + createElement(WorkspaceGrantsEntry, { + scope: 'personabot', + botSlug: 'ada', + channelId: 'dm-ada', + actions, + t: zhTranslate, + composerOnly: true, + }), + ), + ); + expect(listToolApprovalRules).toHaveBeenCalledExactlyOnceWith('ada'); + expect(container.textContent).toContain(zhTranslate('approval.rulesTitle')); + expect(container.textContent).toContain(zhTranslate('approval.ruleFromCard')); + expect( + Array.from(container.querySelectorAll('.bh-note')).map((note) => note.textContent), + ).toContain(zhTranslate('approval.cwd', { path: '/qa' })); + expect(container.querySelector('.bh-tool-approval-input')?.textContent).toBe(scopeKey); + expect(container.textContent).toContain(zhTranslate('approval.orchestrator')); + const button = container.querySelector( + 'button[aria-label="' + zhTranslate('approval.revokeRule') + ': qa_marker"]', + )!; + await act(async () => button.click()); + expect(revokeToolApprovalRule).toHaveBeenCalledExactlyOnceWith('ada', 'saved-card'); + expect(listToolApprovalRules).toHaveBeenCalledTimes(2); + expect(container.textContent).toContain(zhTranslate('approval.ruleInactive')); + expect( + container.querySelector( + 'button[aria-label="' + zhTranslate('approval.revokeRule') + ': qa_marker"]', + )?.disabled, + ).toBe(true); + } finally { + await act(async () => root.unmount()); + container.remove(); + } + }, + ); + it('reuses the Channel sidebar summary row and chevron while keeping native disclosure', async () => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); const container = document.createElement('div'); diff --git a/packages/core/src/bots/bot-create-cli.ts b/packages/core/src/bots/bot-create-cli.ts index db314bd6b2..4919cf0fe5 100644 --- a/packages/core/src/bots/bot-create-cli.ts +++ b/packages/core/src/bots/bot-create-cli.ts @@ -1,3 +1,4 @@ +import { hasCliDeclaration } from './cli-effects.js'; import { botMetadata, type BotMetadataResult } from '../team/bot-administration.js'; import { privateBotRegistry, ownsBot } from '../team/bot-access.js'; import { TeamRoles } from '../team/roles.js'; @@ -80,6 +81,7 @@ import { personaBotAvatarFromBytes, type PersonaBotRecord } from './persona-bot. import { createPersonaBotRegistry, type PersonaBotRegistry } from './registry.js'; import { ZipArchiveError, writeZip, type ZipEntry } from './zip-archive.js'; import { INBOX_HOST_COMMANDS } from './cli-inbox.js'; +import { canonicalCliCommandName } from './cli-command-names.js'; import { CliLiveError, LIVE_COMMANDS, runLiveCli } from './cli-live.js'; import { isActivityCommandName } from './cli-inbox.js'; import { hasAgentCliContext, runAgentCli } from './cli-agent.js'; @@ -2629,10 +2631,12 @@ export async function runBotCreateCli( out.stdout(JSON.stringify(await runAgentCli(command, rest, values, io, argv), null, 2)); return 0; } + if (command !== undefined) command = canonicalCliCommandName(command); if (values.help === true || command === undefined || command === 'help') { out.stdout(BOT_CREATE_HELP.trimEnd()); return 0; } + if (!hasCliDeclaration(command)) throw usageError('Unknown command.'); if (command === 'ssh-tunnel') return await runSshCli(rest, values, out); const online = values.host !== undefined || io.env['DEEPSEEKBOT_HOST'] !== undefined; const teamChannels = command === 'channels' && (online || rest.length > 0); diff --git a/packages/core/src/bots/cli-appearance.ts b/packages/core/src/bots/cli-appearance.ts index b7e4f84c02..f2947e6383 100644 --- a/packages/core/src/bots/cli-appearance.ts +++ b/packages/core/src/bots/cli-appearance.ts @@ -1,4 +1,5 @@ -import { WALLPAPER_COMMANDS, WALLPAPER_OPTIONS, runWallpaperCommand } from './cli-wallpaper.js'; +export { APPEARANCE_OPTIONS } from './cli-option-spec.js'; +import { WALLPAPER_COMMANDS, runWallpaperCommand } from './cli-wallpaper.js'; import { CliLiveError } from './cli-live-error.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; export const APPEARANCE_COMMANDS = [ @@ -30,12 +31,7 @@ export const APPEARANCE_COMMANDS = [ description: 'write --patch-stdin to an explicit --client-id with --expected-revision', }, ] as const; -export const APPEARANCE_OPTIONS = { - ...WALLPAPER_OPTIONS, - 'client-id': { type: 'string' }, - 'confirm-reset': { type: 'boolean' }, - 'expected-wallpaper-revision': { type: 'string' }, -} as const; + export async function runAppearanceCommand( command: string, rest: string[], diff --git a/packages/core/src/bots/cli-approval-reviewer.ts b/packages/core/src/bots/cli-approval-reviewer.ts index f16d7d00ec..e22a480b2e 100644 --- a/packages/core/src/bots/cli-approval-reviewer.ts +++ b/packages/core/src/bots/cli-approval-reviewer.ts @@ -1,11 +1,8 @@ +export { APPROVAL_REVIEWER_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; type Rpc = (method: string, payload: Record) => Promise; -export const APPROVAL_REVIEWER_OPTIONS = { - effort: { type: 'string' }, -} as const; - export const APPROVAL_REVIEWER_COMMANDS = [ { command: 'approval-reviewer-model', diff --git a/packages/core/src/bots/cli-approval-templates.ts b/packages/core/src/bots/cli-approval-templates.ts index 80de2cfeaf..31d80e06e7 100644 --- a/packages/core/src/bots/cli-approval-templates.ts +++ b/packages/core/src/bots/cli-approval-templates.ts @@ -3,21 +3,13 @@ import { parseApprovalTemplateGuidance, } from '../workspaces/approval-template-guidance.js'; import { readApprovalTemplateFile } from '../workspaces/approval-templates.js'; +export { APPROVAL_TEMPLATE_OPTIONS } from './cli-option-spec.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; type Rpc = (method: string, payload: Record) => Promise; -export const APPROVAL_TEMPLATE_OPTIONS = { - from: { type: 'string' }, - blank: { type: 'boolean' }, - 'parts-file': { type: 'string' }, - 'apply-to': { type: 'string' }, - 'text-stdin': { type: 'boolean' }, - 'literal-template': { type: 'boolean' }, -} as const; - export interface ApprovalTemplateValues { bot?: string; file?: string; @@ -27,6 +19,8 @@ export interface ApprovalTemplateValues { 'apply-to'?: string; 'text-stdin'?: boolean; 'literal-template'?: boolean; + confirm?: boolean; + 'delete-revision'?: string; } export const APPROVAL_TEMPLATE_COMMANDS = [ @@ -205,8 +199,17 @@ export async function runApprovalTemplateCommand( return apply(rpc, await rpc('approvalTemplateUpdate', { name, text })); } if (subcommand === 'delete') { + const revision = values['delete-revision']; + if (values.confirm === true && (revision === undefined || !/^[a-f0-9]{64}$/u.test(revision))) + usage( + 'Preview approval-template delete first, then pass --confirm --delete-revision .', + ); + if (values.confirm !== true && revision !== undefined) + usage('--delete-revision requires --confirm.'); const rpc = await connect(); - return rpc('approvalTemplateDelete', { name }); + return values.confirm === true + ? rpc('approvalTemplateDelete', { name, confirmed: true, revision }) + : rpc('approvalTemplateDeletePreview', { name }); } const rpc = await connect(); const bot = subcommand === 'list' ? values.bot?.trim() : undefined; diff --git a/packages/core/src/bots/cli-browser-computer.ts b/packages/core/src/bots/cli-browser-computer.ts index 176994cc1d..215590fa43 100644 --- a/packages/core/src/bots/cli-browser-computer.ts +++ b/packages/core/src/bots/cli-browser-computer.ts @@ -1,3 +1,4 @@ +export { BROWSER_COMPUTER_OPTIONS } from './cli-option-spec.js'; import { createReadStream, createWriteStream, statSync, writeFileSync } from 'node:fs'; import { basename } from 'node:path'; import { Readable } from 'node:stream'; @@ -9,20 +10,6 @@ import type { connectLiveHost } from './cli-live.js'; type LiveHost = Awaited>; -export const BROWSER_COMPUTER_OPTIONS = { - permission: { type: 'string' }, - tab: { type: 'string' }, - profile: { type: 'string' }, - package: { type: 'string', multiple: true }, - confirm: { type: 'boolean' }, - 'token-stdin': { type: 'boolean' }, - dir: { type: 'string' }, - plugin: { type: 'string' }, - entity: { type: 'string' }, - viewer: { type: 'string' }, - probe: { type: 'boolean' }, -} as const; - export const BROWSER_COMPUTER_COMMANDS = [ { command: 'computer-open-permission-settings', diff --git a/packages/core/src/bots/cli-call-timeline.ts b/packages/core/src/bots/cli-call-timeline.ts index 1433b14162..5cf76e9406 100644 --- a/packages/core/src/bots/cli-call-timeline.ts +++ b/packages/core/src/bots/cli-call-timeline.ts @@ -1,12 +1,8 @@ +export { CALL_TIMELINE_OPTIONS } from './cli-option-spec.js'; import { resolveBotDm } from './cli-bot-dm.js'; import type { ChannelVoiceCallRecord } from '../channels/voice-call-record.js'; import { CliLiveError } from './cli-live-error.js'; -export const CALL_TIMELINE_OPTIONS = { - 'from-ms': { type: 'string' }, - 'to-ms': { type: 'string' }, -} as const; - export const CALL_TIMELINE_COMMANDS = [ { command: 'call-list', diff --git a/packages/core/src/bots/cli-call.ts b/packages/core/src/bots/cli-call.ts index 3e89502067..a245b08c94 100644 --- a/packages/core/src/bots/cli-call.ts +++ b/packages/core/src/bots/cli-call.ts @@ -1,3 +1,4 @@ +export { CALL_OPTIONS } from './cli-option-spec.js'; import { readFileSync, writeFileSync } from 'node:fs'; import { isAbsolute } from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -23,15 +24,6 @@ export interface CallHost { readonly text: CallText; } -export const CALL_OPTIONS = { - script: { type: 'string' }, - 'reply-wait': { type: 'string' }, - video: { type: 'string' }, - screen: { type: 'string' }, - 'share-ends-at': { type: 'string' }, - 'share-pause': { type: 'string' }, -} as const; - export interface CallValues { file?: string; script?: string; diff --git a/packages/core/src/bots/cli-channels.ts b/packages/core/src/bots/cli-channels.ts index b4724d5446..8d0ec8d4d9 100644 --- a/packages/core/src/bots/cli-channels.ts +++ b/packages/core/src/bots/cli-channels.ts @@ -1,35 +1,10 @@ +export { CHANNEL_OPTIONS } from './cli-option-spec.js'; import { readFileSync, writeFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; import type { connectLiveHost } from './cli-live.js'; -export const CHANNEL_OPTIONS = { - 'avatar-file': { type: 'string' }, - 'expected-channel': { type: 'string' }, - invitation: { type: 'string' }, - request: { type: 'string' }, - accept: { type: 'boolean' }, - decline: { type: 'boolean' }, - inherit: { type: 'boolean' }, - count: { type: 'string' }, - interval: { type: 'string' }, - direction: { type: 'string' }, - around: { type: 'string' }, - 'older-limit': { type: 'string' }, - 'newer-limit': { type: 'string' }, - through: { type: 'string' }, - since: { type: 'string' }, - epoch: { type: 'string' }, - 'source-event': { type: 'string', multiple: true }, - confirm: { type: 'boolean' }, - emoji: { type: 'string' }, - remove: { type: 'boolean' }, - off: { type: 'boolean' }, - attachment: { type: 'string' }, - representation: { type: 'string' }, -} as const; - export const CHANNEL_COMMANDS = [ { command: 'channel', diff --git a/packages/core/src/bots/cli-command-names.ts b/packages/core/src/bots/cli-command-names.ts new file mode 100644 index 0000000000..6fa903f13c --- /dev/null +++ b/packages/core/src/bots/cli-command-names.ts @@ -0,0 +1,26 @@ +const activityCommandNames = new Map([ + ['activity', 'inbox'], + ['activity-watch', 'inbox-watch'], + ['activity-status', 'inbox-status'], + ['activity-dismiss', 'inbox-dismiss'], + ['activity-restore', 'inbox-restore'], + ['activity-dismiss-all', 'inbox-dismiss-all'], + ['activity-allow-once', 'inbox-allow-once'], + ['activity-ignore', 'inbox-ignore'], + ['activity-snooze', 'inbox-snooze'], +]); +const canonicalCommands = new Map( + [...activityCommandNames].map(([current, legacy]) => [legacy, current]), +); + +export function canonicalCliCommandName(command: string): string { + return canonicalCommands.get(command) ?? command; +} + +export function legacyActivityCommandName(command: string): string { + return activityCommandNames.get(command) ?? command; +} + +export function isActivityCliCommand(command: string): boolean { + return activityCommandNames.has(command) || canonicalCommands.has(command); +} diff --git a/packages/core/src/bots/cli-connect.ts b/packages/core/src/bots/cli-connect.ts index a24f3d2778..f5f96df8fc 100644 --- a/packages/core/src/bots/cli-connect.ts +++ b/packages/core/src/bots/cli-connect.ts @@ -1,3 +1,4 @@ +export { CONNECT_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; export const CONNECT_COMMANDS = [ { @@ -64,15 +65,7 @@ export const CONNECT_COMMANDS = [ description: 'sign out another linked computer by host ID (--confirm)', }, ] as const; -export const CONNECT_OPTIONS = { - 'expected-route-revision': { type: 'string' }, - hostname: { type: 'string' }, - 'token-stdin': { type: 'boolean' }, - wait: { type: 'boolean' }, - quick: { type: 'boolean' }, - origin: { type: 'string' }, - lan: { type: 'boolean' }, -} as const; + const DEVICES = '/api/botharness/devices'; export function isConnectCommand(command: string): boolean { return CONNECT_COMMANDS.some((entry) => entry.command === command); diff --git a/packages/core/src/bots/cli-device-notifications.ts b/packages/core/src/bots/cli-device-notifications.ts index 2b18e1f483..7b5a88a0c7 100644 --- a/packages/core/src/bots/cli-device-notifications.ts +++ b/packages/core/src/bots/cli-device-notifications.ts @@ -1,3 +1,4 @@ +export { DEVICE_NOTIFICATION_OPTIONS } from './cli-option-spec.js'; import { readFileSync } from 'node:fs'; import { parseSavedHost } from '../../../../apps/mobile/src/host/hosts.js'; import { parseNotificationPreferences } from '../../../../apps/mobile/src/host/device-notification-preferences.js'; @@ -15,14 +16,6 @@ export const DEVICE_NOTIFICATION_COMMANDS = [ 'read or copy a paired device notification preference (--device-file, --preferences-stdin, --delivery push|in-app)', }, ] as const; -export const DEVICE_NOTIFICATION_OPTIONS = { - 'metro-port': { type: 'string' }, - 'target-id': { type: 'string' }, - 'device-name': { type: 'string' }, - 'device-file': { type: 'string' }, - 'preferences-stdin': { type: 'boolean' }, - delivery: { type: 'string' }, -} as const; export async function runDeviceNotifications( rest: string[], diff --git a/packages/core/src/bots/cli-effects.ts b/packages/core/src/bots/cli-effects.ts new file mode 100644 index 0000000000..8bf2b8a8d0 --- /dev/null +++ b/packages/core/src/bots/cli-effects.ts @@ -0,0 +1,739 @@ +import { parseBotCliArgs } from './cli-options.js'; +import { canonicalCliCommandName } from './cli-command-names.js'; +import type { ToolEffects } from '../workspaces/tool-effects.js'; + +const opaque = undefined; +const read = { changes: 'none', reach: 'local', personalData: true } satisfies ToolEffects; +const write = { ...read, changes: 'reversible' } satisfies ToolEffects; +const externalRead = { ...read, reach: 'external' } satisfies ToolEffects; +const external = { ...write, changes: 'irreversible', reach: 'external' } satisfies ToolEffects; +const externalWrite = { ...write, reach: 'external' } satisfies ToolEffects; +const destructive = { ...write, changes: 'irreversible' } satisfies ToolEffects; +const memoryRead = { ...read, reach: 'memory' } satisfies ToolEffects; +const memoryWrite = { ...write, reach: 'memory' } satisfies ToolEffects; +const secretRead = { ...read, secrets: true } satisfies ToolEffects; +const destructiveSecret = { ...destructive, secrets: true } satisfies ToolEffects; +const secretWrite = { ...write, secrets: true } satisfies ToolEffects; +const management = { ...write, authority: 'management' } satisfies ToolEffects; +const secretManagement = { ...management, secrets: true } satisfies ToolEffects; +const externalIrreversibleManagement = { + ...management, + changes: 'irreversible', + reach: 'external', +} satisfies ToolEffects; +const externalManagement = { ...management, reach: 'external' } satisfies ToolEffects; +const externalSecretManagement = { ...externalManagement, secrets: true } satisfies ToolEffects; +const destructiveManagement = { ...management, changes: 'irreversible' } satisfies ToolEffects; +const destructiveSecretManagement = { + ...destructiveManagement, + secrets: true, +} satisfies ToolEffects; + +export const CLI_EFFECTS = { + 'tob-cli': { effects: management, brokerRead: false }, + access: { effects: read, brokerRead: true }, + 'access-set': { effects: management, brokerRead: false }, + acknowledge: { effects: write, brokerRead: false }, + acknowledgements: { effects: read, brokerRead: false }, + activity: { effects: read, brokerRead: true }, + 'activity-allow-once': { effects: external, brokerRead: false }, + 'activity-dismiss': { effects: write, brokerRead: false }, + 'activity-dismiss-all': { effects: write, brokerRead: false }, + 'activity-ignore': { effects: write, brokerRead: false }, + 'activity-overview': { effects: read, brokerRead: true }, + 'activity-restore': { effects: write, brokerRead: false }, + 'activity-snooze': { effects: write, brokerRead: false }, + 'activity-status': { effects: read, brokerRead: true }, + 'activity-watch': { effects: read, brokerRead: true }, + 'appearance-clear-panels': { effects: write, brokerRead: false }, + 'appearance-clients': { effects: read, brokerRead: true }, + 'appearance-get': { effects: read, brokerRead: true }, + 'appearance-reset': { effects: write, brokerRead: false }, + 'appearance-set': { effects: write, brokerRead: false }, + 'appearance-targets': { effects: read, brokerRead: true }, + 'approval-retry': { effects: external, brokerRead: false }, + 'approval-reviewer-model': { effects: read, brokerRead: true }, + 'approval-reviewer-model-set': { effects: management, brokerRead: false }, + 'approval-route': { effects: management, brokerRead: false }, + 'approval-routes': { effects: read, brokerRead: true }, + 'approval-template': { effects: management, brokerRead: false }, + 'approval-template-global-set': { effects: management, brokerRead: false }, + 'approval-template-set': { effects: management, brokerRead: false }, + 'approval-template-show': { effects: read, brokerRead: true }, + 'approval-templates': { effects: read, brokerRead: true }, + 'approval-test': { effects: external, brokerRead: false }, + 'ask-secret-account-status': { effects: read, brokerRead: true }, + 'ask-secret-accounts': { effects: read, brokerRead: true }, + 'ask-secret-cancel': { effects: write, brokerRead: false }, + 'ask-secret-replace': { effects: secretWrite, brokerRead: false }, + 'ask-secret-revoke': { effects: destructiveSecret, brokerRead: false }, + 'ask-secret-status': { effects: read, brokerRead: true }, + 'ask-secret-submit': { effects: secretWrite, brokerRead: false }, + assignment: { effects: read, brokerRead: true }, + 'assignment-context': { effects: read, brokerRead: true }, + 'assignment-timeline': { effects: read, brokerRead: true }, + assignments: { effects: read, brokerRead: true }, + audit: { effects: read, brokerRead: false }, + 'bot-activity': { effects: read, brokerRead: true }, + 'bot-activity-history': { effects: read, brokerRead: true }, + 'bot-appearance-set': { effects: write, brokerRead: false }, + 'bot-access': { effects: management, brokerRead: true }, + 'bot-attention': { effects: read, brokerRead: true }, + 'bot-avatar-set': { effects: write, brokerRead: false }, + 'bot-banner-set': { effects: write, brokerRead: false }, + 'bot-compact': { effects: write, brokerRead: false }, + 'bot-context': { effects: read, brokerRead: true }, + 'bot-delete-confirm': { effects: destructive, brokerRead: false }, + 'bot-delete-memory-folder': { effects: read, brokerRead: true }, + 'bot-delete-preview': { effects: read, brokerRead: true }, + 'bot-delete-retry': { effects: destructive, brokerRead: false }, + 'bot-import-preview': { effects: read, brokerRead: false }, + 'bot-lan': { effects: management, brokerRead: false }, + 'bot-new-session': { effects: write, brokerRead: false }, + 'bot-primary-color-set': { effects: write, brokerRead: false }, + 'bot-prompt': { effects: read, brokerRead: true }, + 'bot-prompt-set': { effects: write, brokerRead: false }, + 'bot-session-usage': { effects: read, brokerRead: true }, + 'bot-sessions': { effects: read, brokerRead: true }, + 'bot-source-policies': { effects: read, brokerRead: true }, + 'bot-source-policy-reset': { effects: write, brokerRead: false }, + 'bot-source-policy-set': { effects: write, brokerRead: false }, + 'bot-standing-limits-set': { effects: write, brokerRead: false }, + 'bot-stop': { effects: destructive, brokerRead: false }, + 'bot-system-prompt': { effects: read, brokerRead: true }, + 'bot-tool': { effects: opaque, brokerRead: false }, + 'bot-tools': { effects: read, brokerRead: true }, + 'bot-trace': { effects: read, brokerRead: true }, + 'bot-turn-input': { effects: read, brokerRead: true }, + 'bot-usage': { effects: read, brokerRead: true }, + 'bot-zip-import': { effects: write, brokerRead: false }, + 'bot-zip-import-status': { effects: read, brokerRead: false }, + 'bot-zip-preview': { effects: read, brokerRead: false }, + 'bot-zip-upload': { effects: write, brokerRead: false }, + bots: { effects: write, brokerRead: false }, + 'browser-access-set': { effects: management, brokerRead: false }, + 'browser-frame': { effects: read, brokerRead: false }, + 'browser-input': { effects: external, brokerRead: false }, + 'browser-install-packages': { effects: external, brokerRead: false }, + 'browser-notification-clients': { effects: read, brokerRead: true }, + 'browser-notifications': { effects: write, brokerRead: false }, + 'browser-observation': { effects: read, brokerRead: false }, + 'browser-open': { effects: external, brokerRead: false }, + 'browser-packages': { effects: read, brokerRead: true }, + 'browser-profile-set': { effects: management, brokerRead: false }, + 'browser-stop': { effects: write, brokerRead: false }, + 'browser-takeover': { effects: write, brokerRead: false }, + 'browser-takeover-audit': { effects: read, brokerRead: true }, + 'browser-takeover-recording': { effects: write, brokerRead: false }, + 'browser-tool': { effects: opaque, brokerRead: false }, + 'browser-tools': { effects: read, brokerRead: true }, + 'browser-webrtc': { effects: write, brokerRead: false }, + 'bug-report': { effects: external, brokerRead: false }, + 'call-frame': { effects: read, brokerRead: false }, + 'call-hangup': { effects: destructive, brokerRead: false }, + 'call-list': { effects: read, brokerRead: true }, + 'call-read': { effects: read, brokerRead: true }, + 'call-readiness': { effects: read, brokerRead: true }, + 'call-simulate': { effects: external, brokerRead: false }, + 'call-status': { effects: read, brokerRead: true }, + capabilities: { effects: read, brokerRead: false }, + channel: { effects: read, brokerRead: true }, + 'channel-activity-today': { effects: read, brokerRead: true }, + 'channel-assign': { effects: external, brokerRead: false }, + 'channel-assignments': { effects: read, brokerRead: true }, + 'channel-bot-stop': { effects: destructive, brokerRead: false }, + 'channel-bridge': { effects: external, brokerRead: false }, + 'channel-bridges': { effects: read, brokerRead: true }, + 'channel-changes': { effects: read, brokerRead: true }, + 'channel-connect': { effects: external, brokerRead: false }, + 'channel-files': { effects: read, brokerRead: false }, + 'channel-history': { effects: read, brokerRead: true }, + 'channel-history-sources': { effects: read, brokerRead: false }, + 'channel-human-name-set': { effects: write, brokerRead: false }, + 'channel-ingests': { effects: read, brokerRead: true }, + 'channel-journal': { effects: read, brokerRead: false }, + 'channel-list-changes': { effects: read, brokerRead: true }, + 'channel-mark-all-read': { effects: write, brokerRead: false }, + 'channel-mark-read': { effects: write, brokerRead: false }, + 'channel-media-download': { effects: write, brokerRead: false }, + 'channel-media-target': { effects: read, brokerRead: false }, + 'channel-messages': { effects: read, brokerRead: true }, + 'channel-mute': { effects: write, brokerRead: false }, + 'channel-purge-confirm': { effects: destructive, brokerRead: false }, + 'channel-purge-preview': { effects: read, brokerRead: true }, + 'channel-react': { effects: external, brokerRead: false }, + 'channel-rename': { effects: write, brokerRead: false }, + 'channel-retry': { effects: write, brokerRead: false }, + 'channel-search': { effects: read, brokerRead: true }, + 'channel-timeline': { effects: read, brokerRead: false }, + 'channel-unread': { effects: read, brokerRead: true }, + channels: { effects: read, brokerRead: true }, + cloud: { effects: external, brokerRead: false }, + 'cloud-work': { effects: external, brokerRead: false }, + 'compaction-threshold-set': { effects: write, brokerRead: false }, + 'computer-access-set': { effects: management, brokerRead: false }, + 'computer-diagnostics': { effects: read, brokerRead: true }, + 'computer-export': { effects: secretWrite, brokerRead: false }, + 'computer-exports': { effects: read, brokerRead: true }, + 'computer-frame': { effects: read, brokerRead: false }, + 'computer-import': { effects: secretWrite, brokerRead: false }, + 'computer-input': { effects: external, brokerRead: false }, + 'computer-install-packages': { effects: external, brokerRead: false }, + 'computer-logs': { effects: read, brokerRead: true }, + 'computer-open-dir': { effects: write, brokerRead: false }, + 'computer-open-permission-settings': { effects: write, brokerRead: false }, + 'computer-start': { effects: write, brokerRead: false }, + 'computer-status': { effects: read, brokerRead: true }, + 'computer-stop': { effects: write, brokerRead: false }, + 'computer-takeover': { effects: write, brokerRead: false }, + 'computer-tool': { effects: opaque, brokerRead: false }, + 'computer-tools': { effects: read, brokerRead: true }, + 'computer-upload': { effects: external, brokerRead: false }, + 'computer-video': { effects: write, brokerRead: false }, + 'computer-webrtc': { effects: write, brokerRead: false }, + 'connect-account-hosts': { effects: read, brokerRead: true }, + 'connect-account-revoke': { effects: externalManagement, brokerRead: false }, + 'connect-check': { effects: write, brokerRead: false }, + 'connect-disable': { effects: management, brokerRead: false }, + 'connect-enable': { effects: externalSecretManagement, brokerRead: false }, + 'connect-sign-in': { effects: externalManagement, brokerRead: false }, + 'connect-sign-out': { effects: externalManagement, brokerRead: false }, + 'connect-status': { effects: read, brokerRead: true }, + connection: { effects: write, brokerRead: false }, + 'connection-clients': { effects: read, brokerRead: true }, + 'connection-host': { effects: write, brokerRead: false }, + 'connection-hosts': { effects: write, brokerRead: false }, + create: { effects: external, brokerRead: false }, + 'create-status': { effects: read, brokerRead: false }, + 'data-reset-confirm': { effects: destructive, brokerRead: false }, + 'data-reset-preview': { effects: read, brokerRead: true }, + 'desktop-window-reveal': { effects: write, brokerRead: false }, + 'developer-mode-set': { effects: write, brokerRead: false }, + 'device-account-pair': { effects: externalSecretManagement, brokerRead: false }, + 'device-activity': { effects: write, brokerRead: false }, + 'device-approve-key': { effects: management, brokerRead: false }, + 'device-lan': { effects: management, brokerRead: false }, + 'device-notifications': { effects: write, brokerRead: false }, + 'device-offer': { effects: management, brokerRead: false }, + 'device-offer-status': { effects: read, brokerRead: true }, + 'device-pair': { effects: externalSecretManagement, brokerRead: false }, + 'device-probe': { effects: write, brokerRead: false }, + 'device-requests': { effects: read, brokerRead: true }, + 'device-revoke': { effects: management, brokerRead: false }, + devices: { effects: read, brokerRead: true }, + 'diagnostic-log-record': { effects: write, brokerRead: false }, + 'diagnostic-logs': { effects: read, brokerRead: false }, + 'diagnostic-logs-export': { effects: write, brokerRead: false }, + dm: { effects: write, brokerRead: false }, + doctor: { effects: read, brokerRead: false }, + 'failure-alerts': { effects: read, brokerRead: true }, + 'failure-alerts-retry': { effects: external, brokerRead: false }, + 'failure-alerts-set': { effects: write, brokerRead: false }, + 'failure-alerts-test': { effects: external, brokerRead: false }, + 'feedback-download': { effects: secretWrite, brokerRead: false }, + 'feedback-preview': { effects: read, brokerRead: false }, + 'feedback-submit': { effects: external, brokerRead: false }, + 'folder-browse': { effects: read, brokerRead: true }, + 'genui-submit': { effects: external, brokerRead: false }, + 'genui-view': { effects: read, brokerRead: true }, + 'genui-view-save': { effects: write, brokerRead: false }, + 'git-install': { effects: external, brokerRead: false }, + 'git-status': { effects: read, brokerRead: true }, + 'grant-create': { effects: management, brokerRead: false }, + 'grant-request-approve': { effects: management, brokerRead: false }, + 'grant-revoke': { effects: management, brokerRead: false }, + 'grant-write-set': { effects: management, brokerRead: false }, + grants: { effects: read, brokerRead: true }, + 'group-activity': { effects: read, brokerRead: true }, + 'group-avatar-set': { effects: write, brokerRead: false }, + 'group-create': { effects: write, brokerRead: false }, + 'group-delete': { effects: destructive, brokerRead: false }, + 'group-invite': { effects: external, brokerRead: false }, + 'group-invite-cancel': { effects: write, brokerRead: false }, + 'group-join-decide': { effects: write, brokerRead: false }, + 'group-member-remove': { effects: write, brokerRead: false }, + 'group-send-review': { effects: external, brokerRead: false }, + 'group-wake-policies': { effects: read, brokerRead: true }, + 'group-wake-set': { effects: write, brokerRead: false }, + help: { effects: read, brokerRead: false }, + 'home-model-set': { effects: write, brokerRead: false }, + 'host-look': { effects: read, brokerRead: false }, + 'host-ping': { effects: read, brokerRead: true }, + 'human-identity': { effects: read, brokerRead: true }, + 'human-name-set': { effects: write, brokerRead: false }, + 'idle-compaction': { effects: read, brokerRead: true }, + 'idle-compaction-cache-set': { effects: write, brokerRead: false }, + 'idle-compaction-set': { effects: write, brokerRead: false }, + 'im-app-add': { effects: externalSecretManagement, brokerRead: false }, + 'im-app-remove': { effects: secretManagement, brokerRead: false }, + 'im-app-status': { effects: read, brokerRead: true }, + 'im-apps': { effects: read, brokerRead: true }, + 'im-authorize': { effects: external, brokerRead: false }, + 'im-bind': { effects: externalWrite, brokerRead: false }, + 'im-cancel': { effects: write, brokerRead: false }, + 'im-credentials': { effects: externalSecretManagement, brokerRead: false }, + 'im-status': { effects: read, brokerRead: true }, + 'im-reconnect': { effects: externalWrite, brokerRead: false }, + 'im-unbind': { effects: externalWrite, brokerRead: false }, + 'im-verify': { effects: externalSecretManagement, brokerRead: false }, + list: { effects: read, brokerRead: true }, + 'marketplace-account': { effects: externalRead, brokerRead: true }, + 'marketplace-author': { effects: external, brokerRead: false }, + 'marketplace-author-avatar': { effects: external, brokerRead: false }, + 'marketplace-delete': { effects: external, brokerRead: false }, + 'marketplace-detail': { effects: externalRead, brokerRead: true }, + 'marketplace-digest': { effects: externalRead, brokerRead: true }, + 'marketplace-digests': { effects: externalRead, brokerRead: true }, + 'marketplace-file': { effects: externalRead, brokerRead: true }, + 'marketplace-install': { effects: externalWrite, brokerRead: false }, + 'marketplace-list': { effects: externalRead, brokerRead: false }, + 'marketplace-mine': { effects: externalRead, brokerRead: true }, + 'marketplace-report': { effects: external, brokerRead: false }, + 'marketplace-sections': { effects: externalRead, brokerRead: true }, + 'marketplace-submit': { effects: external, brokerRead: false }, + 'marketplace-topics': { effects: externalRead, brokerRead: true }, + 'marketplace-upload': { effects: external, brokerRead: false }, + 'marketplace-upload-plan': { effects: read, brokerRead: true }, + members: { effects: management, brokerRead: false }, + 'memory-changes': { effects: memoryRead, brokerRead: true }, + 'memory-checkpoints': { effects: memoryRead, brokerRead: true }, + 'memory-commit-diff': { effects: memoryRead, brokerRead: true }, + 'memory-diff': { effects: memoryRead, brokerRead: true }, + 'memory-file': { effects: memoryRead, brokerRead: true }, + 'memory-file-target': { effects: memoryRead, brokerRead: false }, + 'memory-graph': { effects: memoryRead, brokerRead: true }, + 'memory-history': { effects: memoryRead, brokerRead: true }, + 'memory-image': { effects: write, brokerRead: false }, + 'memory-move': { effects: memoryWrite, brokerRead: false }, + 'memory-repair': { effects: memoryWrite, brokerRead: false }, + 'memory-restore': { effects: memoryWrite, brokerRead: false }, + 'memory-restore-commit': { effects: memoryWrite, brokerRead: false }, + 'memory-save': { effects: memoryWrite, brokerRead: false }, + 'memory-snapshot': { effects: memoryRead, brokerRead: true }, + 'memory-version-name': { effects: memoryWrite, brokerRead: false }, + 'memory-version-unname': { effects: memoryWrite, brokerRead: false }, + 'memory-versions': { effects: memoryRead, brokerRead: true }, + 'memory-working-diff': { effects: memoryRead, brokerRead: true }, + 'message-search': { effects: read, brokerRead: true }, + 'messaging-authorize': { effects: management, brokerRead: false }, + 'messaging-channel-target': { effects: write, brokerRead: false }, + 'messaging-conversation': { effects: external, brokerRead: false }, + 'messaging-defaults': { effects: read, brokerRead: true }, + 'messaging-defaults-set': { effects: write, brokerRead: false }, + 'messaging-grants': { effects: read, brokerRead: true }, + 'messaging-group-policy': { effects: management, brokerRead: false }, + 'messaging-post': { effects: external, brokerRead: false }, + 'messaging-post-limit': { effects: write, brokerRead: false }, + 'messaging-post-status': { effects: read, brokerRead: true }, + 'messaging-reachable': { effects: externalRead, brokerRead: true }, + 'messaging-receive': { effects: write, brokerRead: false }, + 'messaging-revoke': { effects: management, brokerRead: false }, + 'messaging-send': { effects: external, brokerRead: false }, + 'messaging-source': { effects: externalRead, brokerRead: true }, + 'messaging-targets': { effects: externalRead, brokerRead: true }, + 'messaging-thread-policy': { effects: management, brokerRead: false }, + 'model-catalog': { effects: read, brokerRead: true }, + 'model-plan': { effects: read, brokerRead: true }, + 'model-plan-assignments-set': { effects: write, brokerRead: false }, + 'model-plan-customize': { effects: write, brokerRead: false }, + 'model-plan-inherit': { effects: write, brokerRead: false }, + 'model-plan-set': { effects: write, brokerRead: false }, + 'model-preset-apply': { effects: write, brokerRead: false }, + 'model-preset-create': { effects: write, brokerRead: false }, + 'model-preset-update': { effects: write, brokerRead: false }, + 'model-presets': { effects: read, brokerRead: true }, + models: { effects: read, brokerRead: false }, + onboarding: { effects: write, brokerRead: false }, + 'overview-memory': { effects: read, brokerRead: true }, + 'overview-usage': { effects: read, brokerRead: true }, + 'pairing-list': { effects: read, brokerRead: true }, + 'pairing-review': { effects: management, brokerRead: false }, + 'pairing-status': { effects: write, brokerRead: false }, + pairings: { effects: read, brokerRead: true }, + 'part-library': { effects: read, brokerRead: true }, + 'part-library-add': { effects: write, brokerRead: false }, + 'part-library-export': { effects: write, brokerRead: false }, + 'part-library-import': { effects: write, brokerRead: false }, + 'part-library-import-image': { effects: write, brokerRead: false }, + pause: { effects: write, brokerRead: false }, + 'phone-notifications': { effects: write, brokerRead: false }, + 'phone-route': { effects: read, brokerRead: true }, + 'phone-route-disable': { effects: externalManagement, brokerRead: false }, + 'phone-route-publish': { effects: externalManagement, brokerRead: false }, + 'plugin-check': { effects: externalRead, brokerRead: true }, + 'plugin-install': { effects: external, brokerRead: false }, + 'plugin-restart': { effects: destructive, brokerRead: false }, + 'presence-report': { effects: write, brokerRead: false }, + 'presence-status': { effects: read, brokerRead: false }, + private: { effects: write, brokerRead: false }, + 'private-connect': { effects: externalSecretManagement, brokerRead: false }, + 'private-ingress-disable': { effects: externalManagement, brokerRead: false }, + 'private-ingress-enable': { effects: externalManagement, brokerRead: false }, + 'private-mcp-remove': { effects: secretManagement, brokerRead: false }, + 'private-mcp-set': { effects: secretManagement, brokerRead: false }, + 'private-route': { effects: write, brokerRead: false }, + 'private-tunnel-disable': { effects: externalManagement, brokerRead: false }, + 'private-tunnel-enable': { effects: externalManagement, brokerRead: false }, + 'profile-backup-activate': { effects: destructiveManagement, brokerRead: false }, + 'profile-backup-authorize': { effects: management, brokerRead: false }, + 'profile-backup-export': { effects: secretManagement, brokerRead: false }, + 'profile-backup-inspect': { effects: secretManagement, brokerRead: false }, + 'profile-backup-preview': { effects: read, brokerRead: true }, + 'profile-backup-recovery': { effects: read, brokerRead: true }, + 'profile-backup-restore': { effects: destructiveSecretManagement, brokerRead: false }, + 'prompt-global-set': { effects: write, brokerRead: false }, + 'prompt-parts': { effects: read, brokerRead: true }, + 'prompt-preset-create': { effects: write, brokerRead: false }, + 'prompt-preset-delete': { effects: destructive, brokerRead: false }, + 'prompt-preset-update': { effects: write, brokerRead: false }, + 'prompt-presets': { effects: read, brokerRead: true }, + 'question-deliveries': { effects: read, brokerRead: true }, + 'question-retry': { effects: external, brokerRead: false }, + relationships: { effects: write, brokerRead: false }, + 'release-check': { effects: externalRead, brokerRead: true }, + 'release-info': { effects: read, brokerRead: true }, + 'release-install': { effects: external, brokerRead: false }, + 'release-restart': { effects: destructive, brokerRead: false }, + resume: { effects: write, brokerRead: false }, + roles: { effects: write, brokerRead: false }, + roster: { effects: read, brokerRead: true }, + 'roster-batch': { effects: write, brokerRead: false }, + 'roster-hidden-set': { effects: write, brokerRead: false }, + 'roster-pins-set': { effects: write, brokerRead: false }, + 'roster-section-create': { effects: write, brokerRead: false }, + 'roster-section-remove': { effects: write, brokerRead: false }, + 'roster-section-rename': { effects: write, brokerRead: false }, + 'roster-section-reorder': { effects: write, brokerRead: false }, + 'roster-top-reorder': { effects: write, brokerRead: false }, + 'schedule-create': { effects: write, brokerRead: false }, + 'schedule-delete': { effects: destructive, brokerRead: false }, + 'schedule-history': { effects: read, brokerRead: true }, + 'schedule-preview': { effects: read, brokerRead: true }, + 'schedule-run-now': { effects: external, brokerRead: false }, + 'schedule-update': { effects: write, brokerRead: false }, + schedules: { effects: read, brokerRead: true }, + search: { effects: read, brokerRead: true }, + 'secret-list': { effects: secretRead, brokerRead: true }, + 'secret-put': { effects: secretWrite, brokerRead: false }, + 'secret-unset': { effects: destructiveSecret, brokerRead: false }, + send: { effects: external, brokerRead: false }, + 'send-status': { effects: read, brokerRead: true }, + 'sender-access': { effects: management, brokerRead: false }, + 'session-archive-set': { effects: write, brokerRead: false }, + 'session-ids': { effects: read, brokerRead: true }, + 'session-owner': { effects: read, brokerRead: true }, + 'session-stop': { effects: destructive, brokerRead: false }, + 'session-subagents': { effects: read, brokerRead: true }, + settings: { effects: read, brokerRead: true }, + 'settings-set': { effects: opaque, brokerRead: false }, + 'share-draft-decide': { effects: write, brokerRead: false }, + 'share-draft-discard': { effects: destructive, brokerRead: false }, + 'share-draft-export': { effects: { ...write, reach: 'workspace' }, brokerRead: false }, + 'share-draft-file': { effects: read, brokerRead: true }, + 'share-draft-finish': { effects: write, brokerRead: false }, + 'share-draft-show': { effects: read, brokerRead: true }, + 'share-draft-start': { effects: write, brokerRead: false }, + show: { effects: read, brokerRead: true }, + spaces: { effects: write, brokerRead: false }, + 'ssh-tunnel': { effects: externalSecretManagement, brokerRead: false }, + 'storage-cleanup-confirm': { effects: destructive, brokerRead: false }, + 'storage-cleanup-preview': { effects: read, brokerRead: true }, + 'storage-messages-cleanup-confirm': { effects: destructive, brokerRead: false }, + 'storage-messages-cleanup-preview': { effects: read, brokerRead: true }, + 'storage-usage': { effects: read, brokerRead: true }, + 'skills-list': { effects: read, brokerRead: true }, + 'skills-memory': { effects: memoryRead, brokerRead: true }, + 'skills-show': { effects: read, brokerRead: true }, + 'skills-remove': { effects: memoryWrite, brokerRead: false }, + 'speaker-policy': { effects: read, brokerRead: true }, + 'takeover-cancel': { effects: write, brokerRead: false }, + 'takeover-complete': { effects: write, brokerRead: false }, + 'takeover-request': { effects: write, brokerRead: false }, + 'takeover-status': { effects: read, brokerRead: true }, + takeovers: { effects: read, brokerRead: true }, + 'team-directory': { effects: read, brokerRead: false }, + 'team-mode': { effects: management, brokerRead: false }, + 'telemetry-set': { effects: write, brokerRead: false }, + 'telemetry-status': { effects: read, brokerRead: true }, + 'tob-home': { effects: read, brokerRead: false }, + 'todo-add': { effects: write, brokerRead: false }, + 'todo-remove': { effects: write, brokerRead: false }, + 'todo-tool': { effects: opaque, brokerRead: false }, + 'todo-tools': { effects: read, brokerRead: true }, + 'todo-update': { effects: write, brokerRead: false }, + todos: { effects: read, brokerRead: true }, + 'tool-approval-decide': { effects: externalIrreversibleManagement, brokerRead: false }, + 'tool-approval-history': { effects: read, brokerRead: true }, + 'tool-approval-rule-revoke': { effects: externalIrreversibleManagement, brokerRead: false }, + 'tool-approval-rules': { effects: read, brokerRead: true }, + 'tool-approval-status': { effects: read, brokerRead: true }, + update: { effects: write, brokerRead: false }, + 'update-cancel': { effects: write, brokerRead: false }, + 'update-status': { effects: read, brokerRead: true }, + usage: { effects: read, brokerRead: false }, + 'user-question-answer': { effects: external, brokerRead: false }, + 'user-question-status': { effects: read, brokerRead: true }, + 'voice-asr-set': { effects: write, brokerRead: false }, + 'voice-default-set': { effects: write, brokerRead: false }, + 'voice-defaults': { effects: read, brokerRead: true }, + 'voice-dictate': { effects: external, brokerRead: false }, + 'voice-local-kit': { effects: write, brokerRead: false }, + 'voice-provider-add': { effects: secretManagement, brokerRead: false }, + 'voice-provider-remove': { effects: destructiveSecret, brokerRead: false }, + 'voice-provider-test': { effects: external, brokerRead: false }, + 'voice-providers': { effects: read, brokerRead: true }, + 'voice-set': { effects: write, brokerRead: false }, + 'voice-synthesize': { effects: external, brokerRead: false }, + 'voice-transcribe': { effects: external, brokerRead: false }, + 'voice-vad-set': { effects: write, brokerRead: false }, + 'wallpaper-crop': { effects: write, brokerRead: false }, + 'wallpaper-get': { effects: read, brokerRead: true }, + 'wallpaper-import': { effects: write, brokerRead: false }, + 'wallpaper-remove': { effects: write, brokerRead: false }, + 'wallpaper-rotation': { effects: write, brokerRead: false }, + 'wallpaper-select': { effects: write, brokerRead: false }, + 'window-zoom-clients': { effects: read, brokerRead: true }, + 'window-zoom-get': { effects: read, brokerRead: true }, + 'window-zoom-reset': { effects: write, brokerRead: false }, + 'window-zoom-set': { effects: write, brokerRead: false }, + 'window-zoom-setup-cancel': { effects: write, brokerRead: false }, + 'window-zoom-setup-disable': { effects: write, brokerRead: false }, + 'window-zoom-setup-enable': { effects: write, brokerRead: false }, + 'window-zoom-setup-status': { effects: read, brokerRead: true }, + 'workspace-create': { effects: write, brokerRead: false }, + 'workspace-options': { effects: read, brokerRead: true }, +} satisfies Record; +const declarations: Readonly< + Partial> +> = CLI_EFFECTS; + +export function hasCliDeclaration(command: string): boolean { + return Object.hasOwn(declarations, canonicalCliCommandName(command)); +} + +function botAccessEffects( + action: string | undefined, + values: ReturnType['values'], +): ToolEffects | undefined { + if (action === 'reachable' || action === 'visibility') return read; + if (action === 'visibility-set') return values.preview ? read : management; + if (action === 'switches') + return values['proactive-dms'] === undefined && + values['join-channels'] === undefined && + values['speaker-context'] === undefined + ? read + : management; + if (action === 'proactive-opt-out') return write; + return undefined; +} + +function familyEffects( + command: string, + action: string | undefined, + rest: readonly string[], + values: ReturnType['values'], + fallback: ToolEffects | undefined, +): ToolEffects | undefined { + switch (command) { + case 'bots': { + switch (action) { + case 'list': + case 'show': + return read; + case 'create': + return values['from-git'] ? externalWrite : write; + case 'delete': + return destructive; + default: + return botAccessEffects(action, values); + } + } + case 'bot-access': + return botAccessEffects(action, values); + case 'channels': + if ( + action === undefined || + ['get', 'roles', 'browse', 'browse-public', 'member-candidates'].includes(action) + ) + return read; + if (action === 'send') return external; + if (['visibility', 'admins', 'add-member', 'policy', 'set-public'].includes(action)) + return management; + if (['join', 'join-public', 'description'].includes(action)) return write; + return undefined; + case 'devices': + return values.revoke === undefined ? read : destructiveManagement; + case 'members': + if (action === 'list' || ((action === 'transfer' || action === 'purge') && values.preview)) + return read; + if (['password', 'change-password', 'reset-password', 'create'].includes(action ?? '')) + return secretManagement; + if (action === 'purge') return destructiveSecretManagement; + return action === undefined ? secretManagement : management; + case 'roles': + return action === 'list' || action === 'catalog' || action === 'conflicts' + ? read + : action === 'delete' + ? destructiveManagement + : management; + case 'spaces': + return action === 'list' || action === 'audience-directory' + ? read + : action === 'delete' + ? destructiveManagement + : management; + case 'team-mode': + return action === 'status' + ? read + : action === 'owner-password' || action === 'transfer-owner' + ? secretManagement + : management; + case 'private-route': + return action === 'list' + ? read + : { ...externalManagement, ...(values['token-stdin'] ? { secrets: true } : {}) }; + case 'private-tunnel-enable': + return { ...externalManagement, ...(values['token-stdin'] ? { secrets: true } : {}) }; + case 'cloud': + return action === 'list' + ? read + : action === 'policy' + ? management + : action === 'import' + ? externalSecretManagement + : action === 'remove' + ? destructiveSecretManagement + : undefined; + case 'skills-show': + return values.owner?.startsWith('bot:') + ? memoryRead + : values.owner?.startsWith('workspace:') + ? { ...read, reach: 'workspace' } + : read; + case 'computer-video': + return action === 'input' ? external : write; + case 'approval-template': + return action === 'delete' + ? values.confirm + ? destructiveManagement + : read + : action === 'list' || action === 'show' + ? read + : action === 'create' && values['apply-to'] === undefined + ? write + : management; + case 'bot-lan': + return action === 'list' ? read : management; + case 'relationships': + return ['list', 'account-discover', 'account-status', 'enrollments'].includes(action ?? '') + ? externalRead + : { ...management, reach: 'external', secrets: true }; + case 'connection-hosts': + return { ...read, reach: 'external' }; + case 'connection-host': { + const operation = rest[1]; + return [ + 'inspect', + 'test-route', + 'read-operation', + 'read-previous-operation', + 'plan-stop-route', + 'plan-revoke-device', + 'plan-sign-out', + ].includes(operation ?? '') + ? externalRead + : { ...management, reach: 'external' }; + } + case 'connection': + return action === 'status' ? read : { ...management, secrets: true }; + case 'browser-notifications': + return values['patch-stdin'] ? management : read; + case 'phone-notifications': + case 'device-notifications': + return values['preferences-stdin'] || values.delivery ? externalManagement : externalRead; + case 'device-activity': + return action === 'capability' ? externalRead : externalWrite; + case 'onboarding': + return values.action === undefined ? read : write; + case 'create': + case 'bot-import-preview': + case 'create-status': + return values['from-git'] + ? command === 'create' + ? externalWrite + : externalRead + : command === 'create' + ? write + : read; + case 'marketplace-install': + return values.review === undefined ? externalRead : externalWrite; + case 'voice-provider-add': + return values['key-stdin'] ? secretManagement : management; + case 'tob-cli': + return action === 'status' ? read : action === 'cancel' ? write : undefined; + case 'bot-tool': + case 'browser-tool': + case 'computer-tool': + case 'todo-tool': + case 'settings-set': + return undefined; + default: + return fallback; + } +} + +export function cliEffects(argv: readonly string[]): ToolEffects | undefined { + let parsed: ReturnType; + try { + parsed = parseBotCliArgs(argv); + } catch { + return undefined; + } + const [requestedCommand, action] = parsed.positionals; + if (!requestedCommand) return undefined; + const command = canonicalCliCommandName(requestedCommand); + if (!hasCliDeclaration(command)) return undefined; + const effects = familyEffects( + command, + action, + parsed.positionals.slice(1), + parsed.values, + declarations[command]?.effects, + ); + if (!effects) return undefined; + if (parsed.values.out !== undefined) + return { + ...effects, + changes: effects.changes === 'none' ? 'reversible' : effects.changes, + reach: effects.reach === 'external' ? 'external' : 'workspace', + }; + return effects; +} + +export function brokerCliEffects(name: string, args: unknown): ToolEffects | undefined { + const command = name.slice('deepseekbot '.length); + if (typeof args !== 'object' || args === null) return undefined; + if ( + 'patch' in args && + typeof args.patch === 'object' && + args.patch !== null && + 'argv' in args.patch + ) { + const argv = args.patch.argv; + if ( + !Array.isArray(argv) || + !argv.every((arg): arg is string => typeof arg === 'string') || + argv[0] !== command + ) + return undefined; + return cliEffects(argv); + } + if ('command' in args && args.command === command) return cliEffects([command]); + return undefined; +} + +export const BROKER_CLI_READS: ReadonlySet = new Set( + Object.entries(CLI_EFFECTS) + .filter(([, declaration]) => declaration.brokerRead) + .map(([name]) => name), +); diff --git a/packages/core/src/bots/cli-genui.ts b/packages/core/src/bots/cli-genui.ts index 6229165c91..4df6b48ee0 100644 --- a/packages/core/src/bots/cli-genui.ts +++ b/packages/core/src/bots/cli-genui.ts @@ -1,3 +1,4 @@ +export { GENUI_OPTIONS } from './cli-option-spec.js'; import { readFileSync, statSync } from 'node:fs'; import { z } from 'zod'; import { genuiReplySchema, genuiViewSchema } from '../channels/genui.js'; @@ -5,10 +6,6 @@ import { genuiDocumentReplySchema, genuiDocumentStateSchema } from '../channels/ import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; -export const GENUI_OPTIONS = { - 'genui-file': { type: 'string' }, - 'genui-stdin': { type: 'boolean' }, -} as const; export const GENUI_COMMANDS = [ { command: 'genui-view', description: 'read your private GenUI view from the live Host' }, { diff --git a/packages/core/src/bots/cli-host-admin.ts b/packages/core/src/bots/cli-host-admin.ts index 13b277d8b7..8fc5aea7a5 100644 --- a/packages/core/src/bots/cli-host-admin.ts +++ b/packages/core/src/bots/cli-host-admin.ts @@ -1,3 +1,4 @@ +export { HOST_ADMIN_OPTIONS } from './cli-option-spec.js'; import type { AltchaChallenge } from '../marketplace/altcha.js'; import { parseChallenge, solveChallenge } from '../marketplace/altcha.js'; import type { MarketplaceDigestSummary } from '../marketplace/client.js'; @@ -6,25 +7,6 @@ import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; import { imageDataUrl, readBytes } from './cli-profile.js'; -export const HOST_ADMIN_OPTIONS = { - force: { type: 'boolean' }, - action: { type: 'string' }, - query: { type: 'string' }, - topic: { type: 'string' }, - sort: { type: 'string' }, - lang: { type: 'string' }, - reason: { type: 'string' }, - decision: { type: 'string' }, - capability: { type: 'string', multiple: true }, - confirm: { type: 'boolean' }, - 'accept-terms': { type: 'boolean' }, - 'include-uploads': { type: 'boolean' }, - review: { type: 'string' }, - replaces: { type: 'string' }, - day: { type: 'string' }, - version: { type: 'string' }, -} as const; - export interface HostAdminValues { force?: boolean; action?: string; diff --git a/packages/core/src/bots/cli-im-authorization.ts b/packages/core/src/bots/cli-im-authorization.ts index 6f71eb9e7f..453a1185b0 100644 --- a/packages/core/src/bots/cli-im-authorization.ts +++ b/packages/core/src/bots/cli-im-authorization.ts @@ -1,13 +1,8 @@ +export { IM_OPTIONS } from './cli-option-spec.js'; import { setTimeout as delay } from 'node:timers/promises'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; -export const IM_OPTIONS = { - 'credentials-stdin': { type: 'boolean' }, - 'verification-stdin': { type: 'boolean' }, - wait: { type: 'boolean' }, -} as const; - export const IM_COMMANDS = [ { command: 'im-apps', description: 'list live Provider IM application authorization flows' }, { diff --git a/packages/core/src/bots/cli-inbox.ts b/packages/core/src/bots/cli-inbox.ts index 7ace1050cd..483d32b6ed 100644 --- a/packages/core/src/bots/cli-inbox.ts +++ b/packages/core/src/bots/cli-inbox.ts @@ -1,32 +1,8 @@ +export { INBOX_OPTIONS } from './cli-option-spec.js'; +import { canonicalCliCommandName, legacyActivityCommandName } from './cli-command-names.js'; import { watchInbox } from './cli-inbox-watch.js'; import { CliLiveError } from './cli-live-error.js'; -export const INBOX_OPTIONS = { - notifications: { type: 'boolean' }, - category: { type: 'string' }, - 'watch-seconds': { type: 'string' }, - channel: { type: 'string' }, - request: { type: 'string' }, - sort: { type: 'string' }, - search: { type: 'string' }, - unread: { type: 'boolean' }, - 'source-key': { type: 'string' }, - source: { type: 'string' }, - section: { type: 'string' }, - unsectioned: { type: 'boolean' }, - index: { type: 'string' }, - archived: { type: 'boolean' }, - unarchived: { type: 'boolean' }, - rule: { type: 'string' }, - server: { type: 'string' }, - confirm: { type: 'boolean' }, - until: { type: 'string' }, - snoozed: { type: 'boolean' }, - dismissed: { type: 'boolean' }, - activity: { type: 'string' }, - 'include-archived': { type: 'boolean' }, -} as const; - export const INBOX_COMMANDS = [ { command: 'grant-request-approve', @@ -155,32 +131,17 @@ function usage(message: string): never { throw new CliLiveError('usage', message); } -const ACTIVITY_COMMAND_NAMES: Readonly> = { - activity: 'inbox', - 'activity-watch': 'inbox-watch', - 'activity-status': 'inbox-status', - 'activity-dismiss': 'inbox-dismiss', - 'activity-restore': 'inbox-restore', - 'activity-dismiss-all': 'inbox-dismiss-all', - 'activity-allow-once': 'inbox-allow-once', - 'activity-ignore': 'inbox-ignore', - 'activity-snooze': 'inbox-snooze', -}; -const LEGACY_INBOX_COMMANDS: ReadonlySet = new Set(Object.values(ACTIVITY_COMMAND_NAMES)); - -export function isActivityCommandName(command: string): boolean { - return LEGACY_INBOX_COMMANDS.has(command) || ACTIVITY_COMMAND_NAMES[command] !== undefined; -} +export { isActivityCliCommand as isActivityCommandName } from './cli-command-names.js'; function inboxCommandName(command: string): string { - return ACTIVITY_COMMAND_NAMES[command] ?? command; + return legacyActivityCommandName(command); } export function isInboxCommand(command: string): boolean { + const canonical = canonicalCliCommandName(command); return ( - LEGACY_INBOX_COMMANDS.has(command) || - INBOX_COMMANDS.some((entry) => entry.command === command) || - INBOX_HOST_COMMANDS.some((entry) => entry === command) + INBOX_COMMANDS.some((entry) => entry.command === canonical) || + INBOX_HOST_COMMANDS.some((entry) => entry === canonical) ); } diff --git a/packages/core/src/bots/cli-live.ts b/packages/core/src/bots/cli-live.ts index eff97a900c..8d5beeb6ad 100644 --- a/packages/core/src/bots/cli-live.ts +++ b/packages/core/src/bots/cli-live.ts @@ -1,7 +1,11 @@ +import { toolEffectLabels } from '../workspaces/tool-effect-labels.js'; +import type { ChannelMessage } from '../channels/channel.js'; + +export { LIVE_OPTIONS } from './cli-option-spec.js'; import { isLanAddress } from '../devices/lan-address.js'; -import { TEAM_COMMANDS, TEAM_OPTIONS, runTeamCommand } from './cli-team.js'; +import { TEAM_COMMANDS, runTeamCommand } from './cli-team.js'; import { runDeviceActivity } from './cli-live-activity.js'; -import { GENUI_COMMANDS, GENUI_OPTIONS, runGenuiCommand } from './cli-genui.js'; +import { GENUI_COMMANDS, runGenuiCommand } from './cli-genui.js'; import { HOST_LOOK_COMMANDS, runHostLook } from './cli-host-look.js'; import { PROFILE_BACKUP_COMMANDS, @@ -9,20 +13,15 @@ import { runProfileBackupCommand, } from './cli-profile-backup.js'; import { runPhoneNotifications } from './cli-phone-notifications.js'; -import { - WINDOW_ZOOM_COMMANDS, - WINDOW_ZOOM_OPTIONS, - runWindowZoomCommand, -} from './cli-window-zoom.js'; +import { WINDOW_ZOOM_COMMANDS, runWindowZoomCommand } from './cli-window-zoom.js'; import { DESKTOP_WINDOW_COMMANDS, runDesktopWindowCommand } from './cli-desktop-window.js'; -import { PRESENCE_COMMANDS, PRESENCE_OPTIONS, runPresenceCommand } from './cli-presence.js'; +import { PRESENCE_COMMANDS, runPresenceCommand } from './cli-presence.js'; import { PHONE_ROUTE_COMMANDS, runPhoneRouteCommand } from './cli-phone-route.js'; import { DEVICES_COMMANDS, isDevicesCommand, runDevicesCommand } from './cli-devices.js'; import { RELATIONSHIP_COMMANDS, runRelationshipCommand } from './cli-relationships.js'; import { DEVICE_CLIENT_COMMANDS, runDeviceClientCommand } from './cli-device-client.js'; import { DEVICE_NOTIFICATION_COMMANDS, - DEVICE_NOTIFICATION_OPTIONS, runDeviceNotifications, } from './cli-device-notifications.js'; import { @@ -33,7 +32,7 @@ import { FEEDBACK_COMMANDS, runFeedbackCommand } from './cli-feedback.js'; import { DIAGNOSTIC_LOG_COMMANDS, runDiagnosticLogCommand } from './cli-diagnostic-logs.js'; import { DOCTOR_COMMANDS, runDoctor } from './cli-doctor.js'; import { BUG_REPORT_COMMANDS, runBugReport } from './cli-bug-report.js'; -import { APPEARANCE_COMMANDS, APPEARANCE_OPTIONS, runAppearanceCommand } from './cli-appearance.js'; +import { APPEARANCE_COMMANDS, runAppearanceCommand } from './cli-appearance.js'; import { prepareCloud, prepareCloudWork } from './cli-cloud.js'; import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; @@ -44,43 +43,34 @@ import { resolveBotDm } from './cli-bot-dm.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; import { CONNECTION_COMMANDS, runConnectionCommand } from './cli-connection.js'; +import { TOB_CLI_COMMANDS, runTobCli } from './cli-tob.js'; import { BOT_TOOL_COMMANDS, runBotToolCommand } from './cli-bot-tool.js'; import { CALL_TIMELINE_COMMANDS, - CALL_TIMELINE_OPTIONS, isCallTimelineCommand, runCallTimelineCommand, } from './cli-call-timeline.js'; -import { - TAKEOVER_COMMANDS, - TAKEOVER_OPTIONS, - isTakeoverCommand, - runTakeoverCommand, -} from './cli-takeover.js'; +import { TAKEOVER_COMMANDS, isTakeoverCommand, runTakeoverCommand } from './cli-takeover.js'; import { channelOperationKey, CHANNEL_COMMANDS, - CHANNEL_OPTIONS, isChannelCommand, runChannelCommand, } from './cli-channels.js'; import { BROWSER_COMPUTER_COMMANDS, - BROWSER_COMPUTER_OPTIONS, isBrowserComputerCommand, runBrowserComputerCommand, type BrowserComputerValues, } from './cli-browser-computer.js'; import { IM_COMMANDS, - IM_OPTIONS, prepareImAuthorization, runImAuthorization, type ImValues, } from './cli-im-authorization.js'; import { MESSAGING_COMMANDS, - MESSAGING_OPTIONS, prepareMessaging, messagingReadMode, runMessaging, @@ -90,26 +80,17 @@ import { import { isModelsUsageCommand, MODELS_USAGE_COMMANDS, - MODELS_USAGE_OPTIONS, runModelsUsage, type ModelsUsageValues, } from './cli-models-usage.js'; import { HOST_ADMIN_COMMANDS, - HOST_ADMIN_OPTIONS, isHostAdminCommand, runHostAdminCommand, type HostAdminValues, } from './cli-host-admin.js'; +import { INBOX_COMMANDS, isInboxCommand, runInboxCommand, type InboxValues } from './cli-inbox.js'; import { - INBOX_COMMANDS, - INBOX_OPTIONS, - isInboxCommand, - runInboxCommand, - type InboxValues, -} from './cli-inbox.js'; -import { - SCHEDULE_OPTIONS, isScheduleCommand, prepareScheduleCommand, runScheduleCommand, @@ -117,60 +98,43 @@ import { } from './cli-schedules.js'; import { PROFILE_COMMANDS, - PROFILE_OPTIONS, isProfileCommand, runProfileCommand, type ProfileValues, } from './cli-profile.js'; -import { - TODO_COMMANDS, - TODO_OPTIONS, - isTodoCommand, - runTodoCommand, - type TodoValues, -} from './cli-todos.js'; +import { TODO_COMMANDS, isTodoCommand, runTodoCommand, type TodoValues } from './cli-todos.js'; import { APPROVAL_TEMPLATE_COMMANDS, - APPROVAL_TEMPLATE_OPTIONS, isApprovalTemplateCommand, runApprovalTemplateCommand, type ApprovalTemplateValues, } from './cli-approval-templates.js'; import { PROMPT_PRESET_COMMANDS, - PROMPT_PRESET_OPTIONS, isPromptPresetCommand, runPromptPresetCommand, } from './cli-prompt-presets.js'; import { APPROVAL_REVIEWER_COMMANDS, - APPROVAL_REVIEWER_OPTIONS, isApprovalReviewerCommand, runApprovalReviewerCommand, type ApprovalReviewerValues, } from './cli-approval-reviewer.js'; -import { - VOICE_COMMANDS, - VOICE_OPTIONS, - isVoiceCommand, - runVoiceCommand, - type VoiceValues, -} from './cli-voice.js'; -import { CALL_COMMANDS, CALL_OPTIONS, isCallCommand, runCallCommand } from './cli-call.js'; +import { VOICE_COMMANDS, isVoiceCommand, runVoiceCommand, type VoiceValues } from './cli-voice.js'; +import { CALL_COMMANDS, isCallCommand, runCallCommand } from './cli-call.js'; import { SKILL_COMMANDS, - SKILL_OPTIONS, isSkillCommand, runSkillCommand, skillInvocationTokens, type SkillValues, } from './cli-skills.js'; + import { VOICE_CALL_PATH, type VoiceCallResult } from '../voice/call-contract.js'; import { isStorageCommand, runStorageCommand, STORAGE_COMMANDS, - STORAGE_OPTIONS, type StorageValues, } from './cli-storage.js'; import { @@ -178,106 +142,14 @@ import { isIdleCompactionCommand, runIdleCompactionCommand, } from './cli-idle-compaction.js'; -import { - CONNECT_COMMANDS, - CONNECT_OPTIONS, - isConnectCommand, - runConnectCommand, -} from './cli-connect.js'; +import { CONNECT_COMMANDS, isConnectCommand, runConnectCommand } from './cli-connect.js'; import { isShareDraftCommand, runShareDraftCommand, SHARE_DRAFT_COMMANDS, - SHARE_DRAFT_OPTIONS, } from './cli-share-draft.js'; export { CliLiveError } from './cli-live-error.js'; -export const LIVE_OPTIONS = { - ...TEAM_OPTIONS, - ...GENUI_OPTIONS, - 'new-home': { type: 'string' }, - - 'connection-id': { type: 'string' }, - 'confirm-disconnect': { type: 'boolean' }, - handover: { type: 'string' }, - 'connection-route-id': { type: 'string' }, - fingerprint: { type: 'string' }, - 'link-file': { type: 'string' }, - 'account-file': { type: 'string' }, - 'remote-host-id': { type: 'string' }, - 'host-id': { type: 'string' }, - ...DEVICE_NOTIFICATION_OPTIONS, - 'activity-stdin': { type: 'boolean' }, - ...WINDOW_ZOOM_OPTIONS, - ...PRESENCE_OPTIONS, - ...CONNECT_OPTIONS, - ...APPEARANCE_OPTIONS, - ...IM_OPTIONS, - ...MESSAGING_OPTIONS, - ...MODELS_USAGE_OPTIONS, - ...CHANNEL_OPTIONS, - ...HOST_ADMIN_OPTIONS, - ...SHARE_DRAFT_OPTIONS, - ...INBOX_OPTIONS, - ...SCHEDULE_OPTIONS, - ...TAKEOVER_OPTIONS, - ...BROWSER_COMPUTER_OPTIONS, - ...PROFILE_OPTIONS, - ...TODO_OPTIONS, - ...APPROVAL_TEMPLATE_OPTIONS, - ...PROMPT_PRESET_OPTIONS, - ...APPROVAL_REVIEWER_OPTIONS, - ...VOICE_OPTIONS, - ...CALL_OPTIONS, - ...CALL_TIMELINE_OPTIONS, - ...STORAGE_OPTIONS, - ...SKILL_OPTIONS, - host: { type: 'string' }, - 'token-file': { type: 'string' }, - 'image-source': { type: 'string' }, - 'image-revision': { type: 'string' }, - 'image-reference': { type: 'string' }, - timeout: { type: 'string' }, - 'message-id': { type: 'string' }, - 'reply-to': { type: 'string' }, - 'failure-message-id': { type: 'string' }, - 'auto-continue-for': { type: 'string' }, - recovery: { type: 'string' }, - outcome: { type: 'string' }, - 'answer-stdin': { type: 'boolean' }, - 'values-stdin': { type: 'boolean' }, - since: { type: 'string' }, - hours: { type: 'string' }, - offline: { type: 'boolean' }, - workspace: { type: 'string' }, - mode: { type: 'string' }, - scope: { type: 'string' }, - 'acknowledge-risk': { type: 'boolean' }, - 'patch-stdin': { type: 'boolean' }, - refresh: { type: 'boolean' }, - 'previous-value': { type: 'string' }, - member: { type: 'string', multiple: true }, - attach: { type: 'string', multiple: true }, - app: { type: 'string' }, - bot: { type: 'string' }, - conversation: { type: 'string' }, - out: { type: 'string' }, - 'route-id': { type: 'string' }, - 'args-stdin': { type: 'boolean' }, - 'cause-event': { type: 'string' }, - session: { type: 'string' }, - turns: { type: 'string' }, - offset: { type: 'string' }, - kind: { type: 'string' }, - checkpoint: { type: 'string' }, - 'expected-current': { type: 'string' }, - 'restore-id': { type: 'string' }, - 'repair-id': { type: 'string' }, - 'default-location': { type: 'boolean' }, - tag: { type: 'string' }, - target: { type: 'string' }, -} as const; - const DEVICE_COMMANDS = [ 'browser-open', 'browser-frame', @@ -366,6 +238,7 @@ export const LIVE_COMMANDS = [ ...BROWSER_COMPUTER_COMMANDS, ...PROFILE_COMMANDS, ...BOT_TOOL_COMMANDS, + ...TOB_CLI_COMMANDS, ...TAKEOVER_COMMANDS, ...TODO_COMMANDS, ...APPROVAL_TEMPLATE_COMMANDS, @@ -1300,6 +1173,10 @@ export async function runLiveCli( return runTakeoverCommand(command, rest, values, () => connectLiveHost(values, io, AbortSignal.timeout(timeoutMs(values.timeout))), ); + if (command === 'tob-cli') + return runTobCli(rest, values, io, () => + connectLiveHost(values, io, AbortSignal.timeout(timeoutMs(values.timeout))), + ); if (BOT_TOOL_COMMANDS.some((entry) => entry.command === command)) return runBotToolCommand( command as (typeof BOT_TOOL_COMMANDS)[number]['command'], @@ -1659,11 +1536,26 @@ export async function runLiveCli( const limit = values.limit === undefined ? undefined : Number(values.limit); if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)) usage('--limit must be 1–200.'); - return rpc('channelMessages', { + const result = await rpc<{ messages: ChannelMessage[]; revision: number }>('channelMessages', { channelId: target, ...(limit === undefined ? {} : { limit }), ...(values.before === undefined ? {} : { before: values.before }), }); + return { + ...result, + messages: result.messages.map((message) => { + const effects = message.toolApprovalRequest?.effects; + return effects === undefined + ? message + : { + ...message, + effectLabels: { + en: toolEffectLabels(effects, 'en'), + zh: toolEffectLabels(effects, 'zh'), + }, + }; + }), + }; } if (command === 'tool-approval-status') return rpc('toolApprovalStatus', { channelId: target, messageId }); diff --git a/packages/core/src/bots/cli-messaging.ts b/packages/core/src/bots/cli-messaging.ts index d7d6a44689..f38c0ecd85 100644 --- a/packages/core/src/bots/cli-messaging.ts +++ b/packages/core/src/bots/cli-messaging.ts @@ -1,19 +1,8 @@ +export { MESSAGING_OPTIONS } from './cli-option-spec.js'; import { randomUUID } from 'node:crypto'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; -export const MESSAGING_OPTIONS = { - 'input-stdin': { type: 'boolean' }, - 'read-mode': { type: 'string' }, - confirm: { type: 'boolean' }, - binding: { type: 'string' }, - source: { type: 'string' }, - channel: { type: 'string' }, - pairing: { type: 'string' }, - delivery: { type: 'string' }, - 'request-id': { type: 'string' }, -} as const; - export const MESSAGING_COMMANDS = [ { command: 'messaging-defaults', diff --git a/packages/core/src/bots/cli-models-usage.ts b/packages/core/src/bots/cli-models-usage.ts index 7c4928ccc1..5f5f96dbd3 100644 --- a/packages/core/src/bots/cli-models-usage.ts +++ b/packages/core/src/bots/cli-models-usage.ts @@ -1,3 +1,4 @@ +export { MODELS_USAGE_OPTIONS } from './cli-option-spec.js'; import { resolveBotDm } from './cli-bot-dm.js'; import type { ModelPreset, ModelRoute } from '../models/presets.js'; import type { ModelPlanState } from '../models/readiness.js'; @@ -7,19 +8,6 @@ import { isUsageOverviewPeriod, usageOverviewPeriods } from '../usage/overview.j type Rpc = (method: string, args: Record) => Promise; -export const MODELS_USAGE_OPTIONS = { - 'expected-revision': { type: 'string' }, - 'plan-stdin': { type: 'boolean' }, - period: { type: 'string' }, - after: { type: 'string' }, - start: { type: 'string' }, - end: { type: 'string' }, - model: { type: 'string' }, - provider: { type: 'string' }, - purpose: { type: 'string' }, - weeks: { type: 'string' }, -} as const; - export const MODELS_USAGE_COMMANDS = [ { command: 'home-model-set', diff --git a/packages/core/src/bots/cli-option-spec.ts b/packages/core/src/bots/cli-option-spec.ts new file mode 100644 index 0000000000..b023239c06 --- /dev/null +++ b/packages/core/src/bots/cli-option-spec.ts @@ -0,0 +1,450 @@ +export const SKILL_OPTIONS = { + skill: { type: 'string', multiple: true }, + owner: { type: 'string' }, + confirm: { type: 'boolean' }, +} as const; + +export const APPROVAL_REVIEWER_OPTIONS = { + effort: { type: 'string' }, +} as const; + +export const APPROVAL_TEMPLATE_OPTIONS = { + from: { type: 'string' }, + 'delete-revision': { type: 'string' }, + blank: { type: 'boolean' }, + 'parts-file': { type: 'string' }, + 'apply-to': { type: 'string' }, + 'text-stdin': { type: 'boolean' }, + 'literal-template': { type: 'boolean' }, +} as const; + +export const BROWSER_COMPUTER_OPTIONS = { + permission: { type: 'string' }, + tab: { type: 'string' }, + profile: { type: 'string' }, + package: { type: 'string', multiple: true }, + confirm: { type: 'boolean' }, + 'token-stdin': { type: 'boolean' }, + dir: { type: 'string' }, + plugin: { type: 'string' }, + entity: { type: 'string' }, + viewer: { type: 'string' }, + probe: { type: 'boolean' }, +} as const; + +export const CALL_TIMELINE_OPTIONS = { + 'from-ms': { type: 'string' }, + 'to-ms': { type: 'string' }, +} as const; + +export const CALL_OPTIONS = { + script: { type: 'string' }, + 'reply-wait': { type: 'string' }, + video: { type: 'string' }, + screen: { type: 'string' }, + 'share-ends-at': { type: 'string' }, + 'share-pause': { type: 'string' }, +} as const; + +export const CHANNEL_OPTIONS = { + 'avatar-file': { type: 'string' }, + 'expected-channel': { type: 'string' }, + invitation: { type: 'string' }, + request: { type: 'string' }, + accept: { type: 'boolean' }, + decline: { type: 'boolean' }, + inherit: { type: 'boolean' }, + count: { type: 'string' }, + interval: { type: 'string' }, + direction: { type: 'string' }, + around: { type: 'string' }, + 'older-limit': { type: 'string' }, + 'newer-limit': { type: 'string' }, + through: { type: 'string' }, + since: { type: 'string' }, + epoch: { type: 'string' }, + 'source-event': { type: 'string', multiple: true }, + confirm: { type: 'boolean' }, + emoji: { type: 'string' }, + remove: { type: 'boolean' }, + off: { type: 'boolean' }, + attachment: { type: 'string' }, + representation: { type: 'string' }, +} as const; + +export const CONNECT_OPTIONS = { + 'expected-route-revision': { type: 'string' }, + hostname: { type: 'string' }, + 'token-stdin': { type: 'boolean' }, + wait: { type: 'boolean' }, + quick: { type: 'boolean' }, + origin: { type: 'string' }, + lan: { type: 'boolean' }, +} as const; + +export const DEVICE_NOTIFICATION_OPTIONS = { + 'metro-port': { type: 'string' }, + 'target-id': { type: 'string' }, + 'device-name': { type: 'string' }, + 'device-file': { type: 'string' }, + 'preferences-stdin': { type: 'boolean' }, + delivery: { type: 'string' }, +} as const; + +export const GENUI_OPTIONS = { + 'genui-file': { type: 'string' }, + 'genui-stdin': { type: 'boolean' }, +} as const; + +export const HOST_ADMIN_OPTIONS = { + force: { type: 'boolean' }, + action: { type: 'string' }, + query: { type: 'string' }, + topic: { type: 'string' }, + sort: { type: 'string' }, + lang: { type: 'string' }, + reason: { type: 'string' }, + decision: { type: 'string' }, + capability: { type: 'string', multiple: true }, + confirm: { type: 'boolean' }, + 'accept-terms': { type: 'boolean' }, + 'include-uploads': { type: 'boolean' }, + review: { type: 'string' }, + replaces: { type: 'string' }, + day: { type: 'string' }, + version: { type: 'string' }, +} as const; + +export const IM_OPTIONS = { + 'credentials-stdin': { type: 'boolean' }, + 'verification-stdin': { type: 'boolean' }, + wait: { type: 'boolean' }, +} as const; + +export const INBOX_OPTIONS = { + notifications: { type: 'boolean' }, + category: { type: 'string' }, + 'watch-seconds': { type: 'string' }, + channel: { type: 'string' }, + request: { type: 'string' }, + sort: { type: 'string' }, + search: { type: 'string' }, + unread: { type: 'boolean' }, + 'source-key': { type: 'string' }, + source: { type: 'string' }, + section: { type: 'string' }, + unsectioned: { type: 'boolean' }, + index: { type: 'string' }, + archived: { type: 'boolean' }, + unarchived: { type: 'boolean' }, + rule: { type: 'string' }, + server: { type: 'string' }, + confirm: { type: 'boolean' }, + until: { type: 'string' }, + snoozed: { type: 'boolean' }, + dismissed: { type: 'boolean' }, + activity: { type: 'string' }, + 'include-archived': { type: 'boolean' }, +} as const; + +export const MESSAGING_OPTIONS = { + 'input-stdin': { type: 'boolean' }, + 'read-mode': { type: 'string' }, + confirm: { type: 'boolean' }, + binding: { type: 'string' }, + source: { type: 'string' }, + channel: { type: 'string' }, + pairing: { type: 'string' }, + delivery: { type: 'string' }, + 'request-id': { type: 'string' }, +} as const; + +export const MODELS_USAGE_OPTIONS = { + 'expected-revision': { type: 'string' }, + 'plan-stdin': { type: 'boolean' }, + period: { type: 'string' }, + after: { type: 'string' }, + start: { type: 'string' }, + end: { type: 'string' }, + model: { type: 'string' }, + provider: { type: 'string' }, + purpose: { type: 'string' }, + weeks: { type: 'string' }, +} as const; + +export const PRESENCE_OPTIONS = { + active: { type: 'boolean' }, + idle: { type: 'boolean' }, +} as const; + +export const PROFILE_OPTIONS = { + file: { type: 'string' }, + 'recipe-stdin': { type: 'boolean' }, + 'part-stdin': { type: 'boolean' }, + color: { type: 'string' }, + automatic: { type: 'boolean' }, + 'source-class': { type: 'string' }, + wake: { type: 'string' }, + delivery: { type: 'string' }, + 'digest-count': { type: 'string' }, + 'digest-interval': { type: 'string' }, + soul: { type: 'string' }, + 'core-memory': { type: 'string' }, + section: { type: 'string' }, + confirm: { type: 'boolean' }, + slot: { type: 'string' }, + colors: { type: 'string' }, + parent: { type: 'string' }, + 'part-id': { type: 'string' }, +} as const; + +export const PROMPT_PRESET_OPTIONS = { + 'parts-stdin': { type: 'boolean' }, + 'prompt-limit': { type: 'string', multiple: true }, + 'expected-revision': { type: 'string' }, + confirm: { type: 'boolean' }, +} as const; + +export const SCHEDULE_OPTIONS = { + confirm: { type: 'boolean' }, +} as const; + +export const SHARE_DRAFT_OPTIONS = { + keep: { type: 'boolean' }, + drop: { type: 'boolean' }, + 'rewrite-stdin': { type: 'boolean' }, +} as const; + +export const SSH_OPTIONS = { + 'pairing-file': { type: 'string' }, + 'local-port': { type: 'string' }, + 'remote-port': { type: 'string' }, + 'ssh-config': { type: 'string' }, +} as const; + +export const STORAGE_OPTIONS = { + chat: { type: 'string', multiple: true }, + media: { type: 'string', multiple: true }, + 'older-than-days': { type: 'string' }, +} as const; + +export const TAKEOVER_OPTIONS = { + minutes: { type: 'string' }, + pending: { type: 'boolean' }, +} as const; + +export const TEAM_OPTIONS = { + private: { type: 'boolean' }, + public: { type: 'string' }, + 'proactive-dms': { type: 'string' }, + 'join-channels': { type: 'string' }, + 'speaker-context': { type: 'string' }, + 'policy-stdin': { type: 'boolean' }, + as: { type: 'string' }, + after: { type: 'string' }, + reason: { type: 'string' }, + audience: { type: 'string' }, + models: { type: 'string' }, + 'human-id': { type: 'string' }, + post: { type: 'string' }, + 'add-members': { type: 'string' }, + 'mention-all': { type: 'string' }, + 'add-bots': { type: 'string' }, + 'edit-details': { type: 'string' }, + to: { type: 'string' }, + preview: { type: 'boolean' }, + 'token-stdin': { type: 'boolean' }, + 'sign-out-others': { type: 'string' }, + permissions: { type: 'string' }, + set: { type: 'string' }, + revoke: { type: 'string' }, + 'role-ids': { type: 'string' }, + username: { type: 'string' }, + 'display-name': { type: 'string' }, + 'initial-password-file': { type: 'string' }, + 'password-stdin': { type: 'boolean' }, +} as const; + +export const TODO_OPTIONS = { + done: { type: 'boolean' }, + 'not-done': { type: 'boolean' }, +} as const; + +export const VOICE_OPTIONS = { + 'base-url': { type: 'string' }, + 'key-stdin': { type: 'boolean' }, + voice: { type: 'string' }, + text: { type: 'string' }, + markdown: { type: 'boolean' }, + language: { type: 'string' }, +} as const; + +export const WALLPAPER_OPTIONS = { + 'wallpaper-item': { type: 'string' }, +} as const; + +export const WINDOW_ZOOM_OPTIONS = { + 'client-id': { type: 'string' }, + 'zoom-level': { type: 'string' }, + 'zoom-default': { type: 'boolean' }, +} as const; + +export const ZIP_UPLOAD_OPTIONS = { + 'upload-key': { type: 'string' }, + 'archive-sha256': { type: 'string' }, + 'archive-size': { type: 'string' }, +} as const; + +export const APPEARANCE_OPTIONS = { + ...WALLPAPER_OPTIONS, + 'client-id': { type: 'string' }, + 'confirm-reset': { type: 'boolean' }, + 'expected-wallpaper-revision': { type: 'string' }, +} as const; + +export const LIVE_OPTIONS = { + ...TEAM_OPTIONS, + ...GENUI_OPTIONS, + 'new-home': { type: 'string' }, + + 'connection-id': { type: 'string' }, + 'confirm-disconnect': { type: 'boolean' }, + handover: { type: 'string' }, + 'connection-route-id': { type: 'string' }, + fingerprint: { type: 'string' }, + 'link-file': { type: 'string' }, + 'account-file': { type: 'string' }, + 'remote-host-id': { type: 'string' }, + 'host-id': { type: 'string' }, + ...DEVICE_NOTIFICATION_OPTIONS, + 'activity-stdin': { type: 'boolean' }, + ...WINDOW_ZOOM_OPTIONS, + ...PRESENCE_OPTIONS, + ...CONNECT_OPTIONS, + ...APPEARANCE_OPTIONS, + ...IM_OPTIONS, + ...MESSAGING_OPTIONS, + ...MODELS_USAGE_OPTIONS, + ...CHANNEL_OPTIONS, + ...HOST_ADMIN_OPTIONS, + ...SHARE_DRAFT_OPTIONS, + ...INBOX_OPTIONS, + ...SCHEDULE_OPTIONS, + ...TAKEOVER_OPTIONS, + ...BROWSER_COMPUTER_OPTIONS, + ...PROFILE_OPTIONS, + ...TODO_OPTIONS, + ...APPROVAL_TEMPLATE_OPTIONS, + ...PROMPT_PRESET_OPTIONS, + ...APPROVAL_REVIEWER_OPTIONS, + ...VOICE_OPTIONS, + ...CALL_OPTIONS, + ...CALL_TIMELINE_OPTIONS, + ...STORAGE_OPTIONS, + ...SKILL_OPTIONS, + host: { type: 'string' }, + 'token-file': { type: 'string' }, + 'image-source': { type: 'string' }, + 'image-revision': { type: 'string' }, + 'image-reference': { type: 'string' }, + timeout: { type: 'string' }, + 'message-id': { type: 'string' }, + 'reply-to': { type: 'string' }, + 'failure-message-id': { type: 'string' }, + 'auto-continue-for': { type: 'string' }, + recovery: { type: 'string' }, + outcome: { type: 'string' }, + 'answer-stdin': { type: 'boolean' }, + 'values-stdin': { type: 'boolean' }, + since: { type: 'string' }, + hours: { type: 'string' }, + offline: { type: 'boolean' }, + workspace: { type: 'string' }, + mode: { type: 'string' }, + scope: { type: 'string' }, + 'acknowledge-risk': { type: 'boolean' }, + 'patch-stdin': { type: 'boolean' }, + refresh: { type: 'boolean' }, + 'previous-value': { type: 'string' }, + member: { type: 'string', multiple: true }, + attach: { type: 'string', multiple: true }, + app: { type: 'string' }, + bot: { type: 'string' }, + conversation: { type: 'string' }, + out: { type: 'string' }, + 'route-id': { type: 'string' }, + 'args-stdin': { type: 'boolean' }, + 'cause-event': { type: 'string' }, + session: { type: 'string' }, + turns: { type: 'string' }, + offset: { type: 'string' }, + kind: { type: 'string' }, + checkpoint: { type: 'string' }, + 'expected-current': { type: 'string' }, + 'restore-id': { type: 'string' }, + 'repair-id': { type: 'string' }, + 'default-location': { type: 'boolean' }, + tag: { type: 'string' }, + target: { type: 'string' }, +} as const; + +export const BOT_CLI_OPTIONS = { + administration: { type: 'boolean' }, + name: { type: 'string' }, + persona: { type: 'string' }, + 'persona-stdin': { type: 'boolean' }, + 'core-memory-stdin': { type: 'boolean' }, + description: { type: 'string' }, + role: { type: 'string', multiple: true }, + preset: { type: 'string' }, + 'preset-revision': { type: 'string' }, + 'operation-key': { type: 'string' }, + ...ZIP_UPLOAD_OPTIONS, + 'expected-profile': { type: 'string' }, + 'erase-memory': { type: 'boolean' }, + 'from-zip': { type: 'string' }, + 'from-dir': { type: 'string' }, + 'from-git': { type: 'string' }, + 'expected-commit': { type: 'string' }, + 'memory-location': { type: 'string' }, + home: { type: 'string' }, + 'orchestrator-provider': { type: 'string' }, + 'orchestrator-model': { type: 'string' }, + 'orchestrator-effort': { type: 'string' }, + 'assignment-provider': { type: 'string' }, + 'assignment-model': { type: 'string' }, + 'assignment-effort': { type: 'string' }, + nickname: { type: 'string' }, + clear: { type: 'boolean' }, + path: { type: 'string' }, + body: { type: 'string' }, + 'body-stdin': { type: 'boolean' }, + 'expected-head': { type: 'string' }, + 'edit-id': { type: 'string' }, + limit: { type: 'string' }, + sha: { type: 'string' }, + before: { type: 'string' }, + cursor: { type: 'string' }, + state: { type: 'string' }, + 'confirmation-stdin': { type: 'boolean' }, + grant: { type: 'string' }, + enabled: { type: 'boolean' }, + disabled: { type: 'boolean' }, + locked: { type: 'boolean' }, + unlocked: { type: 'boolean' }, + title: { type: 'string' }, + prompt: { type: 'string' }, + sid: { type: 'string' }, + every: { type: 'string' }, + daily: { type: 'string' }, + weekly: { type: 'string' }, + weekdays: { type: 'string' }, + 'once-date': { type: 'string' }, + 'once-time': { type: 'string' }, + cron: { type: 'string' }, + timezone: { type: 'string' }, + ...LIVE_OPTIONS, + ...SSH_OPTIONS, + compact: { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, +} as const; diff --git a/packages/core/src/bots/cli-options.ts b/packages/core/src/bots/cli-options.ts index 09a9430c08..68ab43e19e 100644 --- a/packages/core/src/bots/cli-options.ts +++ b/packages/core/src/bots/cli-options.ts @@ -1,68 +1,5 @@ +import { BOT_CLI_OPTIONS } from './cli-option-spec.js'; import { parseArgs } from 'node:util'; -import { ZIP_UPLOAD_OPTIONS } from './cli-zip-upload.js'; -import { LIVE_OPTIONS } from './cli-live.js'; -import { SSH_OPTIONS } from './cli-ssh.js'; - -const BOT_CLI_OPTIONS = { - administration: { type: 'boolean' }, - name: { type: 'string' }, - persona: { type: 'string' }, - 'persona-stdin': { type: 'boolean' }, - 'core-memory-stdin': { type: 'boolean' }, - description: { type: 'string' }, - role: { type: 'string', multiple: true }, - preset: { type: 'string' }, - 'preset-revision': { type: 'string' }, - 'operation-key': { type: 'string' }, - ...ZIP_UPLOAD_OPTIONS, - 'expected-profile': { type: 'string' }, - 'erase-memory': { type: 'boolean' }, - 'from-zip': { type: 'string' }, - 'from-dir': { type: 'string' }, - 'from-git': { type: 'string' }, - 'expected-commit': { type: 'string' }, - 'memory-location': { type: 'string' }, - home: { type: 'string' }, - 'orchestrator-provider': { type: 'string' }, - 'orchestrator-model': { type: 'string' }, - 'orchestrator-effort': { type: 'string' }, - 'assignment-provider': { type: 'string' }, - 'assignment-model': { type: 'string' }, - 'assignment-effort': { type: 'string' }, - nickname: { type: 'string' }, - clear: { type: 'boolean' }, - path: { type: 'string' }, - body: { type: 'string' }, - 'body-stdin': { type: 'boolean' }, - 'expected-head': { type: 'string' }, - 'edit-id': { type: 'string' }, - limit: { type: 'string' }, - sha: { type: 'string' }, - before: { type: 'string' }, - cursor: { type: 'string' }, - state: { type: 'string' }, - 'confirmation-stdin': { type: 'boolean' }, - grant: { type: 'string' }, - enabled: { type: 'boolean' }, - disabled: { type: 'boolean' }, - locked: { type: 'boolean' }, - unlocked: { type: 'boolean' }, - title: { type: 'string' }, - prompt: { type: 'string' }, - sid: { type: 'string' }, - every: { type: 'string' }, - daily: { type: 'string' }, - weekly: { type: 'string' }, - weekdays: { type: 'string' }, - 'once-date': { type: 'string' }, - 'once-time': { type: 'string' }, - cron: { type: 'string' }, - timezone: { type: 'string' }, - ...LIVE_OPTIONS, - ...SSH_OPTIONS, - compact: { type: 'boolean' }, - help: { type: 'boolean', short: 'h' }, -} as const; export function parseBotCliArgs(argv: readonly string[]) { return parseArgs({ diff --git a/packages/core/src/bots/cli-presence.ts b/packages/core/src/bots/cli-presence.ts index cec69ffffa..38a13d0b24 100644 --- a/packages/core/src/bots/cli-presence.ts +++ b/packages/core/src/bots/cli-presence.ts @@ -1,3 +1,4 @@ +export { PRESENCE_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; export const PRESENCE_COMMANDS = [ { @@ -9,10 +10,7 @@ export const PRESENCE_COMMANDS = [ description: 'report --client-id as --active (90 s lease) or --idle', }, ] as const; -export const PRESENCE_OPTIONS = { - active: { type: 'boolean' }, - idle: { type: 'boolean' }, -} as const; + export async function runPresenceCommand( command: string, rest: string[], diff --git a/packages/core/src/bots/cli-profile.ts b/packages/core/src/bots/cli-profile.ts index 9b9868aef7..f0db3d4705 100644 --- a/packages/core/src/bots/cli-profile.ts +++ b/packages/core/src/bots/cli-profile.ts @@ -1,29 +1,9 @@ +export { PROFILE_OPTIONS } from './cli-option-spec.js'; import { readFileSync, writeFileSync } from 'node:fs'; import { resolveBotDm } from './cli-bot-dm.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; -export const PROFILE_OPTIONS = { - file: { type: 'string' }, - 'recipe-stdin': { type: 'boolean' }, - 'part-stdin': { type: 'boolean' }, - color: { type: 'string' }, - automatic: { type: 'boolean' }, - 'source-class': { type: 'string' }, - wake: { type: 'string' }, - delivery: { type: 'string' }, - 'digest-count': { type: 'string' }, - 'digest-interval': { type: 'string' }, - soul: { type: 'string' }, - 'core-memory': { type: 'string' }, - section: { type: 'string' }, - confirm: { type: 'boolean' }, - slot: { type: 'string' }, - colors: { type: 'string' }, - parent: { type: 'string' }, - 'part-id': { type: 'string' }, -} as const; - export const PROFILE_COMMANDS = [ { command: 'bot-avatar-set', description: "set a Bot's avatar image from a file, or --clear it" }, { diff --git a/packages/core/src/bots/cli-prompt-presets.ts b/packages/core/src/bots/cli-prompt-presets.ts index 1f6ccf9d7e..d1d0c62667 100644 --- a/packages/core/src/bots/cli-prompt-presets.ts +++ b/packages/core/src/bots/cli-prompt-presets.ts @@ -1,15 +1,9 @@ +export { PROMPT_PRESET_OPTIONS } from './cli-option-spec.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; type Rpc = (method: string, payload: Record) => Promise; -export const PROMPT_PRESET_OPTIONS = { - 'parts-stdin': { type: 'boolean' }, - 'prompt-limit': { type: 'string', multiple: true }, - 'expected-revision': { type: 'string' }, - confirm: { type: 'boolean' }, -} as const; - export interface PromptPresetValues { name?: string; preset?: string; diff --git a/packages/core/src/bots/cli-schedules.ts b/packages/core/src/bots/cli-schedules.ts index 337c88e241..700eb60356 100644 --- a/packages/core/src/bots/cli-schedules.ts +++ b/packages/core/src/bots/cli-schedules.ts @@ -1,10 +1,7 @@ +export { SCHEDULE_OPTIONS } from './cli-option-spec.js'; import type { BotScheduleTrigger } from '../schedules/bot-schedules.js'; import { CliLiveError } from './cli-live-error.js'; -export const SCHEDULE_OPTIONS = { - confirm: { type: 'boolean' }, -} as const; - export const SCHEDULE_COMMANDS = [ 'schedules', 'schedule-create', diff --git a/packages/core/src/bots/cli-share-draft.ts b/packages/core/src/bots/cli-share-draft.ts index 657c23a1c7..0d5e05d6a6 100644 --- a/packages/core/src/bots/cli-share-draft.ts +++ b/packages/core/src/bots/cli-share-draft.ts @@ -1,3 +1,5 @@ +export { SHARE_DRAFT_OPTIONS } from './cli-option-spec.js'; +import { SHARE_DRAFT_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; export const SHARE_DRAFT_COMMANDS = [ @@ -27,12 +29,6 @@ export const SHARE_DRAFT_COMMANDS = [ }, ] as const; -export const SHARE_DRAFT_OPTIONS = { - keep: { type: 'boolean' }, - drop: { type: 'boolean' }, - 'rewrite-stdin': { type: 'boolean' }, -} as const; - export const TOB_SHARE_DRAFT_COMMAND_USAGE: Readonly> = { 'share-draft-show': 'deepseekbot share-draft-show ', 'share-draft-file': 'deepseekbot share-draft-file --path ', diff --git a/packages/core/src/bots/cli-skills.ts b/packages/core/src/bots/cli-skills.ts index 67fd15c47b..7e3587ca2b 100644 --- a/packages/core/src/bots/cli-skills.ts +++ b/packages/core/src/bots/cli-skills.ts @@ -5,11 +5,7 @@ import { CliLiveError } from './cli-live-error.js'; type Rpc = (method: string, payload: Record) => Promise; -export const SKILL_OPTIONS = { - skill: { type: 'string', multiple: true }, - owner: { type: 'string' }, - confirm: { type: 'boolean' }, -} as const; +export { SKILL_OPTIONS } from './cli-option-spec.js'; export interface SkillValues { bot?: string; diff --git a/packages/core/src/bots/cli-ssh.ts b/packages/core/src/bots/cli-ssh.ts index 32c2cbf7c5..ccdf7fad02 100644 --- a/packages/core/src/bots/cli-ssh.ts +++ b/packages/core/src/bots/cli-ssh.ts @@ -1,3 +1,4 @@ +export { SSH_OPTIONS } from './cli-option-spec.js'; import { closeSync, fstatSync, openSync, readFileSync, writeFileSync } from 'node:fs'; import { isAbsolute } from 'node:path'; import { noiseFingerprint, NOISE_PROTOCOL } from '../devices/noise/xk.js'; @@ -13,13 +14,6 @@ export const SSH_COMMANDS = [ }, ] as const; -export const SSH_OPTIONS = { - 'pairing-file': { type: 'string' }, - 'local-port': { type: 'string' }, - 'remote-port': { type: 'string' }, - 'ssh-config': { type: 'string' }, -} as const; - function record(value: unknown): Record { return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record) diff --git a/packages/core/src/bots/cli-storage.ts b/packages/core/src/bots/cli-storage.ts index adf6972831..045eb242ce 100644 --- a/packages/core/src/bots/cli-storage.ts +++ b/packages/core/src/bots/cli-storage.ts @@ -1,15 +1,10 @@ +export { STORAGE_OPTIONS } from './cli-option-spec.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; import { STORAGE_MEDIA_KINDS, type StorageMediaKind } from '../storage/media-cleanup.js'; type Rpc = (method: string, payload: Record) => Promise; -export const STORAGE_OPTIONS = { - chat: { type: 'string', multiple: true }, - media: { type: 'string', multiple: true }, - 'older-than-days': { type: 'string' }, -} as const; - export const STORAGE_COMMANDS = [ { command: 'storage-usage', diff --git a/packages/core/src/bots/cli-takeover.ts b/packages/core/src/bots/cli-takeover.ts index 4d912d7530..63903e80ba 100644 --- a/packages/core/src/bots/cli-takeover.ts +++ b/packages/core/src/bots/cli-takeover.ts @@ -1,10 +1,6 @@ +export { TAKEOVER_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; -export const TAKEOVER_OPTIONS = { - minutes: { type: 'string' }, - pending: { type: 'boolean' }, -} as const; - export const TAKEOVER_COMMANDS = [ { command: 'takeovers', diff --git a/packages/core/src/bots/cli-team.ts b/packages/core/src/bots/cli-team.ts index 1f591976cd..e86aa58f47 100644 --- a/packages/core/src/bots/cli-team.ts +++ b/packages/core/src/bots/cli-team.ts @@ -1,4 +1,6 @@ +export { TEAM_OPTIONS } from './cli-option-spec.js'; import { botVisibilitySchema, rolePolicySchema } from '../team/bot-contract.js'; + import { privateKindSchema } from '../team/private-contract.js'; import { spaceAudienceSchema } from '../workspaces/spaces.js'; import { @@ -11,38 +13,6 @@ import { z } from 'zod'; import { CliLiveError } from './cli-live-error.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; -export const TEAM_OPTIONS = { - private: { type: 'boolean' }, - public: { type: 'string' }, - 'proactive-dms': { type: 'string' }, - 'join-channels': { type: 'string' }, - 'speaker-context': { type: 'string' }, - 'policy-stdin': { type: 'boolean' }, - topic: { type: 'string' }, - as: { type: 'string' }, - after: { type: 'string' }, - reason: { type: 'string' }, - audience: { type: 'string' }, - models: { type: 'string' }, - 'human-id': { type: 'string' }, - post: { type: 'string' }, - 'add-members': { type: 'string' }, - 'mention-all': { type: 'string' }, - 'add-bots': { type: 'string' }, - 'edit-details': { type: 'string' }, - to: { type: 'string' }, - preview: { type: 'boolean' }, - 'token-stdin': { type: 'boolean' }, - 'sign-out-others': { type: 'string' }, - permissions: { type: 'string' }, - set: { type: 'string' }, - revoke: { type: 'string' }, - 'role-ids': { type: 'string' }, - username: { type: 'string' }, - 'display-name': { type: 'string' }, - 'initial-password-file': { type: 'string' }, - 'password-stdin': { type: 'boolean' }, -} as const; export const TEAM_COMMANDS = [ { command: 'bot-access', diff --git a/packages/core/src/bots/cli-tob.ts b/packages/core/src/bots/cli-tob.ts new file mode 100644 index 0000000000..9439766f26 --- /dev/null +++ b/packages/core/src/bots/cli-tob.ts @@ -0,0 +1,48 @@ +import type { BotCreateCliIo } from './bot-create-cli.js'; +import { CliLiveError } from './cli-live-error.js'; +import { tobCliCommandSchema } from '../tob/cli-request.js'; + +export const TOB_CLI_COMMANDS = [ + { + command: 'tob-cli', + tool: 'deepseekbot_cli', + description: 'start, inspect or cancel an owned model-free Tob CLI request', + }, +] as const; +export async function runTobCli( + rest: string[], + values: { 'args-stdin'?: boolean }, + io: BotCreateCliIo, + connect: () => Promise<{ rpc: (method: string, args: Record) => Promise }>, +): Promise { + const allowed = new Set(['host', 'token-file', 'timeout', 'compact', 'args-stdin']); + if (Object.entries(values).some(([key, value]) => value !== undefined && !allowed.has(key))) + throw new CliLiveError( + 'agent-scope-denied', + 'Tob CLI requests do not accept authority-selection or unrelated flags.', + ); + const [action, id] = rest; + if (action === 'start' && rest.length === 1 && values['args-stdin'] === true) { + let input: unknown; + try { + input = JSON.parse((await io.readStdin?.()) ?? ''); + } catch { + throw new CliLiveError('usage', '--args-stdin must contain a typed CLI request.'); + } + const parsed = tobCliCommandSchema.safeParse(input); + if (!parsed.success) + throw new CliLiveError( + 'invalid-input', + 'Expected bounded argv and optional stdin; actor, source, Session and cwd are not accepted.', + ); + return (await connect()).rpc('tobCli', { action, command: parsed.data }); + } + if ( + (action === 'status' || action === 'cancel') && + rest.length === 2 && + id && + values['args-stdin'] !== true + ) + return (await connect()).rpc('tobCli', { action, id }); + throw new CliLiveError('usage', 'Use tob-cli start --args-stdin, status , or cancel .'); +} diff --git a/packages/core/src/bots/cli-todos.ts b/packages/core/src/bots/cli-todos.ts index 2472a3263c..6ba01a8842 100644 --- a/packages/core/src/bots/cli-todos.ts +++ b/packages/core/src/bots/cli-todos.ts @@ -1,14 +1,10 @@ +export { TODO_OPTIONS } from './cli-option-spec.js'; import type { BotCreateCliIo } from './bot-create-cli.js'; import { CliLiveError } from './cli-live-error.js'; import type { connectLiveHost } from './cli-live.js'; type LiveHost = Awaited>; -export const TODO_OPTIONS = { - done: { type: 'boolean' }, - 'not-done': { type: 'boolean' }, -} as const; - export const TODO_COMMANDS = [ { command: 'todos', description: 'list the shared to-do list (needs the to-do plugin)' }, { command: 'todo-add', description: 'add a to-do as the Human (--title)' }, diff --git a/packages/core/src/bots/cli-voice.ts b/packages/core/src/bots/cli-voice.ts index 94ee176d35..d034c86a97 100644 --- a/packages/core/src/bots/cli-voice.ts +++ b/packages/core/src/bots/cli-voice.ts @@ -1,3 +1,4 @@ +export { VOICE_OPTIONS } from './cli-option-spec.js'; import { readFileSync, writeFileSync } from 'node:fs'; import { isAbsolute } from 'node:path'; @@ -9,15 +10,6 @@ import { CliLiveError } from './cli-live-error.js'; type Rpc = (method: string, payload: Record) => Promise; -export const VOICE_OPTIONS = { - 'base-url': { type: 'string' }, - 'key-stdin': { type: 'boolean' }, - voice: { type: 'string' }, - text: { type: 'string' }, - markdown: { type: 'boolean' }, - language: { type: 'string' }, -} as const; - export interface VoiceValues { dir?: string; bot?: string; diff --git a/packages/core/src/bots/cli-wallpaper.ts b/packages/core/src/bots/cli-wallpaper.ts index 57b6ef30ca..2f908ea6da 100644 --- a/packages/core/src/bots/cli-wallpaper.ts +++ b/packages/core/src/bots/cli-wallpaper.ts @@ -1,3 +1,4 @@ +export { WALLPAPER_OPTIONS } from './cli-option-spec.js'; import { readFileSync, statSync } from 'node:fs'; import { resolve } from 'node:path'; import { CliLiveError } from './cli-live-error.js'; @@ -32,9 +33,7 @@ export const WALLPAPER_COMMANDS = [ 'set {interval,shuffle} from --patch-stdin; interval is 0 or 60000/300000/900000/1800000/3600000 ms', }, ] as const; -export const WALLPAPER_OPTIONS = { - 'wallpaper-item': { type: 'string' }, -} as const; + export async function runWallpaperCommand( command: string, rest: string[], diff --git a/packages/core/src/bots/cli-window-zoom.ts b/packages/core/src/bots/cli-window-zoom.ts index f91cb28625..043d268dd9 100644 --- a/packages/core/src/bots/cli-window-zoom.ts +++ b/packages/core/src/bots/cli-window-zoom.ts @@ -1,3 +1,4 @@ +export { WINDOW_ZOOM_OPTIONS } from './cli-option-spec.js'; import { CliLiveError } from './cli-live-error.js'; export const WINDOW_ZOOM_COMMANDS = [ { command: 'window-zoom-clients', description: 'list active desktop window targets' }, @@ -29,11 +30,7 @@ const SETUP_ACTIONS: Record = { 'window-zoom-setup-disable': 'disable', 'window-zoom-setup-cancel': 'cancel', }; -export const WINDOW_ZOOM_OPTIONS = { - 'client-id': { type: 'string' }, - 'zoom-level': { type: 'string' }, - 'zoom-default': { type: 'boolean' }, -} as const; + export async function runWindowZoomCommand( command: string, rest: string[], diff --git a/packages/core/src/bots/cli-zip-upload.ts b/packages/core/src/bots/cli-zip-upload.ts index c32b799460..2d10a4ed7d 100644 --- a/packages/core/src/bots/cli-zip-upload.ts +++ b/packages/core/src/bots/cli-zip-upload.ts @@ -1,3 +1,4 @@ +export { ZIP_UPLOAD_OPTIONS } from './cli-option-spec.js'; import { createHash } from 'node:crypto'; import { readFileSync, statSync } from 'node:fs'; import type { BotCreateCliIo, CreateValues } from './bot-create-cli.js'; @@ -13,11 +14,6 @@ export const ZIP_UPLOAD_COMMANDS = [ 'bot-zip-import', 'bot-zip-import-status', ] as const; -export const ZIP_UPLOAD_OPTIONS = { - 'upload-key': { type: 'string' }, - 'archive-sha256': { type: 'string' }, - 'archive-size': { type: 'string' }, -} as const; export async function runZipUploadCli( command: string, diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index c8952e4500..9c47122d52 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -1,3 +1,5 @@ +import { ApprovalTemplateDeletion } from '../workspaces/approval-template-deletion.js'; +import type { ApprovalTemplateDeletionPreview } from '../workspaces/approval-template-deletion-contract.js'; import type { ApprovalCard } from '../team/approval-contract.js'; import { requireBotModel, botModelAllowed } from '../team/models.js'; import { TeamError } from '../team/error.js'; @@ -5,7 +7,7 @@ import type { UsageByMemberResult } from '../usage/overview.js'; import { MEMBER_CHANNEL_METHODS } from '../team/member-methods.js'; import type { TeamChannels } from '../team/channels.js'; import { guardHumanBridge } from '../team/bridge-access.js'; -import { botOwner, privateBotRegistry } from '../team/bot-access.js'; +import { botOwner, ownsBot, privateBotRegistry } from '../team/bot-access.js'; import { privateBotCreations } from '../bots/creation.js'; import { createHash } from 'node:crypto'; import { createTeamBridge, type TeamBridgeMethods } from '../team/bridge.js'; @@ -249,6 +251,7 @@ import type { AttachmentStore } from '../attachments/store.js'; import { randomUUID } from 'node:crypto'; import { z } from 'zod'; +import { tobCliRequestSchema, type TobCliStatus } from '../tob/cli-request.js'; import { TakeoverError, type TakeoverHandoff } from '../takeover/contracts.js'; import type { TakeoverHandoffs } from '../takeover/handoffs.js'; @@ -930,6 +933,7 @@ export interface BridgeMethods extends TeamBridgeMethods { messageSearch(payload: unknown): BridgeResult; channelMessages(payload: unknown): BridgeResult<{ messages: ChannelMessage[]; revision: number }>; channelAllBotPreview(payload: unknown): BridgeResult; + tobCli(payload: unknown): Promise>; channelSkillCatalog(payload: unknown): Promise>; botSkills(payload: unknown): Promise>; skillShow(payload: unknown): Promise>; @@ -1123,9 +1127,15 @@ export interface BridgeMethods extends TeamBridgeMethods { promptGlobalSet(payload: unknown): BridgeResult<{ presetId: string | null }>; botPrompt(payload: unknown): BridgeResult; botPromptSet(payload: unknown): BridgeResult; - approvalTemplateDelete( + approvalTemplateDeletePreview( payload: unknown, - ): BridgeResult<{ template: { name: string }; clearedBots: string[] }>; + ): BridgeResult<{ preview: ApprovalTemplateDeletionPreview }>; + approvalTemplateDelete(payload: unknown): BridgeResult<{ + template: { name: string }; + clearedBots: string[]; + inheritedBots: string[]; + globalDefault: string | null; + }>; approvalTemplateGlobalSet(payload: unknown): BridgeResult<{ template: string | null }>; botApprovalTemplateSet(payload: unknown): BridgeResult<{ bot: PersonaBotDetail }>; voiceProviders: VoiceBridgeMethods['voiceProviders']; @@ -1723,6 +1733,38 @@ function scheduleFailure(error: unknown): BridgeResult { return invalidInput(String(error)); } +function templateDeletionFailure( + name: string, + reason: Extract, { ok: false }>['reason'], +): BridgeResult { + if (reason === 'invalid-name' || reason === 'not-found' || reason === 'built-in') + return templateWriteFailure(name, reason); + const errors = { + 'selection-unavailable': [ + 'approval-selection-unavailable', + 'Approval template selection could not be read.', + ], + 'confirmation-required': [ + 'confirmation-required', + 'Preview the deletion and confirm its revision before deleting.', + ], + changed: [ + 'approval-template-delete-changed', + 'Template references or selection changed. Preview the deletion again.', + ], + unavailable: [ + 'approval-template-delete-unavailable', + 'The template could not be deleted. Reload its current references.', + ], + 'rollback-failed': [ + 'approval-template-delete-incomplete', + 'Deletion did not complete. Reload the current template choices.', + ], + } as const; + const [code, message] = errors[reason]; + return { ok: false, error: { code, message } }; +} + function templateWriteFailure( name: string, reason: Extract['reason'], @@ -1790,6 +1832,11 @@ function dmAdmissionFailure( }; case 'blank-body': return invalidInput('body is required'); + case 'cli-request-expired': + return { + ok: false, + error: { code: reason, message: 'Typed CLI requests cannot be replayed.' }, + }; case 'runtime-closed': return { ok: false, @@ -2345,6 +2392,11 @@ function buildBridgeMethods( } const approvalTemplateLibrary = deps.approvalTemplates ?? createApprovalTemplateLibrary(); + const templateDeletion = new ApprovalTemplateDeletion( + approvalTemplateLibrary, + globalRegistry, + (bot) => ownsBot(human, bot), + ); const templateUsers = (name: string, registry = deps.registry): string[] => registry .list() @@ -3291,6 +3343,28 @@ function buildBridgeMethods( }; }); }, + async tobCli(payload) { + if (!isHostOwner()) + return { + ok: false, + error: { code: 'permission-required', message: 'Host owner authentication is required.' }, + }; + const parsed = tobCliRequestSchema.safeParse(payload); + if (!parsed.success) return invalidInput('Invalid bounded Tob CLI request'); + if (!deps.runtime?.tobCli) return unavailable(); + try { + return { ok: true, value: await deps.runtime.tobCli(human, parsed.data) }; + } catch (error) { + return { + ok: false, + error: { + code: error instanceof TobError ? error.code : 'operation-failed', + message: + error instanceof TobError ? error.code : 'The Tob CLI request could not complete.', + }, + }; + } + }, async tobHome() { if (!isHostOwner()) return { ok: true, value: { available: false as const } }; if (!deps.tob) return unavailable(); @@ -5459,18 +5533,34 @@ function buildBridgeMethods( if (!result.ok) return unknownBot(slug); return { ok: true, value: botPromptView(deps, prompts, slug) }; }, - approvalTemplateDelete(payload) { + approvalTemplateDeletePreview(payload) { const name = asObject(payload)['name']; if (typeof name !== 'string') return invalidInput('name is required'); - const result = approvalTemplateLibrary.delete(name); - if (!result.ok) return templateWriteFailure(name, result.reason); - const clearedBots = templateUsers(name, globalRegistry); - for (const slug of clearedBots) globalRegistry.setApprovalTemplate(slug, undefined); + const result = templateDeletion.preview(name); + return result.ok + ? { ok: true, value: { preview: result.preview } } + : templateDeletionFailure(name, result.reason); + }, + approvalTemplateDelete(payload) { + const object = asObject(payload); + const name = object['name']; + if (typeof name !== 'string') return invalidInput('name is required'); + const revision = object['revision']; + const result = templateDeletion.delete(name, { + confirmed: object['confirmed'] === true, + ...(typeof revision === 'string' ? { revision } : {}), + }); + if (!result.ok) return templateDeletionFailure(name, result.reason); + const inheritedBots = result.preview.affectedBots + .filter((bot) => bot.source === 'specific') + .map((bot) => bot.slug); return { ok: true, value: { template: { name }, - clearedBots: clearedBots.filter((slug) => deps.registry.get(slug) !== undefined), + clearedBots: inheritedBots, + inheritedBots, + globalDefault: result.preview.globalDefaultAfter, }, }; }, @@ -9595,6 +9685,7 @@ function buildBridgeMethods( AbortSignal.timeout(DIRECT_TOOL_TIMEOUT_MS), session?.trim(), sourceEventId, + human, ); return { ok: true, value: { slug, ...run } }; } catch (error) { diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index b0c9cfacfb..d98995a16c 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -1,3 +1,6 @@ +import type { ApprovalTemplateDeletionPreview } from '../workspaces/approval-template-deletion-contract.js'; + +import type { TobCliCommand, TobCliStatus } from '../tob/cli-request.js'; import type { BotMetadata, BotMetadataResult, @@ -1723,11 +1726,21 @@ export class BotharnessBridgeService extends TypertRemoteService { ); } - approvalTemplateDelete(name: string): { + approvalTemplateDeletePreview(name: string): { preview: ApprovalTemplateDeletionPreview } { + return unwrap(this.methods.approvalTemplateDeletePreview({ name })); + } + + approvalTemplateDelete( + name: string, + confirmed: boolean, + revision: string, + ): { template: { name: string }; clearedBots: string[]; + inheritedBots: string[]; + globalDefault: string | null; } { - return unwrap(this.methods.approvalTemplateDelete({ name })); + return unwrap(this.methods.approvalTemplateDelete({ name, confirmed, revision })); } approvalTemplateGlobalSet(template: string | null): { template: string | null } { @@ -2267,6 +2280,16 @@ export class BotharnessBridgeService extends TypertRemoteService { channelAllBotPreview(channelId: string): AllBotPreview { return unwrap(this.methods.channelAllBotPreview({ channelId })); } + async tobCli( + action: 'start' | 'status' | 'cancel', + command?: TobCliCommand, + id?: string, + ): Promise { + return unwrap( + await this.methods.tobCli(action === 'start' ? { action, command } : { action, id }), + ); + } + channelSendStatus(channelId: string, messageId: string): ChannelSendStatus { return unwrap(this.methods.channelSendStatus({ channelId, messageId })); } @@ -3438,6 +3461,7 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'tobCli', 'channelSkillCatalog', 'botSkills', 'skillShow', @@ -3543,6 +3567,7 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'botPromptSet', 'approvalTemplateCreate', 'approvalTemplateUpdate', + 'approvalTemplateDeletePreview', 'approvalTemplateDelete', 'approvalTemplateGlobalSet', 'botApprovalTemplateSet', diff --git a/packages/core/src/channels/channel.ts b/packages/core/src/channels/channel.ts index f527401bd7..3dd6171831 100644 --- a/packages/core/src/channels/channel.ts +++ b/packages/core/src/channels/channel.ts @@ -548,6 +548,7 @@ export interface ChannelMessage { onboardingWelcome?: { version: 1; kind?: 'tob' }; + tobCliRequestId?: string; memorySwitchTarget?: string; mentions?: ChannelMention[]; @@ -920,6 +921,14 @@ export function isChannelMessage(value: unknown): value is ChannelMessage { (message['author'] as ChannelMessageAuthor)?.kind !== 'human') ) return false; + const cliRequest = message['tobCliRequestId']; + if ( + cliRequest !== undefined && + (typeof cliRequest !== 'string' || + !/^[a-f0-9-]{36}$/u.test(cliRequest) || + (message['author'] as ChannelMessageAuthor)?.kind !== 'human') + ) + return false; const switchTarget = message['memorySwitchTarget']; if ( switchTarget !== undefined && diff --git a/packages/core/src/channels/sqlite-store.ts b/packages/core/src/channels/sqlite-store.ts index 86fc03231a..61748da2eb 100644 --- a/packages/core/src/channels/sqlite-store.ts +++ b/packages/core/src/channels/sqlite-store.ts @@ -261,6 +261,7 @@ function sameIntent(left: ChannelMessage, right: ChannelMessage): boolean { attachments: attachmentIntent(left.attachments ?? []), replyTo: left.replyTo, memorySwitchTarget: left.memorySwitchTarget, + tobCliRequestId: left.tobCliRequestId, mentions: left.mentions ?? [], humanMentions: left.humanMentions ?? [], channelRefs: left.channelRefs ?? [], @@ -279,6 +280,7 @@ function sameIntent(left: ChannelMessage, right: ChannelMessage): boolean { attachments: attachmentIntent(right.attachments ?? []), replyTo: right.replyTo, memorySwitchTarget: right.memorySwitchTarget, + tobCliRequestId: right.tobCliRequestId, mentions: right.mentions ?? [], humanMentions: right.humanMentions ?? [], channelRefs: right.channelRefs ?? [], diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index cb567861e6..18e43e8811 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -1,3 +1,4 @@ +import { hasIrreversibleExternalEffect, toolEffects } from './workspaces/tool-effects.js'; import { reconcilePublicBotMemories } from './workspaces/bot-memory-placement.js'; import { installNativeSearchResultGuard, currentRoots } from './workspaces/grant-native-tools.js'; import { relocateTobWorkspaces, recoverSpaceTransfers } from './workspaces/space-lifecycle.js'; @@ -91,6 +92,7 @@ import { TOB_MAINTENANCE_CAPABILITIES, } from './tob/cli-maintenance-operations.js'; import { cliModulePath, installTobCliShell } from './tob/cli-shell.js'; +import { ModelFreeTobCliInvocation } from './tob/cli-invocation.js'; import { createTobVoiceOperations, TOB_VOICE_CAPABILITIES } from './tob/cli-voice-operations.js'; import { LOCAL_VOICE_SKILL_CONTENT, @@ -320,13 +322,13 @@ import { import { ChannelToolApproval, registerChannelToolApproval, + requestRequiredToolApproval, type ToolAutoApproval, } from './workspaces/tool-approval.js'; import { changesApprovalPolicy, deletesMarketplaceBot, publishesBotMemory, - requiresHumanDecision, createApprovalTemplateLibrary, } from './workspaces/approval-templates.js'; import { @@ -1739,7 +1741,9 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { ); const turnRefusals = new Map(); ctx.effect(() => () => turnRefusals.clear(), 'botharness: refused Turn reasons'); + const tobCliInvocation = new ModelFreeTobCliInvocation(); const agentAdapter = createDshBotAgentAdapter({ + tobCliInvocation, ...(config.genuiPreviewBrowserPath === undefined ? {} : { genuiPreviewBrowserPath: config.genuiPreviewBrowserPath }), @@ -1749,6 +1753,10 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { promptText: (sessionId) => core.prompts.textForSession(sessionId), defaultModel, observeTurnFailure: (provider, code) => providerCredentials.observe(provider, code), + observeDirectToolCleanupFailure: ({ sessionId, durationMs }) => + ctx.logger.warn( + `direct-tool-cleanup phase=dispose outcome=failed session=${sessionId} durationMs=${durationMs}`, + ), turnRefusal: (sessionId) => turnRefusals.get(sessionId), resolveModelPlan: (slug) => core.registry.get(slug)?.modelPlan, subagentTools: (slug) => @@ -1792,6 +1800,18 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { (name, args) => nativeExecutionRoot(core, agent.session, name, args), (shellCtx, shell) => installTobCliShell(shellCtx, shell, { + nativeCli: { + available: () => + core.tob.isTob(core.ownership.resolve(agent.session.id)?.botSlug ?? '') && + agentAdapter.ownsModelFreeTobTurn(agent), + register: (definition) => + tobCliInvocation.register(agent, definition, () => { + if (!core.runtime.captureTobCliAuthority) + throw new TobError('tob-authority-required'); + return core.runtime.captureTobCliAuthority(agent.session.id); + }), + require: (execution) => tobCliInvocation.require(execution), + }, capture: (execution) => { const actor = execution.agent; if ( @@ -2413,7 +2433,7 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { applyCompactionPolicy(); ctx.on( 'agent/pre-step', - async ({ agent, signal }, next) => { + async ({ agent, signal, messages, modelSelection }, next) => { applyCompactionPolicy(); if (isApprovalReviewSession(agent.session.id)) return reviewing.has(agent.session.id) ? next() : { kind: 'reject' }; @@ -2458,6 +2478,10 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { return { kind: 'reject' }; } turnRefusals.delete(agent.session.id); + if (agentAdapter.ownsModelFreeTobTurn(agent)) { + await agentAdapter.runModelFreeTobTurn(agent, messages, signal, modelSelection); + return { kind: 'reject' }; + } const contextOwner = core.ownership.resolve(agent.session.id); if (contextOwner?.rootRole === 'orchestrator' && contextOwner.parentSessionId === undefined) await compactUnknownContext( @@ -2741,12 +2765,16 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { ctx.on( 'tools/pre-execute', async (execution, next) => { + const irreversibleExternal = hasIrreversibleExternalEffect( + toolEffects(execution.name, execution.arguments), + ); const agent = execution.agent; if (agent === undefined || core.ownership.resolve(agent.session.id) === undefined) return next(); if ( !isDshGovernedTool(execution.name) && - !requiresHumanToolApproval(execution.name, execution.arguments, templateInUse) + !requiresHumanToolApproval(execution.name, execution.arguments, templateInUse) && + execution.name !== 'deepseekbot_cli' ) return next(); const storeDenial = credentialStoreDenial( @@ -2781,7 +2809,7 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { agent.session.id, sessionHasFullAccess(core, agent.session.id), ); - if (computerAuthorization === 'authorized') return next(); + if (computerAuthorization === 'authorized' && !irreversibleExternal) return next(); if (computerAuthorization === 'changed') return { kind: 'deny', @@ -2811,12 +2839,18 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }; } try { - const outcome = await computerApproval.request({ - agent, - toolName: execution.name, - callId: execution.callId, - reason: "This PersonaBot wants to act on the profile's shared Computer.", - signal: execution.signal, + const outcome = await requestRequiredToolApproval({ + approval: computerApproval, + channelApproval: toolApproval, + ownership: core.ownership, + forceChannel: irreversibleExternal, + request: { + agent, + toolName: execution.name, + callId: execution.callId, + reason: "This PersonaBot wants to act on the profile's shared Computer.", + signal: execution.signal, + }, }); if (outcome !== 'allowed-once') { const reviewed = toolApproval.takeReviewRejection(agent.session.id, execution.callId); @@ -2881,7 +2915,7 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { agent.session.id, sessionHasFullAccess(core, agent.session.id), ); - if (browserAuthorization === 'authorized') return next(); + if (browserAuthorization === 'authorized' && !irreversibleExternal) return next(); if (browserAuthorization === 'changed') return { kind: 'deny', @@ -2912,12 +2946,18 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }; } try { - const outcome = await browserApproval.request({ - agent, - toolName: execution.name, - callId: execution.callId, - reason: 'This PersonaBot wants to use the Browser authorized by the Human.', - signal: AbortSignal.any([execution.signal, browserSignal ?? execution.signal]), + const outcome = await requestRequiredToolApproval({ + approval: browserApproval, + channelApproval: toolApproval, + ownership: core.ownership, + forceChannel: irreversibleExternal, + request: { + agent, + toolName: execution.name, + callId: execution.callId, + reason: 'This PersonaBot wants to use the Browser authorized by the Human.', + signal: AbortSignal.any([execution.signal, browserSignal ?? execution.signal]), + }, }); if (outcome !== 'allowed-once') { const reviewed = toolApproval.takeReviewRejection(agent.session.id, execution.callId); @@ -2961,15 +3001,13 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { } const denial = permissionDenial(agent.session); if (denial !== undefined) return { kind: 'deny', reason: denial }; + const cliAdmission = tobCliInvocation.delegate(execution); + if (cliAdmission === 'delegated') return next(); + if (cliAdmission === 'refused') + return { kind: 'deny', reason: 'The owned CLI invocation authority is unavailable' }; if (!requiresHumanToolApproval(execution.name, execution.arguments, templateInUse)) return next(); const eachUse = execution.name === 'secret_cli' || execution.name === 'secret_mcp_connect'; - const fullAccess = sessionHasFullAccess(core, agent.session.id); - if ( - fullAccess && - !requiresHumanDecision(JSON.stringify(execution.arguments) ?? '', templateInUse) - ) - return next(); const approval = ctx.get('approval') as ApprovalService | undefined; const owner = core.ownership.resolve(agent.session.id); const untrack = toolApproval.track( @@ -2988,34 +3026,36 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }; } try { - const outcome = eachUse - ? ((await toolApproval.ask({ - agent, - toolName: execution.name, - callId: execution.callId, - signal: execution.signal, - })) ?? 'unavailable') - : await approval.request({ - agent, - toolName: execution.name, - callId: execution.callId, - reason: - execution.name === 'channel_attachment_open' - ? 'This PersonaBot wants to edit the selected original attachment. All references to this file will show its current contents.' - : execution.name === 'bot_create' - ? 'This PersonaBot wants to create a new PersonaBot with a new Memory folder. The new Bot gets no grants, accesses or secrets from it.' - : publishesBotMemory(JSON.stringify(execution.arguments) ?? '') - ? 'This PersonaBot wants to upload a Bot to the Bot Marketplace. Its Memory files become public. Check them for secrets and private details first.' - : deletesMarketplaceBot(JSON.stringify(execution.arguments) ?? '') - ? 'This PersonaBot wants to delete one of your Uploaded Bots from the Bot Marketplace. Its files and counts are erased and cannot be restored.' - : changesApprovalPolicy( - JSON.stringify(execution.arguments) ?? '', - templateInUse, - ) - ? 'This PersonaBot wants to change persistent permissions or its approval policy. A Human can approve once or save Always allow for this tool in the current scope.' - : 'This PersonaBot wants to run a command-line tool with a secret you entered. The program receives the secret and could reveal it. Check the program and every argument.', - signal: execution.signal, - }); + const outcome = await requestRequiredToolApproval({ + approval, + channelApproval: toolApproval, + ownership: core.ownership, + forceChannel: + eachUse || + irreversibleExternal || + toolEffects(execution.name, execution.arguments)?.authority === 'management', + request: { + agent, + toolName: execution.name, + callId: execution.callId, + reason: + execution.name === 'channel_attachment_open' + ? 'This PersonaBot wants to edit the selected original attachment. All references to this file will show its current contents.' + : execution.name === 'bot_create' + ? 'This PersonaBot wants to create a new PersonaBot with a new Memory folder. The new Bot gets no grants, accesses or secrets from it.' + : publishesBotMemory(JSON.stringify(execution.arguments) ?? '') + ? 'This PersonaBot wants to upload a Bot to the Bot Marketplace. Its Memory files become public. Check them for secrets and private details first.' + : deletesMarketplaceBot(JSON.stringify(execution.arguments) ?? '') + ? 'This PersonaBot wants to delete one of your Uploaded Bots from the Bot Marketplace. Its files and counts are erased and cannot be restored.' + : changesApprovalPolicy( + JSON.stringify(execution.arguments) ?? '', + templateInUse, + ) + ? 'This PersonaBot wants to change persistent permissions or its approval policy. A Human can approve once or save Always allow for this tool in the current scope.' + : 'This PersonaBot wants to run a command-line tool with a secret you entered. The program receives the secret and could reveal it. Check the program and every argument.', + signal: execution.signal, + }, + }); if (outcome !== 'allowed-once') { const reviewed = toolApproval.takeReviewRejection(agent.session.id, execution.callId); return { @@ -3069,7 +3109,10 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { ); installNativeSearchResultGuard(ctx, core, (session) => sessionHasFullAccess(core, session.id)); - ctx.tools.guard(({ agent, name, arguments: args, token }) => { + ctx.tools.guard((execution) => { + const invocationDenial = tobCliInvocation.guard(execution); + if (invocationDenial) return invocationDenial; + const { agent, name, arguments: args, token } = execution; const approvalGuard = approvedCalls.get(token); if (approvalGuard && !approvalGuard(name, args)) return 'Approval authority or operation changed before execution'; diff --git a/packages/core/src/runtime/bot-message-tool.ts b/packages/core/src/runtime/bot-message-tool.ts index 6b9cad421a..20e27bd1fe 100644 --- a/packages/core/src/runtime/bot-message-tool.ts +++ b/packages/core/src/runtime/bot-message-tool.ts @@ -1,3 +1,4 @@ +import { HarnessError } from '@deepseek-ai/dsh-llm'; import { withInlineMentions, mentionPeople, @@ -22,12 +23,9 @@ function unsupportedVoice(): VoiceAttachOutcome { }; } -export class BotMessageError extends Error { - constructor( - readonly code: string, - message: string, - ) { - super(message); +export class BotMessageError extends HarnessError { + constructor(code: string, message: string) { + super(message, code); this.name = 'BotMessageError'; } } diff --git a/packages/core/src/runtime/bot-network.ts b/packages/core/src/runtime/bot-network.ts index 8e19ced269..d9b56bb106 100644 --- a/packages/core/src/runtime/bot-network.ts +++ b/packages/core/src/runtime/bot-network.ts @@ -1,3 +1,4 @@ +import { HarnessError } from '@deepseek-ai/dsh-llm'; import { OWNER_HUMAN_CONTEXT } from '../humans/context.js'; import type { BotMessageCausation, ChannelMessage } from '../channels/channel.js'; import type { NetworkBotContact } from './bot-contact-discovery.js'; @@ -24,9 +25,10 @@ export interface BotNetworkPort { send(hostId: string, message: NetworkBotMessage): Promise; } -export class BotNetworkDeliveryError extends Error { - constructor(readonly code: 'unable-to-deliver' | 'delivery-unknown' | 'network-denied') { - super(code); +export class BotNetworkDeliveryError extends HarnessError { + constructor(override readonly code: 'unable-to-deliver' | 'delivery-unknown' | 'network-denied') { + super(code, code); + this.name = 'BotNetworkDeliveryError'; } } diff --git a/packages/core/src/runtime/bot-runtime.ts b/packages/core/src/runtime/bot-runtime.ts index 3fa93252c4..9e4becc9d8 100644 --- a/packages/core/src/runtime/bot-runtime.ts +++ b/packages/core/src/runtime/bot-runtime.ts @@ -1,3 +1,8 @@ +import { HarnessError } from '@deepseek-ai/dsh-llm'; +import { hasIrreversibleExternalEffect, toolEffects } from '../workspaces/tool-effects.js'; + +import type { TobCliRequest, TobCliStatus, TobCliTurn } from '../tob/cli-request.js'; + import { skillOwnerKey } from '../skills/entries.js'; import type { TeamService } from '../team/service.js'; import { TeamError } from '../team/error.js'; @@ -364,6 +369,7 @@ export interface OrchestratorAgentRun { sourceEventId: string, ): { kind: 'external' } | { kind: 'channel'; channelId: string; messageId: string }; tobCli?: boolean; + tobCliTurn?: TobCliTurn; inboxHistory?(input?: InboxHistoryInput): InboxHistoryPage; triage?: OrchestratorInboxTriage; acceptNativeInput?: () => boolean; @@ -782,12 +788,9 @@ export function skillInvocationPrompt( return `\n\n[The Human invoked ${invocations.length === 1 ? 'this Skill' : 'these Skills'} with /. Each block is the Skill text as it was when the message was sent; follow it for this message. owner names whose Skill it is, not who should act.]\n${blocks.join('\n')}`; } -export class DirectBotToolError extends Error { - constructor( - readonly code: string, - message: string, - ) { - super(message); +export class DirectBotToolError extends HarnessError { + constructor(code: string, message: string) { + super(message, code); this.name = 'DirectBotToolError'; } } @@ -828,12 +831,21 @@ export type DmAdmissionFailure = | 'not-dm' | 'unknown-bot' | 'archived-bot' - | 'blank-body'; + | 'blank-body' + | 'cli-request-expired'; export type DmMessageAdmission = | { admitted: true; settled: Promise } | { admitted: false; reason: DmAdmissionFailure }; +interface TobCliRequestLease { + humanId: string; + botSlug: string; + controller: AbortController; + status: TobCliStatus; + finishedAt: number | undefined; +} + export interface TobCliAuthority { (): void; @@ -936,6 +948,7 @@ export interface BotRuntime { startFreshOrchestrator?(botSlug: string, assertCurrent?: () => void): Promise<'started' | 'busy'>; turnRunning?(botSlug: string): boolean; hasPendingInbox?(botSlug: string): boolean; + tobCli?(human: HumanContext, input: TobCliRequest): Promise; directBotTools?(): DirectBotToolSpec[]; directBotToolCalls?(botSlug: string): readonly DirectBotToolCall[]; runDirectBotTool?( @@ -945,6 +958,7 @@ export interface BotRuntime { signal: AbortSignal, parentSessionId?: string, sourceEventId?: string, + human?: HumanContext, ): Promise<{ tool: string; sessionId: 'direct'; result: unknown }>; triageOpenCount?(botSlug: string): number | undefined; listChannelAssignments?(channelId: string): ChannelAssignmentSummary[]; @@ -1780,6 +1794,8 @@ class BotRuntimeImplementation implements BotRuntime { readonly #assignmentNotices = new Set>(); readonly #waitLifetime = new AbortController(); readonly #waitOptions: Pick; + readonly #activeDirectTools = new Map(); + readonly #tobCliRequests = new Map(); #closed = false; readonly #tob: TobService | undefined; readonly #onTobDelegation: () => void; @@ -2133,6 +2149,7 @@ class BotRuntimeImplementation implements BotRuntime { const message = this.#channels.message(channelId, messageId); if (channel?.type !== 'dm' || !channel.botSlug || message?.author.kind !== 'human') throw new Error('Retry requires the original Human DM message'); + if (message.tobCliRequestId !== undefined) throw new TobError('cli-request-expired'); const safe = this.#database.read((database) => database .prepare( @@ -2151,6 +2168,8 @@ class BotRuntimeImplementation implements BotRuntime { } #continuableDmEvent(channelId: string, messageId: string): string | undefined { + if (this.#channels.message(channelId, messageId)?.tobCliRequestId !== undefined) + return undefined; const channel = this.#channels.get(channelId); const message = this.#channels.message(channelId, messageId); if (channel?.type !== 'dm' || !channel.botSlug || message?.author.kind !== 'human') @@ -2445,7 +2464,137 @@ class BotRuntimeImplementation implements BotRuntime { return result.value; } + async tobCli(human: HumanContext, input: TobCliRequest): Promise { + if (this.#closed) throw new TobError('runtime-closed'); + for (const [id, request] of this.#tobCliRequests) { + if (request.finishedAt !== undefined && Date.now() - request.finishedAt > 10 * 60 * 1000) + this.#tobCliRequests.delete(id); + } + if (input.action !== 'start') { + const request = this.#tobCliRequests.get(input.id); + if (!request || request.humanId !== human.humanId) + throw new TobError('cli-request-unavailable'); + if (input.action === 'cancel' && request.status.state === 'running') { + request.status = { ...request.status, cancelRequested: true }; + request.controller.abort(); + } + return structuredClone(request.status); + } + if (!this.#tob) throw new TobError('tob-authority-required'); + await this.#tob.ensure(human); + if (this.#closed) throw new TobError('runtime-closed'); + const bot = this.#registry + .list() + .find( + (candidate) => this.#tob?.isTob(candidate.slug) && botOwner(candidate) === human.humanId, + ); + if (!bot || bot.paused || !this.#memberBotEnabled(bot)) + throw new TobError('tob-authority-required'); + if ( + this.#tails.has(bot.slug) || + [...this.#activeDirectTools.values()].some((call) => call.botSlug === bot.slug) || + [...this.#tobCliRequests.values()].some((request) => request.status.state === 'running') + ) + throw new TobError('bot-busy'); + if (this.#tobCliRequests.size >= 16) { + const completed = [...this.#tobCliRequests].find( + ([, request]) => request.finishedAt !== undefined, + ); + if (completed) this.#tobCliRequests.delete(completed[0]); + else throw new TobError('bot-busy'); + } + const channel = this.#channels.getOrCreateDm(human, bot.slug, bot.displayName); + if (!channel) throw new TobError('human-dm-required'); + const channelId = channel.id; + const id = randomUUID(); + const messageId = 'human-' + randomUUID(); + const controller = new AbortController(); + const request: TobCliRequestLease = { + humanId: human.humanId, + botSlug: bot.slug, + controller, + status: { + id, + channelId, + messageId, + state: 'running', + cancelRequested: false, + }, + finishedAt: undefined, + }; + this.#tobCliRequests.set(id, request); + const timer = setTimeout(() => controller.abort(), 10 * 60 * 1000); + timer.unref?.(); + let result: import('../tob/cli-request.js').TobCliOutput | undefined; + const finish = (error?: unknown) => { + clearTimeout(timer); + request.finishedAt = Date.now(); + request.status = controller.signal.aborted + ? { + id, + channelId, + messageId, + state: 'cancelled', + cancelRequested: true, + code: 'operation-cancelled', + } + : error !== undefined || result === undefined + ? { + id, + channelId, + messageId, + state: 'failed', + cancelRequested: false, + code: + error instanceof TobError || + error instanceof DirectBotToolError || + error instanceof TeamError + ? error.code + : 'operation-failed', + } + : { id, channelId, messageId, state: 'completed', cancelRequested: false, result }; + }; + try { + this.#requireExecution?.(bot.slug); + const body = 'Run a typed CLI command without a model: ' + input.command.argv[0]; + const appended = await this.#channels.appendMessageOnce(human, channelId, { + id: messageId, + at: this.#now().toISOString(), + author: { kind: 'human', humanId: human.humanId }, + tobCliRequestId: id, + body, + }); + if (appended.status !== 'appended') throw new TobError('human-dm-required'); + controller.signal.throwIfAborted(); + const admission = this.#admitDmMessage( + human, + { channelId, messageId, body }, + { + command: { argv: [...input.command.argv], stdin: input.command.stdin }, + signal: controller.signal, + complete: (output) => { + result = output; + }, + }, + ); + if (!admission.admitted) throw new TobError(admission.reason); + void admission.settled.then(() => finish(), finish); + return structuredClone(request.status); + } catch (error) { + finish(error); + throw error; + } + } + admitDmMessage(human: HumanContext, input: HandleDmMessageInput): DmMessageAdmission { + return this.#admitDmMessage(human, input); + } + + #admitDmMessage( + human: HumanContext, + input: HandleDmMessageInput, + tobCliTurn?: TobCliTurn, + ): DmMessageAdmission { if (this.#closed) return { admitted: false, reason: 'runtime-closed' }; const channel = this.#channels.get(input.channelId); if (channel === undefined) return { admitted: false, reason: 'unknown-channel' }; @@ -2464,7 +2613,10 @@ class BotRuntimeImplementation implements BotRuntime { if (!this.#memberBotEnabled(bot)) return { admitted: false, reason: 'archived-bot' }; if (bot.paused === true) return { admitted: false, reason: 'archived-bot' }; - const persistedBody = this.#channels.message(channel.id, input.messageId)?.body; + const persistedMessage = this.#channels.message(channel.id, input.messageId); + if (persistedMessage?.tobCliRequestId !== undefined && tobCliTurn === undefined) + return { admitted: false, reason: 'cli-request-expired' }; + const persistedBody = persistedMessage?.body; const body = persistedBody?.trim() ? persistedBody : input.body; if (body.trim().length === 0) return { admitted: false, reason: 'blank-body' }; if (this.#autoContinues.get(bot.slug)?.messageId !== input.messageId) @@ -2482,6 +2634,10 @@ class BotRuntimeImplementation implements BotRuntime { ); const steered = claim.shouldRun && + tobCliTurn === undefined && + ![...this.#tobCliRequests.values()].some( + (request) => request.botSlug === bot.slug && request.status.state === 'running', + ) && this.#delivery(bot.slug, 'human-dm') === 'steer' && this.#steerDmAdmission( bot.slug, @@ -2502,7 +2658,15 @@ class BotRuntimeImplementation implements BotRuntime { settled: steered ? Promise.resolve() : this.#enqueue(bot.slug, () => - this.#runHumanDmTurn(bot, channel.id, body, claim, input.messageId), + this.#runHumanDmTurn( + bot, + channel.id, + body, + claim, + input.messageId, + undefined, + tobCliTurn, + ), ), }; } @@ -4438,6 +4602,14 @@ class BotRuntimeImplementation implements BotRuntime { askChannel(sessionId: string): string | undefined { const owner = this.#ownership.resolve(sessionId); if (this.#closed || owner?.rootRole !== 'orchestrator') return undefined; + const direct = this.#activeDirectTools.get(sessionId); + if (direct?.botSlug === owner.botSlug) { + const channel = + direct.approvalChannelId === undefined + ? undefined + : this.#channels.get(direct.approvalChannelId); + return channel?.type === 'dm' && channel.botSlug === owner.botSlug ? channel.id : undefined; + } const turn = this.#turnSources.get(owner.botSlug); if ( turn?.sessionId !== sessionId || @@ -5031,11 +5203,21 @@ class BotRuntimeImplementation implements BotRuntime { signal: AbortSignal, parentSessionId?: string, sourceEventId?: string, + human?: HumanContext, ): Promise<{ tool: string; sessionId: 'direct'; result: unknown }> { if (this.#closed) throw new DirectBotToolError('runtime-closed', 'BotRuntime is closed'); this.#team?.bots.requireActive(botSlug); const bot = this.#registry.get(botSlug); if (bot === undefined) throw new DirectBotToolError('unknown-bot', `Unknown bot: ${botSlug}`); + if ( + [...this.#tobCliRequests.values()].some( + (request) => request.botSlug === botSlug && request.status.state === 'running', + ) + ) + throw new DirectBotToolError( + 'bot-busy', + 'Wait for the active Tob CLI request or cancel it first', + ); if (bot.paused === true) throw new DirectBotToolError('bot-paused', `PersonaBot ${botSlug} is paused`); const runDirect = this.#agents.runDirectTool?.bind(this.#agents); @@ -5130,6 +5312,21 @@ class BotRuntimeImplementation implements BotRuntime { observeReads: false, }), }; + let approvalChannelId: string | undefined; + if ( + hasIrreversibleExternalEffect(toolEffects(tool, args)) || + toolEffects(tool, args)?.authority === 'management' + ) { + if (human !== undefined) + approvalChannelId = this.#channels.getOrCreateDm(human, botSlug, bot.displayName)?.id; + this.#ownership.claim({ + sessionId, + botSlug, + rootRole: 'orchestrator', + provenance: 'created', + at: this.#now().toISOString(), + }); + } const started = this.#now(); const record = (outcome: 'ok' | 'error', result: string) => { const calls = this.#directToolCalls.get(bot.slug) ?? []; @@ -5144,6 +5341,10 @@ class BotRuntimeImplementation implements BotRuntime { }); this.#directToolCalls.set(bot.slug, calls.slice(-DIRECT_TOOL_CALL_LIMIT)); }; + this.#activeDirectTools.set(sessionId, { + botSlug: bot.slug, + ...(approvalChannelId === undefined ? {} : { approvalChannelId }), + }); try { const result = await runDirect( run, @@ -5166,6 +5367,8 @@ class BotRuntimeImplementation implements BotRuntime { } catch (error) { record('error', error instanceof Error ? error.message : String(error)); throw error; + } finally { + this.#activeDirectTools.delete(sessionId); } } @@ -5741,7 +5944,24 @@ class BotRuntimeImplementation implements BotRuntime { } } + #cancelTobCli(botSlug: string): boolean { + let cancelled = false; + for (const request of this.#tobCliRequests.values()) { + if ( + request.botSlug !== botSlug || + request.status.state !== 'running' || + request.controller.signal.aborted + ) + continue; + request.status = { ...request.status, cancelRequested: true }; + request.controller.abort(); + cancelled = true; + } + return cancelled; + } + async stopBot(botSlug: string): Promise { + this.#cancelTobCli(botSlug); const owned = () => this.#ownership .rootsFor(botSlug) @@ -5800,6 +6020,7 @@ class BotRuntimeImplementation implements BotRuntime { }; const ref: StoppedSessionRef = { botSlug, sessionId, role: 'orchestrator' }; const current = this.currentOrchestratorSessionId(botSlug); + const cliStopped = current === sessionId && this.#cancelTobCli(botSlug); const stopped = (current === undefined || current === sessionId) && (await this.#humanStopOrchestrator( @@ -5813,10 +6034,10 @@ class BotRuntimeImplementation implements BotRuntime { role: 'orchestrator', botSlug, sessionId, - stopped, + stopped: stopped || cliStopped, }), ); - return stopped + return stopped || cliStopped ? { outcome: 'settled', stopped: [ref], alreadyIdle: [] } : { outcome: 'settled', stopped: [], alreadyIdle: [ref] }; } @@ -5854,6 +6075,7 @@ class BotRuntimeImplementation implements BotRuntime { } async stopAllSessions(botSlug: string): Promise { + const cliStopped = this.#cancelTobCli(botSlug); const bot = this.#registry.get(botSlug); if (bot === undefined) return { stopped: [], alreadyIdle: [] }; const orchestratorId = this.currentOrchestratorSessionId(botSlug); @@ -5866,7 +6088,7 @@ class BotRuntimeImplementation implements BotRuntime { const alreadyIdle: StoppedSessionRef[] = []; const orchestratorSession = turn?.sessionId ?? orchestratorId; if (orchestratorSession !== undefined) - (turn !== undefined ? stopped : alreadyIdle).push({ + (turn !== undefined || cliStopped ? stopped : alreadyIdle).push({ botSlug, sessionId: orchestratorSession, role: 'orchestrator', @@ -6191,6 +6413,7 @@ class BotRuntimeImplementation implements BotRuntime { async close(): Promise { if (this.#closed) return; this.#closed = true; + for (const request of this.#tobCliRequests.values()) request.controller.abort(); this.#inboxHistory.clear(); this.#approvalCapacity.close(); this.#waitLifetime.abort(new Error('Bot Runtime closed')); @@ -6244,6 +6467,7 @@ class BotRuntimeImplementation implements BotRuntime { claim: SourceEventClaim, messageId: string, continuation?: DmContinuation, + tobCliTurn?: TobCliTurn, ): Promise { if (claim.reconciliationRequired === true) { throw new Error(`Source Event ${claim.sourceEventId} requires reconciliation before replay`); @@ -6256,9 +6480,11 @@ class BotRuntimeImplementation implements BotRuntime { const timestamp = this.#now().toISOString(); let orchestrator = this.#ensureOrchestrator(bot, timestamp); - const collected = this.#collectInbox(bot.slug); + const collected = + tobCliTurn === undefined ? this.#collectInbox(bot.slug) : { units: [], eventIds: [] }; this.#setObserved(collected.eventIds, timestamp, bot.slug); try { + tobCliTurn?.signal.throwIfAborted(); this.#observeAdmission(claim.sourceEventId, bot.slug, channelId, messageId); await this.#runOnLiveOrchestrator(bot, orchestrator, (session) => { orchestrator = session; @@ -6273,6 +6499,11 @@ class BotRuntimeImplementation implements BotRuntime { this.#channels.message(channelId, messageId)?.memorySwitchTarget !== undefined, undefined, collected.eventIds, + undefined, + undefined, + undefined, + undefined, + tobCliTurn, ); }); } catch (error) { @@ -6282,6 +6513,7 @@ class BotRuntimeImplementation implements BotRuntime { const autoAttempts = continuation?.autoAttempts ?? 0; const delayMs = this.#autoContinueDelaysMs[autoAttempts]; const autoContinue = + tobCliTurn === undefined && code !== undefined && TRANSIENT_FAILURE_CODES.has(code) && delayMs !== undefined && @@ -6364,6 +6596,7 @@ class BotRuntimeImplementation implements BotRuntime { acceptNativeInput?: () => boolean, nativeSourceIds: readonly string[] = [], memoryObservation: 'source-event' | 'recovered-question' = 'source-event', + tobCliTurn?: TobCliTurn, ): Promise { if (!this.#memberBotEnabled(bot)) throw new TobError('permission-required'); const readAdmissions = new Set(); @@ -6404,6 +6637,7 @@ class BotRuntimeImplementation implements BotRuntime { .get(bot.slug, sourceEventId ?? null), ); const observeMemory = + tobCliTurn === undefined && memoryObservation === 'source-event' && sourceEventId !== undefined && memorySource?.source_kind !== 'bridge-message' && @@ -6512,7 +6746,8 @@ class BotRuntimeImplementation implements BotRuntime { ['usage'], ); const envelope = this.#speakerInput(bot.slug, orchestrator.sessionId, [...turnSources], body); - await this.#agents.runOrchestrator({ + const run: OrchestratorAgentRun & { triage: OrchestratorInboxTriage } = { + ...(tobCliTurn === undefined ? {} : { tobCliTurn }), setExecutionReady: (ready) => { if (ready) { this.#preparedOrchestrators.add(orchestrator.sessionId); @@ -6573,9 +6808,12 @@ class BotRuntimeImplementation implements BotRuntime { observeReads: true, modelContent: body + '\n' + inbox, }), - }); + }; + await this.#agents.runOrchestrator(run); this.#requireTurnAccess(bot.slug, turnSources); if (acceptNativeInput === undefined) envelope?.commit(); + if (tobCliTurn !== undefined && sourceEventId !== undefined) + run.triage.resolve({ ids: [sourceEventId], outcome: 'done' }); if (observeMemory) { await this.#settleSteerMemoryScan(bot.slug); this.#memoryTurnOperations.add(bot.slug); @@ -6591,7 +6829,8 @@ class BotRuntimeImplementation implements BotRuntime { this.#settleHarvestHandled(bot.slug, [...readAdmissions]); this.#notifyReadAdmissions(readAdmissions); if (!this.#triageRunning.has(bot.slug)) this.#triageBaseline.delete(bot.slug); - if (!this.#stoppedTurns.has(bot.slug)) this.#queueTriage(bot.slug); + if (tobCliTurn === undefined && !this.#stoppedTurns.has(bot.slug)) + this.#queueTriage(bot.slug); } catch (error) { this.#setObserved(memoryEventIds, null); this.#settleHarvestFailure(bot.slug, [...readAdmissions], String(error)); @@ -6625,7 +6864,7 @@ class BotRuntimeImplementation implements BotRuntime { ): Omit< OrchestratorAgentRun, 'sessionId' | 'resume' | 'bot' | 'message' | 'inbox' | 'inboundChannelId' - > { + > & { triage: OrchestratorInboxTriage } { const channels = this.#channelAccess( bot.slug, turn.channelId, diff --git a/packages/core/src/runtime/dsh-bot-agent-adapter.ts b/packages/core/src/runtime/dsh-bot-agent-adapter.ts index a4982490ea..36788c946e 100644 --- a/packages/core/src/runtime/dsh-bot-agent-adapter.ts +++ b/packages/core/src/runtime/dsh-bot-agent-adapter.ts @@ -1,4 +1,7 @@ import { installMemorySkillProvider } from '../skills/memory-provider.js'; +import { hasIrreversibleExternalEffect, toolEffects } from '../workspaces/tool-effects.js'; + +import { randomUUID } from 'node:crypto'; import { TeamError } from '../team/error.js'; import { createChannelActionTool } from './channel-action-tool.js'; import { @@ -15,6 +18,7 @@ import { GENUI_STYLE_GUIDANCE } from '../channels/genui-appearance.js'; import type { GenuiPreviewDiagnostic } from './genui-preview.js'; import { assertOrchestratorWorkingDirectory } from './orchestrator-working-directory.js'; import { TOB_CLI_PROMPT } from '../tob/service.js'; +import { ModelFreeTobCliInvocation } from '../tob/cli-invocation.js'; import { AssignmentInboxAcceptanceUncertainError } from './assignment-delivery.js'; import type { Context } from '@deepseek-ai/cordis'; import { mkdirSync } from 'node:fs'; @@ -83,6 +87,13 @@ export const TURN_ONLY_BOT_TOOLS: ReadonlySet = new Set([ const CATALOG_RUN = { sessionId: '', bot: { slug: '' } } as unknown as OrchestratorAgentRun; +interface ModelFreeTobTurn { + agent: Agent; + turn: NonNullable; + inputId: ReturnType['id']; + outcome: { kind: 'completed' } | { kind: 'failed'; error: unknown } | undefined; +} + interface AssignmentRequestArgs { session_id: string; text: string; @@ -365,6 +376,7 @@ export interface DshAgentPresetHost { } export interface DshBotAgentAdapterOptions { + tobCliInvocation?: ModelFreeTobCliInvocation; onGenuiDiagnostic?: (event: GenuiPreviewDiagnostic) => void; genuiPreviewBrowserPath?: string; genuiAttachmentContext?: Pick; @@ -406,6 +418,7 @@ export interface DshBotAgentAdapterOptions { preparationVisibleMs?: number; observePreparation?: (botSlug: string, sessionId: string, preparing: boolean) => void; + observeDirectToolCleanupFailure?: (event: { sessionId: string; durationMs: number }) => void; } export interface BotAgentSetupInfo { @@ -606,6 +619,8 @@ class DshBotAgentAdapter implements BotAgentAdapter { { current: ModelSelection | undefined; assembled: ModelSelection | undefined } >(); readonly #runs = new Map(); + readonly #modelFreeTobTurns = new Map(); + readonly #tobCliInvocation: ModelFreeTobCliInvocation; readonly #stopping = new Set(); readonly #stoppedBots = new Set(); readonly #humanStops = new Set(); @@ -614,11 +629,13 @@ class DshBotAgentAdapter implements BotAgentAdapter { readonly #preparations = new Map(); readonly #preparationTimeoutMs: number; readonly #observePreparation: DshBotAgentAdapterOptions['observePreparation']; + readonly #observeDirectToolCleanupFailure: DshBotAgentAdapterOptions['observeDirectToolCleanupFailure']; readonly #preparationVisibleMs: number; readonly #drafts: ChannelDraftTracker; #closed = false; constructor(options: DshBotAgentAdapterOptions) { + this.#tobCliInvocation = options.tobCliInvocation ?? new ModelFreeTobCliInvocation(); this.#onGenuiDiagnostic = options.onGenuiDiagnostic; this.#genuiPreviewBrowserPath = options.genuiPreviewBrowserPath; this.#genuiAttachmentContext = options.genuiAttachmentContext; @@ -643,34 +660,51 @@ class DshBotAgentAdapter implements BotAgentAdapter { this.#drafts = new ChannelDraftTracker(options.publishDraft ?? (() => undefined)); this.#preparationTimeoutMs = options.preparationTimeoutMs ?? PREPARATION_TIMEOUT_MS; this.#observePreparation = options.observePreparation; + this.#observeDirectToolCleanupFailure = options.observeDirectToolCleanupFailure; this.#preparationVisibleMs = options.preparationVisibleMs ?? PREPARATION_VISIBLE_MS; } - async #prepare(sessionId: string, work: () => Promise): Promise { + async #prepare( + sessionId: string, + work: (signal: AbortSignal) => Promise, + signal?: AbortSignal, + ): Promise { + if (this.#preparations.has(sessionId)) + throw new DirectBotToolError( + 'bot-busy', + 'The previous native preparation is still being cleaned up', + ); const controller = new AbortController(); this.#preparations.set(sessionId, controller); + const abort = () => controller.abort(); + const release = () => { + if (this.#preparations.get(sessionId) === controller) this.#preparations.delete(sessionId); + }; + let pending: Promise | undefined; let timer: ReturnType | undefined; try { - return await Promise.race([ - work(), - new Promise((_, reject) => { - controller.signal.addEventListener('abort', () => reject(new PreparationStopped()), { - once: true, - }); - timer = setTimeout( - () => - reject( - new Error( - `Preparing this turn took longer than ${Math.round(this.#preparationTimeoutMs / 1000)} s (model route or Session resume did not answer). Check the DSH model provider, then send the message again.`, - ), - ), - this.#preparationTimeoutMs, + const stopped = new Promise((_, reject) => { + controller.signal.addEventListener('abort', () => reject(new PreparationStopped()), { + once: true, + }); + timer = setTimeout(() => { + reject( + new Error( + `Preparing this turn took longer than ${Math.round(this.#preparationTimeoutMs / 1000)} s (model route or Session resume did not answer). Check the DSH model provider, then send the message again.`, + ), ); - }), - ]); + controller.abort(); + }, this.#preparationTimeoutMs); + }); + signal?.addEventListener('abort', abort, { once: true }); + signal?.throwIfAborted(); + pending = Promise.resolve().then(() => work(controller.signal)); + void pending.then(release, release); + return await Promise.race([pending, stopped]); } finally { + signal?.removeEventListener('abort', abort); clearTimeout(timer); - if (this.#preparations.get(sessionId) === controller) this.#preparations.delete(sessionId); + if (pending === undefined) release(); } } @@ -703,7 +737,10 @@ class DshBotAgentAdapter implements BotAgentAdapter { async runOrchestrator(run: OrchestratorAgentRun): Promise { this.#assertOpen(); if (this.#stoppedBots.has(run.bot.slug)) throw new Error('PersonaBot is deleted'); - const entry: ActiveRun = { role: 'orchestrator', run }; + const entry: ActiveRun = { + role: 'orchestrator', + run, + }; this.#runs.set(run.sessionId, entry); this.#stopSeqs.delete(run.sessionId); const abandonable = this.#abandonable(run.sessionId); @@ -742,10 +779,16 @@ class DshBotAgentAdapter implements BotAgentAdapter { }, this.#preparationVisibleMs); reveal.unref?.(); try { - handle = await this.#prepare(run.sessionId, async () => { - await this.#prepareModelRoute?.(run.bot.slug, 'orchestrator'); - return this.#orchestratorHandle(run); - }); + handle = await this.#prepare( + run.sessionId, + async (signal) => { + run.tobCliTurn?.signal.throwIfAborted(); + if (run.tobCliTurn === undefined) + await this.#prepareModelRoute?.(run.bot.slug, 'orchestrator'); + return this.#orchestratorHandle(run, signal); + }, + run.tobCliTurn?.signal, + ); } catch (error) { if (error instanceof PreparationStopped && this.#humanStops.has(run.sessionId)) return; throw error; @@ -769,6 +812,42 @@ class DshBotAgentAdapter implements BotAgentAdapter { const fromSeq = handle.agent.session.seq; run.setExecutionReady?.(true); run.requireContent?.(); + if (run.tobCliTurn !== undefined) { + const agent = handle.agent; + if (agent.status !== 'idle' || agent.inbox.nextTurn.length || agent.inbox.nextStep.length) + throw new DirectBotToolError('bot-busy', 'The native Agent has pending work'); + const input = createUserMessage({ + content: [{ type: 'text', text: run.message }], + source: { kind: 'user' }, + }); + const pending: ModelFreeTobTurn = { + agent, + turn: run.tobCliTurn, + inputId: input.id, + outcome: undefined, + }; + this.#modelFreeTobTurns.set(run.sessionId, pending); + const cancel = () => agent.cancel({ kind: 'user' }, { keepInbox: true }); + run.tobCliTurn.signal.addEventListener('abort', cancel, { once: true }); + try { + run.tobCliTurn.signal.throwIfAborted(); + agent.followup(input); + await agent.whenIdle(); + run.tobCliTurn.signal.throwIfAborted(); + if (!pending.outcome) + throw new DirectBotToolError( + 'native-turn-not-accepted', + 'The native turn did not accept the CLI request', + ); + if (pending.outcome.kind === 'failed') throw pending.outcome.error; + } finally { + run.tobCliTurn.signal.removeEventListener('abort', cancel); + agent.inbox.remove(input.id); + if (this.#modelFreeTobTurns.get(run.sessionId) === pending) + this.#modelFreeTobTurns.delete(run.sessionId); + } + return; + } const text = [run.message, run.inbox].filter((part) => part.trim().length > 0).join('\n\n'); if (run.acceptNativeInput !== undefined) { if (!run.acceptNativeInput()) return; @@ -817,6 +896,105 @@ class DshBotAgentAdapter implements BotAgentAdapter { } } + ownsModelFreeTobTurn(agent: Agent): boolean { + const pending = this.#modelFreeTobTurns.get(agent.session.id); + return pending?.agent === agent; + } + + async runModelFreeTobTurn( + agent: Agent, + messages: readonly ReturnType[], + signal: AbortSignal, + modelSelection: Readonly, + ): Promise { + const pending = this.#modelFreeTobTurns.get(agent.session.id); + if (!pending || pending.agent !== agent) return false; + if (pending.outcome) return true; + const turn = pending.turn; + try { + if (messages.length !== 1 || messages[0]?.id !== pending.inputId) + throw new DirectBotToolError( + 'native-turn-not-accepted', + 'The native input identity changed', + ); + const active = this.#runs.get(agent.session.id); + if (active?.role !== 'orchestrator' || active.run.tobCliTurn !== turn) + throw new DirectBotToolError('agent-context-expired', 'The owned CLI turn ended'); + active.run.requireContent?.(); + active.run.inputAccepted?.(); + turn.signal.throwIfAborted(); + const toolSet = + typeof agent.ctx.tools.resolve === 'function' + ? await agent.ctx.tools.resolve({ agent, modelSelection, signal }) + : undefined; + const result = await (async () => { + try { + if (!toolSet) + throw new DirectBotToolError('tool-failed', 'Native tool selection is unavailable'); + const callId = ToolCallId('tob-cli-' + randomUUID()); + const invocationSignal = AbortSignal.any([signal, turn.signal]); + return await this.#tobCliInvocation.run( + { + agent, + callId, + command: turn.command, + toolSet, + signal: invocationSignal, + requireCurrentTurn: () => { + const current = this.#runs.get(agent.session.id); + if ( + this.#closed || + this.#modelFreeTobTurns.get(agent.session.id) !== pending || + pending.outcome || + current !== active || + current.run.tobCliTurn !== turn + ) + throw new DirectBotToolError('agent-context-expired', 'The owned CLI turn ended'); + current.run.requireContent?.(); + turn.signal.throwIfAborted(); + }, + }, + () => + executeNativeTool(agent.ctx, { + callId, + name: 'deepseekbot_cli', + arguments: turn.command, + agent, + signal: invocationSignal, + toolSet, + }), + ); + } finally { + toolSet?.dispose(); + } + })(); + if (result.isError) + throw new DirectBotToolError( + result.error.info?.code ?? 'tool-failed', + result.error.message, + ); + const value: unknown = + typeof result.value === 'string' ? JSON.parse(result.value) : result.value; + if ( + typeof value !== 'object' || + value === null || + !('exitCode' in value) || + typeof value.exitCode !== 'number' || + !('stdout' in value) || + typeof value.stdout !== 'string' || + !('stderr' in value) || + typeof value.stderr !== 'string' + ) + throw new DirectBotToolError('tool-failed', 'The scoped CLI did not return a result'); + turn.complete({ exitCode: value.exitCode, stdout: value.stdout, stderr: value.stderr }); + pending.outcome = { kind: 'completed' }; + } catch (error) { + pending.outcome = { kind: 'failed', error }; + throw error; + } + return true; + } + stopOrchestratorTurn(botSlug: string): string | undefined { for (const [sessionId, active] of this.#runs) { if (active.role !== 'orchestrator' || active.direct || active.run.bot.slug !== botSlug) @@ -838,7 +1016,12 @@ class DshBotAgentAdapter implements BotAgentAdapter { steerOrchestrator(botSlug: string, text: string): boolean { this.#assertOpen(); for (const [sessionId, active] of this.#runs) { - if (active.role !== 'orchestrator' || active.direct || active.run.bot.slug !== botSlug) + if ( + active.role !== 'orchestrator' || + active.direct || + active.run.tobCliTurn !== undefined || + active.run.bot.slug !== botSlug + ) continue; const handle = this.#handles.get(sessionId); if (handle === undefined) return false; @@ -1076,13 +1259,14 @@ class DshBotAgentAdapter implements BotAgentAdapter { error.name = 'SessionUnavailableError'; throw error; } - await this.#prepare(run.sessionId, async () => { + await this.#prepare(run.sessionId, async (signal) => { await this.#prepareModelRoute?.(run.bot.slug, 'orchestrator'); - await this.#orchestratorHandle(run); + await this.#orchestratorHandle(run, signal); }); } - async #orchestratorHandle(run: OrchestratorAgentRun): Promise { + async #orchestratorHandle(run: OrchestratorAgentRun, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); const existing = this.#liveHandle(run.sessionId); if (existing !== undefined) return existing; const resolvedAgentOptions = agentOptions( @@ -1189,7 +1373,14 @@ class DshBotAgentAdapter implements BotAgentAdapter { }; listBridgeTools(run.externalMessaging?.connected() ?? false); if (borrowed) borrowedDisposers.push(() => listBridgeTools(false)); - this.#orchestratorBridgeTools.set(run.sessionId, listBridgeTools); + const disposeBridgeListing = agentCtx.effect(() => { + this.#orchestratorBridgeTools.set(run.sessionId, listBridgeTools); + return () => { + if (this.#orchestratorBridgeTools.get(run.sessionId) === listBridgeTools) + this.#orchestratorBridgeTools.delete(run.sessionId); + }; + }, 'botharness: Orchestrator bridge tools lifetime'); + if (borrowed) borrowedDisposers.push(disposeBridgeListing); }; const live = this.#agents.get?.(SessionId(run.sessionId)); if (live !== undefined) { @@ -1201,6 +1392,8 @@ class DshBotAgentAdapter implements BotAgentAdapter { this.#authorizeBorrow?.(live, 'orchestrator'); try { await setup(live.ctx, live, true); + signal?.throwIfAborted(); + run.tobCliTurn?.signal.throwIfAborted(); } catch (error) { for (const dispose of borrowedDisposers.reverse()) await dispose(); throw error; @@ -1215,7 +1408,11 @@ class DshBotAgentAdapter implements BotAgentAdapter { this.#orchestratorSelections.set(run.sessionId, selection); return borrowed; } - const options = { agentOptions: resolvedAgentOptions, setup }; + const options = { + agentOptions: resolvedAgentOptions, + setup, + ...(signal === undefined ? {} : { signal }), + }; const meta = createMeta( run, this.#resolveOrchestratorCwd(run.bot), @@ -1235,6 +1432,8 @@ class DshBotAgentAdapter implements BotAgentAdapter { ...options, }); try { + signal?.throwIfAborted(); + run.tobCliTurn?.signal.throwIfAborted(); assertOrchestratorWorkingDirectory( run.sessionId, handle.agent.session.header.cwd, @@ -4058,6 +4257,29 @@ class DshBotAgentAdapter implements BotAgentAdapter { result.error.message, ); value = result.value; + } else if ( + hasIrreversibleExternalEffect(toolEffects(name, args)) || + toolEffects(name, args)?.authority === 'management' + ) { + const handle = await this.#prepare( + run.sessionId, + (preparationSignal) => this.#orchestratorHandle(run, preparationSignal), + signal, + ); + signal.throwIfAborted(); + const result = await executeNativeTool(handle.agent.ctx, { + callId: ToolCallId(run.sessionId), + name, + arguments: args, + agent: handle.agent, + signal, + }); + if (result.isError) + throw new DirectBotToolError( + result.error.info?.code ?? 'tool-failed', + result.error.message, + ); + value = result.value; } else { value = await tool.execute(args, { callId: run.sessionId, @@ -4081,6 +4303,17 @@ class DshBotAgentAdapter implements BotAgentAdapter { throw error; } finally { this.#runs.delete(run.sessionId); + const cleanupStarted = Date.now(); + try { + await this.releaseSession(run.sessionId); + } catch { + try { + this.#observeDirectToolCleanupFailure?.({ + sessionId: run.sessionId, + durationMs: Date.now() - cleanupStarted, + }); + } catch {} + } } } @@ -4295,6 +4528,13 @@ export function createDshBotAgentAdapter(options: DshBotAgentAdapterOptions): Bo acceptAssistantStream(sessionId: string, frame: AssistantStreamFrame): void; forgetAgent(agent: Agent): void; modelSelection(sessionId: string): ModelSelection | undefined; + ownsModelFreeTobTurn(agent: Agent): boolean; + runModelFreeTobTurn( + agent: Agent, + messages: readonly ReturnType[], + signal: AbortSignal, + modelSelection: Readonly, + ): Promise; } { return new DshBotAgentAdapter(options); } diff --git a/packages/core/src/runtime/native-agent-compat.ts b/packages/core/src/runtime/native-agent-compat.ts index 1cd97292f1..80836fe179 100644 --- a/packages/core/src/runtime/native-agent-compat.ts +++ b/packages/core/src/runtime/native-agent-compat.ts @@ -1,7 +1,7 @@ import type { Context } from '@deepseek-ai/cordis'; import { installModelSelection, type Agent, type ModelSelection } from '@deepseek-ai/dsh-agent'; import type { ToolCallId } from '@deepseek-ai/dsh-llm'; -import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools'; +import type { ResolvedToolSet, ToolExecutionResult } from '@deepseek-ai/dsh-tools'; import { installedDshVersion } from '../telemetry/service.js'; declare module '@deepseek-ai/cordis' { @@ -244,6 +244,7 @@ export interface DirectNativeCall { name: string; arguments: unknown; agent?: Agent; + toolSet?: ResolvedToolSet; signal: AbortSignal; } @@ -269,6 +270,7 @@ export async function executeNativeTool( }, ], ...(input.agent === undefined ? {} : { agent: input.agent }), + ...(input.toolSet === undefined ? {} : { toolSet: input.toolSet }), signal: input.signal, }); if (batch.results.length !== 1 || batch.results[0]?.callId !== input.callId) diff --git a/packages/core/src/sessions/ownership.ts b/packages/core/src/sessions/ownership.ts index b123cc3fc0..fb8d33bbd7 100644 --- a/packages/core/src/sessions/ownership.ts +++ b/packages/core/src/sessions/ownership.ts @@ -241,6 +241,7 @@ export function createSessionOwnership(database: OperationalDatabaseModulePort): .prepare( `SELECT ${COLUMNS} FROM session_ownership WHERE bot_slug = ? AND parent_session_id IS NULL + AND session_id NOT LIKE 'direct-%' ${rootRole === undefined ? '' : 'AND root_role = ?'} ORDER BY created_at DESC, session_id ASC`, ) diff --git a/packages/core/src/team/error.ts b/packages/core/src/team/error.ts index f0aa89aa2b..7e727527cb 100644 --- a/packages/core/src/team/error.ts +++ b/packages/core/src/team/error.ts @@ -1,9 +1,11 @@ -export class TeamError extends Error { +import { HarnessError } from '@deepseek-ai/dsh-llm'; + +export class TeamError extends HarnessError { constructor( - readonly code: string, + code: string, readonly retryAfterSeconds?: number, readonly details?: Record, ) { - super(code); + super(code, code); } } diff --git a/packages/core/src/tob/cli-approval.ts b/packages/core/src/tob/cli-approval.ts index 2b563335bf..026eb8851c 100644 --- a/packages/core/src/tob/cli-approval.ts +++ b/packages/core/src/tob/cli-approval.ts @@ -5,6 +5,7 @@ import type { ApprovalService } from '@deepseek-ai/dsh-user-approval'; import type { ChannelToolApproval } from '../workspaces/tool-approval.js'; import type { TobCliWriteProposal } from './cli-broker.js'; import { TobError } from './service.js'; +import { toolApprovalRequired } from '../workspaces/tool-effects.js'; export async function approveTobCliOperation(options: { execution: ToolExecution; @@ -37,7 +38,11 @@ export async function approveTobCliOperation(options: { : 'global'; authorize(); if (!actor || signal.aborted) throw new TobError('agent-context-expired'); - if (!requireExplicitApproval && options.fullAccess()) + if ( + !requireExplicitApproval && + !toolApprovalRequired('deepseekbot ' + command, operation, false) && + options.fullAccess() + ) return () => { authorize(); if (signal.aborted || !options.fullAccess()) throw new TobError('approval-authority-changed'); diff --git a/packages/core/src/tob/cli-broker.ts b/packages/core/src/tob/cli-broker.ts index 9586e6d3df..70a1613941 100644 --- a/packages/core/src/tob/cli-broker.ts +++ b/packages/core/src/tob/cli-broker.ts @@ -1,3 +1,4 @@ +import { toolApprovalRequired } from '../workspaces/tool-effects.js'; import { randomBytes, timingSafeEqual } from 'node:crypto'; import { createServer, type IncomingMessage } from 'node:http'; import { TOB_AGENT_COMMAND_USAGE } from '../bots/cli-agent-management.js'; @@ -298,6 +299,12 @@ export async function startTobCliBroker(options: TobCliBrokerOptions): Promise owner(() => deps.management.lookupCreate(operationKey, input)); if (lookup()) return { + completed: true, run(guard) { guard(); const replay = lookup(); @@ -472,6 +473,7 @@ export function createTobChannelOperations(deps: { const lookup = () => owner(() => deps.management.lookupInvite(operationKey, input)); if (lookup()) return { + completed: true, run(guard) { guard(); const replay = lookup(); diff --git a/packages/core/src/tob/cli-host-commands.ts b/packages/core/src/tob/cli-host-commands.ts index c379529b68..0a0a273e60 100644 --- a/packages/core/src/tob/cli-host-commands.ts +++ b/packages/core/src/tob/cli-host-commands.ts @@ -1,3 +1,6 @@ +import { BROKER_CLI_READS, cliEffects } from '../bots/cli-effects.js'; +import { canonicalCliCommandName } from '../bots/cli-command-names.js'; +export { BROKER_CLI_READS as TOB_HOST_CLI_READS } from '../bots/cli-effects.js'; import { parseBotCliArgs } from '../bots/cli-options.js'; import { ownsBot } from '../team/bot-access.js'; import type { PersonaBotRegistry } from '../bots/registry.js'; @@ -11,169 +14,8 @@ import { pathToFileURL } from 'node:url'; import type { PrepareTobOperation, TobCliCapability } from './cli-operations.js'; import { TobError } from './service.js'; -export const TOB_HOST_CLI_READS: ReadonlySet = new Set([ - 'access', - 'activity', - 'activity-overview', - 'activity-status', - 'activity-watch', - 'appearance-clients', - 'appearance-get', - 'appearance-targets', - 'approval-reviewer-model', - 'approval-routes', - 'approval-template-show', - 'approval-templates', - 'ask-secret-account-status', - 'ask-secret-accounts', - 'ask-secret-status', - 'assignment', - 'assignment-context', - 'assignment-timeline', - 'assignments', - 'bot-activity', - 'bot-activity-history', - 'bot-attention', - 'bot-context', - 'bot-delete-memory-folder', - 'bot-delete-preview', - 'bot-prompt', - 'bot-session-usage', - 'bot-sessions', - 'bot-source-policies', - 'bot-system-prompt', - 'bot-tools', - 'bot-trace', - 'bot-turn-input', - 'bot-usage', - 'browser-notification-clients', - 'browser-packages', - 'browser-takeover-audit', - 'browser-tools', - 'call-list', - 'call-read', - 'call-readiness', - 'call-status', - 'channel', - 'channel-activity-today', - 'channel-assignments', - 'channel-bridges', - 'channel-changes', - 'channel-history', - 'channel-ingests', - 'channel-list-changes', - 'channel-messages', - 'channel-purge-preview', - 'channel-search', - 'channel-unread', - 'channels', - 'computer-diagnostics', - 'computer-exports', - 'computer-logs', - 'computer-status', - 'computer-tools', - 'connect-account-hosts', - 'connect-status', - 'connection-clients', - 'data-reset-preview', - 'device-offer-status', - 'device-requests', - 'devices', - 'failure-alerts', - 'folder-browse', - 'genui-view', - 'git-status', - 'grants', - 'group-activity', - 'group-wake-policies', - 'host-ping', - 'human-identity', - 'idle-compaction', - 'im-app-status', - 'im-apps', - 'im-status', - 'list', - 'marketplace-account', - 'marketplace-detail', - 'marketplace-digest', - 'marketplace-digests', - 'marketplace-file', - 'marketplace-mine', - 'marketplace-sections', - 'marketplace-topics', - 'marketplace-upload-plan', - 'memory-changes', - 'memory-checkpoints', - 'memory-commit-diff', - 'memory-diff', - 'memory-file', - 'memory-graph', - 'memory-history', - 'memory-snapshot', - 'memory-versions', - 'memory-working-diff', - 'message-search', - 'messaging-defaults', - 'messaging-grants', - 'messaging-post-status', - 'messaging-reachable', - 'messaging-source', - 'messaging-targets', - 'model-catalog', - 'model-plan', - 'model-presets', - 'overview-memory', - 'overview-usage', - 'pairing-list', - 'pairings', - 'part-library', - 'phone-route', - 'plugin-check', - 'profile-backup-preview', - 'profile-backup-recovery', - 'prompt-parts', - 'prompt-presets', - 'question-deliveries', - 'release-check', - 'release-info', - 'roster', - 'schedule-history', - 'schedule-preview', - 'schedules', - 'search', - 'secret-list', - 'send-status', - 'session-ids', - 'session-owner', - 'session-subagents', - 'settings', - 'share-draft-file', - 'share-draft-show', - 'show', - 'storage-cleanup-preview', - 'storage-messages-cleanup-preview', - 'storage-usage', - 'takeover-status', - 'takeovers', - 'telemetry-status', - 'todo-tools', - 'todos', - 'tool-approval-history', - 'tool-approval-rules', - 'tool-approval-status', - 'update-status', - 'user-question-status', - 'voice-defaults', - 'voice-providers', - 'wallpaper-get', - 'window-zoom-clients', - 'window-zoom-get', - 'window-zoom-setup-status', - 'workspace-options', -]); - const REFUSED_OPTIONS = ['--host', '--token-file', '--home', '--as', '--administration']; -const REFUSED_COMMANDS = new Set(['ssh-tunnel', 'voice-local-kit', 'audit', 'private']); +const REFUSED_COMMANDS = new Set(['ssh-tunnel', 'voice-local-kit', 'audit', 'private', 'tob-cli']); const MAX_ARGS = 256; const MAX_ARG_BYTES = 64 * 1024; const MAX_OUTPUT_BYTES = 8 * 1024 * 1024; @@ -284,7 +126,13 @@ export function classifyTobHostCli(argv: readonly string[]): { command: string; if (command === undefined || command.startsWith('-')) throw new TobError('invalid-request'); if (REFUSED_COMMANDS.has(command) || REFUSED_OPTIONS.some((name) => hasOption(argv, name))) throw new TobError('cli-command-refused'); - return { command, write: !TOB_HOST_CLI_READS.has(command) || hasOption(argv, '--out') }; + return { + command, + write: + !BROKER_CLI_READS.has(canonicalCliCommandName(command)) || + cliEffects(argv)?.changes !== 'none' || + hasOption(argv, '--out'), + }; } function input(args: Record): { argv: string[]; stdin: string; cwd?: string } { diff --git a/packages/core/src/tob/cli-invocation.ts b/packages/core/src/tob/cli-invocation.ts new file mode 100644 index 0000000000..fd959cb1e3 --- /dev/null +++ b/packages/core/src/tob/cli-invocation.ts @@ -0,0 +1,159 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { Agent } from '@deepseek-ai/dsh-agent'; +import type { ToolCallId } from '@deepseek-ai/dsh-llm'; +import type { ResolvedToolSet, ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools'; +import { tobCliCommandSchema, type TobCliCommand } from './cli-request.js'; +import { TobError } from './service.js'; + +interface Registration { + definition: ToolDefinition; + captureAuthority(): () => void; +} +interface Invocation { + agent: Agent; + callId: ToolCallId; + command: TobCliCommand; + toolSet: ResolvedToolSet; + signal: AbortSignal; + requireCurrentTurn(): void; +} +interface Lease extends Invocation { + registration: Registration; + authorize(): void; + nativeTurn: number; + active: boolean; + token: ToolExecution['token'] | undefined; +} +export class ModelFreeTobCliInvocation { + readonly #registrations = new WeakMap(); + readonly #invocation = new AsyncLocalStorage(); + readonly #active = new WeakMap(); + + register( + agent: Agent, + definition: ToolDefinition, + captureAuthority: () => () => void, + ): () => void { + const registration = { definition, captureAuthority }; + this.#registrations.set(agent, registration); + return () => { + if (this.#registrations.get(agent) === registration) this.#registrations.delete(agent); + }; + } + + async run(input: Invocation, execute: () => Promise): Promise { + const registration = this.#registrations.get(input.agent); + const nativeTurn = this.#nativeTurn(input.agent); + if ( + !registration || + nativeTurn === null || + this.#active.has(input.agent) || + this.#invocation.getStore()?.active + ) + throw new TobError('tob-authority-required'); + const lease: Lease = { + ...input, + command: { argv: [...input.command.argv], stdin: input.command.stdin }, + registration, + authorize: registration.captureAuthority(), + nativeTurn, + active: true, + token: undefined, + }; + this.#active.set(input.agent, lease); + try { + this.#validate(lease); + return await this.#invocation.run(lease, execute); + } finally { + lease.active = false; + this.#active.delete(input.agent); + } + } + delegate(execution: ToolExecution): 'unrelated' | 'delegated' | 'refused' { + if (execution.name !== 'deepseekbot_cli') return 'unrelated'; + const active = this.#invocation.getStore(); + const owned = active !== undefined && execution.callId === active.callId; + if (!owned) { + const registration = execution.agent && this.#registrations.get(execution.agent); + if (registration === undefined) return 'unrelated'; + if (!execution.agent || !execution.toolSet) return 'refused'; + try { + const definition = execution.toolSet.view(execution.agent).get(execution.name); + if (definition === undefined) return 'refused'; + if (definition !== registration.definition) return 'unrelated'; + } catch { + return 'refused'; + } + } + try { + const lease = this.#matching(execution); + if (lease.token !== undefined && lease.token !== execution.token) return 'refused'; + lease.token = execution.token; + return 'delegated'; + } catch { + return 'refused'; + } + } + + require(execution: ToolExecution): void { + const lease = this.#matching(execution); + if (lease.token !== execution.token) throw new TobError('tob-authority-required'); + } + + guard(execution: ToolExecution): string | undefined { + const lease = this.#invocation.getStore(); + if (lease?.token !== execution.token) return undefined; + try { + this.require(execution); + return undefined; + } catch { + return 'The owned CLI invocation authority changed before execution'; + } + } + + #matching(execution: ToolExecution): Lease { + const lease = this.#invocation.getStore(); + if ( + !lease || + execution.agent !== lease.agent || + execution.name !== 'deepseekbot_cli' || + execution.callId !== lease.callId || + execution.rootCallId !== lease.callId || + execution.parent !== undefined || + execution.schema !== undefined || + execution.toolSet !== lease.toolSet || + execution.signal !== lease.signal + ) + throw new TobError('tob-authority-required'); + const parsed = tobCliCommandSchema.safeParse(execution.arguments); + if ( + !parsed.success || + parsed.data.stdin !== lease.command.stdin || + parsed.data.argv.length !== lease.command.argv.length || + parsed.data.argv.some((value, index) => value !== lease.command.argv[index]) + ) + throw new TobError('tob-authority-required'); + this.#validate(lease); + return lease; + } + + #nativeTurn(agent: Agent): number | null { + const agents = agent.ctx.get('agents'); + if (typeof agents?.turnBoundaryOf !== 'function') throw new TobError('tob-authority-required'); + return agents.turnBoundaryOf(agent.session).openTurnStartSeq; + } + + #validate(lease: Lease): void { + lease.signal.throwIfAborted(); + if ( + !lease.active || + this.#active.get(lease.agent) !== lease || + this.#registrations.get(lease.agent) !== lease.registration || + this.#nativeTurn(lease.agent) !== lease.nativeTurn || + lease.toolSet.view(lease.agent).get('deepseekbot_cli') !== lease.registration.definition + ) + throw new TobError('tob-authority-required'); + lease.requireCurrentTurn(); + lease.authorize(); + } +} diff --git a/packages/core/src/tob/cli-operations.ts b/packages/core/src/tob/cli-operations.ts index a0e70a1042..e095479e5f 100644 --- a/packages/core/src/tob/cli-operations.ts +++ b/packages/core/src/tob/cli-operations.ts @@ -7,10 +7,12 @@ export interface TobManagementProposal { readonly via?: 'cli'; } -export interface PreparedTobOperation { - readonly proposal?: TobManagementProposal; +export type PreparedTobOperation = ( + | { readonly proposal: TobManagementProposal; readonly completed?: never } + | { readonly proposal?: undefined; readonly completed?: true } +) & { run(guard: () => void, beforeEffect?: () => void): unknown | Promise; -} +}; export interface TobCliCapability { command: string; diff --git a/packages/core/src/tob/cli-request.ts b/packages/core/src/tob/cli-request.ts new file mode 100644 index 0000000000..118ba40d16 --- /dev/null +++ b/packages/core/src/tob/cli-request.ts @@ -0,0 +1,42 @@ +import { z } from 'zod'; + +export const tobCliCommandSchema = z + .object({ + argv: z.array(z.string()).min(1).max(256), + stdin: z.string().default(''), + }) + .strict() + .superRefine((command, context) => { + if ( + Buffer.byteLength(command.argv.join('\0')) > 64 * 1024 || + Buffer.byteLength(command.stdin) > 1024 * 1024 + ) + context.addIssue({ code: 'custom', message: 'CLI input exceeds its bound' }); + }); +export type TobCliCommand = z.infer; +export const tobCliRequestSchema = z.discriminatedUnion('action', [ + z.object({ action: z.literal('start'), command: tobCliCommandSchema }).strict(), + z.object({ action: z.literal('status'), id: z.string().uuid() }).strict(), + z.object({ action: z.literal('cancel'), id: z.string().uuid() }).strict(), +]); +export type TobCliRequest = z.infer; +export interface TobCliOutput { + exitCode: number; + stdout: string; + stderr: string; +} +export type TobCliStatus = { + id: string; + channelId: string; + messageId: string; + cancelRequested: boolean; +} & ( + | { state: 'running' } + | { state: 'completed'; result: TobCliOutput } + | { state: 'failed' | 'cancelled'; code: string } +); +export interface TobCliTurn { + command: TobCliCommand; + signal: AbortSignal; + complete(result: TobCliOutput): void; +} diff --git a/packages/core/src/tob/cli-shell.ts b/packages/core/src/tob/cli-shell.ts index ab63ceb168..8da39e81c8 100644 --- a/packages/core/src/tob/cli-shell.ts +++ b/packages/core/src/tob/cli-shell.ts @@ -1,3 +1,4 @@ +import { spawn } from 'node:child_process'; import { AsyncLocalStorage } from 'node:async_hooks'; import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -10,13 +11,20 @@ import { type ShellExecSpec, type ShellExecution, } from '@deepseek-ai/dsh-shell'; -import type { ToolExecution } from '@deepseek-ai/dsh-tools'; +import { defineTool, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools'; +import { tobCliCommandSchema } from './cli-request.js'; +import { TobError } from './service.js'; import { startTobCliBroker, type TobCliBrokerOptions } from './cli-broker.js'; export interface TobCliShellOptions { capture(execution: ToolExecution): TobCliBrokerOptions | undefined; cliPath?: string; + nativeCli?: { + available(): boolean; + register(definition: ToolDefinition): () => void; + require(execution: ToolExecution): void; + }; } const CLI_APPROVAL_WAIT_MS = 10 * 60 * 1000; const CLI_COMMAND = /(^|[\s;&|(`])deepseekbot(\s|$)/mu; @@ -80,7 +88,12 @@ export function installTobCliShell( const active = new Set<() => Promise>(); let shim: ReturnType | undefined; ctx.on('tools/execute', async (execution, next) => { - if (execution.name !== 'bash' && execution.name !== 'pwsh') return next(); + if ( + execution.name !== 'bash' && + execution.name !== 'pwsh' && + execution.name !== 'deepseekbot_cli' + ) + return next(); const call: Invocation = { execution, active: true, close: new Set() }; try { return await invocation.run(call, next); @@ -89,6 +102,123 @@ export function installTobCliShell( await Promise.all([...call.close].map((close) => close())); } }); + const nativeCli = options.nativeCli; + if (nativeCli !== undefined) { + const definition = defineTool({ + name: 'deepseekbot_cli', + description: + 'Run one typed deepseekbot command through the scoped Tob broker. Requires the owning live Human DM turn; writes retain their actual approval and execution fences.', + parameters: { + argv: { type: 'array', items: { type: 'string' }, required: true }, + stdin: { type: 'string' }, + }, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + async execute(args, execution) { + if (!nativeCli.available()) throw new TobError('tob-authority-required'); + nativeCli.require(execution); + const command = tobCliCommandSchema.parse(args); + const call = invocation.getStore(); + if (!call?.active || shutdown.signal.aborted) throw new TobError('agent-context-expired'); + const captured = options.capture(call.execution); + if (!captured) throw new TobError('tob-authority-required'); + const signal = AbortSignal.any([shutdown.signal, captured.signal, call.execution.signal]); + signal.throwIfAborted(); + captured.authorize(); + const cwd = call.execution.agent?.session.header.cwd; + if (!cwd) throw new TobError('tob-authority-required'); + const broker = await startTobCliBroker({ ...captured, signal }); + try { + const modulePath = pathToFileURL(options.cliPath ?? cliModulePath()).href; + const entry = `import { runBotCreateCli } from ${JSON.stringify(modulePath)}; +process.exitCode = await runBotCreateCli(process.argv.slice(1), { + env: process.env, + stdout: text => process.stdout.write(text + '\\n'), + stderr: text => process.stderr.write(text + '\\n'), + readStdin: async () => { const chunks = []; for await (const chunk of process.stdin) chunks.push(chunk); return Buffer.concat(chunks).toString('utf8'); } +});`; + const env = { ...process.env }; + for (const key of [ + 'DEEPSEEKBOT_HOST', + 'DEEPSEEKBOT_HOST_TOKEN', + 'DEEPSEEKBOT_AGENT_ENDPOINT', + 'DEEPSEEKBOT_AGENT_TOKEN', + ]) + delete env[key]; + env.DEEPSEEKBOT_AGENT_ENDPOINT = broker.endpoint; + env.DEEPSEEKBOT_AGENT_TOKEN = broker.token; + const output = await new Promise( + (resolve, reject) => { + const child = spawn( + process.execPath, + ['--input-type=module', '--eval', entry, '--', ...command.argv], + { + cwd, + env, + signal, + shell: false, + windowsHide: true, + stdio: ['pipe', 'pipe', 'pipe'], + }, + ); + let bytes = 0, + stdout = '', + stderr = '', + exceeded = false; + let failure: unknown; + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + const append = (chunk: string, stream: 'stdout' | 'stderr') => { + bytes += Buffer.byteLength(chunk); + if (bytes > 1024 * 1024) { + exceeded = true; + child.kill(); + return; + } + if (stream === 'stdout') stdout += chunk; + else stderr += chunk; + }; + child.stdout.on('data', (chunk: string) => append(chunk, 'stdout')); + child.stderr.on('data', (chunk: string) => append(chunk, 'stderr')); + child.once('error', (error) => { + failure = error; + }); + child.once('close', (exitCode) => { + if (failure !== undefined) { + reject(failure); + return; + } + if (exceeded) { + reject(new TobError('request-too-large')); + return; + } + const scrub = (text: string) => + text + .replaceAll(broker.token, '[redacted]') + .replaceAll(encodeURIComponent(broker.token), '[redacted]') + .replaceAll(broker.endpoint, '[scoped-cli]'); + resolve({ + exitCode: exitCode ?? 1, + stdout: scrub(stdout), + stderr: scrub(stderr), + }); + }); + child.stdin.on('error', () => {}); + child.stdin.end(command.stdin); + }, + ); + signal.throwIfAborted(); + return JSON.stringify(output); + } finally { + await broker.close(); + } + }, + }); + ctx.tools.register(definition, { when: () => nativeCli.available() }); + ctx.effect(() => nativeCli.register(definition), 'botharness: trusted typed CLI registration'); + } ctx.effect( () => async () => { shutdown.abort(); diff --git a/packages/core/src/tob/cli-voice-operations.ts b/packages/core/src/tob/cli-voice-operations.ts index 17087d4c51..8ebbd676c1 100644 --- a/packages/core/src/tob/cli-voice-operations.ts +++ b/packages/core/src/tob/cli-voice-operations.ts @@ -14,7 +14,7 @@ export const TOB_VOICE_CAPABILITIES = [ 'Add a keyless TTS or ASR Provider such as the local speech service', true, ], - ['voice-provider-test', 'Health-check a TTS or ASR Provider', false], + ['voice-provider-test', 'Health-check a TTS or ASR Provider', true], ['voice-provider-remove', 'Remove a voice Provider and the Bot bindings that use it', true], ['voice-set', 'Bind or clear a Bot voice', true], ['voice-asr-set', "Bind or clear a Bot's speech recognition", true], @@ -131,12 +131,16 @@ export function createTobVoiceOperations(deps: { keys(args, ['id', 'voiceId']); const id = text(args['id'], 64); const voiceId = optional(args['voiceId'], 200); + const previous = current(id); + if (previous === null) throw new TobError('unknown-provider'); + const patch = { id, ...(voiceId === undefined ? {} : { voiceId }) }; return { - run: async (guard) => { + proposal: proposal(command, id, previous, patch), + run: async (guard, beforeEffect) => { guard(); - return unwrap( - await bridge().voiceProviderTest({ id, ...(voiceId === undefined ? {} : { voiceId }) }), - ); + same(current(id), previous); + beforeEffect?.(); + return unwrap(await bridge().voiceProviderTest(patch)); }, }; } diff --git a/packages/core/src/workspaces/approval-template-deletion-contract.ts b/packages/core/src/workspaces/approval-template-deletion-contract.ts new file mode 100644 index 0000000000..61ee666540 --- /dev/null +++ b/packages/core/src/workspaces/approval-template-deletion-contract.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; + +export const approvalTemplateDeletionPreviewSchema = z.object({ + name: z.string().min(1), + revision: z.string().regex(/^[a-f0-9]{64}$/u), + globalDefaultBefore: z.string().nullable(), + globalDefaultAfter: z.string().nullable(), + globalDefaultAvailable: z.boolean(), + contentUnavailable: z.boolean().optional(), + hiddenBotCount: z.number().int().nonnegative(), + affectedBots: z.array( + z.object({ slug: z.string().min(1), source: z.enum(['specific', 'global']) }), + ), +}); + +export type ApprovalTemplateDeletionPreview = z.infer; diff --git a/packages/core/src/workspaces/approval-template-deletion.ts b/packages/core/src/workspaces/approval-template-deletion.ts new file mode 100644 index 0000000000..4af5601b37 --- /dev/null +++ b/packages/core/src/workspaces/approval-template-deletion.ts @@ -0,0 +1,140 @@ +import { createHash } from 'node:crypto'; +import type { PersonaBotRegistry } from '../bots/registry.js'; +import type { PersonaBotRecord } from '../bots/persona-bot.js'; +import type { ApprovalTemplateDeletionPreview } from './approval-template-deletion-contract.js'; +import { + INHERIT_APPROVAL_TEMPLATE, + isApprovalTemplateName, + type ApprovalTemplateLibrary, +} from './approval-templates.js'; + +type Failure = { + ok: false; + reason: + | 'invalid-name' + | 'not-found' + | 'built-in' + | 'selection-unavailable' + | 'confirmation-required' + | 'changed' + | 'unavailable' + | 'rollback-failed'; +}; + +export class ApprovalTemplateDeletion { + constructor( + private readonly library: ApprovalTemplateLibrary, + private readonly registry: Pick, + private readonly visible: (bot: PersonaBotRecord) => boolean, + ) {} + + preview(name: string): { ok: true; preview: ApprovalTemplateDeletionPreview } | Failure { + const result = this.plan(name); + return result.ok ? { ok: true, preview: result.preview } : result; + } + + private plan( + name: string, + ): { ok: true; preview: ApprovalTemplateDeletionPreview; inheritedBots: string[] } | Failure { + if (!isApprovalTemplateName(name)) return { ok: false, reason: 'invalid-name' }; + try { + const template = this.library.get(name); + const fileIdentity = + template === undefined ? this.library.customFileIdentity(name) : undefined; + if (template === undefined && fileIdentity === undefined) + return { ok: false, reason: 'not-found' }; + if (template?.builtIn) return { ok: false, reason: 'built-in' }; + const global = this.library.global(); + if (global.kind === 'invalid') return { ok: false, reason: 'selection-unavailable' }; + const before = global.kind === 'selected' ? global.name : null; + const after = before === name ? null : before; + const remaining = after === null ? undefined : this.library.get(after); + const bots = this.registry.list(); + const visibleSlugs = new Set(bots.filter(this.visible).map((bot) => bot.slug)); + const affectedBots = bots + .flatMap((bot) => + bot.approvalTemplate === name + ? [{ slug: bot.slug, source: 'specific' }] + : before === name && bot.approvalTemplate === INHERIT_APPROVAL_TEMPLATE + ? [{ slug: bot.slug, source: 'global' }] + : [], + ) + .sort((a, b) => a.slug.localeCompare(b.slug)); + const impact = { + name, + ...(template === undefined ? { contentUnavailable: true } : {}), + globalDefaultBefore: before, + globalDefaultAfter: after, + globalDefaultAvailable: remaining !== undefined, + affectedBots, + }; + const revision = createHash('sha256') + .update(JSON.stringify([impact, template?.text ?? { fileIdentity }, remaining?.text])) + .digest('hex'); + const visibleBots = affectedBots.filter((bot) => visibleSlugs.has(bot.slug)); + return { + ok: true, + preview: { + ...impact, + affectedBots: visibleBots, + hiddenBotCount: affectedBots.length - visibleBots.length, + revision, + }, + inheritedBots: affectedBots + .filter((bot) => bot.source === 'specific') + .map((bot) => bot.slug), + }; + } catch { + return { ok: false, reason: 'unavailable' }; + } + } + + delete( + name: string, + confirmation: { confirmed: boolean; revision?: string }, + ): { ok: true; preview: ApprovalTemplateDeletionPreview; inheritedBots: string[] } | Failure { + const current = this.plan(name); + if (!current.ok) return current; + if (!confirmation.confirmed || confirmation.revision === undefined) + return { ok: false, reason: 'confirmation-required' }; + if (confirmation.revision !== current.preview.revision) return { ok: false, reason: 'changed' }; + const preview = current.preview; + const changed: string[] = []; + let globalChanged = false; + const restore = (): boolean => { + let restored = true; + for (const slug of changed) + try { + if (!this.registry.setApprovalTemplate(slug, name).ok) restored = false; + } catch { + restored = false; + } + if (globalChanged) + try { + this.library.setGlobal(preview.globalDefaultBefore); + } catch { + restored = false; + } + return restored; + }; + try { + if (preview.globalDefaultBefore === name) { + globalChanged = true; + this.library.setGlobal(null); + } + for (const slug of current.inheritedBots) { + changed.push(slug); + if (!this.registry.setApprovalTemplate(slug, INHERIT_APPROVAL_TEMPLATE).ok) + throw new Error('Approval template reference changed'); + } + const deleted = this.library.delete(name); + if (!deleted.ok) { + if (!restore()) return { ok: false, reason: 'rollback-failed' }; + return { ok: false, reason: 'unavailable' }; + } + return { ok: true, preview, inheritedBots: changed }; + } catch { + return { ok: false, reason: restore() ? 'unavailable' : 'rollback-failed' }; + } + } +} diff --git a/packages/core/src/workspaces/approval-templates.ts b/packages/core/src/workspaces/approval-templates.ts index 120b967677..53854ccbc7 100644 --- a/packages/core/src/workspaces/approval-templates.ts +++ b/packages/core/src/workspaces/approval-templates.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { closeSync, existsSync, @@ -7,6 +8,7 @@ import { readSync, renameSync, rmSync, + statSync, writeFileSync, } from 'node:fs'; import { join } from 'node:path'; @@ -140,6 +142,7 @@ export interface ApprovalTemplateLibrary { setGlobal(name: string | null): void; list(): ApprovalTemplate[]; get(name: string): ApprovalTemplate | undefined; + customFileIdentity(name: string): string | undefined; create(name: string, text: string): ApprovalTemplateWriteResult; update(name: string, text: string): ApprovalTemplateWriteResult; delete(name: string): Exclude | { ok: true }; @@ -274,6 +277,29 @@ export function createApprovalTemplateLibrary(dir?: string): ApprovalTemplateLib const builtIn = approvalTemplate(name); return builtIn === undefined ? readCustom(name) : { ...builtIn }; }, + customFileIdentity(name) { + if (dir === undefined || !isApprovalTemplateName(name) || approvalTemplate(name)) return; + try { + const state = statSync(file(name), { bigint: true }); + if (!state.isFile()) return; + return createHash('sha256') + .update( + JSON.stringify( + [ + state.dev, + state.ino, + state.size, + state.mtimeNs, + state.ctimeNs, + state.birthtimeNs, + ].map((value) => value.toString()), + ), + ) + .digest('hex'); + } catch { + return undefined; + } + }, create(name, text) { const problem = check(name, text); if (problem !== undefined) return problem; diff --git a/packages/core/src/workspaces/grant-execution.ts b/packages/core/src/workspaces/grant-execution.ts index 52f00e9fb8..eb87f17f78 100644 --- a/packages/core/src/workspaces/grant-execution.ts +++ b/packages/core/src/workspaces/grant-execution.ts @@ -327,6 +327,7 @@ export function borrowedAgentDenial( } const BOT_TOOL_NAMES = new Set([ + 'deepseekbot_cli', 'speaker_policy', 'create_assignment', 'list_assignment_models', diff --git a/packages/core/src/workspaces/tool-approval.ts b/packages/core/src/workspaces/tool-approval.ts index 162b9d45ac..26ad418fec 100644 --- a/packages/core/src/workspaces/tool-approval.ts +++ b/packages/core/src/workspaces/tool-approval.ts @@ -7,7 +7,7 @@ import { createHash, randomUUID } from 'node:crypto'; import type { Agent } from '@deepseek-ai/dsh-agent'; import type { ToolExecution } from '@deepseek-ai/dsh-tools'; -import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'; +import type { ApprovalOutcome, ApprovalService } from '@deepseek-ai/dsh-user-approval'; import { dmChannelId, type ChannelMessage } from '../channels/channel.js'; import type { ChannelStore } from '../channels/store.js'; @@ -41,6 +41,7 @@ export type ToolApprovalReview = | { kind: 'review'; template: string; version: string; reason: string; fallback?: string }; export interface ToolApprovalRequestCard { + effects?: ToolEffects; approvalReview?: ToolApprovalReview; opaque?: boolean; decidedBy?: ApprovalDecider; @@ -105,7 +106,7 @@ type TrackedCall = ToolApprovalRequestCard & { rememberable?: boolean; remembered?: boolean; execution: ToolExecution; - effects: ToolEffects | undefined; + authorized?: () => boolean; device?: 'computer' | 'browser'; }; @@ -246,6 +247,7 @@ export class ChannelToolApproval { const scopeKey = this.#scope(agent, owner); if (scopeKey === undefined) return undefined; const key = callKey(agent.session.id, execution.callId); + const effects = toolEffects(execution.name, execution.arguments); const tracked: TrackedCall = { agent, botSlug: owner.botSlug, @@ -258,7 +260,7 @@ export class ChannelToolApproval { scopeKey, ...(options?.authorizationScope ? { authorizationScope: options.authorizationScope } : {}), execution, - effects: toolEffects(execution.name, execution.arguments), + ...(effects === undefined ? {} : { effects }), externalDecision, ...(options?.requireExplicitApproval ? { requireExplicitApproval: true } : {}), ...(rememberable && !options?.requireExplicitApproval ? { rememberable } : {}), @@ -319,16 +321,22 @@ export class ChannelToolApproval { } const origin = tracked.role === 'orchestrator' ? this.#askChannel?.(tracked.sessionId) : undefined; + if (tracked.role === 'orchestrator' && this.#askChannel !== undefined && origin === undefined) + return 'unavailable'; const originChannel = origin === undefined ? undefined : this.#channels.get(origin); - const channelId = - originChannel?.type === 'group' && originChannel.members.includes(tracked.botSlug) - ? originChannel.id - : dmChannelId(tracked.botSlug); const channel = - this.#channels.get(channelId) ?? - this.#channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, tracked.botSlug); + origin === undefined + ? (this.#channels.get(dmChannelId(tracked.botSlug)) ?? + this.#channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, tracked.botSlug)) + : originChannel; if (channel === undefined) return 'unavailable'; - if (channel.type !== 'group' && channel.botSlug !== tracked.botSlug) return 'unavailable'; + if ( + channel.type === 'group' + ? !channel.members.includes(tracked.botSlug) + : channel.botSlug !== tracked.botSlug + ) + return 'unavailable'; + const channelId = channel.id; if ( this.#decisionPolicy(tracked, { reviewer: true }).path === 'reviewer' && this.#overrides.delete(overrideKey(tracked)) @@ -375,6 +383,7 @@ export class ChannelToolApproval { role: tracked.role, cwd: tracked.cwd, input: tracked.input, + ...(tracked.effects === undefined ? {} : { effects: tracked.effects }), ...(tracked.approvalReview === undefined ? {} : { approvalReview: tracked.approvalReview }), externalDecision: tracked.externalDecision ?? 'operation', allowAlways: policy.rememberable, @@ -1117,6 +1126,25 @@ export class ChannelToolApproval { } } +export async function requestRequiredToolApproval({ + approval, + channelApproval, + ownership, + request, + forceChannel, +}: { + approval: Pick; + channelApproval: Pick; + ownership: Pick; + request: Parameters[0]; + forceChannel: boolean; +}): Promise { + const owner = ownership.resolve(request.agent.session.id); + if (forceChannel && owner !== undefined && owner.parentSessionId === undefined) + return (await channelApproval.ask(request)) ?? 'unavailable'; + return approval.request(request); +} + export function registerChannelToolApproval( ctx: Context, approval: Pick, diff --git a/packages/core/src/workspaces/tool-effect-labels.ts b/packages/core/src/workspaces/tool-effect-labels.ts new file mode 100644 index 0000000000..6f5f1cc5d8 --- /dev/null +++ b/packages/core/src/workspaces/tool-effect-labels.ts @@ -0,0 +1,36 @@ +import type { ToolEffects } from './tool-effects.js'; + +export function toolEffectLabels(effects: ToolEffects, locale: 'en' | 'zh'): string[] { + const labels = + locale === 'zh' + ? { + changes: { none: '只读', reversible: '可撤销更改', irreversible: '不可撤销' }, + reach: { local: '本机', memory: '记忆', workspace: '工作区', external: '外部影响' }, + personalData: '涉及个人数据', + secrets: '使用密钥', + management: '权限管理', + } + : { + changes: { + none: 'Read only', + reversible: 'Reversible changes', + irreversible: 'Irreversible', + }, + reach: { + local: 'Local', + memory: 'Memory', + workspace: 'Workspace', + external: 'External effect', + }, + personalData: 'Personal data', + secrets: 'Uses secrets', + management: 'Permission management', + }; + return [ + labels.changes[effects.changes], + labels.reach[effects.reach], + ...(effects.personalData ? [labels.personalData] : []), + ...(effects.secrets ? [labels.secrets] : []), + ...(effects.authority === 'management' ? [labels.management] : []), + ]; +} diff --git a/packages/core/src/workspaces/tool-effects-contract.ts b/packages/core/src/workspaces/tool-effects-contract.ts new file mode 100644 index 0000000000..9d90def7f1 --- /dev/null +++ b/packages/core/src/workspaces/tool-effects-contract.ts @@ -0,0 +1,22 @@ +import * as z from 'zod/mini'; + +export const toolEffectsSchema = z.object({ + changes: z.enum(['none', 'reversible', 'irreversible']), + reach: z.enum(['local', 'memory', 'workspace', 'external']), + personalData: z.boolean(), + authority: z.optional(z.literal('management')), + secrets: z.optional(z.boolean()), +}); + +export type ToolEffects = Readonly>; + +export function parseToolEffects(value: unknown): ToolEffects | undefined { + const result = z.safeParse(toolEffectsSchema, value); + if (!result.success) return undefined; + const { authority, secrets, ...required } = result.data; + return { + ...required, + ...(authority === undefined ? {} : { authority }), + ...(secrets === undefined ? {} : { secrets }), + }; +} diff --git a/packages/core/src/workspaces/tool-effects.ts b/packages/core/src/workspaces/tool-effects.ts index f0febb8240..79e0b8e49a 100644 --- a/packages/core/src/workspaces/tool-effects.ts +++ b/packages/core/src/workspaces/tool-effects.ts @@ -1,12 +1,8 @@ +import { cliEffects, brokerCliEffects } from '../bots/cli-effects.js'; import { requiresHumanDecision } from './approval-templates.js'; -export interface ToolEffects { - readonly changes: 'none' | 'reversible' | 'irreversible'; - readonly reach: 'local' | 'memory' | 'workspace' | 'external'; - readonly personalData: boolean; - readonly authority?: 'management'; - readonly secrets?: boolean; -} +import type { ToolEffects } from './tool-effects-contract.js'; +export type { ToolEffects } from './tool-effects-contract.js'; type Declaration = ToolEffects & { readonly approval: 'native' | 'existing' | 'always' | 'attachment'; @@ -26,6 +22,7 @@ const computerRead: Declaration = { ...read, approval: 'native' }; const computerAct: Declaration = { ...send, approval: 'native' }; export const FIRST_PARTY_TOOL_EFFECTS = { + deepseekbot_cli: write, archive_assignment: write, ask_secret: { ...write, secrets: true }, ask_user_question: write, @@ -145,6 +142,18 @@ function inputText(args: unknown): string { } export function toolEffects(name: string, args: unknown): ToolEffects | undefined { + if (name === 'deepseekbot_cli') { + if ( + typeof args !== 'object' || + args === null || + !('argv' in args) || + !Array.isArray(args.argv) || + !args.argv.every((arg): arg is string => typeof arg === 'string') + ) + return undefined; + return cliEffects(args.argv); + } + if (name.startsWith('deepseekbot ')) return brokerCliEffects(name, args); const declared = declaration(name); if (!declared) return undefined; const { approval: _approval, ...effects } = declared; @@ -243,20 +252,27 @@ export interface ToolApprovalPath { | 'human-required'; } +export function hasIrreversibleExternalEffect(effects: ToolEffects | undefined): boolean { + return effects?.changes === 'irreversible' && effects.reach === 'external'; +} + export function decideToolApproval( effects: ToolEffects | undefined, context: ToolApprovalContext, ): ToolApprovalPath { if (context.stage === 'admission') { + const management = context.legacyProtected || effects?.authority === 'management'; const required = + hasIrreversibleExternalEffect(effects) || + effects?.authority === 'management' || context.admission === 'always' || (context.admission === 'attachment' && effects?.changes !== 'none') || context.legacyProtected; return { path: required ? 'request' : 'native', rememberable: true, - explicitRule: context.legacyProtected, - reason: context.legacyProtected + explicitRule: management, + reason: management ? 'protected-operation' : required ? 'effect-approval' @@ -269,7 +285,12 @@ export function decideToolApproval( context.legacyProtected || context.explicitApproval || effects?.authority === 'management'; const explicitRule = explicit || context.device; const rememberable = !context.eachUse || context.rememberable; - if (!explicit && !context.eachUse && context.fullAccess) + if ( + !explicit && + !hasIrreversibleExternalEffect(effects) && + !context.eachUse && + context.fullAccess + ) return { path: 'full-access', rememberable, explicitRule, reason: 'full-access-existing' }; if ( !context.eachUse && diff --git a/packages/core/test/approval-template-deletion-persistence.test.ts b/packages/core/test/approval-template-deletion-persistence.test.ts new file mode 100644 index 0000000000..8126a59496 --- /dev/null +++ b/packages/core/test/approval-template-deletion-persistence.test.ts @@ -0,0 +1,98 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { PersonaBotRecord } from '../src/bots/persona-bot.js'; +import { createPersonaBotRegistry } from '../src/bots/registry.js'; +import { attachOperationalModule, mountOperationalDatabase } from '../src/database/owner.js'; +import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; +import { ApprovalTemplateDeletion } from '../src/workspaces/approval-template-deletion.js'; +import { createApprovalTemplateLibrary } from '../src/workspaces/approval-templates.js'; + +describe('Approval Template deletion persistence budget', () => { + it.each([20, 80])( + 'persists %i fallbacks with linear owner work and survives reopening', + (count) => { + const home = mkdtempSync(join(tmpdir(), 'approval-delete-persistence-')); + const rootDir = join(home, 'botharness', 'bots'); + let database = mountOperationalDatabase({ + dshHome: home, + schemaPlan: BOT_HARNESS_SCHEMA_PLAN, + }); + try { + const registry = createPersonaBotRegistry({ rootDir, database }); + const records: PersonaBotRecord[] = Array.from({ length: count }, (_, index) => ({ + slug: 'reference-' + index, + displayName: 'Reference ' + index, + createdAt: '2026-11-16T00:00:00Z', + workspaces: [], + approvalTemplate: 'night-shift', + })); + const controls: PersonaBotRecord[] = [ + { + slug: 'inherit', + displayName: 'Inherit', + createdAt: '2026-11-16', + workspaces: [], + approvalTemplate: '@global', + }, + { slug: 'off', displayName: 'Off', createdAt: '2026-11-16', workspaces: [] }, + { + slug: 'other', + displayName: 'Other', + createdAt: '2026-11-16', + workspaces: [], + approvalTemplate: 'cautious', + }, + ]; + attachOperationalModule(database, 'deletion-scale-fixture').transaction((db) => { + const insert = db.prepare( + 'INSERT INTO persona_bots (slug, body, owner_human_id) VALUES (?, ?, ?)', + ); + for (const record of [...records, ...controls]) + insert.run(record.slug, JSON.stringify(record), 'local-human'); + }); + const libraryDir = join(home, 'approval-templates'); + const library = createApprovalTemplateLibrary(libraryDir); + expect(library.create('night-shift', '# Night shift\n')).toMatchObject({ ok: true }); + library.setGlobal('get-work-done'); + const deletion = new ApprovalTemplateDeletion(library, registry, () => true); + const preview = deletion.preview('night-shift'); + if (!preview.ok) throw new Error(preview.reason); + expect(preview.preview.affectedBots).toHaveLength(count); + const before = database.diagnostics().metrics; + const result = deletion.delete('night-shift', { + confirmed: true, + revision: preview.preview.revision, + }); + const after = database.diagnostics().metrics; + expect(result).toMatchObject({ + ok: true, + inheritedBots: expect.arrayContaining(records.map((record) => record.slug)), + }); + expect(after.transactionsCommitted - before.transactionsCommitted).toBeLessThanOrEqual( + count, + ); + const maxRegistryReads = 1 + records.length + controls.length + 2 * count; + expect(after.reads - before.reads).toBeLessThanOrEqual(maxRegistryReads); + expect(after.transactionsRolledBack - before.transactionsRolledBack).toBe(0); + expect(library.get('night-shift')).toBeUndefined(); + expect(library.global()).toEqual({ kind: 'selected', name: 'get-work-done' }); + const savedControls = controls.map((record) => registry.get(record.slug)); + database.close(); + database = mountOperationalDatabase({ dshHome: home, schemaPlan: BOT_HARNESS_SCHEMA_PLAN }); + const reopened = createPersonaBotRegistry({ rootDir, database }); + for (const record of records) + expect(reopened.get(record.slug)?.approvalTemplate).toBe('@global'); + expect(controls.map((record) => reopened.get(record.slug))).toEqual(savedControls); + expect(createApprovalTemplateLibrary(libraryDir).global()).toEqual({ + kind: 'selected', + name: 'get-work-done', + }); + } finally { + database.close(); + rmSync(home, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/packages/core/test/approval-template-library.test.ts b/packages/core/test/approval-template-library.test.ts index d4a5db5bb7..2b74d5ee73 100644 --- a/packages/core/test/approval-template-library.test.ts +++ b/packages/core/test/approval-template-library.test.ts @@ -369,10 +369,11 @@ describe('self-escalation guard for Approval Templates', () => { }); describe('Approval Template bridge methods', () => { - function methods() { + function methods(extra: Partial[] = []) { const registry = fakeRegistry([ { slug: 'ada', approvalTemplate: 'night-shift' }, { slug: 'bob' }, + ...extra, ]); const dir = join(tempDir(), 'approval-templates'); const library = createApprovalTemplateLibrary(dir); @@ -489,14 +490,222 @@ describe('Approval Template bridge methods', () => { }); }); - it('clears the selection of every Bot that used a deleted template', () => { - const { bridge, registry } = methods(); + it('does not delete or change references before explicit confirmation', () => { + const { bridge, registry, library } = methods(); bridge.approvalTemplateCreate({ name: 'night-shift', text: MINE }); - expect(bridge.approvalTemplateDelete({ name: 'night-shift' })).toEqual({ + expect(bridge.approvalTemplateDelete({ name: 'night-shift' })).toMatchObject({ + ok: false, + error: { code: 'confirmation-required' }, + }); + expect(library.get('night-shift')?.text).toBe(MINE); + expect(registry.get('ada')?.approvalTemplate).toBe('night-shift'); + }); + + it('previews every direct reference and confirms one bulk fallback to another global template', () => { + const { bridge, registry, library } = methods([ + { slug: 'carol', approvalTemplate: '@global' }, + { slug: 'dave', approvalTemplate: 'get-work-done' }, + ]); + library.create('night-shift', MINE); + library.setGlobal('cautious'); + const initial = registry.bots.map((bot) => ({ ...bot })); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + expect(preview.value.preview).toMatchObject({ + name: 'night-shift', + globalDefaultBefore: 'cautious', + globalDefaultAfter: 'cautious', + globalDefaultAvailable: true, + affectedBots: [{ slug: 'ada', source: 'specific' }], + }); + expect(registry.bots).toEqual(initial); + expect(library.get('night-shift')?.text).toBe(MINE); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: true, - value: { template: { name: 'night-shift' }, clearedBots: ['ada'] }, + value: { inheritedBots: ['ada'], globalDefault: 'cautious' }, + }); + expect(registry.bots).toEqual( + initial.map((bot) => (bot.slug === 'ada' ? { ...bot, approvalTemplate: '@global' } : bot)), + ); + expect(library.get('night-shift')).toBeUndefined(); + expect(bridge.approvalTemplates({ slug: 'ada' })).toMatchObject({ + value: { selected: '@global', effective: 'cautious' }, }); - expect(registry.get('ada')?.approvalTemplate).toBeUndefined(); + }); + + it('shows inherited users and clears the default when deleting the global template', () => { + const { bridge, registry, library } = methods([ + { slug: 'carol', approvalTemplate: 'cautious' }, + ]); + library.create('night-shift', MINE); + library.setGlobal('night-shift'); + registry.setApprovalTemplate('bob', '@global'); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + expect(preview.value.preview).toMatchObject({ + globalDefaultBefore: 'night-shift', + globalDefaultAfter: null, + affectedBots: [ + { slug: 'ada', source: 'specific' }, + { slug: 'bob', source: 'global' }, + ], + }); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: true, value: { inheritedBots: ['ada'], globalDefault: null } }); + expect(library.global()).toEqual({ kind: 'off' }); + expect(registry.get('carol')?.approvalTemplate).toBe('cautious'); + for (const slug of ['ada', 'bob']) + expect(bridge.approvalTemplates({ slug })).toMatchObject({ + value: { selected: '@global', effective: null, source: 'global' }, + }); + }); + + it.each(['global', 'references', 'content', 'global-content'] as const)( + 'refuses stale confirmation after %s changes without mutating any choices', + (change) => { + const { bridge, registry, library } = methods(); + library.create('night-shift', MINE); + library.create('other', '# Other\n\nAsk me.\n'); + library.setGlobal('other'); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + if (change === 'global') library.setGlobal('cautious'); + if (change === 'references') registry.setApprovalTemplate('bob', 'night-shift'); + if (change === 'content') library.update('night-shift', MINE + 'Changed.\n'); + if (change === 'global-content') library.update('other', '# Other\n\nDifferent policy.\n'); + const before = registry.bots.map((bot) => ({ ...bot })); + const globalBefore = library.global(); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: false, error: { code: 'approval-template-delete-changed' } }); + expect(registry.bots).toEqual(before); + expect(library.global()).toEqual(globalBefore); + expect(library.get('night-shift')).toBeDefined(); + }, + ); + + it('explicitly deletes oversized custom content and keeps bulk fallback and global clearing', () => { + const { bridge, registry, library, dir } = methods(); + library.create('night-shift', MINE); + library.setGlobal('night-shift'); + registry.setApprovalTemplate('bob', '@global'); + const file = join(dir, 'night-shift.md'); + writeFileSync(file, 'x'.repeat(APPROVAL_TEMPLATE_TEXT_LIMIT + 1)); + expect(library.get('night-shift')).toBeUndefined(); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + expect(preview.value.preview).toMatchObject({ + contentUnavailable: true, + globalDefaultAfter: null, + affectedBots: [ + { slug: 'ada', source: 'specific' }, + { slug: 'bob', source: 'global' }, + ], + }); + expect(bridge.approvalTemplateDelete({ name: 'night-shift' })).toMatchObject({ + ok: false, + error: { code: 'confirmation-required' }, + }); + expect(existsSync(file)).toBe(true); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: true, value: { inheritedBots: ['ada'], globalDefault: null } }); + expect(existsSync(file)).toBe(false); + expect(registry.get('ada')?.approvalTemplate).toBe('@global'); + expect(registry.get('bob')?.approvalTemplate).toBe('@global'); + expect(library.global()).toEqual({ kind: 'off' }); + }); + + it.each(['grow', 'repair'] as const)('refuses stale oversized deletion after %s', (change) => { + const { bridge, registry, library, dir } = methods(); + library.create('night-shift', MINE); + const file = join(dir, 'night-shift.md'); + writeFileSync(file, 'x'.repeat(APPROVAL_TEMPLATE_TEXT_LIMIT + 1)); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + writeFileSync(file, change === 'repair' ? MINE : 'x'.repeat(APPROVAL_TEMPLATE_TEXT_LIMIT + 2)); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: false, error: { code: 'approval-template-delete-changed' } }); + expect(existsSync(file)).toBe(true); + expect(registry.get('ada')?.approvalTemplate).toBe('night-shift'); + }); + + it('refuses unreadable selection instead of silently choosing a deletion fallback', () => { + const { bridge, registry, library, dir } = methods(); + library.create('night-shift', MINE); + writeFileSync(join(dir, '.selection.json'), '{bad'); + expect(bridge.approvalTemplateDeletePreview({ name: 'night-shift' })).toMatchObject({ + ok: false, + error: { code: 'approval-selection-unavailable' }, + }); + expect( + bridge.approvalTemplateDelete({ name: 'night-shift', confirmed: true, revision: 'x' }), + ).toMatchObject({ ok: false, error: { code: 'approval-selection-unavailable' } }); + expect(registry.get('ada')?.approvalTemplate).toBe('night-shift'); + expect(library.get('night-shift')).toBeDefined(); + expect(readFileSync(join(dir, '.selection.json'), 'utf8')).toBe('{bad'); + }); + + it('restores the original choices if the final file deletion fails', () => { + const { bridge, registry, library } = methods(); + library.create('night-shift', MINE); + library.setGlobal('night-shift'); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + vi.spyOn(library, 'delete').mockReturnValue({ ok: false, reason: 'unavailable' }); + expect( + bridge.approvalTemplateDelete({ + name: 'night-shift', + confirmed: true, + revision: preview.value.preview.revision, + }), + ).toMatchObject({ ok: false, error: { code: 'approval-template-delete-unavailable' } }); + expect(library.global()).toEqual({ kind: 'selected', name: 'night-shift' }); + expect(registry.get('ada')?.approvalTemplate).toBe('night-shift'); + expect(library.get('night-shift')?.text).toBe(MINE); + }); + + it('reads the global choice and registry once per preview across a thousand references', () => { + const { bridge, registry, library } = methods( + Array.from({ length: 1000 }, (_, index) => ({ + slug: 'ref-' + index, + approvalTemplate: 'night-shift', + })), + ); + library.create('night-shift', MINE); + const globalReads = vi.spyOn(library, 'global'); + const registryReads = vi.spyOn(registry, 'list'); + const registryGets = vi.spyOn(registry, 'get'); + const preview = bridge.approvalTemplateDeletePreview({ name: 'night-shift' }); + if (!preview.ok) throw new Error(preview.error.code); + expect(preview.value.preview.affectedBots).toHaveLength(1001); + expect(globalReads).toHaveBeenCalledTimes(1); + expect(registryReads).toHaveBeenCalledTimes(1); + expect(registryGets).not.toHaveBeenCalled(); }); it('refuses with codes', () => { @@ -600,6 +809,10 @@ describe('deepseekbot approval-template', () => { await invoke(['approval-template', 'create', 'mine', '--from', 'cautious'], live.url); await invoke(['approval-template', 'edit', 'mine', '--text-stdin'], live.url, MINE); await invoke(['approval-template', 'delete', 'mine'], live.url); + await invoke( + ['approval-template', 'delete', 'mine', '--confirm', '--delete-revision', 'a'.repeat(64)], + live.url, + ); await invoke(['approval-template-global-set', 'cautious'], live.url); await invoke(['approval-template-global-set', 'off'], live.url); await invoke(['approval-template-set', 'ada', 'inherit'], live.url); @@ -607,7 +820,11 @@ describe('deepseekbot approval-template', () => { { method: 'approvalTemplateCreate', args: { name: 'night-shift', text: MINE } }, { method: 'approvalTemplateCreate', args: { name: 'mine', from: 'cautious' } }, { method: 'approvalTemplateUpdate', args: { name: 'mine', text: MINE } }, - { method: 'approvalTemplateDelete', args: { name: 'mine' } }, + { method: 'approvalTemplateDeletePreview', args: { name: 'mine' } }, + { + method: 'approvalTemplateDelete', + args: { name: 'mine', confirmed: true, revision: 'a'.repeat(64) }, + }, { method: 'approvalTemplateGlobalSet', args: { template: 'cautious' } }, { method: 'approvalTemplateGlobalSet', args: { template: null } }, { method: 'botApprovalTemplateSet', args: { slug: 'ada', template: '@global' } }, @@ -688,6 +905,9 @@ describe('deepseekbot approval-template', () => { ['approval-template', 'edit'], ['approval-template', 'delete', 'a', 'b'], ['approval-template', 'list', '--literal-template'], + ['approval-template', 'delete', 'a', '--confirm'], + ['approval-template', 'delete', 'a', '--delete-revision', 'a'.repeat(64)], + ['approval-template', 'delete', 'a', '--confirm', '--delete-revision', 'bad'], ]) { const result = await invoke(argv, live.url); expect(result.code, argv.join(' ')).not.toBe(0); diff --git a/packages/core/test/auto-approval-breaker.test.ts b/packages/core/test/auto-approval-breaker.test.ts index 60a61b9fb7..7f2e3520d0 100644 --- a/packages/core/test/auto-approval-breaker.test.ts +++ b/packages/core/test/auto-approval-breaker.test.ts @@ -43,6 +43,7 @@ function fixture(fullAccess?: () => boolean) { const outcome = verdicts.shift() ?? 'ask-human'; return { outcome, reason: outcome === 'allow' ? 'Fine.' : 'Not under this template.' }; }); + const template = vi.fn(() => ({ name: 'cautious', text: '# Cautious' })); broker = new ChannelToolApproval( core.channels, core.ownership, @@ -52,7 +53,7 @@ function fixture(fullAccess?: () => boolean) { undefined, undefined, { - template: () => ({ name: 'cautious', text: '# Cautious' }), + template, review, log: () => undefined, }, @@ -91,6 +92,7 @@ function fixture(fullAccess?: () => boolean) { broker, methods, review, + template, verdicts, channelId, sessionId, @@ -146,9 +148,27 @@ describe('two-outcome Reviewer Human control', () => { ); expect(await first).toBe('allowed-once'); f.review.mockClear(); + f.template.mockClear(); expect(await f.call('different input')).toBe('allowed-once'); expect(f.review).not.toHaveBeenCalled(); expect(f.messages().filter((message) => message.toolApprovalRequest)).toHaveLength(1); + expect(f.template).not.toHaveBeenCalled(); + const listed = f.methods.toolApprovalRules({ slug: 'ada' }); + expect(listed.ok).toBe(true); + if (!listed.ok) throw new Error('Expected canonical rules'); + const rule = listed.value.rules[0]!; + expect(rule).toMatchObject({ + botSlug: 'ada', + role: 'orchestrator', + scopeKey: 'qa-scope', + kind: 'tool', + }); + expect(f.methods.toolApprovalRuleRevoke({ slug: 'ada', id: rule.id }).ok).toBe(true); + f.verdicts.push('allow'); + expect(await f.call('different input')).toBe('allowed-once'); + expect(f.review).toHaveBeenCalledTimes(1); + expect(f.core.toolRules.list('ada')).toHaveLength(1); + expect(f.core.toolRules.list('ada')[0]?.revokedAt).toBeDefined(); }); it('keeps reviewing later calls after repeated Human rejections without pausing', async () => { const f = fixture(); diff --git a/packages/core/test/bot-message-tool.test.ts b/packages/core/test/bot-message-tool.test.ts index d134fd4c89..3f76f0e288 100644 --- a/packages/core/test/bot-message-tool.test.ts +++ b/packages/core/test/bot-message-tool.test.ts @@ -17,10 +17,11 @@ function receipt(value: unknown) { } function tools() { + const memoryDir = createTempRoot('bot-message-tool-memory-'); return createDshBotAgentAdapter({ agents: new FakeAgentHost(), defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, - orchestratorCwd: () => '/memory', + orchestratorCwd: () => memoryDir, }); } diff --git a/packages/core/test/bridge-methods.test.ts b/packages/core/test/bridge-methods.test.ts index 7995f498d7..b284c3004a 100644 --- a/packages/core/test/bridge-methods.test.ts +++ b/packages/core/test/bridge-methods.test.ts @@ -620,6 +620,7 @@ describe('bridge methods', () => { slug: 'ada', tool: 'channel_list', args: { limit: 1 }, + humanId: 'untrusted-payload-human', }), ).toEqual({ ok: true, @@ -637,6 +638,7 @@ describe('bridge methods', () => { expect.any(AbortSignal), undefined, undefined, + OWNER_HUMAN_CONTEXT, ); await methods.botToolRun({ slug: 'ada', @@ -651,6 +653,7 @@ describe('bridge methods', () => { expect.any(AbortSignal), 'assign-1', undefined, + OWNER_HUMAN_CONTEXT, ); expect( await methods.botToolRun({ diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index 24c02467e9..eab9956120 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -137,6 +137,35 @@ describe('bridge typert service', () => { expect(approve).not.toHaveBeenCalled(); }); + it('declares and forwards explicit template deletion confirmation through the Gateway', () => { + const { service, methods } = setup(); + const value = { + template: { name: 'night-shift' }, + clearedBots: [], + inheritedBots: [], + globalDefault: null, + }; + const deletion = vi + .spyOn(methods, 'approvalTemplateDelete') + .mockReturnValue({ ok: true, value }); + const revision = 'a'.repeat(64); + expect(parameterNames(service.approvalTemplateDelete)).toEqual([ + 'name', + 'confirmed', + 'revision', + ]); + expect(service.approvalTemplateDelete('night-shift', true, revision)).toEqual(value); + expect(deletion).toHaveBeenLastCalledWith({ name: 'night-shift', confirmed: true, revision }); + deletion.mockReturnValueOnce({ + ok: false, + error: { code: 'confirmation-required', message: 'confirmation-required' }, + }); + expect(() => service.approvalTemplateDelete('night-shift', false, revision)).toThrow( + expect.objectContaining({ code: 'confirmation-required' }), + ); + expect(deletion).toHaveBeenLastCalledWith({ name: 'night-shift', confirmed: false, revision }); + }); + it('forwards optional policy revisions and preserves stale-policy refusals', async () => { const { service, methods } = setup(); const set = vi.spyOn(methods, 'channelPolicySet').mockResolvedValue({ ok: true, value: null }); @@ -880,6 +909,7 @@ describe('bridge typert service', () => { 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'tobCli', 'channelSkillCatalog', 'botSkills', 'skillShow', @@ -985,6 +1015,7 @@ describe('bridge typert service', () => { 'botPromptSet', 'approvalTemplateCreate', 'approvalTemplateUpdate', + 'approvalTemplateDeletePreview', 'approvalTemplateDelete', 'approvalTemplateGlobalSet', 'botApprovalTemplateSet', @@ -1387,3 +1418,27 @@ it('exports the named Overview period and cursor through the existing Typert ser expect(parameterNames(service.overviewUsage)).toEqual(['period', 'after']); expect(() => service.overviewUsage('week')).toThrow('Usage statistics unavailable'); }); + +it('exposes named Tob CLI start/status/cancel arguments through the gateway facade', async () => { + const { service, methods } = setup(); + const response = { + id: 'lease', + channelId: 'dm-tob', + messageId: 'human-cli', + state: 'running' as const, + cancelRequested: false, + }; + const owner = vi.spyOn(methods, 'tobCli').mockResolvedValue({ ok: true, value: response }); + expect(parameterNames(service.tobCli)).toEqual(['action', 'command', 'id']); + expect(await service.tobCli('start', { argv: ['approval-templates'], stdin: '' })).toEqual( + response, + ); + expect(owner).toHaveBeenLastCalledWith({ + action: 'start', + command: { argv: ['approval-templates'], stdin: '' }, + }); + await service.tobCli('status', undefined, 'lease'); + expect(owner).toHaveBeenLastCalledWith({ action: 'status', id: 'lease' }); + await service.tobCli('cancel', undefined, 'lease'); + expect(owner).toHaveBeenLastCalledWith({ action: 'cancel', id: 'lease' }); +}); diff --git a/packages/core/test/channel-approval-routing.test.ts b/packages/core/test/channel-approval-routing.test.ts index 3a2b0457eb..b933f123f3 100644 --- a/packages/core/test/channel-approval-routing.test.ts +++ b/packages/core/test/channel-approval-routing.test.ts @@ -5,7 +5,11 @@ import { ApprovalService } from '@deepseek-ai/dsh-user-approval'; import { Session, SessionId } from '@deepseek-ai/dsh-session'; import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { registerChannelToolApproval } from '../src/workspaces/tool-approval.js'; +import { + registerChannelToolApproval, + requestRequiredToolApproval, +} from '../src/workspaces/tool-approval.js'; +import { createTestOwnership } from './helpers.js'; const contexts: Context[] = []; afterEach(async () => { @@ -92,3 +96,59 @@ describe('Channel approval routing through the native policy boundary', () => { expect(state.native).not.toHaveBeenCalled(); }); }); + +it.each(['secret_cli', 'computer_click', 'browser_open', 'deepseekbot approval-template-set'])( + 'keeps delegated native never ahead of the forced channel path for %s', + async (toolName) => { + const state = await fixture('never'); + const ownership = createTestOwnership(); + ownership.claim({ + sessionId: 'parent', + botSlug: 'ada', + rootRole: 'orchestrator', + at: new Date().toISOString(), + }); + ownership.claim({ + sessionId: state.agent.session.id, + botSlug: 'ada', + rootRole: 'assignment', + parentSessionId: 'parent', + provenance: 'subagent', + at: new Date().toISOString(), + }); + expect( + await requestRequiredToolApproval({ + approval: state.service, + channelApproval: { ask: state.answer }, + ownership, + forceChannel: true, + request: { agent: state.agent, toolName, callId: ToolCallId('owned') }, + }), + ).toBe('rejected'); + expect(state.answer).not.toHaveBeenCalled(); + expect(state.native).not.toHaveBeenCalled(); + expect(state.agent.session.snapshotEvents().map((event) => event.type)).toContain( + 'approval/decided', + ); + }, +); +it('keeps mandatory root approval separate from the native delegated policy', async () => { + const state = await fixture('never'); + const ownership = createTestOwnership(); + ownership.claim({ + sessionId: state.agent.session.id, + botSlug: 'ada', + rootRole: 'orchestrator', + at: new Date().toISOString(), + }); + expect( + await requestRequiredToolApproval({ + approval: state.service, + channelApproval: { ask: state.answer }, + ownership, + forceChannel: true, + request: { agent: state.agent, toolName: 'secret_cli', callId: ToolCallId('owned') }, + }), + ).toBe('allowed-once'); + expect(state.answer).toHaveBeenCalledOnce(); +}); diff --git a/packages/core/test/cli-bot-tool.test.ts b/packages/core/test/cli-bot-tool.test.ts index 79f9f98540..fb42178d9b 100644 --- a/packages/core/test/cli-bot-tool.test.ts +++ b/packages/core/test/cli-bot-tool.test.ts @@ -275,3 +275,31 @@ describe('Harness Bot tool runner commands', () => { expect(live.calls).toEqual([]); }); }); + +it('starts a model-free typed Tob CLI request without accepting actor or source authority', async () => { + const live = await host(() => ({ ok: true, value: { id: 'lease-1', state: 'running' } })); + const result = await invoke( + ['tob-cli', 'start', '--args-stdin'], + live.url, + JSON.stringify({ argv: ['approval-templates'], stdin: '' }), + ); + expect(result.code).toBe(0); + expect(result.json).toMatchObject({ id: 'lease-1', state: 'running' }); + expect(live.calls).toEqual([ + { + method: 'tobCli', + args: { action: 'start', command: { argv: ['approval-templates'], stdin: '' } }, + }, + ]); +}); + +it('refuses authority-selection flags on a typed Tob request before connecting', async () => { + const live = await host(() => ({ ok: true, value: { state: 'running' } })); + const result = await invoke( + ['tob-cli', 'start', '--cause-event', 'historical-source', '--args-stdin'], + live.url, + JSON.stringify({ argv: ['approval-templates'] }), + ); + expect(result.json).toMatchObject({ error: { code: 'agent-scope-denied' } }); + expect(live.calls).toHaveLength(0); +}); diff --git a/packages/core/test/cli-inbox.test.ts b/packages/core/test/cli-inbox.test.ts index 2a3c1903bf..65fb628043 100644 --- a/packages/core/test/cli-inbox.test.ts +++ b/packages/core/test/cli-inbox.test.ts @@ -1,6 +1,9 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { runBotCreateCli } from '../src/bots/bot-create-cli.js'; +import { brokerCliEffects, cliEffects } from '../src/bots/cli-effects.js'; +import { decideToolApproval } from '../src/workspaces/tool-effects.js'; +import { classifyTobHostCli } from '../src/tob/cli-host-commands.js'; const servers: ReturnType[] = []; afterEach(async () => { @@ -608,3 +611,53 @@ it('CLI requests Host notification discovery and refuses unsupported Hosts', asy 'Update the Host', ); }); + +describe('legacy Inbox CLI effect compatibility', () => { + it.each([ + ['inbox', 'activity', 'none', 'local'], + ['inbox-watch', 'activity-watch', 'none', 'local'], + ['inbox-status', 'activity-status', 'none', 'local'], + ['inbox-dismiss', 'activity-dismiss', 'reversible', 'local'], + ['inbox-restore', 'activity-restore', 'reversible', 'local'], + ['inbox-dismiss-all', 'activity-dismiss-all', 'reversible', 'local'], + ['inbox-allow-once', 'activity-allow-once', 'irreversible', 'external'], + ['inbox-ignore', 'activity-ignore', 'reversible', 'local'], + ['inbox-snooze', 'activity-snooze', 'reversible', 'local'], + ] as const)( + 'keeps %s and %s on the same direct and broker policy', + (legacy, current, changes, reach) => { + const effects = { changes, reach, personalData: true }; + expect(classifyTobHostCli([legacy])).toEqual({ command: legacy, write: changes !== 'none' }); + expect(classifyTobHostCli([current])).toEqual({ + command: current, + write: changes !== 'none', + }); + expect(cliEffects([legacy])).toEqual(effects); + expect(cliEffects([current])).toEqual(effects); + expect(brokerCliEffects('deepseekbot ' + legacy, { patch: { argv: [legacy] } })).toEqual( + effects, + ); + expect(brokerCliEffects('deepseekbot ' + current, { patch: { argv: [current] } })).toEqual( + effects, + ); + }, + ); + + it('requires Human review for legacy allow-once even in Full Access', () => { + const effects = cliEffects(['inbox-allow-once', 'autoreject:src-1']); + expect(effects).toEqual({ changes: 'irreversible', reach: 'external', personalData: true }); + expect( + decideToolApproval(effects, { + stage: 'request', + fullAccess: true, + eachUse: false, + explicitApproval: false, + legacyProtected: false, + device: false, + standingRule: 'none', + reviewer: false, + rememberable: true, + }).path, + ).toBe('human'); + }); +}); diff --git a/packages/core/test/connect-network-inbox.test.ts b/packages/core/test/connect-network-inbox.test.ts index f108aa51b6..949dc668b9 100644 --- a/packages/core/test/connect-network-inbox.test.ts +++ b/packages/core/test/connect-network-inbox.test.ts @@ -55,6 +55,24 @@ it.each(['pending', 'started', 'alternate-network', 'lost-ack'] as const)( let eligible = true; let loseAck = phase === 'lost-ack'; let entered = 0; + let signalEntered: () => void = () => undefined; + const runEntered = new Promise((resolve) => { + signalEntered = resolve; + }); + const waitForEntered = async () => { + const core = cores[1]!; + await Promise.race([ + runEntered, + core.runtime.whenIdle().then(() => { + if (entered === 0) + throw new Error( + 'Orchestrator ended before the held fixture run entered: ' + + JSON.stringify(core.channels.readMessages('dm-bot')), + ); + }), + ]); + expect(entered).toBe(1); + }; let finished = false; let release!: () => void; const held = new Promise((resolve) => { @@ -79,6 +97,7 @@ it.each(['pending', 'started', 'alternate-network', 'lost-ack'] as const)( adapter.runOrchestrator = async () => { if (index !== 1) return; entered++; + signalEntered(); await held; if (phase === 'started') { try { @@ -197,7 +216,7 @@ it.each(['pending', 'started', 'alternate-network', 'lost-ack'] as const)( }; if (phase !== 'started') { await appendHuman(1, 'LOCAL_WORK'); - await expect.poll(() => entered).toBe(1); + await waitForEntered(); } const root = await appendHuman(0, 'ROOT'); const contacts = await cores[0]!.runtime.runDirectBotTool!( @@ -218,7 +237,7 @@ it.each(['pending', 'started', 'alternate-network', 'lost-ack'] as const)( if (phase === 'lost-ack') await expect(sending).rejects.toMatchObject({ code: 'delivery-unknown' }); else await sending; - if (phase === 'started') await expect.poll(() => entered).toBe(1); + if (phase === 'started') await waitForEntered(); expect(inbound()).toMatchObject({ ignored_at: null }); eligible = false; await Promise.all(bridges.map((bridge) => bridge.refresh())); diff --git a/packages/core/test/direct-bot-tools.test.ts b/packages/core/test/direct-bot-tools.test.ts index bd8f9f95bc..34eeedc34c 100644 --- a/packages/core/test/direct-bot-tools.test.ts +++ b/packages/core/test/direct-bot-tools.test.ts @@ -4,7 +4,10 @@ import { join } from 'node:path'; import { describe, expect, it, vi } from 'vitest'; import type { Agent } from '@deepseek-ai/dsh-agent'; -import type { Context } from '@deepseek-ai/cordis'; +import { ToolCallId } from '@deepseek-ai/dsh-llm'; +import { Context } from '@deepseek-ai/cordis'; +import { ToolRuntime } from '@deepseek-ai/dsh-tools'; +import { executeNativeTool, installNativeTools } from '../src/runtime/native-agent-compat.js'; import { createBotSubagentModelTools } from '../src/runtime/subagent-model-tools.js'; import { PRIVATE_INPUT_TOOLS } from '../src/credentials/tool-contract.js'; import { TAKEOVER_TOOLS } from '../src/takeover/contracts.js'; @@ -13,7 +16,7 @@ import { createChannelStore } from '../src/channels/store.js'; import { attachOperationalModule, mountOperationalDatabase } from '../src/database/owner.js'; import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; import { directToolTrace } from '../src/bots/tool-trace.js'; -import { createBotRuntime } from '../src/runtime/bot-runtime.js'; +import { createBotRuntime, DirectBotToolError } from '../src/runtime/bot-runtime.js'; import { createSessionOwnership } from '../src/sessions/ownership.js'; import { createDshBotAgentAdapter, @@ -31,7 +34,12 @@ function botToolNamesFrom(source: string): string[] { return block === null ? [] : [...block[1]!.matchAll(/'([a-z_]+)'/g)].map((name) => name[1]!); } -function setup() { +function setup( + suppressAssignmentReports = false, + observeDirectToolCleanupFailure?: Parameters< + typeof createDshBotAgentAdapter + >[0]['observeDirectToolCleanupFailure'], +) { const home = createTempRoot('botharness-direct-tools-'); const registry = createTestRegistry({ rootDir: join(home, 'bots'), now: FIXED_NOW }); expect(registry.create({ slug: 'ada', displayName: 'Ada' }).ok).toBe(true); @@ -40,9 +48,47 @@ function setup() { const owner = trackTestOwner( mountOperationalDatabase({ dshHome: home, schemaPlan: BOT_HARNESS_SCHEMA_PLAN }), ); - const host = new FakeAgentHost({ kind: 'completed' }); + const host = suppressAssignmentReports + ? new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => undefined }) + : new FakeAgentHost({ kind: 'completed' }); const agents = createDshBotAgentAdapter({ agents: host, + ...(observeDirectToolCleanupFailure === undefined ? {} : { observeDirectToolCleanupFailure }), + onAgentSetup: (ctx) => { + Object.assign(ctx.tools, { + execute: async (input: { + name: string; + arguments: unknown; + callId: string; + signal: AbortSignal; + }) => { + const tool = ctx.tools.get(input.name); + if (!tool) throw new Error('Missing fixture tool'); + const native = new Context(); + const providers = native.plugin({ + name: 'direct-test-services', + apply(c: Context) { + c.provide('systemPrompt', { + tools: () => () => undefined, + section: () => () => undefined, + getSectionOrder: () => 1, + }); + }, + }); + const runtime = native.plugin(ToolRuntime, {}); + try { + await providers.await(); + await runtime.await(); + native.tools.register(tool); + await native.inject(['tools'], (c) => installNativeTools(c)).await(); + return await executeNativeTool(native, { ...input, callId: ToolCallId(input.callId) }); + } finally { + await runtime.dispose(); + await providers.dispose(); + } + }, + }); + }, defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, orchestratorCwd: () => join(home, 'memory'), ensureWorkspace: () => undefined, @@ -58,7 +104,16 @@ function setup() { agents, now: FIXED_NOW, }); - return { runtime, channels, dm, host, registry, ownership, owner }; + return { + runtime, + channels, + dm, + host, + agents, + registry, + ownership, + owner, + }; } describe('direct Bot tool runner', () => { @@ -102,7 +157,9 @@ describe('direct Bot tool runner', () => { author: { kind: 'bot', slug: 'ada' }, }), ); - expect(host.sessions).toHaveLength(0); + expect(runtime.currentOrchestratorSessionId!('ada')).toBeUndefined(); + expect(host.received.size).toBe(0); + expect(host.disposed).toHaveLength(host.sessions.length); } finally { await runtime.close(); } @@ -125,7 +182,7 @@ describe('direct Bot tool runner', () => { } }); - it('lists runtime Bot tools while cloud_work has its dedicated direct CLI', () => { + it('lists direct Bot tools while cloud and admitted CLI keep their dedicated paths', async () => { const { runtime } = setup(); const listed = runtime.directBotTools!().map((tool) => tool.name); expect(listed).toContain('channel_list'); @@ -150,12 +207,23 @@ describe('direct Bot tool runner', () => { (name) => !exempt.includes(name) && name !== 'cloud_work' && + name !== 'deepseekbot_cli' && + !TURN_ONLY_BOT_TOOLS.has(name) && !PRIVATE_INPUT_TOOLS.has(name) && !TAKEOVER_TOOLS.has(name), ) .sort(), ); expect(listed.every((name) => botTools.includes(name))).toBe(true); + expect(listed).not.toContain('deepseekbot_cli'); + await expect( + runtime.runDirectBotTool!( + 'ada', + 'deepseekbot_cli', + { argv: ['approval-templates'] }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ code: 'tool-not-direct' }); expect(botTools).toContain('cloud_work'); expect(exempt).not.toContain('cloud_work'); expect(readFileSync(join(repo, 'packages/core/src/bots/cli-live.ts'), 'utf8')).toContain( @@ -184,7 +252,8 @@ describe('direct Bot tool runner', () => { body: 'direct hello', author: { kind: 'bot', slug: 'ada' }, }); - expect(host.sessions).toHaveLength(0); + expect(host.received.size).toBe(0); + expect(host.disposed).toHaveLength(host.sessions.length); const calls = runtime.directBotToolCalls!('ada'); expect(calls.map((call) => [call.tool, call.outcome])).toEqual([ @@ -238,8 +307,8 @@ describe('direct Bot tool runner', () => { ).rejects.toMatchObject({ code: 'bot-paused' }); }); - it('creates and continues an Orchestrator-owned Assignment without waking the Orchestrator', async () => { - const { runtime, host, owner, dm } = setup(); + it('records silent direct Assignment notices separately from native reports', async () => { + const { runtime, host, owner, dm } = setup(true); const signal = new AbortController().signal; const database = attachOperationalModule(owner, 'direct-assignment-test'); try { @@ -288,6 +357,7 @@ describe('direct Bot tool runner', () => { a.source_policy_wake_mode AS wake, a.attempt_state FROM source_events e JOIN inbox_admissions a ON a.source_event_id = e.source_event_id WHERE e.assignment_session_id = ? AND e.source_kind = 'assignment-lifecycle' + AND json_extract(e.payload_json, '$.assignmentLifecycle.cause') IN ('direct-create', 'direct-request') ORDER BY e.rowid`, ) .all(sessionId), @@ -300,7 +370,7 @@ describe('direct Bot tool runner', () => { }), ]); expect(notices()[0]!.body).toContain('"Read the build log and summarize failures."'); - expect(host.sessions.every((session) => String(session.id) === sessionId)).toBe(true); + expect([...host.received.keys()].filter((id) => id.startsWith('direct-'))).toEqual([]); const requested = await runtime.runDirectBotTool!( 'ada', @@ -394,3 +464,47 @@ describe('direct Bot tool runner', () => { ); }); }); + +it.each([true, false])( + 'preserves the direct tool outcome when disposal fails (success: %s)', + async (success) => { + const cleanupFailure = vi.fn(); + const { runtime, channels, dm, agents, host } = setup(false, cleanupFailure); + const release = agents.releaseSession?.bind(agents); + if (!release) throw new Error('Missing release owner'); + const failedCleanup = vi + .spyOn(agents, 'releaseSession') + .mockImplementation(async (sessionId) => { + await release(sessionId); + throw new Error('Synthetic disposal rejection'); + }); + try { + const operation = runtime.runDirectBotTool!( + 'ada', + 'bot_send_message', + success + ? { channel_id: dm.id, body: 'Completed once despite cleanup failure.' } + : { body: 'No destination' }, + new AbortController().signal, + ); + if (success) { + expect(await operation).toMatchObject({ + result: { channelId: dm.id, status: 'committed' }, + }); + expect( + channels + .readMessages(dm.id) + .filter((message) => message.body === 'Completed once despite cleanup failure.'), + ).toHaveLength(1); + } else await expect(operation).rejects.toBeInstanceOf(DirectBotToolError); + expect(cleanupFailure).toHaveBeenCalledExactlyOnceWith({ + sessionId: expect.stringMatching(/^direct-/), + durationMs: expect.any(Number), + }); + expect(host.disposed).toHaveLength(host.sessions.length); + } finally { + failedCleanup.mockRestore(); + await runtime.close(); + } + }, +); diff --git a/packages/core/test/dsh-agent-host-fixture.ts b/packages/core/test/dsh-agent-host-fixture.ts index de60c33804..a08fdb82ca 100644 --- a/packages/core/test/dsh-agent-host-fixture.ts +++ b/packages/core/test/dsh-agent-host-fixture.ts @@ -11,6 +11,9 @@ import { createAssistantMessage, type Message, type UserMessage } from '@deepsee import type { TurnEndReason } from '@deepseek-ai/dsh-session'; import type { ToolDefinition, ToolRunContext } from '@deepseek-ai/dsh-tools'; +import { executeFixtureNativeTool } from './fixtures/native-tools.js'; +import type { DirectNativeCall } from '../src/runtime/native-agent-compat.js'; + import type { PersonaBotRecord } from '../src/bots/persona-bot.js'; import type { DshAgentHost } from '../src/runtime/dsh-bot-agent-adapter.js'; @@ -224,6 +227,8 @@ export class FakeAgentHost implements DshAgentHost { return () => void scope.listeners.delete(event); }, tools: { + execute: (input: DirectNativeCall) => + executeFixtureNativeTool(input, scope.tools, scope.guards), get: (name: string) => scope.tools.find((tool) => tool.name === name), schemas: (viewingAgent: unknown) => viewingAgent === undefined diff --git a/packages/core/test/dsh-bot-agent-adapter.test.ts b/packages/core/test/dsh-bot-agent-adapter.test.ts index b69e6b81db..9ea12cd08d 100644 --- a/packages/core/test/dsh-bot-agent-adapter.test.ts +++ b/packages/core/test/dsh-bot-agent-adapter.test.ts @@ -389,6 +389,44 @@ describe('explicit Inbox completion with messaging tools', () => { ) { const adapter = createDshBotAgentAdapter({ agents: new FakeAgentHost(), + onAgentSetup: (ctx) => { + Object.assign(ctx.tools, { + execute: async (input: { + name: string; + arguments: unknown; + callId: string; + signal: AbortSignal; + }) => { + const tool = ctx.tools.get(input.name); + if (!tool) throw new Error('Missing fixture tool'); + const native = new Context(); + const providers = native.plugin({ + name: 'direct-test-services', + apply(c: Context) { + c.provide('systemPrompt', { + tools: () => () => undefined, + section: () => () => undefined, + getSectionOrder: () => 1, + }); + }, + }); + const runtime = native.plugin(ToolRuntime, {}); + try { + await providers.await(); + await runtime.await(); + native.tools.register(tool); + await native.inject(['tools'], (c) => installNativeTools(c)).await(); + return await executeNativeTool(native, { + ...input, + callId: ToolCallId(input.callId), + }); + } finally { + await runtime.dispose(); + await providers.dispose(); + } + }, + }); + }, defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, orchestratorCwd: () => '/memory/ada', ensureWorkspace: () => undefined, @@ -1546,7 +1584,7 @@ describe('DSH Bot Agent adapter', () => { } }); - it.each(['orchestrator', 'assignment'] as const)( + it.each(['orchestrator', 'assignment', 'model-free-tob'] as const)( 'refuses %s input if principal access changes while preparing the native Agent', async (role) => { let active = true; @@ -1571,8 +1609,21 @@ describe('DSH Bot Agent adapter', () => { }; try { const result = - role === 'orchestrator' - ? adapter.runOrchestrator({ ...reportRun, requireContent }) + role !== 'assignment' + ? adapter.runOrchestrator({ + ...reportRun, + requireContent, + ...(role === 'model-free-tob' + ? { + tobCli: true, + tobCliTurn: { + command: { argv: ['approval-templates'], stdin: '' }, + signal: new AbortController().signal, + complete: vi.fn(), + }, + } + : {}), + }) : adapter.runAssignment({ sessionId: 'm7-preparing-assignment', bot: BOT, @@ -4311,3 +4362,198 @@ describe('Assignment Directory Tools', () => { } }); }); + +describe('model-free Tob preparation cancellation', () => { + it.each([ + { operation: 'create', cancellation: 'signal' }, + { operation: 'resume', cancellation: 'signal' }, + { operation: 'create', cancellation: 'session-stop' }, + { operation: 'resume', cancellation: 'session-stop' }, + ] satisfies { operation: 'create' | 'resume'; cancellation: 'signal' | 'session-stop' }[])( + 'cancels pending native $operation through $cancellation and disposes its late handle before execution', + async ({ operation, cancellation }) => { + const agents = new FakeAgentHost(); + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const originalCreate = agents.create.bind(agents); + const originalResume = agents.resume.bind(agents); + const pending = + operation === 'create' + ? vi.spyOn(agents, 'create').mockImplementation(async (options) => { + const handle = await originalCreate(options); + await gate; + return handle; + }) + : vi.spyOn(agents, 'resume').mockImplementation(async (options) => { + const handle = await originalResume(options); + await gate; + return handle; + }); + const adapter = createDshBotAgentAdapter({ + agents, + defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, + orchestratorCwd: () => '/memory/ada', + ensureWorkspace: () => undefined, + }); + const controller = new AbortController(); + const complete = vi.fn(); + let settled = false; + const running = adapter + .runOrchestrator({ + ...reportRun, + resume: operation === 'resume', + tobCli: true, + tobCliTurn: { + command: { argv: ['approval-templates'], stdin: '' }, + signal: controller.signal, + complete, + }, + }) + .then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + try { + await vi.waitFor(() => expect(pending).toHaveBeenCalledOnce()); + expect(adapter.steerOrchestrator?.(reportRun.bot.slug, 'interruption')).toBe(false); + if (cancellation === 'signal') controller.abort(); + else expect(adapter.stopOrchestratorTurn?.(reportRun.bot.slug)).toBe(reportRun.sessionId); + await vi.waitFor(() => expect(settled).toBe(true), { timeout: 500, interval: 5 }); + expect(complete).not.toHaveBeenCalled(); + release?.(); + await vi.waitFor(() => expect(agents.disposed).toContain(reportRun.sessionId)); + expect(agents.received.get(reportRun.sessionId) ?? []).toEqual([]); + } finally { + release?.(); + await running; + await adapter.close(); + } + }, + ); +}); + +it('keeps a cancelled native publication reserved until its late handle is cleaned up', async () => { + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const agents = new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => {} }); + const original = agents.create.bind(agents); + const create = vi.spyOn(agents, 'create').mockImplementation(async (options) => { + const handle = await original(options); + await gate; + return handle; + }); + const adapter = createDshBotAgentAdapter({ + agents, + defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, + orchestratorCwd: () => '/memory/ada', + ensureWorkspace: () => undefined, + }); + const controller = new AbortController(); + const cancelled = adapter + .runOrchestrator({ + ...reportRun, + tobCli: true, + tobCliTurn: { + command: { argv: ['approval-templates'], stdin: '' }, + signal: controller.signal, + complete: () => { + throw Error('must not execute'); + }, + }, + }) + .catch(() => undefined); + try { + await vi.waitFor(() => expect(agents.get(reportRun.sessionId)).toBeDefined()); + controller.abort(); + await cancelled; + await expect( + adapter.runOrchestrator({ ...reportRun, message: 'Must wait for native cleanup' }), + ).rejects.toThrow('preparation'); + expect(agents.received.get(reportRun.sessionId) ?? []).toEqual([]); + expect(create.mock.calls[0]?.[0].signal?.aborted).toBe(true); + release?.(); + await vi.waitFor(() => expect(agents.disposed).toContain(reportRun.sessionId)); + create.mockRestore(); + await adapter.runOrchestrator({ ...reportRun, message: 'Run safely after cleanup' }); + expect(agents.received.get(reportRun.sessionId)).toHaveLength(1); + expect(agents.get(reportRun.sessionId)).toBeDefined(); + } finally { + release?.(); + await cancelled; + await adapter.close(); + } +}); + +it.each(['create', 'resume'] as const)( + 'cancels direct effect execution during native %s before running the Tool', + async (operation) => { + const agents = new FakeAgentHost(); + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const originalCreate = agents.create.bind(agents); + const originalResume = agents.resume.bind(agents); + const native = + operation === 'create' + ? vi.spyOn(agents, 'create').mockImplementation(async (options) => { + const handle = await originalCreate(options); + await gate; + return handle; + }) + : vi.spyOn(agents, 'resume').mockImplementation(async (options) => { + const handle = await originalResume(options); + await gate; + return handle; + }); + const adapter = createDshBotAgentAdapter({ + agents, + defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, + orchestratorCwd: () => '/memory/ada', + ensureWorkspace: () => undefined, + }); + const controller = new AbortController(); + let settled = false; + const sendToBot = vi.fn(async (): Promise => { + throw new Error('must not execute'); + }); + const running = adapter.runDirectTool!( + { + ...reportRun, + resume: operation === 'resume', + channels: { ...reportRun.channels, sendToBot }, + }, + 'bot_send_message', + { bot_id: 'fixture-missing', message: 'fixture' }, + controller.signal, + ).then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + try { + await vi.waitFor(() => expect(native).toHaveBeenCalledOnce()); + controller.abort(); + await vi.waitFor(() => expect(settled).toBe(true), { timeout: 500, interval: 5 }); + expect(native.mock.calls[0]?.[0].signal?.aborted).toBe(true); + release?.(); + await vi.waitFor(() => expect(agents.disposed).toContain(reportRun.sessionId)); + expect(sendToBot).not.toHaveBeenCalled(); + } finally { + release?.(); + await running; + await adapter.close(); + } + }, +); diff --git a/packages/core/test/fixtures/managed-cli.ts b/packages/core/test/fixtures/managed-cli.ts new file mode 100644 index 0000000000..bfad811d7c --- /dev/null +++ b/packages/core/test/fixtures/managed-cli.ts @@ -0,0 +1,86 @@ +import { createHash } from 'node:crypto'; +import { + copyFile, + mkdir, + mkdtemp, + readFile, + readdir, + realpath, + rm, + symlink, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'tsdown'; + +const externalDependencies = ['@resvg/resvg-js', 'silk-wasm', 'opus-decoder', 'css-tree', 'sharp']; + +async function sourceTreeHash(sourceRoot: string): Promise { + const hash = createHash('sha256'); + for (const path of (await readdir(sourceRoot, { recursive: true })).sort()) { + if (!path.endsWith('.ts') && !path.endsWith('.tsx')) continue; + hash.update(path.replaceAll('\\', '/')); + hash.update(await readFile(join(sourceRoot, path))); + } + return hash.digest('hex'); +} + +export async function buildManagedCliFixture() { + const directory = await mkdtemp(join(tmpdir(), 'botharness-managed-cli-fixture-')); + try { + const entry = fileURLToPath(new URL('../../src/bots/bot-create-cli.ts', import.meta.url)); + const sourceRoot = fileURLToPath(new URL('../../src', import.meta.url)); + const sourceBeforeSha256 = await sourceTreeHash(sourceRoot); + await build({ + config: false, + cwd: fileURLToPath(new URL('../../../../', import.meta.url)), + entry: { index: entry }, + outDir: join(directory, 'cli'), + format: ['esm'], + platform: 'node', + dts: false, + clean: true, + deps: { + alwaysBundle: [/^@deepseek-ai\//], + neverBundle: externalDependencies, + onlyBundle: false, + }, + logLevel: 'silent', + }); + await copyFile( + fileURLToPath(new URL('../../package.json', import.meta.url)), + join(directory, 'package.json'), + ); + const dependencies = await realpath( + fileURLToPath(new URL('../../node_modules/', import.meta.url)), + ); + for (const name of externalDependencies) { + const target = join(directory, 'node_modules', name); + await mkdir(dirname(target), { recursive: true }); + await symlink( + await realpath(join(dependencies, name)), + target, + process.platform === 'win32' ? 'junction' : 'dir', + ); + } + const provenance = { + entrySha256: createHash('sha256') + .update(await readFile(entry)) + .digest('hex'), + sourceBeforeSha256, + sourceAfterSha256: await sourceTreeHash(sourceRoot), + bundleSha256: createHash('sha256') + .update(await readFile(join(directory, 'cli', 'index.mjs'))) + .digest('hex'), + }; + return { + provenance, + path: join(directory, 'cli', 'index.mjs'), + close: () => rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }), + }; + } catch (error) { + await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); + throw error; + } +} diff --git a/packages/core/test/fixtures/native-tools.ts b/packages/core/test/fixtures/native-tools.ts new file mode 100644 index 0000000000..586e8bb7bb --- /dev/null +++ b/packages/core/test/fixtures/native-tools.ts @@ -0,0 +1,36 @@ +import { Context } from '@deepseek-ai/cordis'; +import { ToolRuntime, type ToolDefinition, type ToolGuard } from '@deepseek-ai/dsh-tools'; +import { + executeNativeTool, + installNativeTools, + type DirectNativeCall, +} from '../../src/runtime/native-agent-compat.js'; + +export async function executeFixtureNativeTool( + input: DirectNativeCall, + tools: readonly ToolDefinition[], + guards: readonly ToolGuard[], +) { + const native = new Context(); + const providers = native.plugin({ + name: 'fixture-native-tool-services', + apply(ctx: Context) { + ctx.provide('systemPrompt', { + tools: () => () => undefined, + section: () => () => undefined, + getSectionOrder: () => 1, + }); + }, + }); + const runtime = native.plugin(ToolRuntime, {}); + try { + await providers.await(); + await runtime.await(); + for (const tool of tools) native.tools.register(tool); + for (const guard of guards) native.tools.guard(guard); + await native.inject(['tools'], (ctx) => installNativeTools(ctx)).await(); + return await executeNativeTool(native, input); + } finally { + await native.fiber.dispose(); + } +} diff --git a/packages/core/test/grant-execution.test.ts b/packages/core/test/grant-execution.test.ts index dc6f02caf8..a7f858ed2e 100644 --- a/packages/core/test/grant-execution.test.ts +++ b/packages/core/test/grant-execution.test.ts @@ -317,7 +317,7 @@ describe('Workspace Grant execution boundary', () => { 'group_leave', ]) expect(requiresHumanToolApproval(tool)).toBe(false); - expect(requiresHumanToolApproval('bot_send_message')).toBe(false); + expect(requiresHumanToolApproval('bot_send_message')).toBe(true); for (const tool of [ 'bot_schedule_list', 'bot_schedule_create', @@ -337,7 +337,6 @@ describe('Workspace Grant execution boundary', () => { 'bridge_sender_permissions', 'bridge_directory', 'bridge_attachment_save', - 'bot_send_message', ]) { expect(requiresHumanToolApproval(tool)).toBe(false); expect(isDshGovernedTool(tool)).toBe(false); diff --git a/packages/core/test/native-agent-compat.test.ts b/packages/core/test/native-agent-compat.test.ts index a823da3b9b..e04c52c0b2 100644 --- a/packages/core/test/native-agent-compat.test.ts +++ b/packages/core/test/native-agent-compat.test.ts @@ -228,3 +228,62 @@ describe('native tool API generations', () => { ); }); }); + +it('executes a conditional tool only with its real resolved native tool selection', async () => { + const root = new Context(); + const provider = root.plugin({ + apply(ctx: Context) { + ctx.provide('systemPrompt', { tools: () => () => undefined, section: () => () => undefined }); + }, + }); + await provider.await(); + const runtime = root.plugin(ToolRuntime, {}); + await runtime.await(); + const agent = { session: { id: 'conditional-direct' } } as Agent; + const scope = createScope(root, agent); + try { + await scope.ctx + .inject(['tools'], async (ctx) => { + Object.assign(agent, { ctx }); + let active = false; + ctx.tools.register( + defineTool({ + name: 'write', + description: 'Conditional direct tool', + parameters: {}, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + execute: async () => 'written', + }), + { when: () => active }, + ); + await installAgentNativeTools(ctx, agent); + const context = { + agent, + modelSelection: { provider: 'fixture', model: 'fixture' }, + signal: new AbortController().signal, + }; + const hidden = await ctx.tools.resolve(context); + expect(ctx.tools.schemas(agent, hidden)).toEqual([]); + hidden.dispose(); + expect(await executeNativeTool(ctx, { ...input(), arguments: {}, agent })).toMatchObject({ + isError: true, + }); + active = true; + const selected = await ctx.tools.resolve(context); + try { + expect( + await executeNativeTool(ctx, { ...input(), arguments: {}, agent, toolSet: selected }), + ).toMatchObject({ isError: false, value: 'written' }); + } finally { + selected.dispose(); + } + }) + .await(); + } finally { + await scope.dispose(); + await root.fiber.dispose(); + } +}); diff --git a/packages/core/test/network-direct-tool.test.ts b/packages/core/test/network-direct-tool.test.ts index ed6e2418c3..00ffc57836 100644 --- a/packages/core/test/network-direct-tool.test.ts +++ b/packages/core/test/network-direct-tool.test.ts @@ -129,7 +129,15 @@ it('requires an owned admitted Source Event for a model-free remote Bot send', a expect(core.runtime.botContacts?.('caller', { botId: 'remote:remote:ios' }).contacts).toEqual( [], ); - expect(host.sessions).toHaveLength(0); + expect(host.createOptions).toHaveLength(3); + const sessions = host.sessions.map((session) => session.id); + expect(new Set(sessions).size).toBe(3); + expect(sessions.every((id) => id.startsWith('direct-'))).toBe(true); + expect(host.disposed).toEqual(sessions); + for (const id of sessions) { + expect(host.scopes.get(id)?.tools.map((tool) => tool.name)).toContain('bot_send_message'); + } + expect(host.received.size).toBe(0); } finally { await core.runtime.close(); core.operationalDatabase.close(); diff --git a/packages/core/test/network-withdrawal.test.ts b/packages/core/test/network-withdrawal.test.ts index 13804c764f..b648b92039 100644 --- a/packages/core/test/network-withdrawal.test.ts +++ b/packages/core/test/network-withdrawal.test.ts @@ -49,6 +49,24 @@ it.skipIf(!aliases).each(['pending', 'started', 'alternate-network', 'connect-ro const notifications: Array<(change: TailnetChange) => void> = []; let eligible = true; let entered = 0; + let signalEntered: () => void = () => undefined; + const runEntered = new Promise((resolve) => { + signalEntered = resolve; + }); + const waitForEntered = async () => { + const core = cores[1]!; + await Promise.race([ + runEntered, + core.runtime.whenIdle().then(() => { + if (entered === 0) + throw new Error( + 'Orchestrator ended before the held fixture run entered: ' + + JSON.stringify(core.channels.readMessages('dm-bot')), + ); + }), + ]); + expect(entered).toBe(1); + }; let finished = false; let release!: () => void; const held = new Promise((resolve) => { @@ -73,6 +91,7 @@ it.skipIf(!aliases).each(['pending', 'started', 'alternate-network', 'connect-ro adapter.runOrchestrator = async () => { if (index !== 1) return; entered++; + signalEntered(); await held; if (phase === 'started') { try { @@ -177,7 +196,7 @@ it.skipIf(!aliases).each(['pending', 'started', 'alternate-network', 'connect-ro }; if (phase !== 'started') { await appendHuman(1, 'LOCAL_WORK'); - await expect.poll(() => entered).toBe(1); + await waitForEntered(); } const root = await appendHuman(0, 'ROOT'); const contacts = await cores[0]!.runtime.runDirectBotTool!( @@ -195,7 +214,7 @@ it.skipIf(!aliases).each(['pending', 'started', 'alternate-network', 'connect-ro undefined, root, ); - if (phase === 'started') await expect.poll(() => entered).toBe(1); + if (phase === 'started') await waitForEntered(); expect(inbound()).toMatchObject({ ignored_at: null }); if (phase === 'connect-route') { const peers: AuthenticatedConnectBotPeer[] = nodes.map((node, index) => ({ diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 30ff50e536..0b1c493add 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -366,6 +366,9 @@ describe('plugin entry', () => { apply(ctx, { enabled: true }); const core = ctx.get('botharness') as unknown as BotHarnessCore; core.registry.create({ slug: 'ada', displayName: 'Ada' }); + const origin = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada'); + if (!origin) throw new Error('Missing device fixture DM'); + vi.spyOn(core.runtime, 'askChannel').mockReturnValue(origin.id); core.ownership.claim({ sessionId: 'device-session', botSlug: 'ada', @@ -1027,6 +1030,7 @@ describe('plugin entry', () => { 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'tobCli', 'channelSkillCatalog', 'botSkills', 'skillShow', @@ -1132,6 +1136,7 @@ describe('plugin entry', () => { 'botPromptSet', 'approvalTemplateCreate', 'approvalTemplateUpdate', + 'approvalTemplateDeletePreview', 'approvalTemplateDelete', 'approvalTemplateGlobalSet', 'botApprovalTemplateSet', diff --git a/packages/core/test/session-ownership.test.ts b/packages/core/test/session-ownership.test.ts index 9b92723da6..f982bb0e15 100644 --- a/packages/core/test/session-ownership.test.ts +++ b/packages/core/test/session-ownership.test.ts @@ -31,6 +31,26 @@ function setup(): { home: string; owner: OperationalDatabaseOwner; ownership: Se const AT = '2026-09-21T00:00:00.000Z'; describe('Session ownership', () => { + it('resolves direct execution ownership without selecting it as a persistent Bot root', () => { + const { owner, ownership } = setup(); + try { + const direct = ownership.claim({ + sessionId: 'direct-call-1', + botSlug: 'ada', + rootRole: 'orchestrator', + at: AT, + }); + expect(ownership.resolve(direct.sessionId)).toEqual(direct); + expect(ownership.rootsFor('ada')).toEqual([]); + ownership.claim({ sessionId: 'chat-1', botSlug: 'ada', rootRole: 'orchestrator', at: AT }); + expect(ownership.rootsFor('ada', 'orchestrator').map((root) => root.sessionId)).toEqual([ + 'chat-1', + ]); + } finally { + owner.close(); + } + }); + it('claims and resolves a root Session with its explicit run configuration', () => { const { owner, ownership } = setup(); diff --git a/packages/core/test/team-approvals.test.ts b/packages/core/test/team-approvals.test.ts index c7a2b0b88a..0e436767a1 100644 --- a/packages/core/test/team-approvals.test.ts +++ b/packages/core/test/team-approvals.test.ts @@ -1107,6 +1107,153 @@ describe('M5 approval projections and decisions', () => { }); }); + it.each(['no-template', 'ask-human', 'allow'] as const)( + 'keeps shared-Bot approval and %s Reviewer records in the requesting participant DM', + async (mode) => { + const f = fixture(); + f.team.bots.setVisibility(owner, 'alice-bot', { + kind: 'public', + audience: { kind: 'everyone' }, + }); + const principalDm = f.channels.getOrCreateDm(alice, 'alice-bot', 'Alice Bot')!; + const memberDm = f.channels.getOrCreateDm(bob, 'alice-bot', 'Alice Bot')!; + expect(memberDm.id).not.toBe(principalDm.id); + const sessionId = 'participant-approval-' + mode; + f.ownership.claim({ + sessionId, + botSlug: 'alice-bot', + rootRole: 'orchestrator', + at: new Date().toISOString(), + }); + const agent: Agent = Object.assign(Object.create(null), { + session: { id: sessionId, header: { cwd: '/' }, snapshotEvents: () => [] }, + }); + const review = vi.fn(async () => ({ + outcome: mode === 'allow' ? ('allow' as const) : ('ask-human' as const), + reason: 'PARTICIPANT_REVIEW_REASON', + })); + const broker = new ChannelToolApproval( + f.channels, + f.ownership, + undefined, + undefined, + undefined, + undefined, + () => memberDm.id, + { + template: () => + mode === 'no-template' ? undefined : { name: 'qa', text: 'Ask when uncertain.' }, + review, + log() {}, + }, + () => true, + f.team.approvals, + ); + const callId = ToolCallId('participant-call'); + broker.track({ + agent, + name: 'bot_send_message', + callId, + rootCallId: callId, + arguments: { body: 'PARTICIPANT_PRIVATE_INPUT' }, + token: Object.assign(Object.create(null), Symbol('approval')), + signal: new AbortController().signal, + }); + const pending = broker.ask({ agent, toolName: 'bot_send_message', callId }); + try { + if (mode === 'allow') { + expect(await pending).toBe('allowed-once'); + } else { + await vi.waitFor(() => expect(broker.requests('alice-bot')).toHaveLength(1)); + const request = broker.requests('alice-bot')[0]!; + expect(request.channelId).toBe(memberDm.id); + expect(() => + f.team.approvals.requireRequest(alice, memberDm.id, request.messageId), + ).toThrow(); + expect(() => + f.team.approvals.requireRequest(bob, memberDm.id, request.messageId), + ).toThrow(); + masked( + f.team.approvals.project(bob, { + channelId: memberDm.id, + message: f.channels.message(memberDm.id, request.messageId), + }), + ); + } + expect(JSON.stringify(f.channels.readMessages(principalDm.id))).not.toContain( + 'PARTICIPANT_', + ); + const memberMessages = f.channels.readMessages(memberDm.id); + expect(JSON.stringify(memberMessages)).toContain('PARTICIPANT_PRIVATE_INPUT'); + if (mode !== 'no-template') { + expect(review).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ call: expect.objectContaining({ channelId: memberDm.id }) }), + ); + expect(memberMessages.some((message) => message.toolAutoApproval !== undefined)).toBe( + true, + ); + } else expect(review).not.toHaveBeenCalled(); + await expect( + f.invoke(alice, 'channelMessages', { channelId: memberDm.id }), + ).rejects.toMatchObject({ code: 'remote-access/denied' }); + } finally { + broker.close(); + await pending; + } + }, + ); + + it.each([undefined, 'missing-origin', 'dm-owner-bot'])( + 'refuses unavailable or mismatched approval origin %s without falling back to the principal DM', + async (origin) => { + const f = fixture(); + const sessionId = 'invalid-origin'; + f.ownership.claim({ + sessionId, + botSlug: 'alice-bot', + rootRole: 'orchestrator', + at: new Date().toISOString(), + }); + const agent: Agent = Object.assign(Object.create(null), { + session: { id: sessionId, header: { cwd: '/' } }, + }); + const review = vi.fn(); + const broker = new ChannelToolApproval( + f.channels, + f.ownership, + undefined, + undefined, + undefined, + undefined, + () => origin, + { template: () => ({ name: 'qa', text: 'Review.' }), review, log() {} }, + ); + const callId = ToolCallId('invalid-origin-call'); + broker.track({ + agent, + name: 'bash', + callId, + rootCallId: callId, + arguments: { command: 'PARTICIPANT_PRIVATE_INPUT' }, + token: Object.assign(Object.create(null), Symbol('approval')), + signal: new AbortController().signal, + }); + try { + expect(await broker.ask({ agent, toolName: 'bash', callId })).toBe('unavailable'); + expect(review).not.toHaveBeenCalled(); + expect(broker.requests('alice-bot')).toEqual([]); + expect(JSON.stringify(f.channels.readMessages('dm-alice-bot'))).not.toContain( + 'PARTICIPANT_', + ); + expect(JSON.stringify(f.channels.readMessages('dm-owner-bot'))).not.toContain( + 'PARTICIPANT_', + ); + } finally { + broker.close(); + } + }, + ); + it('commits a real tool decision once with the authenticated Human ID', async () => { const f = fixture(); const sessionId = 'm5-real-tool'; diff --git a/packages/core/test/team-bot-visibility.test.ts b/packages/core/test/team-bot-visibility.test.ts index 43a825ed40..675bd7e369 100644 --- a/packages/core/test/team-bot-visibility.test.ts +++ b/packages/core/test/team-bot-visibility.test.ts @@ -101,6 +101,52 @@ function post(id: string, author: 'human' | 'bot' = 'human', slug = 'alice-bot') } describe('M7 Bot principal and participant authority', () => { + it('binds authenticated direct tools to the caller DM and releases the transient origin', async () => { + const root = createTempRoot('m7-direct-approval-origin-'); + let core: ReturnType; + let sessionId: string | undefined; + let observedOrigin: string | undefined; + core = createCore({ + dshHome: root, + agents: createDshBotAgentAdapter({ + agents: new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => {} }), + defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, + orchestratorCwd: () => join(root, 'memory'), + onAgentSetup: (_ctx, agent) => { + sessionId = agent.session.id; + observedOrigin = core.runtime.askChannel?.(sessionId); + }, + }), + }); + closes.push(async () => { + await core.runtime.close(); + core.operationalDatabase.close(); + }); + const db = attachOperationalModule(core.operationalDatabase, 'direct-approval-origin-test'); + db.transaction((sql) => { + sql.prepare('UPDATE team_settings SET enabled=1').run(); + sql.prepare("INSERT INTO humans VALUES ('alice','Alice','active','now')").run(); + sql.prepare("INSERT INTO human_roles VALUES ('alice','member')").run(); + }); + core.spaces.ensureAccount(alice.humanId); + expect( + core.registry.create({ slug: 'helper', displayName: 'Helper', ownerHumanId: alice.humanId }) + .ok, + ).toBe(true); + const dm = core.channels.getOrCreateDm(alice, 'helper', 'Helper')!; + const result = await createBridgeMethodsForHumans(core)(alice).botToolRun({ + slug: 'helper', + tool: 'bot_send_message', + args: { body: 'No target, no delivery.' }, + humanId: owner.humanId, + }); + expect(result.ok).toBe(false); + expect(observedOrigin).toBe(dm.id); + expect(sessionId).toBeDefined(); + expect(core.runtime.askChannel?.(sessionId!)).toBeUndefined(); + expect(core.channels.readMessages(dm.id)).toEqual([]); + }); + it('preserves omitted switches and performs no write for a slug-only bridge read', async () => { const f = fixture(); f.team.bots.switches(alice, 'alice-bot', { diff --git a/packages/core/test/team-private-bots.test.ts b/packages/core/test/team-private-bots.test.ts index c828bcef03..a2a8ed5159 100644 --- a/packages/core/test/team-private-bots.test.ts +++ b/packages/core/test/team-private-bots.test.ts @@ -173,7 +173,7 @@ describe('M2 private Bot boundaries', () => { expect(scoped.memoryDirFor('bob-bot')).toBeDefined(); }); - it('clears deleted global preset and template references across private Bots without listing them', () => { + it('confirms all shared-template references while keeping private Bot identities hidden', () => { const f = fixture(); const methods = createBridgeMethods(owner, { ...f.core, @@ -196,6 +196,14 @@ describe('M2 private Bot boundaries', () => { f.core.registry.setPromptSettings(slug, { preset: id }); f.core.registry.setApprovalTemplate(slug, template); } + const member = createBridgeMethods(alice, { ...f.core, team: f.team }); + expect(member.approvalTemplateDeletePreview({ name: template })).toMatchObject({ + ok: false, + error: { code: 'permission-required' }, + }); + expect( + member.approvalTemplateDelete({ name: template, confirmed: true, revision: 'a'.repeat(64) }), + ).toMatchObject({ ok: false, error: { code: 'permission-required' } }); expect(methods.approvalTemplates({})).toMatchObject({ ok: true, value: { @@ -208,13 +216,27 @@ describe('M2 private Bot boundaries', () => { ok: true, value: { clearedBots: ['owner-bot'] }, }); - expect(methods.approvalTemplateDelete({ name: template })).toMatchObject({ + const deletion = methods.approvalTemplateDeletePreview({ name: template }); + if (!deletion.ok) throw new Error(deletion.error.code); + expect(deletion.value.preview).toMatchObject({ + affectedBots: [{ slug: 'owner-bot', source: 'specific' }], + hiddenBotCount: 2, + }); + expect(JSON.stringify(deletion)).not.toContain('alice-bot'); + expect(JSON.stringify(deletion)).not.toContain('bob-bot'); + expect( + methods.approvalTemplateDelete({ + name: template, + confirmed: true, + revision: deletion.value.preview.revision, + }), + ).toMatchObject({ ok: true, value: { clearedBots: ['owner-bot'] }, }); for (const slug of ['owner-bot', 'alice-bot', 'bob-bot']) { expect(f.core.registry.get(slug)?.promptPreset).toBeUndefined(); - expect(f.core.registry.get(slug)?.approvalTemplate).toBeUndefined(); + expect(f.core.registry.get(slug)?.approvalTemplate).toBe('@global'); } }); diff --git a/packages/core/test/tob-cli-approval.test.ts b/packages/core/test/tob-cli-approval.test.ts index ae1c061f9b..2af4c1b0b0 100644 --- a/packages/core/test/tob-cli-approval.test.ts +++ b/packages/core/test/tob-cli-approval.test.ts @@ -543,3 +543,104 @@ describe('disruptive scoped CLI operations require Human review', () => { await pending.result; }); }); + +describe('typed native Shell CLI effects under Full Access', () => { + const externalOperation = (command: string): TobCliWriteProposal => ({ + command, + target: 'fixture', + previousValue: null, + patch: {}, + }); + + it.each(['git-install', 'group-invite', 'voice-provider-test'])( + 'sends irreversible external %s through common approval before the write', + async (command) => { + const f = fixture(); + f.setFullAccess(true); + const pending = writeAfterApproval({ ...f.options, operation: externalOperation(command) }); + const card = await f.card(); + expect(card.toolApprovalRequest).toMatchObject({ + toolName: 'deepseekbot ' + command, + effects: { changes: 'irreversible', reach: 'external' }, + }); + expect(pending.write).not.toHaveBeenCalled(); + await f.channelApproval.decide(OWNER_HUMAN_CONTEXT, 'tob', card.id, 'rejected'); + expect(await pending.result).toMatchObject({ ok: false, error: { code: 'approval-denied' } }); + expect(pending.write).not.toHaveBeenCalled(); + expect(f.channelApproval.activeMessageIds()).toEqual([]); + }, + ); + + it('keeps the Reviewer path for declared external operations after Full Access admission', async () => { + const review = vi.fn(async () => ({ + outcome: 'allow' as const, + reason: 'Allowed for fixture', + })); + const f = fixture({ + autoApproval: { + template: () => ({ name: 'fixture', text: 'Allow the fixture' }), + review, + log: vi.fn(), + }, + }); + f.setFullAccess(true); + const pending = writeAfterApproval({ + ...f.options, + operation: externalOperation('git-install'), + }); + expect(await pending.result).toMatchObject({ ok: true }); + expect(review).toHaveBeenCalledTimes(1); + expect(pending.write).toHaveBeenCalledTimes(1); + expect(f.channelApproval.requests('tob')).toEqual([]); + }); + + it('refuses declared external work when common approval is unavailable', async () => { + const f = fixture(); + f.setFullAccess(true); + const pending = writeAfterApproval({ + ...f.options, + operation: externalOperation('git-install'), + approval: undefined, + }); + expect(await pending.result).toMatchObject({ + ok: false, + error: { code: 'approval-unavailable' }, + }); + expect(pending.write).not.toHaveBeenCalled(); + }); +}); + +describe('declared CLI management keeps caller authority separate', () => { + it('requires an explicit exact-command decision with zero model calls and fences revocation', async () => { + const review = vi.fn(async () => ({ outcome: 'allow' as const, reason: 'Allowed' })); + const f = fixture({ + autoApproval: { + template: () => ({ name: 'all', text: 'Allow everything' }), + review, + log: vi.fn(), + }, + }); + f.setFullAccess(true); + const operation: TobCliWriteProposal = { + command: 'grant-write-set', + target: 'grant-write-set', + via: 'cli', + previousValue: null, + patch: { + argv: ['grant-write-set', 'bot', '--grant', 'grant', '--enabled', '--confirm'], + stdinBytes: 2, + stdinSha256: 'exact-stdin-digest', + }, + }; + const pending = approveTobCliOperation({ ...f.options, operation }); + const card = await f.card(); + expect(JSON.parse(card.toolApprovalRequest!.input)).toMatchObject(operation); + expect(review).not.toHaveBeenCalled(); + await f.channelApproval.decide(OWNER_HUMAN_CONTEXT, 'tob', card.id, 'allowed-once'); + const guard = await pending; + expect(() => guard()).not.toThrow(); + f.revoke(); + expect(() => guard()).toThrow('agent-context-expired'); + expect(review).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/test/tob-cli-broker.test.ts b/packages/core/test/tob-cli-broker.test.ts index ca39258484..f3ce52619c 100644 --- a/packages/core/test/tob-cli-broker.test.ts +++ b/packages/core/test/tob-cli-broker.test.ts @@ -60,6 +60,33 @@ const update = () => ({ }); describe('Tob scoped CLI broker', () => { + it('refuses a declared external operation whose owner omitted its proposal', async () => { + const run = vi.fn(); + const f = await fixture({ prepareOperation: () => ({ run }) }); + expect(await f.invoke('voice-provider-test', { id: 'fixture', completed: true })).toMatchObject( + { + ok: false, + error: { code: 'approval-unavailable' }, + }, + ); + expect(run).not.toHaveBeenCalled(); + expect(f.approve).not.toHaveBeenCalled(); + }); + + it('reads a completed invitation receipt without asking or executing another invitation', async () => { + const run = vi.fn((guard: () => void) => { + guard(); + return { operationKey: 'fixture', replayed: true }; + }); + const f = await fixture({ prepareOperation: () => ({ completed: true, run }) }); + expect(await f.invoke('group-invite', { operationKey: 'fixture' })).toMatchObject({ + ok: true, + value: { operationKey: 'fixture', replayed: true }, + }); + expect(run).toHaveBeenCalledOnce(); + expect(f.approve).not.toHaveBeenCalled(); + }); + it.each([ 'operation-key-conflict', 'stale-channel', diff --git a/packages/core/test/tob-cli-host-commands.test.ts b/packages/core/test/tob-cli-host-commands.test.ts index 07dd383f2e..14aedb4f45 100644 --- a/packages/core/test/tob-cli-host-commands.test.ts +++ b/packages/core/test/tob-cli-host-commands.test.ts @@ -206,3 +206,13 @@ describe('Tob runs any Human CLI command on the Host', () => { } }); }); + +it('does not admit write-capable read command families as broker reads', () => { + expect( + classifyTobHostCli(['channels', '--compact', 'send', 'channel', '--body-stdin']).write, + ).toBe(true); + expect(classifyTobHostCli(['devices', '--member', 'alex', '--revoke', 'grant']).write).toBe(true); + expect(classifyTobHostCli(['channels']).write).toBe(false); + expect(classifyTobHostCli(['channels', 'not-a-supported-action']).write).toBe(true); + expect(classifyTobHostCli(['channels', '--unknown-option']).write).toBe(true); +}); diff --git a/packages/core/test/tob-cli-invocation.test.ts b/packages/core/test/tob-cli-invocation.test.ts new file mode 100644 index 0000000000..e0b1aec083 --- /dev/null +++ b/packages/core/test/tob-cli-invocation.test.ts @@ -0,0 +1,614 @@ +import { createHash } from 'node:crypto'; +import { Context } from '@deepseek-ai/cordis'; +import type { Agent } from '@deepseek-ai/dsh-agent'; +import { ToolCallId } from '@deepseek-ai/dsh-llm'; +import { createScope, scopeTarget } from '@deepseek-ai/dsh-scope'; +import { ShellExecutor, type ShellExecSpec, type ShellExecution } from '@deepseek-ai/dsh-shell'; +import { ToolRuntime, defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools'; +import type { ApprovalService } from '@deepseek-ai/dsh-user-approval'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { apply, type BotHarnessCore } from '../src/index.js'; +import { OWNER_HUMAN_CONTEXT } from '../src/humans/context.js'; +import { executeNativeTool, installAgentNativeTools } from '../src/runtime/native-agent-compat.js'; +import { approveTobCliOperation } from '../src/tob/cli-approval.js'; +import { createTobHostCliOperations, type TobHostCliRunner } from '../src/tob/cli-host-commands.js'; +import { ModelFreeTobCliInvocation } from '../src/tob/cli-invocation.js'; +import { installTobCliShell } from '../src/tob/cli-shell.js'; +import { TobError } from '../src/tob/service.js'; +import { ChannelToolApproval } from '../src/workspaces/tool-approval.js'; +import { createTempRoot } from './helpers.js'; +import { buildManagedCliFixture } from './fixtures/managed-cli.js'; + +let cli: Awaited>; +beforeAll(async () => { + cli = await buildManagedCliFixture(); + console.info(JSON.stringify({ event: 'managed_cli_fixture.built', ...cli.provenance })); +}); +afterAll(async () => { + await cli?.close(); +}); + +const cleanup: Array<() => Promise | void> = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) await close(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +async function fixture() { + vi.stubEnv('DSH_HOME', createTempRoot('botharness-owned-cli-home-')); + const ctx = new Context(); + cleanup.push(() => ctx.fiber.dispose()); + ctx.provide('systemPrompt', { tools: () => () => {}, section: () => () => {} } as never); + let nativeTurn: number | null = 1; + ctx.provide('agents', { + create: vi.fn(), + resume: vi.fn(), + get: vi.fn(), + list: () => [], + turnBoundaryOf: () => ({ openTurnStartSeq: nativeTurn }), + } as never); + ctx.provide('sessions', { list: () => [], get: vi.fn() } as never); + ctx.provide('skills', { register: () => () => {} } as never); + ctx.provide('sandboxPolicy', { resolve: () => ({ mode: 'workspace-write' }) } as never); + const approval = { + overrideOf: () => 'ask', + request: (request: Parameters[0]) => + ctx.waterfall('approval/request', request, async () => 'unavailable' as const), + } as unknown as ApprovalService; + ctx.provide('approval', approval); + await ctx.plugin(ToolRuntime, {}).await(); + const delegate = vi.spyOn(ModelFreeTobCliInvocation.prototype, 'delegate'); + const ask = vi.spyOn(ChannelToolApproval.prototype, 'ask'); + apply(ctx, { enabled: true }); + const core: BotHarnessCore | undefined = ctx.get('botharness'); + if (!core) throw new Error('Missing core'); + expect(core.registry.create({ slug: 'ada', displayName: 'Ada' }).ok).toBe(true); + const origin = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada'); + if (!origin) throw new Error('Missing fixture DM'); + vi.spyOn(core.runtime, 'askChannel').mockReturnValue(origin.id); + core.ownership.claim({ + sessionId: 'owned-cli', + botSlug: 'ada', + rootRole: 'orchestrator', + at: new Date().toISOString(), + }); + const actor = { + session: { + id: 'owned-cli', + header: { cwd: core.registry.memoryDirFor('ada') }, + snapshotEvents: () => [], + }, + } as unknown as Agent; + const scope = createScope(ctx, actor); + cleanup.push(() => scope.dispose()); + Object.assign(actor, { ctx: scope.ctx }); + await scope.ctx + .inject(['tools'], async (agentCtx) => { + Object.assign(actor, { ctx: agentCtx }); + await installAgentNativeTools(agentCtx, actor); + }) + .await(); + const controller = new AbortController(); + const probe = { + agent: actor, + name: 'bash', + arguments: { command: 'echo probe' }, + callId: ToolCallId('probe'), + rootCallId: ToolCallId('probe'), + token: Symbol('probe'), + signal: controller.signal, + } as ToolExecution; + expect( + await ctx.waterfall(scopeTarget(ctx.tools, actor), 'tools/pre-execute', probe, async () => ({ + kind: 'allow' as const, + })), + ).toEqual({ kind: 'allow' }); + await approval.request({ + agent: actor, + toolName: 'probe', + callId: ToolCallId('probe'), + signal: controller.signal, + }); + const authority = delegate.mock.contexts.at(-1); + const channelApproval = ask.mock.contexts.at(-1); + if ( + !(authority instanceof ModelFreeTobCliInvocation) || + !(channelApproval instanceof ChannelToolApproval) + ) + throw new Error('Missing production approval owners'); + let authorized = true, + current = true; + const authorize = () => { + if (!authorized) throw new TobError('tob-authority-required'); + }; + const runHost = vi.fn(async () => ({ + exitCode: 0, + stdout: '{"changed":true}', + })); + const prepareOperation = createTobHostCliOperations({ run: runHost }); + class NoShell extends ShellExecutor { + resolve(): ShellExecSpec { + throw new Error('Unexpected Shell'); + } + async execute(): Promise { + throw new Error('Unexpected Shell'); + } + } + const shellCtx = new Context(); + cleanup.push(() => shellCtx.fiber.dispose()); + const registerTool = vi.spyOn(actor.ctx.tools, 'register'); + installTobCliShell(actor.ctx, new NoShell(shellCtx), { + cliPath: cli.path, + nativeCli: { + available: () => true, + register: (definition) => authority.register(actor, definition, () => authorize), + require: (execution) => authority.require(execution), + }, + capture: (execution) => ({ + signal: controller.signal, + authorize, + prepareOperation, + readSetting: () => ({ scope: 'global', value: 3, revision: 0 }), + writeSetting: async () => { + throw new Error('Unexpected settings write'); + }, + approve: (operation, signal) => + approveTobCliOperation({ + execution, + operation, + signal, + authorize, + approval, + channelApproval, + fullAccess: () => true, + }), + }), + }); + const registeredTool = registerTool.mock.results.at(-1); + if (!registeredTool || registeredTool.type !== 'return') + throw new Error('Missing trusted registration disposer'); + const removeTool = registeredTool.value; + registerTool.mockRestore(); + const command = { + argv: ['approval-template-set', 'ada', 'routine'], + stdin: 'private-stdin-value', + }; + const toolSet = await actor.ctx.tools.resolve({ + agent: actor, + modelSelection: { provider: 'unused', model: 'unused' }, + signal: controller.signal, + }); + cleanup.push(() => toolSet.dispose()); + const input = { + agent: actor, + callId: ToolCallId('owned-call'), + command, + toolSet, + signal: controller.signal, + requireCurrentTurn: () => { + if (!current) throw new TobError('agent-context-expired'); + }, + }; + const native = (changes: Partial[1]> = {}) => + executeNativeTool(actor.ctx, { + agent: actor, + callId: input.callId, + name: 'deepseekbot_cli', + arguments: command, + toolSet, + signal: controller.signal, + ...changes, + }); + return { + ctx, + scope, + core, + actor, + removeTool, + authority, + channelApproval, + command, + controller, + toolSet, + input, + native, + runHost, + revoke: () => { + authorized = false; + }, + changeTurn: () => { + current = false; + }, + changeNativeTurn: (value: number | null) => { + nativeTurn = value; + }, + }; +} + +describe('owned model-free Tob CLI invocation', () => { + it('uses the real native interceptor, trusted transport and broker for one exact-operation Human card', async () => { + const f = await fixture(); + const pending = f.authority.run(f.input, () => f.native()); + await vi.waitFor(() => expect(f.channelApproval.requests('ada')).toHaveLength(1)); + const request = f.channelApproval.requests('ada')[0]!; + expect(request.toolName).toBe('deepseekbot approval-template-set'); + expect(JSON.parse(request.input)).toMatchObject({ + via: 'cli', + patch: { + argv: f.command.argv, + cwd: f.actor.session.header.cwd, + stdinBytes: Buffer.byteLength(f.command.stdin), + stdinSha256: createHash('sha256').update(f.command.stdin).digest('hex'), + }, + }); + expect(request.input).not.toContain(f.command.stdin); + expect(f.runHost).not.toHaveBeenCalled(); + await f.channelApproval.decide(OWNER_HUMAN_CONTEXT, 'ada', request.messageId, 'allowed-once'); + expect(await pending).toMatchObject({ isError: false }); + expect(f.runHost).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + argv: f.command.argv, + stdin: f.command.stdin, + cwd: f.actor.session.header.cwd, + }), + ); + expect(f.channelApproval.requests('ada')).toEqual([]); + }); + + it('delegates reads too, without a card or a synthetic allowed-once grant', async () => { + const f = await fixture(); + f.command.argv = ['approval-templates']; + const result = await f.authority.run(f.input, () => f.native()); + expect(result).toMatchObject({ isError: false }); + expect(f.channelApproval.requests('ada')).toEqual([]); + expect(f.runHost, JSON.stringify(result)).toHaveBeenCalledOnce(); + }); + + it.each(['reject', 'cancel', 'source-revoked'] as const)( + 'keeps broker %s and late-decision refusal authoritative', + async (action) => { + const f = await fixture(); + const pending = f.authority.run(f.input, () => f.native()); + await vi.waitFor(() => expect(f.channelApproval.requests('ada')).toHaveLength(1)); + const request = f.channelApproval.requests('ada')[0]!; + if (action === 'cancel') f.controller.abort(); + else { + if (action === 'source-revoked') f.revoke(); + await f.channelApproval.decide( + OWNER_HUMAN_CONTEXT, + 'ada', + request.messageId, + action === 'reject' ? 'rejected' : 'allowed-once', + ); + } + await pending; + expect(f.runHost).not.toHaveBeenCalled(); + expect( + await f.channelApproval.decide( + OWNER_HUMAN_CONTEXT, + 'ada', + request.messageId, + 'allowed-once', + ), + ).not.toMatchObject({ ok: true }); + }, + ); + + it.each([ + 'argv', + 'stdin', + 'callId', + 'agent', + 'signal', + 'selection', + 'native-turn', + 'source', + 'turn', + 'registration', + 'same-definition-new-registration', + 'removed-registration', + 'disposed-selection', + 'token', + 'nested', + 'parent', + 'cancelled-signal', + 'native-turn-ended', + ] as const)('refuses %s identity changes at native admission and body', async (change) => { + const f = await fixture(); + let checked = false; + f.ctx.on( + 'tools/pre-execute', + async (call) => { + expect(f.authority.delegate(call)).toBe('delegated'); + let changed: ToolExecution = call; + switch (change) { + case 'argv': + changed = { ...call, arguments: { ...f.command, argv: [...f.command.argv].reverse() } }; + break; + case 'stdin': + changed = { ...call, arguments: { ...f.command, stdin: 'PRIVATE-stdin-value' } }; + break; + case 'callId': + changed = { ...call, callId: ToolCallId('different') }; + break; + case 'agent': + changed = { ...call, agent: { ...f.actor } }; + break; + case 'signal': + changed = { ...call, signal: new AbortController().signal }; + break; + case 'selection': + changed = { + ...call, + toolSet: await f.actor.ctx.tools.resolve({ + agent: f.actor, + modelSelection: { provider: 'unused', model: 'unused' }, + signal: f.controller.signal, + }), + }; + break; + case 'native-turn': + f.changeNativeTurn(2); + break; + case 'source': + f.revoke(); + break; + case 'turn': + f.changeTurn(); + break; + case 'registration': + f.removeTool(); + f.actor.ctx.tools.register( + defineTool({ + name: 'deepseekbot_cli', + description: 'Shadow', + parameters: {}, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + execute: async () => 'spoof', + }), + ); + break; + case 'same-definition-new-registration': { + const definition = f.toolSet.view(f.actor).get('deepseekbot_cli'); + if (!definition) throw new Error('Missing trusted definition'); + f.removeTool(); + f.actor.ctx.tools.register(definition); + break; + } + case 'removed-registration': + f.removeTool(); + break; + case 'disposed-selection': + f.toolSet.dispose(); + break; + case 'cancelled-signal': + f.controller.abort(); + break; + case 'native-turn-ended': + f.changeNativeTurn(null); + break; + case 'token': + changed = { ...call, token: Symbol('second') } as ToolExecution; + break; + case 'nested': + changed = { ...call, rootCallId: ToolCallId('enclosing') }; + break; + case 'parent': + changed = { ...call, parent: call.token }; + break; + } + expect(f.authority.delegate(changed)).toBe('refused'); + expect(() => f.authority.require(changed)).toThrow(); + if (change !== 'token') expect(f.authority.guard(changed)).toBeDefined(); + if (change === 'selection') changed.toolSet?.dispose(); + checked = true; + return { kind: 'deny', reason: 'Adversarial probe completed before body' }; + }, + { global: true, prepend: true }, + ); + await f.authority.run(f.input, () => f.native()); + expect(f.runHost).not.toHaveBeenCalled(); + expect(checked).toBe(true); + }); + + it('refuses ordinary model-origin and expired native invocations with identical Agent and command', async () => { + const f = await fixture(); + let shouldDelegate = false; + let captured: ToolExecution | undefined; + f.ctx.on( + 'tools/pre-execute', + async (execution) => { + captured = execution; + expect(f.authority.delegate(execution)).toBe(shouldDelegate ? 'delegated' : 'refused'); + return { kind: 'deny', reason: 'Origin probe completed before body' }; + }, + { global: true, prepend: true }, + ); + await f.native(); + shouldDelegate = true; + await f.authority.run(f.input, () => f.native()); + shouldDelegate = false; + await f.native(); + if (!captured) throw new Error('Native executor did not enter policy'); + const expired = captured; + expect(() => f.authority.require(expired)).toThrow(); + expect(f.runHost).not.toHaveBeenCalled(); + }); + + it.each(['guard', 'body'] as const)( + 'revalidates source withdrawal at the native %s boundary', + async (stage) => { + const f = await fixture(); + f.command.argv = ['approval-templates']; + if (stage === 'guard') { + f.ctx.on( + 'tools/pre-execute', + async (_execution, next) => { + const decision = await next(); + f.revoke(); + return decision; + }, + { global: true, prepend: true }, + ); + } else { + f.ctx.on( + 'tools/execute', + async (_execution, next) => { + f.revoke(); + return next(); + }, + { global: true, prepend: true }, + ); + } + expect(await f.authority.run(f.input, () => f.native())).toMatchObject({ isError: true }); + expect(f.runHost).not.toHaveBeenCalled(); + expect(f.channelApproval.requests('ada')).toEqual([]); + }, + ); + + it.each(['source', 'turn', 'native-turn', 'argv', 'stdin', 'callId'] as const)( + 'refuses invalid owned %s through the real interceptor without a transport card', + async (change) => { + const f = await fixture(); + const result = await f.authority.run(f.input, () => { + switch (change) { + case 'source': + f.revoke(); + return f.native(); + case 'turn': + f.changeTurn(); + return f.native(); + case 'native-turn': + f.changeNativeTurn(2); + return f.native(); + case 'argv': + return f.native({ arguments: { ...f.command, argv: [...f.command.argv].reverse() } }); + case 'stdin': + return f.native({ arguments: { ...f.command, stdin: 'PRIVATE-stdin-value' } }); + case 'callId': + return f.native({ callId: ToolCallId('changed-owned-call') }); + } + }); + expect(result).toMatchObject({ isError: true }); + expect(f.channelApproval.requests('ada')).toEqual([]); + expect(f.runHost).not.toHaveBeenCalled(); + }, + ); + + it.each([false, true])( + 'keeps ordinary shadow Tool approval with owned lease=%s', + async (owned) => { + const f = await fixture(); + const body = vi.fn(async () => 'unexpected'); + const shadow = async () => { + f.removeTool(); + f.actor.ctx.tools.register( + defineTool({ + name: 'deepseekbot_cli', + description: 'Untrusted same-name Tool', + parameters: { + argv: { type: 'array', items: { type: 'string' }, required: true }, + stdin: { type: 'string' }, + }, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + execute: body, + }), + ); + const selection = await f.actor.ctx.tools.resolve({ + agent: f.actor, + modelSelection: { provider: 'unused', model: 'unused' }, + signal: f.controller.signal, + }); + try { + return await executeNativeTool(f.actor.ctx, { + agent: f.actor, + name: 'deepseekbot_cli', + callId: ToolCallId('ordinary-shadow-call'), + arguments: f.command, + toolSet: selection, + signal: f.controller.signal, + }); + } finally { + selection.dispose(); + } + }; + const pending = owned ? f.authority.run(f.input, shadow) : shadow(); + await vi.waitFor(() => expect(f.channelApproval.requests('ada')).toHaveLength(1)); + const request = f.channelApproval.requests('ada')[0]!; + expect(request.toolName).toBe('deepseekbot_cli'); + await f.channelApproval.decide(OWNER_HUMAN_CONTEXT, 'ada', request.messageId, 'rejected'); + expect(await pending).toMatchObject({ isError: true }); + expect(body).not.toHaveBeenCalled(); + expect(f.runHost).not.toHaveBeenCalled(); + }, + ); + + it('refuses the trusted private Tool without an owning invocation before exposing an approval', async () => { + const f = await fixture(); + expect(await f.native()).toMatchObject({ isError: true }); + expect(f.channelApproval.requests('ada')).toEqual([]); + expect(f.runHost).not.toHaveBeenCalled(); + }); + + it('keeps the native bash approval boundary during an owned typed lease', async () => { + const f = await fixture(); + const body = vi.fn(async () => 'unexpected'); + f.actor.ctx.tools.register( + defineTool({ + name: 'bash', + description: 'Native Shell policy probe', + parameters: { command: { type: 'string', required: true } }, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + execute: body, + }), + ); + const pending = f.authority.run(f.input, () => + executeNativeTool(f.actor.ctx, { + agent: f.actor, + name: 'bash', + callId: f.input.callId, + signal: f.controller.signal, + arguments: { command: 'deepseekbot approval-template-set ada routine' }, + }), + ); + await vi.waitFor(() => expect(f.channelApproval.requests('ada')).toHaveLength(1)); + const request = f.channelApproval.requests('ada')[0]!; + expect(request.toolName).toBe('bash'); + await f.channelApproval.decide(OWNER_HUMAN_CONTEXT, 'ada', request.messageId, 'rejected'); + expect(await pending).toMatchObject({ isError: true }); + expect(body).not.toHaveBeenCalled(); + expect(f.runHost).not.toHaveBeenCalled(); + }); + + it('admits only one native token and refuses nested or concurrent lease creation', async () => { + const f = await fixture(); + f.command.argv = ['approval-templates']; + let calls = 0; + f.ctx.on( + 'tools/pre-execute', + async (execution, next) => { + calls++; + expect(f.authority.delegate(execution)).toBe(calls === 1 ? 'delegated' : 'refused'); + return next(); + }, + { global: true, prepend: true }, + ); + await f.authority.run(f.input, async () => { + await expect(f.authority.run(f.input, () => f.native())).rejects.toThrow(); + expect(await f.native()).toMatchObject({ isError: false }); + expect(await f.native()).toMatchObject({ isError: true }); + }); + expect(calls).toBe(2); + expect(f.runHost).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/core/test/tob-cli-shell.test.ts b/packages/core/test/tob-cli-shell.test.ts index 675be3593e..7a1a922600 100644 --- a/packages/core/test/tob-cli-shell.test.ts +++ b/packages/core/test/tob-cli-shell.test.ts @@ -222,11 +222,11 @@ describe('Tob native Shell scoped CLI leases', () => { supplied.env!['DEEPSEEKBOT_AGENT_TOKEN'], ); const child = await (process.platform === 'win32' - ? promisify(execFile)( - process.env['ComSpec'] ?? 'cmd.exe', - ['/d', '/s', '/c', spec.command], - { env: { ...process.env, ...supplied.env }, windowsHide: true }, - ) + ? promisify(execFile)(process.execPath, [join(directory, 'entry.mjs'), 'capabilities'], { + env: { ...process.env, ...supplied.env }, + shell: false, + windowsHide: true, + }) : promisify(execFile)('/bin/sh', ['-c', spec.command], { env: { ...process.env, ...supplied.env }, })); diff --git a/packages/core/test/tob.test.ts b/packages/core/test/tob.test.ts index 8fa31d60f9..e1beb599db 100644 --- a/packages/core/test/tob.test.ts +++ b/packages/core/test/tob.test.ts @@ -1,4 +1,4 @@ -import { OWNER_HUMAN_CONTEXT } from '../src/humans/context.js'; +import { OWNER_HUMAN_CONTEXT, humanContext } from '../src/humans/context.js'; import { DEEPSEEKBOT_RECIPE } from '../src/onboarding/service.js'; import { describe, expect, it, vi } from 'vitest'; import { attachOperationalModule } from '../src/database/owner.js'; @@ -601,3 +601,232 @@ describe('Tob canonical identity and settings', () => { } }); }); + +describe('authenticated model-free Tob CLI DM admission', () => { + it('preserves pending Memory notifications for the next model turn', async () => { + const modelInboxes: string[] = []; + const f = fixture(async (run) => { + if (run.tobCliTurn) + run.tobCliTurn.complete({ exitCode: 0, stdout: '{"templates":[]}', stderr: '' }); + else modelInboxes.push(run.inbox); + }); + const bridge = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...f.core }); + try { + const home = await f.core.tob.ensure(OWNER_HUMAN_CONTEXT); + const db = attachOperationalModule( + f.core.operationalDatabase, + 'tob-cli-memory-notification-test', + ); + db.transaction((sql) => { + sql + .prepare( + "INSERT INTO source_events(source_event_id,source_kind,bot_slug,body,created_at,payload_json) VALUES('pending-tob-memory','memory-change',?,'PENDING_MEMORY_NOTIFICATION',?, '{}')", + ) + .run(home.botSlug, new Date().toISOString()); + sql + .prepare( + "INSERT INTO inbox_admissions(source_event_id,bot_slug,reason) VALUES('pending-tob-memory',?,'memory-change')", + ) + .run(home.botSlug); + }); + const state = () => + db.read((sql) => + sql + .prepare( + 'SELECT e.observed_at AS sourceObserved,e.handled_at AS sourceHandled,a.attempt_state AS state,a.observed_at AS admissionObserved FROM source_events e JOIN inbox_admissions a USING(source_event_id) WHERE e.source_event_id=? AND a.bot_slug=?', + ) + .get('pending-tob-memory', home.botSlug), + ); + const started = await bridge.tobCli({ + action: 'start', + command: { argv: ['approval-templates'] }, + }); + expect(started.ok).toBe(true); + await f.core.runtime.whenIdle(); + expect(modelInboxes).toEqual([]); + expect(state()).toMatchObject({ + sourceObserved: null, + sourceHandled: null, + state: 'pending', + admissionObserved: null, + }); + const sent = await bridge.channelSend({ + channelId: home.channelId, + body: 'Read pending Memory notices.', + }); + expect(sent.ok).toBe(true); + await f.core.runtime.whenIdle(); + expect(modelInboxes.some((inbox) => inbox.includes('PENDING_MEMORY_NOTIFICATION'))).toBe( + true, + ); + expect(state()).toMatchObject({ state: 'handled' }); + } finally { + await f.close(); + } + }); + + it('owns the accepted Human DM turn, exposes the result, and expires captured authority on completion', async () => { + let captured!: () => void; + const f = fixture(async (run) => { + if (!run.tobCliTurn) throw new Error('Unexpected model turn'); + captured = f.core.runtime.captureTobCliAuthority!(run.sessionId); + expect(captured).not.toThrow(); + expect(run.tobCliTurn.command).toEqual({ + argv: ['approval-templates'], + stdin: 'private-stdin', + }); + run.tobCliTurn.complete({ exitCode: 0, stdout: '{"templates":[]}', stderr: '' }); + }); + const bridge = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...f.core }); + try { + const started = await bridge.tobCli({ + action: 'start', + command: { argv: ['approval-templates'], stdin: 'private-stdin' }, + }); + if (!started.ok) throw new Error(started.error.message); + await f.core.runtime.whenIdle(); + const messages = f.core.channels.readMessages(started.value.channelId); + expect( + messages.find((message) => message.id === started.value.messageId)?.author, + ).toMatchObject({ kind: 'human' }); + expect(JSON.stringify(messages)).not.toContain('private-stdin'); + expect(await bridge.tobCli({ action: 'status', id: started.value.id })).toMatchObject({ + ok: true, + value: { state: 'completed', result: { exitCode: 0, stdout: '{"templates":[]}' } }, + }); + expect( + f.core.channels.humanSendStatus?.(started.value.channelId, started.value.messageId) + ?.progress, + ).toMatchObject({ state: 'completed', terminal: true }); + expect(captured).toThrow('human-dm-required'); + expect( + f.core.runtime.admitDmMessage(OWNER_HUMAN_CONTEXT, { + channelId: started.value.channelId, + messageId: started.value.messageId, + body: 'replay', + }), + ).toMatchObject({ admitted: false, reason: 'cli-request-expired' }); + } finally { + await f.close(); + } + }); + it.each(['session', 'all'] as const)( + 'stops a running model-free CLI lease through %s Session Stop', + async (scope) => { + let entered!: (run: OrchestratorAgentRun) => void; + const running = new Promise((resolve) => { + entered = resolve; + }); + const f = fixture(async (run) => { + const cli = run.tobCliTurn; + if (!cli) throw new Error('Unexpected model turn'); + entered(run); + await new Promise((resolve) => + cli.signal.addEventListener('abort', () => resolve(), { once: true }), + ); + cli.signal.throwIfAborted(); + }); + const bridge = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...f.core }); + try { + const started = await bridge.tobCli({ + action: 'start', + command: { argv: ['approval-templates'] }, + }); + if (!started.ok) throw new Error(started.error.message); + const run = await running; + if (!f.core.runtime.stopSession || !f.core.runtime.stopAllSessions) + throw new Error('Session Stop is unavailable'); + expect(await f.core.runtime.stopSession(run.bot.slug, 'unrelated-session')).toMatchObject({ + outcome: 'refused', + code: 'unknown-session', + }); + expect(run.tobCliTurn?.signal.aborted).toBe(false); + const outcome = + scope === 'session' + ? await f.core.runtime.stopSession(run.bot.slug, run.sessionId) + : await f.core.runtime.stopAllSessions(run.bot.slug); + expect(outcome).toMatchObject({ + stopped: [{ botSlug: run.bot.slug, sessionId: run.sessionId, role: 'orchestrator' }], + alreadyIdle: [], + }); + expect(run.tobCliTurn?.signal.aborted).toBe(true); + await f.core.runtime.whenIdle(); + expect(await bridge.tobCli({ action: 'status', id: started.value.id })).toMatchObject({ + ok: true, + value: { state: 'cancelled', cancelRequested: true }, + }); + } finally { + await f.close(); + } + }, + ); + + it('rejects a second lease, cancels the active turn, and refuses supplied authority', async () => { + let ready!: () => void; + const entered = new Promise((resolve) => { + ready = resolve; + }); + const f = fixture(async (run) => { + if (!run.tobCliTurn) throw new Error('Unexpected model turn'); + ready(); + await new Promise((resolve) => + run.tobCliTurn!.signal.addEventListener('abort', () => resolve(), { once: true }), + ); + run.tobCliTurn.signal.throwIfAborted(); + }); + const bridge = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...f.core }); + try { + const started = await bridge.tobCli({ + action: 'start', + command: { argv: ['approval-templates'] }, + }); + if (!started.ok) throw new Error(started.error.message); + await entered; + expect( + await bridge.tobCli({ action: 'start', command: { argv: ['approval-templates'] } }), + ).toMatchObject({ ok: false, error: { code: 'bot-busy' } }); + expect( + await bridge.tobCli({ + action: 'start', + command: { argv: ['list'], sourceEventId: 'forged' }, + }), + ).toMatchObject({ ok: false, error: { code: 'invalid-input' } }); + expect(await bridge.tobCli({ action: 'cancel', id: started.value.id })).toMatchObject({ + ok: true, + value: { cancelRequested: true }, + }); + await f.core.runtime.whenIdle(); + expect(await bridge.tobCli({ action: 'status', id: started.value.id })).toMatchObject({ + ok: true, + value: { state: 'cancelled' }, + }); + } finally { + await f.close(); + } + }); +}); + +it('refuses foreign Human and closed-runtime CLI access before allocating a Tob', async () => { + const f = fixture(); + try { + await f.core.team.setOwnerPassword(OWNER_HUMAN_CONTEXT, 'test-owner-password-4212'); + await f.core.team.setMode(OWNER_HUMAN_CONTEXT, true); + const member = await f.core.team.createMember(OWNER_HUMAN_CONTEXT, 'e4-member', 'E4 Member'); + const foreign = createBridgeMethods(humanContext(member.member.humanId), { ...f.core }); + expect( + await foreign.tobCli({ action: 'start', command: { argv: ['approval-templates'] } }), + ).toMatchObject({ ok: false, error: { code: 'permission-required' } }); + expect(f.core.registry.list()).toHaveLength(0); + await f.core.runtime.close(); + const owner = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...f.core }); + expect( + await owner.tobCli({ action: 'status', id: '00000000-0000-4000-8000-000000000000' }), + ).toMatchObject({ ok: false, error: { code: 'runtime-closed' } }); + expect( + await owner.tobCli({ action: 'start', command: { argv: ['approval-templates'] } }), + ).toMatchObject({ ok: false, error: { code: 'runtime-closed' } }); + expect(f.core.registry.list()).toHaveLength(0); + } finally { + await f.close(); + } +}); diff --git a/packages/core/test/tool-approval.test.ts b/packages/core/test/tool-approval.test.ts index 8ef3fcc7b7..091738d471 100644 --- a/packages/core/test/tool-approval.test.ts +++ b/packages/core/test/tool-approval.test.ts @@ -58,6 +58,60 @@ function fixture( } describe('Channel tool approval', () => { + it('uses a saved external-effect authorization before any Reviewer call and rechecks revocation', async () => { + const state = fixture(); + const home = createTempRoot('bh-effect-rule-'); + const database = mountOperationalDatabase({ + dshHome: home, + schemaPlan: BOT_HARNESS_SCHEMA_PLAN, + }); + const rules = createToolApprovalRuleStore( + attachOperationalModule(database, 'tool-approval-rules'), + ); + const review = vi.fn(); + const broker = new ChannelToolApproval( + state.channels, + state.ownership, + rules, + undefined, + undefined, + undefined, + undefined, + { template: () => ({ name: 'review', text: 'Ask the Human.' }), review, log: vi.fn() }, + () => true, + ); + const rule = rules.createPending({ + botSlug, + role: 'assignment', + scopeKey: JSON.stringify(['assignment', '/tmp/project']), + kind: 'tool', + toolName: 'bot_send_message', + input: '', + }); + rules.activate(botSlug, rule.id); + broker.track({ + ...state.execution(), + name: 'bot_send_message', + arguments: { body: 'user already approved', effects: { changes: 'none' } }, + }); + try { + expect( + await broker.ask({ agent: state.agent, toolName: 'bot_send_message', callId: 'call-1' }), + ).toBe('allowed-once'); + expect(review).not.toHaveBeenCalled(); + expect(state.messages).toHaveLength(0); + const guard = broker.executionGuard(state.agent, 'call-1')!; + const args = { body: 'user already approved', effects: { changes: 'none' } }; + expect(guard('bot_send_message', args)).toBe(true); + rules.revoke(botSlug, rule.id); + expect(guard('bot_send_message', args)).toBe(false); + } finally { + broker.close(); + database.close(); + rmSync(home, { recursive: true, force: true }); + } + }); + it.each([ ['channel_read', {}, 'none', false], ['channel_attachment_open', { access: 'read' }, 'none', false], @@ -79,7 +133,7 @@ describe('Channel tool approval', () => { undefined, undefined, undefined, - { template: () => ({ name: 'test', text: 'ask' }), review, log: vi.fn() }, + { template: () => undefined, review, log: vi.fn() }, () => true, ); const effects = toolEffects(name, args); @@ -88,7 +142,11 @@ describe('Channel tool approval', () => { broker.track({ ...state.execution(), name, arguments: args }); try { const answer = broker.ask({ agent: state.agent, toolName: name, callId: 'call-1' }); - if (name === 'bash' || effects?.authority === 'management') { + if ( + name === 'bash' || + effects?.authority === 'management' || + (effects?.changes === 'irreversible' && effects.reach === 'external') + ) { await vi.waitFor(() => expect(state.messages).toHaveLength(1)); await broker.decide(OWNER_HUMAN_CONTEXT, botSlug, state.messages[0]!.id, 'rejected'); expect(await answer).toBe('rejected'); diff --git a/packages/core/test/tool-effects-contract.test.ts b/packages/core/test/tool-effects-contract.test.ts new file mode 100644 index 0000000000..83c0f41596 --- /dev/null +++ b/packages/core/test/tool-effects-contract.test.ts @@ -0,0 +1,42 @@ +import { expect, it } from 'vitest'; +import { parseToolEffects } from '../src/workspaces/tool-effects-contract.js'; + +it('parses effect metadata once and removes unknown or undefined fields', () => { + expect( + parseToolEffects({ + changes: 'irreversible', + reach: 'external', + personalData: true, + authority: 'management', + secrets: false, + actor: 'not authority', + }), + ).toEqual({ + changes: 'irreversible', + reach: 'external', + personalData: true, + authority: 'management', + secrets: false, + }); + expect( + parseToolEffects({ + changes: 'none', + reach: 'local', + personalData: false, + authority: undefined, + secrets: undefined, + }), + ).toEqual({ changes: 'none', reach: 'local', personalData: false }); +}); +it.each([ + undefined, + null, + [], + {}, + { changes: 'reversible', reach: 'external', personalData: true, authority: 'model' }, + { changes: 'irreversible', reach: 'unknown', personalData: true }, + { changes: 'none', reach: 'local', personalData: 'yes' }, + { changes: 'none', reach: 'local', personalData: true, secrets: 'yes' }, +])('omits malformed optional metadata %j without inventing authority', (value) => { + expect(parseToolEffects(value)).toBeUndefined(); +}); diff --git a/packages/core/test/tool-effects.test.ts b/packages/core/test/tool-effects.test.ts index 15e6697482..eeecfc51a1 100644 --- a/packages/core/test/tool-effects.test.ts +++ b/packages/core/test/tool-effects.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { cliEffects, brokerCliEffects } from '../src/bots/cli-effects.js'; import { decideToolApproval, toolEffects, @@ -150,18 +151,24 @@ const request = { const local: ToolEffects = { changes: 'none', reach: 'local', personalData: false }; const external: ToolEffects = { changes: 'irreversible', reach: 'external', personalData: true }; -describe('E1 pure approval decision', () => { +describe('effect approval decision', () => { + it('admits trusted irreversible external declarations regardless of claimed approval in input', () => { + expect( + toolApprovalRequired( + 'bot_send_message', + { body: 'user already approved', effects: { changes: 'none' } }, + true, + ), + ).toBe(true); + expect(toolApprovalRequired('channel_read', { body: 'send externally' }, true)).toBe(false); + expect(toolApprovalRequired('secret_http', { method: 'GET' }, true)).toBe(false); + expect(toolApprovalRequired('secret_http', { method: 'POST' }, true)).toBe(true); + }); + it.each([ [local, { fullAccess: true }, 'full-access', true, false, 'full-access-existing'], - [external, { fullAccess: true }, 'full-access', true, false, 'full-access-existing'], - [ - { ...external, secrets: true }, - { fullAccess: true }, - 'full-access', - true, - false, - 'full-access-existing', - ], + [external, { fullAccess: true }, 'human', true, false, 'human-required'], + [{ ...external, secrets: true }, { fullAccess: true }, 'human', true, false, 'human-required'], [ { ...local, authority: 'management' }, { fullAccess: true, reviewer: true }, @@ -241,3 +248,576 @@ describe('E1 pure approval decision', () => { }, ); }); + +describe('CLI effect declarations at the public approval seam', () => { + it('declares exact brokered management argv without trusting prose', () => { + expect( + toolEffects('deepseekbot grant-write-set', { + patch: { argv: ['grant-write-set', 'bot', '--grant', 'grant', '--enabled', '--confirm'] }, + }), + ).toEqual({ + changes: 'reversible', + reach: 'local', + personalData: true, + authority: 'management', + }); + expect( + toolEffects('deepseekbot unknown', { patch: { argv: ['future-command'] } }), + ).toBeUndefined(); + expect( + toolEffects('bash', { command: 'deepseekbot grant-write-set bot --enabled' }), + ).toBeUndefined(); + }); +}); + +it('keeps irreversible reach when a CLI operation also writes output', () => { + expect( + toolEffects('deepseekbot marketplace-upload', { + patch: { argv: ['marketplace-upload', 'bot', '--out=result.json'] }, + }), + ).toMatchObject({ changes: 'irreversible', reach: 'external' }); + expect( + toolEffects('deepseekbot grant-write-set', { + command: 'grant-write-set', + target: 'bot', + patch: { enabled: true }, + expectedRevision: 2, + }), + ).toMatchObject({ authority: 'management' }); + expect( + toolEffects('deepseekbot channels', { patch: { argv: ['grant-write-set', 'bot'] } }), + ).toBeUndefined(); +}); + +describe('integrated approval-template command effects', () => { + it.each([['--blank'], ['--parts-file', 'guidance.json'], ['--from', 'cautious']])( + 'retains source flags %j and distinguishes save from apply', + (...source) => { + const argv = ['approval-template', 'create', 'draft', ...source]; + expect(toolEffects('deepseekbot approval-template', { patch: { argv } })).toEqual({ + changes: 'reversible', + reach: 'local', + personalData: true, + }); + expect( + toolEffects('deepseekbot approval-template', { + patch: { argv: [...argv, '--apply-to', 'fixture-bot'] }, + }), + ).toEqual({ + changes: 'reversible', + reach: 'local', + personalData: true, + authority: 'management', + }); + }, + ); + + it('retains explicit revision-bound deletion as management', () => { + const argv = [ + 'approval-template', + 'delete', + 'draft', + '--confirm', + '--delete-revision', + 'a'.repeat(64), + ]; + expect(toolEffects('deepseekbot approval-template', { patch: { argv } })).toMatchObject({ + authority: 'management', + }); + }); +}); + +describe('CLI family semantic effects', () => { + it('declares a channels send after strict option parsing as external delivery', () => { + expect( + toolEffects('deepseekbot channels', { + patch: { argv: ['channels', '--compact', 'send', 'channel-1', '--body-stdin'] }, + }), + ).toEqual({ changes: 'irreversible', reach: 'external', personalData: true }); + }); +}); + +it.each([ + [ + 'devices', + ['--member', 'alex', '--revoke', 'grant'], + { changes: 'irreversible', authority: 'management' }, + ], + ['bots', ['delete', 'bot'], { changes: 'irreversible', reach: 'local' }], + ['members', ['password', '--password-stdin'], { authority: 'management', secrets: true }], + ['cloud', ['import', '--input-stdin'], { authority: 'management', secrets: true }], + ['voice-provider-add', ['voice', '--key-stdin'], { secrets: true }], + [ + 'spaces', + ['delete', 'space', '--confirm'], + { changes: 'irreversible', authority: 'management' }, + ], + ['roles', ['list'], { changes: 'none' }], +] as const)('keeps actual family semantics for %s %j', (command, rest, expected) => { + expect( + toolEffects('deepseekbot ' + command, { patch: { argv: [command, ...rest] } }), + ).toMatchObject(expected); +}); + +it.each(['bot-tool', 'browser-tool', 'computer-tool', 'todo-tool', 'settings-set'])( + 'keeps %s opaque when only stdin identity is available', + (command) => { + expect( + toolEffects('deepseekbot ' + command, { + patch: { + argv: [command, 'bot', 'arbitrary-tool', '--args-stdin'], + stdinSha256: 'not-authority', + }, + }), + ).toBeUndefined(); + }, +); +it('keeps remote output, secrets and management together', () => { + expect( + toolEffects('deepseekbot relationships', { + patch: { argv: ['relationships', 'approve', 'id', 'key', '--out=a.json'] }, + }), + ).toMatchObject({ + authority: 'management', + secrets: true, + reach: 'external', + changes: 'reversible', + }); +}); + +it.each(['delete', 'edit'])( + 'does not turn the %s family action into a declared root command', + (command) => { + expect(toolEffects('deepseekbot ' + command, { patch: { argv: [command] } })).toBeUndefined(); + }, +); + +it('resolves private-route reads and secret-bearing remote route changes', () => { + expect( + toolEffects('deepseekbot private-route', { patch: { argv: ['private-route', 'list'] } }), + ).toMatchObject({ changes: 'none', reach: 'local' }); + expect( + toolEffects('deepseekbot private-route', { + patch: { + argv: [ + 'private-route', + 'add', + 'route', + '--hostname', + 'example.test', + '--token-stdin', + '--confirm', + ], + }, + }), + ).toMatchObject({ reach: 'external', authority: 'management', secrets: true }); +}); + +it.each(['tool-approval-decide', 'tool-approval-rule-revoke', 'user-question-answer'])( + 'includes external card settlement for %s', + (command) => { + expect(toolEffects('deepseekbot ' + command, { patch: { argv: [command] } })).toMatchObject({ + changes: 'irreversible', + reach: 'external', + }); + }, +); +it.each([ + 'approval-test', + 'approval-retry', + 'question-retry', + 'failure-alerts-test', + 'failure-alerts-retry', +])('includes actual provider card/notification delivery for %s', (command) => { + expect( + toolEffects('deepseekbot ' + command, { patch: { argv: [command, 'bot'] } }), + ).toMatchObject({ changes: 'irreversible', reach: 'external' }); +}); +it('includes irreversible member purge without weakening broker refusal', () => { + expect( + toolEffects('deepseekbot members', { + patch: { argv: ['members', 'purge', 'member', '--confirm', '--token-stdin'] }, + }), + ).toMatchObject({ changes: 'irreversible', authority: 'management', secrets: true }); +}); + +it('covers the landed im-reconnect owner without inventing permission changes', () => { + expect( + toolEffects('deepseekbot im-reconnect', { + patch: { argv: ['im-reconnect', 'bot', '--app', 'app'] }, + }), + ).toEqual({ changes: 'reversible', reach: 'external', personalData: true }); +}); + +it('shares typed native CLI effects while keeping unknown command provenance opaque', () => { + const argv = ['approval-template-set', 'fixture-bot', 'fixture-template']; + expect(toolEffects('deepseekbot_cli', { argv, stdin: '' })).toEqual( + toolEffects('deepseekbot approval-template-set', { patch: { argv } }), + ); + expect(toolEffects('deepseekbot_cli', { argv: ['unknown-family'], stdin: '' })).toBeUndefined(); + expect( + toolEffects('deepseekbot_cli', { + argv: ['marketplace-upload', 'fixture-bot', '--out=fixture.json'], + }), + ).toMatchObject({ changes: 'irreversible', reach: 'external' }); +}); + +it.each([ + { + argv: ['device-notifications', '--device-file', 'paired.json', '--delivery', 'push'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: [ + 'device-notifications', + '--device-file', + 'paired.json', + '--delivery', + 'push', + '--out', + 'result.json', + ], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: ['device-notifications', '--device-file', 'paired.json', '--preferences-stdin'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: [ + 'device-notifications', + '--device-file', + 'paired.json', + '--preferences-stdin', + '--out', + 'result.json', + ], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: ['phone-notifications', '--device-file', 'paired.json', '--delivery', 'push'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: [ + 'phone-notifications', + '--device-file', + 'paired.json', + '--delivery', + 'push', + '--out', + 'result.json', + ], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: ['phone-notifications', '--device-file', 'paired.json', '--preferences-stdin'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: [ + 'phone-notifications', + '--device-file', + 'paired.json', + '--preferences-stdin', + '--out', + 'result.json', + ], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + personalData: true, + }, + }, + { + argv: ['cloud', 'import', '--input-stdin'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + secrets: true, + personalData: true, + }, + }, + { + argv: ['cloud', 'remove', '--input-stdin', '--confirm'], + expected: { + changes: 'irreversible', + reach: 'local', + authority: 'management', + secrets: true, + personalData: true, + }, + }, + { + argv: ['cloud', 'import', '--input-stdin', '--out', 'result.json'], + expected: { + changes: 'reversible', + reach: 'external', + authority: 'management', + secrets: true, + personalData: true, + }, + }, + { + argv: ['cloud', 'remove', '--input-stdin', '--out', 'result.json', '--confirm'], + expected: { + changes: 'irreversible', + reach: 'workspace', + authority: 'management', + secrets: true, + personalData: true, + }, + }, + { + argv: ['share-draft-export', 'ada'], + expected: { + changes: 'reversible', + reach: 'workspace', + personalData: true, + }, + }, +])('preserves real notification/cloud/workspace effects for $argv', ({ argv, expected }) => { + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot ' + argv[0], { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv, stdin: '' })).toEqual(expected); +}); + +it('keeps the inherited global-template selection behind explicit management approval', () => { + const argv = ['approval-template-global-set', 'cautious']; + const expected = { + changes: 'reversible', + reach: 'local', + personalData: true, + authority: 'management', + }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot approval-template-global-set', { patch: { argv } })).toEqual( + expected, + ); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); +}); + +it.each([false, true])( + 'keeps voice provider creation management authority (key stdin: %s)', + (keyStdin) => { + const argv = ['voice-provider-add', 'qa-provider', ...(keyStdin ? ['--key-stdin'] : [])]; + const expected = { + changes: 'reversible', + reach: 'local', + personalData: true, + authority: 'management', + ...(keyStdin ? { secrets: true } : {}), + }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot voice-provider-add', { patch: { argv } })).toEqual( + expected, + ); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); + expect(toolApprovalRequired('deepseekbot voice-provider-add', { patch: { argv } }, true)).toBe( + true, + ); + }, +); + +it('treats stdin-driven conversation changes conservatively on both CLI paths', () => { + const argv = ['messaging-conversation', 'qa-bot', '--input-stdin', '--confirm']; + const expected = { changes: 'irreversible', reach: 'external', personalData: true }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot messaging-conversation', { patch: { argv } })).toEqual( + expected, + ); + expect(toolEffects('deepseekbot_cli', { argv, stdin: '{"kind":"block"}' })).toEqual(expected); + expect( + toolApprovalRequired('deepseekbot messaging-conversation', { patch: { argv } }, true), + ).toBe(true); +}); + +it.each([ + ['skills-list', '--bot', 'ada'], + ['channels', 'member-candidates', 'group-a', '--query', 'Alice'], +])('keeps new main read commands declared on both execution paths: %j', (...argv) => { + const expected = { changes: 'none', reach: 'local', personalData: true }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot ' + argv[0], { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); +}); +it('parses repeatable Skill Invocations through the same strict send options without weakening delivery effects', () => { + const argv = [ + 'send', + 'ada', + '--text', + '/first /second', + '--skill', + 'host/first', + '--skill', + 'bot:ada/second', + ]; + const expected = { changes: 'irreversible', reach: 'external', personalData: true }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot send', { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); +}); + +it.each([ + { + argv: ['speaker-policy', '--human-id', 'human-a', '--topic', 'project-a'], + effect: { changes: 'none' }, + }, + { argv: ['bot-access', 'reachable'], effect: { changes: 'none' } }, + { argv: ['bot-access', 'visibility', 'ada'], effect: { changes: 'none' } }, + { argv: ['bots', 'visibility', 'ada'], effect: { changes: 'none' } }, + { argv: ['bot-access', 'switches', 'ada'], effect: { changes: 'none' } }, + { + argv: ['bots', 'switches', 'ada', '--speaker-context', 'off'], + effect: { changes: 'reversible', authority: 'management' }, + }, + { + argv: ['bot-access', 'switches', 'ada', '--proactive-dms', 'on', '--join-channels', 'off'], + effect: { changes: 'reversible', authority: 'management' }, + }, + { + argv: ['bots', 'visibility-set', 'ada', '--private', '--preview'], + effect: { changes: 'none' }, + }, + { + argv: ['bot-access', 'visibility-set', 'ada', '--public', 'everyone', '--preview', '--confirm'], + effect: { changes: 'none' }, + }, + { + argv: ['bots', 'visibility-set', 'ada', '--public', 'everyone'], + effect: { changes: 'reversible', authority: 'management' }, + }, + { + argv: ['bot-access', 'visibility-set', 'ada', '--private', '--confirm'], + effect: { changes: 'reversible', authority: 'management' }, + }, + { argv: ['bot-access', 'proactive-opt-out', 'ada', 'on'], effect: { changes: 'reversible' } }, + { argv: ['roles', 'conflicts', 'alice'], effect: { changes: 'none' } }, + { + argv: ['roles', 'update', 'role-a', '--policy-stdin'], + effect: { changes: 'reversible', authority: 'management' }, + }, +])( + 'keeps principal policy read/write effects aligned with actual CLI dispatch for $argv', + ({ argv, effect }) => { + const expected = { + reach: 'local', + personalData: true, + ...effect, + }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot ' + argv[0], { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); + if ('authority' in effect) + expect(toolApprovalRequired('deepseekbot ' + argv[0], { patch: { argv } }, true)).toBe(true); + }, +); + +it.each(['input', 'open', 'status', 'takeover'])( + 'keeps computer-video %s effects aligned with actual desktop input', + (action) => { + const argv = ['computer-video', action, '--args-stdin']; + const expected = { + changes: action === 'input' ? 'irreversible' : 'reversible', + reach: action === 'input' ? 'external' : 'local', + personalData: true, + }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot computer-video', { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); + if (action === 'input') + expect(toolApprovalRequired('deepseekbot computer-video', { patch: { argv } }, true)).toBe( + true, + ); + }, +); +it.each([false, true])( + 'declares template deletion preview versus permanent confirm (%s)', + (confirmed) => { + const argv = [ + 'approval-template', + 'delete', + 'qa', + ...(confirmed ? ['--confirm', '--delete-revision', 'a'.repeat(64)] : []), + ]; + const expected = { + changes: confirmed ? 'irreversible' : 'none', + reach: 'local', + personalData: true, + ...(confirmed ? { authority: 'management' } : {}), + }; + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot approval-template', { patch: { argv } })).toEqual( + expected, + ); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); + if (confirmed) + expect(toolApprovalRequired('deepseekbot approval-template', { patch: { argv } }, true)).toBe( + true, + ); + }, +); + +it.each([ + { + argv: ['skills-memory', '--bot', 'ada'], + expected: { changes: 'none', reach: 'memory', personalData: true }, + }, + { + argv: ['skills-show', 'review', '--owner', 'host'], + expected: { changes: 'none', reach: 'local', personalData: true }, + }, + { + argv: ['skills-show', 'review', '--owner', 'bot:ada'], + expected: { changes: 'none', reach: 'memory', personalData: true }, + }, + { + argv: ['skills-show', 'review', '--owner', 'workspace:project'], + expected: { changes: 'none', reach: 'workspace', personalData: true }, + }, + { + argv: ['skills-remove', 'review', '--bot', 'ada', '--confirm'], + expected: { changes: 'reversible', reach: 'memory', personalData: true }, + }, +])('declares newly landed Skill commands on shared CLI paths: $argv', ({ argv, expected }) => { + expect(cliEffects(argv)).toEqual(expected); + expect(brokerCliEffects('deepseekbot ' + argv[0], { patch: { argv } })).toEqual(expected); + expect(toolEffects('deepseekbot_cli', { argv })).toEqual(expected); +}); diff --git a/packages/core/test/turn-preparation-stop.test.ts b/packages/core/test/turn-preparation-stop.test.ts index 0c7d9f064c..8df897e093 100644 --- a/packages/core/test/turn-preparation-stop.test.ts +++ b/packages/core/test/turn-preparation-stop.test.ts @@ -1,8 +1,10 @@ +import { setImmediate } from 'node:timers/promises'; import { describe, expect, it, vi } from 'vitest'; import { createDshBotAgentAdapter } from '../src/runtime/dsh-bot-agent-adapter.js'; import type { OrchestratorAgentRun } from '../src/runtime/bot-runtime.js'; import { FakeAgentHost, FAKE_BOT as BOT } from './dsh-agent-host-fixture.js'; +import { createTempRoot } from './helpers.js'; const run = { sessionId: 'orchestrator-ada', @@ -14,7 +16,19 @@ const run = { assignments: {}, } as unknown as OrchestratorAgentRun; -const never = () => new Promise(() => undefined); +function preparation() { + let release: () => void = () => undefined; + const pending = new Promise((resolve) => { + release = resolve; + }); + return { + wait: () => pending, + async settle() { + release(); + await setImmediate(); + }, + }; +} function adapterWith( host: FakeAgentHost, @@ -22,11 +36,12 @@ function adapterWith( preparationTimeoutMs?: number, observePreparation?: (botSlug: string, sessionId: string, preparing: boolean) => void, ) { + const memoryDir = createTempRoot('turn-preparation-memory-'); return createDshBotAgentAdapter({ ...(observePreparation === undefined ? {} : { observePreparation, preparationVisibleMs: 0 }), agents: host, defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, - orchestratorCwd: () => '/memory/ada', + orchestratorCwd: () => memoryDir, ensureWorkspace: () => undefined, prepareModelRoute, ...(preparationTimeoutMs === undefined ? {} : { preparationTimeoutMs }), @@ -36,7 +51,8 @@ function adapterWith( describe('a Turn stuck before its Agent starts', () => { it('is released by a Human stop while the model route is preparing, and the next Turn runs', async () => { const host = new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => undefined }); - const prepare = vi.fn<() => Promise>().mockImplementationOnce(never); + const pending = preparation(); + const prepare = vi.fn<() => Promise>().mockImplementationOnce(pending.wait); prepare.mockResolvedValue(undefined); const preparing = vi.fn(); const adapter = adapterWith(host, prepare, undefined, preparing); @@ -51,17 +67,23 @@ describe('a Turn stuck before its Agent starts', () => { expect(host.createOptions).toHaveLength(0); expect(preparing.mock.calls.at(-1)).toEqual([BOT.slug, run.sessionId, false]); + await expect(adapter.runOrchestrator(run)).rejects.toMatchObject({ code: 'bot-busy' }); + expect(host.createOptions).toHaveLength(0); + await pending.settle(); + await expect(adapter.runOrchestrator({ ...run, message: 'again' })).resolves.toBeUndefined(); expect(host.received.get(run.sessionId)).toHaveLength(1); } finally { + await pending.settle(); await adapter.close(); } }); it('is released by a Human stop when the Session already ran a Turn', async () => { const host = new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => undefined }); + const pending = preparation(); const prepare = vi.fn<() => Promise>().mockResolvedValueOnce(undefined); - prepare.mockImplementationOnce(never).mockResolvedValue(undefined); + prepare.mockImplementationOnce(pending.wait).mockResolvedValue(undefined); const adapter = adapterWith(host, prepare); try { await adapter.runOrchestrator(run); @@ -71,16 +93,26 @@ describe('a Turn stuck before its Agent starts', () => { expect(adapter.stopOrchestratorTurn?.(BOT.slug)).toBe(run.sessionId); await expect(stuck).resolves.toBeUndefined(); + await expect(adapter.runOrchestrator(run)).rejects.toMatchObject({ code: 'bot-busy' }); + expect(host.createOptions).toHaveLength(1); + await pending.settle(); + await expect(adapter.runOrchestrator({ ...run, message: 'third' })).resolves.toBeUndefined(); expect(host.received.get(run.sessionId)).toHaveLength(2); } finally { + await pending.settle(); await adapter.close(); } }); it('is released by a Human stop while the Session is resuming', async () => { const host = new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => undefined }); - const resume = vi.spyOn(host, 'resume').mockImplementationOnce(never); + const pending = preparation(); + const realResume = host.resume.bind(host); + const resume = vi.spyOn(host, 'resume').mockImplementationOnce(async (options) => { + await pending.wait(); + return realResume(options); + }); const adapter = adapterWith(host, async () => undefined); try { const stuck = adapter.runOrchestrator({ ...run, resume: true }); @@ -89,25 +121,36 @@ describe('a Turn stuck before its Agent starts', () => { expect(adapter.stopOrchestratorTurn?.(BOT.slug)).toBe(run.sessionId); await expect(stuck).resolves.toBeUndefined(); + await expect(adapter.runOrchestrator(run)).rejects.toMatchObject({ code: 'bot-busy' }); + expect(host.createOptions).toHaveLength(0); + await pending.settle(); + await expect(adapter.runOrchestrator(run)).resolves.toBeUndefined(); expect(host.received.get(run.sessionId)).toHaveLength(1); } finally { + await pending.settle(); await adapter.close(); } }); it('fails a preparation that outlives its timeout with a clear message, then runs the next Turn', async () => { const host = new FakeAgentHost({ kind: 'completed' }, { onTurn: async () => undefined }); - const prepare = vi.fn<() => Promise>().mockImplementationOnce(never); + const pending = preparation(); + const prepare = vi.fn<() => Promise>().mockImplementationOnce(pending.wait); prepare.mockResolvedValue(undefined); const adapter = adapterWith(host, prepare, 20); try { await expect(adapter.runOrchestrator(run)).rejects.toThrow( /Preparing this turn took longer than/, ); + await expect(adapter.runOrchestrator(run)).rejects.toMatchObject({ code: 'bot-busy' }); + expect(host.createOptions).toHaveLength(0); + await pending.settle(); + await expect(adapter.runOrchestrator(run)).resolves.toBeUndefined(); expect(host.received.get(run.sessionId)).toHaveLength(1); } finally { + await pending.settle(); await adapter.close(); } }); diff --git a/packages/core/test/voice-local-service.test.ts b/packages/core/test/voice-local-service.test.ts index 3208e1d30d..79593c310b 100644 --- a/packages/core/test/voice-local-service.test.ts +++ b/packages/core/test/voice-local-service.test.ts @@ -8,7 +8,7 @@ import { promisify } from 'node:util'; import { Context } from '@deepseek-ai/cordis'; import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { runVoiceLocalKit } from '../src/bots/cli-voice.js'; import { parseAgentManagement } from '../src/bots/cli-agent-management.js'; @@ -237,6 +237,47 @@ describe('unreachable custom provider on this computer', () => { }); describe('Tob voice operations', () => { + it('prepares a Provider test for approval and rejects changed targets before network work', async () => { + const { providers, registry } = await fixture(); + const provider = await providers.add({ preset: 'local' }); + const prepare = createTobVoiceOperations({ + providers: () => providers, + registry, + isProtectedBot: () => false, + }); + const prepared = await prepare('voice-provider-test', { + id: provider.id, + voiceId: 'fixture-voice', + }); + if (!prepared) throw new Error('Expected Provider test preparation'); + expect(prepared.proposal).toEqual({ + command: 'voice-provider-test', + target: provider.id, + previousValue: providers.get(provider.id), + patch: { id: provider.id, voiceId: 'fixture-voice' }, + }); + expect( + TOB_VOICE_CAPABILITIES.find((entry) => entry.command === 'voice-provider-test')?.write, + ).toBe(true); + const externalTest = vi.spyOn(providers, 'test'); + const beforeEffect = vi.fn(); + try { + await expect( + prepared.run(() => { + throw new TobError('approval-denied'); + }, beforeEffect), + ).rejects.toThrow('approval-denied'); + const removal = await prepare('voice-provider-remove', { id: provider.id }); + if (!removal) throw new Error('Expected Provider removal preparation'); + await removal.run(() => undefined); + await expect(prepared.run(() => undefined, beforeEffect)).rejects.toThrow('stale-setting'); + expect(beforeEffect).not.toHaveBeenCalled(); + expect(externalTest).not.toHaveBeenCalled(); + } finally { + externalTest.mockRestore(); + } + }); + it('lists, adds a keyless provider with a proposal, and binds a Bot voice', async () => { const { providers, registry } = await fixture(); const prepare = createTobVoiceOperations({ diff --git a/scripts/bounded-file.mjs b/scripts/bounded-file.mjs new file mode 100644 index 0000000000..a2dc194a68 --- /dev/null +++ b/scripts/bounded-file.mjs @@ -0,0 +1,29 @@ +import { openSync, fstatSync, readSync, closeSync } from 'node:fs'; + +export function readBoundedFileSync(filename, maxBytes) { + if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError('Invalid file bound'); + const descriptor = openSync(filename, 'r'); + try { + const stat = fstatSync(descriptor); + if (!stat.isFile() || stat.size > maxBytes) throw new Error('File exceeds capture bound'); + const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1)); + const parts = []; + let total = 0; + while (total <= maxBytes) { + const count = readSync( + descriptor, + chunk, + 0, + Math.min(chunk.length, maxBytes + 1 - total), + null, + ); + if (count === 0) return Buffer.concat(parts, total); + total += count; + if (total > maxBytes) throw new Error('File exceeds capture bound'); + parts.push(Buffer.from(chunk.subarray(0, count))); + } + throw new Error('File exceeds capture bound'); + } finally { + closeSync(descriptor); + } +} diff --git a/scripts/check-cli-effects.mjs b/scripts/check-cli-effects.mjs new file mode 100644 index 0000000000..5f37c2f3aa --- /dev/null +++ b/scripts/check-cli-effects.mjs @@ -0,0 +1,39 @@ +import ts from 'typescript-legacy'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { cliDispatchInventory } from './cli-dispatch-inventory.mjs'; +const root = fileURLToPath(new URL('..', import.meta.url)); +const source = readFileSync( + new URL('../packages/core/src/bots/cli-effects.ts', import.meta.url), + 'utf8', +); +const declared = new Set(); +const ast = ts.createSourceFile('cli-effects.ts', source, ts.ScriptTarget.Latest, true); +function visit(node) { + if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'CLI_EFFECTS') { + const value = + node.initializer && ts.isSatisfiesExpression(node.initializer) + ? node.initializer.expression + : node.initializer; + if (!value || !ts.isObjectLiteralExpression(value)) + throw new Error('CLI_EFFECTS must remain an explicit declaration table'); + for (const entry of value.properties) { + if ( + !ts.isPropertyAssignment(entry) || + !(ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name)) + ) + throw new Error('Unresolved CLI effect declaration'); + declared.add(entry.name.text); + } + } + ts.forEachChild(node, visit); +} +visit(ast); +const missing = cliDispatchInventory(root).filter((name) => !declared.has(name)); +if (missing.length) { + process.stderr.write('CLI effects missing: ' + missing.join(', ') + '\n'); + process.exitCode = 1; +} else + process.stdout.write( + 'CLI effects cover ' + declared.size + ' registered commands and dispatch branches.\n', + ); diff --git a/scripts/check-tool-effects.mjs b/scripts/check-tool-effects.mjs index 1c9f494bd1..21a445404c 100644 --- a/scripts/check-tool-effects.mjs +++ b/scripts/check-tool-effects.mjs @@ -1,3 +1,4 @@ +import './check-cli-effects.mjs'; import { readdirSync, readFileSync } from 'node:fs'; import { join, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; diff --git a/scripts/cli-dispatch-inventory.mjs b/scripts/cli-dispatch-inventory.mjs new file mode 100644 index 0000000000..c9efde5afc --- /dev/null +++ b/scripts/cli-dispatch-inventory.mjs @@ -0,0 +1,59 @@ +import ts from 'typescript-legacy'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +export function cliDispatchInventory(root) { + const required = new Set([ + 'help', + 'bots', + 'capabilities', + 'voice-local-kit', + 'ssh-tunnel', + 'create', + ]); + const dir = join(root, 'packages/core/src/bots'); + for (const file of readdirSync(dir).filter( + (x) => (x.startsWith('cli-') && x.endsWith('.ts')) || x === 'bot-create-cli.ts', + )) { + const sf = ts.createSourceFile( + file, + readFileSync(join(dir, file), 'utf8'), + ts.ScriptTarget.Latest, + true, + ); + function walk(n) { + if ( + ts.isVariableDeclaration(n) && + ts.isIdentifier(n.name) && + n.name.text.endsWith('COMMANDS') && + !n.name.text.endsWith('SUBCOMMANDS') + ) { + function visit(a) { + if (ts.isArrayLiteralExpression(a)) { + for (const e of a.elements) { + if (ts.isStringLiteral(e)) required.add(e.text); + else if (ts.isObjectLiteralExpression(e)) + for (const p of e.properties) + if ( + ts.isPropertyAssignment(p) && + p.name.getText(sf) === 'command' && + ts.isStringLiteral(p.initializer) + ) + required.add(p.initializer.text); + } + } else ts.forEachChild(a, visit); + } + if (n.initializer) visit(n.initializer); + } + if ( + file === 'bot-create-cli.ts' && + ts.isBinaryExpression(n) && + n.left.getText(sf) === 'command' && + ts.isStringLiteral(n.right) + ) + required.add(n.right.text); + ts.forEachChild(n, walk); + } + walk(sf); + } + return [...required].sort(); +} diff --git a/scripts/perf-budgets/cli-effects.json b/scripts/perf-budgets/cli-effects.json new file mode 100644 index 0000000000..250a0ad6e9 --- /dev/null +++ b/scripts/perf-budgets/cli-effects.json @@ -0,0 +1,6 @@ +{ + "maxColdCliMs": 2000, + "maxAddedMedianCliMs": 250, + "maxRssKiB": 262144, + "maxClassificationP99Ms": 5 +} diff --git a/scripts/perf-budgets/genui-opening.json b/scripts/perf-budgets/genui-opening.json index c455faa3e2..375c170b31 100644 --- a/scripts/perf-budgets/genui-opening.json +++ b/scripts/perf-budgets/genui-opening.json @@ -1,6 +1,6 @@ { "name": "genui-opening", - "fixture": "Three sequential plain/rich pairs, fresh browser per target, one canonical message per DM, bundled nine-scene HTML document; no model", + "fixture": "Three sequential plain/rich pairs, fresh browser per target, one canonical content message plus its exact one-time approval records per DM, bundled nine-scene HTML document; no model", "always": [ { "metric": "plain.count", diff --git a/scripts/perf-budgets/tob-cli.json b/scripts/perf-budgets/tob-cli.json new file mode 100644 index 0000000000..8243c0dc7c --- /dev/null +++ b/scripts/perf-budgets/tob-cli.json @@ -0,0 +1,8 @@ +{ + "maxDirectCliMs": 2000, + "maxAddedNativeJourneyMs": 5000, + "maxJourneyMs": 7000, + "maxStatusCliMs": 2000, + "maxCaptureMs": 12000, + "rounds": 3 +} diff --git a/scripts/perf-cli-effects.mjs b/scripts/perf-cli-effects.mjs new file mode 100644 index 0000000000..aa3c0d5020 --- /dev/null +++ b/scripts/perf-cli-effects.mjs @@ -0,0 +1,282 @@ +import { execFile } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const hash = (value) => createHash('sha256').update(value).digest('hex'); +const argument = (name) => { + const index = process.argv.indexOf(name); + return index < 0 ? undefined : process.argv[index + 1]; +}; +const worker = process.argv.includes('--worker'); +if (!worker && !/^[a-f0-9]{40}$/.test(argument('--source-sha') ?? '')) + throw new Error('Pass the frozen 40-character --source-sha.'); +const instancePath = argument('--instance'); +const fixturePath = argument('--fixture'); +if (!instancePath || !fixturePath) + throw new Error('Pass --instance and --fixture private JSON paths.'); +const fixtureBytes = readFileSync(fixturePath); +const fixture = JSON.parse(fixtureBytes); +if ( + !fixture || + !['bot', 'from', 'to'].every((key) => typeof fixture[key] === 'string' && fixture[key].trim()) +) + throw new Error('Fixture requires bot, from and to.'); +const budget = JSON.parse( + readFileSync(argument('--budget') ?? new URL('./perf-budgets/cli-effects.json', import.meta.url)), +); +const quantile = (values, q) => [...values].sort((a, b) => a - b)[Math.ceil(values.length * q) - 1]; +const expectedSelection = (choice) => + choice === 'off' ? null : choice === 'inherit' ? '@global' : choice; +const validTiming = (row) => + row.correct === true && + row.code === 0 && + row.processCode === 0 && + Number.isFinite(row.wallMs) && + row.wallMs >= 0 && + Number.isFinite(row.maxRssKiB) && + row.maxRssKiB > 0; + +if (worker) { + const started = performance.now(); + const operation = argument('--operation'); + if (operation === 'classification') { + const { toolEffects } = await import( + new URL('../packages/core/dist/index.mjs', import.meta.url) + ); + const cases = [ + { name: 'read', argv: ['channels'], expected: { changes: 'none' } }, + { + name: 'management', + argv: ['grant-write-set', fixture.bot, '--grant', 'fixture', '--enabled', '--confirm'], + expected: { authority: 'management' }, + }, + { + name: 'external-output', + argv: ['marketplace-upload', fixture.bot, '--out=fixture.json'], + expected: { changes: 'irreversible', reach: 'external' }, + }, + { + name: 'max-argv-read', + argv: ['channels', ...Array(255).fill('--compact')], + expected: { changes: 'none' }, + }, + ]; + const rows = cases.map((test) => { + const samples = []; + let effects; + for (let i = 0; i < 200; i++) { + const at = performance.now(); + effects = toolEffects('deepseekbot ' + test.argv[0], { patch: { argv: test.argv } }); + samples.push(performance.now() - at); + } + return { + name: test.name, + argc: test.argv.length, + correct: + !!effects && + Object.entries(test.expected).every(([key, value]) => effects[key] === value), + samplesMs: samples, + p50Ms: quantile(samples, 0.5), + p99Ms: quantile(samples, 0.99), + effects, + }; + }); + process.stdout.write( + JSON.stringify({ code: 0, rows, maxRssKiB: process.resourceUsage().maxRSS }), + ); + } else { + const instance = JSON.parse(readFileSync(instancePath)); + const url = new URL(instance.url); + const token = url.searchParams.get('token'); + if (!token) throw new Error('Private instance has no login token.'); + const { runBotCreateCli } = await import( + new URL('../packages/core/cli/index.mjs', import.meta.url) + ); + const commands = { + list: ['list', '--compact'], + set: ['approval-template-set', fixture.bot, fixture.to, '--compact'], + read: ['approval-templates', '--bot', fixture.bot, '--compact'], + restore: ['approval-template-set', fixture.bot, fixture.from, '--compact'], + }; + if (!Object.hasOwn(commands, operation)) throw new Error('Unknown operation.'); + let stdout = ''; + const code = await runBotCreateCli(commands[operation], { + env: { ...process.env, DEEPSEEKBOT_HOST: url.origin, DEEPSEEKBOT_HOST_TOKEN: token }, + stdout: (text) => (stdout += text), + stderr: () => {}, + readStdin: async () => '', + }); + const response = JSON.parse(stdout); + const selected = operation === 'read' ? response.selected : response.bot?.approvalTemplate; + const correct = + code === 0 && + (operation === 'list' + ? response.bots.some((bot) => (bot.id ?? bot.slug) === fixture.bot) + : (selected ?? null) === + expectedSelection(operation === 'restore' ? fixture.from : fixture.to)); + process.stdout.write( + JSON.stringify({ + code, + correct, + operation, + selected, + elapsedMs: performance.now() - started, + maxRssKiB: process.resourceUsage().maxRSS, + cpu: process.cpuUsage(), + error: response.error?.code, + }), + ); + } +} else { + const output = argument('--output'); + if (!output) throw new Error('Pass --output.'); + const run = (operation) => + new Promise((resolve) => { + const at = performance.now(); + execFile( + process.execPath, + [ + fileURLToPath(import.meta.url), + '--worker', + '--instance', + instancePath, + '--fixture', + fixturePath, + '--operation', + operation, + ], + { + cwd: root, + env: process.env, + shell: false, + windowsHide: true, + timeout: 15000, + maxBuffer: 1000000, + }, + (error, stdout) => { + try { + resolve({ + ...JSON.parse(stdout), + wallMs: performance.now() - at, + processCode: error?.code ?? 0, + }); + } catch { + resolve({ + operation, + processCode: error?.code ?? 1, + error: 'worker-output-unavailable', + }); + } + }, + ); + }); + const samples = [], + restorations = [], + failures = []; + let baseline; + const baselinePath = argument('--baseline'); + if (baselinePath) { + try { + baseline = JSON.parse(readFileSync(baselinePath)); + if (baseline?.fixtureSha256 !== hash(fixtureBytes) || baseline?.node !== process.version) + failures.push('baseline:unmatched-fixture-or-node'); + if (!Array.isArray(baseline?.budget?.failures) || baseline.budget.failures.length) + failures.push('baseline:failed'); + for (const operation of ['list', 'set', 'read']) { + const rows = Array.isArray(baseline?.samples) + ? baseline.samples.filter((row) => row?.operation === operation) + : []; + if (rows.length !== 3 || !rows.every(validTiming)) + failures.push('baseline:invalid-samples:' + operation); + } + } catch { + failures.push('baseline:unavailable'); + } + } + if (!failures.length) { + for (let round = 0; round < 3; round++) { + try { + for (const operation of ['list', 'set', 'read']) { + const row = { round, ...(await run(operation)) }; + samples.push(row); + if (!validTiming(row)) { + failures.push(operation + ':incorrect'); + break; + } + } + } catch { + failures.push('worker-failed'); + } finally { + let restore; + try { + restore = await run('restore'); + } catch { + restore = { operation: 'restore', correct: false, error: 'worker-failed' }; + } + restorations.push({ round, ...restore }); + if (!restore.correct || restore.processCode !== 0) failures.push('fixture-restore-failed'); + } + if (failures.length) break; + } + } + const classification = + !failures.length && process.argv.includes('--classification') + ? await run('classification') + : undefined; + const result = { + source: argument('--source-sha'), + node: process.version, + fixtureSha256: hash(fixtureBytes), + artifacts: ['packages/core/cli/index.mjs', 'packages/core/dist/index.mjs'].map((file) => ({ + file, + sha256: hash(readFileSync(new URL('../' + file, import.meta.url))), + })), + samples, + restorations, + classification, + }; + for (const row of samples) { + if (!row.correct || row.processCode !== 0) failures.push(row.operation + ':incorrect'); + if (row.wallMs > budget.maxColdCliMs) failures.push(row.operation + ':latency'); + if (row.maxRssKiB > budget.maxRssKiB) failures.push(row.operation + ':memory'); + } + if (classification) { + if (classification.maxRssKiB > budget.maxRssKiB) failures.push('classification-memory'); + if ( + classification.processCode !== 0 || + classification.code !== 0 || + classification.rows?.length !== 4 + ) + failures.push('classification-incomplete'); + for (const row of classification.rows ?? []) { + if (!row.correct) failures.push(row.name + ':classification-incorrect'); + if (row.p99Ms > budget.maxClassificationP99Ms) + failures.push(row.name + ':classification-latency'); + } + } + if (baseline && !failures.some((failure) => failure.startsWith('baseline:'))) { + for (const operation of ['list', 'set', 'read']) { + const beforeRows = baseline.samples.filter((row) => row.operation === operation); + const afterRows = samples.filter((row) => row.operation === operation); + if (afterRows.length !== 3 || !afterRows.every(validTiming)) { + failures.push(operation + ':comparison-incomplete'); + continue; + } + const before = quantile( + beforeRows.map((row) => row.wallMs), + 0.5, + ); + const after = quantile( + afterRows.map((row) => row.wallMs), + 0.5, + ); + if (after > before + budget.maxAddedMedianCliMs) failures.push(operation + ':added-latency'); + } + } + result.budget = { ...budget, failures }; + writeFileSync(output, JSON.stringify(result, null, 2)); + process.stdout.write(JSON.stringify({ output, failures, samples: samples.length })); + if (failures.length) process.exitCode = 1; +} diff --git a/scripts/perf-genui-opening.mjs b/scripts/perf-genui-opening.mjs index 1f15e8fa41..e56cdf2b15 100644 --- a/scripts/perf-genui-opening.mjs +++ b/scripts/perf-genui-opening.mjs @@ -1,3 +1,4 @@ +import { createPrivateHostRedactor } from './private-host-redaction.mjs'; import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { createHash, randomUUID } from 'node:crypto'; @@ -18,6 +19,7 @@ import { traceGenuiOpening, } from './perf-genui-opening-observer.mjs'; import { openTimelineConversation } from './perf-timeline-navigation.mjs'; +import { runTimelineSeedTool } from './perf-timeline-seed.mjs'; import { dismissGenuiOpeningOverlays as dismiss } from './perf-genui-opening-overlays.mjs'; import { assertNativeViewportUnchanged, @@ -57,14 +59,7 @@ const git = (...args) => execFileSync('git', args, { cwd: root, maxBuffer: 20e6 const budgetPath = resolve(values.budget); const budget = readBudget(budgetPath); const runId = randomUUID(); -const privateUrl = new URL(instance.url); -const redact = (error) => { - let text = String(error).replaceAll(instance.url, '[private Host URL]'); - for (const value of [privateUrl.searchParams.get('token'), privateUrl.hash.slice(1)]) { - if (value) text = text.replaceAll(value, '[redacted]'); - } - return text; -}; +const redact = createPrivateHostRedactor(instance.url); const manifest = { runId, startedAt: new Date().toISOString(), @@ -342,9 +337,13 @@ try { assert.deepEqual(target.previewDiagnostics, []); } const before = performance.now(); - const sent = await call('botToolRun', { + const sent = await runTimelineSeedTool({ + rpc: call, slug: bot.slug, - tool: 'bot_send_message', + onState: (state) => { + target.approval = state; + save(); + }, args: { channel_id: bot.channelId, body: 'Synthetic project comparison. Review the projects and their current metrics.', diff --git a/scripts/perf-idle-timeline.mjs b/scripts/perf-idle-timeline.mjs index 4190ee69f9..7476332cb1 100644 --- a/scripts/perf-idle-timeline.mjs +++ b/scripts/perf-idle-timeline.mjs @@ -1,3 +1,4 @@ +import { createPrivateHostRedactor } from './private-host-redaction.mjs'; import assert from 'node:assert/strict'; import { createRequire } from 'node:module'; import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; @@ -6,6 +7,7 @@ import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import { checkBudget, readBudget } from './perf-budget.mjs'; import { openTimelineConversation } from './perf-timeline-navigation.mjs'; +import { seedTimeline } from './perf-timeline-seed.mjs'; import { createHeapObservation } from './perf-heap-observation.mjs'; import { installTimelineActivity, timelineActivityPlan } from './perf-timeline-activity.mjs'; import { @@ -101,6 +103,7 @@ const pkg = readdirSync(store).find((name) => name.startsWith('puppeteer@')); const puppeteer = createRequire(resolve(store, pkg, 'node_modules/'))('puppeteer'); assert.ok(process.env.BH_E2E_INSTANCE, 'Set BH_E2E_INSTANCE to the task-owned instance.json'); const instance = JSON.parse(readFileSync(process.env.BH_E2E_INSTANCE, 'utf8')); +const redact = createPrivateHostRedactor(instance.url); const out = resolve(options.out); mkdirSync(out, { recursive: true }); const seconds = Number(options.seconds); @@ -186,28 +189,53 @@ await localeSession.send('Emulation.setUserAgentOverride', { acceptLanguage: 'en-US,en', }); const errors = []; -page.on('pageerror', (error) => errors.push(error.message)); +page.on('pageerror', (error) => errors.push(redact(error.message))); +const setup = { phase: 'browser-ready', rpcCalls: 0, pending: [], recent: [] }; +const saveSetup = () => + writeFileSync(resolve(out, options.label + '.setup.json'), JSON.stringify(setup, null, 2)); +const setupPhase = (phase) => { + setup.phase = phase; + saveSetup(); +}; async function rpc(method, args = {}) { - return page.evaluate( - async (method, args) => { - const response = await fetch(`/api/botharness/${method}`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - type: 'client-request', - rpcId: crypto.randomUUID(), - method: `botharness/${method}`, - payload: { args }, - }), - }); - const envelope = await response.json(); - if (!envelope.result?.ok) throw Error(`${method}: ${JSON.stringify(envelope.result)}`); - return envelope.result.value; - }, - method, - args, - ); + const request = { ordinal: ++setup.rpcCalls, method, startedAt: new Date().toISOString() }; + setup.pending.push(request); + saveSetup(); + try { + const result = await page.evaluate( + async (method, args) => { + const response = await fetch(`/api/botharness/${method}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: crypto.randomUUID(), + method: `botharness/${method}`, + payload: { args }, + }), + }); + const envelope = await response.json(); + if (!envelope.result?.ok) throw Error(`${method}: ${JSON.stringify(envelope.result)}`); + return envelope.result.value; + }, + method, + args, + ); + setup.recent.push({ ...request, outcome: 'completed' }); + return result; + } catch (error) { + setup.recent.push({ + ...request, + outcome: 'failed', + error: error instanceof Error ? error.name : 'unknown', + }); + throw error; + } finally { + setup.pending = setup.pending.filter((pending) => pending.ordinal !== request.ordinal); + setup.recent = setup.recent.slice(-32); + saveSetup(); + } } async function dismissOverlays() { @@ -227,55 +255,6 @@ async function dismissOverlays() { } } -async function seed(count) { - const bots = []; - for (const name of ['Perf Ada', 'Perf Lin', 'Perf Kai']) - bots.push((await rpc('create', { displayName: `${name} ${Date.now() % 100000}` })).bot); - const group = ( - await rpc('channelCreate', { - name: `Idle perf ${count}`, - members: bots.map((bot) => bot.slug), - }) - ).channel; - for (const bot of bots) - await rpc('channelGroupWakeSet', { - channelId: group.id, - botSlug: bot.slug, - mode: 'silent', - count: 5, - intervalSeconds: 30, - }); - const ids = []; - let source; - for (let index = 0; index < count; index++) { - if (index % 5 === 0) { - const sent = await rpc('channelSend', { - channelId: group.id, - body: `Human check-in ${index + 1}: how is it going?`, - }); - source = sent.message?.id ?? sent.messageId ?? sent.id; - assert.ok(source, JSON.stringify(sent)); - ids.push(source); - continue; - } - const bot = bots[index % bots.length]; - const run = await rpc('botToolRun', { - slug: bot.slug, - tool: 'bot_send_message', - args: { - channel_id: group.id, - body: bodies[index % bodies.length](index + 1), - reply_to: source, - }, - }); - assert.ok(run.result?.messageId, JSON.stringify(run)); - ids.push(run.result.messageId); - if ((index + 1) % 100 === 0) console.error(`seeded ${index + 1}/${count}`); - } - await rpc('channelMarkRead', { channelId: group.id, messageId: ids.at(-1) }); - return { channelId: group.id, messageIds: ids, bots: bots.map((bot) => bot.slug) }; -} - async function startProfile(cdp) { await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 200 }); @@ -304,13 +283,30 @@ const metric = (list, name) => list.metrics.find((item) => item.name === name)?. try { const startupNativeViewport = options.headed ? await calibrateNativeViewport(page) : undefined; if (!options.headed) await page.setViewport({ width: 1440, height: 900 }); + setupPhase('navigation'); await page.goto(instance.url, { waitUntil: 'networkidle2' }); + setupPhase('dismiss-overlays'); await dismissOverlays(); + setupPhase('fixture'); const fixture = options.fixture ? JSON.parse(readFileSync(options.fixture, 'utf8')) - : await seed(Number(options.messages)); + : await seedTimeline({ + rpc, + count: Number(options.messages), + bodies, + onMessage: (message) => { + setup.message = message; + saveSetup(); + }, + onToolState: (tool) => { + setup.tool = tool; + saveSetup(); + }, + onProgress: (seeded, count) => console.error('seeded ' + seeded + '/' + count), + }); if (!options.fixture) writeFileSync(resolve(out, 'fixture.json'), JSON.stringify(fixture)); + setupPhase('fixture-completed'); await page.reload({ waitUntil: 'networkidle2' }); await dismissOverlays(); @@ -499,10 +495,26 @@ try { if (!check.pass) process.exitCode = 1; } } catch (error) { + writeFileSync( + resolve(out, options.label + '.failure.json'), + JSON.stringify( + { + setup, + seedFailure: error?.timelineSeed, + pageErrors: errors.slice(-20).map((message) => redact(message).slice(0, 500)), + error: + error instanceof Error + ? { name: error.name, message: redact(error.message).slice(0, 1000) } + : { name: 'unknown' }, + }, + null, + 2, + ), + ); const shot = resolve(out, `${options.label}.failure.png`); await page.screenshot({ path: shot }).catch(() => {}); console.error(`perf run failed; page screenshot: ${shot}`); - throw error; + throw new Error(redact(error instanceof Error ? (error.stack ?? error.message) : error)); } finally { await browser.close(); } diff --git a/scripts/perf-timeline-seed.mjs b/scripts/perf-timeline-seed.mjs new file mode 100644 index 0000000000..b57d4dd71f --- /dev/null +++ b/scripts/perf-timeline-seed.mjs @@ -0,0 +1,240 @@ +import assert from 'node:assert/strict'; +import { isDeepStrictEqual } from 'node:util'; + +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const directSession = /^direct-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u; + +async function bounded(promise, timeoutMs, code) { + let timer; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(code)), timeoutMs); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +function matchesRequest(message, slug, args) { + const request = message.toolApprovalRequest; + if ( + message.author.kind !== 'bot' || + message.author.slug !== slug || + request.role !== 'orchestrator' || + !directSession.test(request.sessionId) || + request.callId !== request.sessionId || + request.toolName !== 'bot_send_message' + ) + return false; + try { + return isDeepStrictEqual(JSON.parse(request.input), args); + } catch { + return false; + } +} + +export async function runTimelineSeedTool({ + rpc, + slug, + args, + timeoutMs = 30_000, + pollMs = 25, + onState = () => undefined, +}) { + let closed = false; + let channelId; + let previous = new Set(); + let settled; + let running; + let verified; + const state = { botSlug: slug, operation: 'not-started' }; + const publish = () => onState({ ...state }); + const remember = (message) => { + verified = message; + Object.assign(state, { + channelId, + messageId: message.id, + sessionId: message.toolApprovalRequest.sessionId, + callId: message.toolApprovalRequest.callId, + }); + publish(); + }; + const pendingFrom = (messages) => { + const decided = new Set( + messages.flatMap((message) => + message.toolApprovalDecision ? [message.toolApprovalDecision.requestMessageId] : [], + ), + ); + return messages.filter( + (message) => + message.toolApprovalRequest && !previous.has(message.id) && !decided.has(message.id), + ); + }; + const execute = async () => { + channelId = (await rpc('channelDm', { slug })).channel.id; + state.channelId = channelId; + previous = new Set( + (await rpc('channelMessages', { channelId })).messages.map((message) => message.id), + ); + if (closed) return; + state.operation = 'pending'; + publish(); + running = rpc('botToolRun', { slug, tool: 'bot_send_message', args }).then( + (value) => { + settled = { ok: true, value }; + state.operation = 'completed'; + }, + (error) => { + settled = { ok: false, error }; + state.operation = 'failed'; + }, + ); + const approved = new Set(); + while (!closed) { + await Promise.race([running, pause(pollMs)]); + if (settled) { + publish(); + if (!settled.ok) throw settled.error; + return settled.value; + } + const messages = (await rpc('channelMessages', { channelId })).messages; + if (closed) break; + const pending = pendingFrom(messages).filter((message) => !approved.has(message.id)); + assert.ok(pending.length <= 1, 'timeline-seed-unexpected-approval-count'); + for (const message of pending) { + assert.ok( + matchesRequest(message, slug, args) && approved.size === 0, + 'timeline-seed-unrelated-approval', + ); + remember(message); + assert.equal( + (await rpc('toolApprovalStatus', { channelId, messageId: message.id })).status, + 'pending', + 'timeline-seed-approval-not-pending', + ); + if (closed) break; + const decision = await rpc('toolApprovalDecide', { + channelId, + messageId: message.id, + outcome: 'allowed-once', + }); + assert.equal(decision.accepted, true, 'timeline-seed-approval-refused'); + approved.add(message.id); + state.decision = 'allowed-once'; + publish(); + } + } + }; + try { + return await bounded(execute(), timeoutMs, 'timeline-seed-tool-timeout'); + } catch (error) { + closed = true; + state.cleanup = 'not-required'; + if (running && !settled) { + let cleanupClosed = false; + try { + await bounded( + (async () => { + if (!verified) { + const matching = pendingFrom( + (await rpc('channelMessages', { channelId })).messages, + ).filter((message) => matchesRequest(message, slug, args)); + if (matching.length === 1) remember(matching[0]); + } + if (verified && !cleanupClosed) { + const status = ( + await rpc('toolApprovalStatus', { channelId, messageId: verified.id }) + ).status; + if (status === 'pending' && !cleanupClosed) { + const result = await rpc('toolApprovalDecide', { + channelId, + messageId: verified.id, + outcome: 'rejected', + }); + state.cleanup = result.accepted ? 'rejected' : 'rejection-refused'; + } else state.cleanup = status; + } else state.cleanup = 'matching-card-unavailable'; + })(), + 2_000, + 'timeline-seed-cleanup-timeout', + ); + } catch (cleanupError) { + state.cleanup = cleanupError instanceof Error ? cleanupError.message : 'cleanup-failed'; + } finally { + cleanupClosed = true; + } + try { + await bounded(running, 500, 'timeline-seed-operation-unsettled'); + } catch {} + if (!settled) state.operation = 'pending-host-cleanup-required'; + } + publish(); + const failure = error instanceof Error ? error : new Error('timeline-seed-failed'); + failure.timelineSeed = { ...state }; + throw failure; + } finally { + closed = true; + } +} + +export async function seedTimeline({ + rpc, + count, + bodies, + onMessage = () => undefined, + onProgress = () => undefined, + onToolState = () => undefined, +}) { + const bots = []; + for (const name of ['Perf Ada', 'Perf Lin', 'Perf Kai']) + bots.push((await rpc('create', { displayName: name + ' ' + (Date.now() % 100000) })).bot); + const group = ( + await rpc('channelCreate', { name: 'Idle perf ' + count, members: bots.map((bot) => bot.slug) }) + ).channel; + for (const bot of bots) + await rpc('channelGroupWakeSet', { + channelId: group.id, + botSlug: bot.slug, + mode: 'silent', + count: 5, + intervalSeconds: 30, + }); + const ids = []; + let source; + for (let index = 0; index < count; index++) { + onMessage({ + ordinal: index + 1, + count, + method: index % 5 === 0 ? 'channelSend' : 'botToolRun', + }); + if (index % 5 === 0) { + const sent = await rpc('channelSend', { + channelId: group.id, + body: 'Human check-in ' + (index + 1) + ': how is it going?', + }); + source = sent.message?.id ?? sent.messageId ?? sent.id; + assert.ok(source, 'timeline-seed-human-message-missing'); + ids.push(source); + continue; + } + const bot = bots[index % bots.length]; + const run = await runTimelineSeedTool({ + rpc, + slug: bot.slug, + onState: onToolState, + args: { + channel_id: group.id, + body: bodies[index % bodies.length](index + 1), + reply_to: source, + }, + }); + assert.ok(run.result?.messageId, 'timeline-seed-bot-message-missing'); + ids.push(run.result.messageId); + if ((index + 1) % 100 === 0) onProgress(index + 1, count); + } + await rpc('channelMarkRead', { channelId: group.id, messageId: ids.at(-1) }); + return { channelId: group.id, messageIds: ids, bots: bots.map((bot) => bot.slug) }; +} diff --git a/scripts/perf-tob-cli.mjs b/scripts/perf-tob-cli.mjs new file mode 100644 index 0000000000..8459be9690 --- /dev/null +++ b/scripts/perf-tob-cli.mjs @@ -0,0 +1,217 @@ +import { readBoundedFileSync } from './bounded-file.mjs'; +import { execFile } from 'node:child_process'; +import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import * as zlib from 'node:zlib'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const argument = (name) => process.argv[process.argv.indexOf(name) + 1]; +const source = argument('--source-sha'); +if (!/^[a-f0-9]{40}$/.test(source ?? '')) throw new Error('Pass frozen --source-sha'); +const root = fileURLToPath(new URL('..', import.meta.url)); +const fixtureBytes = readFileSync(argument('--fixture')); +const fixture = JSON.parse(fixtureBytes); +if ( + !Array.isArray(fixture.argv) || + fixture.argv[0] !== 'approval-templates' || + !fixture.argv.every((item) => typeof item === 'string') +) + throw new Error('Use a readonly approval-templates argv fixture'); +const instance = JSON.parse(readFileSync(argument('--instance'))); +const url = new URL(instance.url); +const token = url.searchParams.get('token'); +if (!token) throw new Error('Private authenticated instance required'); +const budget = JSON.parse(readFileSync(new URL('./perf-budgets/tob-cli.json', import.meta.url))); +const rounds = process.argv.includes('--rounds') ? Number(argument('--rounds')) : budget.rounds; +if (!Number.isInteger(rounds) || rounds < 1 || rounds > budget.rounds) + throw new Error('Round count must stay within the recorded cohort cap'); +const hash = (value) => createHash('sha256').update(value).digest('hex'); +const run = (argv, stdin = '') => + new Promise((resolve, reject) => { + const started = performance.now(); + const child = execFile( + process.execPath, + [ + fileURLToPath(new URL('../packages/deepseekbot/dist/deepseekbot.mjs', import.meta.url)), + ...argv, + ], + { + cwd: root, + env: { ...process.env, DEEPSEEKBOT_HOST: url.origin, DEEPSEEKBOT_HOST_TOKEN: token }, + shell: false, + windowsHide: true, + timeout: 5000, + maxBuffer: 1024 * 1024, + }, + (error, stdout) => { + try { + resolve({ + code: error?.code ?? 0, + ms: performance.now() - started, + value: JSON.parse(stdout), + }); + } catch { + reject(new Error('CLI measurement produced no JSON result')); + } + }, + ); + child.stdin.end(stdin); + }); +const nativeAudit = async () => { + if (typeof zlib.zstdDecompressSync !== 'function') + throw Object.assign(new Error('Native audit decoder unavailable'), { + code: 'unsupported-audit-decoder', + }); + const home = await run(['tob-home']); + const slug = home.value.botSlug; + if (home.code !== 0 || typeof slug !== 'string') throw new Error('Owned Tob unavailable'); + const trace = await run(['bot-trace', slug, '--turns', '1']); + const id = trace.value.sessionId; + if (typeof id !== 'string') return { sessionId: null, counts: {} }; + const directory = join(instance.home, 'sessions'); + const matches = readdirSync(directory) + .map((name) => join(directory, name, id, 'session.v4.jsonl.zstd')) + .filter(existsSync); + if (matches.length !== 1) throw new Error('Native audit identity unavailable'); + const bytes = readBoundedFileSync(matches[0], 16 * 1024 * 1024); + const counts = {}; + let offset = 0, + outputBytes = 0, + frames = 0; + while (offset < bytes.length) { + const decoded = zlib.zstdDecompressSync(bytes.subarray(offset), { + info: true, + maxOutputLength: 16 * 1024 * 1024, + }); + const consumed = decoded.engine.bytesWritten; + if (!Number.isSafeInteger(consumed) || consumed <= 0 || consumed > bytes.length - offset) + throw new Error('Native audit frame boundary unavailable'); + offset += consumed; + outputBytes += decoded.buffer.length; + if (++frames > 100000 || outputBytes > 64 * 1024 * 1024) + throw new Error('Native audit exceeds decoded capture bound'); + for (const line of decoded.buffer.toString('utf8').split('\n').filter(Boolean)) { + const event = JSON.parse(line); + counts[event.type] = (counts[event.type] ?? 0) + 1; + } + } + return { + sessionId: id, + counts, + frames, + compressedBytes: bytes.length, + outputBytes, + sha256: hash(bytes), + }; +}; +const samples = [], + failures = []; +const captureAudit = async (phase) => { + try { + return { valid: true, ...(await nativeAudit()) }; + } catch (error) { + const code = + error?.code === 'unsupported-audit-decoder' ? error.code : 'native-audit-unavailable'; + failures.push('native-audit-' + phase + '-failed:' + code); + return { valid: false, error: code }; + } +}; +const auditBefore = await captureAudit('before'); +for (let round = 0; auditBefore.valid && round < rounds; round++) { + let id; + try { + const direct = await run(fixture.argv); + const began = performance.now(); + const start = await run( + ['tob-cli', 'start', '--args-stdin'], + JSON.stringify({ argv: fixture.argv, stdin: '' }), + ); + id = start.value.id; + if (start.code !== 0 || !id) throw new Error('Typed CLI start refused'); + let status; + const polls = []; + while (performance.now() - began < budget.maxCaptureMs) { + status = await run(['tob-cli', 'status', id]); + polls.push(status.ms); + if (status.code !== 0 || status.value.state !== 'running') break; + } + const journeyMs = performance.now() - began; + const result = status?.value.result; + const value = result?.exitCode === 0 ? JSON.parse(result.stdout) : undefined; + const correct = + direct.code === 0 && + status?.value.state === 'completed' && + hash(JSON.stringify(value)) === hash(JSON.stringify(direct.value)); + const row = { + round, + correct, + directMs: direct.ms, + startMs: start.ms, + journeyMs, + addedMs: journeyMs - direct.ms, + statusMs: polls, + polls: polls.length, + resultCode: result?.exitCode, + }; + samples.push(row); + if (!correct) failures.push('command-result-mismatch'); + if (row.directMs > budget.maxDirectCliMs) failures.push('direct-latency'); + if (row.journeyMs > budget.maxJourneyMs || row.addedMs > budget.maxAddedNativeJourneyMs) + failures.push('native-journey-latency'); + if (polls.some((ms) => ms > budget.maxStatusCliMs)) failures.push('status-latency'); + } catch { + samples.push({ round, correct: false, error: 'journey-failed' }); + failures.push('journey-failed'); + } finally { + if (id) + try { + const cancelled = await run(['tob-cli', 'cancel', id]); + if (cancelled.code !== 0) failures.push('cancel-request-failed'); + } catch { + failures.push('cancel-request-failed'); + } + } + if (failures.length) break; +} +const auditAfter = auditBefore.valid + ? await captureAudit('after') + : { valid: false, error: 'native-audit-not-started' }; +if (auditBefore.valid && auditAfter.valid) { + if (auditBefore.sessionId && auditBefore.sessionId !== auditAfter.sessionId) + failures.push('native-session-changed'); + if ( + (auditAfter.counts['turn/start'] ?? 0) - (auditBefore.counts['turn/start'] ?? 0) !== + samples.filter((sample) => sample.correct).length + ) + failures.push('native-turn-count'); + for (const kind of [ + 'step/start', + 'request/header', + 'request/context', + 'assistant/message', + 'assistant/attempt', + ]) { + if ((auditAfter.counts[kind] ?? 0) !== (auditBefore.counts[kind] ?? 0)) + failures.push('unexpected-model-step:' + kind); + } +} +const result = { + source, + node: process.version, + fixtureSha256: hash(fixtureBytes), + capturedAt: new Date().toISOString(), + artifacts: [ + 'packages/core/dist/index.mjs', + 'packages/core/cli/index.mjs', + 'packages/deepseekbot/dist/deepseekbot.mjs', + ].map((file) => ({ file, sha256: hash(readFileSync(new URL('../' + file, import.meta.url))) })), + samples, + protocol: { rounds, stopOnFirstFailure: true }, + nativeAudit: { before: auditBefore, after: auditAfter }, + budget, + failures, +}; +writeFileSync(argument('--output'), JSON.stringify(result, null, 2)); +process.stdout.write(JSON.stringify({ samples: samples.length, failures })); +if (failures.length) process.exitCode = 1; diff --git a/scripts/private-host-redaction.mjs b/scripts/private-host-redaction.mjs new file mode 100644 index 0000000000..6fb8729845 --- /dev/null +++ b/scripts/private-host-redaction.mjs @@ -0,0 +1,9 @@ +export function createPrivateHostRedactor(url) { + const parsed = new URL(url); + const secrets = [parsed.searchParams.get('token'), parsed.hash.slice(1)].filter(Boolean); + return (value) => { + let text = String(value).replaceAll(url, '[private Host URL]'); + for (const secret of secrets) text = text.replaceAll(secret, '[redacted]'); + return text; + }; +} diff --git a/scripts/test/bounded-file.test.mjs b/scripts/test/bounded-file.test.mjs new file mode 100644 index 0000000000..93f181a8c8 --- /dev/null +++ b/scripts/test/bounded-file.test.mjs @@ -0,0 +1,62 @@ +import nativeFs, { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { syncBuiltinESMExports } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, expect, it, vi } from 'vitest'; +import { readBoundedFileSync } from '../bounded-file.mjs'; +const homes = []; +afterEach(() => { + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); +}); +function fixture(bytes) { + const home = mkdtempSync(join(tmpdir(), 'bh-bounded-capture-')); + homes.push(home); + const filename = join(home, 'capture'); + writeFileSync(filename, bytes); + return filename; +} +it('preserves bytes at the capture limit', () => { + const bytes = Buffer.from('bounded'); + expect(readBoundedFileSync(fixture(bytes), bytes.length)).toEqual(bytes); +}); +it('refuses oversized input before reading and closes its descriptor', () => { + const filename = fixture(Buffer.alloc(100)); + const read = vi.spyOn(nativeFs, 'readSync'), + close = vi.spyOn(nativeFs, 'closeSync'); + syncBuiltinESMExports(); + try { + expect(() => readBoundedFileSync(filename, 8)).toThrow('capture bound'); + expect(read).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledTimes(1); + } finally { + read.mockRestore(); + close.mockRestore(); + syncBuiltinESMExports(); + } +}); +it('caps actual I/O at limit plus one when the file grows after descriptor inspection', () => { + const filename = fixture(Buffer.from('ok')); + const actualStat = nativeFs.fstatSync; + let auditedDescriptor; + const stat = vi.spyOn(nativeFs, 'fstatSync').mockImplementation((descriptor) => { + auditedDescriptor = descriptor; + const result = actualStat(descriptor); + appendFileSync(filename, Buffer.alloc(100)); + return result; + }); + const read = vi.spyOn(nativeFs, 'readSync'), + close = vi.spyOn(nativeFs, 'closeSync'); + syncBuiltinESMExports(); + try { + expect(() => readBoundedFileSync(filename, 8)).toThrow('capture bound'); + expect(read.mock.results.reduce((bytes, result) => bytes + Number(result.value), 0)).toBe(9); + expect( + close.mock.calls.filter(([descriptor]) => descriptor === auditedDescriptor), + ).toHaveLength(1); + } finally { + stat.mockRestore(); + read.mockRestore(); + close.mockRestore(); + syncBuiltinESMExports(); + } +}); diff --git a/scripts/test/fixtures/perf-cli-effects-preload.mjs b/scripts/test/fixtures/perf-cli-effects-preload.mjs new file mode 100644 index 0000000000..ea9ebb054e --- /dev/null +++ b/scripts/test/fixtures/perf-cli-effects-preload.mjs @@ -0,0 +1,58 @@ +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { register, syncBuiltinESMExports } from 'node:module'; +import { isMainThread } from 'node:worker_threads'; + +if (isMainThread) { + const read = fs.readFileSync; + fs.readFileSync = (file, ...args) => { + const name = (file instanceof URL ? fileURLToPath(file) : String(file)).replaceAll('\\', '/'); + if (/\/packages\/core\/(?:dist|cli)\/index\.mjs$/u.test(name)) + return Buffer.from('unit-test artifact; no runtime qualification'); + return read(file, ...args); + }; + syncBuiltinESMExports(); + register(import.meta.url); +} + +const cli = ` + import fs from 'node:fs'; + export async function runBotCreateCli(argv, io) { + const fixture = JSON.parse(fs.readFileSync(process.argv[process.argv.indexOf('--fixture') + 1], 'utf8')); + const statePath = process.env.PERF_TEST_STATE; + const callsPath = process.env.PERF_TEST_CALLS; + const calls = fs.existsSync(callsPath) ? JSON.parse(fs.readFileSync(callsPath, 'utf8')) : []; + calls.push(argv); + fs.writeFileSync(callsPath, JSON.stringify(calls)); + const normalize = value => value === 'off' ? null : value === 'inherit' ? '@global' : value; + let selected = fs.existsSync(statePath) ? JSON.parse(fs.readFileSync(statePath, 'utf8')) : normalize(fixture.from); + let value; + let code = 0; + if (argv[0] === 'list') value = { bots: [{ id: fixture.bot }] }; + else if (argv[0] === 'approval-template-set') { + const restore = argv[2] === fixture.from; + if (!restore && process.env.PERF_TEST_FAILURE === 'set-throw') + throw new Error('Unit worker failure'); + if (restore && process.env.PERF_TEST_FAILURE === 'restore-refusal') { + code = 7; + value = { error: { code: 'unit-restore-refused' } }; + } else { + selected = normalize(argv[2]); + fs.writeFileSync(statePath, JSON.stringify(selected)); + value = { bot: { approvalTemplate: selected } }; + } + } else if (argv[0] === 'approval-templates') { + value = selected === null && process.env.PERF_TEST_FAILURE === 'omitted-off' + ? {} : { selected }; + } else throw new Error('Unexpected fixture command'); + io.stdout(JSON.stringify(value)); + return code; + } +`; + +export async function resolve(specifier, context, next) { + const cliUrl = new URL('../../../packages/core/cli/index.mjs', import.meta.url).href; + if (specifier === cliUrl) + return { url: 'data:text/javascript,' + encodeURIComponent(cli), shortCircuit: true }; + return next(specifier, context); +} diff --git a/scripts/test/fixtures/perf-tob-cli-refusal-preload.mjs b/scripts/test/fixtures/perf-tob-cli-refusal-preload.mjs new file mode 100644 index 0000000000..5cb03c23d0 --- /dev/null +++ b/scripts/test/fixtures/perf-tob-cli-refusal-preload.mjs @@ -0,0 +1,69 @@ +import cp from 'node:child_process'; +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { syncBuiltinESMExports } from 'node:module'; +import zlib from 'node:zlib'; +if (process.env.PERF_TEST_CANCEL_MODE === 'decoder-unavailable') + zlib.zstdDecompressSync = undefined; +let auditCalls = 0; +const read = fs.readFileSync; +const calls = []; +fs.readFileSync = (file, ...args) => { + const name = (file instanceof URL ? fileURLToPath(file) : String(file)).replaceAll('\\', '/'); + if (/\/packages\/(?:core\/(?:dist|cli)\/index|deepseekbot\/dist\/deepseekbot)\.mjs$/u.test(name)) + return Buffer.from('unit-test artifact; no runtime qualification'); + return read(file, ...args); +}; +cp.execFile = (executable, args, options, callback) => { + if ( + executable !== process.execPath || + !args[0].replaceAll('\\', '/').endsWith('/packages/deepseekbot/dist/deepseekbot.mjs') || + options.shell !== false || + options.windowsHide !== true + ) + throw new Error('Unit fixture refuses any real subprocess'); + const argv = args.slice(1); + calls.push(argv); + fs.writeFileSync(process.env.PERF_TEST_CALLS, JSON.stringify(calls)); + let value; + if (argv[0] === 'tob-home') value = { botSlug: 'unit-tob' }; + else if (argv[0] === 'bot-trace') { + auditCalls++; + value = { + sessionId: + process.env.PERF_TEST_CANCEL_MODE === 'audit-after-oversize' && auditCalls > 1 + ? 'unit-session' + : null, + }; + } else if (argv[0] === 'approval-templates') value = { templates: [] }; + else if (argv[1] === 'start') value = { id: 'unit-request', state: 'running' }; + else if (argv[1] === 'status') + value = { + state: 'completed', + result: { exitCode: 0, stdout: JSON.stringify({ templates: [] }) }, + }; + else if (argv[1] === 'cancel') value = { error: { code: 'unit-cancel-refusal' } }; + else throw new Error('Unexpected unit command'); + return { + stdin: { + end() { + queueMicrotask(() => { + const failed = + argv[0] === 'tob-cli' && + argv[1] === 'cancel' && + ['coded-json', 'non-json'].includes(process.env.PERF_TEST_CANCEL_MODE); + const output = + failed && process.env.PERF_TEST_CANCEL_MODE === 'non-json' + ? 'not-json' + : JSON.stringify(value); + callback( + failed ? Object.assign(new Error('Unit refusal'), { code: 7 }) : null, + output, + '', + ); + }); + }, + }, + }; +}; +syncBuiltinESMExports(); diff --git a/scripts/test/perf-cli-effects.test.mjs b/scripts/test/perf-cli-effects.test.mjs new file mode 100644 index 0000000000..8d9d3b6608 --- /dev/null +++ b/scripts/test/perf-cli-effects.test.mjs @@ -0,0 +1,170 @@ +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + existsSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { expect, it } from 'vitest'; + +function withRunner({ from = 'inherit', to = 'off', failure = '', baseline }, check) { + const directory = mkdtempSync(join(tmpdir(), 'perf-cli-effects-unit-')); + try { + const checkout = join(directory, 'checkout'); + for (const file of [ + 'perf-cli-effects.mjs', + 'test/fixtures/perf-cli-effects-preload.mjs', + 'perf-budgets/cli-effects.json', + ]) { + const target = join(checkout, 'scripts', file); + mkdirSync(dirname(target), { recursive: true }); + copyFileSync(fileURLToPath(new URL('../' + file, import.meta.url)), target); + } + expect(existsSync(join(checkout, 'packages/core/cli/index.mjs'))).toBe(false); + const fixture = join(directory, 'fixture.json'); + const instance = join(directory, 'instance.json'); + const output = join(directory, 'output.json'); + const calls = join(directory, 'calls.json'); + const state = join(directory, 'state.json'); + const fixtureText = JSON.stringify({ bot: 'unit-bot', from, to }); + writeFileSync(fixture, fixtureText); + writeFileSync(instance, JSON.stringify({ url: 'http://127.0.0.1:1/?token=unit-only' })); + const args = [ + join(checkout, 'scripts/perf-cli-effects.mjs'), + '--source-sha', + 'f'.repeat(40), + '--fixture', + fixture, + '--instance', + instance, + '--output', + output, + ]; + if (baseline) { + const valid = { + fixtureSha256: createHash('sha256').update(fixtureText).digest('hex'), + node: process.version, + budget: { failures: [] }, + samples: ['list', 'set', 'read'].flatMap((operation) => + Array.from({ length: 3 }, (_, round) => ({ + operation, + round, + correct: true, + code: 0, + processCode: 0, + wallMs: 1000, + maxRssKiB: 60000, + })), + ), + }; + baseline(valid); + const baselinePath = join(directory, 'baseline.json'); + writeFileSync(baselinePath, JSON.stringify(valid)); + args.push('--baseline', baselinePath); + } + const preload = pathToFileURL( + join(checkout, 'scripts/test/fixtures/perf-cli-effects-preload.mjs'), + ).href; + const child = spawnSync(process.execPath, args, { + encoding: 'utf8', + shell: false, + windowsHide: true, + timeout: 10000, + env: { + ...process.env, + NODE_OPTIONS: [process.env.NODE_OPTIONS, '--import=' + preload].filter(Boolean).join(' '), + PERF_TEST_CALLS: calls, + PERF_TEST_STATE: state, + PERF_TEST_FAILURE: failure, + }, + }); + expect(existsSync(output), child.stderr).toBe(true); + check({ + status: child.status, + report: JSON.parse(readFileSync(output, 'utf8')), + calls: existsSync(calls) ? JSON.parse(readFileSync(calls, 'utf8')) : [], + selected: existsSync(state) ? JSON.parse(readFileSync(state, 'utf8')) : undefined, + }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +it.each([ + ['inherit', 'off', 'omitted-off', '@global'], + ['off', 'inherit', '', null], + ['named-before', 'inherit', '', 'named-before'], +])( + 'normalizes %s -> %s selections and restores the original choice', + (from, to, failure, expected) => { + withRunner({ from, to, failure }, ({ status, report, selected, calls }) => { + expect(status).toBe(0); + expect(report.budget.failures).toEqual([]); + expect(report.samples).toHaveLength(9); + expect(report.restorations).toHaveLength(3); + expect(report.restorations.every((row) => row.correct)).toBe(true); + expect(selected).toBe(expected); + expect( + calls.filter((argv) => argv[0] === 'approval-template-set' && argv[2] === from), + ).toHaveLength(3); + }); + }, +); + +it('restores the fixture and writes the failure report after a worker throws', () => { + withRunner({ failure: 'set-throw' }, ({ status, report, calls, selected }) => { + expect(status).toBe(1); + expect(report.budget.failures).toContain('set:incorrect'); + expect(report.samples).toHaveLength(2); + expect(report.restorations).toHaveLength(1); + expect(report.restorations[0].correct).toBe(true); + expect(calls.at(-1)).toEqual(['approval-template-set', 'unit-bot', 'inherit', '--compact']); + expect(selected).toBe('@global'); + }); +}); + +it('preserves samples and a coded restoration refusal instead of throwing before output', () => { + withRunner({ failure: 'restore-refusal' }, ({ status, report }) => { + expect(status).toBe(1); + expect(report.samples).toHaveLength(3); + expect(report.budget.failures).toContain('fixture-restore-failed'); + expect(report.restorations[0]).toMatchObject({ code: 7, error: 'unit-restore-refused' }); + }); +}); + +it.each([ + ['failed', (baseline) => baseline.budget.failures.push('set:latency')], + [ + 'missing', + (baseline) => (baseline.samples = baseline.samples.filter((row) => row.operation !== 'set')), + ], + [ + 'nonfinite', + (baseline) => (baseline.samples.find((row) => row.operation === 'read').wallMs = Infinity), + ], + ['incorrect', (baseline) => (baseline.samples[0].correct = false)], + ['worker-failed', (baseline) => (baseline.samples[0].processCode = 1)], +])('refuses a %s baseline before mutating the fixture', (_name, baseline) => { + withRunner({ baseline }, ({ status, report, calls }) => { + expect(status).toBe(1); + expect(report.budget.failures.some((failure) => failure.startsWith('baseline:'))).toBe(true); + expect(report.samples).toEqual([]); + expect(report.restorations).toEqual([]); + expect(calls).toEqual([]); + }); +}); + +it('uses a complete successful matching baseline for latency comparison', () => { + withRunner({ baseline: () => {} }, ({ status, report }) => { + expect(status).toBe(0); + expect(report.budget.failures).toEqual([]); + expect(report.samples).toHaveLength(9); + }); +}); diff --git a/scripts/test/perf-timeline-seed.test.mjs b/scripts/test/perf-timeline-seed.test.mjs new file mode 100644 index 0000000000..1dcfcdb52c --- /dev/null +++ b/scripts/test/perf-timeline-seed.test.mjs @@ -0,0 +1,254 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { describe, expect, it, vi } from 'vitest'; +import { runTimelineSeedTool, seedTimeline } from '../perf-timeline-seed.mjs'; +import { OWNER_HUMAN_CONTEXT } from '../../packages/core/src/humans/context.ts'; +import { createCore } from '../../packages/core/src/plugin.ts'; +import { createBridgeMethods } from '../../packages/core/src/bridge/methods.ts'; +import { createDshBotAgentAdapter } from '../../packages/core/src/runtime/dsh-bot-agent-adapter.ts'; +import { ChannelToolApproval } from '../../packages/core/src/workspaces/tool-approval.ts'; +import { FakeAgentHost } from '../../packages/core/test/dsh-agent-host-fixture.ts'; +import { createTempRoot } from '../../packages/core/test/helpers.ts'; + +function pendingFixture(change = () => undefined) { + const args = { channel_id: 'group-fixture', body: 'Fixture only', reply_to: 'human-1' }; + const sessionId = 'direct-' + randomUUID(); + const request = { + id: 'approval-1', + author: { kind: 'bot', slug: 'seed-bot' }, + toolApprovalRequest: { + sessionId, + callId: sessionId, + toolName: 'bot_send_message', + role: 'orchestrator', + input: JSON.stringify(args), + }, + }; + change(request); + let started = false; + let resolve; + let reject; + const decisions = []; + const rpc = async (method, payload) => { + if (method === 'channelDm') return { channel: { id: 'dm-seed-bot' } }; + if (method === 'channelMessages') return { messages: started ? [request] : [] }; + if (method === 'botToolRun') { + started = true; + return new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + } + if (method === 'toolApprovalStatus') return { status: 'pending' }; + if (method === 'toolApprovalDecide') { + decisions.push(payload); + if (payload.outcome === 'rejected') reject(new Error('approval-denied')); + else resolve({ result: { messageId: 'bot-message-1' } }); + return { accepted: true }; + } + throw new Error('Unexpected RPC ' + method); + }; + return { args, rpc, decisions }; +} + +describe('timeline seed owner decisions', () => { + it('allows only the current exact direct operation once', async () => { + const f = pendingFixture(); + expect(await runTimelineSeedTool({ ...f, slug: 'seed-bot', pollMs: 1 })).toEqual({ + result: { messageId: 'bot-message-1' }, + }); + expect(f.decisions).toEqual([ + { channelId: 'dm-seed-bot', messageId: 'approval-1', outcome: 'allowed-once' }, + ]); + }); + + it.each([ + [ + 'Bot', + (message) => { + message.author.slug = 'foreign-bot'; + }, + ], + [ + 'body', + (message) => { + message.toolApprovalRequest.input = JSON.stringify({ + channel_id: 'group-fixture', + body: 'Other action', + reply_to: 'human-1', + }); + }, + ], + [ + 'tool', + (message) => { + message.toolApprovalRequest.toolName = 'bash'; + }, + ], + [ + 'Session', + (message) => { + message.toolApprovalRequest.sessionId = 'ordinary-session'; + }, + ], + [ + 'call', + (message) => { + message.toolApprovalRequest.callId = 'other-call'; + }, + ], + [ + 'role', + (message) => { + message.toolApprovalRequest.role = 'assignment'; + }, + ], + ])('refuses a different %s without deciding it', async (_name, change) => { + const f = pendingFixture(change); + await expect(runTimelineSeedTool({ ...f, slug: 'seed-bot', pollMs: 1 })).rejects.toThrow( + 'timeline-seed-unrelated-approval', + ); + expect(f.decisions).toEqual([]); + }); + + it('ends an unavailable operation without waiting for the browser protocol deadline', async () => { + const f = pendingFixture(); + const rpc = async (method, args) => + method === 'channelMessages' ? { messages: [] } : f.rpc(method, args); + await expect( + runTimelineSeedTool({ ...f, rpc, slug: 'seed-bot', pollMs: 1, timeoutMs: 20 }), + ).rejects.toThrow('timeline-seed-tool-timeout'); + expect(f.decisions).toEqual([]); + }); + + it('rejects the exact pending card after a timeout and observes the underlying refusal', async () => { + const f = pendingFixture(); + let statuses = 0; + const rpc = async (method, args) => + method === 'toolApprovalStatus' && statuses++ === 0 + ? new Promise(() => undefined) + : f.rpc(method, args); + vi.useFakeTimers(); + try { + const operation = runTimelineSeedTool({ + ...f, + rpc, + slug: 'seed-bot', + pollMs: 1, + timeoutMs: 20, + }).catch((failure) => failure); + await vi.advanceTimersByTimeAsync(1); + expect(statuses).toBe(1); + await vi.advanceTimersByTimeAsync(20); + const error = await operation; + expect(error.message).toBe('timeline-seed-tool-timeout'); + expect(error.timelineSeed).toMatchObject({ + messageId: 'approval-1', + callId: expect.stringMatching(/^direct-/u), + sessionId: expect.stringMatching(/^direct-/u), + cleanup: 'rejected', + operation: 'failed', + }); + expect(f.decisions).toEqual([ + { channelId: 'dm-seed-bot', messageId: 'approval-1', outcome: 'rejected' }, + ]); + } finally { + vi.useRealTimers(); + } + }); + + it('accepts an already-completed baseline operation without manufacturing an approval', async () => { + const f = pendingFixture(); + const rpc = async (method, args) => + method === 'botToolRun' ? { result: { messageId: 'baseline-message' } } : f.rpc(method, args); + expect(await runTimelineSeedTool({ ...f, rpc, slug: 'seed-bot', pollMs: 1 })).toEqual({ + result: { messageId: 'baseline-message' }, + }); + expect(f.decisions).toEqual([]); + }); + + it('seeds through actual Native Tool execution and canonical Human approvals without saving rules', async () => { + const host = new FakeAgentHost(); + const nativeCreate = host.create.bind(host); + const home = createTempRoot('timeline-seed-'); + const adapter = createDshBotAgentAdapter({ + agents: host, + orchestratorCwd: () => home, + ensureWorkspace: () => undefined, + defaultModel: { currentSelection: () => ({ provider: 'test', model: 'test' }) }, + }); + const core = createCore({ dshHome: home, agents: adapter }); + const approval = new ChannelToolApproval(core.channels, core.ownership, core.toolRules); + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, toolApproval: approval }); + const decisions = []; + let groupId; + vi.spyOn(host, 'create').mockImplementation(async (options) => { + const handle = await nativeCreate(options); + const execute = handle.agent.ctx.tools.execute.bind(handle.agent.ctx.tools); + vi.spyOn(handle.agent.ctx.tools, 'execute').mockImplementation(async (input) => { + const untrack = approval.track({ ...input, token: Symbol(input.callId) }); + assert.ok(untrack, 'real runtime ownership must precede native approval'); + try { + assert.equal( + await approval.ask({ + agent: input.agent, + toolName: input.name, + callId: input.callId, + signal: input.signal, + }), + 'allowed-once', + ); + return await execute(input); + } finally { + untrack(); + } + }); + return handle; + }); + const rpc = async (method, payload) => { + if (method === 'toolApprovalDecide') { + assert.equal(methods.toolApprovalStatus(payload).value.status, 'pending'); + const request = core.channels.message( + payload.channelId, + payload.messageId, + ).toolApprovalRequest; + assert.equal( + core.channels.readMessages(groupId).filter((message) => message.author.kind === 'bot') + .length, + decisions.length, + ); + assert.equal(request.toolName, 'bot_send_message'); + decisions.push(payload); + } + const result = await methods[method](payload); + assert.equal(result.ok, true, result.error?.message); + if (method === 'channelCreate') groupId = result.value.channel.id; + return result.value; + }; + try { + const fixture = await seedTimeline({ + rpc, + count: 3, + bodies: [(index) => 'Real fixture ' + index], + }); + expect(fixture.messageIds).toHaveLength(3); + expect(core.channels.readMessages(groupId).map((message) => message.id)).toEqual( + [...fixture.messageIds].reverse(), + ); + expect(decisions).toHaveLength(2); + expect(decisions.every((decision) => decision.outcome === 'allowed-once')).toBe(true); + for (const slug of fixture.bots) + expect(methods.toolApprovalRules({ slug })).toMatchObject({ + ok: true, + value: { rules: [] }, + }); + expect(host.received.size).toBe(0); + } finally { + approval.close(); + await core.runtime.close(); + core.externalMessaging.close(); + core.live.close(); + core.operationalDatabase.close(); + } + }, 60_000); +}); diff --git a/scripts/test/perf-tob-cli.test.mjs b/scripts/test/perf-tob-cli.test.mjs new file mode 100644 index 0000000000..70a55cc005 --- /dev/null +++ b/scripts/test/perf-tob-cli.test.mjs @@ -0,0 +1,125 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, it } from 'vitest'; + +it.each(['coded-json', 'non-json'])( + 'stops the actual performance runner after a %s cancellation failure', + (mode) => { + const home = mkdtempSync(join(tmpdir(), 'perf-tob-cancel-unit-')); + try { + const fixture = join(home, 'fixture.json'), + instance = join(home, 'instance.json'); + const output = join(home, 'output.json'), + calls = join(home, 'calls.json'); + writeFileSync(fixture, JSON.stringify({ argv: ['approval-templates'] })); + writeFileSync(instance, JSON.stringify({ home, url: 'http://127.0.0.1:1/?token=unit-only' })); + const child = spawnSync( + process.execPath, + [ + '--import', + new URL('./fixtures/perf-tob-cli-refusal-preload.mjs', import.meta.url).href, + fileURLToPath(new URL('../perf-tob-cli.mjs', import.meta.url)), + '--source-sha', + 'f'.repeat(40), + '--fixture', + fixture, + '--instance', + instance, + '--output', + output, + ], + { + encoding: 'utf8', + shell: false, + windowsHide: true, + timeout: 10000, + env: { ...process.env, PERF_TEST_CALLS: calls, PERF_TEST_CANCEL_MODE: mode }, + }, + ); + expect(child.status).toBe(1); + const report = JSON.parse(readFileSync(output, 'utf8')); + expect(report.failures).toContain('cancel-request-failed'); + expect(report.samples).toHaveLength(1); + const commands = JSON.parse(readFileSync(calls, 'utf8')); + expect(commands.filter((argv) => argv[0] === 'tob-cli' && argv[1] === 'start')).toHaveLength( + 1, + ); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }, +); + +it.each(['decoder-unavailable', 'audit-after-oversize'])( + 'persists a failed %s audit without discarding collected samples', + (mode) => { + const home = mkdtempSync(join(tmpdir(), 'perf-tob-audit-unit-')); + try { + const fixture = join(home, 'fixture.json'); + const instance = join(home, 'instance.json'); + const output = join(home, 'output.json'); + const calls = join(home, 'calls.json'); + writeFileSync(fixture, JSON.stringify({ argv: ['approval-templates'] })); + writeFileSync(instance, JSON.stringify({ home, url: 'http://127.0.0.1:1/?token=unit-only' })); + const capture = join(home, 'sessions', 'unit-provider', 'unit-session'); + mkdirSync(capture, { recursive: true }); + const oversized = join(capture, 'session.v4.jsonl.zstd'); + writeFileSync(oversized, ''); + truncateSync(oversized, 16 * 1024 * 1024 + 1); + const child = spawnSync( + process.execPath, + [ + '--import', + new URL('./fixtures/perf-tob-cli-refusal-preload.mjs', import.meta.url).href, + fileURLToPath(new URL('../perf-tob-cli.mjs', import.meta.url)), + '--source-sha', + 'f'.repeat(40), + '--fixture', + fixture, + '--instance', + instance, + '--output', + output, + '--rounds', + '1', + ], + { + encoding: 'utf8', + shell: false, + windowsHide: true, + timeout: 10000, + env: { ...process.env, PERF_TEST_CALLS: calls, PERF_TEST_CANCEL_MODE: mode }, + }, + ); + expect(child.status).toBe(1); + const report = JSON.parse(readFileSync(output, 'utf8')); + if (mode === 'decoder-unavailable') { + expect(report.failures).toEqual(['native-audit-before-failed:unsupported-audit-decoder']); + expect(report.nativeAudit.before).toEqual({ + valid: false, + error: 'unsupported-audit-decoder', + }); + expect(report.samples).toEqual([]); + } else { + expect(report.failures).toEqual(['native-audit-after-failed:native-audit-unavailable']); + expect(report.nativeAudit.before.valid).toBe(true); + expect(report.nativeAudit.after).toEqual({ + valid: false, + error: 'native-audit-unavailable', + }); + expect(report.samples).toHaveLength(1); + expect(report.samples[0].correct).toBe(true); + expect(Number.isFinite(report.samples[0].journeyMs)).toBe(true); + const commands = JSON.parse(readFileSync(calls, 'utf8')); + expect( + commands.filter((argv) => argv[0] === 'tob-cli' && argv[1] === 'cancel'), + ).toHaveLength(1); + } + } finally { + rmSync(home, { recursive: true, force: true }); + } + }, +); diff --git a/scripts/test/private-host-redaction.test.mjs b/scripts/test/private-host-redaction.test.mjs new file mode 100644 index 0000000000..b81af32884 --- /dev/null +++ b/scripts/test/private-host-redaction.test.mjs @@ -0,0 +1,34 @@ +import { expect, it } from 'vitest'; +import { createPrivateHostRedactor } from '../private-host-redaction.mjs'; + +it('redacts navigation URLs and standalone credentials before bounded error output', () => { + const url = 'http://127.0.0.1:12345/?token=synthetic-private-token#synthetic-private-fragment'; + const redact = createPrivateHostRedactor(url); + const navigation = new Error('net::ERR_CONNECTION_REFUSED at ' + url); + const messages = [ + navigation.message, + 'token synthetic-private-token, fragment synthetic-private-fragment', + 'x'.repeat(990) + url, + ]; + const artifact = { + error: redact(messages[0]).slice(0, 1000), + pageErrors: messages.map((message) => redact(message).slice(0, 500)), + stderr: redact(navigation.stack), + }; + const output = JSON.stringify(artifact); + expect(output).not.toContain(url); + expect(output).not.toContain('synthetic-private-token'); + expect(output).not.toContain('synthetic-private-fragment'); + expect(artifact.error).toContain('ERR_CONNECTION_REFUSED'); + expect(artifact.error).toContain('[private Host URL]'); + expect(artifact.pageErrors[1]).toContain('[redacted]'); + expect(artifact.pageErrors.every((message) => message.length <= 500)).toBe(true); +}); +it('preserves public diagnostics and handles token-free URLs', () => { + expect(createPrivateHostRedactor('http://localhost:12345/')('public failure')).toBe( + 'public failure', + ); + expect(createPrivateHostRedactor('http://localhost:12345/')(new Error('ordinary failure'))).toBe( + 'Error: ordinary failure', + ); +});