@mono-agent/agent-runtime 0.18.0 → 0.18.2

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.
@@ -85,6 +85,9 @@ import { instrumentLiveInputAppliedEvents } from "./live-input-events.js";
85
85
  * Returned options are never copied into router telemetry.
86
86
  * @property {AgentRuntimeInstance} [runtime]
87
87
  * @property {Object<string, *>} [options]
88
+ * @property {{allowedTools?: ReadonlyArray<string>, disallowedTools?: ReadonlyArray<string>, permissionMode?: string}} [policyOptions]
89
+ * Provider-specific projection of the logical tool policy. This deliberately
90
+ * cannot replace any other protected request field.
88
91
  * @property {() => (void|Promise<void>)} [cleanup]
89
92
  */
90
93
 
@@ -243,6 +246,7 @@ export function createRouterRuntime({ host = {}, chain = [], routeSafety = "unif
243
246
  attemptCleanup = resolution?.cleanup;
244
247
  if (resolveAttempt !== undefined) {
245
248
  callOptions = mergeAttemptOptions(callOptions, resolution?.options);
249
+ callOptions = mergeAttemptPolicyOptions(callOptions, resolution?.policyOptions);
246
250
  }
247
251
  if (routeSafety === "per-route-native") {
248
252
  callOptions = projectPerRouteNativeOptions(entry, callOptions);
@@ -804,6 +808,33 @@ function normalizeAttemptResolution(value) {
804
808
  if (value.cleanup !== undefined && typeof value.cleanup !== "function") {
805
809
  throw new Error("route attempt resolver cleanup must be a function");
806
810
  }
811
+ return {
812
+ ...value,
813
+ ...(value.policyOptions === undefined
814
+ ? {}
815
+ : { policyOptions: normalizeAttemptPolicyOptions(value.policyOptions) }),
816
+ };
817
+ }
818
+
819
+ const ATTEMPT_POLICY_OPTION_KEYS = new Set(["allowedTools", "disallowedTools", "permissionMode"]);
820
+
821
+ function normalizeAttemptPolicyOptions(value) {
822
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
823
+ throw new Error("route attempt resolver policyOptions must be an object");
824
+ }
825
+ for (const key of Object.keys(value)) {
826
+ if (!ATTEMPT_POLICY_OPTION_KEYS.has(key)) {
827
+ throw new Error(`route attempt resolver policyOptions cannot override ${key}`);
828
+ }
829
+ }
830
+ for (const key of ["allowedTools", "disallowedTools"]) {
831
+ if (value[key] !== undefined && !Array.isArray(value[key])) {
832
+ throw new Error(`route attempt resolver policyOptions.${key} must be an array or undefined`);
833
+ }
834
+ }
835
+ if (value.permissionMode !== undefined && typeof value.permissionMode !== "string") {
836
+ throw new Error("route attempt resolver policyOptions.permissionMode must be a string or undefined");
837
+ }
807
838
  return value;
808
839
  }
809
840
 
@@ -826,6 +857,17 @@ function mergeAttemptOptions(base, resolved) {
826
857
  return merged;
827
858
  }
828
859
 
860
+ function mergeAttemptPolicyOptions(base, policyOptions) {
861
+ if (policyOptions === undefined) return base;
862
+ const merged = { ...base };
863
+ for (const key of ATTEMPT_POLICY_OPTION_KEYS) {
864
+ if (!Object.hasOwn(policyOptions, key)) continue;
865
+ if (policyOptions[key] === undefined) delete merged[key];
866
+ else merged[key] = policyOptions[key];
867
+ }
868
+ return merged;
869
+ }
870
+
829
871
  /**
830
872
  * @param {Object<string, *>} options
831
873
  * @returns {Object<string, *>}
package/src/ai/types.js CHANGED
@@ -40,10 +40,80 @@
40
40
  */
41
41
 
42
42
  /**
43
- * @typedef {{type: string, [key: string]: *}} RuntimeEvent
44
- * Structured runtime/telemetry event. `type` is the only required field;
45
- * every event kind (tool_approval_pending, provider_failover_started,
46
- * context_compaction_applied, ...) adds its own extra fields.
43
+ * @typedef {Object} RuntimeNativeSubagentDefinition
44
+ * One caller-defined Claude native `Task` profile. Codex collaboration-agent
45
+ * definitions are owned by Codex and are not represented by this type.
46
+ * @property {string} name
47
+ * @property {string} [displayName]
48
+ * @property {string} [description]
49
+ * @property {string} [helperSystemPrompt]
50
+ * @property {string} [instructions]
51
+ * @property {ReadonlyArray<string>} [allowedTools]
52
+ * @property {ReadonlyArray<string>} [disallowedTools]
53
+ * @property {string | RuntimeModelRef} [modelRef]
54
+ * @property {RuntimeModelRef} [model]
55
+ * @property {string} [effort]
56
+ * @property {Object<string, Object>} [mcpServers]
57
+ */
58
+
59
+ /**
60
+ * @typedef {Object} RuntimeNativeSubagentsOptions
61
+ * Caller-defined native profiles are supported only by the Claude bridges.
62
+ * Codex owns its collaboration agents; use `codexLoadProjectDocs` when those
63
+ * agents should receive repository instructions.
64
+ * @property {"claude"} provider
65
+ * @property {ReadonlyArray<RuntimeNativeSubagentDefinition>} teammates
66
+ */
67
+
68
+ /**
69
+ * @typedef {Object} RuntimeSubagentIdentity
70
+ * Provider-neutral identity attached to every `subagent_activity` event.
71
+ * @property {string} id The canonical parent attachment key: the initiating
72
+ * parent tool-use id when the provider exposes it, or a stable synthetic key
73
+ * for an orphan lifecycle record. A provider-native task/thread id never replaces it.
74
+ * @property {string} [nativeId] Provider-native task or thread id, retained only
75
+ * as diagnostic/correlation metadata.
76
+ * @property {string} name Provider-neutral profile/agent name.
77
+ * @property {number} callIndex Provider call-order ordinal; consumers must not
78
+ * use it as an identity key.
79
+ * @property {string} [label] Short task label or description.
80
+ * @property {string} [agentPath] Provider-reported ancestry for a
81
+ * nested native agent. Informational only; `id` remains the attachment key.
82
+ * @property {number} [costUsd] Priced delegation cost, when the runtime can
83
+ * attribute it to this subagent.
84
+ */
85
+
86
+ /**
87
+ * @typedef {"agent_started"|"started"|"completed"|"message"|"agent_completed"} RuntimeSubagentActivityPhase
88
+ * `agent_started`/`agent_completed` bracket the delegation; `started`/`completed`
89
+ * bracket one child tool call; `message` carries optional child-only prose or
90
+ * thinking and must never be treated as parent answer text or a completed tool.
91
+ */
92
+
93
+ /**
94
+ * @typedef {Object} RuntimeSubagentActivityEvent
95
+ * One normalized native or in-process subagent activity event.
96
+ * @property {"subagent_activity"} type
97
+ * @property {RuntimeSubagentIdentity} subagent
98
+ * @property {RuntimeSubagentActivityPhase} phase
99
+ * @property {string} id Unique activity-row id, namespaced from the canonical
100
+ * `subagent.id` for lifecycle and tool rows.
101
+ * @property {string} [name]
102
+ * @property {*} [arguments]
103
+ * @property {*} [content]
104
+ * @property {"text"|"thinking"|"status"|"warning"|"error"} [kind] Present on a
105
+ * `message` phase when known.
106
+ * @property {"assistant"|"user"} [role] Present on a `message` phase when known.
107
+ * @property {boolean} [isError]
108
+ * @property {number} [executionMs]
109
+ * @property {number} [totalTokens]
110
+ */
111
+
112
+ /**
113
+ * @typedef {RuntimeSubagentActivityEvent | {type: string, [key: string]: *}} RuntimeEvent
114
+ * Structured runtime/telemetry event. Subagent activity uses the normalized
115
+ * shape above; every other event kind (tool_approval_pending,
116
+ * provider_failover_started, context_compaction, ...) adds its own fields.
47
117
  */
48
118
 
49
119
  /** @typedef {"uniform"|"per-route-native"} RuntimeRouteSafetyMode */
@@ -165,12 +235,26 @@
165
235
  * @property {RuntimePromptOverrides} [prompts] Per-run prompt-fragment overrides (run wins over the host default).
166
236
  * @property {import('./providers/acp-client.js').AcpClientHostOptions["resolveAcpProfile"]} [resolveAcpProfile] Per-run ACP profile resolver; wins over the host default.
167
237
  * @property {import('./providers/acp-client.js').AcpClientHostOptions["onAcpInteractionRequest"]} [onAcpInteractionRequest] Per-run ACP permission/elicitation callback; wins over the host default.
238
+ * @property {Uint8Array} [acpSessionTokenKey] Host-owned 32-byte key for confidential authenticated ACP session handles. Required for every ACP task run.
168
239
  * @property {{backend?: "auto"|"searxng"|"keyless", endpoint?: string}} [webSearchConfig] Run-scoped WebSearch backend configuration.
169
240
  * @property {{render?: "never"|"auto", browserCommand?: string}} [webFetchConfig] Run-scoped WebFetch extraction/render configuration.
170
241
  * @property {"sequential"|"safe-parallel"} [piToolExecutionMode] Pi built-in tool scheduling mode. Safe parallelism is the default.
171
242
  * @property {"one-at-a-time"|"all"} [piToolParallelismMode] DEPRECATED. Compatibility alias mapped to piToolExecutionMode.
172
243
  * @property {Object} [settings] DEPRECATED. Legacy flat settings bag; consumed only as a per-group FALLBACK when the corresponding typed object (`toolLimits` / `compaction`) is absent. Consuming any key emits one `deprecated_settings_option` runtime_warning per run. Migrate via resolveRuntimePolicies (@mono-agent/runtime-adapter).
173
- * @property {Object} [nativeSubagents] Same-runtime teammate helpers exposed through native provider subagent surfaces.
244
+ * @property {ReadonlyArray<"user" | "project" | "local">} [settingSources] Claude Agent SDK only. Filesystem
245
+ * settings the SDK may load for this run. Omitted/empty disables user, project, and local sources, including their
246
+ * CLAUDE.md, hooks, plugins, and on-disk agent profiles. Anthropic managed settings remain in force and may still
247
+ * configure hooks or plugins; this option is not a managed-policy bypass. Each opted-in source may execute configured
248
+ * hooks and plugins, so enable only trusted settings and avoid these sources in an untrusted checkout. Include
249
+ * `"project"`/`"user"` to let the native `Task` tool discover `.claude/agents` definitions. Unrecognized entries are
250
+ * dropped. The Claude Code CLI bridge does not take this option: that binary performs its own settings discovery and
251
+ * mono-agent passes no `--setting-sources`, so a CLI run already reads the host config regardless of this value.
252
+ * @property {boolean} [codexLoadProjectDocs] Codex app-server only. Omitted/false starts the managed app-server with
253
+ * `project_doc_max_bytes=0`, preventing automatic repository-instruction discovery. True restores Codex's native
254
+ * project-doc loading defaults. An explicit `codexAppServerArgs` array wins over this convenience option.
255
+ * @property {RuntimeNativeSubagentsOptions} [nativeSubagents] Caller-defined Claude native `Task` profiles. Direct
256
+ * Codex owns its collaboration agents and rejects configured teammate definitions; `codexLoadProjectDocs` controls
257
+ * whether Codex loads repository instructions for its own agents.
174
258
  * @property {RuntimeSubagentsOptions} [subagents] In-process `Agent` built-in: profiles, caps, and the nested-run callback.
175
259
  * @property {Object} [diagnosticsSeed] Set by createRouterRuntime (ai/runtime/router.js) with a `resume_snapshot` when
176
260
  * failing over mid-chain; a host-level coordinator may relay it forward (see agent/transcript.js), not read by any
@@ -182,7 +266,7 @@
182
266
 
183
267
  /**
184
268
  * @typedef {RuntimeRunOptions
185
- * & Pick<AgentRuntimeHostOptions, "resolveCustomPricing" | "resolvePiApiKey" | "resolveAcpProfile" | "onAcpInteractionRequest" | "persistArtifact" | "onCompactionRecorded" | "onToolApprovalRequest" | "toolRiskTiers" | "approvalDefaultRiskTier" | "approvalTimeoutMs" | "approvalAlwaysAllowTools">
269
+ * & Pick<AgentRuntimeHostOptions, "resolveCustomPricing" | "resolvePiApiKey" | "resolveAcpProfile" | "onAcpInteractionRequest" | "acpSessionTokenKey" | "persistArtifact" | "onCompactionRecorded" | "onToolApprovalRequest" | "toolRiskTiers" | "approvalDefaultRiskTier" | "approvalTimeoutMs" | "approvalAlwaysAllowTools">
186
270
  * & {runtimeBrand: import('../runtime-brand.js').RuntimeBrand, toolContext?: import('../agent/tools/shared/tool-context.js').ToolContext, observerHub: {emit: (event: RuntimeEvent) => void, flush: () => Promise<void>}}
187
271
  * } RuntimeRequest
188
272
  * The request shape a bridge's `execute(systemPrompt, req)` receives as its
@@ -221,11 +305,14 @@
221
305
 
222
306
  /**
223
307
  * @typedef {Object} RuntimeInlineSubagentsOptions
224
- * Policy for subagents the model authors at call time rather than picking from
225
- * `definitions`. Absent suppresses authoring entirely.
308
+ * Policy for the runtime-owned general-purpose helper and subagents the model
309
+ * authors at call time rather than picking from `definitions`. Absent
310
+ * suppresses authoring entirely and leaves general-purpose on its safe default.
226
311
  * @property {boolean} [enabled] Only `false` turns authoring off.
227
- * @property {ReadonlyArray<string>} [allowedTools] Ceiling on what an authored subagent may
228
- * request. Absent means the safe read-only default set, never every built-in.
312
+ * @property {ReadonlyArray<string>} [allowedTools] Ceiling on general-purpose's
313
+ * read-only tools and what an authored subagent may request. Configured
314
+ * definitions keep their explicit contracts. Absent means the safe read-only
315
+ * default set, never every built-in.
229
316
  */
230
317
 
231
318
  /**
@@ -281,7 +368,9 @@
281
368
  * @property {boolean} [supports_skills]
282
369
  * @property {boolean} [supports_builtin_tools]
283
370
  * @property {boolean} [supports_live_input]
284
- * @property {boolean} [supports_native_subagents]
371
+ * @property {boolean} [supports_native_subagents] Whether the bridge exposes provider-native subagent surfaces and
372
+ * normalized activity. This does not imply it accepts caller-defined `nativeSubagents`: Codex owns its collaboration
373
+ * agents, while only the Claude bridges project caller-defined profiles.
285
374
  * @property {boolean} [supports_request_tool_environment]
286
375
  * @property {boolean} [supports_fast_mode]
287
376
  * @property {"projected"|"allow_all_only"} [tool_policy] Whether the bridge can
@@ -364,6 +453,7 @@
364
453
  * @property {import('../pi-auth.js').PiApiKeyResolver} [resolvePiApiKey] See createPiOAuthApiKeyResolver (pi-auth.js) for a ready-made implementation.
365
454
  * @property {import('./providers/acp-client.js').AcpClientHostOptions["resolveAcpProfile"]} [resolveAcpProfile] Default ACP profile resolver; a per-run callback wins.
366
455
  * @property {import('./providers/acp-client.js').AcpClientHostOptions["onAcpInteractionRequest"]} [onAcpInteractionRequest] Default ACP interaction callback; a per-run callback wins.
456
+ * @property {Uint8Array} [acpSessionTokenKey] Default host-owned 32-byte key for confidential authenticated ACP session handles.
367
457
  * @property {(artifact: {filename: string, buffer: Buffer, toolName: string, toolUseId: (string|null)}) => (string|null)} [persistArtifact]
368
458
  * @property {(record: CompactionRecordedPayload) => void} [onCompactionRecorded]
369
459
  * @property {(payload: ApprovalRequestPayload) => Promise<ApprovalDecision>} [onToolApprovalRequest]
package/src/runtime.js CHANGED
@@ -55,6 +55,7 @@ const HOST_KEYS = [
55
55
  "resolvePiApiKey",
56
56
  "resolveAcpProfile",
57
57
  "onAcpInteractionRequest",
58
+ "acpSessionTokenKey",
58
59
  "persistArtifact",
59
60
  "onCompactionRecorded",
60
61
  "onToolApprovalRequest",
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * One ephemeral web-tool controller for one model run. It owns in-memory
3
- * deduplication, result caches, anonymous browser namespaces, and cleanup.
3
+ * deduplication, the fetch result cache, anonymous browser namespaces, and
4
+ * cleanup. Search results are the exception: they live in the process-wide
5
+ * cache above so sibling subagents and later turns can reuse them.
4
6
  *
5
7
  * @param {{searchConfig?: any, fetchConfig?: any, sandboxPolicy?: any, sandboxEngine?: any, ctx?: any, fetchImpl?: typeof fetch, browserRenderer?: any}} [options]
6
8
  */
@@ -18,3 +20,5 @@ export function createWebToolController({ searchConfig, fetchConfig, sandboxPoli
18
20
  fetch(params: any, execution?: {}): Promise<any>;
19
21
  close(): Promise<void>;
20
22
  };
23
+ /** Test hook: the shared cache is module state and would leak between cases. */
24
+ export function __resetSharedSearchCacheForTests(): void;
@@ -68,9 +68,22 @@ export function performWebSearch({ query, limit, alternate_queries, domains, exc
68
68
  truncated: boolean;
69
69
  resultCount: number;
70
70
  providerFailureCount: number;
71
+ rateLimited: boolean;
72
+ cooldownBackends: string[];
71
73
  };
72
74
  error: boolean;
73
75
  }>;
76
+ /**
77
+ * Test hook: restores the shipped throttle values and clears cooldown/spacing
78
+ * state. Module-scoped state would otherwise leak between test cases.
79
+ *
80
+ * @param {{maxConcurrency?: number, minSpacingMs?: number, cooldownMs?: number}} [overrides]
81
+ */
82
+ export function __resetWebSearchThrottleForTests(overrides?: {
83
+ maxConcurrency?: number;
84
+ minSpacingMs?: number;
85
+ cooldownMs?: number;
86
+ }): void;
74
87
  export function parseDuckDuckGoResults(html: any): {
75
88
  title: string;
76
89
  url: string;
@@ -214,6 +214,10 @@ export type AcpClientHostOptions = {
214
214
  cwd?: string;
215
215
  signal?: AbortSignal;
216
216
  context?: Record<string, unknown>;
217
+ /**
218
+ * Host-owned 32-byte key required by operations that emit or consume opaque session handles.
219
+ */
220
+ acpSessionTokenKey?: Uint8Array;
217
221
  };
218
222
  import { AcpClientError } from "./acp-session-tokens.js";
219
223
  import { encodeAcpProviderSessionId } from "./acp-session-tokens.js";
@@ -1,9 +1,15 @@
1
1
  /** @param {string} profileId @returns {string} */
2
2
  export function validateAcpProfileId(profileId: string): string;
3
- /** @param {string} profileId @param {string} sessionId */
4
- export function encodeAcpProviderSessionId(profileId: string, sessionId: string): string;
5
- /** Internal protocol-state decoder. This module is not a package export. @param {string} providerSessionId */
6
- export function decodeAcpProviderSessionId(providerSessionId: string): {
3
+ /** @param {unknown} key @returns {Buffer} */
4
+ export function validateAcpSessionTokenKey(key: unknown): Buffer;
5
+ /** @param {string} profileId @param {string} sessionId @param {Uint8Array} key */
6
+ export function encodeAcpProviderSessionId(profileId: string, sessionId: string, key: Uint8Array): string;
7
+ /**
8
+ * Internal protocol-state decoder. This module is not a package export.
9
+ * @param {string} providerSessionId
10
+ * @param {Uint8Array} key
11
+ */
12
+ export function decodeAcpProviderSessionId(providerSessionId: string, key: Uint8Array): {
7
13
  profileId: string;
8
14
  sessionId: string;
9
15
  };
@@ -13,13 +19,14 @@ export function decodeAcpProviderSessionId(providerSessionId: string): {
13
19
  *
14
20
  * @param {string} providerSessionId
15
21
  * @param {string} expectedProfileId
22
+ * @param {Uint8Array} key Host-owned 32-byte ACP session-token key.
16
23
  * @returns {string}
17
24
  */
18
- export function validateAcpProviderSessionId(providerSessionId: string, expectedProfileId: string): string;
19
- /** @param {string} profileId @param {string} cursor */
20
- export function encodeAcpSessionCursor(profileId: string, cursor: string): string;
21
- /** @param {string} profileId @param {unknown} cursor */
22
- export function decodeAcpSessionCursor(profileId: string, cursor: unknown): string;
25
+ export function validateAcpProviderSessionId(providerSessionId: string, expectedProfileId: string, key: Uint8Array): string;
26
+ /** @param {string} profileId @param {string} cursor @param {Uint8Array} key */
27
+ export function encodeAcpSessionCursor(profileId: string, cursor: string, key: Uint8Array): string;
28
+ /** @param {string} profileId @param {unknown} cursor @param {Uint8Array} key */
29
+ export function decodeAcpSessionCursor(profileId: string, cursor: unknown, key: Uint8Array): string;
23
30
  export class AcpClientError extends Error {
24
31
  /**
25
32
  * @param {string} code
@@ -1,3 +1,16 @@
1
+ /**
2
+ * Open one SDK connection inside an async context that strips payload-bearing
3
+ * SDK console arguments. The SDK starts its detached receive loop during
4
+ * `connect`, so descendants retain this scope without muting concurrent host
5
+ * work or other ACP connections.
6
+ *
7
+ * @template {{closed: Promise<unknown>}} T
8
+ * @param {() => T} connect
9
+ * @returns {T}
10
+ */
11
+ export function connectWithSafeAcpSdkDiagnostics<T extends {
12
+ closed: Promise<unknown>;
13
+ }>(connect: () => T): T;
1
14
  /**
2
15
  * @param {unknown} value
3
16
  * @param {number} [fallback]
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Correlate Claude's live native-agent stream into provider-neutral
3
+ * `subagent_activity` events.
4
+ *
5
+ * `observe()` returns `consumed: true` for every event owned by a native
6
+ * subagent. Provider bridges must not additionally forward or interpret those
7
+ * records as parent events. Non-agent background tasks are consumed without
8
+ * creating activity.
9
+ */
10
+ export function createClaudeSubagentActivityNormalizer(): {
11
+ observe: (raw: Record<string, any>) => {
12
+ consumed: boolean;
13
+ events: {
14
+ type: string;
15
+ subagent: {
16
+ label?: any;
17
+ nativeId?: any;
18
+ id: any;
19
+ name: any;
20
+ callIndex: any;
21
+ };
22
+ }[];
23
+ forwarded?: undefined;
24
+ } | {
25
+ consumed: boolean;
26
+ events: {
27
+ type: string;
28
+ subagent: {
29
+ label?: any;
30
+ nativeId?: any;
31
+ id: any;
32
+ name: any;
33
+ callIndex: any;
34
+ };
35
+ }[];
36
+ forwarded: {
37
+ message: any;
38
+ };
39
+ };
40
+ /** Close every still-open child and its tools exactly once. */
41
+ drain(reason?: string): {
42
+ type: string;
43
+ subagent: {
44
+ label?: any;
45
+ nativeId?: any;
46
+ id: any;
47
+ name: any;
48
+ callIndex: any;
49
+ };
50
+ }[];
51
+ subagentInvoked: () => boolean;
52
+ nativeSubagentsUsed: () => any[];
53
+ };
@@ -73,5 +73,14 @@ export type RouterAttemptResolution = {
73
73
  options?: {
74
74
  [x: string]: any;
75
75
  };
76
+ /**
77
+ * Provider-specific projection of the logical tool policy. This deliberately
78
+ * cannot replace any other protected request field.
79
+ */
80
+ policyOptions?: {
81
+ allowedTools?: ReadonlyArray<string>;
82
+ disallowedTools?: ReadonlyArray<string>;
83
+ permissionMode?: string;
84
+ };
76
85
  cleanup?: () => (void | Promise<void>);
77
86
  };