pi-better-subagents 0.26.2 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -6
- package/child-operations.ts +1109 -0
- package/child-ownership.ts +12 -1
- package/cleanup.ts +11 -2
- package/docs/usage.md +44 -3
- package/finalization.ts +53 -8
- package/goal-provider.ts +42 -4
- package/index.ts +549 -14
- package/lifecycle.ts +26 -0
- package/navigator.mjs +13 -2
- package/navigator.ts +1 -0
- package/operation-bridge-types.ts +1109 -0
- package/package.json +2 -1
- package/park-checkpoint.ts +61 -0
- package/parse.ts +19 -1
- package/registry.ts +192 -6
- package/session-store.ts +3 -0
- package/shared-execution-policy.ts +2 -0
- package/shared-operation-coordinator/index.ts +113 -0
- package/shared-operation-coordinator/src/errors.ts +75 -0
- package/shared-operation-coordinator/src/operations.ts +376 -0
- package/shared-operation-coordinator/src/outbox.ts +431 -0
- package/shared-operation-coordinator/src/rows.ts +439 -0
- package/shared-operation-coordinator/src/schema.ts +244 -0
- package/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/shared-operation-coordinator/src/store.ts +397 -0
- package/shared-operation-coordinator/src/types.ts +648 -0
- package/shared-operation-coordinator/src/validate.ts +239 -0
- package/shared-operation-coordinator/src/waits.ts +1378 -0
- package/shared-task-exec.ts +9 -0
- package/stop.ts +7 -3
- package/task-guard.ts +22 -3
- package/task-policy.ts +7 -0
- package/worker-operations-host.ts +1226 -0
- package/worker-waits.ts +2549 -0
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared contracts for the trusted parent-hosted worker operation bridge.
|
|
3
|
+
*
|
|
4
|
+
* The bridge is a local transport, not a permission system. The host validates
|
|
5
|
+
* transport identity, request shape and the run's task ownership callback, then
|
|
6
|
+
* invokes injectable handlers. Those handlers must intersect the worker's task
|
|
7
|
+
* authority with the current Background profile; this module deliberately does
|
|
8
|
+
* not implement or claim that authorization decision.
|
|
9
|
+
*
|
|
10
|
+
* No function in this module reads credentials from a request body. The only
|
|
11
|
+
* secret is the per-run bearer token, which is compared by hash and never
|
|
12
|
+
* copied into a result, wait record, checkpoint or diagnostic event.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
15
|
+
import { resolve, sep } from "node:path";
|
|
16
|
+
|
|
17
|
+
export const OPERATION_BRIDGE_VERSION = 1 as const;
|
|
18
|
+
|
|
19
|
+
/** Parent-to-child environment. The child uses these instead of reading the parent process. */
|
|
20
|
+
export const OPERATIONS_ENABLED_ENV = "PI_BETTER_OPERATIONS_ENABLED";
|
|
21
|
+
export const OPERATIONS_ENDPOINT_ENV = "PI_BETTER_OPERATIONS_ENDPOINT";
|
|
22
|
+
export const OPERATIONS_TOKEN_ENV = "PI_BETTER_OPERATIONS_TOKEN";
|
|
23
|
+
export const OPERATIONS_RUN_ID_ENV = "PI_BETTER_OPERATIONS_RUN_ID";
|
|
24
|
+
export const OPERATIONS_CONVERSATION_ID_ENV = "PI_BETTER_OPERATIONS_CONVERSATION_ID";
|
|
25
|
+
export const OPERATIONS_ATTEMPT_ID_ENV = "PI_BETTER_OPERATIONS_ATTEMPT_ID";
|
|
26
|
+
export const OPERATIONS_WRITER_LEASE_ID_ENV = "PI_BETTER_OPERATIONS_WRITER_LEASE_ID";
|
|
27
|
+
export const OPERATIONS_CHILD_ID_ENV = "PI_BETTER_OPERATIONS_CHILD_ID";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parent-provided bridge environment. A launched background task must not
|
|
31
|
+
* inherit any of these names: the token authorizes this child, not a shell it
|
|
32
|
+
* starts. The host rejects them in request bodies and result details; the
|
|
33
|
+
* parent must also strip them from the environment it passes to a spawned task.
|
|
34
|
+
*/
|
|
35
|
+
export const OPERATION_BRIDGE_ENV_KEYS: readonly string[] = Object.freeze([
|
|
36
|
+
OPERATIONS_ENABLED_ENV,
|
|
37
|
+
OPERATIONS_ENDPOINT_ENV,
|
|
38
|
+
OPERATIONS_TOKEN_ENV,
|
|
39
|
+
OPERATIONS_RUN_ID_ENV,
|
|
40
|
+
OPERATIONS_CONVERSATION_ID_ENV,
|
|
41
|
+
OPERATIONS_ATTEMPT_ID_ENV,
|
|
42
|
+
OPERATIONS_WRITER_LEASE_ID_ENV,
|
|
43
|
+
OPERATIONS_CHILD_ID_ENV,
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const BRIDGE_ENV_KEY_SET = new Set(OPERATION_BRIDGE_ENV_KEYS);
|
|
47
|
+
|
|
48
|
+
export function findBridgeEnvironmentKey(value: unknown, seen = new Set<object>()): string | undefined {
|
|
49
|
+
if (!value || typeof value !== "object") return undefined;
|
|
50
|
+
if (seen.has(value)) return undefined;
|
|
51
|
+
seen.add(value);
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
for (const entry of value) {
|
|
54
|
+
const found = findBridgeEnvironmentKey(entry, seen);
|
|
55
|
+
if (found) return found;
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
|
60
|
+
if (BRIDGE_ENV_KEY_SET.has(key)) return key;
|
|
61
|
+
const found = findBridgeEnvironmentKey(entry, seen);
|
|
62
|
+
if (found) return found;
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Tools a child may expose. An endpoint cannot add names outside this list. */
|
|
68
|
+
export const OPERATION_BRIDGE_TOOL_NAMES = [
|
|
69
|
+
"bg_task_spawn",
|
|
70
|
+
"bg_task_watch",
|
|
71
|
+
"bg_task_status",
|
|
72
|
+
"bg_task_log",
|
|
73
|
+
"wait_for_operations",
|
|
74
|
+
"acknowledge_operation_result",
|
|
75
|
+
] as const;
|
|
76
|
+
|
|
77
|
+
export type OperationBridgeToolName = (typeof OPERATION_BRIDGE_TOOL_NAMES)[number];
|
|
78
|
+
|
|
79
|
+
/** Tools whose successful call starts one physical operation and therefore needs replay idempotency. */
|
|
80
|
+
export const OPERATION_LAUNCH_TOOL_NAMES: readonly OperationBridgeToolName[] = ["bg_task_spawn", "bg_task_watch"];
|
|
81
|
+
|
|
82
|
+
export const WAIT_OPERATIONS_TOOL = "wait_for_operations" as const;
|
|
83
|
+
export const ACKNOWLEDGE_OPERATION_TOOL = "acknowledge_operation_result" as const;
|
|
84
|
+
|
|
85
|
+
export type OperationBridgeMethod =
|
|
86
|
+
| "handshake"
|
|
87
|
+
| "ping"
|
|
88
|
+
| "checkpoint"
|
|
89
|
+
| "park_failed"
|
|
90
|
+
| "close"
|
|
91
|
+
| OperationBridgeToolName;
|
|
92
|
+
|
|
93
|
+
export const OPERATION_BRIDGE_METHODS: readonly OperationBridgeMethod[] = [
|
|
94
|
+
"handshake",
|
|
95
|
+
"ping",
|
|
96
|
+
"checkpoint",
|
|
97
|
+
"park_failed",
|
|
98
|
+
"close",
|
|
99
|
+
...OPERATION_BRIDGE_TOOL_NAMES,
|
|
100
|
+
];
|
|
101
|
+
|
|
102
|
+
export type JsonRecord = Record<string, unknown>;
|
|
103
|
+
|
|
104
|
+
export interface OperationBridgeCapabilities {
|
|
105
|
+
background: {
|
|
106
|
+
spawn: boolean;
|
|
107
|
+
watch: boolean;
|
|
108
|
+
status: boolean;
|
|
109
|
+
log: boolean;
|
|
110
|
+
};
|
|
111
|
+
/** The child may ask to wait on terminal outcomes. */
|
|
112
|
+
wait: boolean;
|
|
113
|
+
/** The child may interpret evidence and consume a wait generation. */
|
|
114
|
+
acknowledge: boolean;
|
|
115
|
+
/**
|
|
116
|
+
* The child may park. Exposing wait while this is false would let a worker
|
|
117
|
+
* look parked without a certified checkpoint; the child refuses that combination.
|
|
118
|
+
*/
|
|
119
|
+
parking: boolean;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface OperationToolDescriptor {
|
|
123
|
+
name: OperationBridgeToolName;
|
|
124
|
+
label: string;
|
|
125
|
+
description: string;
|
|
126
|
+
/** JSON Schema, copied from the production tool registration when the parent has it. */
|
|
127
|
+
parameters: JsonRecord;
|
|
128
|
+
promptGuidelines?: readonly string[];
|
|
129
|
+
promptSnippet?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface OperationBridgeLimits {
|
|
133
|
+
maxRequestBytes: number;
|
|
134
|
+
maxResponseBytes: number;
|
|
135
|
+
requestTimeoutMs: number;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface OperationBridgeDescriptor {
|
|
139
|
+
bridgeVersion: typeof OPERATION_BRIDGE_VERSION;
|
|
140
|
+
/** Stable hash of the version and tool descriptors, so the child rejects a changed handshake. */
|
|
141
|
+
fingerprint: string;
|
|
142
|
+
runId: string;
|
|
143
|
+
conversationId: string;
|
|
144
|
+
tools: readonly OperationToolDescriptor[];
|
|
145
|
+
capabilities: OperationBridgeCapabilities;
|
|
146
|
+
limits: OperationBridgeLimits;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface OperationBridgeRequestEnvelope {
|
|
150
|
+
v: typeof OPERATION_BRIDGE_VERSION;
|
|
151
|
+
id: string;
|
|
152
|
+
token: string;
|
|
153
|
+
runId: string;
|
|
154
|
+
conversationId: string;
|
|
155
|
+
method: OperationBridgeMethod;
|
|
156
|
+
params?: unknown;
|
|
157
|
+
/** Required for launch tools. Reused on a transport retry so one launch intent starts one operation. */
|
|
158
|
+
key?: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export type OperationBridgeErrorCode =
|
|
162
|
+
| "invalid-json"
|
|
163
|
+
| "invalid-request"
|
|
164
|
+
| "request-too-large"
|
|
165
|
+
| "handshake-required"
|
|
166
|
+
| "invalid-token"
|
|
167
|
+
| "stale-token"
|
|
168
|
+
| "run-revoked"
|
|
169
|
+
| "run-unknown"
|
|
170
|
+
| "conversation-mismatch"
|
|
171
|
+
| "unsupported-method"
|
|
172
|
+
| "unsupported-tool"
|
|
173
|
+
| "schema-invalid"
|
|
174
|
+
| "authority-field"
|
|
175
|
+
| "cwd-outside"
|
|
176
|
+
| "cwd-invalid"
|
|
177
|
+
| "task-invalid"
|
|
178
|
+
| "foreign-task"
|
|
179
|
+
| "foreign-result-task"
|
|
180
|
+
| "ownership-error"
|
|
181
|
+
| "idempotency-key-required"
|
|
182
|
+
| "idempotency-conflict"
|
|
183
|
+
| "idempotency-evicted"
|
|
184
|
+
| "launch-in-progress"
|
|
185
|
+
| "bridge-env-leak"
|
|
186
|
+
| "launch-outcome-unknown"
|
|
187
|
+
| "too-many-requests"
|
|
188
|
+
| "handler-timeout"
|
|
189
|
+
| "handler-error"
|
|
190
|
+
| "tool-error"
|
|
191
|
+
| "response-too-large"
|
|
192
|
+
| "response-invalid"
|
|
193
|
+
| "secret-in-result"
|
|
194
|
+
| "unknown-wait"
|
|
195
|
+
| "checkpoint-invalid"
|
|
196
|
+
| "unsupported"
|
|
197
|
+
| "closed";
|
|
198
|
+
|
|
199
|
+
export interface OperationBridgeErrorBody {
|
|
200
|
+
code: OperationBridgeErrorCode;
|
|
201
|
+
message: string;
|
|
202
|
+
retryable?: boolean;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export type OperationBridgeResponse =
|
|
206
|
+
| { v: typeof OPERATION_BRIDGE_VERSION; id: string; ok: true; result: unknown }
|
|
207
|
+
| { v: typeof OPERATION_BRIDGE_VERSION; id: string; ok: false; error: OperationBridgeErrorBody };
|
|
208
|
+
|
|
209
|
+
export class OperationBridgeError extends Error {
|
|
210
|
+
readonly code: OperationBridgeErrorCode;
|
|
211
|
+
readonly retryable: boolean;
|
|
212
|
+
|
|
213
|
+
constructor(code: OperationBridgeErrorCode, message: string, retryable = false) {
|
|
214
|
+
super(message);
|
|
215
|
+
this.name = "OperationBridgeError";
|
|
216
|
+
this.code = code;
|
|
217
|
+
this.retryable = retryable;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A handler may throw this to return a model-facing tool error without exposing an internal stack. */
|
|
222
|
+
export class OperationToolError extends Error {
|
|
223
|
+
readonly code: string;
|
|
224
|
+
|
|
225
|
+
constructor(message: string, code = "tool-error") {
|
|
226
|
+
super(message);
|
|
227
|
+
this.name = "OperationToolError";
|
|
228
|
+
this.code = code;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function isOperationBridgeError(error: unknown): error is OperationBridgeError {
|
|
233
|
+
return error instanceof OperationBridgeError;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function generateOperationBridgeToken(): string {
|
|
237
|
+
return randomBytes(32).toString("base64url");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function hashOperationBridgeToken(token: string): Buffer {
|
|
241
|
+
return createHash("sha256").update(token, "utf8").digest();
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Deterministic JSON used for fingerprints. Objects with `undefined` are not accepted. */
|
|
245
|
+
export function canonicalJson(value: unknown): string {
|
|
246
|
+
return JSON.stringify(sortJson(value));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function sortJson(value: unknown): unknown {
|
|
250
|
+
if (value === null || typeof value !== "object") return value;
|
|
251
|
+
if (Array.isArray(value)) return value.map(sortJson);
|
|
252
|
+
const source = value as Record<string, unknown>;
|
|
253
|
+
const out: Record<string, unknown> = {};
|
|
254
|
+
for (const key of Object.keys(source).sort()) {
|
|
255
|
+
const entry = source[key];
|
|
256
|
+
if (entry !== undefined) out[key] = sortJson(entry);
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function descriptorFingerprint(
|
|
262
|
+
tools: readonly OperationToolDescriptor[],
|
|
263
|
+
capabilities: OperationBridgeCapabilities,
|
|
264
|
+
): string {
|
|
265
|
+
return createHash("sha256")
|
|
266
|
+
.update(canonicalJson({
|
|
267
|
+
bridgeVersion: OPERATION_BRIDGE_VERSION,
|
|
268
|
+
tools: [...tools].sort((a, b) => a.name.localeCompare(b.name)),
|
|
269
|
+
capabilities,
|
|
270
|
+
}), "utf8")
|
|
271
|
+
.digest("hex");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---- JSON schema validation -------------------------------------------------
|
|
275
|
+
|
|
276
|
+
export type JsonSchemaValidation =
|
|
277
|
+
| { ok: true }
|
|
278
|
+
| { ok: false; path: string; message: string; schemaError?: boolean };
|
|
279
|
+
|
|
280
|
+
const IGNORED_SCHEMA_KEYWORDS = new Set([
|
|
281
|
+
"$schema", "$id", "$comment", "title", "description", "default", "examples", "deprecated",
|
|
282
|
+
"readOnly", "writeOnly", "format", "contentMediaType", "contentEncoding",
|
|
283
|
+
]);
|
|
284
|
+
|
|
285
|
+
function valueFailure(path: string, message: string): JsonSchemaValidation {
|
|
286
|
+
return { ok: false, path, message };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function schemaFailure(path: string, message: string): JsonSchemaValidation {
|
|
290
|
+
return { ok: false, path, message, schemaError: true };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const SUPPORTED_SCHEMA_KEYWORDS = new Set([
|
|
294
|
+
"type", "const", "enum", "allOf", "anyOf", "oneOf", "not", "minLength", "maxLength", "pattern",
|
|
295
|
+
"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minItems", "maxItems", "uniqueItems",
|
|
296
|
+
"items", "required", "properties", "additionalProperties", "minProperties", "maxProperties",
|
|
297
|
+
]);
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Preflight the whole schema, including branches a particular value would not
|
|
301
|
+
* visit. Without this, `{not:{properties:{x:{$ref:...}}}}` with `{}` could pass
|
|
302
|
+
* because the unsupported subschema was never selected.
|
|
303
|
+
*/
|
|
304
|
+
function scanSchemaSupport(schema: unknown, path: string): JsonSchemaValidation {
|
|
305
|
+
if (schema === true || schema === undefined || schema === false) return { ok: true };
|
|
306
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
307
|
+
return schemaFailure(path, "schema is not an object");
|
|
308
|
+
}
|
|
309
|
+
const spec = schema as Record<string, unknown>;
|
|
310
|
+
for (const key of Object.keys(spec)) {
|
|
311
|
+
if (IGNORED_SCHEMA_KEYWORDS.has(key) || SUPPORTED_SCHEMA_KEYWORDS.has(key)) continue;
|
|
312
|
+
return schemaFailure(path, `unsupported schema keyword ${key}`);
|
|
313
|
+
}
|
|
314
|
+
if (typeof spec.pattern === "string") {
|
|
315
|
+
try { new RegExp(spec.pattern); } catch { return schemaFailure(path, "schema pattern is invalid"); }
|
|
316
|
+
}
|
|
317
|
+
if (spec.required !== undefined && !Array.isArray(spec.required)) {
|
|
318
|
+
return schemaFailure(path, "required must be an array");
|
|
319
|
+
}
|
|
320
|
+
if (spec.enum !== undefined && !Array.isArray(spec.enum)) {
|
|
321
|
+
return schemaFailure(path, "enum must be an array");
|
|
322
|
+
}
|
|
323
|
+
if (spec.type !== undefined) {
|
|
324
|
+
const types = Array.isArray(spec.type) ? spec.type : [spec.type];
|
|
325
|
+
const known = new Set(["object", "array", "string", "integer", "number", "boolean", "null"]);
|
|
326
|
+
if (types.some((type) => typeof type !== "string" || !known.has(type))) {
|
|
327
|
+
return schemaFailure(path, "schema type is unsupported");
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
for (const key of ["allOf", "anyOf", "oneOf"] as const) {
|
|
331
|
+
if (spec[key] === undefined) continue;
|
|
332
|
+
if (!Array.isArray(spec[key])) return schemaFailure(path, `${key} must be an array`);
|
|
333
|
+
for (const [index, sub] of spec[key].entries()) {
|
|
334
|
+
const result = scanSchemaSupport(sub, `${path}/${key}/${index}`);
|
|
335
|
+
if (!result.ok) return result;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (spec.not !== undefined) {
|
|
339
|
+
const result = scanSchemaSupport(spec.not, `${path}/not`);
|
|
340
|
+
if (!result.ok) return result;
|
|
341
|
+
}
|
|
342
|
+
if (spec.items !== undefined) {
|
|
343
|
+
if (Array.isArray(spec.items)) return schemaFailure(path, "tuple items are unsupported");
|
|
344
|
+
const result = scanSchemaSupport(spec.items, `${path}/items`);
|
|
345
|
+
if (!result.ok) return result;
|
|
346
|
+
}
|
|
347
|
+
if (spec.properties !== undefined) {
|
|
348
|
+
if (!spec.properties || typeof spec.properties !== "object" || Array.isArray(spec.properties)) {
|
|
349
|
+
return schemaFailure(path, "properties must be an object");
|
|
350
|
+
}
|
|
351
|
+
for (const [key, sub] of Object.entries(spec.properties as Record<string, unknown>)) {
|
|
352
|
+
const result = scanSchemaSupport(sub, `${path}/properties/${key}`);
|
|
353
|
+
if (!result.ok) return result;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (spec.additionalProperties !== undefined && spec.additionalProperties !== true && spec.additionalProperties !== false) {
|
|
357
|
+
const result = scanSchemaSupport(spec.additionalProperties, `${path}/additionalProperties`);
|
|
358
|
+
if (!result.ok) return result;
|
|
359
|
+
}
|
|
360
|
+
return { ok: true };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Checks schema support without requiring a value, so bad descriptors fail early. */
|
|
364
|
+
export function validateJsonSchemaSupport(schema: unknown): JsonSchemaValidation {
|
|
365
|
+
return scanSchemaSupport(schema, "$");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* A deliberately small JSON Schema subset. It covers the TypeBox schemas the
|
|
370
|
+
* parent hands over without importing TypeBox into the child and without ever
|
|
371
|
+
* evaluating code from an endpoint. Unsupported keywords that can change
|
|
372
|
+
* acceptance are refused instead of being treated as permissive.
|
|
373
|
+
*
|
|
374
|
+
* A `schemaError` result means the validator could not understand part of the
|
|
375
|
+
* schema. It must never be treated as "the value did not match this branch";
|
|
376
|
+
* composition keywords propagate it so an unsupported subschema cannot make a
|
|
377
|
+
* value pass.
|
|
378
|
+
*/
|
|
379
|
+
export function validateJsonSchema(schema: unknown, value: unknown, path = "$"): JsonSchemaValidation {
|
|
380
|
+
const support = scanSchemaSupport(schema, path);
|
|
381
|
+
if (!support.ok) return support;
|
|
382
|
+
if (schema === true || schema === undefined) return { ok: true };
|
|
383
|
+
if (schema === false) return valueFailure(path, "value is not allowed");
|
|
384
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
385
|
+
return schemaFailure(path, "schema is not an object");
|
|
386
|
+
}
|
|
387
|
+
const spec = schema as Record<string, unknown>;
|
|
388
|
+
for (const key of ["$ref", "if", "then", "else", "dependentSchemas", "patternProperties", "propertyNames"]) {
|
|
389
|
+
if (key in spec) return schemaFailure(path, `unsupported schema keyword ${key}`);
|
|
390
|
+
}
|
|
391
|
+
if ("const" in spec && canonicalJson(value) !== canonicalJson(spec.const)) {
|
|
392
|
+
return valueFailure(path, "value does not match const");
|
|
393
|
+
}
|
|
394
|
+
if (Array.isArray(spec.enum)) {
|
|
395
|
+
const encoded = canonicalJson(value);
|
|
396
|
+
if (!spec.enum.some((entry) => canonicalJson(entry) === encoded)) {
|
|
397
|
+
return valueFailure(path, "value is not in enum");
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (Array.isArray(spec.allOf)) {
|
|
401
|
+
for (const [index, sub] of spec.allOf.entries()) {
|
|
402
|
+
const result = validateJsonSchema(sub, value, `${path}/allOf/${index}`);
|
|
403
|
+
if (!result.ok) return result;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (Array.isArray(spec.anyOf)) {
|
|
407
|
+
const results = spec.anyOf.map((sub, index) => validateJsonSchema(sub, value, `${path}/anyOf/${index}`));
|
|
408
|
+
const unsupported = results.find((result) => !result.ok && result.schemaError);
|
|
409
|
+
if (unsupported) return unsupported;
|
|
410
|
+
if (!results.some((result) => result.ok)) {
|
|
411
|
+
return valueFailure(path, "value matches none of anyOf");
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (Array.isArray(spec.oneOf)) {
|
|
415
|
+
const results = spec.oneOf.map((sub, index) => validateJsonSchema(sub, value, `${path}/oneOf/${index}`));
|
|
416
|
+
const unsupported = results.find((result) => !result.ok && result.schemaError);
|
|
417
|
+
if (unsupported) return unsupported;
|
|
418
|
+
if (results.filter((result) => result.ok).length !== 1) {
|
|
419
|
+
return valueFailure(path, "value must match exactly one oneOf branch");
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (spec.not !== undefined) {
|
|
423
|
+
const forbidden = validateJsonSchema(spec.not, value, `${path}/not`);
|
|
424
|
+
if (!forbidden.ok && forbidden.schemaError) return forbidden;
|
|
425
|
+
if (forbidden.ok) return valueFailure(path, "value matches the forbidden schema");
|
|
426
|
+
}
|
|
427
|
+
if (spec.type !== undefined) {
|
|
428
|
+
const types = Array.isArray(spec.type) ? spec.type : [spec.type];
|
|
429
|
+
if (!types.some((type) => typeof type === "string" && matchesJsonType(type, value))) {
|
|
430
|
+
return valueFailure(path, `expected ${types.join(" or ")}`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (typeof value === "string") {
|
|
434
|
+
if (typeof spec.minLength === "number" && value.length < spec.minLength) {
|
|
435
|
+
return valueFailure(path, `shorter than ${spec.minLength}`);
|
|
436
|
+
}
|
|
437
|
+
if (typeof spec.maxLength === "number" && value.length > spec.maxLength) {
|
|
438
|
+
return valueFailure(path, `longer than ${spec.maxLength}`);
|
|
439
|
+
}
|
|
440
|
+
if (typeof spec.pattern === "string") {
|
|
441
|
+
let pattern: RegExp;
|
|
442
|
+
try {
|
|
443
|
+
pattern = new RegExp(spec.pattern);
|
|
444
|
+
} catch {
|
|
445
|
+
return schemaFailure(path, "schema pattern is invalid");
|
|
446
|
+
}
|
|
447
|
+
if (!pattern.test(value)) return valueFailure(path, "does not match pattern");
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (typeof value === "number") {
|
|
451
|
+
if (typeof spec.minimum === "number" && value < spec.minimum) {
|
|
452
|
+
return valueFailure(path, `less than ${spec.minimum}`);
|
|
453
|
+
}
|
|
454
|
+
if (typeof spec.maximum === "number" && value > spec.maximum) {
|
|
455
|
+
return valueFailure(path, `greater than ${spec.maximum}`);
|
|
456
|
+
}
|
|
457
|
+
if (typeof spec.exclusiveMinimum === "number" && value <= spec.exclusiveMinimum) {
|
|
458
|
+
return valueFailure(path, `not greater than ${spec.exclusiveMinimum}`);
|
|
459
|
+
}
|
|
460
|
+
if (typeof spec.exclusiveMaximum === "number" && value >= spec.exclusiveMaximum) {
|
|
461
|
+
return valueFailure(path, `not less than ${spec.exclusiveMaximum}`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (Array.isArray(value)) {
|
|
465
|
+
if (typeof spec.minItems === "number" && value.length < spec.minItems) {
|
|
466
|
+
return valueFailure(path, `fewer than ${spec.minItems} items`);
|
|
467
|
+
}
|
|
468
|
+
if (typeof spec.maxItems === "number" && value.length > spec.maxItems) {
|
|
469
|
+
return valueFailure(path, `more than ${spec.maxItems} items`);
|
|
470
|
+
}
|
|
471
|
+
if (spec.uniqueItems === true) {
|
|
472
|
+
const seen = new Set(value.map((entry) => canonicalJson(entry)));
|
|
473
|
+
if (seen.size !== value.length) return valueFailure(path, "items are not unique");
|
|
474
|
+
}
|
|
475
|
+
if (spec.items !== undefined) {
|
|
476
|
+
for (const [index, item] of value.entries()) {
|
|
477
|
+
const result = validateJsonSchema(spec.items, item, `${path}/${index}`);
|
|
478
|
+
if (!result.ok) return result;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
483
|
+
const object = value as Record<string, unknown>;
|
|
484
|
+
if (Array.isArray(spec.required)) {
|
|
485
|
+
for (const key of spec.required) {
|
|
486
|
+
if (typeof key === "string" && !Object.prototype.hasOwnProperty.call(object, key)) {
|
|
487
|
+
return valueFailure(`${path}/${key}`, "is required");
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const properties = spec.properties && typeof spec.properties === "object" && !Array.isArray(spec.properties)
|
|
492
|
+
? spec.properties as Record<string, unknown>
|
|
493
|
+
: undefined;
|
|
494
|
+
if (properties) {
|
|
495
|
+
for (const [key, subschema] of Object.entries(properties)) {
|
|
496
|
+
if (!Object.prototype.hasOwnProperty.call(object, key)) continue;
|
|
497
|
+
const result = validateJsonSchema(subschema, object[key], `${path}/${key}`);
|
|
498
|
+
if (!result.ok) return result;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const additional = spec.additionalProperties;
|
|
502
|
+
if (additional === false) {
|
|
503
|
+
for (const key of Object.keys(object)) {
|
|
504
|
+
if (!properties || !Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
505
|
+
return valueFailure(`${path}/${key}`, "is not an allowed property");
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
} else if (additional && typeof additional === "object") {
|
|
509
|
+
for (const key of Object.keys(object)) {
|
|
510
|
+
if (properties && Object.prototype.hasOwnProperty.call(properties, key)) continue;
|
|
511
|
+
const result = validateJsonSchema(additional, object[key], `${path}/${key}`);
|
|
512
|
+
if (!result.ok) return result;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (typeof spec.minProperties === "number" && Object.keys(object).length < spec.minProperties) {
|
|
516
|
+
return valueFailure(path, `fewer than ${spec.minProperties} properties`);
|
|
517
|
+
}
|
|
518
|
+
if (typeof spec.maxProperties === "number" && Object.keys(object).length > spec.maxProperties) {
|
|
519
|
+
return valueFailure(path, `more than ${spec.maxProperties} properties`);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
for (const key of Object.keys(spec)) {
|
|
523
|
+
if (IGNORED_SCHEMA_KEYWORDS.has(key)) continue;
|
|
524
|
+
if ([
|
|
525
|
+
"type", "const", "enum", "allOf", "anyOf", "oneOf", "not", "minLength", "maxLength", "pattern",
|
|
526
|
+
"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minItems", "maxItems", "uniqueItems",
|
|
527
|
+
"items", "required", "properties", "additionalProperties", "minProperties", "maxProperties",
|
|
528
|
+
].includes(key)) continue;
|
|
529
|
+
// A descriptor from a newer production schema must not silently weaken validation.
|
|
530
|
+
return schemaFailure(path, `unsupported schema keyword ${key}`);
|
|
531
|
+
}
|
|
532
|
+
return { ok: true };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function matchesJsonType(type: string, value: unknown): boolean {
|
|
536
|
+
switch (type) {
|
|
537
|
+
case "object": return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
538
|
+
case "array": return Array.isArray(value);
|
|
539
|
+
case "string": return typeof value === "string";
|
|
540
|
+
case "integer": return typeof value === "number" && Number.isInteger(value);
|
|
541
|
+
case "number": return typeof value === "number" && Number.isFinite(value);
|
|
542
|
+
case "boolean": return typeof value === "boolean";
|
|
543
|
+
case "null": return value === null;
|
|
544
|
+
default: return false;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ---- canonical tool schemas -------------------------------------------------
|
|
549
|
+
|
|
550
|
+
const string = (extra: JsonRecord = {}): JsonRecord => ({ type: "string", ...extra });
|
|
551
|
+
const object = (properties: JsonRecord, required: string[] = [], extra: JsonRecord = {}): JsonRecord => ({
|
|
552
|
+
type: "object",
|
|
553
|
+
additionalProperties: false,
|
|
554
|
+
...(required.length ? { required } : {}),
|
|
555
|
+
properties,
|
|
556
|
+
...extra,
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
const LOOSE_BACKGROUND_SCHEMA: JsonRecord = { type: "object", additionalProperties: true };
|
|
560
|
+
|
|
561
|
+
export const WAIT_FOR_OPERATIONS_SCHEMA: JsonRecord = object({
|
|
562
|
+
task_ids: {
|
|
563
|
+
type: "array",
|
|
564
|
+
minItems: 1,
|
|
565
|
+
maxItems: 100,
|
|
566
|
+
items: string({ minLength: 1, maxLength: 128 }),
|
|
567
|
+
},
|
|
568
|
+
continuation_note: string({ minLength: 1, maxLength: 2_000 }),
|
|
569
|
+
}, ["task_ids", "continuation_note"]);
|
|
570
|
+
|
|
571
|
+
export const ACKNOWLEDGE_OPERATION_RESULT_SCHEMA: JsonRecord = object({
|
|
572
|
+
wait_id: string({ minLength: 1, maxLength: 128 }),
|
|
573
|
+
generation: { type: "integer", minimum: 1 },
|
|
574
|
+
terminal_revisions: {
|
|
575
|
+
anyOf: [
|
|
576
|
+
{
|
|
577
|
+
type: "array",
|
|
578
|
+
minItems: 1,
|
|
579
|
+
maxItems: 100,
|
|
580
|
+
items: object({
|
|
581
|
+
task_id: string({ minLength: 1, maxLength: 128 }),
|
|
582
|
+
operation_id: string({ minLength: 1, maxLength: 128 }),
|
|
583
|
+
revision: { type: "integer", minimum: 1 },
|
|
584
|
+
}, ["operation_id", "revision"]),
|
|
585
|
+
},
|
|
586
|
+
{
|
|
587
|
+
type: "object",
|
|
588
|
+
additionalProperties: { type: "integer", minimum: 1 },
|
|
589
|
+
},
|
|
590
|
+
],
|
|
591
|
+
},
|
|
592
|
+
disposition: { type: "string", enum: ["continue", "blocked", "assignment-complete"] },
|
|
593
|
+
note: string({ maxLength: 4_000 }),
|
|
594
|
+
}, ["wait_id", "generation", "terminal_revisions", "disposition", "note"]);
|
|
595
|
+
|
|
596
|
+
export const CHECKPOINT_SCHEMA: JsonRecord = object({
|
|
597
|
+
wait_id: string({ minLength: 1, maxLength: 128 }),
|
|
598
|
+
generation: { type: "integer", minimum: 1 },
|
|
599
|
+
tool_call_id: string({ minLength: 1, maxLength: 256 }),
|
|
600
|
+
attempt_id: string({ minLength: 1, maxLength: 256 }),
|
|
601
|
+
writer_lease_id: string({ minLength: 1, maxLength: 256 }),
|
|
602
|
+
evidence: object({
|
|
603
|
+
version: { type: "integer", const: 1 },
|
|
604
|
+
sessionId: string({ minLength: 1, maxLength: 256 }),
|
|
605
|
+
sessionFile: string({ minLength: 1, maxLength: 4_096 }),
|
|
606
|
+
toolCallId: string({ minLength: 1, maxLength: 256 }),
|
|
607
|
+
waitId: string({ minLength: 1, maxLength: 128 }),
|
|
608
|
+
generation: { type: "integer", minimum: 1 },
|
|
609
|
+
entryId: string({ minLength: 1, maxLength: 256 }),
|
|
610
|
+
prefixBytes: { type: "integer", minimum: 1 },
|
|
611
|
+
prefixSha256: string({ minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$" }),
|
|
612
|
+
}, ["version", "sessionId", "sessionFile", "toolCallId", "waitId", "generation", "entryId", "prefixBytes", "prefixSha256"]),
|
|
613
|
+
}, ["wait_id", "generation", "tool_call_id", "evidence"]);
|
|
614
|
+
|
|
615
|
+
export const PARK_FAILED_SCHEMA: JsonRecord = object({
|
|
616
|
+
wait_id: string({ minLength: 1, maxLength: 128 }),
|
|
617
|
+
generation: { type: "integer", minimum: 1 },
|
|
618
|
+
reason: string({ minLength: 1, maxLength: 2_000 }),
|
|
619
|
+
}, ["wait_id", "generation", "reason"]);
|
|
620
|
+
|
|
621
|
+
const HANDSHAKE_SCHEMA: JsonRecord = object({
|
|
622
|
+
bridge_version: { type: "integer", const: OPERATION_BRIDGE_VERSION },
|
|
623
|
+
client: object({
|
|
624
|
+
name: string({ minLength: 1, maxLength: 128 }),
|
|
625
|
+
version: string({ minLength: 1, maxLength: 128 }),
|
|
626
|
+
}, [], { additionalProperties: true }),
|
|
627
|
+
}, ["bridge_version"]);
|
|
628
|
+
|
|
629
|
+
export function canonicalToolSchema(name: OperationBridgeToolName): JsonRecord {
|
|
630
|
+
switch (name) {
|
|
631
|
+
case "wait_for_operations": return WAIT_FOR_OPERATIONS_SCHEMA;
|
|
632
|
+
case "acknowledge_operation_result": return ACKNOWLEDGE_OPERATION_RESULT_SCHEMA;
|
|
633
|
+
default: return LOOSE_BACKGROUND_SCHEMA;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const TOOL_LABELS: Record<OperationBridgeToolName, string> = {
|
|
638
|
+
bg_task_spawn: "BG Spawn",
|
|
639
|
+
bg_task_watch: "BG Watch",
|
|
640
|
+
bg_task_status: "BG Status",
|
|
641
|
+
bg_task_log: "BG Log",
|
|
642
|
+
wait_for_operations: "Wait for Operations",
|
|
643
|
+
acknowledge_operation_result: "Acknowledge Operation Result",
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
const TOOL_DESCRIPTIONS: Record<OperationBridgeToolName, string> = {
|
|
647
|
+
bg_task_spawn: "Start one long-running background operation through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
648
|
+
bg_task_watch: "Start one background command watch through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
649
|
+
bg_task_status: "Inspect one operation owned by this worker conversation. Only task ids accepted by the parent ownership check are readable.",
|
|
650
|
+
bg_task_log: "Read the retained log of one operation owned by this worker conversation. Only task ids accepted by the parent ownership check are readable.",
|
|
651
|
+
wait_for_operations: "Register an all-settled wait on operations owned by this conversation. A settled result returns evidence and keeps this attempt running; an unsettled result parks the worker only after the parent certifies the saved tool result.",
|
|
652
|
+
acknowledge_operation_result: "Interpret the exact terminal evidence of a registered wait and mark that wait generation consumed. The disposition does not complete the assignment by itself.",
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
const TOOL_GUIDELINES: Partial<Record<OperationBridgeToolName, readonly string[]>> = {
|
|
656
|
+
bg_task_spawn: ["Use bg_task_spawn for established long commands; do not emulate background execution with polling, sleep loops, nohup or shell detachment."],
|
|
657
|
+
bg_task_watch: ["Use bg_task_watch for repeated observation. Do not run a foreground poll loop."],
|
|
658
|
+
wait_for_operations: ["Call wait_for_operations only when no independent work remains. A final answer that says you are waiting is not a park request."],
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
export function createToolDescriptor(
|
|
662
|
+
name: OperationBridgeToolName,
|
|
663
|
+
overrides: Partial<Omit<OperationToolDescriptor, "name">> = {},
|
|
664
|
+
): OperationToolDescriptor {
|
|
665
|
+
// The wait/acknowledge schemas are fixed here; a parent descriptor may not
|
|
666
|
+
// loosen the contract that decides when a worker parks or consumes evidence.
|
|
667
|
+
const parameters = name === WAIT_OPERATIONS_TOOL || name === ACKNOWLEDGE_OPERATION_TOOL
|
|
668
|
+
? canonicalToolSchema(name)
|
|
669
|
+
: (overrides.parameters ?? canonicalToolSchema(name));
|
|
670
|
+
return deepFreeze({
|
|
671
|
+
name,
|
|
672
|
+
label: overrides.label ?? TOOL_LABELS[name],
|
|
673
|
+
description: overrides.description ?? TOOL_DESCRIPTIONS[name],
|
|
674
|
+
parameters: cloneJson(parameters) as JsonRecord,
|
|
675
|
+
...(overrides.promptGuidelines ? { promptGuidelines: [...overrides.promptGuidelines] } : TOOL_GUIDELINES[name] ? { promptGuidelines: [...TOOL_GUIDELINES[name]!] } : {}),
|
|
676
|
+
...(overrides.promptSnippet ? { promptSnippet: overrides.promptSnippet } : {}),
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export function descriptorsForCapabilities(capabilities: OperationBridgeCapabilities): OperationToolDescriptor[] {
|
|
681
|
+
return deepFreeze([
|
|
682
|
+
...(capabilities.background.spawn ? [createToolDescriptor("bg_task_spawn")] : []),
|
|
683
|
+
...(capabilities.background.watch ? [createToolDescriptor("bg_task_watch")] : []),
|
|
684
|
+
...(capabilities.background.status ? [createToolDescriptor("bg_task_status")] : []),
|
|
685
|
+
...(capabilities.background.log ? [createToolDescriptor("bg_task_log")] : []),
|
|
686
|
+
...(capabilities.wait && capabilities.parking ? [createToolDescriptor("wait_for_operations")] : []),
|
|
687
|
+
...(capabilities.acknowledge ? [createToolDescriptor("acknowledge_operation_result")] : []),
|
|
688
|
+
] as OperationToolDescriptor[]);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Validates and freezes a descriptor set. Unknown tool names are a handshake
|
|
693
|
+
* failure, not a reason to expose an extra tool.
|
|
694
|
+
*/
|
|
695
|
+
export function normalizeToolDescriptors(
|
|
696
|
+
tools: readonly OperationToolDescriptor[],
|
|
697
|
+
capabilities: OperationBridgeCapabilities,
|
|
698
|
+
): readonly OperationToolDescriptor[] {
|
|
699
|
+
const seen = new Set<string>();
|
|
700
|
+
const normalized: OperationToolDescriptor[] = [];
|
|
701
|
+
for (const tool of tools) {
|
|
702
|
+
if (!OPERATION_BRIDGE_TOOL_NAMES.includes(tool.name)) {
|
|
703
|
+
throw new OperationBridgeError("invalid-request", `Unknown bridge tool ${String((tool as { name?: unknown }).name)}`);
|
|
704
|
+
}
|
|
705
|
+
if (seen.has(tool.name)) throw new OperationBridgeError("invalid-request", `Duplicate bridge tool ${tool.name}`);
|
|
706
|
+
seen.add(tool.name);
|
|
707
|
+
const allowed = capabilityForTool(tool.name, capabilities);
|
|
708
|
+
if (!allowed) throw new OperationBridgeError("invalid-request", `${tool.name} is not enabled by the run capabilities`);
|
|
709
|
+
normalized.push(createToolDescriptor(tool.name, tool));
|
|
710
|
+
}
|
|
711
|
+
// A capability without a descriptor would let the child believe a tool
|
|
712
|
+
// exists while the host rejects it. Reject the inconsistent registration.
|
|
713
|
+
for (const name of OPERATION_BRIDGE_TOOL_NAMES) {
|
|
714
|
+
if (!seen.has(name) && capabilityForTool(name, capabilities)) {
|
|
715
|
+
throw new OperationBridgeError("invalid-request", `${name} is enabled but has no descriptor`);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return deepFreeze(normalized.sort((a, b) => a.name.localeCompare(b.name)));
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
export function capabilityForTool(name: OperationBridgeToolName, capabilities: OperationBridgeCapabilities): boolean {
|
|
722
|
+
switch (name) {
|
|
723
|
+
case "bg_task_spawn": return capabilities.background.spawn;
|
|
724
|
+
case "bg_task_watch": return capabilities.background.watch;
|
|
725
|
+
case "bg_task_status": return capabilities.background.status;
|
|
726
|
+
case "bg_task_log": return capabilities.background.log;
|
|
727
|
+
case "wait_for_operations": return capabilities.wait && capabilities.parking;
|
|
728
|
+
case "acknowledge_operation_result": return capabilities.acknowledge;
|
|
729
|
+
default: return false;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
export function createBridgeDescriptor(
|
|
734
|
+
runId: string,
|
|
735
|
+
conversationId: string,
|
|
736
|
+
tools: readonly OperationToolDescriptor[],
|
|
737
|
+
capabilities: OperationBridgeCapabilities,
|
|
738
|
+
limits: OperationBridgeLimits,
|
|
739
|
+
): OperationBridgeDescriptor {
|
|
740
|
+
return deepFreeze({
|
|
741
|
+
bridgeVersion: OPERATION_BRIDGE_VERSION,
|
|
742
|
+
fingerprint: descriptorFingerprint(tools, capabilities),
|
|
743
|
+
runId,
|
|
744
|
+
conversationId,
|
|
745
|
+
tools: [...tools],
|
|
746
|
+
capabilities: deepFreezeCopy(capabilities),
|
|
747
|
+
limits: { ...limits },
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ---- identity, authority and task helpers -------------------------------------------------
|
|
752
|
+
|
|
753
|
+
const AUTHORITY_FIELDS = new Set([
|
|
754
|
+
"run_id", "runId", "conversation_id", "conversationId", "owner", "owner_id", "ownerId",
|
|
755
|
+
"session_id", "sessionId", "endpoint", "token", "access_token", "accessToken",
|
|
756
|
+
"capabilities", "authority", "authority_reference", "authorityReference",
|
|
757
|
+
"permissions", "permission", "parent", "parent_id", "parentId", "child_id", "childId",
|
|
758
|
+
"workspace_root", "workspaceRoot",
|
|
759
|
+
]);
|
|
760
|
+
|
|
761
|
+
/** Caller fields that would override parent-owned authority are refused, never merged. */
|
|
762
|
+
export function findAuthorityField(params: JsonRecord): string | undefined {
|
|
763
|
+
for (const key of Object.keys(params)) {
|
|
764
|
+
if (AUTHORITY_FIELDS.has(key)) return key;
|
|
765
|
+
}
|
|
766
|
+
return undefined;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
const SECRET_FIELDS = new Set([
|
|
770
|
+
"token", "access_token", "accessToken", "launch_token", "launchToken",
|
|
771
|
+
"claim_token", "claimToken", "bearer", "authorization", "secret",
|
|
772
|
+
"client_secret", "clientSecret", "password", "passwd", "private_key", "privateKey",
|
|
773
|
+
"credential", "credentials",
|
|
774
|
+
]);
|
|
775
|
+
|
|
776
|
+
/** Shallow and nested scan used to keep secrets out of child-visible results and checkpoint records. */
|
|
777
|
+
export function findSecretField(value: unknown, seen = new Set<object>()): string | undefined {
|
|
778
|
+
if (!value || typeof value !== "object") return undefined;
|
|
779
|
+
if (seen.has(value)) return undefined;
|
|
780
|
+
seen.add(value);
|
|
781
|
+
if (Array.isArray(value)) {
|
|
782
|
+
for (const entry of value) {
|
|
783
|
+
const found = findSecretField(entry, seen);
|
|
784
|
+
if (found) return found;
|
|
785
|
+
}
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
|
789
|
+
if (SECRET_FIELDS.has(key)) return key;
|
|
790
|
+
const found = findSecretField(entry, seen);
|
|
791
|
+
if (found) return found;
|
|
792
|
+
}
|
|
793
|
+
return undefined;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
export function extractTaskIds(tool: string, params: JsonRecord): string[] {
|
|
797
|
+
const ids: unknown[] = [];
|
|
798
|
+
const add = (value: unknown) => { if (value !== undefined) ids.push(value); };
|
|
799
|
+
add(params.id);
|
|
800
|
+
add(params.task_id);
|
|
801
|
+
add(params.taskId);
|
|
802
|
+
add(params.task_ids);
|
|
803
|
+
add(params.taskIds);
|
|
804
|
+
if (Array.isArray(params.terminal_revisions)) {
|
|
805
|
+
for (const revision of params.terminal_revisions) {
|
|
806
|
+
if (revision && typeof revision === "object") {
|
|
807
|
+
const record = revision as JsonRecord;
|
|
808
|
+
add(record.task_id);
|
|
809
|
+
add(record.taskId);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const flattened: string[] = [];
|
|
814
|
+
for (const value of ids) {
|
|
815
|
+
if (Array.isArray(value)) {
|
|
816
|
+
for (const entry of value) if (typeof entry === "string") flattened.push(entry);
|
|
817
|
+
} else if (typeof value === "string") {
|
|
818
|
+
flattened.push(value);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return [...new Set(flattened)];
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Task ids the supervisor returned for a launch; used to reject a handler that claimed a foreign task. */
|
|
825
|
+
export function extractResultTaskIds(value: unknown, seen = new Set<object>()): string[] {
|
|
826
|
+
const found: string[] = [];
|
|
827
|
+
if (!value || typeof value !== "object") return found;
|
|
828
|
+
if (seen.has(value)) return found;
|
|
829
|
+
seen.add(value);
|
|
830
|
+
if (Array.isArray(value)) {
|
|
831
|
+
for (const entry of value) found.push(...extractResultTaskIds(entry, seen));
|
|
832
|
+
return [...new Set(found)];
|
|
833
|
+
}
|
|
834
|
+
const record = value as Record<string, unknown>;
|
|
835
|
+
const looksLikeTaskId = (entry: unknown): entry is string =>
|
|
836
|
+
typeof entry === "string" && entry.startsWith("bg_") && !entry.startsWith("bg_batch_") && isValidTaskId(entry);
|
|
837
|
+
for (const key of ["taskId", "task_id", "taskIds", "task_ids"]) {
|
|
838
|
+
const entry = record[key];
|
|
839
|
+
if (typeof entry === "string") found.push(entry);
|
|
840
|
+
else if (Array.isArray(entry)) {
|
|
841
|
+
for (const item of entry) if (typeof item === "string") found.push(item);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// A read result may expose the task as `id`, and a list-shaped result may
|
|
845
|
+
// put task ids under `task`/`tasks`. Treat only background-task-shaped ids
|
|
846
|
+
// as tasks so operation and request ids are not mistaken for them.
|
|
847
|
+
if (looksLikeTaskId(record.id)) found.push(record.id);
|
|
848
|
+
for (const key of ["task", "tasks"]) {
|
|
849
|
+
const entries = Array.isArray(record[key]) ? record[key] as unknown[] : [record[key]];
|
|
850
|
+
for (const entry of entries) {
|
|
851
|
+
if (entry && typeof entry === "object" && looksLikeTaskId((entry as Record<string, unknown>).id)) {
|
|
852
|
+
found.push((entry as Record<string, string>).id);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
for (const [key, entry] of Object.entries(record)) {
|
|
857
|
+
if (key === "taskId" || key === "task_id" || key === "taskIds" || key === "task_ids" || key === "id" || key === "task" || key === "tasks") continue;
|
|
858
|
+
if (entry && typeof entry === "object") found.push(...extractResultTaskIds(entry, seen));
|
|
859
|
+
}
|
|
860
|
+
return [...new Set(found)];
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
export function isValidTaskId(value: string): boolean {
|
|
864
|
+
return /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export function isLaunchTool(tool: string, params: JsonRecord): boolean {
|
|
868
|
+
if (OPERATION_LAUNCH_TOOL_NAMES.includes(tool as OperationBridgeToolName)) return true;
|
|
869
|
+
// Wrapper names are not exposed by this bridge, but keeping the classifier
|
|
870
|
+
// correct makes the host safe if the parent later adds one to the handshake.
|
|
871
|
+
if (tool === "bg_task" || tool === "bg_status") return params.action === "spawn" || params.action === "watch";
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
export function isInsideWorkspace(workspace: string, candidate: string): boolean {
|
|
876
|
+
const root = resolve(workspace);
|
|
877
|
+
const path = resolve(root, candidate);
|
|
878
|
+
return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// ---- request envelope and wait-result validation -------------------------------------------------
|
|
882
|
+
|
|
883
|
+
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
884
|
+
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
|
|
885
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,199}$/;
|
|
886
|
+
|
|
887
|
+
export function validateRequestEnvelope(value: unknown): { ok: true; envelope: OperationBridgeRequestEnvelope } | { ok: false; id: string; message: string } {
|
|
888
|
+
const id = value && typeof value === "object" && typeof (value as JsonRecord).id === "string"
|
|
889
|
+
? (value as JsonRecord).id as string
|
|
890
|
+
: "";
|
|
891
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, id, message: "request must be an object" };
|
|
892
|
+
const record = value as JsonRecord;
|
|
893
|
+
if (record.v !== OPERATION_BRIDGE_VERSION) return { ok: false, id, message: "unsupported bridge version" };
|
|
894
|
+
if (typeof record.id !== "string" || !REQUEST_ID_PATTERN.test(record.id)) return { ok: false, id, message: "invalid request id" };
|
|
895
|
+
if (typeof record.token !== "string" || record.token.length < 16 || record.token.length > 512 || /[\r\n]/.test(record.token)) {
|
|
896
|
+
return { ok: false, id, message: "invalid token shape" };
|
|
897
|
+
}
|
|
898
|
+
if (typeof record.runId !== "string" || !ID_PATTERN.test(record.runId)) return { ok: false, id, message: "invalid run id" };
|
|
899
|
+
if (typeof record.conversationId !== "string" || !ID_PATTERN.test(record.conversationId)) {
|
|
900
|
+
return { ok: false, id, message: "invalid conversation id" };
|
|
901
|
+
}
|
|
902
|
+
if (typeof record.method !== "string" || !OPERATION_BRIDGE_METHODS.includes(record.method as OperationBridgeMethod)) {
|
|
903
|
+
return { ok: false, id, message: "unknown method" };
|
|
904
|
+
}
|
|
905
|
+
if (record.params !== undefined && record.params !== null &&
|
|
906
|
+
(typeof record.params !== "object" || Array.isArray(record.params))) {
|
|
907
|
+
return { ok: false, id, message: "params must be an object" };
|
|
908
|
+
}
|
|
909
|
+
if (record.key !== undefined && (typeof record.key !== "string" || !IDEMPOTENCY_KEY_PATTERN.test(record.key))) {
|
|
910
|
+
return { ok: false, id, message: "invalid idempotency key" };
|
|
911
|
+
}
|
|
912
|
+
return {
|
|
913
|
+
ok: true,
|
|
914
|
+
envelope: {
|
|
915
|
+
v: OPERATION_BRIDGE_VERSION,
|
|
916
|
+
id: record.id,
|
|
917
|
+
token: record.token,
|
|
918
|
+
runId: record.runId,
|
|
919
|
+
conversationId: record.conversationId,
|
|
920
|
+
method: record.method as OperationBridgeMethod,
|
|
921
|
+
params: cloneJson(record.params) as JsonRecord | undefined,
|
|
922
|
+
...(record.key === undefined ? {} : { key: record.key }),
|
|
923
|
+
},
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
export function validateHandshakeParams(params: unknown): { ok: true; client?: { name: string; version: string } } | { ok: false; message: string } {
|
|
928
|
+
const result = validateJsonSchema(HANDSHAKE_SCHEMA, params);
|
|
929
|
+
if (!result.ok) return { ok: false, message: result.message };
|
|
930
|
+
const record = (params ?? {}) as JsonRecord;
|
|
931
|
+
const client = record.client && typeof record.client === "object"
|
|
932
|
+
? record.client as { name?: unknown; version?: unknown }
|
|
933
|
+
: undefined;
|
|
934
|
+
return {
|
|
935
|
+
ok: true,
|
|
936
|
+
...(client && typeof client.name === "string" && typeof client.version === "string"
|
|
937
|
+
? { client: { name: client.name, version: client.version } }
|
|
938
|
+
: {}),
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
export type NormalizedWaitOutcome = "succeeded" | "failed" | "cancelled" | "lost";
|
|
943
|
+
|
|
944
|
+
export interface NormalizedWaitDependency {
|
|
945
|
+
taskId?: string;
|
|
946
|
+
operationId?: string;
|
|
947
|
+
terminalRevision: number;
|
|
948
|
+
terminalOutcome: NormalizedWaitOutcome | null;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
export interface NormalizedWaitResult {
|
|
952
|
+
waitId: string;
|
|
953
|
+
generation: number;
|
|
954
|
+
phase: string;
|
|
955
|
+
settled: boolean;
|
|
956
|
+
park: boolean;
|
|
957
|
+
taskIds: string[];
|
|
958
|
+
dependencies: NormalizedWaitDependency[];
|
|
959
|
+
continuationNote?: string;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
export function normalizeWaitForOperationsResult(value: unknown): { ok: true; result: NormalizedWaitResult } | { ok: false; message: string } {
|
|
963
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, message: "wait result must be an object" };
|
|
964
|
+
const record = value as JsonRecord;
|
|
965
|
+
const nested = record.operationWait && typeof record.operationWait === "object"
|
|
966
|
+
? record.operationWait as JsonRecord
|
|
967
|
+
: undefined;
|
|
968
|
+
const source = nested ?? record;
|
|
969
|
+
const waitRecord = record.wait && typeof record.wait === "object" ? record.wait as JsonRecord : undefined;
|
|
970
|
+
const waitId = source.waitId ?? source.wait_id ?? waitRecord?.waitId;
|
|
971
|
+
const generation = source.generation ?? waitRecord?.generation;
|
|
972
|
+
const phase = source.phase ?? waitRecord?.phase ?? "waiting";
|
|
973
|
+
if (typeof waitId !== "string" || !waitId) return { ok: false, message: "wait result has no wait id" };
|
|
974
|
+
if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 1) {
|
|
975
|
+
return { ok: false, message: "wait result has no valid generation" };
|
|
976
|
+
}
|
|
977
|
+
if (typeof phase !== "string" || !phase) return { ok: false, message: "wait result has no phase" };
|
|
978
|
+
const origin = waitRecord?.origin && typeof waitRecord.origin === "object"
|
|
979
|
+
? waitRecord.origin as JsonRecord
|
|
980
|
+
: undefined;
|
|
981
|
+
const rawTaskIds = source.taskIds ?? source.task_ids ?? record.taskIds ?? record.task_ids ??
|
|
982
|
+
origin?.taskIds ?? origin?.task_ids ?? [];
|
|
983
|
+
const taskIds = Array.isArray(rawTaskIds) ? rawTaskIds.filter((entry): entry is string => typeof entry === "string") : [];
|
|
984
|
+
if (taskIds.some((taskId) => !isValidTaskId(taskId))) return { ok: false, message: "wait result contains an invalid task id" };
|
|
985
|
+
const rawDependencies = source.dependencies ?? record.dependencies ?? waitRecord?.dependencies;
|
|
986
|
+
const dependencies: NormalizedWaitDependency[] = [];
|
|
987
|
+
if (Array.isArray(rawDependencies)) {
|
|
988
|
+
for (const entry of rawDependencies) {
|
|
989
|
+
if (!entry || typeof entry !== "object") continue;
|
|
990
|
+
const dep = entry as JsonRecord;
|
|
991
|
+
const revision = dep.terminalRevision ?? dep.terminal_revision;
|
|
992
|
+
const outcome = dep.terminalOutcome ?? dep.terminal_outcome;
|
|
993
|
+
if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
|
|
994
|
+
return { ok: false, message: "wait dependency has no valid terminal revision" };
|
|
995
|
+
}
|
|
996
|
+
if (outcome !== null && outcome !== undefined && !["succeeded", "failed", "cancelled", "lost"].includes(outcome as string)) {
|
|
997
|
+
return { ok: false, message: "wait dependency has an unknown outcome" };
|
|
998
|
+
}
|
|
999
|
+
const operationId = dep.operationId ?? dep.operation_id;
|
|
1000
|
+
const taskId = dep.taskId ?? dep.task_id;
|
|
1001
|
+
if (operationId !== undefined && (typeof operationId !== "string" || !operationId)) {
|
|
1002
|
+
return { ok: false, message: "wait dependency has an invalid operation id" };
|
|
1003
|
+
}
|
|
1004
|
+
if (taskId !== undefined && (typeof taskId !== "string" || !isValidTaskId(taskId))) {
|
|
1005
|
+
return { ok: false, message: "wait dependency has an invalid task id" };
|
|
1006
|
+
}
|
|
1007
|
+
dependencies.push({
|
|
1008
|
+
...(typeof taskId === "string" ? { taskId } : {}),
|
|
1009
|
+
...(typeof operationId === "string" ? { operationId } : {}),
|
|
1010
|
+
terminalRevision: revision,
|
|
1011
|
+
terminalOutcome: (outcome ?? null) as NormalizedWaitOutcome | null,
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const settled = source.settled === true || record.settled === true || record.settledAtRegistration === true ||
|
|
1016
|
+
waitRecord?.settled === true || (dependencies.length > 0 && dependencies.every((dep) => dep.terminalRevision > 0));
|
|
1017
|
+
const park = source.park === true || record.park === true ||
|
|
1018
|
+
(waitRecord?.park !== undefined && waitRecord.park !== null);
|
|
1019
|
+
const continuationNote = source.continuationNote ?? source.continuation_note ??
|
|
1020
|
+
record.continuationNote ?? record.continuation_note ?? waitRecord?.continuationNote;
|
|
1021
|
+
if (findSecretField(value)) return { ok: false, message: "wait result contains a credential-shaped field" };
|
|
1022
|
+
return {
|
|
1023
|
+
ok: true,
|
|
1024
|
+
result: {
|
|
1025
|
+
waitId,
|
|
1026
|
+
generation,
|
|
1027
|
+
phase,
|
|
1028
|
+
settled,
|
|
1029
|
+
park,
|
|
1030
|
+
taskIds,
|
|
1031
|
+
dependencies,
|
|
1032
|
+
...(typeof continuationNote === "string" ? { continuationNote } : {}),
|
|
1033
|
+
},
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
export function validateCheckpointParams(params: unknown): { ok: true; value: JsonRecord } | { ok: false; message: string } {
|
|
1038
|
+
const result = validateJsonSchema(CHECKPOINT_SCHEMA, params);
|
|
1039
|
+
if (!result.ok) return { ok: false, message: result.message };
|
|
1040
|
+
if (findSecretField(params)) return { ok: false, message: "checkpoint contains a credential-shaped field" };
|
|
1041
|
+
return { ok: true, value: cloneJson(params) as JsonRecord };
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
export function validateParkFailedParams(params: unknown): { ok: true; value: JsonRecord } | { ok: false; message: string } {
|
|
1045
|
+
const result = validateJsonSchema(PARK_FAILED_SCHEMA, params);
|
|
1046
|
+
if (!result.ok) return { ok: false, message: result.message };
|
|
1047
|
+
return { ok: true, value: cloneJson(params) as JsonRecord };
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// ---- cloning and freezing -------------------------------------------------
|
|
1051
|
+
|
|
1052
|
+
export function cloneJson<T>(value: T): T {
|
|
1053
|
+
if (value === undefined) return value;
|
|
1054
|
+
return JSON.parse(JSON.stringify(value)) as T;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
export function deepFreeze<T>(value: T): T {
|
|
1058
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1059
|
+
Object.freeze(value);
|
|
1060
|
+
for (const entry of Object.values(value as Record<string, unknown>)) deepFreeze(entry);
|
|
1061
|
+
}
|
|
1062
|
+
return value;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
export function deepFreezeCopy<T>(value: T): T {
|
|
1066
|
+
return deepFreeze(cloneJson(value));
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
export function endpointKind(endpoint: string): "unix" | "tcp" {
|
|
1070
|
+
if (endpoint.startsWith("unix://")) return "unix";
|
|
1071
|
+
if (endpoint.startsWith("tcp://")) return "tcp";
|
|
1072
|
+
throw new OperationBridgeError("invalid-request", "endpoint must be unix:// or tcp://");
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
export function parseBridgeEndpoint(endpoint: string): { kind: "unix"; path: string } | { kind: "tcp"; host: string; port: number } {
|
|
1076
|
+
if (endpoint.startsWith("unix://")) {
|
|
1077
|
+
const path = endpoint.slice("unix://".length);
|
|
1078
|
+
if (!path.startsWith("/") || path.length > 4_096 || path.includes("\0")) {
|
|
1079
|
+
throw new OperationBridgeError("invalid-request", "invalid unix endpoint");
|
|
1080
|
+
}
|
|
1081
|
+
return { kind: "unix", path };
|
|
1082
|
+
}
|
|
1083
|
+
if (endpoint.startsWith("tcp://")) {
|
|
1084
|
+
const url = new URL(endpoint);
|
|
1085
|
+
const port = Number(url.port);
|
|
1086
|
+
if (!url.hostname || !Number.isInteger(port) || port < 1 || port > 65_535) {
|
|
1087
|
+
throw new OperationBridgeError("invalid-request", "invalid tcp endpoint");
|
|
1088
|
+
}
|
|
1089
|
+
return { kind: "tcp", host: url.hostname, port };
|
|
1090
|
+
}
|
|
1091
|
+
throw new OperationBridgeError("invalid-request", "endpoint must be unix:// or tcp://");
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/** Redacts a known token or token-shaped assignment from a model-facing error string. */
|
|
1095
|
+
export function redactSecret(message: string, token?: string): string {
|
|
1096
|
+
let redacted = message.replace(/\b(authorization|token|access_token|secret|password)\s*[:=]\s*\S+/gi, "$1=[redacted]");
|
|
1097
|
+
if (token && token.length >= 8) redacted = redacted.split(token).join("[redacted]");
|
|
1098
|
+
return redacted.replace(/[\r\n]+/g, " ").slice(0, 2_000);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
export function operationBridgeErrorBody(error: unknown, token?: string): OperationBridgeErrorBody {
|
|
1102
|
+
const bridge = isOperationBridgeError(error) ? error : undefined;
|
|
1103
|
+
const tool = error instanceof OperationToolError ? error : undefined;
|
|
1104
|
+
return {
|
|
1105
|
+
code: bridge?.code ?? (tool ? "tool-error" : "handler-error"),
|
|
1106
|
+
message: redactSecret(error instanceof Error ? error.message : String(error), token),
|
|
1107
|
+
retryable: bridge?.retryable ?? false,
|
|
1108
|
+
};
|
|
1109
|
+
}
|