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
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ 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
+
21
+ ## [0.5.6](https://github.com/typicalday/owenloop/compare/v0.5.5...v0.5.6) (2026-08-15)
22
+
23
+
24
+ ### Features
25
+
26
+ * gate tool calls so ask actually asks and auto-safe actually classifies ([#171](https://github.com/typicalday/owenloop/issues/171)) ([f1e95f5](https://github.com/typicalday/owenloop/commit/f1e95f5990f73399c5542cf2d103e16761792a64))
27
+ * tell every step agent where its inputs are and how much rope is left ([#169](https://github.com/typicalday/owenloop/issues/169)) ([47d0485](https://github.com/typicalday/owenloop/commit/47d0485f44ac893c9d2870f7afe31b8a4c42ca92))
28
+
7
29
  ## [0.5.5](https://github.com/typicalday/owenloop/compare/v0.5.4...v0.5.5) (2026-08-15)
8
30
 
9
31
 
@@ -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
+ }
@@ -70,11 +70,47 @@ export interface BriefSpec {
70
70
  */
71
71
  escalated?: boolean;
72
72
  /**
73
- * The owed output paths for this order, in packet order — `packet.owes`
74
- * mapped to its `path`. Feeds the submit contract; absent or empty renders
75
- * the contract without naming any path.
73
+ * The owed outputs for this order, in packet order. Feeds the submit contract
74
+ * (which names every path) and the attempt history (which reads the two reject
75
+ * counters); absent or empty renders neither.
76
+ *
77
+ * The caller is responsible for the FALLBACK: `packet.owes` is the hub's live
78
+ * answer to "what does this order still owe" and is the right source, but a
79
+ * hub old enough to project no `owes` array at all leaves it empty while
80
+ * `packet.outputs` still names the same paths. See `agent/loop.ts` — an empty
81
+ * list here silently deletes both contracts, which is the exact failure they
82
+ * were written to close.
76
83
  */
77
- owes?: readonly string[];
84
+ owes?: readonly OwedBrief[];
85
+ }
86
+ /**
87
+ * One owed output as the brief sees it: the path, plus how many times a prior
88
+ * submission to it was knocked back.
89
+ *
90
+ * Both counters are optional because a hub that does not project them is not a
91
+ * hub reporting zero — it is a hub with nothing to say, and the attempt history
92
+ * stays silent rather than telling an agent on its fourth attempt that this is
93
+ * its first.
94
+ */
95
+ export interface OwedBrief {
96
+ path: string;
97
+ /** Consumer/judge verdicts against a submitted value (`packet.owes[].judgmentRejects`). */
98
+ judgmentRejects?: number;
99
+ /** Engine refusals of a malformed value against the path's declared JSON
100
+ * Schema (`packet.owes[].schemaRejects`). */
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';
78
114
  }
79
115
  /**
80
116
  * Substitute the four dispatch tokens into a step template.
@@ -11,6 +11,12 @@ export const SHIFT_TOKEN = '__OWENLOOP_SHIFT__';
11
11
  function composite(spec) {
12
12
  return `${spec.workflow}/${spec.run}`;
13
13
  }
14
+ /** The owed paths worth naming: every non-empty `path`, in packet order. An
15
+ * empty string is not a path a `submit` or `ask` call could be made against, so
16
+ * it is dropped here once rather than guarded at each use. */
17
+ function owedPaths(spec) {
18
+ return (spec.owes ?? []).map((o) => o.path).filter((p) => p !== '');
19
+ }
14
20
  /**
15
21
  * Substitute the four dispatch tokens into a step template.
16
22
  *
@@ -30,12 +36,119 @@ export function renderBrief(templateContent, spec) {
30
36
  .join(spec.shiftId ?? '');
31
37
  const blocks = [
32
38
  renderRoutingLine(spec),
39
+ renderInputContract(spec),
33
40
  renderSubmitContract(spec),
41
+ renderShapeContract(spec),
42
+ renderAttemptHistory(spec),
34
43
  renderEscalationContract(spec),
35
44
  substituted,
36
45
  ];
37
46
  return blocks.filter((b) => b !== '').join('\n\n');
38
47
  }
48
+ /**
49
+ * Where this order's INPUTS are, stated to every agent on every run.
50
+ *
51
+ * WHY THIS EXISTS. The brief and the mounted work-holder are two halves of one
52
+ * order and nothing ever joined them. The brief is a rendered template; the
53
+ * order's actual data — the resolved `consumes` map, the owed paths, each path's
54
+ * reason thread — lives on the hub behind `get_order`, a tool the agent is
55
+ * mounted with and was never told about. So an agent whose template says "review
56
+ * the plan" has no stated way to obtain the plan, and the two things it does
57
+ * instead are both silent: it looks in its working directory and finds nothing,
58
+ * or it writes what a plan would plausibly say. Observed live: a planner whose
59
+ * working directory was empty produced a confident, fully-fabricated plan, and a
60
+ * builder began executing it. The working-directory half of that run was a
61
+ * separate defect and is fixed; this half is not, and it is the half that turns
62
+ * "I have no inputs" into fiction rather than into a question.
63
+ *
64
+ * WHEN IT RENDERS. On the same condition as the submit and escalation contracts
65
+ * — the order owes at least one named path — even though `get_order` itself
66
+ * takes no arguments and could always be stated. Two reasons, both concrete:
67
+ * this block's closing sentence sends the agent to `ask`, and `ask` is only
68
+ * described when there is an owed path for it to name, so an unconditional
69
+ * version would point at a section that is not there; and an order owing nothing
70
+ * has no work to orient for. The tool it names is always mounted — every agent
71
+ * order gets the full work-holder surface, because `buildOwenloopMcp` passes no
72
+ * tool selector.
73
+ *
74
+ * WHY IT RANKS `get_order` ABOVE THE BRIEF. The brief is rendered once at
75
+ * dispatch and is a summary; the packet is live and authoritative, and on a
76
+ * re-offer it carries reason threads this text cannot. Telling the agent which
77
+ * of the two wins removes the judgement call.
78
+ *
79
+ * WHY THE LAST LINE POINTS AT `ask`. Naming the source of inputs without saying
80
+ * what to do when an input is missing from it just relocates the guess.
81
+ *
82
+ * Vendor-neutral by construction: names owenloop's own tool and mount, no
83
+ * harness. `test/vendor-gate.test.ts` enforces this.
84
+ */
85
+ function renderInputContract(spec) {
86
+ if (owedPaths(spec).length === 0)
87
+ return '';
88
+ return [
89
+ 'Before you start: call the `get_order` tool on the mounted `owenloop` MCP server. It takes no arguments and returns THIS order in full — the inputs you were given (`consumes`), the exact output paths you owe, and each path\'s reason thread, including why any previous attempt was rejected.',
90
+ 'That packet is authoritative. This brief is a summary of it, rendered once when the order was dispatched; where the two disagree, the packet is right.',
91
+ 'If something you need is not in what `get_order` returns and you cannot recover it by working — reading the repository, re-reading your inputs, running a read-only command — then it was not given to you. Do not invent it and do not proceed on an assumption: use `ask` (below).',
92
+ ].join('\n');
93
+ }
94
+ /**
95
+ * How much rope is left, stated only when some has already been used.
96
+ *
97
+ * WHY THIS EXISTS, GIVEN THE REJECTION DELTA ALREADY SHIPS. `renderRejection` /
98
+ * `renderReplayBrief` tell a re-offered agent WHAT was wrong with its last
99
+ * submission. Neither tells it that the retrying is BOUNDED. Those are different
100
+ * facts and they drive different behaviour: the reasons make an agent revise,
101
+ * and revising is right up until the point where the blocker is not something
102
+ * revision can fix — at which point the agent needs to know that grinding out
103
+ * one more attempt is not free. Without a count, every attempt looks like the
104
+ * first one, so an agent has no reason to ever switch from retrying to asking,
105
+ * and the step burns its whole budget rediscovering the same blocker. The
106
+ * counter is the input to that decision and the packet has carried it all along.
107
+ *
108
+ * WHY IT DOES NOT NAME THE CAP. The cap is `maxAttempts` / `maxSchemaFailures`,
109
+ * resolved per-produce from the def (`model.ts`'s `effectiveMaxAttempts`), and
110
+ * the order packet does not carry it. Rendering a guessed number would be worse
111
+ * than rendering none: an agent told it has "2 of 5" left when it has 2 of 3
112
+ * will keep grinding. So this states the counts, which are true, and states that
113
+ * the budget is finite, which is also true, and states neither more precisely
114
+ * than the packet allows.
115
+ *
116
+ * WHY IT SEPARATES THE TWO COUNTERS. They mean opposite things to the agent. A
117
+ * judgment reject is a reader disagreeing with the CONTENT of a value that was
118
+ * otherwise well-formed. A schema reject is the engine refusing the SHAPE before
119
+ * anybody read it — rewriting the content again cannot help, and the fix is the
120
+ * structure of what was submitted. Reporting them as one number would send an
121
+ * agent to revise prose that was never read.
122
+ *
123
+ * Silent when every counter is zero or absent: a first attempt has no history,
124
+ * and "0 previous rejections" is a sentence that costs tokens to say nothing.
125
+ */
126
+ function renderAttemptHistory(spec) {
127
+ const lines = [];
128
+ for (const owed of spec.owes ?? []) {
129
+ if (owed.path === '')
130
+ continue;
131
+ const judgment = owed.judgmentRejects ?? 0;
132
+ const schema = owed.schemaRejects ?? 0;
133
+ if (judgment === 0 && schema === 0)
134
+ continue;
135
+ const parts = [];
136
+ if (judgment > 0) {
137
+ parts.push(`${judgment} rejected on judgment (a reader disagreed with the value — see its reason thread via \`get_order\`)`);
138
+ }
139
+ if (schema > 0) {
140
+ parts.push(`${schema} rejected on schema (the value did not match the declared shape — the fix is the STRUCTURE of what you submit, not its wording)`);
141
+ }
142
+ lines.push(`- \`${owed.path}\`: ${parts.join('; ')}.`);
143
+ }
144
+ if (lines.length === 0)
145
+ return '';
146
+ return [
147
+ 'Attempt history for this order — previous submissions that were knocked back:',
148
+ ...lines,
149
+ 'This retrying is bounded. After enough rejections on a path the engine stops re-arming this step entirely and it sits until a person intervenes, so a further attempt that repeats the last one costs a real attempt and gains nothing. If you now believe the blocker is something another attempt cannot fix, `ask` instead of resubmitting.',
150
+ ].join('\n');
151
+ }
39
152
  /**
40
153
  * How an order is COMPLETED, stated to every agent on every run.
41
154
  *
@@ -67,7 +180,7 @@ export function renderBrief(templateContent, spec) {
67
180
  * `src/harness/` that names a vendor.
68
181
  */
69
182
  function renderSubmitContract(spec) {
70
- const owed = (spec.owes ?? []).filter((p) => p !== '');
183
+ const owed = owedPaths(spec);
71
184
  // Nothing owed, nothing to say — the same stance the routing line takes on an
72
185
  // absent modifier. A contract with no path to name would have to write
73
186
  // `<path>` into its own example, which teaches the shape of the call while
@@ -80,6 +193,56 @@ function renderSubmitContract(spec) {
80
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.',
81
194
  ].join('\n');
82
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
+ }
83
246
  /**
84
247
  * What an agent does when it CANNOT complete the order, stated to every agent on
85
248
  * every run, right after the submit contract.
@@ -120,7 +283,7 @@ function renderSubmitContract(spec) {
120
283
  * Vendor-neutral by construction — names owenloop's own tool and mount only.
121
284
  */
122
285
  function renderEscalationContract(spec) {
123
- const owed = (spec.owes ?? []).filter((p) => p !== '');
286
+ const owed = owedPaths(spec);
124
287
  if (owed.length === 0)
125
288
  return '';
126
289
  return [
@@ -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";
@@ -71,6 +72,50 @@ export const DEFAULT_SUBMIT_GRACE_MS = 15_000;
71
72
  function errMsg(e) {
72
73
  return e instanceof Error ? e.message : String(e);
73
74
  }
75
+ /**
76
+ * The owed outputs the brief renders its submit contract, attempt history and
77
+ * escalation contract from.
78
+ *
79
+ * `packet.owes` is the RIGHT source and is used whenever it has anything in it:
80
+ * it is the hub's live answer to "what does this order still owe", so on a
81
+ * re-offer where some paths are already paid it names only the ones left, and it
82
+ * is the only source carrying the reject counters.
83
+ *
84
+ * THE FALLBACK, and why it is not defensive noise. `owes` reaching this function
85
+ * empty is a real, reachable state, not a can't-happen: the hub's order
86
+ * projection (`projectReferenceOrder`) is a deliberate allow-list that emits
87
+ * `owes: []` for any persisted row whose `owes` is not an array — every order
88
+ * written before the engine emitted the field. `packet.outputs` is projected
89
+ * from the same row and names the same paths, minus the counters. Preferring an
90
+ * empty `owes` over a populated `outputs` would render a brief with NO submit
91
+ * contract and NO escalation contract — silently reproducing, on exactly the old
92
+ * runs least able to cope with it, the defect both contracts exist to close. So:
93
+ * fall back to the paths, and let the attempt history stay silent because there
94
+ * are genuinely no counters to report.
95
+ *
96
+ * An order that owes nothing under BOTH fields renders neither contract, which
97
+ * is correct — there is no path for `submit` or `ask` to name.
98
+ */
99
+ function briefOwes(packet) {
100
+ if (packet.owes.length > 0) {
101
+ return packet.owes.map((owed) => ({
102
+ path: owed.path,
103
+ judgmentRejects: owed.judgmentRejects,
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
+ : {}),
112
+ }));
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.
117
+ return packet.outputs.map((path) => ({ path }));
118
+ }
74
119
  /**
75
120
  * Resolve an order's composed capabilities against this machine's map.
76
121
  *
@@ -187,6 +232,10 @@ export function createAgentRunLoop(opts) {
187
232
  order,
188
233
  attempt,
189
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 } : {}),
190
239
  token: sessionRef?.token ?? '',
191
240
  cwd: recordCwd,
192
241
  status,
@@ -427,9 +476,7 @@ export function createAgentRunLoop(opts) {
427
476
  // statement about the RUN, and a shift has no say in it.
428
477
  ...(packet.modifier !== undefined ? { modifier: packet.modifier } : {}),
429
478
  ...(packet.escalated === true ? { escalated: true } : {}),
430
- // The hub's own answer to "what does this order still owe", so the submit
431
- // contract names the right paths on a re-offer where some are already paid.
432
- owes: packet.owes.map((owed) => owed.path),
479
+ owes: briefOwes(packet),
433
480
  };
434
481
  // Permissions arrive PRE-NORMALIZED in the spec. `prepare` ran
435
482
  // `normalizeStepPermissions` over the step's `x.harness` options at cache
@@ -541,6 +588,22 @@ export function createAgentRunLoop(opts) {
541
588
  deliveredReasonAt = delta.deliveredReasonAt;
542
589
  }
543
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
+ });
544
607
  const resolvedModel = routing.kind === 'resolved'
545
608
  ? { model: routing.resolution.model, effort: routing.resolution.effort }
546
609
  : undefined;
@@ -548,6 +611,7 @@ export function createAgentRunLoop(opts) {
548
611
  cwd: recordCwd,
549
612
  owenloopMcp,
550
613
  permissions,
614
+ approvals,
551
615
  ...(resolvedModel ?? {}),
552
616
  };
553
617
  /** Built lazily: a cold start after a refused resume needs a FRESH one. */
@@ -563,6 +627,7 @@ export function createAgentRunLoop(opts) {
563
627
  cwd: recordCwd,
564
628
  owenloopMcp,
565
629
  permissions,
630
+ approvals,
566
631
  ...(resolvedModel ?? {}),
567
632
  });
568
633
  const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
@@ -1,4 +1,6 @@
1
1
  import type { Options, Query, SDKMessage } from '@anthropic-ai/claude-agent-sdk';
2
+ import type { GatePolicy } from './gatekeeper.ts';
3
+ import type { ApprovalRequester } from './contract.ts';
2
4
  import type { AgentEvent, HarnessAdapter, HarnessSessionRef, StartArgs, StepPermissions } from './contract.ts';
3
5
  /**
4
6
  * Build the environment the harness child runs under.
@@ -65,6 +67,29 @@ export declare function allowApiBillingFrom(source: Record<string, string | unde
65
67
  * and the `PATH` searched are the same ones the child will see.
66
68
  */
67
69
  export declare function resolveExecutable(source: Record<string, string | undefined>): string | undefined;
70
+ /**
71
+ * How hard the gatekeeper gates, from the mode the step ACTUALLY AUTHORED.
72
+ *
73
+ * Derived from the authored string rather than from the translated SDK mode
74
+ * because the translation is deliberately lossy in exactly the place that
75
+ * matters: `ask` and `auto-safe` both become `default`, and the whole difference
76
+ * between them now lives here.
77
+ *
78
+ * WHY AN UNSET MODE CLASSIFIES RATHER THAN DENYING. A step that names no
79
+ * `permissionMode` gets the SDK's own `default`, which routes to the callback.
80
+ * Before a callback existed that meant the SDK denied every unapproved call —
81
+ * silently, finally, with nobody prompted and nothing recorded. Treating the
82
+ * unset case as `classifier` is not a widening of what those steps were promised;
83
+ * it is the first time they get anything at all. The same reasoning covers a
84
+ * step that named the vendor's `default` or `acceptEdits`.
85
+ *
86
+ * `dontAsk` is the one value that keeps its narrow meaning: it is documented as
87
+ * "deny if not pre-approved", so it maps to the policy that denies rather than
88
+ * being folded into the classifier. The SDK short-circuits that mode before the
89
+ * callback, so this is a statement of intent more than a live path — but a
90
+ * future SDK that does route it must not find it silently widened here.
91
+ */
92
+ export declare function gatePolicyFor(authoredMode: string | undefined): GatePolicy;
68
93
  /** Everything `buildClaudeOptions` reads for either cold start or resume. */
69
94
  export interface ClaudeOptionInputs {
70
95
  cwd: string;
@@ -77,6 +102,9 @@ export interface ClaudeOptionInputs {
77
102
  /** Per-start override; wins over `permissions.effort`. */
78
103
  effort?: string;
79
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;
80
108
  }
81
109
  /** The non-declarative bits a caller supplies per invocation. */
82
110
  export interface ClaudeOptionExtras {