owenloop 0.5.6 → 0.5.8

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 (82) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +3 -6
  3. package/dist/packages/work/src/agent/approvals.d.ts +53 -0
  4. package/dist/packages/work/src/agent/approvals.js +132 -0
  5. package/dist/packages/work/src/agent/brief.d.ts +12 -0
  6. package/dist/packages/work/src/agent/brief.js +51 -0
  7. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  8. package/dist/packages/work/src/agent/capability-model.js +94 -91
  9. package/dist/packages/work/src/agent/loop.d.ts +43 -25
  10. package/dist/packages/work/src/agent/loop.js +135 -50
  11. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  12. package/dist/packages/work/src/exec/loop.js +37 -15
  13. package/dist/packages/work/src/harness/child-env.js +4 -5
  14. package/dist/packages/work/src/harness/claude.d.ts +4 -0
  15. package/dist/packages/work/src/harness/claude.js +72 -3
  16. package/dist/packages/work/src/harness/codex.d.ts +37 -1
  17. package/dist/packages/work/src/harness/codex.js +136 -18
  18. package/dist/packages/work/src/harness/contract.d.ts +54 -1
  19. package/dist/packages/work/src/harness/session-store.d.ts +127 -17
  20. package/dist/packages/work/src/harness/session-store.js +157 -60
  21. package/dist/packages/work/src/hub/client.d.ts +13 -1
  22. package/dist/packages/work/src/hub/client.js +3 -0
  23. package/dist/packages/work/src/hub/types.d.ts +104 -3
  24. package/dist/packages/work/src/main.js +1 -0
  25. package/dist/packages/work/src/roles/agent-run.js +52 -42
  26. package/dist/packages/work/src/roles/approvals.d.ts +76 -0
  27. package/dist/packages/work/src/roles/approvals.js +231 -0
  28. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  29. package/dist/packages/work/src/roles/sessions.js +9 -2
  30. package/dist/packages/work/src/roles/settings.js +1 -1
  31. package/dist/packages/work/src/settings/roster.d.ts +21 -0
  32. package/dist/packages/work/src/settings/roster.js +80 -0
  33. package/dist/packages/work/src/settings/settings.d.ts +12 -24
  34. package/dist/packages/work/src/settings/settings.js +17 -35
  35. package/dist/packages/work/src/shift/loop.d.ts +2 -0
  36. package/dist/packages/work/src/shift/loop.js +2 -0
  37. package/dist/packages/work/src/shift/runtime.js +17 -9
  38. package/dist/packages/work/src/shift/spawn.d.ts +10 -53
  39. package/dist/packages/work/src/shift/spawn.js +28 -60
  40. package/dist/packages/work/src/usage.d.ts +1 -1
  41. package/dist/packages/work/src/usage.js +8 -4
  42. package/dist/src/capabilities.d.ts +44 -0
  43. package/dist/src/capabilities.js +38 -0
  44. package/dist/src/cli.d.ts +1 -0
  45. package/dist/src/cli.js +460 -5
  46. package/dist/src/config-dir.d.ts +13 -18
  47. package/dist/src/config-dir.js +15 -23
  48. package/dist/src/credentials.d.ts +1 -1
  49. package/dist/src/credentials.js +1 -1
  50. package/dist/src/crypto/records.d.ts +3 -0
  51. package/dist/src/crypto/records.js +19 -0
  52. package/dist/src/crypto/trust-roots.d.ts +2 -2
  53. package/dist/src/crypto/trust-roots.js +2 -2
  54. package/dist/src/engine.d.ts +14 -0
  55. package/dist/src/engine.js +26 -14
  56. package/dist/src/global-config.d.ts +4 -7
  57. package/dist/src/global-config.js +4 -7
  58. package/dist/src/hub.d.ts +207 -5
  59. package/dist/src/hub.js +263 -3
  60. package/dist/src/index.d.ts +2 -2
  61. package/dist/src/index.js +1 -1
  62. package/dist/src/model.d.ts +37 -1
  63. package/dist/src/model.js +47 -1
  64. package/dist/src/schemas/index.d.ts +19 -0
  65. package/dist/src/schemas/order.v1.schema.json +15 -1
  66. package/dist/src/store/pre-commit-verifier.js +1 -1
  67. package/dist/src/types.d.ts +58 -4
  68. package/dist/src/work-settings.d.ts +2 -4
  69. package/dist/src/work-settings.js +2 -4
  70. package/docs/agent-runner.md +2 -2
  71. package/docs/bundles.md +3 -1
  72. package/docs/cli.md +295 -101
  73. package/docs/crypto.md +14 -14
  74. package/docs/routing.md +607 -0
  75. package/docs/shift-logs.md +22 -6
  76. package/package.json +1 -1
  77. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/claude-code/plugin/.mcp.json +1 -1
  79. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  80. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  81. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  82. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
@@ -58,12 +58,13 @@
58
58
  */
