owenloop 0.4.0 → 0.5.0

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 (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,193 @@
1
+ /** The composite `<workflow>/<run>` order id token. */
2
+ export const ORDER_TOKEN = '__OWENLOOP_ORDER__';
3
+ /** The hub origin token. */
4
+ export const ORIGIN_TOKEN = '__OWENLOOP_ORIGIN__';
5
+ /** The Scoped Identity account token. */
6
+ export const ACCOUNT_TOKEN = '__OWENLOOP_ACCOUNT__';
7
+ /** The dispatching Shift's self-declared id token (advisory only). */
8
+ export const SHIFT_TOKEN = '__OWENLOOP_SHIFT__';
9
+ /** The composite order id — the only form the hub verbs accept. */
10
+ function composite(spec) {
11
+ return `${spec.workflow}/${spec.run}`;
12
+ }
13
+ /**
14
+ * Substitute the four dispatch tokens into a step template.
15
+ *
16
+ * `split(...).join(...)` rather than a regex replace, mirroring the legacy
17
+ * stamp exactly: it replaces every occurrence and treats the token as a literal
18
+ * (no accidental `$&` expansion from template text the author controls).
19
+ */
20
+ export function renderBrief(templateContent, spec) {
21
+ return templateContent
22
+ .split(ORDER_TOKEN)
23
+ .join(composite(spec))
24
+ .split(ORIGIN_TOKEN)
25
+ .join(spec.origin)
26
+ .split(ACCOUNT_TOKEN)
27
+ .join(spec.account)
28
+ .split(SHIFT_TOKEN)
29
+ .join(spec.shiftId ?? '');
30
+ }
31
+ /**
32
+ * The born-bound work-holder mount handed to `HarnessAdapter.start` as
33
+ * `StartArgs.owenloopMcp`. The adapter mounts it verbatim and never builds it.
34
+ *
35
+ * `--shift=<cid>` is ONE argv element, not two. An absent cid then degrades
36
+ * to the single well-formed string `"--shift="` instead of a dangling flag
37
+ * with no value or a null array entry, which is what `hold`'s parser expects.
38
+ * (The shape originated with the deleted stamp path, which had to survive a YAML
39
+ * args array; it is kept because it is still the correct, unambiguous form.)
40
+ */
41
+ export function buildOwenloopMcp(spec) {
42
+ return {
43
+ command: 'owenloop',
44
+ args: [
45
+ 'work',
46
+ 'hold',
47
+ '--order',
48
+ composite(spec),
49
+ '--origin',
50
+ spec.origin,
51
+ '--as',
52
+ spec.account,
53
+ `--shift=${spec.shiftId ?? ''}`,
54
+ '--mcp',
55
+ ],
56
+ };
57
+ }
58
+ /** Rough token budget for the cold-replay brief, per the Phase 4 plan. */
59
+ export const REPLAY_TOKEN_BUDGET = 100_000;
60
+ /** chars/4 — the cheap, deliberately approximate token estimate. Nothing here
61
+ * needs a real tokenizer: the cap exists to avoid a pathological brief, not to
62
+ * hit a byte-exact ceiling. */
63
+ export function estimateTokens(text) {
64
+ return Math.ceil(text.length / 4);
65
+ }
66
+ /** One rendered reason line. `kind`/`by` are attribution the model needs to weigh
67
+ * a reason; `text` is the reason itself. */
68
+ function reasonLine(index, r) {
69
+ return `${index}. [${r.kind}, by ${r.by}] ${r.text}`;
70
+ }
71
+ /**
72
+ * Render the REJECTION DELTA — the whole point of Phase 4.
73
+ *
74
+ * THE CENTRAL DESIGN POINT: this message is SHORT, and it deliberately does NOT
75
+ * contain the brief. The session being resumed already holds the original brief,
76
+ * the file reads, the tool results and the prior submission — that is the entire
77
+ * reason the worker resumes instead of restarting. Re-sending the brief would
78
+ * spend exactly the tokens this phase exists to save, and would leave the model
79
+ * with two copies of its instructions and no way to tell which is current.
80
+ *
81
+ * WHAT IT MAY NOT CONTAIN, and why each is named rather than left to judgement:
82
+ * - `brief` / `material.templateContent` / `packet.prompt` — see above.
83
+ * - `packet.consumes` and any submit hint — the resumed session already has them.
84
+ * - any credential material. `OrderPacket.owes` carries none, and this function
85
+ * reads nothing else, so the property holds by construction rather than by
86
+ * filtering. `test/agent-rejection.test.ts` asserts it anyway.
87
+ *
88
+ * REASON SELECTION, restated from `docs/agent-runner.md` (c): the reasons come
89
+ * from `OrderPacket.owes[].reasons`, filtered to `at > deliveredReasonAt` and, when
90
+ * `spec.paths` is given, to those owed paths. NEVER from `WorkOrder.feedback` —
91
+ * that is the flattened `whats_next` shape, it carries no `at`, and a shape with
92
+ * no timestamp cannot be diffed against a watermark.
93
+ *
94
+ * PURE: packet + watermark in, string out. No I/O, no clock, no harness.
95
+ */
96
+ export function renderRejection(spec) {
97
+ const since = spec.deliveredReasonAt;
98
+ const wanted = spec.paths === undefined ? undefined : new Set(spec.paths);
99
+ const sections = [];
100
+ let newest;
101
+ let count = 0;
102
+ for (const owed of spec.packet.owes) {
103
+ if (wanted !== undefined && !wanted.has(owed.path))
104
+ continue;
105
+ const fresh = owed.reasons.filter((r) => since === undefined || r.at > since);
106
+ // A schema reject with no text is a real shape: the owed entry exists, the
107
+ // reason thread is empty. Filtering to nothing here is what makes the caller
108
+ // cold-start rather than resume with a bare "you were rejected".
109
+ if (fresh.length === 0)
110
+ continue;
111
+ const lines = fresh.map((r, i) => reasonLine(i + 1, r));
112
+ sections.push(`Your submission for \`${owed.path}\` was rejected. Reasons:\n\n${lines.join('\n')}`);
113
+ count += fresh.length;
114
+ for (const r of fresh) {
115
+ if (newest === undefined || r.at > newest)
116
+ newest = r.at;
117
+ }
118
+ }
119
+ if (sections.length === 0)
120
+ return { message: '', count: 0 };
121
+ const message = [
122
+ ...sections,
123
+ 'Revise and submit again to the same path with the same tool. Do not start over —\n' +
124
+ 'keep everything you already have that was not called out above.',
125
+ ].join('\n\n');
126
+ return { message, count, ...(newest !== undefined ? { deliveredReasonAt: newest } : {}) };
127
+ }
128
+ /**
129
+ * Assemble a COLD-REPLAY brief: the ordinary rendered brief plus the same
130
+ * rejection body as a trailing section.
131
+ *
132
+ * Used when resume is impossible (no prior session, a different harness, a dead
133
+ * session, a reaped cwd, a `replay`-tier adapter, or the provider rejecting the
134
+ * resume with `ResumeUnavailableError`). The session is gone, so the brief has to
135
+ * come back — but the reasons still have to arrive, or the fresh agent repeats
136
+ * the rejected submission verbatim.
137
+ *
138
+ * THE CAP. The assembled text is held to roughly `REPLAY_TOKEN_BUDGET` tokens by
139
+ * a chars/4 estimate. When it is over, WHOLE reason entries are dropped from the
140
+ * OLDEST end first and the message says how many were dropped. Never a mid-entry
141
+ * truncation: the kanna `handoff.ts` rule — never orphan a tool result from its
142
+ * call — generalizes here to "never emit half a structured item", because half a
143
+ * reason reads as a complete but different instruction.
144
+ *
145
+ * The BRIEF is never trimmed. If the brief alone exceeds the budget, the brief
146
+ * wins and the rejection section is reduced to as many of the NEWEST reasons as
147
+ * still fit, possibly none — losing the brief would leave the agent with no task
148
+ * at all, which is strictly worse than losing old reasons.
149
+ */
150
+ export function renderReplayBrief(brief, spec) {
151
+ const full = renderRejection(spec);
152
+ if (full.message === '')
153
+ return brief;
154
+ const join = (body, dropped) => {
155
+ const note = dropped > 0
156
+ ? `\n\n(${dropped} older rejection reason${dropped === 1 ? '' : 's'} omitted to fit the context budget.)`
157
+ : '';
158
+ return `${brief}\n\n---\n\n${body}${note}`;
159
+ };
160
+ let assembled = join(full.message, 0);
161
+ if (estimateTokens(assembled) <= REPLAY_TOKEN_BUDGET)
162
+ return assembled;
163
+ // Over budget: re-render with progressively fewer reasons, oldest dropped
164
+ // first. `ordered` is every candidate entry in ascending `at`, so slicing off
165
+ // the FRONT drops the oldest and keeps whole entries.
166
+ const since = spec.deliveredReasonAt;
167
+ const wanted = spec.paths === undefined ? undefined : new Set(spec.paths);
168
+ const ordered = spec.packet.owes
169
+ .filter((o) => wanted === undefined || wanted.has(o.path))
170
+ .flatMap((o) => o.reasons)
171
+ .filter((r) => since === undefined || r.at > since)
172
+ .sort((a, b) => a.at - b.at);
173
+ for (let drop = 1; drop <= ordered.length; drop += 1) {
174
+ const keep = new Set(ordered.slice(drop));
175
+ const trimmed = renderRejection({
176
+ ...spec,
177
+ packet: {
178
+ owes: spec.packet.owes.map((o) => ({ ...o, reasons: o.reasons.filter((r) => keep.has(r)) })),
179
+ },
180
+ // The watermark filter already ran; re-applying it is harmless but the
181
+ // `keep` set is now the authority on which entries survive.
182
+ ...(since !== undefined ? { deliveredReasonAt: since } : {}),
183
+ });
184
+ if (trimmed.message === '')
185
+ break;
186
+ assembled = join(trimmed.message, drop);
187
+ if (estimateTokens(assembled) <= REPLAY_TOKEN_BUDGET)
188
+ return assembled;
189
+ }
190
+ // Everything was dropped and it still does not fit — the brief alone is over
191
+ // budget. Return the brief: an agent with a task and no reasons can still work.
192
+ return brief;
193
+ }
@@ -0,0 +1,135 @@
1
+ import type { HubClient } from '../hub/client.ts';
2
+ import type { ContactHolder, OrderPacket } from '../hub/types.ts';
3
+ import type { NormalizedStepSpec } from '../bundle/types.ts';
4
+ import type { HarnessAdapter } from '../harness/contract.ts';
5
+ import { type SessionRecord } from '../harness/session-store.ts';
6
+ /** Discriminated result of one worker life; the role maps these to exit codes. */
7
+ export type AgentRunOutcome = 'submitted' | 'completed' | 'misroute' | 'no-template' | 'no-harness' | 'no-submit' | 'killed' | 'lease-lost' | 'ownership-error' | 'hub-unreachable' | 'stopped';
8
+ /**
9
+ * Locate the normalized step spec for an order. Injected because the lookup is
10
+ * I/O (the bundle cache) and because resolving WHICH cached def serves this
11
+ * instance is the role's business, not the loop's. `null` ⇒ no spec, which is
12
+ * the `'no-template'` outcome (release, leave it for the pickup window).
13
+ *
14
+ * The spec arrives ALREADY NORMALIZED from `prepare` — brief, harness id, and
15
+ * `StepPermissions`. That is what lets this loop stay vendor-neutral: it never
16
+ * reaches into a step def's extension bag, so there is no key to name.
17
+ */
18
+ export type StepLoader = (order: OrderPacket) => Promise<NormalizedStepSpec | null>;
19
+ /**
20
+ * The outcome of resolving which adapter hosts this step agent.
21
+ *
22
+ * The loop never reads a registry and never names a harness: the role
23
+ * (`src/roles/agent-run.ts`, the composition root) owns the precedence
24
+ * `--harness` > `OWENLOOP_HARNESS` > the step def's `harness` field > the
25
+ * built-in default, and hands back the id it picked plus the adapter, if any.
26
+ * `registered` is only ever used to make the failure message actionable.
27
+ */
28
+ export interface AdapterResolution {
29
+ id: string;
30
+ adapter?: HarnessAdapter;
31
+ registered: string[];
32
+ }
33
+ /** `stepHarness` is the step def's `harness` field, the third precedence rank. */
34
+ export type AdapterResolver = (stepHarness: string | undefined) => AdapterResolution;
35
+ /** Default confirm-phase cadence: one `get_order` per second. */
36
+ export declare const DEFAULT_CONFIRM_INTERVAL_MS = 1000;
37
+ /** Default confirm-phase bound: give the hub 15s to show the submit's outcome. */
38
+ export declare const DEFAULT_SUBMIT_GRACE_MS = 15000;
39
+ export interface AgentRunLoopOptions {
40
+ hub: HubClient;
41
+ workflow: string;
42
+ run: string;
43
+ /** The worker's holder tag `{kind:'exec', id}` — `'exec'` is drain-exempt. */
44
+ holder: ContactHolder;
45
+ /** Hub origin — rides the mounted work-holder's `--origin`. */
46
+ origin: string;
47
+ /** Scoped Identity account — rides the mounted work-holder's `--as`. */
48
+ account: string;
49
+ /** Advisory Shift attribution — rides `--shift=<cid>` (may be absent). */
50
+ shiftId?: string;
51
+ /** cwd for the step agent when the order packet carries no `workdir`. */
52
+ cwd: string;
53
+ loadStep: StepLoader;
54
+ resolveAdapter: AdapterResolver;
55
+ /** Append one session record. Wired to `appendSession` by the role. */
56
+ appendSession: (rec: SessionRecord) => void;
57
+ /** The attempt number for this `(workflow, run, step)`. Wired to `latestFor`. */
58
+ nextAttempt: (workflow: string, run: string, step: string) => number;
59
+ /**
60
+ * PHASE 4 — the last session record for this `(workflow, run, step)`, or `null`
61
+ * when the step has never run here. Wired to `latestFor(sessionsFile, ...)` by
62
+ * the role, the same reader `nextAttempt` already uses.
63
+ *
64
+ * It is what makes a resume possible at all: the prior `token` to resume, the
65
+ * `harness` that minted it, the `cwd` it is scoped to, and the
66
+ * `deliveredReasonAt` watermark that says which reasons the session has already
67
+ * heard. Absent (or returning `null`) ⇒ every firing is a cold start, which is
68
+ * exactly the pre-Phase-4 behaviour.
69
+ */
70
+ latestSession?: (workflow: string, run: string, step: string) => SessionRecord | null;
71
+ /**
72
+ * Does this directory still exist? Injected for the same reason every other
73
+ * side effect here is: a unit test drives the "the work dir was reaped, so the
74
+ * session cannot resume" branch without touching a filesystem. Defaults to
75
+ * `node:fs` `existsSync`.
76
+ */
77
+ dirExists?: (path: string) => boolean;
78
+ sleep: (ms: number) => Promise<void>;
79
+ now: () => number;
80
+ random?: () => number;
81
+ out: (line: string) => void;
82
+ err: (line: string) => void;
83
+ heartbeatIntervalMs?: number;
84
+ jumpToleranceMs?: number;
85
+ failureWindowMs?: number;
86
+ /** Confirm-phase poll cadence (default `DEFAULT_CONFIRM_INTERVAL_MS`). */
87
+ confirmIntervalMs?: number;
88
+ /** Confirm-phase upper bound (default `DEFAULT_SUBMIT_GRACE_MS`). */
89
+ submitGraceMs?: number;
90
+ }
91
+ export interface AgentRunLoop {
92
+ run(): Promise<AgentRunOutcome>;
93
+ /** Final breath: tear the session down and release. Wired to SIGINT/SIGTERM. */
94
+ stop(reason?: string): void;
95
+ }
96
+ /** How the bounded confirm phase ended. */
97
+ export type ConfirmResult = 'submitted' | 'lease-lost' | 'no-submit';
98
+ export interface ConfirmOptions {
99
+ hub: HubClient;
100
+ workflow: string;
101
+ run: string;
102
+ holder: ContactHolder;
103
+ sleep: (ms: number) => Promise<void>;
104
+ now: () => number;
105
+ err: (line: string) => void;
106
+ intervalMs: number;
107
+ graceMs: number;
108
+ /**
109
+ * Bail out early. Set once the caller's race is already decided (the lease
110
+ * loop settled, or a signal arrived), so a pending poll cannot hold the event
111
+ * loop open for the rest of the grace. The returned value is discarded in
112
+ * that case.
113
+ */
114
+ cancelled?: () => boolean;
115
+ }
116
+ /**
117
+ * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
118
+ * question: did the hub see the agent's `submit`?
119
+ *
120
+ * - `lease.outcome` present ⇒ `'submitted'` — the run closed.
121
+ * - `lease.claimed === false` with no outcome ⇒ `'lease-lost'` — something
122
+ * else took the run; releasing would be wrong and a submit would race it.
123
+ * - the grace expires, still claimed, still no outcome ⇒ `'no-submit'`.
124
+ *
125
+ * It calls `hub.getOrder` DIRECTLY rather than poking the lease loop:
126
+ * `LeaseLoop`'s public surface is `{run, stop}` with no probe-now method, and
127
+ * `src/lease/loop.ts` is load-bearing for six existing drills and must stay
128
+ * unchanged. Re-calling `get_order` while already holding the claim is exactly
129
+ * what the lease loop's own heartbeat does, so this adds no new hub semantics.
130
+ *
131
+ * A throwing `get_order` is transient by assumption: it is logged and the poll
132
+ * continues until the grace expires. Nothing here releases; only the caller does.
133
+ */
134
+ export declare function confirmOutcome(o: ConfirmOptions): Promise<ConfirmResult>;
135
+ export declare function createAgentRunLoop(opts: AgentRunLoopOptions): AgentRunLoop;