@stage-labs/metro 0.1.0-beta.293 → 0.1.0-beta.295

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.
Files changed (29) hide show
  1. package/package.json +1 -1
  2. package/runtime/marketplace/plugin/.claude-plugin/plugin.json +1 -1
  3. package/runtime/node_modules/@metro-labs/core/src/runner-activity.ts +42 -5
  4. package/runtime/node_modules/@metro-labs/daemon/src/channels/relay.ts +4 -0
  5. package/runtime/node_modules/@metro-labs/daemon/src/connectors/migration-control.ts +3 -1
  6. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime-discovery.ts +3 -3
  7. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime.ts +12 -6
  8. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-control.ts +16 -3
  9. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-watch.ts +1 -1
  10. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync.ts +8 -1
  11. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay.ts +2 -2
  12. package/runtime/node_modules/@metro-labs/daemon/src/connectors/tools.ts +1 -85
  13. package/runtime/node_modules/@metro-labs/daemon/src/mcp/index.ts +1 -1
  14. package/runtime/node_modules/@metro-labs/daemon/src/mcp/raw-get-stream.ts +25 -13
  15. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session-slot.ts +25 -6
  16. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session.ts +4 -0
  17. package/runtime/node_modules/@metro-labs/http/package.json +1 -0
  18. package/runtime/node_modules/@metro-labs/http/src/connector-delivery-validation.ts +4 -3
  19. package/runtime/node_modules/@metro-labs/http/src/connector-delivery.ts +2 -2
  20. package/runtime/node_modules/@metro-labs/http/src/connector-policy.ts +39 -3
  21. package/runtime/node_modules/@metro-labs/http/src/connector-tools.ts +94 -0
  22. package/runtime/runtime.json +1 -1
  23. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/runner-activity.ts +42 -5
  24. package/runtime/sdk-runner/runner.json +1 -1
  25. package/runtime/sdk-runner/src/activity.ts +14 -20
  26. package/runtime/sdk-runner/src/app.ts +2 -2
  27. package/runtime/sdk-runner/src/errors.ts +131 -0
  28. package/runtime/sdk-runner/src/main.ts +4 -2
  29. package/runtime/sdk-runner/src/runner.ts +25 -11
@@ -2,15 +2,24 @@ import { isRecord } from '@metro-labs/core/is-record';
2
2
 
3
3
  export type ConnectorDecision = 'allow' | 'ask' | 'deny';
4
4
 
5
+ type ToolGroup = 'read' | 'write';
6
+
5
7
  export interface ConnectorPolicy {
6
8
  read?: ConnectorDecision;
7
9
  write?: ConnectorDecision;
8
10
  tools?: Record<string, ConnectorDecision>;
9
11
  }
10
12
 
13
+ export interface ConnectorPolicyLayers {
14
+ organization: ConnectorPolicy;
15
+ agent: ConnectorPolicy;
16
+ }
17
+
11
18
  const RANK: Record<ConnectorDecision, number> = { allow: 0, ask: 1, deny: 2 };
12
19
  const TOOL_RE = /^[A-Za-z0-9_.:/-]{1,256}$/;
13
20
 
21
+ export const validConnectorToolName = (name: string): boolean => TOOL_RE.test(name) && !['__proto__', 'constructor', 'prototype'].includes(name);
22
+
14
23
  const decision = (value: unknown): value is ConnectorDecision => value === 'allow' || value === 'ask' || value === 'deny';
15
24
 
