owenloop 0.4.1 → 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 (154) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +58 -31
  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/{cli.d.ts → src/cli.d.ts} +18 -3
  109. package/dist/{cli.js → src/cli.js} +770 -114
  110. package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
  111. package/dist/{credentials.js → src/credentials.js} +14 -12
  112. package/dist/{defs.js → src/defs.js} +36 -36
  113. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  114. package/dist/{engine.js → src/engine.js} +14 -14
  115. package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
  116. package/dist/{hub.js → src/hub.js} +370 -12
  117. package/dist/{index.d.ts → src/index.d.ts} +1 -1
  118. package/dist/{index.js → src/index.js} +1 -1
  119. package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
  120. package/dist/{mcp → src/mcp}/serve.js +168 -31
  121. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  122. package/dist/{mcp → src/mcp}/server.js +6 -9
  123. package/dist/{model.js → src/model.js} +1 -1
  124. package/dist/{types.d.ts → src/types.d.ts} +18 -18
  125. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  126. package/dist/{util.js → src/util.js} +3 -2
  127. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  128. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  129. package/docs/authoring.md +93 -53
  130. package/docs/cli.md +597 -76
  131. package/docs/design.md +33 -33
  132. package/docs/embedding.md +10 -9
  133. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  134. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  135. package/examples/workflows/judges/gate-sharpness.md +39 -0
  136. package/examples/workflows/judges/security.md +34 -0
  137. package/package.json +17 -8
  138. /package/dist/{add.d.ts → src/add.d.ts} +0 -0
  139. /package/dist/{add.js → src/add.js} +0 -0
  140. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  141. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  142. /package/dist/{factory.js → src/factory.js} +0 -0
  143. /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
  144. /package/dist/{lock.js → src/lock.js} +0 -0
  145. /package/dist/{model.d.ts → src/model.d.ts} +0 -0
  146. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  147. /package/dist/{paths.js → src/paths.js} +0 -0
  148. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  149. /package/dist/{schema.js → src/schema.js} +0 -0
  150. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  151. /package/dist/{store.js → src/store.js} +0 -0
  152. /package/dist/{types.js → src/types.js} +0 -0
  153. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  154. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,447 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * `owenloop work agent-run <order-id>` (Phase 3) — the detached, self-leasing worker
