owenloop 0.5.9 → 0.5.11

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 (86) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +77 -37
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.js +7 -0
  5. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  6. package/dist/packages/work/src/bundle/pull.js +118 -0
  7. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  8. package/dist/packages/work/src/exec/instructions.js +3 -0
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +92 -14
  11. package/dist/packages/work/src/harness/claude.js +16 -0
  12. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  13. package/dist/packages/work/src/harness/codex.js +27 -1
  14. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  15. package/dist/packages/work/src/roles/agent-run.js +38 -10
  16. package/dist/packages/work/src/roles/exec.js +25 -8
  17. package/dist/packages/work/src/shift/loop.js +118 -4
  18. package/dist/packages/work/src/shift/runtime.d.ts +3 -0
  19. package/dist/packages/work/src/shift/runtime.js +10 -1
  20. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  21. package/dist/packages/work/src/submit-proof.js +11 -8
  22. package/dist/src/capabilities.d.ts +70 -6
  23. package/dist/src/capabilities.js +49 -6
  24. package/dist/src/capability-mapping-client.d.ts +29 -0
  25. package/dist/src/capability-mapping-client.js +160 -0
  26. package/dist/src/cli.d.ts +2 -2
  27. package/dist/src/cli.js +1200 -166
  28. package/dist/src/defs.d.ts +41 -1
  29. package/dist/src/defs.js +461 -92
  30. package/dist/src/engine.d.ts +108 -22
  31. package/dist/src/engine.js +573 -85
  32. package/dist/src/factory.js +5 -3
  33. package/dist/src/hub.d.ts +77 -0
  34. package/dist/src/hub.js +162 -0
  35. package/dist/src/implements.d.ts +37 -0
  36. package/dist/src/implements.js +790 -0
  37. package/dist/src/index.d.ts +12 -10
  38. package/dist/src/index.js +7 -6
  39. package/dist/src/mcp/serve.js +254 -45
  40. package/dist/src/mcp/server.d.ts +10 -7
  41. package/dist/src/mcp/server.js +53 -8
  42. package/dist/src/model.d.ts +46 -10
  43. package/dist/src/model.js +224 -78
  44. package/dist/src/order-resolver.js +1 -0
  45. package/dist/src/store/def-source.d.ts +19 -0
  46. package/dist/src/store/def-source.js +87 -17
  47. package/dist/src/store/gc-recovery.d.ts +46 -0
  48. package/dist/src/store/gc-recovery.js +258 -0
  49. package/dist/src/store/gc.d.ts +94 -0
  50. package/dist/src/store/gc.js +563 -0
  51. package/dist/src/store/index.d.ts +3 -1
  52. package/dist/src/store/index.js +2 -0
  53. package/dist/src/store/install.d.ts +34 -5
  54. package/dist/src/store/install.js +73 -11
  55. package/dist/src/store/pre-commit-verifier.js +42 -2
  56. package/dist/src/store/snapshot-guard.d.ts +18 -0
  57. package/dist/src/store/snapshot-guard.js +94 -0
  58. package/dist/src/store.d.ts +66 -4
  59. package/dist/src/store.js +333 -12
  60. package/dist/src/types.d.ts +97 -17
  61. package/dist/src/types.js +4 -0
  62. package/dist/src/util.js +4 -1
  63. package/docs/authoring.md +214 -9
  64. package/docs/bundles.md +19 -0
  65. package/docs/cli.md +270 -30
  66. package/docs/crypto.md +13 -7
  67. package/docs/design.md +107 -46
  68. package/docs/evals/mcp-charter-baseline.json +428 -0
  69. package/docs/mcp-charter-eval.md +124 -0
  70. package/docs/shift-logs.md +18 -0
  71. package/docs/wire-contracts.md +28 -7
  72. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  73. package/examples/workflows/ship.yaml +28 -2
  74. package/package.json +2 -1
  75. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  76. package/plugins/claude-code/plugin/.mcp.json +1 -1
  77. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  78. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  79. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  80. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  81. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  82. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  83. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  84. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  85. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  86. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
@@ -149,8 +149,51 @@ function loginHint(origin) {
149
149
  * 4. on a 401 with an oauth credential, exactly ONE `refreshOAuth` + one
150
150
  * retry; a final 401 → `authFailed`.
151
151
  * The response body is parsed leniently (a parse failure yields `{}`, status
152
- * preserved). The bearer never leaves the `Authorization` header.
152
+ * preserved), including Streamable HTTP's JSON and SSE response forms. The
153
+ * bearer never leaves the `Authorization` header.
153
154
  */
