From 1a88607c1eb6788bfada2ef0faf2d6920350a56a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:35:54 +0000 Subject: [PATCH 1/5] fix(runtime): an action body that runs out of time answers a sentence naming the action and its limit The action arm of the sandbox budget error now carries a caller sentence (the action's name and the limit it hit, in ms) at a declared 500 with no code, so the /actions door and MCP run_action answer 500 INTERNAL_ERROR with that sentence instead of the bare "Internal server error". A crash stays sanitised; a hook's or a job's timeout is unchanged; the declared 500 keeps the sentence off the /data door. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .changeset/35027-action-timeout-sentence.md | 12 +++ content/docs/api/error-catalog.mdx | 3 +- packages/mcp/src/mcp-coded-refusal.test.ts | 22 ++++ .../sandbox-unreadable-rejection-door.test.ts | 4 + .../runtime/src/sandbox/quickjs-runner.ts | 53 +++++++++- .../sandboxed-action-crash-is-a-fault.test.ts | 100 ++++++++++++++++++ .../unreadable-rejection-recorded.test.ts | 7 +- 7 files changed, 196 insertions(+), 5 deletions(-) create mode 100644 .changeset/35027-action-timeout-sentence.md diff --git a/.changeset/35027-action-timeout-sentence.md b/.changeset/35027-action-timeout-sentence.md new file mode 100644 index 00000000000..b9fbb3f53b0 --- /dev/null +++ b/.changeset/35027-action-timeout-sentence.md @@ -0,0 +1,12 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): an action body that runs out of time answers a sentence naming the action and its limit, at the same `500 INTERNAL_ERROR` + +Clause-②: no +Metadata-protocol: none + +An action body that hit its time limit answered `500 INTERNAL_ERROR "Internal server error"` on the `/actions` door and MCP `run_action`, naming neither the action nor the limit, so a caller (an AI agent above all) could not tell a slow action from a broken platform. It now answers the same status and code with the sentence `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.`, where `N` is the CPU-time budget the body ran under (its `body.timeoutMs`, the enclosing timeout, or the `OS_SANDBOX_ACTION_TIMEOUT_MS` default). A body stuck waiting on platform calls past the wall-clock ceiling answers `Action 'NAME' timed out: it exceeded its N ms time limit while waiting on platform calls, and was stopped.` Both doors read one reader, so they answer the same sentence. The server log line is unchanged (`action 'NAME' exceeded CPU budget of Nms (after P pump iterations)`). + +Nothing else moves. A body that crashes (a `TypeError`, say) still answers the sanitised `500 "Internal server error"`, because its own text may carry the data it was reading. A hook's or a job's timeout is unchanged: it carries no caller sentence, and the `/data` door and import rows answer it as before. The action's sentence is declared at `500`, so the `/data` door, which relays a sandbox sentence only below the server band, never serves it as business text. diff --git a/content/docs/api/error-catalog.mdx b/content/docs/api/error-catalog.mdx index 89ba645ac1b..59404b8aac9 100644 --- a/content/docs/api/error-catalog.mdx +++ b/content/docs/api/error-catalog.mdx @@ -708,7 +708,8 @@ value directly (single wrap). | Caller lacks `requiredPermissions` | **403** | `{ success: false, error: { message, code } }` | | Type has no server dispatch (`url`/`modal`/`form`/`api`), or a param-contract violation | **400** | `{ success: false, error: { message, code } }` | | Data engine or automation service unavailable | **503** | `{ success: false, error: { message, code } }` | -| Handler **crashed** (`TypeError`, driver error, sandbox timeout) | **500** | `{ success: false, error: { message, code } }` | +| Handler **crashed** (`TypeError`, driver error) | **500** | `{ success: false, error: { message, code } }` | +| Sandboxed body **timed out** (its CPU-time limit, or the wall-clock ceiling while waiting on platform calls) | **500** | `{ success: false, error: { message, code: 'INTERNAL_ERROR' } }` — `message` names the action and its limit: `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.` (the ceiling's adds `while waiting on platform calls`). MCP `run_action` answers the same sentence. A crash's own text is never served; a hook's or a job's timeout keeps `Internal server error` | | Sandboxed body **does not compile** in its `(async (input, ctx) => { … })` wrapper | **500** | `{ success: false, error: { message, code: 'INTERNAL_ERROR' } }` — `message` names the action and the compile error | A rejection and a crash are told apart by the thrown error: a plain diff --git a/packages/mcp/src/mcp-coded-refusal.test.ts b/packages/mcp/src/mcp-coded-refusal.test.ts index e091b7a493a..c5ba51acf7d 100644 --- a/packages/mcp/src/mcp-coded-refusal.test.ts +++ b/packages/mcp/src/mcp-coded-refusal.test.ts @@ -990,6 +990,28 @@ describe('run_action / resume_run: a throw answers what the /actions door answer expect([door.code, door.declaredCode, door.status]).toEqual([error.code, error.declaredCode, error.status]); }); + it(`${site.tool}: an action body that timed out answers the door's 500 INTERNAL_ERROR with the sentence naming the action and its limit`, async () => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}); + // The shape `QuickJSScriptRunner` raises for an action that ran out of + // time (`@objectstack/runtime`'s `sandboxed-action-crash-is-a-fault.test.ts` + // measures it on a real run and on the HTTP door): the operator line in + // `.message`, the caller sentence in `innerMessage`, a declared 500, no code. + const sentence = "Action 'demo_leave_body' timed out: it exceeded its 50 ms time limit and was stopped."; + const thrown = () => Object.assign( + new Error("action 'demo_leave_body' exceeded CPU budget of 50ms (after 3 pump iterations)"), + { name: 'SandboxError', innerMessage: sentence, status: 500 }, + ); + const result = await callTool(site, thrown()); + expect(result.isError).toBe(true); + const { error } = JSON.parse(String(result.content[0].text)); + expect(error).toEqual({ code: 'INTERNAL_ERROR', message: sentence, status: 500 }); + const door = actionsDoorAnswerOf(thrown()); + expect(error).toEqual({ code: door.code, message: door.message, status: door.status }); + // The operator line reaches the log, and never the tool result. + expect(log).toHaveBeenCalledTimes(1); + expect(String(result.content[0].text)).not.toContain('pump iterations'); + }); + it(`${site.tool}: a fault carries no thrown details; a refusal still does`, async () => { vi.spyOn(console, 'error').mockImplementation(() => {}); const details = { host: 'db-primary.internal', pool: 'writer' }; diff --git a/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts b/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts index ddfcf7c0f00..f58dfb9753c 100644 --- a/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts +++ b/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts @@ -158,5 +158,9 @@ describe('[#23723] CONTROL — the door\'s other answers stand', () => { const response = await postAction('never_settles'); expect(response.status, JSON.stringify(response.body)).toBe(500); expect(response.body?.error?.code).toBe('INTERNAL_ERROR'); + // The timeout names the action and its limit, never a refusal. + expect(response.body?.error?.message).toBe( + `Action 'never_settles' timed out: it exceeded its ${CEILING_MS} ms time limit while waiting on platform calls, and was stopped.`, + ); }); }); diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 571aa67e747..bd707882481 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -238,13 +238,33 @@ export class QuickJSScriptRunner implements ScriptRunner { // Map a settled-VM state to the right budget error, or null if the body is // simply still progressing. Callers add the just-run slice to `cpuMs` first, // so `cpuMs` here is inclusive. + // + // An ACTION's timeout carries a caller sentence naming the action and its + // limit ({@link actionTimeoutSentence}); a hook's or a job's does not, and + // keeps the bare fault every door answers with the sanitised 500. Each + // construction keeps its message a literal template, which is what the core + // sandbox-fault census renders. const budgetError = (pumps: number): SandboxError | null => { if (cpuMs > cpuBudget) { + if (args.origin.kind === 'action') { + return new SandboxError( + `action '${args.origin.name}' exceeded CPU budget of ${cpuBudget}ms (after ${pumps} pump iterations)`, + actionTimeoutSentence(args.origin.name, cpuBudget, false), + { status: 500 }, + ); + } return new SandboxError( `${args.origin.kind} '${args.origin.name}' exceeded CPU budget of ${cpuBudget}ms (after ${pumps} pump iterations)`, ); } if (Date.now() > wallDeadline) { + if (args.origin.kind === 'action') { + return new SandboxError( + `action '${args.origin.name}' exceeded wall-clock ceiling of ${wallCeiling}ms while awaiting host calls (after ${pumps} pump iterations)`, + actionTimeoutSentence(args.origin.name, wallCeiling, true), + { status: 500 }, + ); + } return new SandboxError( `${args.origin.kind} '${args.origin.name}' exceeded wall-clock ceiling of ${wallCeiling}ms while awaiting host calls (after ${pumps} pump iterations)`, ); @@ -2412,6 +2432,31 @@ function actionBodyCompileFailure(actionName: string, compilerError: string): Sa ); } +/** + * The caller sentence an action that ran out of time answers with: the action's + * name and the limit it hit, in milliseconds, and nothing the body was doing. + * + * A timeout is neither a refusal nor a crash. It stays a server fault, so the + * declared status is `500` and no code is declared: the doors answer the + * status's own `INTERNAL_ERROR` and relay this sentence, as they do for an + * action body that does not compile ({@link actionBodyCompileFailure}). What + * the sentence adds is the one fact a caller cannot get any other way: this + * action was slow, the platform did not break. A crash keeps the sanitised + * `Internal server error`, because its native text may carry the data the body + * was reading; a limit and a name carry none. + * + * Actions only. A hook's or a job's timeout keeps no `innerMessage`, so the + * `/data` door and the import rows answer it as the sandbox's own fault, as + * before. The declared `500` is also what keeps this sentence off the `/data` + * door should an action's timeout ever reach it: that door relays an + * `innerMessage` only below the server band. + */ +function actionTimeoutSentence(actionName: string, limitMs: number, waitingOnHostCalls: boolean): string { + return waitingOnHostCalls + ? `Action '${actionName}' timed out: it exceeded its ${limitMs} ms time limit while waiting on platform calls, and was stopped.` + : `Action '${actionName}' timed out: it exceeded its ${limitMs} ms time limit and was stopped.`; +} + function formatErr(err: unknown): string { if (err && typeof err === 'object') { const o = err as { message?: string; name?: string; stack?: string }; @@ -2427,8 +2472,12 @@ export class SandboxError extends Error { * message without the ` '' threw:` debug wrapper that lives in * `.message`. Safe to surface to end users (e.g. an action's error toast); * the wrapped `.message` stays for server logs. Undefined for the sandbox's - * own internal errors (timeouts, marshalling failures), which have no - * user-meaningful inner message. + * own internal errors (a hook's or a job's timeout, marshalling failures), + * which have no user-meaningful inner message. + * + * An ACTION's timeout is not one of those either: it carries the sentence + * naming the action and the limit it hit, at a declared `500` + * (`actionTimeoutSentence`). * * [#26903/#26965] A capability denial is not one of those: it is a refusal * naming the body and the capability, so it carries this field and its diff --git a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts index 7e44fa1279f..06eb2be8c3d 100644 --- a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts +++ b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts @@ -29,6 +29,7 @@ import { describe, it, expect, vi } from 'vitest'; import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; import type { ScriptRunOptions } from './script-runner.js'; import { HttpDispatcher } from '../http-dispatcher.js'; +import { actionsDoorAnswerOf, INTERNAL_ERROR_MESSAGE, mapDataError } from '@objectstack/types'; // Paid during collection, never inside a case's clocked window: the door's // reach loads this package lazily (`check:test-source-alias`). import '@objectstack/metadata'; @@ -177,3 +178,102 @@ describe('an action body that does not compile answers naming the action and the expect(response.body.error.message).toBe('Internal server error'); }); }); + +/** + * An action body that runs out of time answers a sentence naming the action and + * the limit it hit, at the same `500 INTERNAL_ERROR` as before; a crash keeps + * the sanitised sentence; a hook's or a job's timeout is unchanged. + * + * Both doors are measured on a REAL timeout, produced by running the body: the + * `/actions` HTTP door through the real dispatcher, and the MCP `run_action` + * tool through the one reader it renders a throw with (`actionsDoorAnswerOf`, + * whose envelope `@objectstack/mcp`'s `mcp-coded-refusal.test.ts` pins on the + * tool itself). The `/data` door is measured through its classifier + * (`mapDataError`). + */ +describe('an action body that times out answers naming the action and its limit', () => { + const CPU_SENTENCE = "Action 'submit_signoff' timed out: it exceeded its 50 ms time limit and was stopped."; + const WALL_SENTENCE = + "Action 'submit_signoff' timed out: it exceeded its 300 ms time limit while waiting on platform calls, and was stopped."; + + /** A body that burns its 50 ms CPU budget. */ + async function cpuTimeout(opts: ScriptRunOptions = actionOpts): Promise { + const e = await runner + .runScript({ language: 'js', source: 'while (true) {}', capabilities: [], timeoutMs: 50 }, { input: {} }, opts) + .then(() => null, (err) => err as SandboxError); + expect(e, 'expected the body to time out, but the script resolved').toBeInstanceOf(SandboxError); + return e!; + } + + /** A body stuck on a promise that never settles, cut at a 300 ms wall ceiling. */ + async function wallTimeout(): Promise { + const e = await new QuickJSScriptRunner({ actionTimeoutMs: 250, wallCeilingMs: 300 }) + .runScript({ language: 'js', source: 'await new Promise(() => {});', capabilities: [] }, { input: {} }, actionOpts) + .then(() => null, (err) => err as SandboxError); + expect(e, 'expected the body to time out, but the script resolved').toBeInstanceOf(SandboxError); + return e!; + } + + it('the runner keeps its operator line, and declares 500 with the sentence and no code', async () => { + const cpu = await cpuTimeout(); + expect(cpu.message).toMatch(/^action 'submit_signoff' exceeded CPU budget of 50ms \(after \d+ pump iterations\)$/); + expect(cpu.innerMessage).toBe(CPU_SENTENCE); + expect(cpu.status).toBe(500); + expect(cpu.code).toBeUndefined(); + + const wall = await wallTimeout(); + expect(wall.message).toMatch(/^action 'submit_signoff' exceeded wall-clock ceiling of 300ms while awaiting host calls/); + expect(wall.innerMessage).toBe(WALL_SENTENCE); + expect(wall.status).toBe(500); + expect(wall.code).toBeUndefined(); + }); + + it('the /actions door and the MCP run_action reader answer 500 INTERNAL_ERROR with the same sentence', async () => { + for (const [produce, sentence] of [[cpuTimeout, CPU_SENTENCE], [wallTimeout, WALL_SENTENCE]] as const) { + const response = await throughActionsDoor(await produce()); + expect(response.status).toBe(500); + expect(response.body.error.code).toBe('INTERNAL_ERROR'); + expect(response.body.error.message).toBe(sentence); + + const mcp = actionsDoorAnswerOf(await produce(), 'crm_invoice'); + expect({ status: mcp.status, code: mcp.code, message: mcp.message }).toEqual({ + status: response.status, + code: response.body.error.code, + message: response.body.error.message, + }); + } + }); + + it('control: a crash beside it keeps the sanitised 500 on both doors, naming nothing', async () => { + const response = await throughActionsDoor(await realCrash()); + const mcp = actionsDoorAnswerOf(await realCrash(), 'crm_invoice'); + for (const answer of [ + { status: response.status, code: response.body.error.code, message: response.body.error.message }, + { status: mcp.status, code: mcp.code, message: mcp.message }, + ]) { + expect(answer).toEqual({ status: 500, code: 'INTERNAL_ERROR', message: INTERNAL_ERROR_MESSAGE }); + } + }); + + it('the /data door does not read the action sentence as business text', async () => { + const door = mapDataError(await cpuTimeout(), 'crm_invoice'); + expect(door.status).toBe(500); + expect(JSON.stringify(door.body)).not.toContain('submit_signoff'); + expect(door.body.error).toBe(INTERNAL_ERROR_MESSAGE); + }); + + it('control: a hook timeout is unchanged, and the /data door answers it the sanitised fault', async () => { + const hook = await cpuTimeout({ origin: { kind: 'hook', name: 'guard_invoice' } }); + expect(hook.message).toMatch(/^hook 'guard_invoice' exceeded CPU budget of 50ms/); + expect(hook.innerMessage).toBeUndefined(); + expect(hook.status).toBeUndefined(); + const door = mapDataError(hook, 'crm_invoice'); + expect(door.status).toBe(500); + expect(door.body).toEqual({ error: INTERNAL_ERROR_MESSAGE, code: 'INTERNAL_ERROR' }); + + const job = await cpuTimeout({ origin: { kind: 'job', name: 'nightly_invoice' } }); + expect(job.message).toMatch(/^job 'nightly_invoice' exceeded CPU budget of 50ms/); + expect(job.innerMessage).toBeUndefined(); + expect(job.status).toBeUndefined(); + }); +}); diff --git a/packages/runtime/src/sandbox/unreadable-rejection-recorded.test.ts b/packages/runtime/src/sandbox/unreadable-rejection-recorded.test.ts index f72d58cba3e..5fd1702ba52 100644 --- a/packages/runtime/src/sandbox/unreadable-rejection-recorded.test.ts +++ b/packages/runtime/src/sandbox/unreadable-rejection-recorded.test.ts @@ -111,9 +111,12 @@ describe('[#23723] CONTROL — what was readable, and what never settles', () => expect(err.code).toBe('EMAIL_TAKEN'); }); - it('a body that never settles still ends at the wall-clock ceiling, with no innerMessage', async () => { + it('a body that never settles still ends at the wall-clock ceiling, with the timeout sentence, not the recorded one', async () => { const err = await thrownBy(`await new Promise(() => {});`); expect(err.message).toMatch(new RegExp(`exceeded wall-clock ceiling of ${CEILING_MS}ms`)); - expect(err.innerMessage).toBeUndefined(); + expect(err.innerMessage).toBe( + `Action 'submit' timed out: it exceeded its ${CEILING_MS} ms time limit while waiting on platform calls, and was stopped.`, + ); + expect(err.status).toBe(500); }); }); From d50f96953750d1d2f5b6add48d7793ac0add2c6a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:19:31 +0000 Subject: [PATCH 2/5] test(runtime): the never-settles door test pays the metadata load during collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- packages/runtime/src/sandbox-unreadable-rejection-door.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts b/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts index f58dfb9753c..472ad4620b8 100644 --- a/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts +++ b/packages/runtime/src/sandbox-unreadable-rejection-door.test.ts @@ -34,6 +34,9 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { HttpDispatcher } from './http-dispatcher.js'; import { actionBodyRunnerFactory } from './sandbox/body-runner.js'; import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js'; +// Paid during collection, never inside a case's clocked window: the door's +// reach loads this package lazily (`check:test-source-alias`). +import '@objectstack/metadata'; const PREFIX = '/api/v1'; /** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ From 80100913434277dc013263414203d51fae22c493 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:56:25 +0000 Subject: [PATCH 3/5] docs(actions): a sandbox timeout is a 500 whose message names the action and its limit, not a crash Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- content/docs/ui/actions.mdx | 7 ++++--- packages/runtime/src/domains/actions.ts | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index f731f2229fb..0457cfcd2e4 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -653,9 +653,10 @@ Failures speak HTTP — the status code is the signal (#3962): - **404 / 403 / 503** — it never dispatched: no such action, denied, service unavailable. A `url`/`modal`/`form` type, or an `api` type whose `target` is on another origin, has no server dispatch and is also a 400. -- **500** — it **crashed**: a `TypeError` in your handler, a driver error, a - sandbox timeout. A deliberate `throw new Error('…')` is a 400 rejection, - not a crash. +- **500** — it **crashed** (a `TypeError` in your handler, a driver error) or + **timed out**; a timeout's message names the action and its limit, while a + crash answers only `Internal server error`. A deliberate + `throw new Error('…')` is a 400 rejection, not a crash. Full table in the [error catalog](/docs/api/error-catalog). The [client SDK](/docs/api/client-sdk) folds all of it into one diff --git a/packages/runtime/src/domains/actions.ts b/packages/runtime/src/domains/actions.ts index 956da40f97d..c0ab330e751 100644 --- a/packages/runtime/src/domains/actions.ts +++ b/packages/runtime/src/domains/actions.ts @@ -51,7 +51,8 @@ * Success is now a SINGLE wrap (`data` = the handler's return value), a * deliberate rejection (body `throw`, flow rejection, ValidationError) is a * 400 carrying `code`/`fields` in `details`, and a crash (`TypeError`, driver - * class, sandbox timeout — told apart by the error's NAME, #3951) is a 500. + * class — told apart by the error's NAME, #3951) is a 500. A sandbox timeout + * is a 500 too, but not a crash: its message names the action and its limit. * * did a handler run? no → 404 / 403 / 400 / 503 * did it reject or crash? reject → 400; crash → 500 From 331f618981d034662f82c33ff8c0b73bf4cf6c56 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 07:48:34 +0000 Subject: [PATCH 4/5] fix(runtime): an action's refusal catalogue passes the runner's own sentenced faults through An action that declares `refusals` handed its timeout to resolveActionRefusal, which read the new caller sentence as the body's code-less throw and replaced it with the undeclared-refusal fault: both doors answered the bare 500 and the log named a throw that never happened. The compile-failure fault had the same route. The runner now marks the faults it makes itself that carry a caller sentence (an action timeout, an action body that does not compile) by identity, and the catalogue passes them through before reading any field. A body's own code-less throw, a declared 500 with the timeout's own words included, is still refused as undeclared. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../sandbox/action-refusal-catalogue.test.ts | 105 +++++++++++++++++- .../src/sandbox/hook-refusal-catalogue.ts | 14 ++- .../runtime/src/sandbox/quickjs-runner.ts | 42 +++++-- 3 files changed, 148 insertions(+), 13 deletions(-) diff --git a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts index fd80dff5c60..332a4e4b330 100644 --- a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts @@ -16,7 +16,7 @@ import { describe, it, expect, vi } from 'vitest'; // Paid at collection, not inside a case's clocked window: the dispatcher's // reach loads `@objectstack/metadata` lazily (`check:test-source-alias`). import '@objectstack/metadata'; -import { mapDataError } from '@objectstack/types'; +import { actionsDoorAnswerOf, mapDataError } from '@objectstack/types'; import { actionBodyRunnerFactory } from './body-runner.js'; import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; @@ -52,13 +52,21 @@ const ZH_GLOBAL = '(全局)只有草稿发票可以签核。'; /** A `script` action with a `js` body and the catalogue, bound through the real factory. */ function boundAction( source: string, - opts: { refusals?: object; objectName?: string | null; i18n?: () => HookRefusalI18nService | undefined } = {}, + opts: { + refusals?: object; + objectName?: string | null; + i18n?: () => HookRefusalI18nService | undefined; + runner?: QuickJSScriptRunner; + logger?: Record void>; + timeoutMs?: number; + } = {}, ) { const objectName = opts.objectName === undefined ? 'crm_invoice' : opts.objectName ?? undefined; - const fn = actionBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: opts.i18n })({ + const fn = actionBodyRunnerFactory(opts.runner ?? runner, { ql: {}, appId: 'crm', i18n: opts.i18n, logger: opts.logger as any })({ name: 'submit_signoff', type: 'script', ...(objectName !== undefined ? { objectName, object: objectName } : {}), + ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}), body: { language: 'js', source, capabilities: [] }, refusals: 'refusals' in opts ? opts.refusals : REFUSALS, } as any); @@ -271,3 +279,94 @@ describe('[#34273] the `/actions` door answers the declared refusal in the calle expect(response.body.error.userMessage).toBeUndefined(); }); }); + +/** + * The runner's own faults are the platform speaking, never a refusal the body + * chose, so an action that declares `refusals` answers them exactly as an + * action without one does. A timeout keeps the sentence naming the action and + * its limit, a body that does not compile keeps the sentence naming the + * compiler's reason, and the operator log keeps the runner's own line, never + * the catalogue's "threw no code" fault. + * + * Driven through the real bound handler (`actionBodyRunnerFactory`), which + * hands every throw to `resolveActionRefusal` before it logs and rethrows it, + * and read on both action doors: the `/actions` HTTP door and the reader the + * MCP `run_action` tool renders a throw with (`actionsDoorAnswerOf`). + */ +describe('the runner\'s own faults pass an action\'s refusal catalogue untouched', () => { + const CPU_SENTENCE = "Action 'submit_signoff' timed out: it exceeded its 50 ms time limit and was stopped."; + const WALL_SENTENCE = + "Action 'submit_signoff' timed out: it exceeded its 300 ms time limit while waiting on platform calls, and was stopped."; + const COMPILE_BODY = 'const input = ctx.input || {}; return 1;'; + + /** + * Records the `.message` of each error logged at `error`, read when it is + * logged: the door later rewrites `.message` to the caller sentence. + */ + function capturingLogger() { + const logged: string[] = []; + const error = vi.fn((_line: string, err: { message: string }) => { logged.push(err.message); }); + return { error, logged, logger: { error, info: vi.fn(), warn: vi.fn(), debug: vi.fn() } }; + } + + /** Both doors' answers to one thrown error, as `{ status, code, message }`. */ + async function bothDoors(err: unknown) { + const response = await throughActionsDoor(err); + const mcp = actionsDoorAnswerOf(err, 'crm_invoice'); + return { + actions: { status: response.status, code: response.body.error.code, message: response.body.error.message }, + mcp: { status: mcp.status, code: mcp.code, message: mcp.message }, + }; + } + + it('a CPU timeout answers its sentence on both doors, and the log keeps the budget line', async () => { + const { error, logged, logger } = capturingLogger(); + const err = await rejectionOf(boundAction('while (true) {}', { logger, timeoutMs: 50 })(actionCtx())); + expect(err).toBeInstanceOf(SandboxError); + const expected = { status: 500, code: 'INTERNAL_ERROR', message: CPU_SENTENCE }; + expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected }); + + expect(error).toHaveBeenCalledTimes(1); + expect(error.mock.calls[0][1]).toBe(err); + expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded CPU budget of 50ms/); + }); + + it('a wall-clock timeout answers its sentence on both doors, and the log keeps the ceiling line', async () => { + const { logged, logger } = capturingLogger(); + const wallRunner = new QuickJSScriptRunner({ actionTimeoutMs: 250, wallCeilingMs: 300 }); + const err = await rejectionOf( + boundAction('await new Promise(() => {});', { logger, runner: wallRunner })(actionCtx()), + ); + const expected = { status: 500, code: 'INTERNAL_ERROR', message: WALL_SENTENCE }; + expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected }); + expect(logged).toHaveLength(1); + expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded wall-clock ceiling of 300ms/); + }); + + it('a body that does not compile answers its sentence on both doors, and the log names the compiler', async () => { + const { logged, logger } = capturingLogger(); + const err = await rejectionOf(boundAction(COMPILE_BODY, { logger })(actionCtx())); + const answers = await bothDoors(err); + expect(answers.mcp).toEqual(answers.actions); + expect(answers.actions.status).toBe(500); + expect(answers.actions.code).toBe('INTERNAL_ERROR'); + expect(answers.actions.message).toContain("Action 'submit_signoff' cannot run: its body does not compile"); + expect(logged).toHaveLength(1); + expect(logged[0]).toMatch(/^action 'submit_signoff' does not compile: SyntaxError/); + }); + + it('CONTROL: a body\'s own code-less throw is still refused as undeclared, a declared 500 and the timeout\'s own words included', async () => { + for (const source of [ + "throw new Error('no code');", + "throw Object.assign(new Error('The server is busy.'), { status: 500 });", + `throw Object.assign(new Error(${JSON.stringify(CPU_SENTENCE)}), { status: 500 });`, + ]) { + const err = await rejectionOf(boundAction(source)(actionCtx())); + expect(err.message, source).toContain('threw no `code`'); + expect(err.innerMessage, source).toBeUndefined(); + const answers = await bothDoors(err); + expect(answers.actions, source).toEqual({ status: 500, code: 'INTERNAL_ERROR', message: 'Internal server error' }); + expect(answers.mcp, source).toEqual(answers.actions); + } + }); +}); diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index 3bf0e07986d..1d140e65a29 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -36,7 +36,10 @@ * refusal of a `ctx.api` write, a nested hook's refusal), the engine's own * error the runner relays as itself, a crash (`TypeError: …`) and the * sandbox's own faults (budget, capability) all pass through as before: they - * are the platform speaking, or a bug, never a refusal the body chose. + * are the platform speaking, or a bug, never a refusal the body chose. An + * action's timeout and an action body that does not compile carry a caller + * sentence, so they pass by identity ({@link isRunnerOwnFault}), not by the + * missing `innerMessage` the other faults pass on. * * **Reasons and params (#33214, ruling 6879477573: S1 and params).** A code * may hold further declared sentences under `reasons`; a throw that names a @@ -82,6 +85,7 @@ import { SandboxError, isHostRelayedSandboxError, isRelayedSandboxRefusal, + isRunnerOwnFault, sandboxRefusalAddressOf, type SandboxRefusalAddress, } from './quickjs-runner.js'; @@ -453,8 +457,12 @@ function resolveSandboxedRefusal( locale: unknown, opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, ): unknown { - // Not the body's own throw: the engine's error relayed as itself, the - // sandbox's own fault, a host error re-thrown unchanged, a nested refusal. + // Not the body's own throw: the runner's own fault that carries a caller + // sentence (an action's timeout, an action body that does not compile; by + // identity, before any field is read, since a body can throw the same + // fields), the engine's error relayed as itself, the sandbox's own fault, a + // host error re-thrown unchanged, a nested refusal. + if (isRunnerOwnFault(err)) return err; if (!(err instanceof SandboxError) || err.innerMessage === undefined) return err; if (isHostRelayedSandboxError(err) || isRelayedSandboxRefusal(err)) return err; // A crash (`TypeError: …`) is a bug, not a refusal: it stays the fault it is. diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index f0ca53ab7f7..82740de8143 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -243,15 +243,17 @@ export class QuickJSScriptRunner implements ScriptRunner { // limit ({@link actionTimeoutSentence}); a hook's or a job's does not, and // keeps the bare fault every door answers with the sanitised 500. Each // construction keeps its message a literal template, which is what the core - // sandbox-fault census renders. + // sandbox-fault census renders. The action's is marked as the runner's own + // fault ({@link isRunnerOwnFault}), so an action's refusal catalogue passes + // it through rather than reading its sentence as the body's code-less throw. const budgetError = (pumps: number): SandboxError | null => { if (cpuMs > cpuBudget) { if (args.origin.kind === 'action') { - return new SandboxError( + return markRunnerOwnFault(new SandboxError( `action '${args.origin.name}' exceeded CPU budget of ${cpuBudget}ms (after ${pumps} pump iterations)`, actionTimeoutSentence(args.origin.name, cpuBudget, false), { status: 500 }, - ); + )); } return new SandboxError( `${args.origin.kind} '${args.origin.name}' exceeded CPU budget of ${cpuBudget}ms (after ${pumps} pump iterations)`, @@ -259,11 +261,11 @@ export class QuickJSScriptRunner implements ScriptRunner { } if (Date.now() > wallDeadline) { if (args.origin.kind === 'action') { - return new SandboxError( + return markRunnerOwnFault(new SandboxError( `action '${args.origin.name}' exceeded wall-clock ceiling of ${wallCeiling}ms while awaiting host calls (after ${pumps} pump iterations)`, actionTimeoutSentence(args.origin.name, wallCeiling, true), { status: 500 }, - ); + )); } return new SandboxError( `${args.origin.kind} '${args.origin.name}' exceeded wall-clock ceiling of ${wallCeiling}ms while awaiting host calls (after ${pumps} pump iterations)`, @@ -2425,12 +2427,12 @@ function isCompileFailure(err: unknown): boolean { */ function actionBodyCompileFailure(actionName: string, compilerError: string): SandboxError { const reason = compilerError.split('\n')[0].slice(0, 240); - return new SandboxError( + return markRunnerOwnFault(new SandboxError( `action '${actionName}' does not compile: ${compilerError}`, `Action '${actionName}' cannot run: its body does not compile (${reason}). ` + 'The action\'s author must fix its body.source and publish it again.', { status: 500 }, - ); + )); } /** @@ -2594,6 +2596,32 @@ export function isHostRelayedSandboxError(err: unknown): boolean { return typeof err === 'object' && err !== null && hostRelayedErrors.has(err); } +/** + * The faults this runner made itself that still carry a caller sentence: an + * action's timeout ({@link actionTimeoutSentence}) and an action body that does + * not compile ({@link actionBodyCompileFailure}). Both are `innerMessage` + a + * declared `500` + no `code`, which is also what a body's own code-less throw + * of `{ status: 500 }` looks like, so no field tells them apart: identity does, + * for the reason {@link relayedRefusals} gives. The runner's other faults carry + * no `innerMessage` and need no mark. + */ +const runnerOwnFaults = new WeakSet(); + +function markRunnerOwnFault(err: SandboxError): SandboxError { + runnerOwnFaults.add(err); + return err; +} + +/** + * Was this error made by the runner itself (an action's timeout, an action + * body that does not compile) rather than thrown by the body? A refusal + * catalogue passes it through unchanged: it is the platform speaking, never a + * refusal the body chose (`resolveActionRefusal`). + */ +export function isRunnerOwnFault(err: unknown): boolean { + return typeof err === 'object' && err !== null && runnerOwnFaults.has(err); +} + /** * [#33214] What a body's throw named beside its `code` for a hook's refusal * catalogue: a `reason` (one of the code's declared sentences) and the From 48170d26e646f73c394777b16cc1751a4d40227f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 07:51:32 +0000 Subject: [PATCH 5/5] docs(changeset): an action that declares refusals keeps the timeout and compile-failure sentences Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .changeset/35027-action-timeout-sentence.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.changeset/35027-action-timeout-sentence.md b/.changeset/35027-action-timeout-sentence.md index b9fbb3f53b0..48c2f818cf9 100644 --- a/.changeset/35027-action-timeout-sentence.md +++ b/.changeset/35027-action-timeout-sentence.md @@ -9,4 +9,6 @@ Metadata-protocol: none An action body that hit its time limit answered `500 INTERNAL_ERROR "Internal server error"` on the `/actions` door and MCP `run_action`, naming neither the action nor the limit, so a caller (an AI agent above all) could not tell a slow action from a broken platform. It now answers the same status and code with the sentence `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.`, where `N` is the CPU-time budget the body ran under (its `body.timeoutMs`, the enclosing timeout, or the `OS_SANDBOX_ACTION_TIMEOUT_MS` default). A body stuck waiting on platform calls past the wall-clock ceiling answers `Action 'NAME' timed out: it exceeded its N ms time limit while waiting on platform calls, and was stopped.` Both doors read one reader, so they answer the same sentence. The server log line is unchanged (`action 'NAME' exceeded CPU budget of Nms (after P pump iterations)`). +The same holds for an action that declares `refusals`. A timeout, like a body that does not compile, is the platform's own fault, so the action's refusal catalogue passes it through unchanged: the caller gets the sentence and the log keeps the runner's own line. Before, the catalogue read a compile failure on such an action as the body's code-less throw, answered the bare `500 "Internal server error"`, and logged "threw no code, and its refusals declares no such code". A body's own throw without a code is still refused that way. + Nothing else moves. A body that crashes (a `TypeError`, say) still answers the sanitised `500 "Internal server error"`, because its own text may carry the data it was reading. A hook's or a job's timeout is unchanged: it carries no caller sentence, and the `/data` door and import rows answer it as before. The action's sentence is declared at `500`, so the `/data` door, which relays a sandbox sentence only below the server band, never serves it as business text.