owenloop 0.5.5 → 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 (45) hide show
  1. package/CHANGELOG.md +22 -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 +40 -4
  5. package/dist/packages/work/src/agent/brief.js +165 -2
  6. package/dist/packages/work/src/agent/loop.d.ts +4 -0
  7. package/dist/packages/work/src/agent/loop.js +68 -3
  8. package/dist/packages/work/src/harness/claude.d.ts +28 -0
  9. package/dist/packages/work/src/harness/claude.js +193 -22
  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 +79 -21
  13. package/dist/packages/work/src/harness/contract.js +25 -20
  14. package/dist/packages/work/src/harness/gatekeeper.d.ts +124 -0
  15. package/dist/packages/work/src/harness/gatekeeper.js +208 -0
  16. package/dist/packages/work/src/harness/session-store.d.ts +65 -15
  17. package/dist/packages/work/src/harness/session-store.js +53 -51
  18. package/dist/packages/work/src/hub/client.d.ts +13 -1
  19. package/dist/packages/work/src/hub/client.js +3 -0
  20. package/dist/packages/work/src/hub/types.d.ts +101 -0
  21. package/dist/packages/work/src/main.js +1 -0
  22. package/dist/packages/work/src/roles/agent-run.js +4 -0
  23. package/dist/packages/work/src/roles/approvals.d.ts +76 -0
  24. package/dist/packages/work/src/roles/approvals.js +231 -0
  25. package/dist/packages/work/src/shift/loop.d.ts +2 -0
  26. package/dist/packages/work/src/shift/loop.js +2 -0
  27. package/dist/packages/work/src/shift/runtime.js +23 -7
  28. package/dist/packages/work/src/shift/spawn.d.ts +4 -0
  29. package/dist/packages/work/src/shift/spawn.js +6 -0
  30. package/dist/packages/work/src/usage.d.ts +1 -1
  31. package/dist/packages/work/src/usage.js +5 -0
  32. package/dist/src/crypto/records.d.ts +2 -0
  33. package/dist/src/crypto/records.js +13 -0
  34. package/dist/src/engine.js +5 -1
  35. package/dist/src/model.d.ts +37 -1
  36. package/dist/src/model.js +47 -1
  37. package/dist/src/schemas/index.d.ts +11 -0
  38. package/dist/src/schemas/order.v1.schema.json +9 -0
  39. package/dist/src/types.d.ts +34 -0
  40. package/docs/agent-runner.md +17 -5
  41. package/package.json +1 -1
  42. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  43. package/plugins/claude-code/plugin/.mcp.json +1 -1
  44. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  45. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -26,6 +26,7 @@
26
26
  import { randomUUID } from 'node:crypto';
27
27
  import { accessSync, constants, existsSync } from 'node:fs';
28
28
  import { delimiter, join } from 'node:path';
29
+ import { classifyToolCall } from "./gatekeeper.js";
29
30
  import { register } from "./registry.js";
30
31
  import { filterOwenloopEnv } from "./child-env.js";
31
32
  import { normalizeStepPermissions, validateHarnessOptions } from "./permissions.js";