16
25
  export function connectorPolicyOf(value: unknown): ConnectorPolicy {
@@ -30,15 +39,23 @@ function toolPolicyOf(value: unknown): Record<string, ConnectorDecision> {
30
39
  if (!isRecord(value) || Object.keys(value).length > 2000) throw new Error('Invalid connector policy.');
31
40
  const out: Record<string, ConnectorDecision> = {};
32
41
  for (const [name, rule] of Object.entries(value)) {
33
- if (!TOOL_RE.test(name) || ['__proto__', 'constructor', 'prototype'].includes(name) || !decision(rule)) throw new Error('Invalid connector policy.');
42
+ if (!validConnectorToolName(name) || !decision(rule)) throw new Error('Invalid connector policy.');
34
43
  out[name] = rule;
35
44
  }
36
45
  return out;
37
46
  }
38
47
 
48
+ export function connectorPolicyLayersOf(value: unknown): ConnectorPolicyLayers {
49
+ if (!isRecord(value) || Object.keys(value).some((key) => !['organization', 'agent'].includes(key))) throw new Error('Invalid connector policy layers.');
50
+ return { organization: connectorPolicyOf(value.organization), agent: connectorPolicyOf(value.agent) };
51
+ }
52
+
39
53
  const strictest = (...values: (ConnectorDecision | undefined)[]): ConnectorDecision => values.reduce<ConnectorDecision>((held, next) => next !== undefined && RANK[next] > RANK[held] ? next : held, 'allow');
54
+ const toolRule = (policy: ConnectorPolicy, name: string): ConnectorDecision | undefined => policy.tools !== undefined && Object.hasOwn(policy.tools, name) ? policy.tools[name] : undefined;
55
+ const toolGroup = (groups: Record<string, ToolGroup>, name: string): ToolGroup => Object.hasOwn(groups, name) && groups[name] === 'read' ? 'read' : 'write';
56
+ const access = (policy: ConnectorPolicy, name: string, group: ToolGroup): ConnectorDecision => toolRule(policy, name) ?? policy[group] ?? 'allow';
40
57
 
41
- export function combineConnectorPolicies(global: ConnectorPolicy, assignment: ConnectorPolicy): ConnectorPolicy {
58
+ export function combineConnectorPolicies(global: ConnectorPolicy, assignment: ConnectorPolicy, groups?: Record<string, ToolGroup>): ConnectorPolicy {
42
59
  const policies = [connectorPolicyOf(global), connectorPolicyOf(assignment)];
43
60
  const neutral = (policy: ConnectorPolicy): boolean => (policy.read ?? 'allow') === 'allow' && (policy.write ?? 'allow') === 'allow' && Object.keys(policy.tools ?? {}).length === 0;
44
61
  if (neutral(assignment)) return connectorPolicyOf(global);
@@ -48,9 +65,28 @@ export function combineConnectorPolicies(global: ConnectorPolicy, assignment: Co
48
65
  write: strictest(...policies.map((policy) => policy.write)),
49
66
  };
50
67
  const names = new Set(policies.flatMap((policy) => Object.keys(policy.tools ?? {})));
68
+ if (groups === undefined && names.size > 2000) return { read: 'deny', write: 'deny' };
51
69
  if (names.size > 0) {
52
70
  out.tools = {};
53
- for (const name of names) out.tools[name] = strictest(...policies.flatMap((policy) => [policy.read, policy.write, policy.tools?.[name]]));
71
+ for (const name of names) {
72
+ out.tools[name] = groups === undefined
73
+ ? strictest(...policies.flatMap((policy) => [policy.read, policy.write, toolRule(policy, name)]))
74
+ : strictest(...policies.map((policy) => access(policy, name, toolGroup(groups, name))));
75
+ }
54
76
  }
55
77
  return out;
56
78
  }
79
+
80
+ export function effectiveConnectorPolicy(row: { policy: ConnectorPolicy; policyLayers?: ConnectorPolicyLayers }, groups: Record<string, ToolGroup>): ConnectorPolicy {
81
+ const layers = row.policyLayers;
82
+ return layers === undefined ? connectorPolicyOf(row.policy) : combineConnectorPolicies(layers.organization, layers.agent, groups);
83
+ }
84
+
85
+ export function connectorPoliciesBlocked(layers: ConnectorPolicyLayers): boolean {
86
+ const policies = [layers.organization, layers.agent];
87
+ const names = new Set(policies.flatMap((policy) => Object.keys(policy.tools ?? {})));
88
+ return (['read', 'write'] as const).every((group) =>
89
+ strictest(...policies.map((policy) => policy[group])) === 'deny' &&
90
+ [...names].every((name) => strictest(...policies.map((policy) => access(policy, name, group))) === 'deny'),
91
+ );
92
+ }
@@ -0,0 +1,94 @@
1
+ import { isRecord } from '@metro-labs/core/is-record';
2
+ import { errMsg, log } from '@metro-labs/core/log';
3
+ import type { FetchLike } from '@metro-labs/core/stations/oauth';
4
+ import { authHeaders, INITIALIZE, mcpPost, payloadOf, type ConnectorAuth } from './connector-mcp.js';
5
+ import { ConnectorUnauthorized, refused } from './connector-url.js';
6
+
7
+ export interface RemoteTool {
8
+ name: string;
9
+ title: string;
10
+ description: string;
11
+ readOnly: boolean;
12
+ }
13
+
14
+ const TIMEOUT_MS = 15_000;
15
+ const MAX_PAGES = 100;
16
+ const MAX_TOOLS = 2000;
17
+
18
+ function resultOf(text: string, contentType: string): Record<string, unknown> | null {
19
+ let parsed: unknown = null;
20
+ try {
21
+ parsed = JSON.parse(payloadOf(text, contentType));
22
+ } catch {
23
+ return null;
24
+ }
25
+ return isRecord(parsed) && isRecord(parsed.result) ? parsed.result : null;
26
+ }
27
+
28
+ async function rpc(url: URL, auth: ConnectorAuth, session: Map<string, string>, body: unknown, fetchImpl?: FetchLike): Promise<Record<string, unknown> | null> {
29
+ const res = await mcpPost(url, auth, body, { timeoutMs: TIMEOUT_MS, headers: Object.fromEntries(session), fetch: fetchImpl });
30
+ const id = res.headers.get('mcp-session-id');
31
+ if (id !== null && id !== '') session.set('mcp-session-id', id);
32
+ const text = await res.text().catch(() => '');
33
+ if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorized(`${url.hostname} rejected the credential; connect it again`, 400);
34
+ if (!res.ok) throw refused(`${url.hostname} answered ${String(res.status)}`);
35
+ return resultOf(text, res.headers.get('content-type') ?? '');
36
+ }
37
+
38
+ function toTool(raw: unknown): RemoteTool | null {
39
+ if (!isRecord(raw) || typeof raw.name !== 'string') return null;
40
+ const annotations = isRecord(raw.annotations) ? raw.annotations : {};
41
+ const title = typeof raw.title === 'string' && raw.title !== '' ? raw.title : raw.name;
42
+ return { name: raw.name, title, description: typeof raw.description === 'string' ? raw.description : '', readOnly: annotations.readOnlyHint === true };
43
+ }
44
+
45
+ async function endSession(url: URL, auth: ConnectorAuth, session: Map<string, string>, fetchImpl?: FetchLike): Promise<void> {
46
+ if (!session.has('mcp-session-id')) return;
47
+ try {
48
+ const send = fetchImpl ?? fetch;
49
+ const res = await send(url.toString(), { method: 'DELETE', redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT_MS), headers: { ...authHeaders(auth), ...Object.fromEntries(session) } });
50
+ if (res.ok) await res.body?.pipeTo(new WritableStream<Uint8Array>());
51
+ else await res.body?.cancel();
52
+ } catch (err) {
53
+ log.debug(fetchImpl === undefined ? { host: url.hostname, err: errMsg(err) } : {}, 'connector-tools: the remote declined to end the session');
54
+ }
55
+ }
56
+
57
+ function addTools(result: Record<string, unknown> | null, tools: Map<string, RemoteTool>): unknown {
58
+ if (result === null || !Array.isArray(result.tools)) throw refused('The provider did not return a complete tool list.');
59
+ for (const raw of result.tools) {
60
+ const tool = toTool(raw);
61
+ if (tool === null || tools.has(tool.name)) throw refused('The provider returned an invalid tool list.');
62
+ tools.set(tool.name, tool);
63
+ if (tools.size > MAX_TOOLS) throw refused('The provider returned too many tools.');
64
+ }
65
+ return result.nextCursor;
66
+ }
67
+
68
+ async function walkTools(url: URL, auth: ConnectorAuth, session: Map<string, string>, fetchImpl?: FetchLike): Promise<RemoteTool[]> {
69
+ const tools = new Map<string, RemoteTool>();
70
+ const cursors = new Set<string>();
71
+ let cursor = '';
72
+ for (let page = 0; page < MAX_PAGES; page += 1) {
73
+ const result = await rpc(url, auth, session, { jsonrpc: '2.0', id: 2 + page, method: 'tools/list', params: cursor === '' ? {} : { cursor } }, fetchImpl);
74
+ const next = addTools(result, tools);
75
+ if (next === undefined || next === null || next === '') return [...tools.values()];
76
+ if (typeof next !== 'string' || cursors.has(next)) throw refused('The provider did not return a complete tool list.');
77
+ cursors.add(next);
78
+ cursor = next;
79
+ }
80
+ throw refused('The provider did not return a complete tool list.');
81
+ }
82
+
83
+ export async function listRemoteTools(url: URL, auth: ConnectorAuth, fetchImpl?: FetchLike): Promise<RemoteTool[]> {
84
+ const session = new Map<string, string>();
85
+ try {
86
+ const init = await rpc(url, auth, session, INITIALIZE, fetchImpl);
87
+ if (init === null || typeof init.protocolVersion !== 'string') throw refused(`${url.hostname} answered, but it does not speak MCP.`);
88
+ session.set('mcp-protocol-version', init.protocolVersion);
89
+ await rpc(url, auth, session, { jsonrpc: '2.0', method: 'notifications/initialized' }, fetchImpl);
90
+ return await walkTools(url, auth, session, fetchImpl);
91
+ } finally {
92
+ await endSession(url, auth, session, fetchImpl);
93
+ }
94
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.293"
2
+ "version": "0.1.0-beta.295"
3
3
  }
@@ -26,6 +26,9 @@ const FAILURE = {
26
26
  status_unavailable: 'The SDK status file cannot be written. Check its path and permissions before starting.',
27
27
  saved_state: 'The saved Agent SDK state cannot be read. Restore it before starting.',
28
28
  executable: 'The SDK executable could not start. Prepare the SDK runtime again.',
29
+ module: 'The SDK runtime could not load a required module. Prepare the SDK runtime again.',
30
+ configuration: 'The SDK launch configuration is missing or invalid. Check Harness and the Model page before starting.',
31
+ process_exit: 'The SDK process exited unexpectedly. Check its reported exit code or signal before retrying.',
29
32
  connection: 'The SDK connection failed. Check the server and provider connection.',
30
33
  session_ended: 'The Agent SDK session ended unexpectedly.',
31
34
  interrupted: 'The SDK stopped before finishing a chat request. Check Conversations before retrying; actions may already have run.',
@@ -33,8 +36,40 @@ const FAILURE = {
33
36
  } as const;
34
37
  export type RunnerFailureCode = keyof typeof FAILURE;
35
38
 
36
- export function runnerFailureSummary(code: RunnerFailureCode, tool: string | null = null): string {
37
- return code === 'tool_error' && name(tool) !== null ? `${tool} failed. See its result in Conversations.` : FAILURE[code];
39
+ const ERROR_CODES = ['ENOENT', 'EACCES', 'EPERM', 'ENOEXEC', 'ENOMEM', 'ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND', 'ERR_DLOPEN_FAILED', 'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'CERT_HAS_EXPIRED', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'] as const;
40
+ const SIGNALS = ['SIGTERM', 'SIGKILL', 'SIGSEGV', 'SIGABRT', 'SIGBUS', 'SIGILL', 'SIGINT', 'SIGHUP', 'SIGPIPE'] as const;
41
+
42
+ export interface RunnerDiagnostic {
43
+ source: 'exception' | 'stderr';
44
+ errorCode?: (typeof ERROR_CODES)[number];
45
+ httpStatus?: number;
46
+ exitCode?: number;
47
+ signal?: (typeof SIGNALS)[number];
48
+ }
49
+
50
+ const boundedNumber = (value: unknown, min: number, max: number): number | undefined => typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max ? value : undefined;
51
+
52
+ export function runnerDiagnostic(raw: unknown): RunnerDiagnostic | undefined {
53
+ if (!isRecord(raw) || (raw.source !== 'exception' && raw.source !== 'stderr')) return undefined;
54
+ const errorCode = ERROR_CODES.find((code) => code === raw.errorCode);
55
+ const signal = SIGNALS.find((value) => value === raw.signal);
56
+ const httpStatus = boundedNumber(raw.httpStatus, 400, 599);
57
+ const exitCode = boundedNumber(raw.exitCode, 0, 255);
58
+ return {
59
+ source: raw.source,
60
+ ...(errorCode === undefined ? {} : { errorCode }),
61
+ ...(httpStatus === undefined ? {} : { httpStatus }),
62
+ ...(exitCode === undefined ? {} : { exitCode }),
63
+ ...(signal === undefined ? {} : { signal }),
64
+ };
65
+ }
66
+
67
+ export function runnerFailureSummary(code: RunnerFailureCode, tool: string | null = null, diagnostic?: RunnerDiagnostic): string {
68
+ const summary = code === 'tool_error' && name(tool) !== null ? `${tool} failed. See its result in Conversations.` : FAILURE[code];
69
+ const safe = runnerDiagnostic(diagnostic);
70
+ if (safe === undefined) return summary;
71
+ const details = [safe.errorCode, safe.httpStatus === undefined ? null : `HTTP ${safe.httpStatus}`, safe.exitCode === undefined ? null : `exit ${safe.exitCode}`, safe.signal].filter((value) => value !== undefined && value !== null);
72
+ return details.length === 0 ? summary : `${summary} Observed: ${details.join(', ')} (${safe.source === 'stderr' ? 'startup stderr' : 'exception'}).`;
38
73
  }
39
74
 
40
75
  export interface RunnerTask {
@@ -70,6 +105,7 @@ export interface RunnerEvent {
70
105
  toolUseId?: string;
71
106
  taskId: string | null;
72
107
  code?: RunnerFailureCode;
108
+ diagnostic?: RunnerDiagnostic;
73
109
  }
74
110
 
75
111
  export interface RunnerFailure extends RunnerEvent {
@@ -146,16 +182,17 @@ function tool(raw: unknown): RunnerTool | null {
146
182
  return { id: String(raw.id), name: String(raw.name), taskId: name(raw.taskId), startedAt: count(raw.startedAt), ...(typeof raw.worker === 'boolean' ? { worker: raw.worker } : {}) };
147
183
  }
148
184
 
149
- const failureCode = (value: unknown): value is RunnerFailureCode => typeof value === 'string' && Object.hasOwn(FAILURE, value);
185
+ export const runnerFailureCode = (value: unknown): value is RunnerFailureCode => typeof value === 'string' && Object.hasOwn(FAILURE, value);
150
186
  const failureKind = (value: RunnerEventKind): boolean => ['turn_failed', 'tool_failed', 'task_failed', 'compact_failed', 'session_failed'].includes(value);
151
187
 
152
188
  function event(raw: unknown): RunnerEvent | null {
153
189
  if (!isRecord(raw) || !eventKind(raw.kind) || count(raw.at) === 0) return null;
190
+ const diagnostic = runnerDiagnostic(raw.diagnostic);
154
191
  return {
155
192
  at: count(raw.at), kind: raw.kind, tool: name(raw.tool), taskId: name(raw.taskId),
156
193
  ...(name(raw.id) === null ? {} : { id: String(raw.id) }),
157
194
  ...(name(raw.toolUseId) === null ? {} : { toolUseId: String(raw.toolUseId) }),
158
- ...(failureKind(raw.kind) && failureCode(raw.code) ? { code: raw.code } : {}),
195
+ ...(failureKind(raw.kind) && runnerFailureCode(raw.code) ? { code: raw.code, ...(diagnostic === undefined ? {} : { diagnostic }) } : {}),
159
196
  };
160
197
  }
161
198
 
@@ -184,7 +221,7 @@ function processIdentity(value: unknown): Pick<RunnerActivity, 'procStart'> {
184
221
  function failureFields(raw: Record<string, unknown>): Pick<RunnerActivity, 'lastError' | 'activeFailure' | 'lastFailure'> {
185
222
  const activeFailure = failure(raw.activeFailure);
186
223
  return {
187
- lastError: Object.hasOwn(raw, 'activeFailure') ? activeFailure === null ? null : runnerFailureSummary(activeFailure.code, activeFailure.tool) : safeError(raw.lastError),
224
+ lastError: Object.hasOwn(raw, 'activeFailure') ? activeFailure === null ? null : runnerFailureSummary(activeFailure.code, activeFailure.tool, activeFailure.diagnostic) : safeError(raw.lastError),
188
225
  ...(Object.hasOwn(raw, 'activeFailure') ? { activeFailure } : {}),
189
226
  ...(Object.hasOwn(raw, 'lastFailure') ? { lastFailure: failure(raw.lastFailure) } : {}),
190
227
  };
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.0-beta.293",
2
+ "version": "0.1.0-beta.295",
3
3
  "dependencies": {
4
4
  "@anthropic-ai/claude-agent-sdk": "0.3.287",
5
5
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -3,11 +3,13 @@ import { readFileSync } from 'node:fs';
3
3
  import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
4
4
  import { isRecord } from '@metro-labs/core/is-record';
5
5
  import { log } from '@metro-labs/core/log';
6
- import { runnerFailureSummary, type RunnerActivity, type RunnerEvent, type RunnerEventKind, type RunnerFailure, type RunnerFailureCode, type RunnerInput, type RunnerPhase, type RunnerTool } from '@metro-labs/core/runner-activity';
6
+ import { runnerFailureSummary, type RunnerActivity, type RunnerDiagnostic, type RunnerEvent, type RunnerEventKind, type RunnerFailure, type RunnerFailureCode, type RunnerInput, type RunnerPhase, type RunnerTool } from '@metro-labs/core/runner-activity';
7
7
  import { writeAtomic } from '@metro-labs/core/secure-fs';
8
8
  import { ActivityTasks, activityName } from './activity-tasks.js';
9
9
  import type { ApprovalAsk } from './approvals.js';
10
10
  import type { SavedTask } from './task-state.js';
11
+ import { sessionFailure } from './errors.js';
12
+ export { failureSummary } from './errors.js';
11
13
 
12
14
  const HEARTBEAT_MS = 5_000;
13
15
  const MAX_TRACKED = 200;
@@ -18,19 +20,10 @@ type System = Extract<SDKMessage, { type: 'system' }>;
18
20
  interface TrackedTool extends RunnerTool { parent: string | null }
19
21
  interface Approval { tool: string | null; taskId: string | null; worker: boolean }
20
22
 
21
- function sessionFailureCode(err: unknown): RunnerFailureCode {
22
- const text = err instanceof Error ? err.message : String(err);
23
- for (const code of ['status_unavailable', 'session_ended', 'interrupted', 'saved_state', 'authentication', 'executable', 'connection'] as const)
24
- if (text === runnerFailureSummary(code)) return code;
25
- if (/saved Agent SDK state/i.test(text)) return 'saved_state';
26
- if (/unauthorized|authentication|invalid.*key|\b40[13]\b/i.test(text)) return 'authentication';
27
- if (/ENOENT|not found|executable|spawn/i.test(text)) return 'executable';
28
- if (/ECONN|network|fetch failed|timed? ?out/i.test(text)) return 'connection';
29
- return 'session_error';
23
+ function copyEvent<T extends RunnerEvent>(event: T): T {
24
+ return { ...event, ...(event.diagnostic === undefined ? {} : { diagnostic: { ...event.diagnostic } }) };
30
25
  }
31
26
 
32
- export function failureSummary(err: unknown): string { return runnerFailureSummary(sessionFailureCode(err)); }
33
-
34
27
  const PROVIDER_ERRORS: Record<NonNullable<Extract<SDKMessage, { type: 'assistant' }>['error']>, RunnerFailureCode> = {
35
28
  authentication_failed: 'authentication', oauth_org_not_allowed: 'authentication', cloud_credential_error: 'authentication', account_on_hold: 'authentication', verification_required: 'authentication',
36
29
  billing_error: 'billing', rate_limit: 'rate_limit', overloaded: 'provider_unavailable', server_error: 'provider_unavailable',
@@ -94,9 +87,9 @@ export class Activity {
94
87
  const s = this.state;
95
88
  return {
96
89
  ...s, tools: [...s.tools], activeTools: s.activeTools.map((tool) => ({ ...tool })),
97
- tasks: s.tasks.map((task) => ({ ...task })), events: s.events.map((event) => ({ ...event })),
90
+ tasks: s.tasks.map((task) => ({ ...task })), events: s.events.map(copyEvent),
98
91
  ...(s.inputs === undefined ? {} : { inputs: s.inputs.map((input) => ({ ...input })) }),
99
- activeFailure: s.activeFailure ? { ...s.activeFailure } : null, lastFailure: s.lastFailure ? { ...s.lastFailure } : null,
92
+ activeFailure: s.activeFailure ? copyEvent(s.activeFailure) : null, lastFailure: s.lastFailure ? copyEvent(s.lastFailure) : null,
100
93
  };
101
94
  }
102
95
 
@@ -154,13 +147,14 @@ export class Activity {
154
147
  this.update();
155
148
  }
156
149
 
157
- fail(message: string): void {
150
+ fail(err: unknown): void {
158
151
  this.failed = true;
159
- const failure = this.failure('session_failed', sessionFailureCode(message), true);
152
+ const safe = sessionFailure(err);
153
+ const failure = this.failure('session_failed', safe.code, true, null, null, {}, safe.diagnostic);
160
154
  if (failure.code === 'interrupted') this.interrupted = failure;
161
155
  this.state.phase = 'error';
162
156
  this.state.mainPhase = 'error';
163
- log.error({ reason: failure.code }, 'sdk-runner: activity error');
157
+ log.error({ reason: failure.code, diagnostic: failure.diagnostic, summary: this.state.lastError }, 'sdk-runner: activity error');
164
158
  this.flush();
165
159
  }
166
160
 
@@ -335,12 +329,12 @@ export class Activity {
335
329
  this.state.lastError = this.interrupted === null ? null : runnerFailureSummary(this.interrupted.code);
336
330
  }
337
331
 
338
- private failure(kind: RunnerEventKind, code: RunnerFailureCode, active: boolean, tool: string | null = null, taskId: string | null = null, identity: Pick<RunnerEvent, 'id' | 'toolUseId'> = {}): RunnerFailure {
339
- const failure: RunnerFailure = { id: activityName(identity.id) ?? randomUUID(), at: Date.now(), kind, code, tool, taskId, ...(activityName(identity.toolUseId) === null ? {} : { toolUseId: identity.toolUseId }) };
332
+ private failure(kind: RunnerEventKind, code: RunnerFailureCode, active: boolean, tool: string | null = null, taskId: string | null = null, identity: Pick<RunnerEvent, 'id' | 'toolUseId'> = {}, diagnostic?: RunnerDiagnostic): RunnerFailure {
333
+ const failure: RunnerFailure = { id: activityName(identity.id) ?? randomUUID(), at: Date.now(), kind, code, tool, taskId, ...(activityName(identity.toolUseId) === null ? {} : { toolUseId: identity.toolUseId }), ...(diagnostic === undefined ? {} : { diagnostic }) };
340
334
  this.state.lastFailure = failure;
341
335
  if (active) {
342
336
  this.state.activeFailure = failure;
343
- this.state.lastError = runnerFailureSummary(code, tool);
337
+ this.state.lastError = runnerFailureSummary(code, tool, diagnostic);
344
338
  }
345
339
  this.record(failure);
346
340
  return failure;
@@ -4,7 +4,7 @@ import { AutomationStore } from '@metro-labs/core/automation-store';
4
4
  import { errMsg, log } from '@metro-labs/core/log';
5
5
  import { skillSourceRoot } from '@metro-labs/core/skill-source';
6
6
  import { SkillsRefresh } from './skills.js';
7
- import { failureSummary, type Activity } from './activity.js';
7
+ import type { Activity } from './activity.js';
8
8
  import { approvalsThrough } from './approvals.js';
9
9
  import type { RunnerConfig } from './config.js';
10
10
  import { MetroLink } from './link.js';
@@ -79,7 +79,7 @@ export async function startAgent(cfg: RunnerConfig, hooks: AppHooks): Promise<Ru
79
79
  hooks.activity?.start();
80
80
  return await connected(cfg, hooks, release);
81
81
  } catch (err) {
82
- hooks.activity?.fail(failureSummary(err));
82
+ hooks.activity?.fail(err);
83
83
  hooks.activity?.stop();
84
84
  await release().catch(() => { log.warn('sdk-runner: releasing process ownership failed'); });
85
85
  throw err;
@@ -0,0 +1,131 @@
1
+ import { isRecord } from '@metro-labs/core/is-record';
2
+ import { runnerDiagnostic, runnerFailureCode, runnerFailureSummary, type RunnerDiagnostic, type RunnerFailureCode } from '@metro-labs/core/runner-activity';
3
+
4
+ const SCAN_MAX = 2_048;
5
+ const ERROR_FAILURES: Record<NonNullable<RunnerDiagnostic['errorCode']>, RunnerFailureCode> = {
6
+ ENOENT: 'executable', EACCES: 'executable', EPERM: 'executable', ENOEXEC: 'executable', ENOMEM: 'executable',
7
+ ERR_MODULE_NOT_FOUND: 'module', MODULE_NOT_FOUND: 'module', ERR_DLOPEN_FAILED: 'module',
8
+ ECONNREFUSED: 'connection', ECONNRESET: 'connection', ENOTFOUND: 'connection', EAI_AGAIN: 'connection', ETIMEDOUT: 'connection',
9
+ CERT_HAS_EXPIRED: 'connection', UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'connection',
10
+ };
11
+ const KNOWN = ['status_unavailable', 'session_ended', 'interrupted', 'saved_state', 'authentication', 'executable', 'connection', 'module', 'configuration', 'process_exit', 'session_error'] as const;
12
+
13
+ export interface SessionFailure {
14
+ code: RunnerFailureCode;
15
+ diagnostic?: RunnerDiagnostic;
16
+ }
17
+
18
+ function normalizeFailure(raw: unknown): SessionFailure {
19
+ if (!isRecord(raw) || !runnerFailureCode(raw.code)) return { code: 'session_error' };
20
+ const diagnostic = runnerDiagnostic(raw.diagnostic);
21
+ return { code: raw.code, ...(diagnostic === undefined ? {} : { diagnostic }) };
22
+ }
23
+
24
+ export class SessionError extends Error {
25
+ readonly failure: SessionFailure;
26
+
27
+ constructor(failure: SessionFailure) {
28
+ const safe = normalizeFailure(failure);
29
+ super(runnerFailureSummary(safe.code, null, safe.diagnostic));
30
+ this.failure = safe;
31
+ }
32
+ }
33
+
34
+ function statusFailure(status: number | undefined): RunnerFailureCode | null {
35
+ if (status === undefined) return null;
36
+ if (status === 401 || status === 403) return 'authentication';
37
+ if (status === 402) return 'billing';
38
+ if (status === 429) return 'rate_limit';
39
+ return status >= 500 ? 'provider_unavailable' : 'invalid_request';
40
+ }
41
+
42
+ const TEXT_FAILURES: [RunnerFailureCode, RegExp][] = [
43
+ ['authentication', /\bunauthorized\b|\bauthentication (?:failed|error)\b|\binvalid(?:[ -]api)?[ -]key\b/i],
44
+ ['module', /cannot find (?:module|package)|error (?:while )?loading shared libraries|module not found/i],
45
+ ['configuration', /METRO_(?:RUNNER_MCP_URL|AGENT_KEY) is not set|invalid (?:configuration|settings)|failed to parse (?:configuration|settings)|unknown (?:option|argument)/i],
46
+ ['executable', /executable|spawn|command not found/i],
47
+ ['connection', /network|fetch failed|timed? ?out/i],
48
+ ];
49
+
50
+ function errorText(value: unknown): string {
51
+ if (typeof value === 'string') return value.slice(0, SCAN_MAX);
52
+ return isRecord(value) && typeof value.message === 'string' ? value.message.slice(0, SCAN_MAX) : '';
53
+ }
54
+
55
+ function evidence(raw: Record<string, unknown>, message: string, source: RunnerDiagnostic['source']): RunnerDiagnostic | undefined {
56
+ const errorCodes = message.match(/\b[A-Z][A-Z_]{2,40}\b/g) ?? [];
57
+ return runnerDiagnostic({
58
+ source, errorCode: raw.code ?? errorCodes.find((code) => Object.hasOwn(ERROR_FAILURES, code)),
59
+ httpStatus: raw.status ?? raw.statusCode ?? Number(/(?:^|\bHTTP(?:\/[12](?:\.\d)?)?\s+|\bstatus(?: code)?[:= ]+)([45]\d\d)\b/i.exec(message)?.[1]),
60
+ exitCode: raw.exitCode ?? Number(/^Claude Code process exited with code (\d{1,3})\b/.exec(message)?.[1]),
61
+ signal: raw.signal ?? /^Claude Code process terminated by signal (SIG[A-Z]{1,8})\b/.exec(message)?.[1],
62
+ });
63
+ }
64
+
65
+ function diagnosticCode(message: string, diagnostic: RunnerDiagnostic | undefined): RunnerFailureCode | null {
66
+ if (/saved Agent SDK state/i.test(message)) return 'saved_state';
67
+ if (diagnostic?.errorCode !== undefined) return ERROR_FAILURES[diagnostic.errorCode];
68
+ return statusFailure(diagnostic?.httpStatus);
69
+ }
70
+
71
+ function processFailure(diagnostic: RunnerDiagnostic | undefined): RunnerFailureCode | null {
72
+ return diagnostic?.exitCode !== undefined || diagnostic?.signal !== undefined ? 'process_exit' : null;
73
+ }
74
+
75
+ function classify(value: unknown, source: RunnerDiagnostic['source']): SessionFailure {
76
+ const message = errorText(value);
77
+ const known = KNOWN.find((code) => message === runnerFailureSummary(code));
78
+ if (known !== undefined) return { code: known };
79
+ const diagnostic = evidence(isRecord(value) ? value : {}, message, source);
80
+ const code = diagnosticCode(message, diagnostic) ?? TEXT_FAILURES.find(([, pattern]) => pattern.test(message))?.[0] ?? processFailure(diagnostic) ?? 'session_error';
81
+ return code === 'session_error' ? { code } : { code, ...(diagnostic === undefined ? {} : { diagnostic }) };
82
+ }
83
+
84
+ export function sessionFailure(err: unknown): SessionFailure {
85
+ try {
86
+ if (err instanceof SessionError) return normalizeFailure(err.failure);
87
+ let current = err;
88
+ let result: SessionFailure = { code: 'session_error' };
89
+ for (let depth = 0; depth < 4; depth++) {
90
+ const next = classify(current, 'exception');
91
+ if (next.code !== 'session_error') result = next;
92
+ if (!isRecord(current) || current.cause === undefined) break;
93
+ current = current.cause;
94
+ }
95
+ return result;
96
+ } catch {
97
+ return { code: 'session_error' };
98
+ }
99
+ }
100
+
101
+ export const failureSummary = (err: unknown): string => {
102
+ const failure = sessionFailure(err);
103
+ return runnerFailureSummary(failure.code, null, failure.diagnostic);
104
+ };
105
+
106
+ export class StartupDiagnostics {
107
+ private tail = '';
108
+ private observed: SessionFailure | null = null;
109
+
110
+ stderr(text: string): void {
111
+ const head = text.slice(0, SCAN_MAX);
112
+ const candidates = [head, (this.tail + head).slice(-SCAN_MAX), text.length > SCAN_MAX ? text.slice(-SCAN_MAX) : ''];
113
+ for (const candidate of candidates) {
114
+ const failure = classify(candidate, 'stderr');
115
+ if (failure.code !== 'session_error' && (failure.code !== 'process_exit' || this.observed === null)) this.observed = failure;
116
+ }
117
+ this.tail = (this.tail + (text.length > SCAN_MAX ? text.slice(-SCAN_MAX) : text)).slice(-SCAN_MAX);
118
+ }
119
+
120
+ failure(err: unknown): SessionFailure {
121
+ const failure = sessionFailure(err);
122
+ const observed = this.observed;
123
+ if (observed === null || !['session_error', 'process_exit'].includes(failure.code)) return failure;
124
+ return { ...observed, diagnostic: runnerDiagnostic({ ...failure.diagnostic, ...observed.diagnostic }) };
125
+ }
126
+
127
+ clear(): void {
128
+ this.tail = '';
129
+ this.observed = null;
130
+ }
131
+ }
@@ -3,6 +3,7 @@ import { log } from '@metro-labs/core/log';
3
3
  import { Activity, failureSummary } from './activity.js';
4
4
  import { startAgent, type RunningAgent } from './app.js';
5
5
  import { runnerConfig } from './config.js';
6
+ import { sessionFailure } from './errors.js';
6
7
 
7
8
  let agent: RunningAgent | null = null;
8
9
  let starting: Promise<RunningAgent> | null = null;
@@ -45,9 +46,10 @@ try {
45
46
  await agent.done;
46
47
  if (!exiting) activity.fail('The Agent SDK session ended unexpectedly.');
47
48
  } catch (err) {
48
- if (!exiting) activity.fail(failureSummary(err));
49
+ if (!exiting) activity.fail(err);
49
50
  }
50
51
  } catch (err) {
51
- log.error({ reason: failureSummary(err) }, 'sdk-runner: the Agent SDK session failed to start');
52
+ const failure = sessionFailure(err);
53
+ log.error({ reason: failure.code, diagnostic: failure.diagnostic, summary: failureSummary(err) }, 'sdk-runner: the Agent SDK session failed to start');
52
54
  }
53
55
  await exit(1);
@@ -18,6 +18,7 @@ import type { SessionStore } from './session-store.js';
18
18
  import { completedCommand, SessionWatch, startedCommand, uuidsOf } from './session-watch.js';
19
19
  import { TaskRecovery } from './task-recovery.js';
20
20
  import { METRO_SERVER, type MetroTools } from './tool-proxy.js';
21
+ import { failureSummary, SessionError, StartupDiagnostics } from './errors.js';
21
22
 
22
23
  const STARTUP_WAIT = 'CLAUDE_CODE_MCP_STARTUP_WAIT_MS';
23
24
  export const COMPACT_AT = 120_000;
@@ -53,9 +54,6 @@ export function runnerOptions(cfg: RunnerConfig, tools: MetroTools, canUseTool:
53
54
  includePartialMessages: true,
54
55
  extraArgs: { 'system-prompt-snapshot': 'off' },
55
56
  ...(resume === null ? {} : { resume }),
56
- stderr: (text: string) => {
57
- log.debug({ text: text.slice(0, 500) }, 'sdk-runner: claude stderr');
58
- },
59
57
  };
60
58
  }
61
59
 
@@ -98,6 +96,7 @@ export class Runner {
98
96
  readonly automation: Automation | null;
99
97
  private readonly recovery: TaskRecovery;
100
98
  private readonly watch: SessionWatch;
99
+ private readonly diagnostics = new StartupDiagnostics();
101
100
  private readonly tasks = new ActivityTasks(() => undefined);
102
101
  private readonly skillWork = new SkillWork();
103
102
  private compactTimer: ReturnType<typeof setTimeout> | null = null;
@@ -149,7 +148,13 @@ export class Runner {
149
148
  if (this.session !== null) throw new Error('the runner was already started');
150
149
  if (options.resume === undefined) this.watch.restoreContext(0);
151
150
  else this.maybeCompact(true);
152
- this.session = (this.parts.open ?? query)({ prompt: this.inbox, options });
151
+ try {
152
+ this.session = (this.parts.open ?? query)({ prompt: this.inbox, options: { ...options, stderr: (text) => { if (this.sessionId === null) this.diagnostics.stderr(text); } } });
153
+ } catch (err) {
154
+ const failure = this.diagnostics.failure(err);
155
+ this.diagnostics.clear();
156
+ throw new SessionError(failure);
157
+ }
153
158
  this.model = options.model ?? null;
154
159
  this.queueModel(this.model);
155
160
  this.parts.skills?.start({
@@ -185,15 +190,22 @@ export class Runner {
185
190
  this.maybeCompact();
186
191
  observe?.(message);
187
192
  }
193
+ } catch (err) {
194
+ throw new SessionError(this.diagnostics.failure(err));
188
195
  } finally {
189
- this.cancelCompact();
190
- this.parts.skills?.close();
191
- this.automation?.close(false);
192
- this.recovery.close(false);
193
- this.ended = true;
196
+ this.finishRun();
194
197
  }
195
198
  }
196
199
 
200
+ private finishRun(): void {
201
+ this.diagnostics.clear();
202
+ this.cancelCompact();
203
+ this.parts.skills?.close();
204
+ this.automation?.close(false);
205
+ this.recovery.close(false);
206
+ this.ended = true;
207
+ }
208
+
197
209
  chat(event: ChannelEvent): Uuid {
198
210
  try {
199
211
  const uuid = this.inbox.push('chat', channelText(METRO_SERVER, event.content, event.meta));
@@ -228,8 +240,9 @@ export class Runner {
228
240
  this.switching = this.switching
229
241
  .then(() => this.applyModel(model))
230
242
  .catch((err: unknown) => {
231
- this.parts.activity?.fail('The SDK could not apply the selected model. Check the Model page.');
232
- log.warn({ model, err: errMsg(err) }, 'sdk-runner: the session could not take the model the Model page picked');
243
+ const failure = new SessionError(this.diagnostics.failure(err));
244
+ this.parts.activity?.fail(failure);
245
+ log.warn({ reason: failure.failure.code, diagnostic: failure.failure.diagnostic, summary: failureSummary(failure) }, 'sdk-runner: the session could not take the model the Model page picked');
233
246
  });
234
247
  }
235
248
 
@@ -333,6 +346,7 @@ export class Runner {
333
346
  const id = typeof m.session_id === 'string' ? m.session_id : null;
334
347
  if (id === null || id === this.sessionId) return;
335
348
  this.sessionId = id;
349
+ this.diagnostics.clear();
336
350
  log.info({ session: id, model: m.model, claude: m.claude_code_version }, 'sdk-runner: session up');
337
351
  try {
338
352
  this.parts.store.save(id);