155
+ function parseSseMessages(body) {
156
+ const messages = [];
157
+ let data = [];
158
+ const dispatch = () => {
159
+ if (data.length === 0)
160
+ return;
161
+ const payload = data.join('\n');
162
+ data = [];
163
+ if (payload === '[DONE]')
164
+ return;
165
+ try {
166
+ messages.push(JSON.parse(payload));
167
+ }
168
+ catch {
169
+ // A malformed event is not a valid MCP response. Keep looking in case a
170
+ // later event carries the request's response, then fail closed if not.
171
+ }
172
+ };
173
+ for (const rawLine of body.split('\n')) {
174
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
175
+ if (line === '') {
176
+ dispatch();
177
+ continue;
178
+ }
179
+ if (!line.startsWith('data:'))
180
+ continue;
181
+ const value = line.slice('data:'.length);
182
+ data.push(value.startsWith(' ') ? value.slice(1) : value);
183
+ }
184
+ dispatch();
185
+ return messages;
186
+ }
187
+ async function parseHubResponse(res, jsonRpcResponseId) {
188
+ const contentType = res.headers.get('content-type')?.toLowerCase() ?? '';
189
+ if (!contentType.includes('text/event-stream'))
190
+ return res.json();
191
+ const messages = parseSseMessages(await res.text());
192
+ if (jsonRpcResponseId !== undefined) {
193
+ return messages.find((message) => isObject(message) && message['id'] === jsonRpcResponseId) ?? {};
194
+ }
195
+ return messages.at(-1) ?? {};
196
+ }
154
197
  async function callHub(deps, req) {
155
198
  const { io, origin } = deps;
156
199
  let cred;
@@ -176,6 +219,7 @@ async function callHub(deps, req) {
176
219
  Authorization: authHeader(c),
177
220
  Accept: 'application/json',
178
221
  ...(req.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
222
+ ...(req.headers ?? {}),
179
223
  };
180
224
  return hubFetch(io, resolveEndpoint(origin, req.path + (req.query ?? '')), {
181
225
  method: req.method,
@@ -198,12 +242,12 @@ async function callHub(deps, req) {
198
242
  }
199
243
  let json;
200
244
  try {
201
- json = await res.json();
245
+ json = await parseHubResponse(res, req.jsonRpcResponseId);
202
246
  }
203
247
  catch {
204
248
  json = {};
205
249
  }
206
- return { status: res.status, json };
250
+ return { status: res.status, json, mcpSessionId: res.headers.get('mcp-session-id') ?? undefined };
207
251
  }
208
252
  /** Whether an HTTP status is a 2xx success. */
209
253
  const isOk = (status) => status >= 200 && status < 300;
@@ -229,6 +273,113 @@ function toolResultFromRest(r) {
229
273
  function errorText(text) {
230
274
  return { content: [{ type: 'text', text }], isError: true };
231
275
  }
276
+ /**
277
+ * Attest the *remote* hub's ephemeral workflow contract before forwarding an
278
+ * `ephemeral:true` create. The local proxy always advertises its newest schema,
279
+ * so neither its tools/list response nor a successful inclusive REST listing
280
+ * can establish that an older selected hub honors these fields. This follows
281
+ * the Streamable HTTP lifecycle with authenticated, non-mutating requests:
282
+ * initialize, notifications/initialized, then tools/list. The negotiated
283
+ * protocol version and any returned session id ride every later request.
284
+ */
285
+ async function attestRemoteEphemeralWorkflowSupport(deps) {
286
+ const noCreate = '; no create request was sent';
287
+ const jsonRpcError = (stage, response) => {
288
+ const error = isObject(response) ? response['error'] : undefined;
289
+ if (error === undefined)
290
+ return undefined;
291
+ return `ephemeral workflow preflight remote MCP ${stage} returned JSON-RPC error ${JSON.stringify(error)}${noCreate}`;
292
+ };
293
+ const initialize = await callHub(deps, {
294
+ method: 'POST',
295
+ path: '/mcp',
296
+ headers: { Accept: 'application/json, text/event-stream' },
297
+ jsonRpcResponseId: 'owenloop-ephemeral-preflight-initialize',
298
+ body: {
299
+ jsonrpc: '2.0',
300
+ id: 'owenloop-ephemeral-preflight-initialize',
301
+ method: 'initialize',
302
+ params: {
303
+ protocolVersion: '2025-06-18',
304
+ capabilities: {},
305
+ clientInfo: { name: 'owenloop-cli-mcp', version: packageVersion() },
306
+ },
307
+ },
308
+ });
309
+ if (initialize.authFailed)
310
+ return initialize.authMessage ?? loginHint(deps.origin);
311
+ const initializeError = jsonRpcError('initialize', initialize.json);
312
+ if (initializeError !== undefined)
313
+ return initializeError;
314
+ if (!isOk(initialize.status)) {
315
+ return `ephemeral workflow preflight could not initialize remote MCP at ${deps.origin} (HTTP ${initialize.status}); no create request was sent`;
316
+ }
317
+ const initializeResult = isObject(initialize.json) ? initialize.json['result'] : undefined;
318
+ const protocolVersion = isObject(initializeResult) ? initializeResult['protocolVersion'] : undefined;
319
+ if (typeof protocolVersion !== 'string' || protocolVersion === '') {
320
+ return `ephemeral workflow preflight received no negotiated remote MCP protocol version from ${deps.origin}${noCreate}`;
321
+ }
322
+ const subsequentHeaders = {
323
+ Accept: 'application/json, text/event-stream',
324
+ 'MCP-Protocol-Version': protocolVersion,
325
+ ...(initialize.mcpSessionId === undefined ? {} : { 'Mcp-Session-Id': initialize.mcpSessionId }),
326
+ };
327
+ const initialized = await callHub(deps, {
328
+ method: 'POST',
329
+ path: '/mcp',
330
+ headers: subsequentHeaders,
331
+ body: { jsonrpc: '2.0', method: 'notifications/initialized' },
332
+ });
333
+ if (initialized.authFailed)
334
+ return initialized.authMessage ?? loginHint(deps.origin);
335
+ const initializedError = jsonRpcError('initialized notification', initialized.json);
336
+ if (initializedError !== undefined)
337
+ return initializedError;
338
+ if (!isOk(initialized.status)) {
339
+ return `ephemeral workflow preflight could not send remote MCP initialized notification to ${deps.origin} (HTTP ${initialized.status})${noCreate}`;
340
+ }
341
+ const listed = await callHub(deps, {
342
+ method: 'POST',
343
+ path: '/mcp',
344
+ headers: subsequentHeaders,
345
+ jsonRpcResponseId: 'owenloop-ephemeral-preflight-tools-list',
346
+ body: {
347
+ jsonrpc: '2.0',
348
+ id: 'owenloop-ephemeral-preflight-tools-list',
349
+ method: 'tools/list',
350
+ params: {},
351
+ },
352
+ });
353
+ if (listed.authFailed)
354
+ return listed.authMessage ?? loginHint(deps.origin);
355
+ const listedError = jsonRpcError('tools/list', listed.json);
356
+ if (listedError !== undefined)
357
+ return listedError;
358
+ if (!isOk(listed.status)) {
359
+ return `ephemeral workflow preflight could not list remote MCP tools at ${deps.origin} (HTTP ${listed.status}); no create request was sent`;
360
+ }
361
+ const response = isObject(listed.json) ? listed.json['result'] : undefined;
362
+ const tools = isObject(response) && Array.isArray(response['tools']) ? response['tools'] : undefined;
363
+ if (tools === undefined) {
364
+ return `ephemeral workflow preflight received no remote MCP tools/list result from ${deps.origin}; no create request was sent`;
365
+ }
366
+ const findTool = (name) => tools.find((tool) => isObject(tool) && tool['name'] === name);
367
+ const supportsBoolean = (tool, field) => {
368
+ const schema = tool?.['inputSchema'];
369
+ const properties = isObject(schema) ? schema['properties'] : undefined;
370
+ const property = isObject(properties) ? properties[field] : undefined;
371
+ return isObject(property) && property['type'] === 'boolean';
372
+ };
373
+ const missing = [
374
+ !supportsBoolean(findTool('create_workflow'), 'ephemeral') ? 'create_workflow.ephemeral' : undefined,
375
+ !supportsBoolean(findTool('list_workflows'), 'include_ephemeral') ? 'list_workflows.include_ephemeral' : undefined,
376
+ findTool('delete_workflow') === undefined ? 'delete_workflow' : undefined,
377
+ ].filter((item) => item !== undefined);
378
+ if (missing.length > 0) {
379
+ return `ephemeral workflow preflight found that remote MCP at ${deps.origin} lacks ${missing.join(', ')}; no create request was sent`;
380
+ }
381
+ return undefined;
382
+ }
232
383
  // ---- tool table -------------------------------------------------------------
233
384
  /** JSON-Schema fragment for a `{kind:'session'|'exec', id}` holder tag. */
234
385
  const HOLDER_SCHEMA = {
@@ -327,9 +478,11 @@ function submissionFingerprint(order, deps) {
327
478
  * judge-approve commit does not increment it. Producer claims name
328
479
  * `owes[].version`, the target the engine issued for this owed output inside
329
480
  * the claim transaction — the version the next successful commit lands, and
330
- * the version the consumer checks the proof against. See
331
- * `outputVersionForSubmission` in packages/work/src/submit-proof.ts for the
332
- * retry-safety argument; this is the same rule on the local MCP path.
481
+ * the version the consumer checks the proof against. It is re-read off the
482
+ * order on every submit and never cached, because a reject that re-arms an
483
+ * open claim re-stamps it. See `outputVersionForSubmission` in
484
+ * packages/work/src/submit-proof.ts for the retry-safety argument; this is the
485
+ * same rule on the local MCP path.
333
486
  */
334
487
  function outputVersion(order, path) {
335
488
  if (order.judge === path)
@@ -346,13 +499,13 @@ function warnMcpUnsigned(deps, reason) {
346
499
  deps.io.err(`owenloop mcp: ${reason}`);
347
500
  }
348
501
  /**
349
- * The 20 baseline tools — names, descriptions, and schemas mirror the hub's own
502
+ * The 23 baseline tools — names, descriptions, and schemas mirror the hub's own
350
503
  * HTTP-MCP toolset (owenloop-service `apps/hub-edge/src/mcp/tools.ts`); each maps
351
504
  * to an H3 `/api/*` REST mirror. Descriptions say "Scoped Identity" for the identity
352
505
  * (wire names keep `agent`), never "tool" (model-doc §0/§10).
353
506
  *
354
507
  * This is not the server's whole tool list. `runMcpCommand` assembles the full
355
- * set: these 20, plus `createAgentTool`, plus the four crew tools from
508
+ * set: these 23, plus `createAgentTool`, plus the four crew tools from
356
509
  * `buildCrewTools` (below — deliberately NOT folded in here, since they do not
357
510
  * mirror the hub's own MCP toolset), plus the conditionally-registered
358
511
  * `stageEnrollmentTool`.
@@ -361,7 +514,7 @@ function buildBaselineTools(deps) {
361
514
  return [
362
515
  {
363
516
  name: 'whats_next',
364
- 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).',
517
+ description: 'The chief-of-staff follow-up, tick, and inbox operation: relay returned work or status to the human and let crews execute it rather than treating orders as inline scratchpad work. 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).',
365
518
  inputSchema: {
366
519
  type: 'object',
367
520
  properties: {
@@ -370,17 +523,27 @@ function buildBaselineTools(deps) {
370
523
  serve_capabilities: {
371
524
  type: 'array',
372
525
  items: { type: 'string' },
373
- description: 'Capability keys this caller serves, raw (bare names and exact compounds). ' +
374
- 'Shifts compute this from their effective rosters; other callers normally omit it.',
526
+ description: 'Raw capability keys this caller serves (bare names and exact compounds). ' +
527
+ 'Shifts derive them from their effective rosters; other callers normally omit them.',
375
528
  },
376
529
  },
377
530
  additionalProperties: false,
378
531
  },
379
532
  handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/whats_next', body: a })),
380
533
  },
534
+ {
535
+ name: 'pending_gates',
536
+ description: 'Find workflow gates currently waiting on a person. A gate is an owed workflow input that no worker can supply; call this after starting or attending runs, or whenever the human asks what decisions or values need attention. Pass serve_crews to narrow the result to those crews.',
537
+ inputSchema: {
538
+ type: 'object',
539
+ properties: { serve_crews: { type: 'array', items: { type: 'string' } } },
540
+ additionalProperties: false,
541
+ },
542
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/pending_gates', body: a })),
543
+ },
381
544
  {
382
545
  name: 'submit',
383
- description: 'Submit a work order output. On schema-rejected the run stays open — fix the value and submit again with the same run.',
546
+ description: 'A crew member or held-order holder returns an owed output here; a chief of staff must not use it to fabricate inline step progress. On schema rejection the run stays open — fix the value and submit again with the same run.',
384
547
  inputSchema: {
385
548
  type: 'object',
386
549
  properties: {
@@ -413,10 +576,15 @@ function buildBaselineTools(deps) {
413
576
  },
414
577
  {
415
578
  name: 'reject_artifact',
416
- description: 'Reject an upstream artifact, sending it back to its producer with a reason.',
579
+ description: 'Surface actionable feedback on a real upstream defect by sending it to its producer with a concrete reason. Rejection must be handled, never bypassed to force progress.',
417
580
  inputSchema: {
418
581
  type: 'object',
419
- properties: { workflow: { type: 'string' }, path: { type: 'string' }, reason: { type: 'string' } },
582
+ properties: {
583
+ workflow: { type: 'string' },
584
+ path: { type: 'string' },
585
+ reason: { type: 'string' },
586
+ requested: { type: 'string' },
587
+ },
420
588
  required: ['workflow', 'path', 'reason'],
421
589
  additionalProperties: false,
422
590
  },
@@ -424,9 +592,9 @@ function buildBaselineTools(deps) {
424
592
  },
425
593
  {
426
594
  name: 'retry_artifact',
427
- description: "The human stall-clearing lever: re-arm a stalled or rejected artifact to 'owed', resetting its " +
428
- 'reject counters. This is also the answer path for a worker that escalated with `ask` — `text` ' +
429
- "rides to the next producer on the artifact's reason thread. Omit `text` for a bare stall-clear.",
595
+ description: "The deliberate human stall-clear and worker-`ask` answer path: re-arm a stalled or rejected artifact to 'owed', resetting its " +
596
+ 'reject counters, but never use it to bypass unresolved rejection feedback. `text` rides to the next producer on ' +
597
+ "the artifact's reason thread; omit it only for a bare stall-clear.",
430
598
  inputSchema: {
431
599
  type: 'object',
432
600
  properties: { workflow: { type: 'string' }, path: { type: 'string' }, text: { type: 'string' } },
@@ -437,7 +605,7 @@ function buildBaselineTools(deps) {
437
605
  },
438
606
  {
439
607
  name: 'provide_input',
440
- description: 'The human-gate answer path: provide a value for a seeded/owed input.',
608
+ description: 'Relay a human answer into a seeded or owed gate by providing its input value.',
441
609
  inputSchema: {
442
610
  type: 'object',
443
611
  properties: {
@@ -452,7 +620,7 @@ function buildBaselineTools(deps) {
452
620
  },
453
621
  {
454
622
  name: 'start_run',
455
- description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs. ' +
623
+ description: 'For a fitting multi-step playbook, start a run from its selected definition name and let its crews execute; optionally seed provided inputs. ' +
456
624
  '`scope` is a free routing label recorded on the run; when omitted it defaults to this ' +
457
625
  "session's repository name (the `origin` remote's last path segment) when one can be " +
458
626
  'determined, and is sent as nothing otherwise. `priority` is the rate-limit band; omit it ' +
@@ -479,18 +647,28 @@ function buildBaselineTools(deps) {
479
647
  },
480
648
  {
481
649
  name: 'create_workflow',
482
- 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.',
650
+ description: 'Only when no catalog entry fits and the human chooses ordinary authoring, use this parse-and-load hard gate for a workflow definition YAML. It is stored only if it loads clean; failures return 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.',
483
651
  inputSchema: {
484
652
  type: 'object',
485
- properties: { yaml: { type: 'string' } },
653
+ properties: { yaml: { type: 'string' }, bundle_digest: { type: 'string' }, ephemeral: { type: 'boolean' } },
486
654
  required: ['yaml'],
487
655
  additionalProperties: false,
488
656
  },
489
- handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/create_workflow', body: a })),
657
+ handler: async (a) => {
658
+ if (a['ephemeral'] === true) {
659
+ const preflightFailure = await attestRemoteEphemeralWorkflowSupport(deps);
660
+ if (preflightFailure !== undefined)
661
+ return errorText(preflightFailure);
662
+ }
663
+ const r = await callHub(deps, { method: 'POST', path: '/api/create_workflow', body: a });
664
+ if (r.authFailed)
665
+ return errorText(r.authMessage ?? loginHint(deps.origin));
666
+ return toolResultFromRest(r);
667
+ },
490
668
  },
491
669
  {
492
670
  name: 'get_workflow',
493
- 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.',
671
+ description: 'Inspect a promising catalog entry in full before selecting it: def summary and bundle with steps, 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.',
494
672
  inputSchema: {
495
673
  type: 'object',
496
674
  properties: { name: { type: 'string' } },
@@ -504,13 +682,44 @@ function buildBaselineTools(deps) {
504
682
  },
505
683
  {
506
684
  name: 'list_workflows',
507
- description: 'Names, titles, step counts, and def content hash/version of every loaded workflow definition.',
508
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
509
- handler: passthrough(deps, () => ({ method: 'GET', path: '/api/workflows' })),
685
+ description: 'Discover published workflow definitions and decide which one fits a task.',
686
+ inputSchema: { type: 'object', properties: { include_ephemeral: { type: 'boolean' } }, additionalProperties: false },
687
+ handler: passthrough(deps, (a) => ({
688
+ method: 'GET',
689
+ path: '/api/workflows',
690
+ ...('include_ephemeral' in a ? { query: `?include_ephemeral=${String(a['include_ephemeral'])}` } : {}),
691
+ })),
692
+ },
693
+ {
694
+ name: 'search_workflows',
695
+ description: 'Search the same published catalog as a context-smaller ranked read when it is too large to read whole or the host cannot spend the full-list context. For smaller catalogs (roughly below 75 definitions), reading the full listing can support better selection.',
696
+ // Deliberately stricter than the REST route, which ignores unknown fields: MCP callers fail locally without a hub round-trip.
697
+ inputSchema: {
698
+ type: 'object',
699
+ properties: {
700
+ query: { type: 'string' },
701
+ limit: { type: 'integer', minimum: 1 },
702
+ include_ephemeral: { type: 'boolean' },
703
+ },
704
+ required: ['query'],
705
+ additionalProperties: false,
706
+ },
707
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/search_workflows', body: a })),
708
+ },
709
+ {
710
+ name: 'delete_workflow',
711
+ description: 'Retire an ephemeral workflow live name. Refuses while an active root references its exact pinned definition closure.',
712
+ inputSchema: {
713
+ type: 'object',
714
+ properties: { name: { type: 'string', minLength: 1 } },
715
+ required: ['name'],
716
+ additionalProperties: false,
717
+ },
718
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/delete_workflow', body: a })),
510
719
  },
511
720
  {
512
721
  name: 'get_status',
513
- description: 'engine.status verbatim plus a plain-English one-paragraph rendering.',
722
+ description: 'Inspect and relay a run\'s current state rather than performing its work: engine.status verbatim plus a plain-English one-paragraph rendering.',
514
723
  inputSchema: {
515
724
  type: 'object',
516
725
  properties: { workflow: { type: 'string' } },
@@ -524,7 +733,7 @@ function buildBaselineTools(deps) {
524
733
  },
525
734
  {
526
735
  name: 'heartbeat',
527
- 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).',
736
+ description: 'A held-run liveness and first-contact signal, distinct from Shift presence: touch an open run so it is not reaped mid-step (the design-doc "renew"). The first heartbeat on a freshly served claim closes the ~2-minute pickup window. Optionally tag who holds the claim (session or exec).',
528
737
  inputSchema: {
529
738
  type: 'object',
530
739
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
@@ -535,7 +744,7 @@ function buildBaselineTools(deps) {
535
744
  },
536
745
  {
537
746
  name: 'get_order',
538
- 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.',
747
+ description: 'For a holder rebinding to a persisted order already served to it, re-fetch that packet and its live lease state (claimed/claimedAt/heartbeatAt/outcome); this is not workflow discovery. Optionally tag who holds the claim.',
539
748
  inputSchema: {
540
749
  type: 'object',
541
750
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
@@ -546,7 +755,7 @@ function buildBaselineTools(deps) {
546
755
  },
547
756
  {
548
757
  name: 'release',
549
- 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.',
758
+ description: 'Give a held claim back so its order can be re-offered without waiting for 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.',
550
759
  inputSchema: {
551
760
  type: 'object',
552
761
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, session: { type: 'string' } },
@@ -567,7 +776,7 @@ function buildBaselineTools(deps) {
567
776
  },
568
777
  {
569
778
  name: 'publish_event',
570
- 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`.',
779
+ description: 'Delegate event-driven work through matching subscriptions: 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`.',
571
780
  inputSchema: {
572
781
  type: 'object',
573
782
  properties: {
@@ -582,13 +791,13 @@ function buildBaselineTools(deps) {
582
791
  },
583
792
  {
584
793
  name: 'list_subscriptions',
585
- description: "The org's contract subscriptions — what a publish will cascade into. Creating/revoking a subscription is admin-only and deliberately not exposed here.",
794
+ description: "Preview which playbooks a publish may start through the org's contract subscriptions. Creating or revoking a subscription is admin-only and deliberately not exposed here.",
586
795
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
587
796
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/subscriptions' })),
588
797
  },
589
798
  {
590
799
  name: 'presence_ping',
591
- 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.',
800
+ description: 'Report Shift availability only by registering or refreshing its presence: name, crews served, and optionally process incarnation. 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`, which is per claimed run and whose lapse reaps that claim. Every field overwrites, not keeps-previous: omitting serve_crews stores an empty set, meaning every crew this principal belongs to (the same reading whats_next gives an empty serve_crews), not no crews; omitting shift_id/started_at clears them.',
592
801
  inputSchema: {
593
802
  type: 'object',
594
803
  properties: {
@@ -597,8 +806,8 @@ function buildBaselineTools(deps) {
597
806
  serve_capabilities: {
598
807
  type: 'array',
599
808
  items: { type: 'string' },
600
- description: 'Capability keys this caller serves, raw (bare names and exact compounds). ' +
601
- 'Shifts compute this from their effective rosters; other callers normally omit it.',
809
+ description: 'Raw capability keys this caller serves (bare names and exact compounds). ' +
810
+ 'Shifts derive them from their effective rosters; other callers normally omit them.',
602
811
  },
603
812
  shift_id: { type: 'string' },
604
813
  started_at: { type: 'number' },
@@ -610,25 +819,25 @@ function buildBaselineTools(deps) {
610
819
  },
611
820
  {
612
821
  name: 'list_shifts',
613
- 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.",
822
+ description: "Show available or offline execution coverage for this principal so gaps can be relayed: registered Shifts with an online/offline flag (derived at read time from its last ping, ~3 min), last-seen age, crews served (returned as `crews`; an empty list means every crew this principal belongs to, not none), and recorded process incarnation (`shiftId`/`startedAt`).",
614
823
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
615
824
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/shifts' })),
616
825
  },
617
826
  {
618
827
  name: 'get_rosters',
619
- description: "The org's roster cascade: one org-global capability table plus optional per-crew tables. These rows select harness/model/effort after the hub has already routed work to a crew.",
828
+ description: "Inspect post-crew routing choices rather than execute work: the org's roster cascade has one org-global capability table plus optional per-crew tables, whose rows select harness/model/effort after the hub has already routed work to a crew.",
620
829
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
621
830
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/rosters' })),
622
831
  },
623
832
  {
624
833
  name: 'list_harness_models',
625
- description: "The hub's known harnesses and model snapshots, including each model's supported effort values. Read-only; roster writes stay in the terminal CLI.",
834
+ description: "Read-only roster-planning data: the hub's known harnesses and model snapshots, including each model's supported effort values. Roster writes stay in the terminal CLI.",
626
835
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
627
836
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/harness_models' })),
628
837
  },
629
838
  {
630
839
  name: 'wake',
631
- 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.',
840
+ description: 'The cheap place to park between changes: a polling pre-check returning only { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. It is not a substitute for whats_next — it never returns work orders, only whether to ask.',
632
841
  inputSchema: {
633
842
  type: 'object',
634
843
  properties: { cursor: { type: 'integer', minimum: 0 } },
@@ -655,7 +864,7 @@ const AGENT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
655
864
  function createAgentTool(deps) {
656
865
  return {
657
866
  name: 'create_agent',
658
- 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.',
867
+ description: 'Administrative setup that enables crews to execute runs, not the normal task path: 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.',
659
868
  inputSchema: {
660
869
  type: 'object',
661
870
  properties: {
@@ -720,7 +929,7 @@ function createAgentTool(deps) {
720
929
  function stageEnrollmentTool(deps) {
721
930
  return {
722
931
  name: 'stage_enrollment',
723
- 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.',
932
+ description: 'Administrative setup that enables crews to execute runs, not the normal task path: 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.',
724
933
  inputSchema: {
725
934
  type: 'object',
726
935
  properties: {
@@ -767,7 +976,7 @@ function buildCrewTools(deps) {
767
976
  return [
768
977
  {
769
978
  name: 'list_crews',
770
- description: "The org's crews, each with its membership rows inline (principalKind/principalId/addedBy/addedAt) — " +
979
+ description: "Inspect execution capacity and membership before a run or membership change: the org's crews, each with its membership rows inline (principalKind/principalId/addedBy/addedAt) — " +
771
980
  'one call, no per-crew fan-out. An org with no crews at all is a normal empty result, not an error. ' +
772
981
  "The org's reserved ORPHAN crew (kind: \"orphan\", or a name starting \"orphan:\") IS returned when it " +
773
982
  'exists and is deliberately NOT filtered out — it is where the hub re-homes work whose crew was ' +
@@ -779,7 +988,7 @@ function buildCrewTools(deps) {
779
988
  },
780
989
  {
781
990
  name: 'create_crew',
782
- description: "Create a crew on the hub org. `kind` is 'personal' or 'shared', forwarded verbatim — the hub is the " +
991
+ description: "Configure who can execute by creating a crew on the hub org. `kind` is 'personal' or 'shared', forwarded verbatim — the hub is the " +
783
992
  "enforcement of record for legal values ('orphan' is reserved for the hub's own crew and is refused). " +
784
993
  "`ownerMemberId` is required for a 'personal' crew and is simply omitted from the request when not " +
785
994
  'passed. NOT admin-only: an org admin may create any crew, AND a non-admin may create a personal crew ' +
@@ -801,7 +1010,7 @@ function buildCrewTools(deps) {
801
1010
  },
802
1011
  {
803
1012
  name: 'add_crew_member',
804
- description: "Add one principal to a crew. `principalKind` is 'member' (a human) or 'agent' (a Scoped Identity), " +
1013
+ description: "Configure who can execute by adding one principal to a crew. `principalKind` is 'member' (a human) or 'agent' (a Scoped Identity), " +
805
1014
  'forwarded verbatim; the hub validates it. NOT admin-only: an org admin may act on any crew, AND the ' +
806
1015
  'OWNER of a personal crew may add members to that crew without being an admin. HTTP 400 (not a ' +
807
1016
  'permissions error, and NOT tolerant): an unknown crewId, an unknown principalId, or a principal that ' +
@@ -823,7 +1032,7 @@ function buildCrewTools(deps) {
823
1032
  },
824
1033
  {
825
1034
  name: 'remove_crew_member',
826
- description: 'Remove one principal from a crew. TOLERANT: removing a principal that was never a member is a normal ' +
1035
+ description: 'Configure who can execute by removing one principal from a crew. TOLERANT: removing a principal that was never a member is a normal ' +
827
1036
  'success — HTTP 200 with removed:false, NOT a 404. Read the `removed` boolean rather than treating a ' +
828
1037
  'false as a failure. An unknown crewId is DIFFERENT and is an HTTP 400 error. NOT admin-only: same ' +
829
1038
  'self-service carve-out as add_crew_member — an org admin, or the owner of the personal crew being ' +
@@ -22,22 +22,25 @@
22
22
  * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
23
23
  *
24
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).
25
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo,
26
+ * instructions, and the agreed protocolVersion
27
+ * (echo the client's when recognized, else
28
+ * answer with ours).
28
29
  * - `notifications/initialized` → no-op (no response; it is a notification).
29
30
  * - `ping` → `{}`.
30
31
  * - `tools/list` → the registered tool defs.
31
- * - `tools/call` → dispatch to the tool handler; the result is
32
- * `{content:[{type:'text',text:<JSON>}], isError?}`.
32
+ * - `tools/call` → validate arguments against the registered
33
+ * input schema, then dispatch to the handler;
34
+ * the result is `{content:[{type:'text',text:<JSON>}], isError?}`.
33
35
  * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
34
36
  * aborted call sends NO response frame.
35
37
  * - outbound `notifications/progress` when a call carried
36
38
  * `params._meta.progressToken` (via `ctx.sendProgress`).
37
39
  *
38
40
  * 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
+ * invalid params (including a tool-schema mismatch) → -32602. A notification
42
+ * (no `id`) never gets a response, even on error. The process must never crash
43
+ * on a bad line.
41
44
  */
42
45
  export declare const PARSE_ERROR = -32700;
43
46
  export declare const INVALID_REQUEST = -32600;