owenloop 0.5.6 → 0.5.7

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 (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/packages/work/src/agent/approvals.d.ts +53 -0
  3. package/dist/packages/work/src/agent/approvals.js +132 -0
  4. package/dist/packages/work/src/agent/brief.d.ts +12 -0
  5. package/dist/packages/work/src/agent/brief.js +51 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +4 -0
  7. package/dist/packages/work/src/agent/loop.js +33 -0
  8. package/dist/packages/work/src/harness/claude.d.ts +4 -0
  9. package/dist/packages/work/src/harness/claude.js +72 -3
  10. package/dist/packages/work/src/harness/codex.d.ts +37 -1
  11. package/dist/packages/work/src/harness/codex.js +133 -14
  12. package/dist/packages/work/src/harness/contract.d.ts +54 -1
  13. package/dist/packages/work/src/harness/session-store.d.ts +65 -15
  14. package/dist/packages/work/src/harness/session-store.js +53 -51
  15. package/dist/packages/work/src/hub/client.d.ts +13 -1
  16. package/dist/packages/work/src/hub/client.js +3 -0
  17. package/dist/packages/work/src/hub/types.d.ts +101 -0
  18. package/dist/packages/work/src/main.js +1 -0
  19. package/dist/packages/work/src/roles/agent-run.js +4 -0
  20. package/dist/packages/work/src/roles/approvals.d.ts +76 -0
  21. package/dist/packages/work/src/roles/approvals.js +231 -0
  22. package/dist/packages/work/src/shift/loop.d.ts +2 -0
  23. package/dist/packages/work/src/shift/loop.js +2 -0
  24. package/dist/packages/work/src/shift/runtime.js +23 -7
  25. package/dist/packages/work/src/shift/spawn.d.ts +4 -0
  26. package/dist/packages/work/src/shift/spawn.js +6 -0
  27. package/dist/packages/work/src/usage.d.ts +1 -1
  28. package/dist/packages/work/src/usage.js +5 -0
  29. package/dist/src/crypto/records.d.ts +2 -0
  30. package/dist/src/crypto/records.js +13 -0
  31. package/dist/src/engine.js +5 -1
  32. package/dist/src/model.d.ts +37 -1
  33. package/dist/src/model.js +47 -1
  34. package/dist/src/schemas/index.d.ts +11 -0
  35. package/dist/src/schemas/order.v1.schema.json +9 -0
  36. package/dist/src/types.d.ts +34 -0
  37. package/package.json +1 -1
  38. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  39. package/plugins/claude-code/plugin/.mcp.json +1 -1
  40. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  41. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,20 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.5.7](https://github.com/typicalday/owenloop/compare/v0.5.6...v0.5.7) (2026-08-16)
8
+
9
+
10
+ ### Features
11
+
12
+ * bridge an escalated tool call to a human approval and back ([#174](https://github.com/typicalday/owenloop/issues/174)) ([aa60594](https://github.com/typicalday/owenloop/commit/aa6059445dc95fcd3f0a810ecfbdada2f687aa9c))
13
+ * let a codex step's escalated call reach the same human approval gate ([#175](https://github.com/typicalday/owenloop/issues/175)) ([e43ca74](https://github.com/typicalday/owenloop/commit/e43ca74bf51485a499cf6f254c6a7a34fd4a1a5d))
14
+ * tell a step agent the shape it owes, before it produces one ([#172](https://github.com/typicalday/owenloop/issues/172)) ([54461b4](https://github.com/typicalday/owenloop/commit/54461b490f5617931cd1751db08885873ec9cbe7))
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * stop one shift from killing another shift's live agent sessions ([#176](https://github.com/typicalday/owenloop/issues/176)) ([82d9d82](https://github.com/typicalday/owenloop/commit/82d9d82f84121749c32e7a67b36b9506a51020b2))
20
+
7
21
  ## [0.5.6](https://github.com/typicalday/owenloop/compare/v0.5.5...v0.5.6) (2026-08-15)
8
22
 
9
23
 
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The worker half of the deterministic tool-approval gate: raise one escalated
3
+ * tool call to the hub, wait for a person, and hand the answer back to the
4
+ * BLOCKED CALL — not to a future attempt.
5
+ *
6
+ * WHY WAITING HERE IS SAFE, WHICH IS THE WHOLE PREMISE. Two independent facts
7
+ * have to hold at once, and both were verified before this was written:
8
+ *
9
+ * 1. The harness has no park deadline on a permission prompt. The host
10
+ * callback may take as long as it takes; what it must never do is fail to
11
+ * answer at all, because an unanswered prompt blocks that tool call
12
+ * forever with nothing recorded.
13
+ * 2. The lease keeps heartbeating while the agent is blocked. The worker's
14
+ * lease loop runs on its own timer, started but never awaited by the agent
15
+ * loop, so it is not suspended by a blocked callback. Without this, waiting
16
+ * would let the hub reap the very claim the approval is stamped to.
17
+ *
18
+ * WHAT THIS DELIBERATELY DOES NOT DO. It does not model the deadline hub-side.
19
+ * The hub has no view of how long a given worker is willing to wait, and a
20
+ * hub-side expiry racing this one would produce the single outcome that must not
21
+ * exist: an approval marked answered that no worker ever received. The deadline
22
+ * lives here, with the process that is actually waiting.
23
+ *
24
+ * EVERY NON-ANSWER IS A DENIAL. Deadline reached, hub unreachable, lease gone,
25
+ * caller aborted — all of them return `denied` with a reason. The adapter then
26
+ * does exactly what it did before this existed: refuse the call and route the
27
+ * agent to `ask`. That is the degradation path, and it is the pre-existing
28
+ * behavior rather than a new one, which is why adding this cannot make a
29
+ * deployment worse than it was.
30
+ */
31
+ import type { ApprovalRequester } from '../harness/contract.ts';
32
+ import type { HubClient } from '../hub/client.ts';
33
+ /** Emitted so a blocked worker is visible in the shift log rather than looking
34
+ * hung. The worker supplies its own event sink. */
35
+ export interface ApprovalEvent {
36
+ kind: 'raised' | 'waiting' | 'decided' | 'failed';
37
+ text: string;
38
+ }
39
+ export interface ApprovalRequesterOptions {
40
+ client: HubClient;
41
+ workflow: string;
42
+ run: string;
43
+ /** How long to wait for a person before denying. */
44
+ deadlineMs?: number;
45
+ /** How often to re-send the (idempotent) request while waiting. */
46
+ pollIntervalMs?: number;
47
+ onEvent?: (e: ApprovalEvent) => void;
48
+ /** Injected in tests. Defaults to an unref'd `setTimeout`. */
49
+ sleep?: (ms: number) => Promise<void>;
50
+ /** Injected in tests. Defaults to `Date.now`. */
51
+ now?: () => number;
52
+ }
53
+ export declare function createApprovalRequester(opts: ApprovalRequesterOptions): ApprovalRequester;
@@ -0,0 +1,132 @@
1
+ import { HubError } from "../hub/types.js";
2
+ /**
3
+ * Twenty minutes. Long enough that a person who is at their desk but not
4
+ * watching this specific run can still answer, short enough that a run left
5
+ * blocked overnight does not hold a worker slot until the shift is restarted.
6
+ * A denial at the deadline costs the run one honest `ask`, not a failure.
7
+ */
8
+ const DEFAULT_DEADLINE_MS = 20 * 60 * 1_000;
9
+ /**
10
+ * Five seconds. The poll is the same idempotent request as the raise, so its
11
+ * only cost is one small round trip; the reason not to go faster is that a
12
+ * person cannot answer faster than this anyway.
13
+ */
14
+ const DEFAULT_POLL_MS = 5_000;
15
+ /** A timer that cannot by itself keep the event loop alive — a blocked approval
16
+ * must never be the reason a worker process refuses to exit. */
17
+ function sleepUnref(ms) {
18
+ return new Promise((resolve) => {
19
+ const t = setTimeout(resolve, ms);
20
+ t.unref();
21
+ });
22
+ }
23
+ function errText(err) {
24
+ if (err instanceof HubError)
25
+ return `${err.status} ${err.message}`;
26
+ return err instanceof Error ? err.message : String(err);
27
+ }
28
+ /**
29
+ * A hub error while WAITING is not necessarily fatal — a hub restart, a network
30
+ * blip, or a 5xx are all things the next poll may well ride through, and denying
31
+ * on the first one would make the gate useless on any imperfect link. A 4xx is
32
+ * different: the request itself is wrong or refused (bad scope, unknown run),
33
+ * and repeating it cannot change that.
34
+ */
35
+ function isRetryable(err) {
36
+ if (!(err instanceof HubError))
37
+ return true;
38
+ return err.status >= 500 || err.status === 429;
39
+ }
40
+ export function createApprovalRequester(opts) {
41
+ const deadlineMs = opts.deadlineMs ?? DEFAULT_DEADLINE_MS;
42
+ const pollMs = opts.pollIntervalMs ?? DEFAULT_POLL_MS;
43
+ const sleep = opts.sleep ?? sleepUnref;
44
+ const now = opts.now ?? Date.now;
45
+ const emit = (e) => opts.onEvent?.(e);
46
+ return async function request(req) {
47
+ const started = now();
48
+ let raised = false;
49
+ let consecutiveErrors = 0;
50
+ for (;;) {
51
+ if (req.signal?.aborted === true) {
52
+ return { decision: 'denied', reason: 'the session ended before anyone answered' };
53
+ }
54
+ let res;
55
+ try {
56
+ // The SAME call every time. Raise and poll are one verb, keyed on
57
+ // `toolUseId`, so a retry after a network failure cannot open a second
58
+ // question and a poll cannot ask about one nobody raised.
59
+ res = await opts.client.requestApproval({
60
+ workflow: opts.workflow,
61
+ run: opts.run,
62
+ tool_use_id: req.toolUseId,
63
+ tool_name: req.toolName,
64
+ tool_input: req.toolInput,
65
+ reason: req.reason,
66
+ ...(req.title !== undefined ? { title: req.title } : {}),
67
+ });
68
+ consecutiveErrors = 0;
69
+ }
70
+ catch (err) {
71
+ if (!isRetryable(err)) {
72
+ emit({ kind: 'failed', text: `approval refused by the hub: ${errText(err)}` });
73
+ return { decision: 'denied', reason: `the hub refused the approval request (${errText(err)})` };
74
+ }
75
+ consecutiveErrors += 1;
76
+ if (now() - started >= deadlineMs) {
77
+ return {
78
+ decision: 'denied',
79
+ reason: `the hub was unreachable for the whole wait (${consecutiveErrors} attempts, last: ${errText(err)})`,
80
+ };
81
+ }
82
+ await sleep(pollMs);
83
+ continue;
84
+ }
85
+ // The claim ended underneath us. Nothing was written and there is nobody
86
+ // left for an answer to reach, so waiting longer cannot help.
87
+ if (res.ok === false || res.approval === undefined) {
88
+ const why = res.reason ?? 'the hub did not record the request';
89
+ emit({ kind: 'failed', text: `approval not open: ${why}` });
90
+ return { decision: 'denied', reason: `this run no longer holds its claim (${why})` };
91
+ }
92
+ const state = res.approval.state;
93
+ if (state === 'approved') {
94
+ emit({
95
+ kind: 'decided',
96
+ text: `approved by ${res.approval.decidedBy ?? 'a person'}: ${req.toolName}`,
97
+ });
98
+ return {
99
+ decision: 'approved',
100
+ ...(res.approval.note !== null ? { note: res.approval.note } : {}),
101
+ };
102
+ }
103
+ if (state === 'denied' || state === 'expired') {
104
+ emit({
105
+ kind: 'decided',
106
+ text: `${state} by ${res.approval.decidedBy ?? 'the hub'}: ${req.toolName}`,
107
+ });
108
+ return {
109
+ decision: 'denied',
110
+ reason: state === 'denied' ? 'a person denied this call' : 'the approval is no longer live',
111
+ ...(res.approval.note !== null ? { note: res.approval.note } : {}),
112
+ };
113
+ }
114
+ // Still pending.
115
+ if (!raised) {
116
+ raised = true;
117
+ emit({
118
+ kind: 'raised',
119
+ text: `waiting on a human decision: ${req.toolName} — ${req.reason}`,
120
+ });
121
+ }
122
+ if (now() - started >= deadlineMs) {
123
+ emit({ kind: 'waiting', text: `nobody answered within the wait window: ${req.toolName}` });
124
+ return {
125
+ decision: 'denied',
126
+ reason: `nobody answered within ${Math.round(deadlineMs / 60_000)} minutes`,
127
+ };
128
+ }
129
+ await sleep(pollMs);
130
+ }
131
+ };
132
+ }
@@ -99,6 +99,18 @@ export interface OwedBrief {
99
99
  /** Engine refusals of a malformed value against the path's declared JSON
100
100
  * Schema (`packet.owes[].schemaRejects`). */
101
101
  schemaRejects?: number;
102
+ /**
103
+ * The JSON Schema the engine will enforce on this path at commit time
104
+ * (`packet.owes[].schema`). Optional for the same reason the counters are: a
105
+ * hub that does not project it is not a hub reporting "no constraint", so the
106
+ * shape contract stays silent rather than telling an agent its output is
107
+ * unconstrained when it may not be.
108
+ */
109
+ schema?: unknown;
110
+ /** What `schema` governs (`packet.owes[].schemaAppliesTo`) — `'value'` for the
111
+ * submitted value itself, `'member'` for each member emitted into a
112
+ * collection. Read only when `schema` is present. */
113
+ schemaAppliesTo?: 'value' | 'member';
102
114
  }
103
115
  /**
104
116
  * Substitute the four dispatch tokens into a step template.
@@ -38,6 +38,7 @@ export function renderBrief(templateContent, spec) {
38
38
  renderRoutingLine(spec),
39
39
  renderInputContract(spec),
40
40
  renderSubmitContract(spec),
41
+ renderShapeContract(spec),
41
42
  renderAttemptHistory(spec),
42
43
  renderEscalationContract(spec),
43
44
  substituted,
@@ -192,6 +193,56 @@ function renderSubmitContract(spec) {
192
193
  'Printing that value as text, or inside a code fence, does NOT submit it — the turn ends, the hub records nothing, and this order is re-offered from scratch. Wherever this brief says "green <path> with <value>", it means exactly this tool call.',
193
194
  ].join('\n');
194
195
  }
196
+ /**
197
+ * The SHAPE each owed value must have, stated before the agent produces one.
198
+ *
199
+ * WHY THIS EXISTS. The attempt history already tells a re-offered agent that its
200
+ * last submission failed its schema, and how many refusals remain before the
201
+ * step freezes. It never tells it the schema. So the agent on attempt two knows
202
+ * only that something about the shape was wrong, holds exactly the information
203
+ * it held on attempt one, and the most available move is to resubmit a near
204
+ * variant — which is how a step burns its whole `maxSchemaFailures` budget on
205
+ * one misunderstanding. The counter and the reasons are the symptom channel;
206
+ * this is the requirement channel, and only one of them was wired.
207
+ *
208
+ * A schema refusal is also the CHEAPEST failure to prevent and the most
209
+ * pointless to suffer: the engine rejects the value structurally, so no
210
+ * consumer and no judge ever sees it, no reviewer time is spent, and the agent
211
+ * learns nothing it could not have been told for free at dispatch.
212
+ *
213
+ * WHEN IT RENDERS. Only for owed paths whose produce actually declares a
214
+ * schema. Most do not, and for those the engine accepts any JSON — so silence
215
+ * here is correct, and a blanket "no schema declared" line would be worse than
216
+ * nothing: a hub too old to project the field looks identical to a produce with
217
+ * no schema, and only one of those two justifies telling an agent its output is
218
+ * unconstrained. Neither gets that claim.
219
+ *
220
+ * WHY IT PRINTS THE SCHEMA WHOLE. A truncated JSON Schema is not a smaller
221
+ * requirement, it is a different and wrong one — an agent that reads a clipped
222
+ * `required` array will confidently omit a field. If a schema is large, large
223
+ * is what the contract is.
224
+ *
225
+ * WHY `member` IS SPELLED OUT. A collection's owed path is its seal, but the
226
+ * declared schema is checked against each member emitted into it, never against
227
+ * the seal value. Printing the schema under the seal path without that sentence
228
+ * would tell the agent to shape the wrong thing.
229
+ */
230
+ function renderShapeContract(spec) {
231
+ const constrained = (spec.owes ?? []).filter((o) => o.path !== '' && o.schema !== undefined);
232
+ if (constrained.length === 0)
233
+ return '';
234
+ const blocks = constrained.map((o) => {
235
+ const governs = o.schemaAppliesTo === 'member'
236
+ ? `Each member you emit into \`${o.path}\` must satisfy this JSON Schema — it is checked per member, NOT against the sealed collection itself.`
237
+ : `The value you submit to \`${o.path}\` must satisfy this JSON Schema.`;
238
+ return `${governs}\n\`\`\`json\n${JSON.stringify(o.schema, null, 2)}\n\`\`\``;
239
+ });
240
+ return [
241
+ 'The shape of what you owe:',
242
+ ...blocks,
243
+ 'The engine checks these at submit time, before any consumer or judge sees the value. A value that does not match is refused structurally — it is not reviewed, not partially accepted, and the refusal spends one of this order\'s limited schema attempts. Match the schema exactly rather than submitting something close and waiting to be told.',
244
+ ].join('\n');
245
+ }
195
246
  /**
196
247
  * What an agent does when it CANNOT complete the order, stated to every agent on
197
248
  * every run, right after the submit contract.
@@ -50,6 +50,10 @@ export interface AgentRunLoopOptions {
50
50
  account: string;
51
51
  /** Advisory Shift attribution — rides `--shift=<cid>` (may be absent). */
52
52
  shiftId?: string;
53
+ /** Stable Shift ownership name — persisted on every session row when present. */
54
+ shiftName?: string;
55
+ /** Stable Shift owner key — survives generated per-boot public names. */
56
+ shiftOwner?: string;
53
57
  /** cwd for the step agent when the order packet carries no `workdir`. */
54
58
  cwd: string;
55
59
  /**
@@ -58,6 +58,7 @@
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";
@@ -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
  /**
@@ -221,6 +232,10 @@ export function createAgentRunLoop(opts) {
221
232
  order,
222
233
  attempt,
223
234
  harness: sessionRef?.harness ?? adapterId,
235
+ pid: process.pid,
236
+ ...(opts.shiftName !== undefined && opts.shiftName !== '' ? { shiftName: opts.shiftName } : {}),
237
+ ...(opts.shiftOwner !== undefined && opts.shiftOwner !== '' ? { shiftOwner: opts.shiftOwner } : {}),
238
+ ...(opts.shiftId !== undefined && opts.shiftId !== '' ? { shiftId: opts.shiftId } : {}),
224
239
  token: sessionRef?.token ?? '',
225
240
  cwd: recordCwd,
226
241
  status,
@@ -573,6 +588,22 @@ export function createAgentRunLoop(opts) {
573
588
  deliveredReasonAt = delta.deliveredReasonAt;
574
589
  }
575
590
  const owenloopMcp = buildOwenloopMcp(spec);
591
+ /**
592
+ * The human approval channel for this session's escalated tool calls.
593
+ *
594
+ * Built HERE, not by an adapter, because only the worker knows which run the
595
+ * session is serving — and the run is what the hub stamps the approval to.
596
+ * Waiting inside a `canUseTool` callback is safe precisely because
597
+ * `lease.run()` below is started and never awaited: its heartbeat timer is
598
+ * independent of the harness process, so a blocked tool call cannot let this
599
+ * claim be reaped out from under the question.
600
+ */
601
+ const approvals = createApprovalRequester({
602
+ client: opts.hub,
603
+ workflow: opts.workflow,
604
+ run: opts.run,
605
+ onEvent: (e) => opts.out(`owenloop work agent-run: approval ${e.kind} — ${e.text}`),
606
+ });
576
607
  const resolvedModel = routing.kind === 'resolved'
577
608
  ? { model: routing.resolution.model, effort: routing.resolution.effort }
578
609
  : undefined;
@@ -580,6 +611,7 @@ export function createAgentRunLoop(opts) {
580
611
  cwd: recordCwd,
581
612
  owenloopMcp,
582
613
  permissions,
614
+ approvals,
583
615
  ...(resolvedModel ?? {}),
584
616
  };
585
617
  /** Built lazily: a cold start after a refused resume needs a FRESH one. */
@@ -595,6 +627,7 @@ export function createAgentRunLoop(opts) {
595
627
  cwd: recordCwd,
596
628
  owenloopMcp,
597
629
  permissions,
630
+ approvals,
598
631
  ...(resolvedModel ?? {}),
599
632
  });
600
633
  const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
@@ -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;