59
59
  import { existsSync } from 'node:fs';
60
60
  import { isWorkdirAllowed } from "./workdir.js";
61
+ import { createApprovalRequester } from "./approvals.js";
61
62
  import { createLeaseLoop } from "../lease/loop.js";
62
63
  import { isResumeUnavailable } from "../harness/contract.js";
63
64
  import { preflightStepPermissions } from "../harness/permissions.js";
64
- import { orderId } from "../harness/session-store.js";
65
+ import { orderId, } from "../harness/session-store.js";
65
66
  import { buildOwenloopMcp, renderBrief, renderRejection, renderReplayBrief, } from "./brief.js";
66
- import { resolveCapabilityModel, } from "./capability-model.js";
67
+ import { resolveCapabilityCandidates, selectCandidate, } from "./capability-model.js";
67
68
  /** Default confirm-phase cadence: one `get_order` per second. */
68
69
  export const DEFAULT_CONFIRM_INTERVAL_MS = 1_000;
69
70
  /** Default confirm-phase bound: give the hub 15s to show the submit's outcome. */
@@ -101,8 +102,18 @@ function briefOwes(packet) {
101
102
  path: owed.path,
102
103
  judgmentRejects: owed.judgmentRejects,
103
104
  schemaRejects: owed.schemaRejects,
105
+ // Spread rather than assigned, so an absent schema stays absent instead
106
+ // of becoming an explicit `undefined`. The shape contract keys off
107
+ // `schema !== undefined`, and a hub that does not project the field must
108
+ // read as "nothing to say", never as "no constraint".
109
+ ...(owed.schema !== undefined
110
+ ? { schema: owed.schema, schemaAppliesTo: owed.schemaAppliesTo }
111
+ : {}),
104
112
  }));
105
113
  }
114
+ // The `outputs` fallback carries paths only — no counters and no schema. A
115
+ // hub old enough to project no `owes` is old enough to project no schema
116
+ // either, so there is nothing lost here that was ever available.
106
117
  return packet.outputs.map((path) => ({ path }));
107
118
  }
108
119
  /**
@@ -113,12 +124,48 @@ function briefOwes(packet) {
113
124
  * abstract rung with no meaning left, and reading it as a model id would put a
114
125
  * literal `strong` on the wire to a vendor.
115
126
  */
