diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml index b232d35110..098256e7ce 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-06-15-ptc.md -2026-06-15-ptc.md: 18f45d8c0fef79962db233661be05c63b4eba2bb -2026-06-15-ptc.zh.md: 43e52a438a5dda887deaf8204d8b0f95445c53c8 +2026-06-15-ptc.md: 44736d2c48ffc60548a678ed751051d56de25fb1 +2026-06-15-ptc.zh.md: d436c33e402280ca2da3776110ab4751e4e18ff1 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.md b/.agents/notes/implemented/feature/2026-06-15-ptc.md index 18f45d8c0f..44736d2c48 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.md @@ -24,6 +24,12 @@ Three decisions, each elaborated in its own section below: This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, canonical binding values, `ToolCallError` and lossless outer output. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules. +### Per-program execution controls + +The consumer advertises `timeoutMs` from the runtime's readonly `timeout` descriptor and passes explicit values through its resolver. Unsupported providers expose no timeout field and reject an explicit request. Sandbox escalation uses the shared strict-widening approval helper before runtime resolution and launch; replacing only the resolved policy's mode keeps the grant local to one program. Nested dispatches retain the original Agent and Session, so their approvals and file policy remain independent. No failed program is replayed implicitly because earlier effects may already have committed. + +The [Node execution decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md#deferred-timeout-design) owns elapsed-budget accounting and deferred lifetime questions. + ### The registry owns the mode `ToolRuntime` gains a schemastery-validated config (`static Config`), its first: `mode: 'native' | 'ptc' | 'both'`, default `'native'`. A deployment flips it from `cordis.yml` (`tools: { mode: ptc }`) — no code edit, per the no-hardcoded-tunables convention. diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md index 43e52a438a..d436c33e40 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md @@ -24,6 +24,12 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、规范绑定值、`ToolCallError` 与无损外层输出。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。 +### 每段程序的执行控制 + +消费方根据运行时只读 `timeout` 描述符通告 `timeoutMs`,并把显式值交给其解析器。不支持的提供方不公开超时字段,并拒绝显式请求。沙箱提升在运行时解析和启动前使用共享的严格扩大权限审批辅助函数;仅替换已解析策略的模式,使授权只作用于一段程序。嵌套分发保留原始 Agent 和 Session,因此其审批与文件策略保持独立。失败程序不会隐式重放,因为先前效果可能已提交。 + +[Node 执行决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md#deferred-timeout-design) 负责经过时间预算核算与延期的生命周期问题。 + ### 注册表拥有模式 `ToolRuntime` 获得一个经 schemastery 校验的配置(`static Config`),这是它的第一个配置:`mode: 'native' | 'ptc' | 'both'`,默认 `'native'`。部署通过 `cordis.yml` 翻转模式(`tools: { mode: ptc }`),无需改代码,遵循 no-hardcoded-tunables 约定。 diff --git a/apps/web/tests/ptc-escalation.e2e.ts b/apps/web/tests/ptc-escalation.e2e.ts new file mode 100644 index 0000000000..f9dbd31eae --- /dev/null +++ b/apps/web/tests/ptc-escalation.e2e.ts @@ -0,0 +1,92 @@ +// Real PTC sandbox denial followed by one approved program execution. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-user-approval' +import { + assertFinalWorkspaceSnapshot, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/ptc-escalation-approved', import.meta.url)) +const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl') +const UI_EXPECTED = join(SNAPSHOT_DIR, 'approval.expected.md') +const MODE = webSnapshotMode() +const PROMPT = 'Use run_code with timeoutMs 120000 and direct Node filesystem access to create approved.txt in the working directory containing exactly "approved\\n". ' + + 'Use await import("node:fs/promises") and writeFile; do not call nested tools. First attempt the write under the current read-only sandbox without escalation. ' + + 'If the sandbox denies it, explicitly retry the program with sandbox_permissions "workspace-write" and justification "Create the file requested by the user". ' + + 'I will answer the approval prompt. After the file is written, reply DONE and stop.' + +describe('web e2e: PTC program sandbox escalation', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + const events: SessionEvent[] = [] + + beforeAll(async () => { + scaffold = await launchWebScaffold({ + agentPresets: { roots: [], default: 'ptc' }, + compareReplaySession: true, + ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }), + }) + scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { events.push(event) }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('keeps the file absent until approval and records the granted program', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-ptc-escalation')) + if (MODE !== 'record') expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) + const input = page.locator('[data-composer-input]').first() + await input.waitFor({ timeout: 10_000 }) + await page.locator('[aria-label^="Access mode"]').click() + await page.getByRole('menuitem', { name: 'Read Only' }).click() + await expect.poll(() => page.locator('[aria-label="Access mode, current: Read Only"]').count()).toBe(1) + const settled = scaffold.whenTurnSettled(MODE === 'record' ? 240_000 : 60_000) + await input.fill(PROMPT) + await input.press('Enter') + const panel = page.locator('[data-approval-key]') + await panel.waitFor({ timeout: MODE === 'record' ? 180_000 : 60_000 }) + const calls = events.filter(event => event.type === 'tool/call') + expect(calls.length).toBeGreaterThanOrEqual(2) + expect(calls.every(event => event.data.name === 'run_code')).toBe(true) + expect(JSON.stringify(calls[0]?.data)).toContain('node:fs/promises') + expect(JSON.stringify(calls.at(-1)?.data)).toContain('workspace-write') + const file = join(scaffold.workspaceCwd, 'workspace', 'approved.txt') + await expect(readFile(file, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) + if (MODE !== 'record') { + await compareOrRefreshGolden(UI_EXPECTED, await captureStableAria(page, '[data-approval-key]', scaffold.workspaceCwd), MODE) + } + await panel.getByRole('button', { name: 'Allow once' }).click() + const sessionId = await settled + expect(await readFile(file, 'utf8')).toBe('approved\n') + expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(0) + expect(events.filter(event => event.type === 'approval/decided').map(event => event.data)).toMatchObject([{ outcome: 'allowed-once' }]) + expect(await page.locator('[aria-label="Access mode, current: Read Only"]').count()).toBe(1) + await expect.poll(() => page.getByText('DONE', { exact: true }).count()).toBeGreaterThanOrEqual(1) + expect(await panel.count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + if (MODE === 'record') await recordFixture(scaffold, sessionId, FIXTURE) + await assertFinalWorkspaceSnapshot(SNAPSHOT_DIR, join(scaffold.workspaceCwd, 'workspace')) + }, 300_000) + + it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { + await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'approval.expected.md', 'workspace.expected']) + }) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4d9821891e..0b5602d46a 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -32,6 +32,7 @@ "tests/live-interactions.e2e.ts", "tests/question-composer.e2e.ts", "tests/approval-composer.e2e.ts", + "tests/ptc-escalation.e2e.ts", "tests/plan-control-row.e2e.ts", "tests/plan-review.e2e.ts", "tests/steering.e2e.ts", diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index a9fa6c7545..6f1aec6569 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/tool-catalog.md -tool-catalog.md: c6c09aee8ed1cac69558bb02ca3395eaebed86e5 -tool-catalog.zh.md: 2cd6715ff03752885da0bb91e7e9ed9796f9ede4 +tool-catalog.md: f89d8983844cd8f0b4e95e1460515b61919f323b +tool-catalog.zh.md: 68449c7b016f0a034fc7efa7e007f578db505ecf diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index c6c09aee8e..f89d898384 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -135,6 +135,22 @@ Execute a TypeScript program against the available tools. Takes two required arg "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, capped by the deployment maximum." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 2cd6715ff0..68449c7b01 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -139,6 +139,22 @@ ask_user_question 会暂停工具调用,直到当前 UI 提供方返回人类 "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, capped by the deployment maximum." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/packages/code-runtime/code-runtime-node/README.i18n.yaml b/packages/code-runtime/code-runtime-node/README.i18n.yaml index 69c2eafef8..21126ea061 100644 --- a/packages/code-runtime/code-runtime-node/README.i18n.yaml +++ b/packages/code-runtime/code-runtime-node/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/code-runtime/code-runtime-node/README.md -README.md: 357173bf93a0e5d1e0048b6ee06fac36db856a62 -README.zh.md: 5808193e493b1a8dcf1e404dcc938f62b4b246db +README.md: 4897656b6b42a7a5b38401576506088130d7b92a +README.zh.md: 83c17be7c1d3a0c9b6d1ac5b7e1c2dd647006914 diff --git a/packages/code-runtime/code-runtime-node/README.md b/packages/code-runtime/code-runtime-node/README.md index 357173bf93..4897656b6b 100644 --- a/packages/code-runtime/code-runtime-node/README.md +++ b/packages/code-runtime/code-runtime-node/README.md @@ -65,6 +65,8 @@ Direct filesystem, network and subprocess operations remain Node operations, sub ### Deadlines and cancellation +The PTC consumer exposes per-call timeout and approved sandbox choices as described in [dsh-tools](../../core/tools/README.md#ptc-mode). The runtime's readonly `timeout` descriptor reports its effective default and maximum to that consumer. + The elapsed deadline covers runtime setup and execution, including time awaiting nested tools or approval. It is not a CPU meter. Timeout or cancellation stops a synchronous loop through the host's managed process owner; successful completion also cleans that managed range. The timer stops when an outcome is selected, before cleanup, so the returned call can take longer than its execution deadline while cleanup settles. ### Failures diff --git a/packages/code-runtime/code-runtime-node/README.zh.md b/packages/code-runtime/code-runtime-node/README.zh.md index 5808193e49..83c17be7c1 100644 --- a/packages/code-runtime/code-runtime-node/README.zh.md +++ b/packages/code-runtime/code-runtime-node/README.zh.md @@ -65,6 +65,8 @@ kind: "package-reference" ### 截止时间与取消 +PTC 消费方按 [dsh-tools](../../core/tools/README.zh.md#ptc-mode) 的说明公开逐次超时与经审批的沙箱选择。运行时只读 `timeout` 描述符向该消费方报告有效默认值与上限。 + 经过时间截止覆盖运行时准备和执行,包括等待嵌套工具或审批的时间。它不是 CPU 计量器。超时或取消通过 Host 的受管进程所有者停止同步循环;成功完成也会清理该受管范围。选择结果后、清理前停止计时器,因此调用可能要在执行截止之后等待清理结算才返回。 ### 失败 diff --git a/packages/code-runtime/code-runtime/README.i18n.yaml b/packages/code-runtime/code-runtime/README.i18n.yaml index a83e000c93..9c28667d66 100644 --- a/packages/code-runtime/code-runtime/README.i18n.yaml +++ b/packages/code-runtime/code-runtime/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/code-runtime/code-runtime/README.md -README.md: 32f5b76fb88c4880cef16abbfa11da52ae13d5ab -README.zh.md: 28718c23b8449592ccc0c8c03fa4a9b38963c673 +README.md: ede55ec882cc8d51f0457800d6c79c31145882c4 +README.zh.md: 938ccd0dcfa37dbc237f8f8b016763053b4e0ea2 diff --git a/packages/code-runtime/code-runtime/README.md b/packages/code-runtime/code-runtime/README.md index 32f5b76fb8..ede55ec882 100644 --- a/packages/code-runtime/code-runtime/README.md +++ b/packages/code-runtime/code-runtime/README.md @@ -68,6 +68,8 @@ The package is the Service Definition role of the code-execution capability seam ### Service API +The readonly `timeout` descriptor exposes `{ defaultMs, maxMs }` for a provider supporting per-call overrides; `undefined` means that the consumer must omit the field. It reports presentation values, while `resolve` remains the validation and clamping authority. + `resolve(request)` owns supported option validation and deployment defaulting. `run(spec)` executes the complete inputs and resolves program outcomes after cleanup. Language and substrate descriptors guide presentation; `sandboxMode` indicates whether the consumer can pass a resolved file policy. Neither descriptors nor a successful program result substitute for the backend's reported enforcement facts. The exhaustive semantics live in the [code runtime subsystem reference](../../../docs/subsystems/code-runtime.md); the exact signatures are in [`src/index.ts`](src/index.ts). diff --git a/packages/code-runtime/code-runtime/README.zh.md b/packages/code-runtime/code-runtime/README.zh.md index 28718c23b8..938ccd0dcf 100644 --- a/packages/code-runtime/code-runtime/README.zh.md +++ b/packages/code-runtime/code-runtime/README.zh.md @@ -68,6 +68,8 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配 `[A-Za ### 服务 API +只读 `timeout` 描述符为支持逐次覆盖的提供方公开 `{ defaultMs, maxMs }`;`undefined` 表示消费方必须省略该字段。它报告呈现值,验证与截断仍由 `resolve` 负责。 + `resolve(request)` 负责支持选项的验证与部署默认值。`run(spec)` 执行完整输入,并在清理后返回程序结果。语言和执行基底描述符指导呈现;`sandboxMode` 表示消费方能否传入已解析文件策略。描述符与程序成功结果都不能代替后端报告的强制能力事实。 穷尽式语义见[代码运行时子系统参考](../../../docs/subsystems/code-runtime.zh.md);确切签名见 [`src/index.ts`](src/index.ts)。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index d4db7dca51..9b774bcd6a 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/tools/README.md -README.md: 17e2eb05bac152c75f7a906bf6e15f26517d38dc -README.zh.md: cd08e9282e2ac6e75c1694d9989a4079d65985b5 +README.md: 8b93c831a7570e6521dc5fdffb18f76619e945b1 +README.zh.md: 1d4ecfbcf1e5b5af96df6217647b2659e836bb51 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 17e2eb05ba..8b93c831a7 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -126,6 +126,8 @@ Under `ptc` or `both`, the registry exposes the reserved `run_code` transport pl New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque and correlate events by exact equality; restored historical ids retain their original bytes. The [PTC mode decision](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns durable naming and restoration rules. +`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. + ### Extension points diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index cd08e9282e..1d4ecfbcf1 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -126,6 +126,8 @@ ctx.tools.register(defineTool({ 新子调用使用 `:ptc:` 标识。消费方将这些标识视为不透明值,并通过精确相等关联事件;恢复的历史标识保留原始字节。[PTC mode 决策](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md) 负责持久化命名与恢复规则。 +当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 + ### 扩展点 diff --git a/packages/core/tools/src/ptc.ts b/packages/core/tools/src/ptc.ts index 17f4f73623..afc8fc1efb 100644 --- a/packages/core/tools/src/ptc.ts +++ b/packages/core/tools/src/ptc.ts @@ -105,6 +105,8 @@ const RUN_CODE_CONTROLS = { } as const function controlParameters(runtime: CodeRuntime | undefined) { + // Catalog readers have no mounted runtime; real model assembly requires one. + if (runtime === undefined) return RUN_CODE_CONTROLS return { ...runtime?.timeout === undefined ? {} : { timeoutMs: { ...RUN_CODE_CONTROLS.timeoutMs, diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index d186c5db5b..3c86a3fa70 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -615,6 +615,33 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { expect(safe.order.indexOf('start:r3')).toBeGreaterThan(safe.order.indexOf('end:r1')) }) + it('holds later dispatches while settled results await log storage', async () => { + const { ctx, runtime } = await setup({ maxParallelSubCalls: 1 }) + const calls = registerEcho(ctx) + const { agent } = fakeAgent() + const release = Promise.withResolvers() + const blocked = Promise.withResolvers() + let pendingLogs = 0 + ctx.on('tools/ptc-dispatch-log', async (_dispatch, next) => { + if (++pendingLogs === 2) blocked.resolve(undefined) + await release.promise + return next() + }) + runtime.behavior = async request => ({ logs: [], value: await Promise.all( + [0, 1, 2, 3].map(value => request.bindings[0]!.functions.echo!({ value: String(value) })), + ) }) + const running = runCode(ctx, 'program', { agent }) + try { + await blocked.promise + // Synchronous executors exhaust their unblocked microtasks before this checkpoint. + await new Promise(resolve => setImmediate(resolve)) + expect(calls).toHaveLength(2) + release.resolve(undefined) + expect((await running).isError).toBe(false) + expect(calls).toHaveLength(4) + } finally { release.resolve(undefined); await running; await ctx.fiber.dispose() } + }) + it('maxParallelSubCalls caps the overlap window', async () => { const { ctx, runtime } = await setup({ mode: 'ptc', maxParallelSubCalls: 2 }) const gated = registerGated(ctx, 'safe_read', true) @@ -2020,6 +2047,19 @@ describe('per-program execution controls', () => { } finally { await ctx.fiber.dispose() } }) + it('rejects escalation fields for a runtime without confinement support', async () => { + const { ctx, tools, runtime } = await setup() + try { + const result = await tools.execute({ + callId: ToolCallId('unsupported-escalation'), name: RUN_CODE_NAME, signal: testToolSignal, + arguments: { code: 'return 1', description: 'Try an unsupported mode', sandbox_permissions: 'workspace-write', justification: 'Need file writes' }, + }) + expect(result.isError).toBe(true) + expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this code runtime') + expect(runtime.lastRequest).toBeUndefined() + } finally { await ctx.fiber.dispose() } + }) + it('forwards an explicit timeout to the runtime resolver', async () => { const { ctx, runtime, execute } = await controlledSetup() const resolver = vi.spyOn(runtime, 'resolve') diff --git a/snapshots/session/both-mode-turn/tool-schemas.expected.json b/snapshots/session/both-mode-turn/tool-schemas.expected.json index fcaa91628e..73118f5fbb 100644 --- a/snapshots/session/both-mode-turn/tool-schemas.expected.json +++ b/snapshots/session/both-mode-turn/tool-schemas.expected.json @@ -322,7 +322,7 @@ }, { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run.", + "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "parameters": { "type": "object", "properties": { @@ -333,6 +333,22 @@ "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/snapshots/session/ptc-node-read-only/tool-schemas.expected.json b/snapshots/session/ptc-node-read-only/tool-schemas.expected.json index e48595aed7..ed4515dd3d 100644 --- a/snapshots/session/ptc-node-read-only/tool-schemas.expected.json +++ b/snapshots/session/ptc-node-read-only/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run.", + "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "parameters": { "type": "object", "properties": { @@ -13,6 +13,22 @@ "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/snapshots/session/ptc-node-workspace/tool-schemas.expected.json b/snapshots/session/ptc-node-workspace/tool-schemas.expected.json index e48595aed7..ed4515dd3d 100644 --- a/snapshots/session/ptc-node-workspace/tool-schemas.expected.json +++ b/snapshots/session/ptc-node-workspace/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run.", + "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "parameters": { "type": "object", "properties": { @@ -13,6 +13,22 @@ "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/snapshots/session/ptc-turn/tool-schemas.expected.json b/snapshots/session/ptc-turn/tool-schemas.expected.json index e48595aed7..ed4515dd3d 100644 --- a/snapshots/session/ptc-turn/tool-schemas.expected.json +++ b/snapshots/session/ptc-turn/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run.", + "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "parameters": { "type": "object", "properties": { @@ -13,6 +13,22 @@ "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [ diff --git a/snapshots/web/ptc-escalation-approved/approval.expected.md b/snapshots/web/ptc-escalation-approved/approval.expected.md new file mode 100644 index 0000000000..764a75c3e9 --- /dev/null +++ b/snapshots/web/ptc-escalation-approved/approval.expected.md @@ -0,0 +1,4 @@ +- text: Waiting for approval +- group "Approval details": "escalate sandbox to workspace-write: Create the file requested by the user" +- button "Reject" +- button "Allow once" diff --git a/snapshots/web/ptc-escalation-approved/session.v3.jsonl b/snapshots/web/ptc-escalation-approved/session.v3.jsonl new file mode 100644 index 0000000000..4ef795eb9f --- /dev/null +++ b/snapshots/web/ptc-escalation-approved/session.v3.jsonl @@ -0,0 +1,33 @@ +{"type":"session","version":3,"id":"{{session:1}}","createdAt":1789145654713,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"ptc"} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"command/run","data":{"commandId":"{{command:1}}","name":"permission","args":" read-only","source":{"kind":"user"}}} +{"type":"permission/preset","data":{"preset":"read-only"}} +{"type":"sandbox/mode","data":{"mode":"read-only"}} +{"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"preset read-only"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use run_code with timeoutMs 120000 and direct Node filesystem access to create approved.txt in the working directory containing exactly \"approved\\n\". Use await import(\"node:fs/promises\") and writeFile; do not call nested tools. First attempt the write under the current read-only sandbox without escalation. If the sandbox denies it, explicitly retry the program with sandbox_permissions \"workspace-write\" and justification \"Create the file requested by the user\". I will answer the approval prompt. After the file is written, reply DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use run_code with timeoutMs 120000 and direct Node filesystem access to create approved.txt in the working directory containing exactly \"approved\\n\". Use await import(\"node:fs/promises\") and writeFile; do not call nested tools. First attempt the write under the current read-only sandbox without escalation. If the sandbox denies it, explicitly retry the program with sandbox_permissions \"workspace-write\" and justification \"Create the file requested by the user\". I will answer the approval prompt. After the file is written, reply DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} +{"type":"session/title","data":{"title":"Use run_code with timeoutMs 120000","messageSeqs":[12],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to use run_code with direct Node filesystem access to create approved.txt. Let me attempt the write under read-only sandbox first without escalation.\n\nLet me write the program.\n\nThe instruction says \"do not call nested tools\" — so inside run_code I should just use node:fs/promises directly, no tools.bash etc.\n\nLet me do that."},{"type":"tool-call","id":"call_00_p0f6uzlwMZsoKQfC837b1176","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt under read-only sandbox\", \"timeoutMs\": 120000}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":1347,"outputTokens":230,"totalTokens":9001,"cacheReadTokens":7424,"reasoningTokens":77},"stream":[{"type":"chunk","time":1789145655763,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789145655763,"index":0,"dt":[114,16,1,0,0,10,0,1,0,14,1,9,1,0,0,10,0,0,0,16,0,12,0,12,1,10,1,0,0,0,12,0,0,0,1,13,0,0,0,13,16,1,12,0,8,0,0,17,0,0,0,8,0,0,0,13,0,13,13,0,0,22,0,0,0,5,0,13,0,0,12,0,0,0,0,18],"texts":["The"," user"," wants"," me"," to"," use"," run","_code"," with"," direct"," Node"," files","ystem"," access"," to"," create"," approved",".txt","."," Let"," me"," attempt"," the"," write"," under"," read","-only"," sand","box"," first"," without"," escalation",".\n\n","Let"," me"," write"," the"," program",".\n\n","The"," instruction"," says"," \"","do"," not"," call"," nested"," tools","\""," —"," so"," inside"," run","_code"," I"," should"," just"," use"," node",":","fs","/p","rom","ises"," directly",","," no"," tools",".b","ash"," etc",".\n\n","Let"," me"," do"," that","."]},{"type":"chunk","time":1789145656223,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789145656223,"index":1,"dt":[12,0,0,0,0,12,0,0,0,0,13,0,1,0,0,0,13,0,0,0,1,13,0,0,14,0,0,0,13,1,0,0,0,14,0,0,0,0,0,12,0,0,0,0,0,19,0,3,11,15,0,0,0,1,0,9,0,0,0,1,0,11,0,0,0,15,0,0,14,0,0,0,19,0,0,0,1,0,7,1,0,0,8,0,0,13,0,0,0,12,0,0,15,9,0,0,0,14,0,12,0,0,1,0,14,0,12],"id":"call_00_p0f6uzlwMZsoKQfC837b1176","name":"run_code","args":["","{","\"","code","\"",": ","\"","const"," fs"," ="," await"," import","(\\\"","node",":","fs","/p","rom","ises","\\\");\\n","const"," c","wd"," ="," process",".c","wd","();\\n","const"," target"," ="," c","wd"," +"," \\\"/","approved",".txt","\\\";\\n","await"," fs",".write","File","(target",","," \\\"","approved","\\\\n","\\\");\\n","const"," back"," ="," await"," fs",".read","File","(target",","," \\\"","utf","8","\\\");\\n","return"," {"," c","wd",","," target",","," content",":"," back",","," bytes",":"," Buffer",".byte","Length","(","back",")"," }",";","\"",", ","\"","description","\"",": ","\"","Write"," approved",".txt"," under"," read","-only"," sand","box","\"",", ","\"","time","out","Ms","\"",": ","120","000","}"]},{"type":"chunk","time":1789145656595,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to use run_code with direct Node filesystem access to create approved.txt. Let me attempt the write under read-only sandbox first without escalation.\n\nLet me write the program.\n\nThe instruction says \"do not call nested tools\" — so inside run_code I should just use node:fs/promises directly, no tools.bash etc.\n\nLet me do that."}}},{"type":"chunk","time":1789145656595,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_p0f6uzlwMZsoKQfC837b1176","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt under read-only sandbox\", \"timeoutMs\": 120000}"}}},{"type":"chunk","time":1789145656595,"chunk":{"type":"usage","usage":{"inputTokens":1347,"outputTokens":230,"totalTokens":9001,"cacheReadTokens":7424,"reasoningTokens":77}}},{"type":"chunk","time":1789145656595,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_p0f6uzlwMZsoKQfC837b1176","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt under read-only sandbox\", \"timeoutMs\": 120000}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_p0f6uzlwMZsoKQfC837b1176"},"content":[{"type":"tool-result","toolCallId":"call_00_p0f6uzlwMZsoKQfC837b1176","content":[{"type":"text","text":"Error: code run failed (exception): Error: EPERM: operation not permitted, open '{{cwd}}/approved.txt'\n at async open (node:internal/fs/promises:697:25)\n at async Module.writeFile (node:internal/fs/promises:1317:14)\n at async eval (eval at runProgram (file:///Users/cty/dsh-ptc-pr3/packages/code-runtime/code-runtime-node/lib/process.js:1029:31), :7:1)\n at async runProgram (file:///Users/cty/dsh-ptc-pr3/packages/code-runtime/code-runtime-node/lib/process.js:1029:25)\n at async runNodeMain (file:///Users/cty/dsh-ptc-pr3/packages/code-runtime/code-runtime-node/lib/process.js:1086:3)\n at async file:///Users/cty/dsh-ptc-pr3/packages/code-runtime/code-runtime-node/lib/process.js:1105:1\nFile sandbox: read-only; enforcement: full; operation denied. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically."}],"isError":true}],"role":"user","id":"{{message:5}}"},"error":{"name":"CodeRunFailedError","code":"CODE_RUN_FAILED"}},"sourceEventSeqs":[18],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The write was denied with EPERM under read-only sandbox. Now retry with sandbox_permissions \"workspace-write\" and the specified justification."},{"type":"text","text":"The read-only sandbox denied the write with `EPERM`. Retrying the same program with the requested escalation."},{"type":"tool-call","id":"call_00_mbdxC6SS8svc8XoECgMN3999","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt with workspace-write escalation\", \"timeoutMs\": 120000, \"sandbox_permissions\": \"workspace-write\", \"justification\": \"Create the file requested by the user\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":401,"outputTokens":254,"totalTokens":9615,"cacheReadTokens":8960,"reasoningTokens":33},"stream":[{"type":"chunk","time":1789145657462,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789145657462,"index":0,"dt":[66,13,0,0,0,0,0,12,0,18,1,0,0,18,0,6,1,0,9,1,0,0,0,0,14,0,0,0,0,13,15,0],"texts":["The"," write"," was"," denied"," with"," E","PER","M"," under"," read","-only"," sand","box","."," Now"," ret","ry"," with"," sand","box","_per","missions"," \"","works","pace","-w","rite","\""," and"," the"," specified"," justification","."]},{"type":"chunk","time":1789145657649,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1789145657649,"index":1,"dt":[0,12,0,13,0,0,0,1,0,13,1,0,0,0,0,21,9,1,0,0,0,13,0],"texts":["The"," read","-only"," sand","box"," denied"," the"," write"," with"," `","EP","ER","M","`."," Ret","rying"," the"," same"," program"," with"," the"," requested"," escalation","."]},{"type":"chunk","time":1789145657759,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789145657759,"index":2,"dt":[16,0,0,0,0,13,0,0,0,0,0,14,0,0,0,0,0,12,0,0,0,0,0,13,1,0,0,0,0,12,0,0,0,0,0,14,0,0,0,1,0,14,0,0,0,23,0,0,0,0,0,2,0,0,0,0,0,14,0,0,0,0,0,12,0,0,0,0,0,14,0,0,0,0,0,13,0,0,0,0,16,1,12,0,0,0,1,10,0,0,0,0,13,0,13,0,0,15,0,0,12,0,0,0,15,0,11,0,14,0,0,0,0,0,44,0,0,0,0,0,0,0,0,0,9,0,0,0,13,0,0,16,0,0,0,11],"id":"call_00_mbdxC6SS8svc8XoECgMN3999","name":"run_code","args":["","{","\"","code","\"",": ","\"","const"," fs"," ="," await"," import","(\\\"","node",":","fs","/p","rom","ises","\\\");\\n","const"," c","wd"," ="," process",".c","wd","();\\n","const"," target"," ="," c","wd"," +"," \\\"/","approved",".txt","\\\";\\n","await"," fs",".write","File","(target",","," \\\"","approved","\\\\n","\\\");\\n","const"," back"," ="," await"," fs",".read","File","(target",","," \\\"","utf","8","\\\");\\n","return"," {"," c","wd",","," target",","," content",":"," back",","," bytes",":"," Buffer",".byte","Length","(","back",")"," }",";","\"",", ","\"","description","\"",": ","\"","Write"," approved",".txt"," with"," workspace","-w","rite"," escalation","\"",", ","\"","time","out","Ms","\"",": ","120","000",", ","\"","sand","box","_per","missions","\"",": ","\"","works","pace","-w","rite","\"",", ","\"","just","ification","\"",": ","\"","Create"," the"," file"," requested"," by"," the"," user","\"","}"]},{"type":"chunk","time":1789145658191,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The write was denied with EPERM under read-only sandbox. Now retry with sandbox_permissions \"workspace-write\" and the specified justification."}}},{"type":"chunk","time":1789145658191,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The read-only sandbox denied the write with `EPERM`. Retrying the same program with the requested escalation."}}},{"type":"chunk","time":1789145658191,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_mbdxC6SS8svc8XoECgMN3999","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt with workspace-write escalation\", \"timeoutMs\": 120000, \"sandbox_permissions\": \"workspace-write\", \"justification\": \"Create the file requested by the user\"}"}}},{"type":"chunk","time":1789145658191,"chunk":{"type":"usage","usage":{"inputTokens":401,"outputTokens":254,"totalTokens":9615,"cacheReadTokens":8960,"reasoningTokens":33}}},{"type":"chunk","time":1789145658191,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_00_mbdxC6SS8svc8XoECgMN3999","name":"run_code","arguments":"{\"code\": \"const fs = await import(\\\"node:fs/promises\\\");\\nconst cwd = process.cwd();\\nconst target = cwd + \\\"/approved.txt\\\";\\nawait fs.writeFile(target, \\\"approved\\\\n\\\");\\nconst back = await fs.readFile(target, \\\"utf8\\\");\\nreturn { cwd, target, content: back, bytes: Buffer.byteLength(back) };\", \"description\": \"Write approved.txt with workspace-write escalation\", \"timeoutMs\": 120000, \"sandbox_permissions\": \"workspace-write\", \"justification\": \"Create the file requested by the user\"}"}} +{"type":"approval/asked","data":{"id":"{{approval:1}}","toolName":"run_code","callId":"call_00_mbdxC6SS8svc8XoECgMN3999","reason":"escalate sandbox to workspace-write: Create the file requested by the user"}} +{"type":"approval/decided","data":{"id":"{{approval:1}}","outcome":"allowed-once"}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_mbdxC6SS8svc8XoECgMN3999"},"content":[{"type":"tool-result","toolCallId":"call_00_mbdxC6SS8svc8XoECgMN3999","content":[{"type":"text","text":"{\n \"cwd\": \"{{cwd}}\",\n \"target\": \"{{cwd}}/approved.txt\",\n \"content\": \"approved\\n\",\n \"bytes\": 9\n}"}],"isError":false}],"role":"user","id":"{{message:7}}"}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"step/start","data":{"turn":1,"step":3}} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":149,"outputTokens":3,"totalTokens":9752,"cacheReadTokens":9600,"reasoningTokens":0},"stream":[{"type":"chunk","time":1789145659021,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789145659022,"index":0,"dt":[13],"texts":["D","ONE"]},{"type":"chunk","time":1789145659035,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1789145659035,"chunk":{"type":"usage","usage":{"inputTokens":149,"outputTokens":3,"totalTokens":9752,"cacheReadTokens":9600,"reasoningTokens":0}}},{"type":"chunk","time":1789145659035,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":3}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/ptc-escalation-approved/snapshot.yml b/snapshots/web/ptc-escalation-approved/snapshot.yml new file mode 100644 index 0000000000..d55fb10c45 --- /dev/null +++ b/snapshots/web/ptc-escalation-approved/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: ptc-escalation-approved +profile: web +composition: web-ptc +recording: live +header: + class: web-ptc +workspace: + final: true diff --git a/snapshots/web/ptc-escalation-approved/workspace.expected/approved.txt b/snapshots/web/ptc-escalation-approved/workspace.expected/approved.txt new file mode 100644 index 0000000000..367ff43054 --- /dev/null +++ b/snapshots/web/ptc-escalation-approved/workspace.expected/approved.txt @@ -0,0 +1 @@ +approved diff --git a/snapshots/web/ptc-round/tool-schemas.expected.json b/snapshots/web/ptc-round/tool-schemas.expected.json index e48595aed7..ed4515dd3d 100644 --- a/snapshots/web/ptc-round/tool-schemas.expected.json +++ b/snapshots/web/ptc-round/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run.", + "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "parameters": { "type": "object", "properties": { @@ -13,6 +13,22 @@ "description": { "type": "string", "description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"." + }, + "timeoutMs": { + "type": "number", + "description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline." + }, + "sandbox_permissions": { + "type": "string", + "description": "Wider sandbox mode for this complete program execution; requires justification and approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Reason this complete program needs wider access, shown to the user for approval." } }, "required": [