feat(ptc): give run_code and PTC runtime failures error codes
run_code argument checks now throw ToolArgsError (INVALID_ARGS), including timeoutMs or sandbox_permissions passed to a runtime whose schema does not expose them; a missing runtime, workingDirectory, or sandboxPolicy throws ToolContextUnavailableError. CodeRunFailedError gains CODE_RUN_UNAVAILABLE after executor disposal, keeping CODE_RUN_FAILED as the default. A runtime rejection without its own code becomes CODE_RUN_FAILED with the rejection as cause; caller cancellation keeps the signal's reason. The PTC runtime Service Definition adds PtcRuntimeError for contract misuse: PTC_RUNTIME_INVALID_ARGUMENT, PTC_RUNTIME_UNAVAILABLE, and PTC_RUNTIME_CONFLICT. The Node runtime throws it for invalid specs and bindings, use after disposal, incomplete retained cleanup, concurrent runs for one owner, and a retained environment under another sandbox policy. dsh-ptc-runtime now declares @deepseek-ai/dsh-error. Refs #7869
This commit is contained in:
1 parent
09bb00b640
commit
6b3023d888
26 files changed
+153
-61
No files matched your search
@@ -225,7 +225,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
|
||||
|
||||
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
|
||||
|
||||
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
|
||||
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -241,7 +241,7 @@ release(owner: object): Promise<void>
|
||||
* Resolve supported options and provider defaults before execution.
|
||||
* @param request - Program, bindings, cancellation and optional execution choices.
|
||||
* @returns Complete directory, deadline and supported authority for run.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
|
||||
*/
|
||||
abstract resolve(request: PtcRunRequest): PtcRunSpec
|
||||
|
||||
|
||||
@@ -225,7 +225,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
|
||||
|
||||
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
|
||||
|
||||
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
|
||||
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -241,7 +241,7 @@ release(owner: object): Promise<void>
|
||||
* Resolve supported options and provider defaults before execution.
|
||||
* @param request - Program, bindings, cancellation and optional execution choices.
|
||||
* @returns Complete directory, deadline and supported authority for run.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
|
||||
*/
|
||||
abstract resolve(request: PtcRunRequest): PtcRunSpec
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 78708b3779d999a9
|
||||
zh: ad6173f9f01630de
|
||||
/deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode:
|
||||
en: 5623dd6cdd26bda2
|
||||
zh: 0b93be49e84ef52c
|
||||
en: 9b4bce1edd565a03
|
||||
zh: e167fb6fa9036b54
|
||||
/deepseek-ai-dsh-tool-executor-ptc/further-exploration:
|
||||
en: ee69078c38c655a9
|
||||
zh: fb0873407f23c8c5
|
||||
|
||||
@@ -62,7 +62,7 @@ New sub-calls use `<parent>:ptc:<n>` ids. Consumers treat these ids as opaque an
|
||||
|
||||
Successful image-bearing subcall results become deferred user-message context with `source.kind` set to `ptc-mode`. Other additional contexts retain their producing tool's attribution.
|
||||
|
||||
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. Cancellation can discard retained runtime state and does not undo completed tool effects.
|
||||
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects.
|
||||
|
||||
`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls.
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ PTC 执行器公开保留的 `run_code` 传输,以及按所加载运行时语
|
||||
|
||||
成功且包含图片的子调用结果会成为延后的 user-message 上下文,其 `source.kind` 为 `ptc-mode`。其他 additional context 保留其生产工具的归属。
|
||||
|
||||
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
|
||||
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
|
||||
|
||||
当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消所有 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。
|
||||
|
||||
|
||||
@@ -20,18 +20,32 @@ export class ToolCallLimitExceededError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every {@link CodeRunFailedError} code:
|
||||
* - `CODE_RUN_FAILED`: the program run failed, or the runtime rejected it without its own error code.
|
||||
* - `CODE_RUN_UNAVAILABLE`: the executor was disposed before the run started.
|
||||
*/
|
||||
export const CODE_RUN_ERROR_CODES = ['CODE_RUN_FAILED', 'CODE_RUN_UNAVAILABLE'] as const
|
||||
|
||||
/** One {@link CodeRunFailedError} code. */
|
||||
export type CodeRunErrorCode = typeof CODE_RUN_ERROR_CODES[number]
|
||||
|
||||
/**
|
||||
* Thrown by `run_code` when the program run itself failed — a program
|
||||
* exception, a budget expiry, a runtime-local abort, or substrate death. Caller
|
||||
* cancellation uses the shared `AbortError` / `ABORTED` tool outcome. Extends
|
||||
* {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
|
||||
* pipeline converts it into a structured `isError` result whose text carries
|
||||
* the failure kind plus the captured logs, so the model can self-correct.
|
||||
* exception, a budget expiry, a runtime-local abort, or substrate death — or
|
||||
* could not start. Caller cancellation uses the shared `AbortError` /
|
||||
* `ABORTED` tool outcome. Extends {@link HarnessError} with a code from
|
||||
* {@link CODE_RUN_ERROR_CODES}; the registry's execution pipeline converts it
|
||||
* into a structured `isError` result whose text carries the failure kind plus
|
||||
* the captured logs, so the model can self-correct.
|
||||
*/
|
||||
export class CodeRunFailedError extends HarnessError {
|
||||
constructor(message: string) {
|
||||
super(message, 'CODE_RUN_FAILED')
|
||||
override readonly code: CodeRunErrorCode
|
||||
|
||||
constructor(message: string, code: CodeRunErrorCode = 'CODE_RUN_FAILED', options?: ErrorOptions) {
|
||||
super(message, code, options)
|
||||
this.name = 'CodeRunFailedError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ export class PtcCalls {
|
||||
await Promise.all(pending.map(call => call.done))
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
if (this.disposed) throw new Error('PTC tool executor disposed')
|
||||
if (this.disposed) throw new CodeRunFailedError('PTC tool executor disposed', 'CODE_RUN_UNAVAILABLE')
|
||||
const controller = new AbortController()
|
||||
const done = Promise.withResolvers<undefined>()
|
||||
const currentSignal = AbortSignal.any([signal, controller.signal])
|
||||
|
||||
@@ -19,7 +19,9 @@ import type {} from '@deepseek-ai/dsh-user-approval'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
import { defineTool, parameterSchemaSpecToJsonSchema, RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
|
||||
import {
|
||||
defineTool, parameterSchemaSpecToJsonSchema, RUN_CODE_NAME, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError,
|
||||
} from '@deepseek-ai/dsh-tools'
|
||||
import type { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { scopeTarget } from '@deepseek-ai/dsh-scope'
|
||||
@@ -81,11 +83,11 @@ const RUN_CODE_FLAVORS = {
|
||||
export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
|
||||
const runtime = ctx.get('ptcRuntime')
|
||||
if (runtime === undefined) {
|
||||
throw new Error('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
|
||||
throw new ToolContextUnavailableError('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
|
||||
}
|
||||
if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language)) {
|
||||
const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ')
|
||||
throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
|
||||
throw new ToolContextUnavailableError(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
|
||||
}
|
||||
return runtime as SupportedPtcRuntime
|
||||
}
|
||||
@@ -253,14 +255,14 @@ type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: PtcRunSandb
|
||||
async function resolveWorkingDirectory(ctx: Context, exec: ToolRunContext): Promise<string | undefined> {
|
||||
if (exec.agent === undefined) return undefined
|
||||
const directories = ctx.get('workingDirectory')
|
||||
if (directories === undefined) throw new Error('dsh-tools: run_code with an Agent requires workingDirectory')
|
||||
if (directories === undefined) throw new ToolContextUnavailableError('dsh-tools: run_code with an Agent requires workingDirectory')
|
||||
return directories.ensure(exec.agent, exec.signal)
|
||||
}
|
||||
|
||||
/** Resolve standing authority for a runtime that enforces file policy. */
|
||||
function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecutionPolicy {
|
||||
const policy = ctx.get('sandboxPolicy')
|
||||
if (policy === undefined) throw new Error('dsh-tools: confined PTC runtime requires sandboxPolicy')
|
||||
if (policy === undefined) throw new ToolContextUnavailableError('dsh-tools: confined PTC runtime requires sandboxPolicy')
|
||||
return policy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
|
||||
}
|
||||
|
||||
@@ -343,21 +345,21 @@ export function createRunCodeTool(
|
||||
},
|
||||
async execute(args, exec): Promise<RunCodeOutput> {
|
||||
if (args.description.trim().length === 0) {
|
||||
throw new Error('invalid description: expected a non-empty string')
|
||||
throw new ToolArgsError(['invalid description: expected a non-empty string'])
|
||||
}
|
||||
const runtime = requirePtcRuntime(ctx)
|
||||
const run = async (callSignal: AbortSignal): Promise<RunCodeOutput> => {
|
||||
validateEscalationArgs(args.sandbox_permissions, args.justification)
|
||||
if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
|
||||
throw new Error('timeoutMs is not available for this PTC runtime')
|
||||
throw new ToolArgsError(['timeoutMs is not available for this PTC runtime'])
|
||||
}
|
||||
if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
|
||||
throw new Error('invalid timeoutMs: expected a positive finite number')
|
||||
throw new ToolArgsError(['invalid timeoutMs: expected a positive finite number'])
|
||||
}
|
||||
const standingPolicy = runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec)
|
||||
let policy = standingPolicy
|
||||
if (args.sandbox_permissions !== undefined && args.justification !== undefined) {
|
||||
if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime')
|
||||
if (standingPolicy === undefined) throw new ToolArgsError(['sandbox_permissions is not available for this PTC runtime'])
|
||||
const approvedMode = await approveEscalation({
|
||||
requestedMode: args.sandbox_permissions,
|
||||
justification: args.justification,
|
||||
@@ -698,6 +700,11 @@ export function createRunCodeTool(
|
||||
maxSubCalls = spec.timeoutMs === null ? Infinity
|
||||
: Math.floor(spec.timeoutMs / 60_000 * maxSubCallsPerMinute)
|
||||
result = await runtime.run(spec)
|
||||
} catch (error) {
|
||||
// Runtimes reject only contract misuse; a rejection without its own code becomes CODE_RUN_FAILED.
|
||||
exec.signal.throwIfAborted()
|
||||
if (error instanceof HarnessError) throw error
|
||||
throw new CodeRunFailedError(`code run failed: ${toolErrorMessage(error)}`, 'CODE_RUN_FAILED', { cause: error })
|
||||
} finally {
|
||||
// Abort sub-dispatches and drain every in-flight dispatch before
|
||||
// closing the turn (queued-unstarted ones are abandoned unlogged).
|
||||
|
||||
@@ -86,6 +86,9 @@ it('unloads the executor only after calls stop and refuses late admission', asyn
|
||||
await rejected
|
||||
await disposed
|
||||
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toThrow('PTC tool executor disposed')
|
||||
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toMatchObject({
|
||||
name: 'CodeRunFailedError', code: 'CODE_RUN_UNAVAILABLE',
|
||||
})
|
||||
} finally { cleanup.resolve(undefined); await first; await disposed }
|
||||
})
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { ToolSchema } from '@deepseek-ai/dsh-llm'
|
||||
import { createScope } from '@deepseek-ai/dsh-scope'
|
||||
import type { Scope } from '@deepseek-ai/dsh-scope'
|
||||
import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
|
||||
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import type { PtcRunFailure, PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import ToolRuntime, { RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
|
||||
@@ -1866,6 +1866,7 @@ describe('the run_code dispatch bridge', () => {
|
||||
const result = await runCode(ctx, 'program')
|
||||
expect(result.isError).toBe(true)
|
||||
expect((result.content[0] as { text: string }).text).toContain('requires a PTC runtime')
|
||||
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
|
||||
})
|
||||
|
||||
it('refuses an agent-owned program before dispatch when its directory owner is missing', async () => {
|
||||
@@ -1889,6 +1890,7 @@ describe('the run_code dispatch bridge', () => {
|
||||
expect(result.content).toEqual([{
|
||||
type: 'text', text: 'Error: dsh-tools: run_code with an Agent requires workingDirectory',
|
||||
}])
|
||||
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
|
||||
expect(runtime.lastRequest).toBeUndefined()
|
||||
expect(calls).toEqual([])
|
||||
expect(events).toEqual([])
|
||||
@@ -1910,11 +1912,25 @@ describe('the run_code dispatch bridge', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies runtime rejections, keeping a runtime error code', async () => {
|
||||
const { ctx, runtime } = await setup({ mode: 'ptc' })
|
||||
const misuse = new TypeError('runtime contract violated')
|
||||
runtime.behavior = () => Promise.reject(misuse)
|
||||
const failed = await runCode(ctx, 'return 1')
|
||||
expect(failed.error).toEqual({
|
||||
message: 'code run failed: runtime contract violated',
|
||||
info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' },
|
||||
})
|
||||
runtime.behavior = () => Promise.reject(new PtcRuntimeError('ptc-runtime-node: run after disposal', 'PTC_RUNTIME_UNAVAILABLE'))
|
||||
expect((await runCode(ctx, 'return 1')).error?.info).toEqual({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
|
||||
})
|
||||
|
||||
it('rejects a whitespace-only description with a structured isError', async () => {
|
||||
const { ctx } = await setup({ mode: 'ptc' })
|
||||
const result = await runCode(ctx, 'return 1', { description: ' ' })
|
||||
expect(result.isError).toBe(true)
|
||||
expect((result.content[0] as { text: string }).text).toContain('invalid description')
|
||||
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -2644,6 +2660,7 @@ describe('PTC standing file policy and sandbox outcomes', () => {
|
||||
const result = await runCode(ctx, 'return 1')
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.content).toEqual([{ type: 'text', text: 'Error: dsh-tools: confined PTC runtime requires sandboxPolicy' }])
|
||||
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
|
||||
expect((ctx.ptcRuntime as ConfinedFakeRuntime).lastRequest).toBeUndefined()
|
||||
} finally { await ctx.fiber.dispose() }
|
||||
})
|
||||
@@ -2751,6 +2768,7 @@ describe('per-program execution controls', () => {
|
||||
arguments: { code: 'pass', description: 'Try unsupported timeout', timeoutMs: 5 },
|
||||
})
|
||||
expect(rejected.isError).toBe(true)
|
||||
expect(rejected.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
|
||||
expect(python.runtime.lastRequest).toBeUndefined()
|
||||
} finally { await python.ctx.fiber.dispose() }
|
||||
})
|
||||
@@ -2758,7 +2776,9 @@ describe('per-program execution controls', () => {
|
||||
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, '1000', null])('rejects invalid timeout %s before runtime execution', async (timeoutMs) => {
|
||||
const { ctx, runtime, execute } = await controlledSetup()
|
||||
try {
|
||||
expect((await execute({ timeoutMs })).isError).toBe(true)
|
||||
const result = await execute({ timeoutMs })
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
|
||||
expect(runtime.lastRequest).toBeUndefined()
|
||||
} finally { await ctx.fiber.dispose() }
|
||||
})
|
||||
@@ -2772,6 +2792,7 @@ describe('per-program execution controls', () => {
|
||||
})
|
||||
expect(result.isError).toBe(true)
|
||||
expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this PTC runtime')
|
||||
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
|
||||
expect(runtime.lastRequest).toBeUndefined()
|
||||
} finally { await ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
@@ -2573,7 +2573,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
{
|
||||
key: 'ptcRuntime',
|
||||
summary: 'Registers one `ctx.ptcRuntime` implementation.',
|
||||
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
|
||||
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
|
||||
methods: [
|
||||
{
|
||||
signature: 'abstract readonly language: string',
|
||||
@@ -2597,7 +2597,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
description: 'Resolve supported options and provider defaults before execution.',
|
||||
parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }],
|
||||
returns: 'Complete directory, deadline and supported authority for run.',
|
||||
throws: ['When an explicit choice is invalid or unsupported by this provider.'],
|
||||
throws: ['When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.'],
|
||||
},
|
||||
{
|
||||
signature: 'abstract run(spec: PtcRunSpec): Promise<PtcRunResult>',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Validate and capture the binding names available to one program. */
|
||||
import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, PtcRuntimeError, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import type { PtcBindingFunction, PtcBindingNamespace, PtcJsonValue, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
import { encodePtcJsonWire, type PtcJsonWire } from './json-wire.ts'
|
||||
@@ -13,7 +13,7 @@ export function validateBindings(request: PtcRunRequest): Map<string, PtcBinding
|
||||
const bindings = new Map<string, PtcBindingNamespace>()
|
||||
for (const namespace of request.bindings) {
|
||||
if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
// RESERVED_BINDING_GLOBALS is the seam's shared backend-owned set:
|
||||
// `console` is THIS backend's log-capture slot; the dunder entries exist
|
||||
@@ -22,10 +22,10 @@ export function validateBindings(request: PtcRunRequest): Map<string, PtcBinding
|
||||
// portable across backends. The seam declaration is the single home for
|
||||
// why each entry is reserved.
|
||||
if (RESERVED_BINDING_GLOBALS.has(namespace.global)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
if (bindings.has(namespace.global)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
bindings.set(namespace.global, namespace)
|
||||
}
|
||||
@@ -35,17 +35,17 @@ export function validateBindings(request: PtcRunRequest): Map<string, PtcBinding
|
||||
const descriptor = namespace.errorClass
|
||||
if (!descriptor) continue
|
||||
if (!IDENTIFIER.test(descriptor.name) || PORTABLE_RESERVED_WORDS.has(descriptor.name)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
const member = descriptor.memberNameProperty
|
||||
if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member) || DUNDER_MEMBER.test(member)) {
|
||||
throw new Error(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`)
|
||||
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
}
|
||||
errorClassNames.add(descriptor.name)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { stripTypeScriptTypes } from 'node:module'
|
||||
import { isAbsolute } from 'node:path'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { PtcRuntimeError, type PtcProgramFormat, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { clampTimeout } from '@deepseek-ai/dsh-timeout'
|
||||
import type { ResolvedConfig } from './config.ts'
|
||||
@@ -72,7 +72,7 @@ class NodeExecution {
|
||||
resolve(request: PtcRunRequest): PtcRunSpec {
|
||||
const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
|
||||
const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
|
||||
if (!isAbsolute(cwd)) throw new Error(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`)
|
||||
if (!isAbsolute(cwd)) throw new PtcRuntimeError(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
return { ...request, sandboxPolicy, cwd, timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, this.mode.retainsState ? 'persistent PTC timeoutMs' : 'ptc-runtime-node: timeoutMs') }
|
||||
}
|
||||
|
||||
@@ -82,8 +82,8 @@ class NodeExecution {
|
||||
* @returns Captured logs, JSON completion, or a structured execution failure.
|
||||
*/
|
||||
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
||||
if (spec.sandboxPolicy === undefined) throw new Error('ptc-runtime-node: run requires a resolved sandbox policy')
|
||||
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new Error('ptc-runtime-node: run requires resolved cwd and timeout')
|
||||
if (spec.sandboxPolicy === undefined) throw new PtcRuntimeError('ptc-runtime-node: run requires a resolved sandbox policy', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new PtcRuntimeError('ptc-runtime-node: run requires resolved cwd and timeout', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
||||
const bindings = validateBindings(spec)
|
||||
const owner = this.mode.retainsState ? spec.stateOwner : undefined
|
||||
let worker = owner === undefined ? undefined : this.owners.get(owner)
|
||||
@@ -91,7 +91,7 @@ class NodeExecution {
|
||||
if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode
|
||||
|| worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot
|
||||
|| worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) {
|
||||
throw new Error('persistent PTC: release the retained environment before changing its sandbox policy')
|
||||
throw new PtcRuntimeError('persistent PTC: release the retained environment before changing its sandbox policy', 'PTC_RUNTIME_CONFLICT')
|
||||
}
|
||||
// Retained processes keep their launch-time directory grants until release.
|
||||
if (!worker || worker.closed) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Node PTC provider with uniform admission and configurable evaluation and process ownership. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
@@ -65,7 +65,7 @@ export class NodePtcRuntime extends PtcRuntime {
|
||||
resolve(request: PtcRunRequest): PtcRunSpec {
|
||||
if (this.disposed) {
|
||||
const source = this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'
|
||||
throw new Error(`${source}: resolve after disposal`)
|
||||
throw new PtcRuntimeError(`${source}: resolve after disposal`, 'PTC_RUNTIME_UNAVAILABLE')
|
||||
}
|
||||
return this.execution.resolve(request)
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export class NodePtcRuntime extends PtcRuntime {
|
||||
* @returns Logs, JSON completion or failure; retained processes remain until release or invalidation.
|
||||
*/
|
||||
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
||||
if (this.disposed) throw new Error('ptc-runtime-node: run after disposal')
|
||||
if (this.disposed) throw new PtcRuntimeError('ptc-runtime-node: run after disposal', 'PTC_RUNTIME_UNAVAILABLE')
|
||||
const controller = new AbortController()
|
||||
const completion = Promise.withResolvers<void>()
|
||||
const unregister = spec.sandboxPolicy === undefined ? undefined : this.processes.register(spec.sandboxPolicy, async () => {
|
||||
@@ -90,7 +90,7 @@ export class NodePtcRuntime extends PtcRuntime {
|
||||
await this.processes.wait(spec.sandboxPolicy?.sessionId)
|
||||
// Disposal can begin while a previous policy's process cleanup is pending.
|
||||
// oxlint-disable-next-line typescript/no-unnecessary-condition
|
||||
if (this.disposed) throw new Error(`${this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: run after disposal`)
|
||||
if (this.disposed) throw new PtcRuntimeError(`${this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: run after disposal`, 'PTC_RUNTIME_UNAVAILABLE')
|
||||
const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal])
|
||||
return await this.execution.run({ ...spec, signal })
|
||||
} finally {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Managed Node process shared by temporary and owner-retained evaluations. */
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { PtcRunSpec, PtcRunResult, PtcRunSandbox, PtcRunFailure, PtcBindingNamespace, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { PtcRuntimeError, type PtcRunSpec, type PtcRunResult, type PtcRunSandbox, type PtcRunFailure, type PtcBindingNamespace, type PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox'
|
||||
import type { ConfinedArgv, SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
||||
import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
|
||||
@@ -74,8 +74,8 @@ export class ProgramWorker {
|
||||
|
||||
/** Reject reuse until the previous evaluation and required cleanup settle. */
|
||||
assertIdle(): void {
|
||||
if (this.running) throw new Error('persistent PTC does not accept concurrent runs for one state owner')
|
||||
if (this.cleanupPending) throw new Error('persistent PTC environment cleanup is incomplete; release the owner before running another program')
|
||||
if (this.running) throw new PtcRuntimeError('persistent PTC does not accept concurrent runs for one state owner', 'PTC_RUNTIME_CONFLICT')
|
||||
if (this.cleanupPending) throw new PtcRuntimeError('persistent PTC environment cleanup is incomplete; release the owner before running another program', 'PTC_RUNTIME_UNAVAILABLE')
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { validateBindings } from '../src/bindings.ts'
|
||||
|
||||
const INVALID_ARGUMENT = { name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT' }
|
||||
|
||||
describe('program binding validation', () => {
|
||||
it.each(['$name', '', 'while', 'lambda', 'console'])('rejects unusable global %s', (global) => {
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global, functions: {} }] })).toThrow()
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global, functions: {} }] })).toThrow(expect.objectContaining(INVALID_ARGUMENT))
|
||||
})
|
||||
it('rejects duplicated globals and accepts arbitrary own member names', () => {
|
||||
const functions = Object.create(null) as Record<string, () => Promise<string>>
|
||||
@@ -12,10 +14,10 @@ describe('program binding validation', () => {
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions }, { global: 'tools', functions }] })).toThrow('duplicate')
|
||||
})
|
||||
it.each(['$name', 'while', 'console', 'tools'])('rejects invalid error class name %s', (name) => {
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name, memberNameProperty: 'member' } }] })).toThrow()
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name, memberNameProperty: 'member' } }] })).toThrow(expect.objectContaining(INVALID_ARGUMENT))
|
||||
})
|
||||
it.each(['', 'name', '__member__'])('rejects invalid error member %s', (memberNameProperty) => {
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolError', memberNameProperty } }] })).toThrow()
|
||||
expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolError', memberNameProperty } }] })).toThrow(expect.objectContaining(INVALID_ARGUMENT))
|
||||
})
|
||||
it('rejects two injected constructors with the same name', () => {
|
||||
expect(() => validateBindings({ program: '', bindings: ['first', 'second'].map(global => ({ global, functions: {}, errorClass: { name: 'ToolError', memberNameProperty: 'member' } })) })).toThrow('duplicate')
|
||||
|
||||
@@ -58,13 +58,18 @@ describe('Node runtime host failures', () => {
|
||||
const h = await setup({}, 'read-only')
|
||||
expect(h.runtime.sandboxMode).toBe('read-only')
|
||||
expect(() => h.runtime.resolve({ ...request, cwd: 'relative' })).toThrow('cwd must be absolute')
|
||||
expect(() => h.runtime.resolve({ ...request, cwd: 'relative' })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT' }))
|
||||
await expect(h.runtime.run({ ...request, cwd: process.cwd(), timeoutMs: 1 })).rejects.toThrow('resolved sandbox policy')
|
||||
await expect(h.runtime.run({ ...request, cwd: process.cwd(), timeoutMs: 1 })).rejects.toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT' })
|
||||
const spec = h.runtime.resolve(request)
|
||||
await expect(h.runtime.run({ ...spec, timeoutMs: Infinity })).rejects.toThrow('resolved cwd and timeout')
|
||||
await expect(h.runtime.run({ ...spec, timeoutMs: Infinity })).rejects.toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT' })
|
||||
expect(h.spawn).not.toHaveBeenCalled()
|
||||
await h.ctx.fiber.dispose()
|
||||
expect(() => h.runtime.resolve(request)).toThrow('resolve after disposal')
|
||||
expect(() => h.runtime.resolve(request)).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' }))
|
||||
await expect(h.runtime.run(spec)).rejects.toThrow('run after disposal')
|
||||
await expect(h.runtime.run(spec)).rejects.toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
|
||||
})
|
||||
|
||||
it('fails a required unavailable sandbox before spawning', async () => {
|
||||
|
||||
@@ -321,6 +321,7 @@ describe.each([
|
||||
await entered.promise
|
||||
await expect(run('1')).rejects.toThrow('concurrent runs')
|
||||
await expect(run('const =')).rejects.toThrow('concurrent runs')
|
||||
await expect(run('1')).rejects.toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_CONFLICT' })
|
||||
expect((await run('2', { stateOwner: {} })).value).toBe(2)
|
||||
} finally { proceed.resolve(null) }
|
||||
expect((await pending).value).toBeNull()
|
||||
|
||||
@@ -203,6 +203,7 @@ it('blocks reuse after fallback cleanup fails until release succeeds', async ()
|
||||
await vi.advanceTimersByTimeAsync(150)
|
||||
expect((await pending).error?.message).toContain('managed process cleanup failed: exit not confirmed')
|
||||
await expect(h.runtime.run(h.runtime.resolve(h.request))).rejects.toThrow('cleanup is incomplete')
|
||||
await expect(h.runtime.run(h.runtime.resolve(h.request))).rejects.toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
|
||||
await h.runtime.release(h.request.stateOwner)
|
||||
const replacement = fakeChild(h.ctx, h.runtime, h.request)
|
||||
replacement.onBoot(() => { replacement.complete({}) })
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
en: 4e46c1672701b8df
|
||||
zh: 0353c5855c9ff6be
|
||||
/deepseek-ai-dsh-ptc-runtime/use-this-package/what-can-go-wrong:
|
||||
en: 44f9fdf2c8e2cacc
|
||||
zh: 99dd555a49075f88
|
||||
en: 35129568fa436d64
|
||||
zh: 0f4138ad427ef486
|
||||
/deepseek-ai-dsh-ptc-runtime/understand-the-implementation:
|
||||
en: 686d570f5e669fa4
|
||||
zh: 2075cf27c30f251a
|
||||
|
||||
@@ -52,7 +52,7 @@ Binding-global and error-class names are language-portable: they must match `[A-
|
||||
|
||||
### What can go wrong
|
||||
|
||||
Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal.
|
||||
Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal. Contract misuse rejects with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for an invalid request or spec, `PTC_RUNTIME_UNAVAILABLE` after disposal or while a retained environment's cleanup is incomplete, and `PTC_RUNTIME_CONFLICT` for a concurrent run for one owner or a retained environment launched under another sandbox policy.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配 `[A-Za
|
||||
|
||||
### 可能出什么问题
|
||||
|
||||
失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。
|
||||
失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。契约误用以 `PtcRuntimeError` 拒绝:无效的请求或 spec 为 `PTC_RUNTIME_INVALID_ARGUMENT`,资源释放后或保留环境清理未完成时为 `PTC_RUNTIME_UNAVAILABLE`,同一所有者的并发运行或保留环境以其他沙箱策略启动时为 `PTC_RUNTIME_CONFLICT`。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -31,10 +31,12 @@
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-sandbox": "workspace:*"
|
||||
"@deepseek-ai/dsh-sandbox": "workspace:*",
|
||||
"@deepseek-ai/dsh-error": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-sandbox": "workspace:*"
|
||||
"@deepseek-ai/dsh-sandbox": "workspace:*",
|
||||
"@deepseek-ai/dsh-error": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-error'
|
||||
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from './types.ts'
|
||||
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
||||
|
||||
@@ -95,10 +96,39 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every {@link PtcRuntimeError} code:
|
||||
* - `PTC_RUNTIME_UNAVAILABLE`: the runtime was disposed, or a retained environment's cleanup is
|
||||
* incomplete; release the owner or reload the runtime before running more programs.
|
||||
* - `PTC_RUNTIME_CONFLICT`: a program is already running for the same state owner, or the owner's
|
||||
* retained environment was launched under a different sandbox policy; wait, or release the owner.
|
||||
* - `PTC_RUNTIME_INVALID_ARGUMENT`: the consumer passed a request or spec that violates this contract,
|
||||
* such as a relative `cwd` or an unresolved spec.
|
||||
*/
|
||||
export const PTC_RUNTIME_ERROR_CODES = [
|
||||
'PTC_RUNTIME_UNAVAILABLE',
|
||||
'PTC_RUNTIME_CONFLICT',
|
||||
'PTC_RUNTIME_INVALID_ARGUMENT',
|
||||
] as const
|
||||
|
||||
/** One {@link PtcRuntimeError} code. */
|
||||
export type PtcRuntimeErrorCode = typeof PTC_RUNTIME_ERROR_CODES[number]
|
||||
|
||||
/** Contract misuse a {@link PtcRuntime} rejects; `code` is one of {@link PTC_RUNTIME_ERROR_CODES}. */
|
||||
export class PtcRuntimeError extends HarnessError {
|
||||
override readonly code: PtcRuntimeErrorCode
|
||||
|
||||
constructor(message: string, code: PtcRuntimeErrorCode, options?: ErrorOptions) {
|
||||
super(message, code, options)
|
||||
this.name = 'PtcRuntimeError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate
|
||||
* failures resolve in {@link PtcRunResult}; only Service Definition contract misuse rejects. Implementations bridge
|
||||
* structured-cloneable bindings, materialize each declared namespace rejection
|
||||
* failures resolve in {@link PtcRunResult}; only Service Definition contract misuse rejects, with
|
||||
* {@link PtcRuntimeError}. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection
|
||||
* class, treat programs as hostile peers, isolate distinct state owners, and
|
||||
* terminate and await in-flight runs during disposal.
|
||||
*/
|
||||
@@ -154,7 +184,7 @@ export abstract class PtcRuntime extends Service {
|
||||
* Resolve supported options and provider defaults before execution.
|
||||
* @param request - Program, bindings, cancellation and optional execution choices.
|
||||
* @returns Complete directory, deadline and supported authority for run.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider.
|
||||
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
|
||||
*/
|
||||
abstract resolve(request: PtcRunRequest): PtcRunSpec
|
||||
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../../sandbox/sandbox"
|
||||
},
|
||||
{
|
||||
"path": "../../util/error"
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+3
@@ -14148,6 +14148,9 @@ importers:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
version: link:../../../vendor/cordis
|
||||
'@deepseek-ai/dsh-error':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/error
|
||||
'@deepseek-ai/dsh-sandbox':
|
||||
specifier: workspace:*
|
||||
version: link:../../sandbox/sandbox
|
||||
|
||||
Reference in new issue
Block a user