owenloop 0.4.0 → 0.5.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.
Files changed (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,132 @@
1
+ /**
2
+ * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
+ * over stdio, hand-rolled (O2 plan Decision 1).
4
+ *
5
+ * PROVENANCE: this transport core was ported from the execution subsystem's
6
+ * proven `src/mcp/server.ts` implementation (`createMcpServer` / `pumpStdin` /
7
+ * `textResult` / the error-code consts / `LineStream`). The implementation now
8
+ * lives in the root package so engine and execution commands ship together.
9
+ * `test/mcpcore.test.ts` re-proves the transport behavior against this file,
10
+ * so later changes are caught rather than assumed.
11
+ *
12
+ * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is two
13
+ * runtime deps (`@cfworker/json-schema` + `yaml`). The SDK drags zod and a
14
+ * transport stack for a surface we need only a few hundred lines of. The hub
15
+ * side already proves interop against the official SDK client, so drift is
16
+ * tested rather than assumed.
17
+ *
18
+ * The core is transport-agnostic and side-effect-injected: it exposes
19
+ * `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
20
+ * (transport EOF), and it emits every outbound frame through the injected
21
+ * `write(msg)`. Unit tests feed lines and inspect writes with no child process;
22
+ * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
23
+ *
24
+ * Supported methods (the subset an MCP host needs):
25
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
26
+ * agreed protocolVersion (echo the client's when
27
+ * recognized, else answer with ours).
28
+ * - `notifications/initialized` → no-op (no response; it is a notification).
29
+ * - `ping` → `{}`.
30
+ * - `tools/list` → the registered tool defs.
31
+ * - `tools/call` → dispatch to the tool handler; the result is
32
+ * `{content:[{type:'text',text:<JSON>}], isError?}`.
33
+ * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
34
+ * aborted call sends NO response frame.
35
+ * - outbound `notifications/progress` when a call carried
36
+ * `params._meta.progressToken` (via `ctx.sendProgress`).
37
+ *
38
+ * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
39
+ * invalid params → -32602. A notification (no `id`) never gets a response, even
40
+ * on error. The process must never crash on a bad line.
41
+ */
42
+ export declare const PARSE_ERROR = -32700;
43
+ export declare const INVALID_REQUEST = -32600;
44
+ export declare const METHOD_NOT_FOUND = -32601;
45
+ export declare const INVALID_PARAMS = -32602;
46
+ export declare const INTERNAL_ERROR = -32603;
47
+ /** A tool result as MCP serves it: text content blocks, optional error flag. */
48
+ export interface ToolResult {
49
+ content: Array<{
50
+ type: 'text';
51
+ text: string;
52
+ }>;
53
+ isError?: boolean;
54
+ }
55
+ /** Convenience: wrap a JSON-able value as a single text content block. */
56
+ export declare function textResult(value: unknown, isError?: boolean): ToolResult;
57
+ /** The per-call context handed to a tool handler. */
58
+ export interface ToolCallContext {
59
+ /** True once the caller cancelled this request (`notifications/cancelled`). */
60
+ readonly cancelled: boolean;
61
+ /** Register a callback fired when this request is cancelled. */
62
+ onCancel(cb: () => void): void;
63
+ /**
64
+ * Emit a `notifications/progress` frame for this call. A no-op when the caller
65
+ * supplied no `progressToken` (progress is meaningless without one).
66
+ */
67
+ sendProgress(payload: {
68
+ progress?: number;
69
+ total?: number;
70
+ message?: string;
71
+ }): void;
72
+ }
73
+ export type ToolHandler = (args: Record<string, unknown>, ctx: ToolCallContext) => Promise<ToolResult> | ToolResult;
74
+ /** A registered tool: its advertised shape plus the handler that runs it. */
75
+ export interface ToolRegistration {
76
+ name: string;
77
+ description: string;
78
+ /** JSON-Schema for the tool's arguments (advertised via `tools/list`). */
79
+ inputSchema: Record<string, unknown>;
80
+ handler: ToolHandler;
81
+ }
82
+ export interface McpServerOptions {
83
+ name: string;
84
+ version: string;
85
+ tools: ToolRegistration[];
86
+ /** Outbound frame sink — the caller JSON-serializes + newline-terminates. */
87
+ write: (msg: unknown) => void;
88
+ /** Diagnostic sink (stderr); protocol frames never go here. */
89
+ err?: (line: string) => void;
90
+ }
91
+ export interface McpServer {
92
+ /** Feed one framed JSON-RPC line (no trailing newline required). */
93
+ handleLine(line: string): Promise<void>;
94
+ /**
95
+ * Transport EOF — cancels in-flight calls so parked handlers unblock. Their
96
+ * replies are still flushed (close-cancel ≠ client-cancel; see `InFlight`).
97
+ */
98
+ close(reason?: string): void;
99
+ }
100
+ export declare function createMcpServer(opts: McpServerOptions): McpServer;
101
+ /** The slice of a readable stream `pumpStdin` needs — injectable for tests. */
102
+ export interface LineStream {
103
+ on(event: 'data', handler: (chunk: Buffer | string) => void): unknown;
104
+ on(event: 'end' | 'close', handler: () => void): unknown;
105
+ setEncoding?(enc: string): void;
106
+ resume?(): void;
107
+ }
108
+ /**
109
+ * Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
110
+ * on newlines, feed each complete line to `server.handleLine`, and call
111
+ * `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
112
+ * flushed if non-empty.
113
+ *
114
+ * Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
115
+ * in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
116
+ * long call is outstanding, `notifications/cancelled` must reach the server to
117
+ * abort it and `ping` must still answer. Serializing the pump behind the
118
+ * in-flight call chain would deadlock exactly those frames on the real
119
+ * transport. Per-frame ordering still holds for the non-parking methods because
120
+ * `handleLine` runs synchronously up to the first tool-handler await, and
121
+ * responses are matched by id, not by order.
122
+ *
123
+ * EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
124
+ * cancels any parked in-flight call, which is what lets a process waiting on
125
+ * this pump actually exit (chaining the close behind a parked call would
126
+ * deadlock EOF against the very call only the close can unpark). A close-cancel
127
+ * does NOT suppress the call's reply the way a client cancel does — every call
128
+ * received before EOF still answers. `onEof` fires only after every dispatched
129
+ * line has settled, so those reply frames are on the pipe before the caller
130
+ * acts on EOF (e.g. exits the process).
131
+ */
132
+ export declare function pumpStdin(stream: LineStream, server: McpServer, onEof?: () => void): void;
@@ -0,0 +1,327 @@
1
+ /**
2
+ * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
+ * over stdio, hand-rolled (O2 plan Decision 1).
4
+ *
5
+ * PROVENANCE: this transport core was ported from the execution subsystem's
6
+ * proven `src/mcp/server.ts` implementation (`createMcpServer` / `pumpStdin` /
7
+ * `textResult` / the error-code consts / `LineStream`). The implementation now
8
+ * lives in the root package so engine and execution commands ship together.
9
+ * `test/mcpcore.test.ts` re-proves the transport behavior against this file,
10
+ * so later changes are caught rather than assumed.
11
+ *
12
+ * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is two
13
+ * runtime deps (`@cfworker/json-schema` + `yaml`). The SDK drags zod and a
14
+ * transport stack for a surface we need only a few hundred lines of. The hub
15
+ * side already proves interop against the official SDK client, so drift is
16
+ * tested rather than assumed.
17
+ *
18
+ * The core is transport-agnostic and side-effect-injected: it exposes
19
+ * `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
20
+ * (transport EOF), and it emits every outbound frame through the injected
21
+ * `write(msg)`. Unit tests feed lines and inspect writes with no child process;
22
+ * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
23
+ *
24
+ * Supported methods (the subset an MCP host needs):
25
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
26
+ * agreed protocolVersion (echo the client's when
27
+ * recognized, else answer with ours).
28
+ * - `notifications/initialized` → no-op (no response; it is a notification).
29
+ * - `ping` → `{}`.
30
+ * - `tools/list` → the registered tool defs.
31
+ * - `tools/call` → dispatch to the tool handler; the result is
32
+ * `{content:[{type:'text',text:<JSON>}], isError?}`.
33
+ * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
34
+ * aborted call sends NO response frame.
35
+ * - outbound `notifications/progress` when a call carried
36
+ * `params._meta.progressToken` (via `ctx.sendProgress`).
37
+ *
38
+ * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
39
+ * invalid params → -32602. A notification (no `id`) never gets a response, even
40
+ * on error. The process must never crash on a bad line.
41
+ */
42
+ /** The MCP revisions this server will agree to echo back on `initialize`. */
43
+ const RECOGNIZED_PROTOCOL_VERSIONS = new Set([
44
+ '2024-11-05',
45
+ '2025-03-26',
46
+ '2025-06-18',
47
+ '2025-11-05',
48
+ ]);
49
+ /** The version we answer with when the client's is missing or unrecognized. */
50
+ const OUR_PROTOCOL_VERSION = '2025-06-18';
51
+ // ---- JSON-RPC error codes ---------------------------------------------------
52
+ export const PARSE_ERROR = -32700;
53
+ export const INVALID_REQUEST = -32600;
54
+ export const METHOD_NOT_FOUND = -32601;
55
+ export const INVALID_PARAMS = -32602;
56
+ export const INTERNAL_ERROR = -32603;
57
+ /** Convenience: wrap a JSON-able value as a single text content block. */
58
+ export function textResult(value, isError = false) {
59
+ return { content: [{ type: 'text', text: JSON.stringify(value) }], ...(isError ? { isError: true } : {}) };
60
+ }
61
+ export function createMcpServer(opts) {
62
+ const err = opts.err ?? (() => { });
63
+ const tools = new Map();
64
+ for (const t of opts.tools)
65
+ tools.set(t.name, t);
66
+ // Tracks in-flight tools/call requests by id so notifications/cancelled can
67
+ // abort them (and so we can suppress the response frame of a cancelled call).
68
+ const inFlight = new Map();
69
+ let closed = false;
70
+ // NOTE: deliberately NOT gated on `closed` — a reply whose handler settled a
71
+ // microtask after transport EOF must still reach the pipe (the cancel
72
+ // contract already suppresses replies of cancelled calls, and sendProgress
73
+ // gates on `closed` itself). A write to a gone pipe lands in the catch.
74
+ function send(msg) {
75
+ try {
76
+ opts.write(msg);
77
+ }
78
+ catch (e) {
79
+ err(`mcp: write failed: ${e instanceof Error ? e.message : String(e)}`);
80
+ }
81
+ }
82
+ function reply(id, result) {
83
+ send({ jsonrpc: '2.0', id, result });
84
+ }
85
+ function replyError(id, code, message) {
86
+ send({ jsonrpc: '2.0', id, error: { code, message } });
87
+ }
88
+ function keyOf(id) {
89
+ return typeof id === 'number' ? `n:${id}` : `s:${String(id)}`;
90
+ }
91
+ async function handleToolsCall(id, params) {
92
+ if (!isObject(params) || typeof params['name'] !== 'string') {
93
+ replyError(id, INVALID_PARAMS, 'tools/call requires a string "name"');
94
+ return;
95
+ }
96
+ const name = params['name'];
97
+ const reg = tools.get(name);
98
+ if (reg === undefined) {
99
+ replyError(id, METHOD_NOT_FOUND, `unknown tool '${name}'`);
100
+ return;
101
+ }
102
+ const rawArgs = params['arguments'];
103
+ const args = isObject(rawArgs) ? rawArgs : {};
104
+ const progressToken = readProgressToken(params);
105
+ const tracked = { cancelled: false, byClose: false, cancelCbs: [] };
106
+ // Only tracked when it has a concrete id (a notification cannot be cancelled).
107
+ if (id !== null && id !== undefined)
108
+ inFlight.set(keyOf(id), tracked);
109
+ const ctx = {
110
+ get cancelled() {
111
+ return tracked.cancelled;
112
+ },
113
+ onCancel(cb) {
114
+ if (tracked.cancelled)
115
+ cb();
116
+ else
117
+ tracked.cancelCbs.push(cb);
118
+ },
119
+ sendProgress(payload) {
120
+ if (progressToken === undefined || tracked.cancelled || closed)
121
+ return;
122
+ send({
123
+ jsonrpc: '2.0',
124
+ method: 'notifications/progress',
125
+ params: { progressToken, ...payload },
126
+ });
127
+ },
128
+ };
129
+ try {
130
+ const result = await reg.handler(args, ctx);
131
+ // A CLIENT-cancelled call sends NO response frame (the JSON-RPC/MCP
132
+ // cancel contract). A close-cancelled call still replies — see InFlight.
133
+ if (tracked.cancelled && !tracked.byClose)
134
+ return;
135
+ reply(id, result);
136
+ }
137
+ catch (e) {
138
+ if (tracked.cancelled && !tracked.byClose)
139
+ return;
140
+ err(`mcp: tool '${name}' threw: ${e instanceof Error ? e.message : String(e)}`);
141
+ reply(id, textResult({ error: e instanceof Error ? e.message : String(e) }, true));
142
+ }
143
+ finally {
144
+ if (id !== null && id !== undefined)
145
+ inFlight.delete(keyOf(id));
146
+ }
147
+ }
148
+ function handleCancelled(params) {
149
+ if (!isObject(params))
150
+ return;
151
+ const requestId = params['requestId'];
152
+ if (requestId === undefined || requestId === null)
153
+ return;
154
+ const tracked = inFlight.get(keyOf(requestId));
155
+ if (tracked === undefined)
156
+ return;
157
+ tracked.cancelled = true;
158
+ for (const cb of tracked.cancelCbs.splice(0)) {
159
+ try {
160
+ cb();
161
+ }
162
+ catch {
163
+ // a cancel callback must never take the server down
164
+ }
165
+ }
166
+ }
167
+ function handleInitialize(id, params) {
168
+ const requested = isObject(params) ? params['protocolVersion'] : undefined;
169
+ const agreed = typeof requested === 'string' && RECOGNIZED_PROTOCOL_VERSIONS.has(requested) ? requested : OUR_PROTOCOL_VERSION;
170
+ reply(id, {
171
+ protocolVersion: agreed,
172
+ capabilities: { tools: {} },
173
+ serverInfo: { name: opts.name, version: opts.version },
174
+ });
175
+ }
176
+ function handleToolsList(id) {
177
+ reply(id, {
178
+ tools: [...tools.values()].map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
179
+ });
180
+ }
181
+ async function handleLine(line) {
182
+ const trimmed = line.trim();
183
+ if (trimmed === '')
184
+ return;
185
+ let msg;
186
+ try {
187
+ msg = JSON.parse(trimmed);
188
+ }
189
+ catch {
190
+ // No id is recoverable from an unparseable line — reply with a null-id
191
+ // parse error per JSON-RPC and keep serving.
192
+ replyError(null, PARSE_ERROR, 'parse error: line was not valid JSON');
193
+ return;
194
+ }
195
+ if (!isObject(msg) || typeof msg.method !== 'string') {
196
+ const id = isObject(msg) && 'id' in msg ? msg.id : null;
197
+ replyError(id ?? null, INVALID_REQUEST, 'invalid request: missing "method"');
198
+ return;
199
+ }
200
+ const isNotification = !('id' in msg) || msg.id === undefined;
201
+ const id = (msg.id ?? null);
202
+ switch (msg.method) {
203
+ case 'initialize':
204
+ if (!isNotification)
205
+ handleInitialize(id, msg.params);
206
+ return;
207
+ case 'notifications/initialized':
208
+ case 'initialized':
209
+ return; // no-op notification
210
+ case 'ping':
211
+ if (!isNotification)
212
+ reply(id, {});
213
+ return;
214
+ case 'tools/list':
215
+ if (!isNotification)
216
+ handleToolsList(id);
217
+ return;
218
+ case 'tools/call':
219
+ if (isNotification)
220
+ return; // a call with no id has nowhere to answer
221
+ await handleToolsCall(id, msg.params);
222
+ return;
223
+ case 'notifications/cancelled':
224
+ case 'cancelled':
225
+ handleCancelled(msg.params);
226
+ return;
227
+ default:
228
+ if (!isNotification)
229
+ replyError(id, METHOD_NOT_FOUND, `unknown method '${msg.method}'`);
230
+ return;
231
+ }
232
+ }
233
+ function close() {
234
+ if (closed)
235
+ return;
236
+ closed = true;
237
+ for (const tracked of inFlight.values()) {
238
+ tracked.cancelled = true;
239
+ tracked.byClose = true;
240
+ for (const cb of tracked.cancelCbs.splice(0)) {
241
+ try {
242
+ cb();
243
+ }
244
+ catch {
245
+ // best-effort
246
+ }
247
+ }
248
+ }
249
+ inFlight.clear();
250
+ }
251
+ return { handleLine, close };
252
+ }
253
+ // ---- helpers ----------------------------------------------------------------
254
+ function isObject(v) {
255
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
256
+ }
257
+ /** Pull `params._meta.progressToken` (string|number) when present. */
258
+ function readProgressToken(params) {
259
+ const meta = params['_meta'];
260
+ if (!isObject(meta))
261
+ return undefined;
262
+ const tok = meta['progressToken'];
263
+ return typeof tok === 'string' || typeof tok === 'number' ? tok : undefined;
264
+ }
265
+ /**
266
+ * Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
267
+ * on newlines, feed each complete line to `server.handleLine`, and call
268
+ * `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
269
+ * flushed if non-empty.
270
+ *
271
+ * Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
272
+ * in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
273
+ * long call is outstanding, `notifications/cancelled` must reach the server to
274
+ * abort it and `ping` must still answer. Serializing the pump behind the
275
+ * in-flight call chain would deadlock exactly those frames on the real
276
+ * transport. Per-frame ordering still holds for the non-parking methods because
277
+ * `handleLine` runs synchronously up to the first tool-handler await, and
278
+ * responses are matched by id, not by order.
279
+ *
280
+ * EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
281
+ * cancels any parked in-flight call, which is what lets a process waiting on
282
+ * this pump actually exit (chaining the close behind a parked call would
283
+ * deadlock EOF against the very call only the close can unpark). A close-cancel
284
+ * does NOT suppress the call's reply the way a client cancel does — every call
285
+ * received before EOF still answers. `onEof` fires only after every dispatched
286
+ * line has settled, so those reply frames are on the pipe before the caller
287
+ * acts on EOF (e.g. exits the process).
288
+ */
289
+ export function pumpStdin(stream, server, onEof) {
290
+ stream.setEncoding?.('utf8');
291
+ let buffer = '';
292
+ let ended = false;
293
+ const pending = new Set();
294
+ const dispatch = (line) => {
295
+ const p = Promise.resolve(server.handleLine(line)).catch(() => { });
296
+ pending.add(p);
297
+ void p.finally(() => pending.delete(p));
298
+ };
299
+ stream.on('data', (chunk) => {
300
+ buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
301
+ let nl = buffer.indexOf('\n');
302
+ while (nl !== -1) {
303
+ const line = buffer.slice(0, nl);
304
+ buffer = buffer.slice(nl + 1);
305
+ dispatch(line);
306
+ nl = buffer.indexOf('\n');
307
+ }
308
+ });
309
+ const finish = () => {
310
+ if (ended)
311
+ return;
312
+ ended = true;
313
+ const tail = buffer;
314
+ buffer = '';
315
+ if (tail.trim() !== '')
316
+ dispatch(tail);
317
+ // Snapshot BEFORE close: close() cancels parked calls, which is what makes
318
+ // these settle. A handler that ignores cancellation would stall EOF — ours
319
+ // all resolve on cancel or are bounded hub calls.
320
+ const flushed = Promise.allSettled([...pending]);
321
+ server.close('stdin-eof');
322
+ void flushed.then(() => onEof?.());
323
+ };
324
+ stream.on('end', finish);
325
+ stream.on('close', finish);
326
+ stream.resume?.();
327
+ }
@@ -176,8 +176,44 @@ export declare function pendingOwed(def: WorkflowDef, arts: ArtifactMap): Artifa
176
176
  * output to discharge. This is the scheduling gate (§11.4): necessary, not
177
177
  * sufficient; the commit fingerprint (§12.2) is the correctness boundary.
178
178
  * Assumes `pendingOwed` has already been materialized into `arts`.
179
+ *
180
+ * `opts.ignoreFreeze` (used by `modelCheck`'s stall-vs-true-deadlock
181
+ * recompute): when true, treat every `frozen()` guard as false — i.e.
182
+ * "what would be eligible if every maxAttempts/maxSchemaFailures/held brake
183
+ * were lifted (a human `retry` = unlimited attempts)". It ONLY lifts the
184
+ * freeze; group-exclusivity, input-green gates, and `isDebt` are untouched.
185
+ */
186
+ export declare function eligibleFirings(def: WorkflowDef, arts: ArtifactMap, time?: TimeFacts, opts?: {
187
+ ignoreFreeze?: boolean;
188
+ }): Firing[];
189
+ /**
190
+ * Pure static predicate: can `step` EVER fire, under ANY search bounds?
191
+ *
192
+ * A SOUND detector of deadness: returns false ONLY when we are CERTAIN no
193
+ * firing can ever be pushed for this step, mirroring the discharge-set logic
194
+ * `eligibleFirings` (above) actually uses. When uncertain, returns true (the
195
+ * safe, non-failing default) — a false "structurally dead" would wrongly make
196
+ * `check` exit nonzero, so soundness is biased toward under-reporting.
197
+ *
198
+ * - Reachability: if any consumed stem is not reachable from the workflow
199
+ * inputs (see `reachableStems`), the step can never fire. Belt-and-suspenders
200
+ * — `validateDef`'s `reachabilityErrors` already turns this into a hard error
201
+ * before `modelCheck` ever runs, so this arm is defensive, not the live path.
202
+ * - Judge step (`step.judges`): fires against the judged stem, not a produces
203
+ * set; can-fire iff the judged stem is reachable (already implied by the
204
+ * reachability arm above, since a judge step consumes the judged stem — kept
205
+ * explicit for clarity and to stay correct if judge-step synthesis changes).
206
+ * - reduce: the discharge set is `singletonProduces(step)` only (see the
207
+ * reduce branch of `eligibleFirings`) — zero singleton produces means no
208
+ * firing is ever pushed, regardless of bounds.
209
+ * - map: needs both a map-consume and a map-produce to bind an element.
210
+ * - plain (inputsGreen / allGreen / idle): the discharge set is `plainOutputs`
211
+ * (singleton produces + collection seals) — empty means no firing ever.
212
+ *
213
+ * `reachable` may be precomputed once by the caller and passed in (modelCheck
214
+ * calls this per dead step and must not recompute the fixpoint each time).
179
215
  */
180
- export declare function eligibleFirings(def: WorkflowDef, arts: ArtifactMap, time?: TimeFacts): Firing[];
216
+ export declare function canEverFire(step: StepDef, def: WorkflowDef, reachable?: Set<string>): boolean;
181
217
  /**
182
218
  * The standing guard: re-derive the invariant "an artifact is green only while
183
219
  * every artifact it directly consumed is green and unmoved" and report the
@@ -368,10 +404,29 @@ export declare function applyOutcome(def: WorkflowDef, arts: Map<string, Artifac
368
404
  * Bounded reachability / liveness checker over a workflow definition.
369
405
  *
370
406
  * Explores the full (or depth/state-bounded) state space via BFS to find:
371
- * - deadlocks: reachable states that are not done and have no eligible firings
372
- * - stuck states: reachable states with a stalled debt
407
+ * - a non-done, zero-eligible-firings state is split into exactly ONE of two
408
+ * mutually exclusive buckets by recomputing eligibility with every freeze
409
+ * lifted (unlimited attempts — see `eligibleFirings`'s `ignoreFreeze`):
410
+ * - stall states: the recompute yields >= 1 firing — the state's only
411
+ * blocker is a frozen/stalled debt (maxAttempts / maxSchemaFailures /
412
+ * held). A by-design human-escalation brake. EXPECTED, never a defect.
413
+ * - true deadlocks: the recompute STILL yields zero firings — a genuine
414
+ * structural dead-end with no path to completion even at unlimited
415
+ * attempts. A real defect.
416
+ * - stuck states: reachable states that have a stalled debt but STILL have
417
+ * >= 1 eligible firing elsewhere (a brake tripped on one branch while the
418
+ * line moves on another). Informational only; a no-moves state is never
419
+ * listed here — it lands in `stallStates` or `deadlocks` instead, so no
420
+ * state is ever double-listed.
373
421
  * - completability: whether any reachable state is done (with an example path)
374
- * - dead steps: steps whose name never appears as a firing in any explored transition
422
+ * - dead steps: steps whose name never appears as a firing in any explored
423
+ * transition. Split into two categories by the static `canEverFire` check
424
+ * (independent of search bounds):
425
+ * - structurally-dead: `canEverFire` is false — the step can NEVER fire
426
+ * regardless of `--max-depth`/`--max-states`. A genuine wiring defect.
427
+ * - unreached-within-bounds: `canEverFire` is true — the step CAN fire in
428
+ * principle but the bounded search didn't reach it. A bounds artifact,
429
+ * not a defect; raising `--max-states`/`--max-depth` may surface it.
375
430
  *
376
431
  * Pure — no store, no engine, no IO.
377
432
  */