@@ -185,25 +186,33 @@ const PERMISSION_MODES = [
185
186
  * - `ask` → `default`. The SDK's `default` routes each unapproved tool to the
186
187
  * `canUseTool` callback — a human decision point — and denies when no callback
187
188
  * is wired. That is the "human is the gate" position.
188
- * - `auto-safe` → `auto`. `auto` is the SDK's model-classifier mode: it decides
189
- * per call, with no prompt. NOT `acceptEdits`, which auto-approves filesystem
190
- * operations by category and applies no judgment to anything else, and NOT
191
- * `dontAsk`, which DENIES an unapproved tool rather than consulting anyone —
192
- * silently narrower than what the step asked for.
193
- *
194
- * MEASURED against SDK 0.3.220, `canUseTool` wired throughout: the classifier
195
- * consulted the host on NONE of five probe commands, and emitted no
196
- * `permission_denied` system message for any of them. Four ran, including
197
- * `rm -rf` on an ABSOLUTE path outside the session cwd (verified by the
198
- * target directory being gone afterwards), a `curl` to the public internet,
199
- * and a read of a file under `$HOME` outside cwd.
200
- *
201
- * So `auto` does not, in practice, escalate to whoever hosts the session.
202
- * Wiring `canUseTool` does not give `auto-safe` a human exception path — the
203
- * callback is simply never reached. Anything that needs a person in the loop
204
- * has to run under `ask`, whose `default` mode does route to the callback
205
- * (measured on the same SDK build, including calls originating inside a
206
- * subagent, which arrive carrying that subagent's `agentID`).
189
+ * - `auto-safe` → `default`, with this adapter's own gatekeeper in the
190
+ * `canUseTool` callback. NOT the SDK's `auto`, and that is the substance of
191
+ * this mapping rather than a detail of it.
192
+ *
193
+ * MEASURED against SDK 0.3.220, `canUseTool` wired throughout: `auto`'s
194
+ * model-side classifier consulted the host on NONE of five probe commands and
195
+ * emitted no `permission_denied` system message for any of them. Four ran,
196
+ * including `rm -rf` on an ABSOLUTE path outside the session cwd (verified by
197
+ * the target directory being gone afterwards), a `curl` to the public
198
+ * internet, and a read of a file under `$HOME` outside cwd.
199
+ *
200
+ * So `auto` never reaches the callback and cannot escalate to anyone. The
201
+ * position `auto-safe` names — a classifier gates, a human is the exception
202
+ * path — is therefore not something `auto` can be configured into; it has to
203
+ * be built on the one mode that does route to the callback. `default` is that
204
+ * mode (measured on the same SDK build, including calls originating inside a
205
+ * subagent, which arrive carrying that subagent's `agentID`), so `auto-safe`
206
+ * and `ask` now share it and differ by the `GatePolicy` handed to the
207
+ * gatekeeper. The trade is deliberate: `auto` classifies with a model and this
208
+ * adapter classifies with path containment plus a short deny-list, which is
209
+ * the blunter instrument — but it is the only one of the two that can put a
210
+ * person in the loop, which is the whole of what the position promises.
211
+ *
212
+ * NOT `acceptEdits`, which auto-approves filesystem operations by category and
213
+ * applies no judgment to anything else, and NOT `dontAsk`, which DENIES an
214
+ * unapproved tool rather than consulting anyone — silently narrower than what
215
+ * the step asked for.
207
216
  * - `full-access` → `bypassPermissions`. The only SDK mode that runs tools with
208
217
  * no prompt at all, and the one the companion flag below exists for.
209
218
  *
@@ -212,7 +221,7 @@ const PERMISSION_MODES = [
212
221
  */
213
222
  const NEUTRAL_TO_SDK_MODE = Object.freeze({
214
223
  'ask': 'default',
215
- 'auto-safe': 'auto',
224
+ 'auto-safe': 'default',
216
225
  'full-access': 'bypassPermissions',
217
226
  });
218
227
  /** Values `preflight` accepts: the SDK's own union plus the neutral vocabulary. */
@@ -235,6 +244,162 @@ function toSdkPermissionMode(mode) {
235
244
  }
236
245
  return PERMISSION_MODES.includes(mode) ? mode : undefined;
237
246
  }
247
+ /**
248
+ * How hard the gatekeeper gates, from the mode the step ACTUALLY AUTHORED.
249
+ *
250
+ * Derived from the authored string rather than from the translated SDK mode
251
+ * because the translation is deliberately lossy in exactly the place that
252
+ * matters: `ask` and `auto-safe` both become `default`, and the whole difference
253
+ * between them now lives here.
254
+ *
255
+ * WHY AN UNSET MODE CLASSIFIES RATHER THAN DENYING. A step that names no
256
+ * `permissionMode` gets the SDK's own `default`, which routes to the callback.
257
+ * Before a callback existed that meant the SDK denied every unapproved call —
258
+ * silently, finally, with nobody prompted and nothing recorded. Treating the
259
+ * unset case as `classifier` is not a widening of what those steps were promised;
260
+ * it is the first time they get anything at all. The same reasoning covers a
261
+ * step that named the vendor's `default` or `acceptEdits`.
262
+ *
263
+ * `dontAsk` is the one value that keeps its narrow meaning: it is documented as
264
+ * "deny if not pre-approved", so it maps to the policy that denies rather than
265
+ * being folded into the classifier. The SDK short-circuits that mode before the
266
+ * callback, so this is a statement of intent more than a live path — but a
267
+ * future SDK that does route it must not find it silently widened here.
268
+ */
269
+ export function gatePolicyFor(authoredMode) {
270
+ if (authoredMode === 'ask')
271
+ return 'human-gate';
272
+ if (authoredMode === 'dontAsk')
273
+ return 'deny-unapproved';
274
+ return 'classifier';
275
+ }
276
+ /**
277
+ * What an escalated call tells the agent.
278
+ *
279
+ * This is the whole of the "human exception path" today, and it is a ROUTE
280
+ * rather than an answer: no person is watching a headless run at the moment the
281
+ * call is made, so the honest thing is to refuse the call and name the channel
282
+ * that does reach one. `ask` is that channel — it freezes the owed artifact,
283
+ * closes the run cheaply instead of burning attempts against a wall, and puts a
284
+ * question on the operator's attention feed with an answer path back into the
285
+ * next attempt.
286
+ *
287
+ * The message names the specific reason and tells the agent both of its real
288
+ * options, because the wrong outcome here is an agent that reads a denial as
289
+ * "try a different phrasing" and grinds through its attempt budget. Most
290
+ * escalations have an ordinary alternative — the same work done inside the
291
+ * step's own directory — and the message says so before it points at `ask`.
292
+ */
293
+ function escalationMessage(reason) {
294
+ return [
295
+ `Denied: ${reason}.`,
296
+ 'Nobody is watching this run to approve it, so this call cannot be granted here and rephrasing it will not change that.',
297
+ 'If the work has an equivalent inside your own working directory, do that instead.',
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
+ ].join(' ');
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
+ }
318
+ /**
319
+ * The `canUseTool` callback, wired on every start.
320
+ *
321
+ * WIRED UNCONDITIONALLY, including under `bypassPermissions`, where the SDK
322
+ * never consults it. A callback that is present but unreached costs nothing; a
323
+ * callback wired only under the modes we predict will reach it is one SDK change
324
+ * away from restoring the silent deny-everything behavior this exists to end.
325
+ *
326
+ * FAIL-CLOSED, deliberately. A throw inside this callback would leave the SDK
327
+ * with no `control_response` and the tool blocked forever — permission prompts
328
+ * have no park deadline. So the classification is wrapped: anything unexpected
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.
345
+ */
346
+ function buildCanUseTool(cwd, policy, onEvent, approvals) {
347
+ return async (toolName, input, options) => {
348
+ let verdict;
349
+ try {
350
+ verdict = classifyToolCall({ toolName, input, workdir: cwd, blockedPath: options.blockedPath }, policy);
351
+ }
352
+ catch (err) {
353
+ verdict = { decision: 'escalate', reason: `the gatekeeper could not judge this call (${errText(err)})` };
354
+ }
355
+ if (verdict.decision === 'allow')
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
+ }
394
+ // Recorded as well as returned: a denial the operator cannot see is how the
395
+ // pre-callback behavior stayed invisible for as long as it did.
396
+ onEvent({
397
+ kind: 'progress',
398
+ text: `permission escalation: ${toolName} denied — ${verdict.reason}`,
399
+ });
400
+ return { behavior: 'deny', message: escalationMessage(verdict.reason) };
401
+ };
402
+ }
238
403
  /** The five-value closed union the SDK types `Options.effort` as. */
239
404
  const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
240
405
  /** Audited built-ins that cannot mutate the filesystem. WebFetch/WebSearch
@@ -408,6 +573,10 @@ export function buildClaudeOptions(inputs, extra) {
408
573
  stderr: (data) => {
409
574
  extra.onEvent({ kind: 'progress', text: `stderr: ${data.trimEnd()}` });
410
575
  },
576
+ // Set here, before the `permissionMode` block below, because it is not
577
+ // conditional on that block running: a step naming no mode at all is exactly
578
+ // the case that used to reach the SDK's `default` and be denied wholesale.
579
+ canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), extra.onEvent, inputs.approvals),
411
580
  };
412
581
  // Omit the key entirely when nothing resolves — see `resolveExecutable`.
413
582
  const executable = resolveExecutable(extra.env);
@@ -436,8 +605,10 @@ export function buildClaudeOptions(inputs, extra) {
436
605
  if (permissions.permissionMode !== undefined) {
437
606
  // Neutral `full-access` lands here as `bypassPermissions`, so the companion
438
607
  // flag below covers it too — that is the point of translating BEFORE the
439
- // pairing rather than after it. Neutral `auto-safe` lands as `auto` and
440
- // deliberately does NOT get the flag: it is still allowed to stop and ask.
608
+ // pairing rather than after it. Neutral `ask` and `auto-safe` both land as
609
+ // `default` and deliberately do NOT get the flag: `default` is the mode that
610
+ // routes to `canUseTool`, which is where the difference between those two
611
+ // positions is actually drawn (see `gatePolicyFor`).
441
612
  const mode = toSdkPermissionMode(permissions.permissionMode);
442
613
  if (mode !== undefined) {
443
614
  options.permissionMode = mode;
@@ -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;
@@ -670,17 +670,94 @@ function createTurnGate(onEvent) {
670
670
  },
671
671
  };
672
672
  }
673
+ const BRIDGEABLE_APPROVALS = Object.freeze({
674
+ 'item/commandExecution/requestApproval': { kind: 'exec', toolName: 'command', legacy: false },
675
+ 'item/fileChange/requestApproval': { kind: 'file', toolName: 'file-change', legacy: false },
676
+ 'execCommandApproval': { kind: 'exec', toolName: 'command', legacy: true },
677
+ 'applyPatchApproval': { kind: 'patch', toolName: 'file-change', legacy: true },
678
+ });
679
+ /** Join a legacy `command: string[]` (or pass a v2 `command: string`) for display. */
680
+ function commandText(value) {
681
+ if (Array.isArray(value)) {
682
+ const parts = value.filter((p) => typeof p === 'string');
683
+ return parts.length > 0 ? parts.join(' ') : undefined;
684
+ }
685
+ return str(value);
686
+ }
687
+ /**
688
+ * Turn one approval request into the question a person will actually read.
689
+ *
690
+ * The identity (`toolUseId`) has to be stable for the life of the call and
691
+ * unique among live calls, because the hub keys the approval on it. `itemId` /
692
+ * `callId` is that identity; `approvalId` is appended when present, since one
693
+ * item can raise several callbacks (the zsh-exec-bridge case) and collapsing
694
+ * them would let one answer decide two commands.
695
+ *
696
+ * `toolInput` is trimmed rather than forwarded whole. The raw params carry full
697
+ * file diffs and policy-amendment proposals, and a hub row nobody can read is
698
+ * not evidence — the command and the paths are what the decision turns on.
699
+ */
700
+ function describeApproval(shape, params) {
701
+ const p = asMap(params);
702
+ const base = str(p['itemId']) ?? str(p['callId']) ?? 'unknown';
703
+ const callback = str(p['approvalId']);
704
+ const toolUseId = `${shape.kind}:${base}${callback !== undefined ? `:${callback}` : ''}`;
705
+ const command = commandText(p['command']);
706
+ const cwd = str(p['cwd']);
707
+ const files = Object.keys(asMap(p['fileChanges']));
708
+ const grantRoot = str(p['grantRoot']);
709
+ const detail = command !== undefined
710
+ ? command
711
+ : files.length > 0
712
+ ? `writes ${files.join(', ')}`
713
+ : grantRoot !== undefined
714
+ ? `writes under ${grantRoot}`
715
+ : 'a change this harness would not make on its own';
716
+ return {
717
+ toolUseId,
718
+ toolName: shape.toolName,
719
+ toolInput: {
720
+ ...(command !== undefined ? { command } : {}),
721
+ ...(cwd !== undefined ? { cwd } : {}),
722
+ ...(files.length > 0 ? { files } : {}),
723
+ ...(grantRoot !== undefined ? { grantRoot } : {}),
724
+ },
725
+ // The harness's own words when it supplied them. When it did not, say WHY
726
+ // this arrived rather than inventing a hazard nobody assessed: the step's
727
+ // approval policy is what escalated it.
728
+ reason: str(p['reason']) ??
729
+ "the step's approval policy escalated this call instead of running it unattended",
730
+ title: cap(detail),
731
+ };
732
+ }
673
733
  /**
674
734
  * Answer every server→client request. An unanswered one hangs the turn past the
675
735
  * worker's lease, which is the single worst outcome available in this file.
676
736
  *
677
- * Exactly ONE thing is auto-approved — a tool call on owenloop's own MCP mount,
678
- * see the `mcpServer/elicitation/request` case. Everything else is refused:
679
- * under `approvalPolicy:'never'` a command/file approval request should not
680
- * arrive at all; if one does, throwing (which the client turns into a JSON-RPC
681
- * error reply) is a loud, non-hanging failure, whereas inventing an approval the
682
- * policy said would never be asked for is a security decision this adapter is
683
- * not authorized to make.
737
+ * TWO THINGS CAN BE GRANTED WITHOUT A PERSON, and only two.
738
+ *
739
+ * 1. A tool call on owenloop's own MCP mount — see the
740
+ * `mcpServer/elicitation/request` case.
741
+ * 2. Nothing else.
742
+ *
743
+ * WHAT CHANGED WHEN THE APPROVAL CHANNEL LANDED. The four requests in
744
+ * `BRIDGEABLE_APPROVALS` used to be refused with a throw, on the reasoning that
745
+ * "inventing an approval the policy said would never be asked for is a security
746
+ * decision this adapter is not authorized to make". That reasoning still holds
747
+ * exactly — and it is why `approvals` is the ONLY thing that changes it. With a
748
+ * requester wired in, this adapter is no longer inventing anything: it is
749
+ * relaying a question to a person and replying with THEIR answer. With no
750
+ * requester, the old refusal is what still happens, byte for byte.
751
+ *
752
+ * A REFUSAL IS NEVER A HANG. Every path here replies: an approval becomes
753
+ * `accept`/`approved`, and a denial, a deadline, an unreachable hub, or a
754
+ * requester that throws all become `decline`/`denied` plus a `progress` line
755
+ * naming the cause. On the legacy pair the person's reason travels back to the
756
+ * model inside `{denied:{rejection}}`; the v2 decision enum has no message
757
+ * field, so there the reason reaches the log and not the model.
758
+ *
759
+ * `item/permissions/requestApproval` is still refused unconditionally — see
760
+ * `BRIDGEABLE_APPROVALS` for why a permission profile is not a yes/no question.
684
761
  *
685
762
  * `item/tool/requestUserInput` and every non-owenloop elicitation emit
686
763
  * `needs_input` and then throw: the Phase 1 contract deliberately has no reply
@@ -688,8 +765,33 @@ function createTurnGate(onEvent) {
688
765
  * error reply surfaces to the model as a failed tool call — the least-wrong
689
766
  * behavior available (contract observation 3).
690
767
  */
691
- function handleServerRequest(onEvent) {
768
+ export function handleServerRequest(onEvent, approvals) {
692
769
  return async (method, params) => {
770
+ const shape = BRIDGEABLE_APPROVALS[method];
771
+ if (shape !== undefined && approvals !== undefined) {
772
+ const ask = describeApproval(shape, params);
773
+ let denial = 'the approval channel produced no answer';
774
+ try {
775
+ const outcome = await approvals(ask);
776
+ if (outcome.decision === 'approved') {
777
+ onEvent({ kind: 'progress', text: `approved '${method}': ${ask.title}` });
778
+ return shape.legacy ? { decision: 'approved' } : { decision: 'accept' };
779
+ }
780
+ denial = outcome.note !== undefined && outcome.note !== ''
781
+ ? `${outcome.reason ?? 'denied'} — ${outcome.note}`
782
+ : (outcome.reason ?? 'denied');
783
+ }
784
+ catch (err) {
785
+ // The requester is contracted to always answer, so this is a defect in
786
+ // it rather than an expected path. It still cannot be allowed to hang
787
+ // the turn: a broken channel denies, exactly like a silent one.
788
+ denial = `the approval channel failed: ${describe(err)}`;
789
+ }
790
+ onEvent({ kind: 'progress', text: `denied '${method}': ${cap(denial)}` });
791
+ return shape.legacy
792
+ ? { decision: { denied: { rejection: denial } } }
793
+ : { decision: 'decline' };
794
+ }
693
795
  switch (method) {
694
796
  case 'item/tool/requestUserInput': {
695
797
  const questions = asMap(params)['questions'];
@@ -723,14 +825,26 @@ function handleServerRequest(onEvent) {
723
825
  onEvent({ kind: 'needs_input', question: cap(message) });
724
826
  throw new Error('owenloop hosts this session headlessly and cannot answer an elicitation');
725
827
  }
828
+ case 'item/permissions/requestApproval': {
829
+ // Refused even WITH an approval channel: the reply is a permission
830
+ // profile, not a decision, so there is no question a person could be
831
+ // shown whose answer this would be.
832
+ onEvent({
833
+ kind: 'progress',
834
+ text: `refusing '${method}': granting it means synthesizing a permission profile, not answering a question`,
835
+ });
836
+ throw new Error(`'${method}' is not answerable by a headless host`);
837
+ }
726
838
  case 'item/commandExecution/requestApproval':
727
839
  case 'item/fileChange/requestApproval':
728
- case 'item/permissions/requestApproval':
729
840
  case 'applyPatchApproval':
730
841
  case 'execCommandApproval': {
842
+ // Only reachable with NO approval channel wired in — with one, the
843
+ // branch above this switch handled it. Unchanged from before the
844
+ // channel existed: this adapter does not invent an approval.
731
845
  onEvent({
732
846
  kind: 'progress',
733
- text: `refusing '${method}': owenloop runs with approvalPolicy 'never' and does not grant approvals`,
847
+ text: `refusing '${method}': no approval channel is wired to this session, so nobody can grant it`,
734
848
  });
735
849
  throw new Error(`'${method}' is not answerable by a headless host`);
736
850
  }
@@ -742,7 +856,7 @@ function handleServerRequest(onEvent) {
742
856
  };
743
857
  }
744
858
  /** Spawn one app-server, complete the handshake, and return the wired client. */
745
- async function openClient(cwd, onEvent, gate) {
859
+ async function openClient(cwd, onEvent, gate, approvals) {
746
860
  let exitReported = false;
747
861
  const reportExit = (exitCode, error) => {
748
862
  if (exitReported)
@@ -772,7 +886,12 @@ async function openClient(cwd, onEvent, gate) {
772
886
  // — unsolicited traffic arrives before any request completes, and throwing
773
887
  // on one would kill a healthy session.
774
888
  onNotification: (method, params) => gate.onNotification(method, params),
775
- onServerRequest: handleServerRequest(onEvent),
889
+ // A blocked approval parks INSIDE this handler, for as long as it takes a
890
+ // person to answer. That is safe here and nowhere else in this file: the
891
+ // transport fires each server request without awaiting it (`void (async …)`
892
+ // in `jsonrpc-stdio.ts`), so the reader keeps draining notifications, and no
893
+ // timeout wraps a server request the way `client.request` wraps ours.
894
+ onServerRequest: handleServerRequest(onEvent, approvals),
776
895
  onStderr: (line) => onEvent({ kind: 'progress', text: cap(line) }),
777
896
  onExit: (code, signal) => {
778
897
  reportExit(code, signal === null ? undefined : `killed by ${signal}`);
@@ -958,7 +1077,7 @@ export const codexAdapter = {
958
1077
  const startParams = buildThreadStartParams(args, onEvent);
959
1078
  // Handshake failure disposes the child inside `openClient` — see the catch
960
1079
  // there. Nothing is spawned and unowned by the time this rejects.
961
- const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
1080
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
962
1081
  let threadId;
963
1082
  try {
964
1083
  const res = await client.request('thread/start', startParams, SETUP_TIMEOUT_MS);
@@ -1022,7 +1141,7 @@ export const codexAdapter = {
1022
1141
  SESSIONS.delete(ref.token);
1023
1142
  await previous.client.dispose();
1024
1143
  }
1025
- const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
1144
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
1026
1145
  try {
1027
1146
  await client.request('thread/resume', resumeParams, SETUP_TIMEOUT_MS);
1028
1147
  }
@@ -143,30 +143,35 @@ export interface StepPermissions {
143
143
  * `full-access`, and the two exist separately so that choice is stated rather
144
144
  * than inferred.
145
145
  *
146
- * WHAT `auto-safe` COSTS YOU TODAY, MEASURED. The three positions above
147
- * describe the vocabulary, not a guarantee about how far any given classifier
148
- * actually goes before it consults someone. On one shipped adapter the
149
- * classifier was probed with five actions — among them a recursive delete on an
150
- * absolute path outside the session working directory, an outbound network
151
- * request, and a read of a file outside that directory — and it consulted the
152
- * host on none of them and reported no auto-denial for any of them; four ran.
153
- * On the other, the position that maps to `auto-safe` keys its judgment on
146
+ * WHO ACTUALLY DOES THE GATING, AND WHAT IT COSTS. The three positions above
147
+ * describe the vocabulary, not a guarantee about how far any given VENDOR
148
+ * classifier goes before it consults someone — and measurement showed the
149
+ * vendor classifiers do not, in practice, consult anyone. One was probed with
150
+ * five actions, among them a recursive delete on an absolute path outside the
151
+ * session working directory, an outbound network request, and a read of a file
152
+ * outside that directory; it consulted the host on none of them and reported no
153
+ * auto-denial for any of them, and four ran. The other keys its judgment on
154
154
  * filesystem access being restricted, so a step that also declares
155
155
  * `filesystem: unrestricted` moves it close to `full-access` as well.
156
156
  *
157
- * The practical consequence for a definition author: choosing `auto-safe`
158
- * because you want a person consulted on the dangerous cases may get you
159
- * neither the prompt nor a record that one was skipped. Choose `ask` when a
160
- * human decision genuinely has to happen, and `full-access` when it genuinely
161
- * must not. Treat `auto-safe` as the classifier's own judgment with no
162
- * guaranteed appeal, not as a supervised `full-access`.
157
+ * So `auto-safe` is NOT implemented by handing the decision to a vendor
158
+ * classifier and hoping. An adapter that can intercept its harness's tool calls
159
+ * gates them itself (see `./gatekeeper.ts`) — path containment against the
160
+ * step's own working directory, plus a short deny-list of destructive shell
161
+ * patterns — which is a blunter instrument than a model-side classifier and the
162
+ * only one of the two that can actually escalate. An adapter that CANNOT
163
+ * intercept owes this vocabulary the other legitimate answer: refuse the value
164
+ * in `preflight`, per "WHAT AN ADAPTER OWES THIS VOCABULARY" below.
163
165
  *
164
- * `ask` and `auto-safe` are meaningful only where something can answer a
165
- * prompt. In a Shift-dispatched run nothing can, so a prompt is a stall: the
166
- * Step Agent stops mid-turn, submits nothing, and the hub re-arms the step into
167
- * a retry storm whose every worker dies in the same place. That is a reason for
168
- * a definition author to choose `full-access` for unattended steps, not a
169
- * reason for an adapter to silently upgrade one value into another.
166
+ * `ask` and `auto-safe` name positions where something is consulted. In a
167
+ * Shift-dispatched run no person is watching at the moment of the call, so the
168
+ * consultation cannot be synchronous: an adapter refuses the call and routes the
169
+ * agent to the `ask` MCP tool, which freezes the owed artifact and puts the
170
+ * question on a human's attention feed with an answer path back into the next
171
+ * attempt. What an adapter must never do is leave the call waiting on a prompt
172
+ * nobody will answer — that is a stall, and the hub re-arms the step into a
173
+ * retry storm whose every worker dies in the same place. Nor may it silently
174
+ * upgrade one value into another to avoid the problem.
170
175
  *
171
176
  * WHAT AN ADAPTER OWES THIS VOCABULARY. For each value an adapter must either
172
177
  * map it onto the vendor mode with the same meaning, or refuse it in
@@ -197,6 +202,53 @@ export interface PermissionIssue {
197
202
  field?: string;
198
203
  message: string;
199
204
  }
205
+ /**
206
+ * ONE escalated tool call, as the adapter hands it to the approval channel.
207
+ *
208
+ * `toolUseId` is the HARNESS's own id for the blocked call. It is the approval's
209
+ * identity, which is what makes a repeat of the same request the same question
210
+ * rather than a second one — an adapter that polls does so by re-sending an
211
+ * identical request.
212
+ */
213
+ export interface ApprovalRequest {
214
+ toolUseId: string;
215
+ toolName: string;
216
+ /** The call's arguments, as the harness presented them. */
217
+ toolInput: unknown;
218
+ /** Why the gatekeeper would not allow the call on its own. Shown to a person. */
219
+ reason: string;
220
+ /** The harness's own one-line rendering of the prompt, when it has one. */
221
+ title?: string;
222
+ /** Aborts the wait when the harness gives up on the call (session teardown). */
223
+ signal?: AbortSignal;
224
+ }
225
+ /**
226
+ * What came back. `note` is the deciding person's own words, when they left any.
227
+ *
228
+ * THERE IS NO THIRD OUTCOME. A timeout, a hub error, a lease that ended while
229
+ * the worker waited — every one of them is `denied`, with a `reason` an adapter
230
+ * can put in front of the agent. The alternative would be an adapter that has to
231
+ * decide what "no answer" means at the moment it is least able to, and the
232
+ * failure mode of guessing wrong is a tool call that runs because nobody said
233
+ * no.
234
+ */
235
+ export interface ApprovalOutcome {
236
+ decision: 'approved' | 'denied';
237
+ /** Why, when the decision was not a person's explicit yes. */
238
+ reason?: string;
239
+ note?: string;
240
+ }
241
+ /**
242
+ * The channel an adapter uses to ask a PERSON about one tool call and wait.
243
+ *
244
+ * Supplied by the worker, not built by an adapter: it is the worker that holds
245
+ * the hub client and knows which run this session is serving. An adapter that
246
+ * receives no requester keeps its pre-existing behavior — refuse the call and
247
+ * route the agent to `ask` — which is why this is optional rather than required.
248
+ * Nothing about the shape is vendor-specific; every harness that can intercept a
249
+ * tool call can use it.
250
+ */
251
+ export type ApprovalRequester = (req: ApprovalRequest) => Promise<ApprovalOutcome>;
200
252
  /** Everything an adapter needs to launch one step agent. */
201
253
  export interface StartArgs {
202
254
  /** The fully rendered step prompt. */
@@ -239,6 +291,12 @@ export interface StartArgs {
239
291
  };
240
292
  /** Normalized from the step def by `normalizeStepPermissions`. */
241
293
  permissions: StepPermissions;
294
+ /**
295
+ * The human approval channel for escalated tool calls, when this deployment
296
+ * has one. ABSENT means the adapter's existing refuse-and-route-to-`ask`
297
+ * behavior stands — that is a supported deployment, not a degraded one.
298
+ */
299
+ approvals?: ApprovalRequester;
242
300
  }
243
301
  /**
244
302
  * Everything an adapter needs to RESUME an existing session with one message.
@@ -266,7 +324,7 @@ export interface StartArgs {
266
324
  * happened to hold, and it must NOT fall back to a minimal option set on a map
267
325
  * miss.
268
326
  */
269
- export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort'>;
327
+ export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort' | 'approvals'>;
270
328
  /**
271
329
  * One harness implementation.
272
330
  *