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,702 @@
1
+ /**
2
+ * `owenloop mcp` — the owenloop-cli-mcp stdio control-plane surface (O2).
3
+ *
4
+ * TWO-PLANE MODEL (identity-and-setup-model doc, §5/§6/§8, in the
5
+ * owenloop-service repo): owenloop runs two distinct planes. The HUMAN control
6
+ * plane is the everyday operator surface — starting runs, answering gates,
7
+ * pushing defs — and it authenticates as the logged-in human. The AGENT plane
8
+ * is what a Step Agent uses with its own `olp_` bearer. This module
9
+ * serves the HUMAN plane to a local MCP host (Claude Code) over stdio: it reads
10
+ * newline-delimited JSON-RPC 2.0 on stdin, translates each `tools/call` into one
11
+ * authenticated HTTPS request to the hub's `/api/*` REST mirror, and writes the
12
+ * JSON-RPC reply on stdout. It is spawned by hosts, never run by a human at a
13
+ * prompt.
14
+ *
15
+ * The model doc's cardinal rule (§6): the MODEL must never see a live token.
16
+ * Two consequences are load-bearing here:
17
+ * 1. Every hub call reads the stored `human` credential fresh and refreshes it
18
+ * through O1's locked path (`ensureFreshOAuth`/`refreshOAuth` in
19
+ * `src/credentials.ts`); the bearer only ever rides the `Authorization`
20
+ * header, never a tool result. The server holds NO credential state between
21
+ * calls — its only state is the resolved origin and the fixed tool list.
22
+ * 2. `create_agent` MINTS an `olp_` agent token and writes it straight to the
23
+ * local store (`storeCredential`, slot `agent:<name>`, caller-chosen scopes,
24
+ * default `['work']`);
25
+ * the token is NEVER returned in a tool result, printed, or logged. The
26
+ * mint response body carries the plaintext in TWO fields (`data.token` AND
27
+ * the human `text` "Store this secret now…"), so the handler builds its
28
+ * result object FROM SCRATCH (`{name, crews, stored:true}`) and never
29
+ * passes any field of the raw body outbound.
30
+ *
31
+ * The transport core is in `./server.ts` (a copy of owenloop's; see its header).
32
+ * Everything owenloop-specific — origin resolution, the authenticated hub
33
+ * client, the tool registrations, the enrollment capability gate, and the
34
+ * command body — lives here.
35
+ */
36
+ import { CliError } from "../util.js";
37
+ import { authHeader, ensureFreshOAuth, hubFetch, refreshOAuth, storeCredential, } from "../credentials.js";
38
+ import { credentialBackend, listStoredHubOrigins, normalizeOrigin, readStoredCredential, resolveEndpoint, } from "../hub.js";
39
+ import { createMcpServer, pumpStdin, textResult } from "./server.js";
40
+ /** The human control plane authenticates as the human slot, always. */
41
+ const HUMAN = { principal: 'human' };
42
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
43
+ /**
44
+ * Resolve the hub origin this server binds to, precedence:
45
+ * 1. `--hub <origin>` flag,
46
+ * 2. `OWENLOOP_HUB` env,
47
+ * 3. if the FILE credential backend holds exactly ONE hub with a valid `human`
48
+ * slot, use it,
49
+ * 4. else exit 2 with a message naming BOTH remedies.
50
+ *
51
+ * Rungs 1–2 normalize the origin (a malformed value throws a `CliError` → the
52
+ * command's exit-1 path via `mainAsync`'s catch, matching every other command).
53
+ * Rung 3 is file-backend-only because only the file backend can enumerate
54
+ * (`listStoredHubOrigins`); `null` (cannot enumerate — keychain/external), `[]`
55
+ * (nothing stored), and length>1 (ambiguous) each get a tailored exit-2 message.
56
+ *
57
+ * DELIBERATELY there is NO silent production fallback (the CLI's `resolveHub`
58
+ * `DEFAULT_HUB` rung): a control-plane server must never bind to a hub the
59
+ * operator did not name.
60
+ */
61
+ export function resolveMcpOrigin(io, hubFlag) {
62
+ const explicit = hubFlag ?? io.env.OWENLOOP_HUB;
63
+ if (explicit !== undefined && explicit.trim() !== '') {
64
+ try {
65
+ return { origin: normalizeOrigin(explicit) };
66
+ }
67
+ catch (e) {
68
+ throw new CliError(e.message);
69
+ }
70
+ }
71
+ const origins = listStoredHubOrigins(io.env, io.keychain);
72
+ if (origins === null) {
73
+ const backend = credentialBackend(io.env, io.keychain);
74
+ const which = backend.kind === 'external' ? 'external-command' : 'keychain';
75
+ return {
76
+ exitCode: 2,
77
+ message: `cannot list stored hubs from the ${which} credential store — ` +
78
+ 'pass --hub <origin> (or set OWENLOOP_HUB)',
79
+ };
80
+ }
81
+ if (origins.length === 0) {
82
+ return {
83
+ exitCode: 2,
84
+ message: 'no hub credentials stored — run `owenloop login --hub <origin>` first, or pass --hub <origin>',
85
+ };
86
+ }
87
+ if (origins.length > 1) {
88
+ return {
89
+ exitCode: 2,
90
+ message: `multiple hubs in the credential store (${origins.join(', ')}) — pass --hub <origin>`,
91
+ };
92
+ }
93
+ return { origin: origins[0] };
94
+ }
95
+ // ---- the authenticated hub client -------------------------------------------
96
+ /** The non-interactive "you are not authenticated" instruction (Decision 8). */
97
+ function loginHint(origin) {
98
+ return `not logged in to ${origin} — run \`owenloop login --hub ${origin}\` in a terminal, then retry`;
99
+ }
100
+ /**
101
+ * Make ONE authenticated hub call for the current `tools/call`, mirroring the
102
+ * CLI's `authedGet` refresh-and-retry discipline (cli.ts):
103
+ * 1. read the `human` slot fresh (picks up a `login` performed while the
104
+ * server runs) — missing → `authFailed`;
105
+ * 2. `ensureFreshOAuth` (persist=true → O1's locked, double-checked refresh) —
106
+ * a `CliError` → `authFailed` with its message + the login hint;
107
+ * 3. the HTTP call with `Authorization: authHeader(cred)`;
108
+ * 4. on a 401 with an oauth credential, exactly ONE `refreshOAuth` + one
109
+ * retry; a final 401 → `authFailed`.
110
+ * The response body is parsed leniently (a parse failure yields `{}`, status
111
+ * preserved). The bearer never leaves the `Authorization` header.
112
+ */
113
+ async function callHub(deps, req) {
114
+ const { io, origin } = deps;
115
+ let cred;
116
+ try {
117
+ cred = readStoredCredential(origin, { principal: 'human', env: io.env, keychain: io.keychain });
118
+ }
119
+ catch (e) {
120
+ // External-command backend failing to supply a credential is an auth failure.
121
+ return { status: 0, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
122
+ }
123
+ if (cred === null) {
124
+ return { status: 0, json: undefined, authFailed: true, authMessage: loginHint(origin) };
125
+ }
126
+ let current;
127
+ try {
128
+ current = await ensureFreshOAuth(io, origin, HUMAN, cred);
129
+ }
130
+ catch (e) {
131
+ return { status: 0, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
132
+ }
133
+ const fetchOnce = async (c) => {
134
+ const headers = {
135
+ Authorization: authHeader(c),
136
+ Accept: 'application/json',
137
+ ...(req.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
138
+ };
139
+ return hubFetch(io, resolveEndpoint(origin, req.path + (req.query ?? '')), {
140
+ method: req.method,
141
+ headers,
142
+ ...(req.body !== undefined ? { body: JSON.stringify(req.body) } : {}),
143
+ });
144
+ };
145
+ let res = await fetchOnce(current);
146
+ if (res.status === 401 && current.kind === 'oauth') {
147
+ try {
148
+ current = await refreshOAuth(io, origin, HUMAN, current);
149
+ }
150
+ catch (e) {
151
+ return { status: 401, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
152
+ }
153
+ res = await fetchOnce(current);
154
+ }
155
+ if (res.status === 401) {
156
+ return { status: 401, json: undefined, authFailed: true, authMessage: loginHint(origin) };
157
+ }
158
+ let json;
159
+ try {
160
+ json = await res.json();
161
+ }
162
+ catch {
163
+ json = {};
164
+ }
165
+ return { status: res.status, json };
166
+ }
167
+ /** Whether an HTTP status is a 2xx success. */
168
+ const isOk = (status) => status >= 200 && status < 300;
169
+ /**
170
+ * The MCP tool result for a baseline REST passthrough: 2xx → the body as one
171
+ * text block; non-2xx → an `isError` result carrying the body's `message` when
172
+ * it parses as `{error, message}`, else `HTTP <status>`.
173
+ */
174
+ function toolResultFromRest(r) {
175
+ if (isOk(r.status))
176
+ return textResult(r.json);
177
+ let error = `http_${r.status}`;
178
+ let message = `HTTP ${r.status}`;
179
+ if (isObject(r.json)) {
180
+ if (typeof r.json['error'] === 'string')
181
+ error = r.json['error'];
182
+ if (typeof r.json['message'] === 'string')
183
+ message = r.json['message'];
184
+ }
185
+ return textResult({ error, message }, true);
186
+ }
187
+ /** An `isError` result whose single text block is `text` verbatim (not JSON). */
188
+ function errorText(text) {
189
+ return { content: [{ type: 'text', text }], isError: true };
190
+ }
191
+ // ---- tool table -------------------------------------------------------------
192
+ /** JSON-Schema fragment for a `{kind:'session'|'exec', id}` holder tag. */
193
+ const HOLDER_SCHEMA = {
194
+ type: 'object',
195
+ properties: { kind: { type: 'string', enum: ['session', 'exec'] }, id: { type: 'string' } },
196
+ required: ['kind', 'id'],
197
+ additionalProperties: false,
198
+ };
199
+ /** Build a baseline passthrough handler from a request-builder. */
200
+ function passthrough(deps, build) {
201
+ return async (args) => {
202
+ const r = await callHub(deps, build(args));
203
+ if (r.authFailed)
204
+ return errorText(r.authMessage ?? loginHint(deps.origin));
205
+ return toolResultFromRest(r);
206
+ };
207
+ }
208
+ /**
209
+ * The 17 baseline tools — names, descriptions, and schemas mirror the hub's own
210
+ * HTTP-MCP toolset (owenloop-service `apps/hub-edge/src/mcp/tools.ts`); each maps
211
+ * to an H3 `/api/*` REST mirror. Descriptions say "Scoped Identity" for the identity
212
+ * (wire names keep `agent`), never "tool" (model-doc §0/§10).
213
+ *
214
+ * This is not the server's whole tool list. `runMcpCommand` assembles the full
215
+ * set: these 17, plus `createAgentTool`, plus the four crew tools from
216
+ * `buildCrewTools` (below — deliberately NOT folded in here, since they do not
217
+ * mirror the hub's own MCP toolset), plus the conditionally-registered
218
+ * `stageEnrollmentTool`.
219
+ */
220
+ function buildBaselineTools(deps) {
221
+ return [
222
+ {
223
+ name: 'whats_next',
224
+ description: 'THE verb. With workflow: ticks it and returns the next work order(s), or a status summary if none. Without workflow: the inbox of started instances. Serves only YOUR OWN runs by default. Pass serve_crews to partition your own runs further (intersects with each step\'s capabilities; absent or [] = no capability filter). serve_crews is ignored in inbox mode (no workflow).',
225
+ inputSchema: {
226
+ type: 'object',
227
+ properties: { workflow: { type: 'string' }, serve_crews: { type: 'array', items: { type: 'string' } } },
228
+ additionalProperties: false,
229
+ },
230
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/whats_next', body: a })),
231
+ },
232
+ {
233
+ name: 'submit',
234
+ description: 'Submit a work order output. On schema-rejected the run stays open — fix the value and submit again with the same run.',
235
+ inputSchema: {
236
+ type: 'object',
237
+ properties: {
238
+ workflow: { type: 'string' },
239
+ run: { type: 'string' },
240
+ path: { type: 'string' },
241
+ value: { type: 'object', additionalProperties: true },
242
+ done: { type: 'boolean' },
243
+ },
244
+ required: ['workflow', 'run', 'path', 'value'],
245
+ additionalProperties: false,
246
+ },
247
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/submit', body: a })),
248
+ },
249
+ {
250
+ name: 'reject_artifact',
251
+ description: 'Reject an upstream artifact, sending it back to its producer with a reason.',
252
+ inputSchema: {
253
+ type: 'object',
254
+ properties: { workflow: { type: 'string' }, path: { type: 'string' }, reason: { type: 'string' } },
255
+ required: ['workflow', 'path', 'reason'],
256
+ additionalProperties: false,
257
+ },
258
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/reject_artifact', body: a })),
259
+ },
260
+ {
261
+ name: 'provide_input',
262
+ description: 'The human-gate answer path: provide a value for a seeded/owed input.',
263
+ inputSchema: {
264
+ type: 'object',
265
+ properties: {
266
+ workflow: { type: 'string' },
267
+ name: { type: 'string' },
268
+ value: { type: 'object', additionalProperties: true },
269
+ },
270
+ required: ['workflow', 'name', 'value'],
271
+ additionalProperties: false,
272
+ },
273
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/provide_input', body: a })),
274
+ },
275
+ {
276
+ name: 'start_run',
277
+ description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs.',
278
+ inputSchema: {
279
+ type: 'object',
280
+ properties: { workflow_name: { type: 'string' }, provide: { type: 'object', additionalProperties: true } },
281
+ required: ['workflow_name'],
282
+ additionalProperties: false,
283
+ },
284
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/start_run', body: a })),
285
+ },
286
+ {
287
+ name: 'create_workflow',
288
+ description: 'The authoring hard gate: parse + load a workflow def YAML through the engine. Only stored if it loads clean. On failure returns the engine/parser error verbatim. Idempotent: re-pushing identical content is a no-op success (unchanged: true with the existing version); changed content version-forwards.',
289
+ inputSchema: {
290
+ type: 'object',
291
+ properties: { yaml: { type: 'string' } },
292
+ required: ['yaml'],
293
+ additionalProperties: false,
294
+ },
295
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/create_workflow', body: a })),
296
+ },
297
+ {
298
+ name: 'get_workflow',
299
+ description: 'Def summary and full workflow bundle: steps with consumes/produces, schemas, judges, each step\'s prompt body, model/executor/command, and x extension bags, plus mermaid source and the def content hash/version.',
300
+ inputSchema: {
301
+ type: 'object',
302
+ properties: { name: { type: 'string' } },
303
+ required: ['name'],
304
+ additionalProperties: false,
305
+ },
306
+ handler: passthrough(deps, (a) => ({
307
+ method: 'GET',
308
+ path: `/api/workflows/${encodeURIComponent(String(a['name'] ?? ''))}`,
309
+ })),
310
+ },
311
+ {
312
+ name: 'list_workflows',
313
+ description: 'Names, titles, step counts, and def content hash/version of every loaded workflow definition.',
314
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
315
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/workflows' })),
316
+ },
317
+ {
318
+ name: 'get_status',
319
+ description: 'engine.status verbatim plus a plain-English one-paragraph rendering.',
320
+ inputSchema: {
321
+ type: 'object',
322
+ properties: { workflow: { type: 'string' } },
323
+ required: ['workflow'],
324
+ additionalProperties: false,
325
+ },
326
+ handler: passthrough(deps, (a) => ({
327
+ method: 'GET',
328
+ path: `/api/status/${encodeURIComponent(String(a['workflow'] ?? ''))}`,
329
+ })),
330
+ },
331
+ {
332
+ name: 'heartbeat',
333
+ description: 'Touch the liveness timestamp on an open run so it is not reaped mid-step (the design-doc "renew"). The first heartbeat on a freshly served claim is "first contact" — it closes the ~2-minute pickup window. Optionally tag who holds the claim (session or exec).',
334
+ inputSchema: {
335
+ type: 'object',
336
+ properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
337
+ required: ['workflow', 'run'],
338
+ additionalProperties: false,
339
+ },
340
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/heartbeat', body: a })),
341
+ },
342
+ {
343
+ name: 'get_order',
344
+ description: 'Re-fetch the persisted order packet for a run you hold, plus its live lease state (claimed/claimedAt/heartbeatAt/outcome) — for a holder rebinding to work it already had served. Optionally tag who holds the claim.',
345
+ inputSchema: {
346
+ type: 'object',
347
+ properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
348
+ required: ['workflow', 'run'],
349
+ additionalProperties: false,
350
+ },
351
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/get_order', body: a })),
352
+ },
353
+ {
354
+ name: 'release',
355
+ description: 'Voluntarily give back a claim so its order is re-offered without waiting out the reap TTL. Either target one run (`workflow`+`run`) or drain a session (`session`). Idempotent: releasing an unheld/closed run is a no-op, never an error.',
356
+ inputSchema: {
357
+ type: 'object',
358
+ properties: { workflow: { type: 'string' }, run: { type: 'string' }, session: { type: 'string' } },
359
+ additionalProperties: false,
360
+ },
361
+ handler: async (a) => {
362
+ // Mirror the hub tool's client-side "either session or workflow+run" guard.
363
+ const hasSession = a['session'] !== undefined;
364
+ const hasRunPair = a['workflow'] !== undefined && a['run'] !== undefined;
365
+ if (!hasSession && !hasRunPair) {
366
+ return errorText('release requires either `session`, or both `workflow` and `run`.');
367
+ }
368
+ const r = await callHub(deps, { method: 'POST', path: '/api/release', body: a });
369
+ if (r.authFailed)
370
+ return errorText(r.authMessage ?? loginHint(deps.origin));
371
+ return toolResultFromRest(r);
372
+ },
373
+ },
374
+ {
375
+ name: 'publish_event',
376
+ description: 'Publish an event against a contract: validate the payload against the pinned contract version schema, then start one run per matched active subscription (best-effort, per-target isolation). Returns the per-match outcome. Requires agent scope `run`.',
377
+ inputSchema: {
378
+ type: 'object',
379
+ properties: {
380
+ name: { type: 'string' },
381
+ version: { type: 'integer', minimum: 1 },
382
+ payload: {},
383
+ },
384
+ required: ['name', 'payload'],
385
+ additionalProperties: false,
386
+ },
387
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/publish_event', body: a })),
388
+ },
389
+ {
390
+ name: 'list_subscriptions',
391
+ description: "The org's contract subscriptions — what a publish will cascade into. Creating/revoking a subscription is admin-only and deliberately not exposed here.",
392
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
393
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/subscriptions' })),
394
+ },
395
+ {
396
+ name: 'presence_ping',
397
+ description: 'Register or refresh this Shift in the presence registry: its name, the crews it serves, and optionally which process incarnation is reporting. Call it on a ~60s cadence; the entry reads as offline once ~3 min have passed since its last ping — derived when the registry is read, nothing sweeps it. Observability only: it never affects serving and never wakes anyone. This is NOT the lease heartbeat — that is the separate `heartbeat` tool, one per claimed run, whose lapse gets the claim reaped. Every field is overwrite, NOT keep-previous: omitting serve_crews stores an empty set, which means "every crew this principal belongs to" (the same reading whats_next gives an empty serve_crews) and NOT "no crews"; omitting shift_id/started_at clears them.',
398
+ inputSchema: {
399
+ type: 'object',
400
+ properties: {
401
+ name: { type: 'string' },
402
+ serve_crews: { type: 'array', items: { type: 'string' } },
403
+ shift_id: { type: 'string' },
404
+ started_at: { type: 'number' },
405
+ },
406
+ required: ['name'],
407
+ additionalProperties: false,
408
+ },
409
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/presence_ping', body: a })),
410
+ },
411
+ {
412
+ name: 'list_shifts',
413
+ description: "Your principal's registered Shifts, each with an online/offline flag (derived at read time from its last ping, ~3 min), how long since it was last seen, the crews it serves (returned as `crews`; an empty list means every crew this principal belongs to, not none), and the reporting process incarnation (`shiftId`/`startedAt`) when the hub recorded one.",
414
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
415
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/shifts' })),
416
+ },
417
+ {
418
+ name: 'wake',
419
+ description: 'A cheap "has anything relevant to you changed since cursor X" pre-check for a polling loop — returns { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. NOT a substitute for whats_next — it never returns work orders, only whether to ask.',
420
+ inputSchema: {
421
+ type: 'object',
422
+ properties: { cursor: { type: 'integer', minimum: 0 } },
423
+ additionalProperties: false,
424
+ },
425
+ handler: passthrough(deps, (a) => {
426
+ const cursor = a['cursor'];
427
+ const query = typeof cursor === 'number' ? `?cursor=${encodeURIComponent(String(cursor))}` : undefined;
428
+ return { method: 'GET', path: '/api/wake', query };
429
+ }),
430
+ },
431
+ ];
432
+ }
433
+ /** Legal agent name, mirroring hub.ts's `ACCOUNT_RE` shape — advisory in the schema, ENFORCED in the handler. */
434
+ const AGENT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
435
+ /**
436
+ * Tool 18 — `create_agent`. Mints a NEW Scoped Identity and writes its `olp_`
437
+ * token straight to the local store; NEVER returns the token. Decision 6: the
438
+ * mint response leaks the plaintext in `data.token` AND the human `text` field,
439
+ * so this handler never passes the raw body outbound — it takes only the
440
+ * validated `token` (to store) and the safe `crews` names (to report), and
441
+ * builds `{name, crews, stored:true}` from scratch.
442
+ */
443
+ function createAgentTool(deps) {
444
+ return {
445
+ name: 'create_agent',
446
+ description: 'Create a NEW Scoped Identity on the hub and store its credential locally. NEVER returns the token — it is written to this machine\'s credential store only. Refuses a name that is already taken. Mints with `work` scope by default; pass `scopes` (e.g. ["work","run"]) to choose.',
447
+ inputSchema: {
448
+ type: 'object',
449
+ properties: {
450
+ name: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' },
451
+ crews: { type: 'array', items: { type: 'string' } },
452
+ scopes: { type: 'array', items: { type: 'string' } },
453
+ },
454
+ required: ['name'],
455
+ additionalProperties: false,
456
+ },
457
+ handler: async (args) => {
458
+ const name = args['name'];
459
+ // Re-validate the name BEFORE any network call — the advertised schema is
460
+ // advisory (hosts may not enforce it); `credentialSlot` is the backstop.
461
+ if (typeof name !== 'string' || !AGENT_NAME_RE.test(name)) {
462
+ return errorText('invalid agent name — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*');
463
+ }
464
+ // `scopes` is optional. When present it must be a non-empty array of
465
+ // non-empty strings — validated BEFORE any network call (the schema is
466
+ // advisory). Absent → the `work`-only default. No scope-NAME check: the
467
+ // hub is the enforcement of record (same stance as crews).
468
+ const scopesArg = args['scopes'];
469
+ let scopes;
470
+ if (scopesArg !== undefined) {
471
+ if (!Array.isArray(scopesArg) || scopesArg.length === 0 || !scopesArg.every((s) => typeof s === 'string' && s !== '')) {
472
+ return errorText('invalid scopes — expected a non-empty array of scope name strings');
473
+ }
474
+ scopes = scopesArg;
475
+ }
476
+ const crews = args['crews'];
477
+ const body = { name, scopes: scopes ?? ['work'] };
478
+ if (Array.isArray(crews))
479
+ body.crews = crews;
480
+ const r = await callHub(deps, { method: 'POST', path: '/api/mint_agent_token', body });
481
+ if (r.authFailed)
482
+ return errorText(r.authMessage ?? loginHint(deps.origin));
483
+ if (!isOk(r.status)) {
484
+ // Surface the hub's `message` ONLY (error bodies never carry tokens, but
485
+ // never echo the whole body regardless).
486
+ const message = isObject(r.json) && typeof r.json['message'] === 'string' ? r.json['message'] : `HTTP ${r.status}`;
487
+ return errorText(message);
488
+ }
489
+ // 2xx: extract and validate the token WITHOUT echoing the body.
490
+ const token = isObject(r.json) ? r.json['token'] : undefined;
491
+ if (typeof token !== 'string' || !token.startsWith('olp_')) {
492
+ return errorText('hub response did not include an agent token');
493
+ }
494
+ try {
495
+ await storeCredential(deps.io, deps.origin, { principal: 'agent', account: name }, { kind: 'agent', accessToken: token });
496
+ }
497
+ catch (e) {
498
+ return errorText(`${e.message} — the minted token was NOT stored — revoke/re-key the Scoped Identity '${name}' from the console`);
499
+ }
500
+ // Success: built from scratch. `crews` (crewNames) is safe; token/text/id
501
+ // /agentId/crewIds from the body must never reach an outbound frame.
502
+ const outCrews = isObject(r.json) && Array.isArray(r.json['crews']) ? r.json['crews'] : [];
503
+ return textResult({ name, crews: outCrews, stored: true });
504
+ },
505
+ };
506
+ }
507
+ /** Tool 19 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
508
+ function stageEnrollmentTool(deps) {
509
+ return {
510
+ name: 'stage_enrollment',
511
+ description: 'Stage a Scoped Identity enrollment on the hub, returning a join code the enrolling machine redeems. A join code is transferred authority, not a credential — it is safe to surface.',
512
+ inputSchema: {
513
+ type: 'object',
514
+ properties: {
515
+ name: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' },
516
+ crews: { type: 'array', items: { type: 'string' } },
517
+ },
518
+ required: ['name'],
519
+ additionalProperties: false,
520
+ },
521
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/stage_enrollment', body: a })),
522
+ };
523
+ }
524
+ /**
525
+ * Crew management — the MCP counterpart to the `owenloop crew` CLI family
526
+ * (`src/cli.ts`'s `dispatchCrew`, merged as PR #88). All FOUR tools below are
527
+ * plain `passthrough` registrations: the hub's crew response bodies carry no
528
+ * secret (unlike `create_agent`'s mint body), so there is no reason to
529
+ * hand-build a result, and the hub's `/api/*` routes plus the verbs underneath
530
+ * them are already the enforcement of record for every field — a client-side
531
+ * copy of that validation would just be a second place for the rules to drift.
532
+ *
533
+ * CREDENTIAL PLANE: unchanged, and worth restating because it is what makes
534
+ * crew mutation reachable at all from this server. `callHub` always
535
+ * authenticates as the `human` slot (`HUMAN`, above) — `owenloop mcp` never
536
+ * calls the hub as a Scoped Identity. On the hub, `createCrew`, `addCrewMember`,
537
+ * and `removeCrewMember` gate through `assertCrewMutationAllowed`
538
+ * (`packages/hub-core/src/verbs/manage-crews.ts`), which falls through to
539
+ * `assertAllowed(actor, 'manage_crews')` — a verb with NO entry in
540
+ * `AGENT_SCOPE_FOR_VERB` (`rbac.ts`), so an agent-kind actor is refused
541
+ * `ForbiddenError` there no matter what scopes it holds. Because this server
542
+ * always authenticates as a human, that refusal never applies to it. `listCrews`
543
+ * is gated on the separate, agent-reachable `list` verb instead.
544
+ *
545
+ * `delete_crew` IS DELIBERATELY ABSENT, and stays absent — a decision by the
546
+ * repo's human owner, not a technical gap. Deleting a crew transfers its live
547
+ * `order_crews` stamps onto the org's orphan crew and deletes the crew's own
548
+ * membership rows outright; that is not an operation a model-driven host
549
+ * should be able to trigger. Do not add a `delete_crew` tool, an env-flag
550
+ * variant, or a confirmation-style variant — `owenloop crew rm` on the CLI
551
+ * remains the only way to delete a crew. Removing a single MEMBER (below) is a
552
+ * different, reversible operation and stays in scope.
553
+ */
554
+ function buildCrewTools(deps) {
555
+ return [
556
+ {
557
+ name: 'list_crews',
558
+ description: "The org's crews, each with its membership rows inline (principalKind/principalId/addedBy/addedAt) — " +
559
+ 'one call, no per-crew fan-out. An org with no crews at all is a normal empty result, not an error. ' +
560
+ "The org's reserved ORPHAN crew (kind: \"orphan\", or a name starting \"orphan:\") IS returned when it " +
561
+ 'exists and is deliberately NOT filtered out — it is where the hub re-homes work whose crew was ' +
562
+ 'deleted, so a caller has to be able to see where that work went. It is materialized LAZILY: a fresh ' +
563
+ "org has none. Its membership is derived (always the org's current admins) and cannot be edited — " +
564
+ 'add_crew_member/remove_crew_member both refuse it.',
565
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
566
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/crews' })),
567
+ },
568
+ {
569
+ name: 'create_crew',
570
+ description: "Create a crew on the hub org. `kind` is 'personal' or 'shared', forwarded verbatim — the hub is the " +
571
+ "enforcement of record for legal values ('orphan' is reserved for the hub's own crew and is refused). " +
572
+ "`ownerMemberId` is required for a 'personal' crew and is simply omitted from the request when not " +
573
+ 'passed. NOT admin-only: an org admin may create any crew, AND a non-admin may create a personal crew ' +
574
+ 'they own by passing kind:"personal" with ownerMemberId set to their own member id (the ' +
575
+ 'self-service branch of the mutation gate). A non-admin asking for a shared crew, for a personal crew ' +
576
+ 'owned by someone else, or for a personal crew with ownerMemberId OMITTED, is refused 403 — the hub ' +
577
+ 'deliberately does not infer the caller as the owner.',
578
+ inputSchema: {
579
+ type: 'object',
580
+ properties: {
581
+ name: { type: 'string' },
582
+ kind: { type: 'string' },
583
+ ownerMemberId: { type: 'string' },
584
+ },
585
+ required: ['name', 'kind'],
586
+ additionalProperties: false,
587
+ },
588
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/create_crew', body: a })),
589
+ },
590
+ {
591
+ name: 'add_crew_member',
592
+ description: "Add one principal to a crew. `principalKind` is 'member' (a human) or 'agent' (a Scoped Identity), " +
593
+ 'forwarded verbatim; the hub validates it. NOT admin-only: an org admin may act on any crew, AND the ' +
594
+ 'OWNER of a personal crew may add members to that crew without being an admin. HTTP 400 (not a ' +
595
+ 'permissions error, and NOT tolerant): an unknown crewId, an unknown principalId, or a principal that ' +
596
+ 'is ALREADY a member — a duplicate add IS an error, unlike remove_crew_member below. REFUSED OUTRIGHT ' +
597
+ "against the org's orphan crew, for every caller including an admin, as a 400 (never a 403 — the " +
598
+ "refusal is identity-independent: it objects to the target crew, not the caller's role). The orphan " +
599
+ "crew's membership is the derived org admin roster and cannot be edited this way.",
600
+ inputSchema: {
601
+ type: 'object',
602
+ properties: {
603
+ crewId: { type: 'string' },
604
+ principalKind: { type: 'string' },
605
+ principalId: { type: 'string' },
606
+ },
607
+ required: ['crewId', 'principalKind', 'principalId'],
608
+ additionalProperties: false,
609
+ },
610
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/add_crew_member', body: a })),
611
+ },
612
+ {
613
+ name: 'remove_crew_member',
614
+ description: 'Remove one principal from a crew. TOLERANT: removing a principal that was never a member is a normal ' +
615
+ 'success — HTTP 200 with removed:false, NOT a 404. Read the `removed` boolean rather than treating a ' +
616
+ 'false as a failure. An unknown crewId is DIFFERENT and is an HTTP 400 error. NOT admin-only: same ' +
617
+ 'self-service carve-out as add_crew_member — an org admin, or the owner of the personal crew being ' +
618
+ "acted on. REFUSED OUTRIGHT against the org's orphan crew, for every caller including an admin, as a " +
619
+ '400 — and that orphan refusal is NOT tolerant: it throws even when the principal was never a member, ' +
620
+ 'because the objection is to the target crew and is decided before the hub looks at the membership ' +
621
+ 'row. Removing a member is reversible. DELETING a crew is deliberately NOT available on this server at ' +
622
+ 'all — use the `owenloop crew rm` CLI command for that.',
623
+ inputSchema: {
624
+ type: 'object',
625
+ properties: {
626
+ crewId: { type: 'string' },
627
+ principalId: { type: 'string' },
628
+ },
629
+ required: ['crewId', 'principalId'],
630
+ additionalProperties: false,
631
+ },
632
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/remove_crew_member', body: a })),
633
+ },
634
+ ];
635
+ }
636
+ // ---- enrollment capability gate (Decision 7) --------------------------------
637
+ /** The probe deadline; `OWENLOOP_MCP_PROBE_TIMEOUT_MS` overrides the 3000ms default. */
638
+ function probeTimeoutMs(env) {
639
+ const override = Number(env.OWENLOOP_MCP_PROBE_TIMEOUT_MS);
640
+ return Number.isFinite(override) && override > 0 ? override : 3000;
641
+ }
642
+ /**
643
+ * Decide, ONCE at startup, whether `stage_enrollment` is registered (the core's
644
+ * tool list is fixed at construction). `OWENLOOP_MCP_ENROLLMENT=1` → yes; `=0` →
645
+ * no; unset → PROBE. Probe (only when a human credential is stored): a
646
+ * short-deadline `POST /api/stage_enrollment {}` via the authed client; register
647
+ * iff the call completes with a status that is neither 404 nor 401 (a registered
648
+ * route answers 400/403/2xx to an empty body; an unregistered route 404s). Any
649
+ * network error, timeout, refresh failure, or missing credential → NOT
650
+ * registered (fail-closed: worst case the tool is hidden until H4/H7 revisit).
651
+ */
652
+ async function shouldRegisterEnrollment(deps) {
653
+ const flag = deps.io.env.OWENLOOP_MCP_ENROLLMENT;
654
+ if (flag === '1')
655
+ return true;
656
+ if (flag === '0')
657
+ return false;
658
+ try {
659
+ const cred = readStoredCredential(deps.origin, { principal: 'human', env: deps.io.env, keychain: deps.io.keychain });
660
+ if (cred === null)
661
+ return false;
662
+ const probeTimeout = probeTimeoutMs(deps.io.env);
663
+ const probeIo = { ...deps.io, env: { ...deps.io.env, OWENLOOP_HUB_TIMEOUT_MS: String(probeTimeout) } };
664
+ const r = await callHub({ io: probeIo, origin: deps.origin }, { method: 'POST', path: '/api/stage_enrollment', body: {} });
665
+ if (r.authFailed)
666
+ return false;
667
+ return r.status !== 404 && r.status !== 401;
668
+ }
669
+ catch {
670
+ return false;
671
+ }
672
+ }
673
+ // ---- command body -----------------------------------------------------------
674
+ /**
675
+ * Run the `owenloop mcp` command: resolve the origin, decide the enrollment
676
+ * gate, build the tool list, construct the JSON-RPC server, and pump stdin until
677
+ * EOF. Returns the process exit code: 2 on an origin-ambiguity (message to
678
+ * stderr, nothing to stdout — stdout is the protocol channel), else 0 on stdin
679
+ * EOF. A malformed `--hub`/`OWENLOOP_HUB` throws a `CliError` (exit-1 path).
680
+ */
681
+ export async function runMcpCommand(io, opts) {
682
+ const resolved = resolveMcpOrigin(io, opts.hubFlag);
683
+ if ('exitCode' in resolved) {
684
+ io.err(resolved.message);
685
+ return resolved.exitCode;
686
+ }
687
+ const deps = { io, origin: resolved.origin };
688
+ const tools = [...buildBaselineTools(deps), createAgentTool(deps), ...buildCrewTools(deps)];
689
+ if (await shouldRegisterEnrollment(deps))
690
+ tools.push(stageEnrollmentTool(deps));
691
+ const server = createMcpServer({
692
+ name: 'owenloop-cli-mcp',
693
+ version: '0.0.1',
694
+ tools,
695
+ write: (msg) => io.out(JSON.stringify(msg)),
696
+ err: (line) => io.err(line),
697
+ });
698
+ return new Promise((resolve) => {
699
+ const stream = io.stdinStream ?? process.stdin;
700
+ pumpStdin(stream, server, () => resolve(0));
701
+ });
702
+ }