116
- export function resolveOrderRouting(packet, map) {
127
+ export function resolveOrderRouting(packet, rosters, stepHarness, isAvailable) {
117
128
  const capabilities = packet.capabilities ?? [];
118
129
  if (capabilities.length === 0)
119
130
  return { kind: 'unrouted' };
120
- const resolution = map === undefined ? undefined : resolveCapabilityModel(map, capabilities);
121
- return resolution === undefined ? { kind: 'refused', capabilities } : { kind: 'resolved', resolution };
131
+ let firstHarnessPolicy;
132
+ for (const roster of rosters ?? []) {
133
+ // Preserve arbitrary capability names through the boundary between the
134
+ // provenance-bearing merged roster and the candidate-only selector.
135
+ const candidateRows = Object.create(null);
136
+ for (const capability of Object.keys(roster)) {
137
+ if (!Object.prototype.hasOwnProperty.call(roster, capability))
138
+ continue;
139
+ candidateRows[capability] = roster[capability].candidates;
140
+ }
141
+ const candidates = resolveCapabilityCandidates(candidateRows, capabilities);
142
+ if (candidates === undefined)
143
+ continue;
144
+ const outcome = selectCandidate(candidates.candidates, stepHarness, isAvailable);
145
+ if (outcome.kind === 'selected') {
146
+ return {
147
+ kind: 'resolved',
148
+ capability: candidates.capability,
149
+ match: candidates.match,
150
+ harness: outcome.candidate.harness,
151
+ model: outcome.candidate.model,
152
+ effort: outcome.candidate.effort,
153
+ };
154
+ }
155
+ if (outcome.kind === 'harness-policy' && firstHarnessPolicy === undefined) {
156
+ firstHarnessPolicy = { offered: outcome.offered, stepHarness };
157
+ }
158
+ }
159
+ if (firstHarnessPolicy !== undefined) {
160
+ return {
161
+ kind: 'refused',
162
+ capabilities,
163
+ reason: 'harness-policy',
164
+ offered: firstHarnessPolicy.offered,
165
+ ...(firstHarnessPolicy.stepHarness !== undefined ? { stepHarness: firstHarnessPolicy.stepHarness } : {}),
166
+ };
167
+ }
168
+ return { kind: 'refused', capabilities, reason: 'unresolvable-capability' };
122
169
  }
123
170
  /**
124
171
  * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
@@ -173,6 +220,10 @@ export function createAgentRunLoop(opts) {
173
220
  let sessionRef;
174
221
  let adapterId = '';
175
222
  let stepName = '';
223
+ /** `OrderPacket.key`, set beside `stepName` when the packet arrives. Typed
224
+ * `undefined`-until-known rather than defaulted to `''`, because `''` is the
225
+ * REAL key of an unfanned step and must not double as "not known yet". */
226
+ let stepKey;
176
227
  let attempt = 1;
177
228
  let createdAt = 0;
178
229
  let recordCwd = opts.cwd;
@@ -218,9 +269,19 @@ export function createAgentRunLoop(opts) {
218
269
  workflow,
219
270
  run: runId,
220
271
  step: stepName,
272
+ // Written whenever the packet is known — which, given the guard above, is
273
+ // always. The conditional spread exists so the field is OMITTED rather
274
+ // than forged if that ever stops being true: an absent `key` means "cannot
275
+ // be attributed to a task" and costs a cold start, while a wrong `key`
276
+ // would hand a worker another task's session.
277
+ ...(stepKey !== undefined ? { key: stepKey } : {}),
221
278
  order,
222
279
  attempt,
223
280
  harness: sessionRef?.harness ?? adapterId,
281
+ pid: process.pid,
282
+ ...(opts.shiftName !== undefined && opts.shiftName !== '' ? { shiftName: opts.shiftName } : {}),
283
+ ...(opts.shiftOwner !== undefined && opts.shiftOwner !== '' ? { shiftOwner: opts.shiftOwner } : {}),
284
+ ...(opts.shiftId !== undefined && opts.shiftId !== '' ? { shiftId: opts.shiftId } : {}),
224
285
  token: sessionRef?.token ?? '',
225
286
  cwd: recordCwd,
226
287
  status,
@@ -322,21 +383,21 @@ export function createAgentRunLoop(opts) {
322
383
  * An `unrouted` order is not reported at all: the payload's `capability` is
323
384
  * required and non-empty on the hub side, and there is no capability to name.
324
385
  */
325
- async function reportResolution(routing, harness) {
386
+ async function reportResolution(routing) {
326
387
  if (routing.kind === 'unrouted')
327
388
  return;
328
389
  const payload = routing.kind === 'resolved'
329
390
  ? {
330
- capability: routing.resolution.capability,
331
- match: routing.resolution.match,
332
- model: routing.resolution.model,
333
- effort: routing.resolution.effort,
334
- harness,
391
+ capability: routing.capability,
392
+ match: routing.match,
393
+ model: routing.model,
394
+ effort: routing.effort,
395
+ harness: routing.harness,
335
396
  }
336
397
  : // The refusal names the capability the order was OFFERED under — the
337
398
  // first one — because that is the row an operator has to add. Model
338
399
  // and effort are absent: nothing was selected.
339
- { capability: routing.capabilities[0] ?? '', match: 'refused', harness };
400
+ { capability: routing.capabilities[0] ?? '', match: 'refused' };
340
401
  try {
341
402
  await opts.hub.reportResolution({ workflow, run: runId, resolution: payload });
342
403
  }
@@ -397,6 +458,7 @@ export function createAgentRunLoop(opts) {
397
458
  }
398
459
  }
399
460
  stepName = packet.step;
461
+ stepKey = packet.key;
400
462
  recordCwd = packet.workdir ?? opts.cwd;
401
463
  // MACHINE POLICY. The operator who started this shift named the directories
402
464
  // work may happen in (`owenloop shift start --work-root`, or
@@ -439,7 +501,26 @@ export function createAgentRunLoop(opts) {
439
501
  /** `material` is a `let`, so its null-narrowing does not survive into the
440
502
  * closures below. This const carries the narrowing across. */
441
503
  const step = material;
442
- const resolution = opts.resolveAdapter(step.harness);
504
+ // ---- ROUTING: select a roster candidate before resolving an adapter ----
505
+ //
506
+ // Phase 1's crew order is interim. Phase 2 replaces these locally supplied
507
+ // rosters with crew stamps the hub puts on each offer.
508
+ const routing = resolveOrderRouting(packet, opts.rosters, step.harness, opts.harnessAvailable);
509
+ await reportResolution(routing);
510
+ if (routing.kind === 'refused') {
511
+ if (routing.reason === 'harness-policy') {
512
+ opts.err(`owenloop work agent-run: step '${packet.step}' declares harness '${routing.stepHarness ?? ''}', ` +
513
+ `but its roster candidates offer [${(routing.offered ?? []).join(', ')}] — releasing`);
514
+ return releaseWith('incompatible-harness-policy', 'incompatible-harness-policy');
515
+ }
516
+ opts.err(`owenloop work agent-run: no crew roster row for ${order} — the order's capabilities ` +
517
+ `[${routing.capabilities.join(', ')}] match neither an exact row nor a bare name row in 'roster'. ` +
518
+ `Add a candidate array for one of them and restart the shift. Releasing — this shift will not pick ` +
519
+ `a model it was not told to use.`);
520
+ return releaseWith('unresolvable-capability', 'unresolvable-capability');
521
+ }
522
+ const chosenHarnessId = routing.kind === 'resolved' ? routing.harness : undefined;
523
+ const resolution = opts.resolveAdapter(chosenHarnessId, step.harness);
443
524
  adapterId = resolution.id;
444
525
  if (resolution.adapter === undefined) {
445
526
  const known = resolution.registered.length > 0 ? resolution.registered.join(', ') : '<none>';
@@ -450,27 +531,24 @@ export function createAgentRunLoop(opts) {
450
531
  /** The same object as `adapter`, but narrowed — the module-scope `adapter`
451
532
  * stays `HarnessAdapter | undefined` for `teardown`/`stop`. */
452
533
  const active = resolution.adapter;
453
- attempt = opts.nextAttempt(workflow, runId, packet.step);
534
+ /** This firing's engine task. Built once, from the packet, and used for both
535
+ * the attempt count and the Phase 4 resume lookup so the two can never
536
+ * disagree about which history they are reading. */
537
+ const task = { workflow, step: packet.step, key: packet.key };
538
+ attempt = opts.nextAttempt(task);
454
539
  const spec = {
455
540
  workflow,
456
541
  run: runId,
457
542
  origin: opts.origin,
458
543
  account: opts.account,
459
544
  ...(opts.shiftId !== undefined ? { shiftId: opts.shiftId } : {}),
460
- // Straight from the packet, not from settings: the modifier is the hub's
461
- // statement about the RUN, and a shift has no say in it.
462
545
  ...(packet.modifier !== undefined ? { modifier: packet.modifier } : {}),
463
546
  ...(packet.escalated === true ? { escalated: true } : {}),
464
547
  owes: briefOwes(packet),
465
548
  };
466
- // Permissions arrive PRE-NORMALIZED in the spec. `prepare` ran
467
- // `normalizeStepPermissions` over the step's `x.harness` options at cache
468
- // time, so this loop never looks inside an extension bag and never has a bag
469
- // key — vendor-keyed lookup does not exist in neutral code any more.
470
549
  const permissions = step.permissions;
471
550
  // Mandatory final-boundary preflight. Common checks run first, followed by
472
- // the selected adapter's exact capability check. A refusal starts neither a
473
- // cold session nor a resumed provider process; the held claim is released.
551
+ // the selected adapter's exact capability check.
474
552
  const policyIssues = [
475
553
  ...preflightStepPermissions(permissions),
476
554
  ...active.preflight(permissions),
@@ -482,35 +560,13 @@ export function createAgentRunLoop(opts) {
482
560
  }
483
561
  return releaseWith('incompatible-harness-policy', 'incompatible-harness-policy');
484
562
  }
485
- // ---- ROUTING: which model serves this order, and telling the hub --------
486
- //
487
- // DELIBERATELY THE LAST GATE BEFORE DISPATCH, and deliberately AFTER every
488
- // launch gate above (misroute, consumed verification, step spec, adapter,
489
- // harness policy). Plan §3: the launch gates block on a malformed order
490
- // before model selection is even attempted, so a refusal never has to be
491
- // explained in terms of a model the order was never going to reach.
492
- const routing = resolveOrderRouting(packet, opts.capabilityModels);
493
- // Plan §6: the record must exist BEFORE tokens are spent, which is why this
494
- // is a dedicated verb and not a field on the next heartbeat. It is reported
495
- // on the refusal path too — a refusal is a true observation of what this
496
- // shift resolved, and the whole point of the report is that the hub can say
497
- // why an order did or did not run.
498
- await reportResolution(routing, resolution.id);
499
- if (routing.kind === 'refused') {
500
- opts.err(`owenloop work agent-run: no settings row for ${order} — the order's capabilities ` +
501
- `[${routing.capabilities.join(', ')}] match neither an exact row nor a bare name row in ` +
502
- `'capabilityModels'. Add a row for one of them (a bare row such as ` +
503
- `'${routing.capabilities[0]?.split(':')[0] ?? ''}' covers every modifier) and restart the shift. ` +
504
- `Releasing — this shift will not pick a model it was not told to use.`);
505
- return releaseWith('unresolvable-capability', 'unresolvable-capability');
506
- }
507
563
  if (routing.kind === 'unrouted') {
508
- opts.err(`owenloop work agent-run: ${order} carries no capabilities, so no settings row applies — ` +
509
- `running on '${resolution.id}''s own default model.`);
564
+ opts.err(`owenloop work agent-run: ${order} carries no capabilities, so no crew roster row applies — ` +
565
+ `running on '${resolution.id}'s own default model.`);
510
566
  }
511
567
  else {
512
- opts.out(`owenloop work agent-run: ${order} resolved '${routing.resolution.capability}' ` +
513
- `(${routing.resolution.match} row) → ${routing.resolution.model} at ${routing.resolution.effort}`);
568
+ opts.out(`owenloop work agent-run: ${order} resolved '${routing.capability}' (${routing.match} row) → ` +
569
+ `${routing.harness}/${routing.model} at ${routing.effort}`);
514
570
  }
515
571
  // ---- PHASE 4: resume or cold replay? -----------------------------------
516
572
  //
@@ -518,7 +574,7 @@ export function createAgentRunLoop(opts) {
518
574
  // resume preconditions. `renderRejection` reads `packet.owes[].reasons`
519
575
  // filtered to `at > prev.deliveredReasonAt` — the packet's `owes` IS the set
520
576
  // of paths being re-armed, so no extra path filter is needed here.
521
- const prev = opts.latestSession?.(workflow, runId, packet.step) ?? null;
577
+ const prev = opts.latestSession?.(task) ?? null;
522
578
  const dirExists = opts.dirExists ?? existsSync;
523
579
  const delta = renderRejection({
524
580
  packet,
@@ -538,6 +594,14 @@ export function createAgentRunLoop(opts) {
538
594
  // dirExists(prev.cwd) a reaped work dir invalidates the session
539
595
  // delta.message !== '' nothing new to say — a resume that says
540
596
  // nothing spends a turn communicating nothing
597
+ //
598
+ // ON `prev.cwd === recordCwd` NOW THAT `prev` CAN ACTUALLY BE FOUND. An order
599
+ // carrying an explicit `packet.workdir` names the same directory on every
600
+ // firing, so this passes and the resume happens. An order with no `workdir`
601
+ // falls back to `<workRoot>/<workflow>/<run>` (see `agent/workdir.ts`), which
602
+ // moves with the run id — so this declines and the firing starts cold. That
603
+ // is the guard doing its job, not a leftover: the previous session's files
604
+ // genuinely are in a directory this firing is not working in.
541
605
  const resumable = prev !== null &&
542
606
  prev.token !== '' &&
543
607
  prev.harness === resolution.id &&
@@ -573,13 +637,33 @@ export function createAgentRunLoop(opts) {
573
637
  deliveredReasonAt = delta.deliveredReasonAt;
574
638
  }
575
639
  const owenloopMcp = buildOwenloopMcp(spec);
640
+ /**
641
+ * The human approval channel for this session's escalated tool calls.
642
+ *
643
+ * Built HERE, not by an adapter, because only the worker knows which run the
644
+ * session is serving — and the run is what the hub stamps the approval to.
645
+ * Waiting inside a `canUseTool` callback is safe precisely because
646
+ * `lease.run()` below is started and never awaited: its heartbeat timer is
647
+ * independent of the harness process, so a blocked tool call cannot let this
648
+ * claim be reaped out from under the question.
649
+ */
650
+ const approvals = createApprovalRequester({
651
+ client: opts.hub,
652
+ workflow: opts.workflow,
653
+ run: opts.run,
654
+ onEvent: (e) => opts.out(`owenloop work agent-run: approval ${e.kind} — ${e.text}`),
655
+ });
656
+ // A resolved crew-roster candidate wins over the step's authored harness,
657
+ // model, and effort. The harness was already selected above; these values
658
+ // keep the established rule for the adapter start arguments.
576
659
  const resolvedModel = routing.kind === 'resolved'
577
- ? { model: routing.resolution.model, effort: routing.resolution.effort }
660
+ ? { model: routing.model, effort: routing.effort }
578
661
  : undefined;
579
662
  const deliverArgs = {
580
663
  cwd: recordCwd,
581
664
  owenloopMcp,
582
665
  permissions,
666
+ approvals,
583
667
  ...(resolvedModel ?? {}),
584
668
  };
585
669
  /** Built lazily: a cold start after a refused resume needs a FRESH one. */
@@ -595,6 +679,7 @@ export function createAgentRunLoop(opts) {
595
679
  cwd: recordCwd,
596
680
  owenloopMcp,
597
681
  permissions,
682
+ approvals,
598
683
  ...(resolvedModel ?? {}),
599
684
  });
600
685
  const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
@@ -62,9 +62,9 @@ export interface FetchedStep {
62
62
  * LIFTED by `validateFetchedDef` from `x.harness.id`, or from a top-level
63
63
  * `harness` key when the def carries one (top-level WINS — forward compat for
64
64
  * an owenloop grammar that promotes the field). Declaration only: nothing
65
- * validates the id here; `src/roles/agent-run.ts` resolves it, ranking BELOW
66
- * `--harness` and `OWENLOOP_HARNESS`, and fails honestly when the id names no
67
- * registered adapter.
65
+ * validates the id here; `src/roles/agent-run.ts` uses it after a selected
66
+ * roster candidate and an explicit `--harness`, and fails honestly when the
67
+ * id names no registered adapter.
68
68
  */
69
69
  harness?: string;
70
70
  /**
@@ -302,8 +302,8 @@ export function createExecLoop(opts) {
302
302
  return 'continue';
303
303
  }
304
304
  /**
305
- * Relay the child's own output to this process's stderr when the command did
306
- * not succeed.
305
+ * Relay the child's own output unconditionally: to this process's stdout
306
+ * when the command succeeds, and stderr otherwise.
307
307
  *
308
308
  * ## Why this exists
309
309
  *
@@ -322,26 +322,48 @@ export function createExecLoop(opts) {
322
322
  * schema-rejected — with no trace of what the child said. Reproducing the
323
323
  * script by hand outside the engine was the only way to see its stderr.
324
324
  *
325
- * `outputTail` is already capped at 4 KiB by the runner, so this cannot flood
326
- * a log. Each line is prefixed so the child's words are never mistaken for
327
- * exec's own.
325
+ * The success half matters because a non-judge command step has no exit-code
326
+ * failure channel: a deferral is expressed as exit 0 and no payload.
327
+ * `merge-gate` does exactly that on its `cadence: 2m` re-offer. Before this
328
+ * relay, every deferral produced three identical log lines and no reason; the
329
+ * measured 40-minute case is recorded in `src/config-dir.ts:19-26`.
330
+ *
331
+ * Silence is printed rather than skipped because "this gate printed nothing"
332
+ * is itself the diagnosis, and an absent line is indistinguishable from the
333
+ * bug this relay fixes.
334
+ *
335
+ * `outputTail` is capped at 4 KiB by the runner (`runner.ts:40`), and a
336
+ * delivery run has roughly eleven command steps, so the worst case is about
337
+ * 44 KiB per run. That cap is why no volume knob exists: a knob would let a
338
+ * machine silently reintroduce this exact bug. Each line is prefixed so the
339
+ * child's words are never mistaken for exec's own.
328
340
  */
329
341
  function relayChildOutput(result, step) {
330
- if (result.exitCode === 0 && result.error === undefined)
331
- return;
332
- const how = result.error !== undefined
333
- ? `could not be run (${result.error})`
334
- : result.signal !== undefined
335
- ? `was killed by ${result.signal}`
336
- : `exited ${result.exitCode}`;
337
- opts.err(`owenloop work exec: the command for step '${step}' ${how}; its last output follows`);
342
+ const succeeded = result.exitCode === 0 && result.error === undefined;
343
+ // TWO CHANNELS ON PURPOSE, and this is not tidiness to be refactored away.
344
+ // `opts.err` is the channel a reader treats as trouble; routing a green
345
+ // step's routine output there would make every successful step look like a
346
+ // problem. A successful command's output is a RECORD, a failed one's is a
347
+ // DIAGNOSIS. Do not unify them.
348
+ const write = succeeded ? opts.out : opts.err;
349
+ if (succeeded) {
350
+ write(`owenloop work exec: the command for step '${step}' succeeded; its output follows`);
351
+ }
352
+ else {
353
+ const how = result.error !== undefined
354
+ ? `could not be run (${result.error})`
355
+ : result.signal !== undefined
356
+ ? `was killed by ${result.signal}`
357
+ : `exited ${result.exitCode}`;
358
+ write(`owenloop work exec: the command for step '${step}' ${how}; its last output follows`);
359
+ }
338
360
  const tail = result.outputTail.replace(/\n+$/, '');
339
361
  if (tail === '') {
340
- opts.err(' (the command produced no output)');
362
+ write(' (the command produced no output)');
341
363
  return;
342
364
  }
343
365
  for (const line of tail.split('\n'))
344
- opts.err(` | ${line}`);
366
+ write(` | ${line}`);
345
367
  }
346
368
  /** Build the receipt and submit it to every owed path. */
347
369
  async function submitReceipt(result, order, resolvedCommand) {
@@ -110,11 +110,10 @@ export const ADMITTED_OWENLOOP_KEYS = new Set([
110
110
  'OWENLOOP_SESSION',
111
111
  // `owenloopConfigDir` — src/config-dir.ts. Scopes owenloop's OWN config
112
112
  // directory (`settings.json`, `credentials.json`, `allowed_signers`) without
113
- // touching `XDG_CONFIG_HOME`, which the rest of the operator's toolchain also
114
- // reads. A path, not credential material — but the credential FILE backend
115
- // resolves under it (`readStoredCredential` → `configDir` → src/hub.ts), so a
116
- // mount that does not see this variable falls back to `XDG_CONFIG_HOME` and
117
- // reads a DIFFERENT credential store than the shift that spawned it.
113
+ // touching the rest of the operator's toolchain. A path, not credential
114
+ // material — but the credential file backend resolves under it
115
+ // (`readStoredCredential` → `configDir` → src/hub.ts), so a mount that does
116
+ // not see this variable reads a different credential store than its shift.
118
117
  'OWENLOOP_CONFIG_DIR',
119
118
  ]);
120
119
  /** The namespace this filter governs. Nothing outside it is ever touched. */
@@ -1,5 +1,6 @@
1
1
  import type { Options, Query, SDKMessage } from '@anthropic-ai/claude-agent-sdk';
2
2
  import type { GatePolicy } from './gatekeeper.ts';
3
+ import type { ApprovalRequester } from './contract.ts';
3
4
  import type { AgentEvent, HarnessAdapter, HarnessSessionRef, StartArgs, StepPermissions } from './contract.ts';
4
5
  /**
5
6
  * Build the environment the harness child runs under.
@@ -101,6 +102,9 @@ export interface ClaudeOptionInputs {
101
102
  /** Per-start override; wins over `permissions.effort`. */
102
103
  effort?: string;
103
104
  permissions: StepPermissions;
105
+ /** The human approval channel, when this deployment has one. Absent keeps the
106
+ * refuse-and-route-to-`ask` behavior — see `buildCanUseTool`. */
107
+ approvals?: ApprovalRequester;
104
108
  }
105
109
  /** The non-declarative bits a caller supplies per invocation. */
106
110
  export interface ClaudeOptionExtras {
@@ -298,6 +298,23 @@ function escalationMessage(reason) {
298
298
  'If it does not — if you genuinely cannot finish what you owe without this — call the `ask` tool on the mounted `owenloop` MCP server and state what you need and why. That reaches a person, and their answer comes back to you on your next attempt. Do not guess, and do not submit work that pretends this succeeded.',
299
299
  ].join(' ');
300
300
  }
301
+ /**
302
+ * What a call refused BY A PERSON, or by a wait that ran out, tells the agent.
303
+ *
304
+ * Kept distinct from `escalationMessage` because the two say different true
305
+ * things. That one says nobody was asked; this one says somebody was, and the
306
+ * answer was no. Telling an agent "nobody is watching" right after a person
307
+ * declined would be a lie that invites it to keep trying, so the routing advice
308
+ * is the same but the first sentence is not.
309
+ */
310
+ function decisionMessage(reason, note) {
311
+ return [
312
+ `Denied: ${reason}.`,
313
+ ...(note !== undefined && note !== '' ? [`They said: ${note}`] : []),
314
+ 'This was a decision, not a missing approver — repeating the call will reach the same answer.',
315
+ 'If the work has an equivalent inside your own working directory, do that instead. If it does not, call the `ask` tool on the mounted `owenloop` MCP server and state what you need and why. Do not guess, and do not submit work that pretends this succeeded.',
316
+ ].join(' ');
317
+ }
301
318
  /**
302
319
  * The `canUseTool` callback, wired on every start.
303
320
  *
@@ -309,9 +326,24 @@ function escalationMessage(reason) {
309
326
  * FAIL-CLOSED, deliberately. A throw inside this callback would leave the SDK
310
327
  * with no `control_response` and the tool blocked forever — permission prompts
311
328
  * have no park deadline. So the classification is wrapped: anything unexpected
312
- * becomes a denial with the same routing message rather than a hang.
329
+ * becomes a denial with the same routing message rather than a hang. The same
330
+ * rule governs the approval channel below: it is awaited inside a `try`, and a
331
+ * requester that throws denies rather than hangs.
332
+ *
333
+ * THE APPROVAL CHANNEL, when `approvals` is supplied. An escalated call is put
334
+ * to a PERSON and this callback waits for their answer, which is only safe
335
+ * because the same absence of a park deadline that makes a throw fatal makes a
336
+ * long wait harmless — and because the worker's lease heartbeat runs on its own
337
+ * timer, so a blocked callback does not let the claim be reaped. `options.
338
+ * toolUseID` is what makes the wait resumable and the question single: it is the
339
+ * harness's own id for this exact call, so a re-sent request is the same
340
+ * question rather than a second one.
341
+ *
342
+ * WITHOUT a requester — and for every outcome that is not an explicit approval —
343
+ * the behavior is exactly what it was before: deny, and name `ask` as the
344
+ * channel that does reach someone.
313
345
  */
314
- function buildCanUseTool(cwd, policy, onEvent) {
346
+ function buildCanUseTool(cwd, policy, onEvent, approvals) {
315
347
  return async (toolName, input, options) => {
316
348
  let verdict;
317
349
  try {
@@ -322,6 +354,43 @@ function buildCanUseTool(cwd, policy, onEvent) {
322
354
  }
323
355
  if (verdict.decision === 'allow')
324
356
  return { behavior: 'allow' };
357
+ if (approvals !== undefined) {
358
+ onEvent({
359
+ kind: 'progress',
360
+ text: `permission escalation: ${toolName} raised for approval — ${verdict.reason}`,
361
+ });
362
+ let outcome;
363
+ try {
364
+ outcome = await approvals({
365
+ toolUseId: options.toolUseID,
366
+ toolName,
367
+ toolInput: input,
368
+ reason: verdict.reason,
369
+ ...(options.title !== undefined ? { title: options.title } : {}),
370
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
371
+ });
372
+ }
373
+ catch (err) {
374
+ // The requester owns its own failure modes and is documented never to
375
+ // throw. If it does anyway, that is a bug in it, not a reason to leave
376
+ // the harness with no answer.
377
+ onEvent({
378
+ kind: 'progress',
379
+ text: `permission escalation: ${toolName} denied — the approval channel failed (${errText(err)})`,
380
+ });
381
+ return { behavior: 'deny', message: escalationMessage(verdict.reason) };
382
+ }
383
+ if (outcome.decision === 'approved') {
384
+ onEvent({
385
+ kind: 'progress',
386
+ text: `permission escalation: ${toolName} approved by a human`,
387
+ });
388
+ return { behavior: 'allow' };
389
+ }
390
+ const why = outcome.reason ?? verdict.reason;
391
+ onEvent({ kind: 'progress', text: `permission escalation: ${toolName} denied — ${why}` });
392
+ return { behavior: 'deny', message: decisionMessage(why, outcome.note) };
393
+ }
325
394
  // Recorded as well as returned: a denial the operator cannot see is how the
326
395
  // pre-callback behavior stayed invisible for as long as it did.
327
396
  onEvent({
@@ -507,7 +576,7 @@ export function buildClaudeOptions(inputs, extra) {
507
576
  // Set here, before the `permissionMode` block below, because it is not
508
577
  // conditional on that block running: a step naming no mode at all is exactly
509
578
  // the case that used to reach the SDK's `default` and be denied wholesale.
510
- canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), extra.onEvent),
579
+ canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), extra.onEvent, inputs.approvals),
511
580
  };
512
581
  // Omit the key entirely when nothing resolves — see `resolveExecutable`.
513
582
  const executable = resolveExecutable(extra.env);
@@ -1,4 +1,4 @@
1
- import type { AgentEvent, DeliverArgs, HarnessAdapter } from './contract.ts';
1
+ import type { AgentEvent, ApprovalRequester, DeliverArgs, HarnessAdapter } from './contract.ts';
2
2
  /** The adapter id. Matches the `"codex"` key in `harness-versions.json`, so the
3
3
  * worker can use one string for both the version pin and the adapter lookup. */
4
4
  export declare const HARNESS_ID = "codex";
@@ -108,4 +108,40 @@ export declare function mapNotification(method: string, params: unknown): AgentE
108
108
  * would deadlock the moment the notification is renamed.
109
109
  */
110
110
  export declare function readOwenloopMountFailure(method: string, params: unknown): string | undefined;
111
+ /**
112
+ * Answer every server→client request. An unanswered one hangs the turn past the
113
+ * worker's lease, which is the single worst outcome available in this file.
114
+ *
115
+ * TWO THINGS CAN BE GRANTED WITHOUT A PERSON, and only two.
116
+ *
117
+ * 1. A tool call on owenloop's own MCP mount — see the
118
+ * `mcpServer/elicitation/request` case.
119
+ * 2. Nothing else.
120
+ *
121
+ * WHAT CHANGED WHEN THE APPROVAL CHANNEL LANDED. The four requests in
122
+ * `BRIDGEABLE_APPROVALS` used to be refused with a throw, on the reasoning that
123
+ * "inventing an approval the policy said would never be asked for is a security
124
+ * decision this adapter is not authorized to make". That reasoning still holds
125
+ * exactly — and it is why `approvals` is the ONLY thing that changes it. With a
126
+ * requester wired in, this adapter is no longer inventing anything: it is
127
+ * relaying a question to a person and replying with THEIR answer. With no
128
+ * requester, the old refusal is what still happens, byte for byte.
129
+ *
130
+ * A REFUSAL IS NEVER A HANG. Every path here replies: an approval becomes
131
+ * `accept`/`approved`, and a denial, a deadline, an unreachable hub, or a
132
+ * requester that throws all become `decline`/`denied` plus a `progress` line
133
+ * naming the cause. On the legacy pair the person's reason travels back to the
134
+ * model inside `{denied:{rejection}}`; the v2 decision enum has no message
135
+ * field, so there the reason reaches the log and not the model.
136
+ *
137
+ * `item/permissions/requestApproval` is still refused unconditionally — see
138
+ * `BRIDGEABLE_APPROVALS` for why a permission profile is not a yes/no question.
139
+ *
140
+ * `item/tool/requestUserInput` and every non-owenloop elicitation emit
141
+ * `needs_input` and then throw: the Phase 1 contract deliberately has no reply
142
+ * channel, so replying `{answers:{}}` would be fabricating a user's answer. The
143
+ * error reply surfaces to the model as a failed tool call — the least-wrong
144
+ * behavior available (contract observation 3).
145
+ */
146
+ export declare function handleServerRequest(onEvent: (e: AgentEvent) => void, approvals?: ApprovalRequester): (method: string, params: unknown) => Promise<unknown>;
111
147
  export declare const codexAdapter: HarnessAdapter;