11
+ * that HOSTS one step agent, and the harness-registry COMPOSITION ROOT.
12
+ *
13
+ * The shift spawns one detached
14
+ * `owenloop work agent-run <workflow>/<run> --origin <url>` per AGENT order — the
15
+ * ONLY path an agent order takes, since Phase 5 deleted the legacy stamp path
16
+ * it used to share the lane with. This
17
+ * process owns that order end to end: it takes the lease on first contact,
18
+ * renders the step's brief, starts the step agent inside a harness adapter with
19
+ * a work-holder MCP mount born bound to this order, keeps the lease warm
20
+ * underneath the turn, and learns whether the agent submitted FROM THE HUB.
21
+ * Nothing is ever written to any agent-definition directory.
22
+ *
23
+ * The orchestration CORE lives in `src/agent/loop.ts` (lease + adapter + confirm
24
+ * phase, every side effect injected); this role only parses the arg contract,
25
+ * resolves origin/credential/cache, tags the holder identity, resolves WHICH
26
+ * adapter hosts the agent, loads the brief template, wires the signal seam, and
27
+ * maps `AgentRunOutcome` to an exit code.
28
+ *
29
+ * ── WHERE THE ADAPTERS COME FROM (Phase 6) ──
30
+ *
31
+ * `src/harness/registry.ts` starts empty and forbids a barrel, so SOMEBODY has
32
+ * to import the adapter modules for their `register(...)` side effect to fire.
33
+ * Through Phase 5 that somebody was this file AND `src/roles/lint.ts`, each
34
+ * carrying the same import pair in the same hand-maintained order. Phase 6
35
+ * consolidated both into `src/harnesses.ts`; this file imports THAT, and the
36
+ * single line is directly below the header. Adapter import order — which decides
37
+ * the default harness — now has exactly one owner.
38
+ *
39
+ * ── WHERE THE STEP SPEC COMES FROM ──
40
+ *
41
+ * The spawn argv (D6) carries only `<workflow>/<run>`, `--origin`, `--shift`
42
+ * and `--harness` — no def name and no def hash, both of which the bundle cache
43
+ * needs. So the worker resolves the def name ITSELF: one non-claiming
44
+ * `whats_next({workflow})` returns `def` in per-workflow mode, which feeds
45
+ * `readDispatchBundle(cacheDir, def)` → `bundle.def.hash` → `readStepSpec(...)`.
46
+ * That keeps the argv exactly as D6 specifies and adds no new settings surface.
47
+ *
48
+ * ── CREDENTIALS ──
49
+ *
50
+ * Origin/credential resolution mirrors `exec`: origin `--origin` → settings; the
51
+ * bearer comes from owenloop's store via `resolveBearer`, reading the
52
+ * `agent:<account>` slot for the account the shift set in this child's
53
+ * `OWENLOOP_ACCOUNT` spawn env (default `default`). `agent-run` has NO `--as`
54
+ * flag — the spawn-env channel is the contract.
55
+ *
56
+ * D10, CLOSED IN PHASE 6. The MCP mount this worker builds carries no
57
+ * credential — the mounted work-holder resolves its own from the same store —
58
+ * and as of Phase 6 the dev-only `OWENLOOP_TOKEN` override is no longer
59
+ * inherited by the harness child either. Both adapters filter it out through
60
+ * `filterOwenloopEnv` (`src/harness/child-env.ts`), an allowlist scoped to the
61
+ * `OWENLOOP_*` namespace ONLY, so nothing a harness needs in order to start —
62
+ * `PATH`, `HOME`, `NODE_OPTIONS`, a shift setting, a vendor's own credential
63
+ * variable — can be stranded by it.
64
+ *
65
+ * The consequence lands in this file: because the child cannot see the override,
66
+ * THIS ROLE IGNORES IT TOO, so worker and child authenticate as the same
67
+ * principal. See the block around the `resolveBearer` call. `resolveBearer`
68
+ * itself is unchanged and every other role still honours the override.
69
+ *
70
+ * Phase 4's narrower guarantee still holds and is still asserted: the rejection
71
+ * delta and the replay brief carry no credential material
72
+ * (`test/agent-rejection.test.ts`).
73
+ *
74
+ * ── WHERE THE STEP AGENT WORKS (Phase 4) ──
75
+ *
76
+ * `OrderPacket.workdir` (the hub's choice) > `<workRoot>/<workflow>/<run>/` >
77
+ * this process's cwd. The middle rung is new: see `src/agent/workdir.ts` for the
78
+ * per-RUN layout and the reaper that removes it.
79
+ */
80
+ // ── The composition root, imported for its side effect ──────────────────────
81
+ //
82
+ // PHASE 6: this file used to carry the adapter imports itself, and so did
83
+ // `src/roles/lint.ts` — two roots whose import ORDER had to be kept identical by
84
+ // hand, because the first id registered is the default harness. Both now import
85
+ // the single root, `src/harnesses.ts`, which owns that order. Without this line
86
+ // nothing is registered and every run fails with `'no-harness'`.
87
+ import "../harnesses.js";
88
+ // ─────────────────────────────────────────────────────────────────────────────
89
+ import { hostname } from 'node:os';
90
+ import { readDispatchBundle, readStepSpec, resolveCacheDir } from "../bundle/cache.js";
91
+ import { createAgentRunLoop } from "../agent/loop.js";
92
+ import { createHubClient } from "../hub/client.js";
93
+ import { resolveBearer } from "../credentials/resolve.js";
94
+ import { loadSettings } from "../settings/settings.js";
95
+ import { adapterFor, defaultHarnessId, registeredHarnessIds } from "../harness/registry.js";
96
+ import { appendSession, latestFor, sessionsPath } from "../harness/session-store.js";
97
+ import { ensureWorkDir, resolveWorkRepo, resolveWorkRoot } from "../agent/workdir.js";
98
+ import { resolveShiftId, resolveTarget } from "./hold.js";
99
+ import { installSignalHandlers } from "./signals.js";
100
+ const DEFAULT_INTERVAL_MS = 60_000;
101
+ /** Positive-integer flag parse shared by the four ms knobs. */
102
+ function positiveMs(name, raw) {
103
+ const n = Number(raw);
104
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
105
+ return { error: `${name} must be a positive integer, got '${raw}'` };
106
+ }
107
+ return { value: n };
108
+ }
109
+ /**
110
+ * Parse the positional `<order-id>` plus `--workflow`/`--origin`/`--shift`/
111
+ * `--harness`/`--heartbeat-interval`/`--jump-tolerance`/`--submit-grace`/
112
+ * `--confirm-interval`. Supports `--flag value` and `--flag=value`; a second
113
+ * positional or an unknown flag is an error. Mirrors `src/roles/exec.ts`.
114
+ */
115
+ export function parseArgs(args) {
116
+ const parsed = {};
117
+ const takeValue = (a, i) => {
118
+ const eq = a.indexOf('=');
119
+ if (eq !== -1)
120
+ return { value: a.slice(eq + 1), next: i };
121
+ const v = args[i + 1];
122
+ if (v === undefined)
123
+ return { error: `missing value for ${a}` };
124
+ return { value: v, next: i + 1 };
125
+ };
126
+ for (let i = 0; i < args.length; i++) {
127
+ const a = args[i];
128
+ if (!a.startsWith('-')) {
129
+ if (parsed.orderId !== undefined)
130
+ return { error: `unexpected extra argument '${a}'` };
131
+ parsed.orderId = a;
132
+ continue;
133
+ }
134
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
135
+ switch (name) {
136
+ case '--workflow':
137
+ case '--origin':
138
+ case '--shift':
139
+ case '--harness':
140
+ case '--heartbeat-interval':
141
+ case '--jump-tolerance':
142
+ case '--submit-grace':
143
+ case '--confirm-interval': {
144
+ const r = takeValue(a, i);
145
+ if ('error' in r)
146
+ return { error: r.error };
147
+ i = r.next;
148
+ if (name === '--workflow')
149
+ parsed.workflow = r.value;
150
+ else if (name === '--origin')
151
+ parsed.origin = r.value;
152
+ else if (name === '--shift')
153
+ parsed.shift = r.value;
154
+ else if (name === '--harness')
155
+ parsed.harness = r.value;
156
+ else {
157
+ const n = positiveMs(name, r.value);
158
+ if ('error' in n)
159
+ return { error: n.error };
160
+ if (name === '--heartbeat-interval')
161
+ parsed.heartbeatIntervalMs = n.value;
162
+ else if (name === '--jump-tolerance')
163
+ parsed.jumpToleranceMs = n.value;
164
+ else if (name === '--submit-grace')
165
+ parsed.submitGraceMs = n.value;
166
+ else
167
+ parsed.confirmIntervalMs = n.value;
168
+ }
169
+ break;
170
+ }
171
+ default:
172
+ return { error: `unknown option '${a}'` };
173
+ }
174
+ }
175
+ return parsed;
176
+ }
177
+ function usage() {
178
+ process.stderr.write('usage: owenloop work agent-run <workflow>/<run> [--origin <url>] [--harness <id>] [--shift <id>]\n' +
179
+ ' [--heartbeat-interval <ms>] [--jump-tolerance <ms>]\n' +
180
+ ' [--submit-grace <ms>] [--confirm-interval <ms>]\n' +
181
+ ' or: owenloop work agent-run <run> --workflow <wf> [...]\n');
182
+ }
183
+ function errMsg(err) {
184
+ return err instanceof Error ? err.message : String(err);
185
+ }
186
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
187
+ export function exitCodeFor(outcome) {
188
+ switch (outcome) {
189
+ case 'submitted':
190
+ case 'completed':
191
+ return 0;
192
+ case 'misroute':
193
+ case 'no-template':
194
+ case 'no-harness':
195
+ case 'no-submit':
196
+ case 'killed':
197
+ case 'lease-lost':
198
+ case 'ownership-error':
199
+ case 'hub-unreachable':
200
+ case 'stopped':
201
+ return 1;
202
+ }
203
+ }
204
+ /**
205
+ * Import the module named by `OWENLOOP_HARNESS_MODULE`, if any, so its
206
+ * `register(...)` side effect fires before adapter resolution.
207
+ *
208
+ * TEST SEAM. Phase 4 filled the composition root's static import block above
209
+ * with the real adapters, so production no longer needs this to have ANY
210
+ * adapter at all. What it still buys is the ability for a drill to register a
211
+ * FAKE adapter inside a real spawned child without the child reaching for a
212
+ * real CLI. Production leaves the variable unset and this is a no-op. Drills
213
+ * that use it also pin `OWENLOOP_HARNESS=fake`, because the statically
214
+ * imported real adapters now occupy the front of the registry and would
215
+ * otherwise win the `defaultHarnessId()` tie-break. A failed import is
216
+ * reported and then ignored — resolution proceeds and fails honestly with
217
+ * `'no-harness'` if nothing ended up registered.
218
+ */
219
+ async function loadHarnessModule(spec, err) {
220
+ if (spec === undefined || spec.trim() === '')
221
+ return;
222
+ try {
223
+ await import(__rewriteRelativeImportExtension(spec));
224
+ }
225
+ catch (e) {
226
+ err(`owenloop work agent-run: could not load OWENLOOP_HARNESS_MODULE '${spec}': ${errMsg(e)}`);
227
+ }
228
+ }
229
+ export async function run(args, deps = {}) {
230
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
231
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
232
+ const parsed = parseArgs(args);
233
+ if (parsed.error !== undefined) {
234
+ err(`owenloop work agent-run: ${parsed.error}`);
235
+ usage();
236
+ return 2;
237
+ }
238
+ if (parsed.orderId === undefined || parsed.orderId === '') {
239
+ err('owenloop work agent-run: missing required <order-id>');
240
+ usage();
241
+ return 2;
242
+ }
243
+ const target = resolveTarget(parsed.orderId, parsed.workflow);
244
+ if ('error' in target) {
245
+ err(`owenloop work agent-run: ${target.error}`);
246
+ usage();
247
+ return 2;
248
+ }
249
+ const env = process.env;
250
+ let settings;
251
+ try {
252
+ settings = loadSettings(env);
253
+ }
254
+ catch (e) {
255
+ err(`owenloop work agent-run: ${errMsg(e)}`);
256
+ return 1;
257
+ }
258
+ const origin = parsed.origin ?? settings.hubOrigin;
259
+ if (origin === undefined || origin.trim() === '') {
260
+ err('owenloop work agent-run: no hub origin — pass --origin <url> or set hubOrigin in settings');
261
+ return 2;
262
+ }
263
+ let cacheDir;
264
+ try {
265
+ cacheDir = resolveCacheDir(env, settings.cacheDir);
266
+ }
267
+ catch (e) {
268
+ err(`owenloop work agent-run: ${errMsg(e)}`);
269
+ return 1;
270
+ }
271
+ // D10, CLOSED in Phase 6 (see the header). The dev-only bearer override is no
272
+ // longer passed to harness children: `filterOwenloopEnv` denies it in both
273
+ // adapters, because a harness child is an ordinary process that inherits this
274
+ // environment and at least one harness persists its start parameters to disk.
275
+ //
276
+ // THIS BLOCK IS THE OTHER HALF OF THAT CHANGE, and the two must stay together.
277
+ // If the worker kept honouring the override while the child could not see it,
278
+ // the two sides would authenticate as different principals: the worker with
279
+ // the override, the child falling back to its `agent:<account>` credential
280
+ // slot. An empty slot would then surface mid-order as an opaque MCP handshake
281
+ // failure, long after startup. So `agent-run` ignores the override too. Both
282
+ // sides now read the same slot, and an empty slot fails at STARTUP through
283
+ // `resolveBearer`'s existing exit-code-2 refusal, whose message names the
284
+ // login command to run.
285
+ //
286
+ // SCOPE: this file only. `resolveBearer` is unchanged and every other role
287
+ // keeps the override — `agent-run` is the one role that spawns a harness.
288
+ const workerEnv = { ...env };
289
+ if ((workerEnv['OWENLOOP_TOKEN'] ?? '') !== '') {
290
+ delete workerEnv['OWENLOOP_TOKEN'];
291
+ err('owenloop work agent-run: OWENLOOP_TOKEN is set and is being IGNORED here. The dev-only ' +
292
+ 'bearer override is not passed to harness children, so honouring it would ' +
293
+ 'authenticate the worker and the harness child as different principals. ' +
294
+ 'Authenticate the account instead: `owenloop login --hub <origin> --as agent:<account>`.');
295
+ }
296
+ const account = workerEnv['OWENLOOP_ACCOUNT'] ?? 'default';
297
+ let hub = deps.hub;
298
+ if (hub === undefined) {
299
+ const bearer = await resolveBearer({ origin, account, env: workerEnv });
300
+ if (!bearer.ok) {
301
+ err(`owenloop work agent-run: ${bearer.message}`);
302
+ return bearer.code;
303
+ }
304
+ const token = bearer.token;
305
+ hub = createHubClient({ origin, getToken: async () => token });
306
+ }
307
+ const client = hub;
308
+ await loadHarnessModule(env['OWENLOOP_HARNESS_MODULE'], err);
309
+ const shiftId = resolveShiftId(parsed.shift, env);
310
+ const holder = {
311
+ kind: 'exec',
312
+ id: deps.holderId ?? `${hostname()}:${process.pid}`,
313
+ ...(shiftId !== undefined ? { shiftId } : {}),
314
+ };
315
+ /**
316
+ * Adapter id precedence: `--harness` > `OWENLOOP_HARNESS` > the step def's
317
+ * `harness` field > the first registered adapter. Every rank is a plain
318
+ * string comparison — nothing here knows what any id MEANS.
319
+ */
320
+ const envHarness = env['OWENLOOP_HARNESS'];
321
+ const resolveAdapter = (stepHarness) => {
322
+ const id = (parsed.harness !== undefined && parsed.harness !== '' ? parsed.harness : undefined) ??
323
+ (envHarness !== undefined && envHarness !== '' ? envHarness : undefined) ??
324
+ (stepHarness !== undefined && stepHarness !== '' ? stepHarness : undefined) ??
325
+ defaultHarnessId() ??
326
+ '';
327
+ const adapter = id !== '' ? adapterFor(id) : undefined;
328
+ return {
329
+ id: id !== '' ? id : '<none>',
330
+ ...(adapter !== undefined ? { adapter } : {}),
331
+ registered: registeredHarnessIds(),
332
+ };
333
+ };
334
+ /** Resolve the def name off the hub, then the cached step spec for the step. */
335
+ const loadStep = async (order) => {
336
+ const res = await client.whatsNext({ workflow: target.workflow });
337
+ const defName = res.def;
338
+ if (defName === undefined || defName === '') {
339
+ err(`owenloop work agent-run: whats_next reported no def for workflow '${target.workflow}'`);
340
+ return null;
341
+ }
342
+ const dispatch = readDispatchBundle(cacheDir, defName);
343
+ if (dispatch.warning !== undefined)
344
+ err(`owenloop work agent-run: ${dispatch.warning}`);
345
+ if (dispatch.bundle === null) {
346
+ err(`owenloop work agent-run: no cached bundle for def '${defName}' — run \`owenloop work prepare ${defName}\``);
347
+ return null;
348
+ }
349
+ const spec = readStepSpec(cacheDir, defName, dispatch.bundle.def.hash, order.step);
350
+ if (spec === null) {
351
+ err(`owenloop work agent-run: no step spec for '${order.step}' at ${dispatch.bundle.def.hash} — ` +
352
+ `re-run \`owenloop work prepare ${defName}\``);
353
+ return null;
354
+ }
355
+ return spec;
356
+ };
357
+ /**
358
+ * The session-store sink. `appendSession` PROPAGATES fs failures by design
359
+ * (see `src/harness/session-store.ts`), but the store is a resume convenience,
360
+ * not the lease — a full disk must not abort a run that is otherwise doing its
361
+ * job. So the role swallows the failure here, after reporting it, and the loop
362
+ * carries on. The lease, not this file, remains the record of truth.
363
+ */
364
+ const sessionsFile = sessionsPath(cacheDir);
365
+ const writeSession = (rec) => {
366
+ try {
367
+ appendSession(sessionsFile, rec, { warn: err });
368
+ }
369
+ catch (e) {
370
+ err(`owenloop work agent-run: could not record the session in ${sessionsFile}: ${errMsg(e)}`);
371
+ }
372
+ };
373
+ /**
374
+ * PHASE 4 — where the step agent works when the hub supplies no `workdir`.
375
+ *
376
+ * Precedence, highest first:
377
+ * 1. `deps.cwd` — the test seam. An injected cwd is an explicit instruction
378
+ * and must not be second-guessed by a settings key.
379
+ * 2. `<workRoot>/<workflow>/<run>/`, created here.
380
+ * 3. `process.cwd()`, if creating that directory fails.
381
+ *
382
+ * `OrderPacket.workdir` outranks all three, but it lives on the packet, which
383
+ * this role never sees — `src/agent/loop.ts` applies it over whatever is
384
+ * passed here.
385
+ *
386
+ * Created EAGERLY, before the first order arrives, because the loop takes a
387
+ * plain `cwd: string` and turning it into a thunk would push a filesystem
388
+ * concern into the pure orchestration core. The cost of being early is one
389
+ * empty directory for a run whose packets all carry a hub `workdir`; the
390
+ * reaper removes it on the same terms as any other.
391
+ */
392
+ let workCwd = deps.cwd ?? process.cwd();
393
+ if (deps.cwd === undefined) {
394
+ const workRoot = resolveWorkRoot(env, settings.workRoot, cacheDir);
395
+ const workRepo = resolveWorkRepo(env, settings.workRepo);
396
+ try {
397
+ workCwd = ensureWorkDir({
398
+ workRoot,
399
+ workflow: target.workflow,
400
+ run: target.run,
401
+ ...(workRepo !== undefined ? { workRepo } : {}),
402
+ err,
403
+ });
404
+ }
405
+ catch (e) {
406
+ err(`owenloop work agent-run: could not create a work directory under ${workRoot}: ${errMsg(e)} — ` +
407
+ `falling back to ${workCwd}`);
408
+ }
409
+ }
410
+ const loop = createAgentRunLoop({
411
+ hub: client,
412
+ workflow: target.workflow,
413
+ run: target.run,
414
+ holder,
415
+ origin,
416
+ account,
417
+ ...(shiftId !== undefined ? { shiftId } : {}),
418
+ cwd: workCwd,
419
+ loadStep,
420
+ resolveAdapter,
421
+ appendSession: writeSession,
422
+ nextAttempt: (workflow, run, step) => {
423
+ const prev = latestFor(sessionsFile, workflow, run, step);
424
+ return prev === null ? 1 : prev.attempt + 1;
425
+ },
426
+ // PHASE 4: the same reader `nextAttempt` uses, handed to the loop whole so
427
+ // it can decide resume vs cold replay. Reads only; the loop is what writes.
428
+ latestSession: (workflow, run, step) => latestFor(sessionsFile, workflow, run, step),
429
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
430
+ now: () => Date.now(),
431
+ out,
432
+ err,
433
+ heartbeatIntervalMs: parsed.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS,
434
+ // Test affordances only: each exposes an existing knob (defaults unchanged)
435
+ // so a drill can provoke a clock jump or a short confirm without waiting.
436
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
437
+ ...(parsed.submitGraceMs !== undefined ? { submitGraceMs: parsed.submitGraceMs } : {}),
438
+ ...(parsed.confirmIntervalMs !== undefined ? { confirmIntervalMs: parsed.confirmIntervalMs } : {}),
439
+ });
440
+ installSignalHandlers(loop, deps.signalHost ?? process, err, {
441
+ role: 'agent-run',
442
+ drainNote: 'stopping the step agent and releasing the order',
443
+ stopReason: 'signal',
444
+ });
445
+ const outcome = await loop.run();
446
+ return exitCodeFor(outcome);
447
+ }
@@ -0,0 +1,40 @@
1
+ import { type HubClient } from '../hub/client.ts';
2
+ import { type ExecOutcome } from '../exec/loop.ts';
3
+ import { type CommandRunner } from '../exec/runner.ts';
4
+ import { type SignalHost } from './signals.ts';
5
+ interface ParsedArgs {
6
+ orderId?: string;
7
+ workflow?: string;
8
+ origin?: string;
9
+ shift?: string;
10
+ heartbeatIntervalMs?: number;
11
+ jumpToleranceMs?: number;
12
+ error?: string;
13
+ }
14
+ /**
15
+ * Parse the positional `<order-id>` plus `--workflow`/`--origin`/
16
+ * `--heartbeat-interval`/`--jump-tolerance`. Supports `--flag value` and
17
+ * `--flag=value`; a second positional or an unknown flag is an error.
18
+ */
19
+ export declare function parseArgs(args: string[]): ParsedArgs;
20
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
21
+ export declare function exitCodeFor(outcome: ExecOutcome): number;
22
+ /**
23
+ * Injectable process-boundary deps for `run` — defaulting to the real ones, so
24
+ * the role wiring (holder tag, signal handlers, outcome mapping) is testable
25
+ * without spawning a real child, signaling the test process, or reaching a real
26
+ * hub.
27
+ */
28
+ export interface RunDeps {
29
+ signalHost?: SignalHost;
30
+ hub?: HubClient;
31
+ runner?: CommandRunner;
32
+ out?: (line: string) => void;
33
+ err?: (line: string) => void;
34
+ /** cwd for a command order that carries no `workdir` (default `process.cwd()`). */
35
+ cwd?: string;
36
+ /** Holder id override (default `<hostname>:<pid>`) — pinned in tests. */
37
+ holderId?: string;
38
+ }
39
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
40
+ export {};