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,203 @@
1
+ /**
2
+ * `owenloop work exec <order-id>` (C5) — the detached, self-leasing command worker.
3
+ *
4
+ * The shift (C3) spawns one detached `owenloop work exec <workflow>/<run> --origin
5
+ * <url>` per COMMAND order. This process owns that order end to end: it takes the
6
+ * lease on first contact, keeps it warm while it shells the order's `command`
7
+ * out, and submits a receipt to every owed output path — then exits. It is the
8
+ * one process in the system that actually executes an order's command string.
9
+ *
10
+ * The orchestration CORE lives in `src/exec/loop.ts` (lease + runner + receipt,
11
+ * every side effect injected); this role only parses the arg contract, resolves
12
+ * origin/token, builds the real hub client + default runner, tags the exec
13
+ * holder identity, wires the signal seam, and maps the loop's `ExecOutcome` to an
14
+ * exit code.
15
+ *
16
+ * ORDER ID: a positional `<workflow>/<run>` composite (or a bare `<run>` plus
17
+ * `--workflow <wf>`), resolved by the same `resolveTarget` `hold` uses. The shift
18
+ * always emits the composite form.
19
+ *
20
+ * HOLDER IDENTITY: every get_order/heartbeat rides the B3 holder tag
21
+ * `{kind:'exec', id}` where id is `<hostname>:<pid>`. `kind:'exec'` is the drain
22
+ * exemption (B3/C6): an exec-held claim survives a SESSION drain — only a signal
23
+ * aimed at THIS process hands the order back. `--shift <cid>` (env fallback
24
+ * `OWENLOOP_SHIFT_ID`), when known, rides along on the holder as
25
+ * `shiftId` — self-declared and advisory only (D8/INV-82).
26
+ *
27
+ * Origin/credential resolution mirrors `hold`/`shift`: origin `--origin` →
28
+ * settings; the bearer comes from owenloop's store via `resolveBearer`, reading
29
+ * the `agent:<account>` slot for the account the shift set in this child's
30
+ * `OWENLOOP_ACCOUNT` spawn env (default `default`), with `OWENLOOP_TOKEN` as a
31
+ * documented dev-only override. Exec has NO `--as` flag — the spawn-env channel
32
+ * is the contract. Exit codes are documented in `src/usage.ts`.
33
+ */
34
+ import { hostname } from 'node:os';
35
+ import { createHubClient } from "../hub/client.js";
36
+ import { resolveBearer } from "../credentials/resolve.js";
37
+ import { loadSettings } from "../settings/settings.js";
38
+ import { createExecLoop } from "../exec/loop.js";
39
+ import { createDefaultRunner } from "../exec/runner.js";
40
+ import { resolveShiftId, resolveTarget } from "./hold.js";
41
+ import { installSignalHandlers } from "./signals.js";
42
+ const DEFAULT_INTERVAL_MS = 60_000;
43
+ /**
44
+ * Parse the positional `<order-id>` plus `--workflow`/`--origin`/
45
+ * `--heartbeat-interval`/`--jump-tolerance`. Supports `--flag value` and
46
+ * `--flag=value`; a second positional or an unknown flag is an error.
47
+ */
48
+ export function parseArgs(args) {
49
+ const parsed = {};
50
+ const takeValue = (a, i) => {
51
+ const eq = a.indexOf('=');
52
+ if (eq !== -1)
53
+ return { value: a.slice(eq + 1), next: i };
54
+ const v = args[i + 1];
55
+ if (v === undefined)
56
+ return { error: `missing value for ${a}` };
57
+ return { value: v, next: i + 1 };
58
+ };
59
+ for (let i = 0; i < args.length; i++) {
60
+ const a = args[i];
61
+ if (!a.startsWith('-')) {
62
+ if (parsed.orderId !== undefined)
63
+ return { error: `unexpected extra argument '${a}'` };
64
+ parsed.orderId = a;
65
+ continue;
66
+ }
67
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
68
+ switch (name) {
69
+ case '--workflow':
70
+ case '--origin':
71
+ case '--shift':
72
+ case '--heartbeat-interval':
73
+ case '--jump-tolerance': {
74
+ const r = takeValue(a, i);
75
+ if ('error' in r)
76
+ return { error: r.error };
77
+ i = r.next;
78
+ if (name === '--workflow')
79
+ parsed.workflow = r.value;
80
+ else if (name === '--origin')
81
+ parsed.origin = r.value;
82
+ else if (name === '--shift')
83
+ parsed.shift = r.value;
84
+ else if (name === '--heartbeat-interval') {
85
+ const n = Number(r.value);
86
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
87
+ return { error: `--heartbeat-interval must be a positive integer, got '${r.value}'` };
88
+ }
89
+ parsed.heartbeatIntervalMs = n;
90
+ }
91
+ else if (name === '--jump-tolerance') {
92
+ const n = Number(r.value);
93
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
94
+ return { error: `--jump-tolerance must be a positive integer, got '${r.value}'` };
95
+ }
96
+ parsed.jumpToleranceMs = n;
97
+ }
98
+ break;
99
+ }
100
+ default:
101
+ return { error: `unknown option '${a}'` };
102
+ }
103
+ }
104
+ return parsed;
105
+ }
106
+ function usage() {
107
+ process.stderr.write('usage: owenloop work exec <workflow>/<run> [--origin <url>] [--shift <id>] [--heartbeat-interval <ms>] [--jump-tolerance <ms>]\n' +
108
+ ' or: owenloop work exec <run> --workflow <wf> [...]\n');
109
+ }
110
+ function errMsg(err) {
111
+ return err instanceof Error ? err.message : String(err);
112
+ }
113
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
114
+ export function exitCodeFor(outcome) {
115
+ switch (outcome) {
116
+ case 'submitted':
117
+ case 'completed':
118
+ return 0;
119
+ case 'misroute':
120
+ case 'killed':
121
+ case 'lease-lost':
122
+ case 'ownership-error':
123
+ case 'hub-unreachable':
124
+ case 'submit-rejected':
125
+ case 'submit-failed':
126
+ case 'stopped':
127
+ return 1;
128
+ }
129
+ }
130
+ export async function run(args, deps = {}) {
131
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
132
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
133
+ const parsed = parseArgs(args);
134
+ if (parsed.error !== undefined) {
135
+ err(`owenloop work exec: ${parsed.error}`);
136
+ usage();
137
+ return 2;
138
+ }
139
+ if (parsed.orderId === undefined || parsed.orderId === '') {
140
+ err('owenloop work exec: missing required <order-id>');
141
+ usage();
142
+ return 2;
143
+ }
144
+ const target = resolveTarget(parsed.orderId, parsed.workflow);
145
+ if ('error' in target) {
146
+ err(`owenloop work exec: ${target.error}`);
147
+ usage();
148
+ return 2;
149
+ }
150
+ const env = process.env;
151
+ let settings;
152
+ try {
153
+ settings = loadSettings(env);
154
+ }
155
+ catch (e) {
156
+ err(`owenloop work exec: ${errMsg(e)}`);
157
+ return 1;
158
+ }
159
+ const origin = parsed.origin ?? settings.hubOrigin;
160
+ if (origin === undefined || origin.trim() === '') {
161
+ err('owenloop work exec: no hub origin — pass --origin <url> or set hubOrigin in settings');
162
+ return 2;
163
+ }
164
+ const account = env['OWENLOOP_ACCOUNT'] ?? 'default';
165
+ const bearer = await resolveBearer({ origin, account, env });
166
+ if (!bearer.ok) {
167
+ err(`owenloop work exec: ${bearer.message}`);
168
+ return bearer.code;
169
+ }
170
+ const token = bearer.token;
171
+ const shiftId = resolveShiftId(parsed.shift, env);
172
+ const holder = {
173
+ kind: 'exec',
174
+ id: deps.holderId ?? `${hostname()}:${process.pid}`,
175
+ ...(shiftId !== undefined ? { shiftId } : {}),
176
+ };
177
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
178
+ const runner = deps.runner ?? createDefaultRunner();
179
+ const loop = createExecLoop({
180
+ hub,
181
+ runner,
182
+ workflow: target.workflow,
183
+ run: target.run,
184
+ holder,
185
+ cwd: deps.cwd ?? process.cwd(),
186
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
187
+ now: () => Date.now(),
188
+ out,
189
+ err,
190
+ heartbeatIntervalMs: parsed.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS,
191
+ // Test affordance only: exposes the lease loop's existing jumpToleranceMs
192
+ // knob (default unchanged) so a drill can trip the clock-jump lease check
193
+ // with a short freeze instead of a real >30s laptop sleep.
194
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
195
+ });
196
+ installSignalHandlers(loop, deps.signalHost ?? process, err, {
197
+ role: 'exec',
198
+ drainNote: 'killing the command and releasing the order',
199
+ stopReason: 'signal',
200
+ });
201
+ const outcome = await loop.run();
202
+ return exitCodeFor(outcome);
203
+ }
@@ -0,0 +1,68 @@
1
+ import { type HubClient } from '../hub/client.ts';
2
+ import { type HoldOutcome } from '../hold/loop.ts';
3
+ import type { ContactHolder } from '../hub/types.ts';
4
+ import { type SignalHost, type StdinHost } from './signals.ts';
5
+ interface ParsedArgs {
6
+ order?: string;
7
+ workflow?: string;
8
+ session?: string;
9
+ origin?: string;
10
+ as?: string;
11
+ shift?: string;
12
+ heartbeatIntervalMs?: number;
13
+ jumpToleranceMs?: number;
14
+ ignoreStdin: boolean;
15
+ mcp: boolean;
16
+ error?: string;
17
+ }
18
+ /** Parse `--flag value` and `--flag=value`; unknown flags are an error. */
19
+ export declare function parseArgs(args: string[]): ParsedArgs;
20
+ /**
21
+ * Resolve (workflow, run) from `--order` (+ optional `--workflow`).
22
+ * - composite `<workflow>/<run>`: split on the FIRST `/` only (run ids must
23
+ * not be silently truncated). A conflicting `--workflow` is a usage error.
24
+ * - bare `<run>`: requires `--workflow`.
25
+ */
26
+ export declare function resolveTarget(order: string, workflowFlag?: string): {
27
+ workflow: string;
28
+ run: string;
29
+ } | {
30
+ error: string;
31
+ };
32
+ /**
33
+ * Resolve the born-bound `--shift` cid: explicit `--shift`, else env
34
+ * `OWENLOOP_SHIFT_ID`, else `undefined` (no cid known — a hand-run hold
35
+ * with no stamped/exported cid). Advisory only (D8/INV-82).
36
+ */
37
+ export declare function resolveShiftId(shift: string | undefined, env: Record<string, string | undefined>): string | undefined;
38
+ /**
39
+ * Resolve the B3 session-holder tag (D5): explicit `--session`, else env
40
+ * `OWENLOOP_SESSION`, else a per-process fallback `anon:<hostname>:<pid>` —
41
+ * NEVER undefined. The fallback is deliberately unique per process (not a
42
+ * shared constant like `'anon'`): `release --session <id>` drains match on
43
+ * session id, and a shared constant would let unrelated Shifts' claims
44
+ * collide in a drain. `opts.shiftId` rides along on the holder when known
45
+ * (advisory only, D8/INV-82); `opts.hostname`/`opts.pid` are test seams.
46
+ */
47
+ export declare function resolveHolder(session: string | undefined, env: Record<string, string | undefined>, opts?: {
48
+ shiftId?: string;
49
+ hostname?: string;
50
+ pid?: number;
51
+ }): ContactHolder;
52
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
53
+ export declare function exitCodeFor(outcome: HoldOutcome): number;
54
+ /**
55
+ * Injectable process-boundary deps for `run` — defaulting to the real ones.
56
+ * Mirrors the loop's injected-seams pattern so the ROLE wiring (signal
57
+ * handlers, stdin-EOF watcher, message lines) is testable without signaling
58
+ * the test process, closing real stdin, or reaching a real hub.
59
+ */
60
+ export interface RunDeps {
61
+ signalHost?: SignalHost;
62
+ stdin?: StdinHost;
63
+ hub?: HubClient;
64
+ out?: (line: string) => void;
65
+ err?: (line: string) => void;
66
+ }
67
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
68
+ export {};
@@ -0,0 +1,324 @@
1
+ /**
2
+ * `owenloop work hold --order <id>` (C4) — keeps one order's lease alive on behalf
3
+ * of an interactive session and performs the final-breath handoff when that
4
+ * session goes away.
5
+ *
6
+ * It heartbeats the order's lease on a safe cadence (default 60s — well inside
7
+ * the hub's reap TTL; no verb exposes the TTL, so the cadence is a client
8
+ * constant) with jitter/backoff on transient failures, and on SIGINT, SIGTERM,
9
+ * or stdin EOF performs a targeted `release` so the order re-offers immediately
10
+ * instead of stranding until its lease expires. The loop CORE lives in
11
+ * `src/hold/loop.ts` with every side effect injected; this role parses flags,
12
+ * resolves origin/token, builds the real hub client, wires the signal + stdin
13
+ * seams (`src/roles/signals.ts`), and maps the loop's `HoldOutcome` to an exit
14
+ * code.
15
+ *
16
+ * SESSION IDENTITY: `--session <id>` (env fallback `OWENLOOP_SESSION`) rides
17
+ * every get_order/heartbeat as the B3 holder tag `{kind:'session', id}`. A
18
+ * holder is now ALWAYS sent (D5): when no session id is configured, `id`
19
+ * falls back to `anon:<hostname>:<pid>` — never omitted. Only `kind:'session'`
20
+ * — exec identity is C5's.
21
+ *
22
+ * SHIFT ATTRIBUTION: `--shift <cid>` (env fallback
23
+ * `OWENLOOP_SHIFT_ID`), when known, rides along on the holder as
24
+ * `shiftId` — self-declared and advisory only (D8/INV-82), never used for
25
+ * authorization, routing, dispatch, or claim correctness.
26
+ *
27
+ * STDIN EOF: a live stdin pipe closing means the parent interactive session
28
+ * died, so hold takes its final breath. When stdin is `/dev/null` or already
29
+ * closed at spawn (backgrounded/detached use), pass `--ignore-stdin` so hold
30
+ * does not final-breath at birth.
31
+ *
32
+ * Origin/credential resolution mirrors `shift`: origin `--origin` → settings;
33
+ * the bearer comes from owenloop's store via `resolveBearer`, reading the
34
+ * `agent:<account>` slot for `--as <account>` (default `default`, so a hand-run
35
+ * hold and a shift-stamped `hold --as <account>` both work), with
36
+ * `OWENLOOP_TOKEN` as a documented dev-only override. Exit codes are documented
37
+ * in `src/usage.ts`.
38
+ */
39
+ import { hostname } from 'node:os';
40
+ import { createHubClient } from "../hub/client.js";
41
+ import { resolveBearer } from "../credentials/resolve.js";
42
+ import { loadSettings } from "../settings/settings.js";
43
+ import { createHoldLoop } from "../hold/loop.js";
44
+ import { createHoldMcp } from "../hold/mcp.js";
45
+ import { createMcpServer, pumpStdin } from "../mcp/server.js";
46
+ import { installSignalHandlers, watchStdinEof } from "./signals.js";
47
+ const DEFAULT_INTERVAL_MS = 60_000;
48
+ // Deliberate duplicate of main.ts's VERSION (also '0.0.0'): the roles must not
49
+ // import the CLI entry module, and the MCP serverInfo version is cosmetic.
50
+ const VERSION = '0.0.0';
51
+ /** Parse `--flag value` and `--flag=value`; unknown flags are an error. */
52
+ export function parseArgs(args) {
53
+ const parsed = { ignoreStdin: false, mcp: false };
54
+ const takeValue = (a, i) => {
55
+ const eq = a.indexOf('=');
56
+ if (eq !== -1)
57
+ return { value: a.slice(eq + 1), next: i };
58
+ const v = args[i + 1];
59
+ if (v === undefined)
60
+ return { error: `missing value for ${a}` };
61
+ return { value: v, next: i + 1 };
62
+ };
63
+ for (let i = 0; i < args.length; i++) {
64
+ const a = args[i];
65
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
66
+ switch (name) {
67
+ case '--ignore-stdin':
68
+ parsed.ignoreStdin = true;
69
+ break;
70
+ case '--mcp':
71
+ parsed.mcp = true;
72
+ break;
73
+ case '--order':
74
+ case '--workflow':
75
+ case '--session':
76
+ case '--origin':
77
+ case '--as':
78
+ case '--shift':
79
+ case '--heartbeat-interval':
80
+ case '--jump-tolerance': {
81
+ const r = takeValue(a, i);
82
+ if ('error' in r)
83
+ return { ignoreStdin: false, mcp: false, error: r.error };
84
+ i = r.next;
85
+ if (name === '--order')
86
+ parsed.order = r.value;
87
+ else if (name === '--workflow')
88
+ parsed.workflow = r.value;
89
+ else if (name === '--session')
90
+ parsed.session = r.value;
91
+ else if (name === '--origin')
92
+ parsed.origin = r.value;
93
+ else if (name === '--as')
94
+ parsed.as = r.value;
95
+ else if (name === '--shift')
96
+ parsed.shift = r.value;
97
+ else if (name === '--heartbeat-interval') {
98
+ const n = Number(r.value);
99
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
100
+ return { ignoreStdin: false, mcp: false, error: `--heartbeat-interval must be a positive integer, got '${r.value}'` };
101
+ }
102
+ parsed.heartbeatIntervalMs = n;
103
+ }
104
+ else if (name === '--jump-tolerance') {
105
+ const n = Number(r.value);
106
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
107
+ return { ignoreStdin: false, mcp: false, error: `--jump-tolerance must be a positive integer, got '${r.value}'` };
108
+ }
109
+ parsed.jumpToleranceMs = n;
110
+ }
111
+ break;
112
+ }
113
+ default:
114
+ return { ignoreStdin: false, mcp: false, error: `unknown option '${a}'` };
115
+ }
116
+ }
117
+ return parsed;
118
+ }
119
+ /** Both accepted `--order` forms, for usage messages. */
120
+ const ORDER_FORMS = '--order <workflow>/<run> (or --order <run> --workflow <wf>)';
121
+ /**
122
+ * Resolve (workflow, run) from `--order` (+ optional `--workflow`).
123
+ * - composite `<workflow>/<run>`: split on the FIRST `/` only (run ids must
124
+ * not be silently truncated). A conflicting `--workflow` is a usage error.
125
+ * - bare `<run>`: requires `--workflow`.
126
+ */
127
+ export function resolveTarget(order, workflowFlag) {
128
+ const slash = order.indexOf('/');
129
+ if (slash !== -1) {
130
+ const workflow = order.slice(0, slash);
131
+ const run = order.slice(slash + 1);
132
+ if (workflow === '' || run === '') {
133
+ return { error: `--order '${order}' is malformed — expected ${ORDER_FORMS}` };
134
+ }
135
+ if (workflowFlag !== undefined && workflowFlag !== workflow) {
136
+ return { error: `--order carries workflow '${workflow}' but --workflow says '${workflowFlag}' — drop one` };
137
+ }
138
+ return { workflow, run };
139
+ }
140
+ if (workflowFlag === undefined || workflowFlag === '') {
141
+ return { error: `--order '${order}' has no workflow — use ${ORDER_FORMS}` };
142
+ }
143
+ return { workflow: workflowFlag, run: order };
144
+ }
145
+ function usage() {
146
+ process.stderr.write('usage: owenloop work hold --order <workflow>/<run> [--origin <url>] [--as <account>] [--session <id>]\n' +
147
+ ' [--shift <id>] [--heartbeat-interval <ms>] [--jump-tolerance <ms>] [--ignore-stdin] [--mcp]\n' +
148
+ ' or: owenloop work hold --order <run> --workflow <wf> [...]\n');
149
+ }
150
+ function errMsg(err) {
151
+ return err instanceof Error ? err.message : String(err);
152
+ }
153
+ /**
154
+ * Resolve the born-bound `--shift` cid: explicit `--shift`, else env
155
+ * `OWENLOOP_SHIFT_ID`, else `undefined` (no cid known — a hand-run hold
156
+ * with no stamped/exported cid). Advisory only (D8/INV-82).
157
+ */
158
+ export function resolveShiftId(shift, env) {
159
+ const id = shift ?? env['OWENLOOP_SHIFT_ID'];
160
+ return id !== undefined && id !== '' ? id : undefined;
161
+ }
162
+ /**
163
+ * Resolve the B3 session-holder tag (D5): explicit `--session`, else env
164
+ * `OWENLOOP_SESSION`, else a per-process fallback `anon:<hostname>:<pid>` —
165
+ * NEVER undefined. The fallback is deliberately unique per process (not a
166
+ * shared constant like `'anon'`): `release --session <id>` drains match on
167
+ * session id, and a shared constant would let unrelated Shifts' claims
168
+ * collide in a drain. `opts.shiftId` rides along on the holder when known
169
+ * (advisory only, D8/INV-82); `opts.hostname`/`opts.pid` are test seams.
170
+ */
171
+ export function resolveHolder(session, env, opts = {}) {
172
+ const configured = session ?? env['OWENLOOP_SESSION'];
173
+ const id = configured !== undefined && configured !== '' ? configured : `anon:${opts.hostname ?? hostname()}:${opts.pid ?? process.pid}`;
174
+ return {
175
+ kind: 'session',
176
+ id,
177
+ ...(opts.shiftId !== undefined ? { shiftId: opts.shiftId } : {}),
178
+ };
179
+ }
180
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
181
+ export function exitCodeFor(outcome) {
182
+ switch (outcome) {
183
+ case 'completed':
184
+ case 'released':
185
+ case 'stopped':
186
+ return 0;
187
+ case 'ownership-error':
188
+ case 'lease-lost':
189
+ case 'hub-unreachable':
190
+ case 'release-failed':
191
+ return 1;
192
+ }
193
+ }
194
+ export async function run(args, deps = {}) {
195
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
196
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
197
+ const parsed = parseArgs(args);
198
+ if (parsed.error !== undefined) {
199
+ err(`owenloop work hold: ${parsed.error}`);
200
+ usage();
201
+ return 2;
202
+ }
203
+ if (parsed.order === undefined || parsed.order === '') {
204
+ err('owenloop work hold: missing required --order <id>');
205
+ usage();
206
+ return 2;
207
+ }
208
+ // In --mcp mode stdin IS the JSON-RPC transport; its EOF is the session-death
209
+ // signal that fires the final breath. --ignore-stdin (don't watch stdin) is
210
+ // therefore contradictory.
211
+ if (parsed.mcp && parsed.ignoreStdin) {
212
+ err('owenloop work hold: --mcp and --ignore-stdin are mutually exclusive (stdin is the MCP transport)');
213
+ usage();
214
+ return 2;
215
+ }
216
+ const target = resolveTarget(parsed.order, parsed.workflow);
217
+ if ('error' in target) {
218
+ err(`owenloop work hold: ${target.error}`);
219
+ usage();
220
+ return 2;
221
+ }
222
+ const env = process.env;
223
+ let settings;
224
+ try {
225
+ settings = loadSettings(env);
226
+ }
227
+ catch (e) {
228
+ err(`owenloop work hold: ${errMsg(e)}`);
229
+ return 1;
230
+ }
231
+ const origin = parsed.origin ?? settings.hubOrigin;
232
+ if (origin === undefined || origin.trim() === '') {
233
+ err('owenloop work hold: no hub origin — pass --origin <url> or set hubOrigin in settings');
234
+ return 2;
235
+ }
236
+ if (parsed.as !== undefined && parsed.as.trim() === '') {
237
+ err('owenloop work hold: --as requires a non-empty account name');
238
+ return 2;
239
+ }
240
+ const account = parsed.as ?? 'default';
241
+ const bearer = await resolveBearer({ origin, account, env });
242
+ if (!bearer.ok) {
243
+ err(`owenloop work hold: ${bearer.message}`);
244
+ return bearer.code;
245
+ }
246
+ const token = bearer.token;
247
+ const shiftId = resolveShiftId(parsed.shift, env);
248
+ const holder = resolveHolder(parsed.session, env, { shiftId });
249
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
250
+ // --mcp: run the born-bound work-holder as a stdio MCP server (get_order /
251
+ // submit) with the lease loop kept warm underneath. stdout is the JSON-RPC
252
+ // channel, so every diagnostic (and the loop's own lines) goes to stderr;
253
+ // stdin is the transport, and its EOF (the session died) fires the final
254
+ // breath.
255
+ if (parsed.mcp) {
256
+ const mount = createHoldMcp({
257
+ hub,
258
+ workflow: target.workflow,
259
+ run: target.run,
260
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
261
+ now: () => Date.now(),
262
+ err,
263
+ holder,
264
+ ...(parsed.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: parsed.heartbeatIntervalMs } : {}),
265
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
266
+ });
267
+ const server = createMcpServer({
268
+ name: 'owenloop-hold',
269
+ version: VERSION,
270
+ tools: mount.tools,
271
+ write: (msg) => void process.stdout.write(`${JSON.stringify(msg)}\n`),
272
+ err,
273
+ });
274
+ installSignalHandlers(mount.loop, deps.signalHost ?? process, err, {
275
+ role: 'hold',
276
+ drainNote: 'final breath',
277
+ stopReason: 'signal',
278
+ });
279
+ // The MCP server must keep answering until the TRANSPORT ends, not until
280
+ // the lease loop does (plan section 4): a submit that closes the run
281
+ // terminates the loop, but the submit's own response frame may still be
282
+ // racing down the stdout pipe and the client may issue further calls (they
283
+ // fast-fail via the mount's terminal guard). So: stdin EOF is both the
284
+ // final-breath trigger AND the exit condition; the loop's outcome only
285
+ // decides the exit code. A signal stops the loop early too — the process
286
+ // then serves fast-fails until the parent closes the pipe (a second signal
287
+ // still hard-exits via installSignalHandlers).
288
+ const stdin = (deps.stdin ?? process.stdin);
289
+ const eof = new Promise((resolve) => {
290
+ pumpStdin(stdin, server, () => {
291
+ mount.loop.stop('stdin-eof');
292
+ resolve();
293
+ });
294
+ });
295
+ const outcome = await mount.loop.run();
296
+ await eof;
297
+ return exitCodeFor(outcome);
298
+ }
299
+ const loop = createHoldLoop({
300
+ hub,
301
+ workflow: target.workflow,
302
+ run: target.run,
303
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
304
+ now: () => Date.now(),
305
+ out,
306
+ err,
307
+ heartbeatIntervalMs: parsed.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS,
308
+ // Test affordance only: exposes the lease loop's existing jumpToleranceMs
309
+ // knob (default unchanged) so a drill can trip the clock-jump lease check
310
+ // with a short freeze instead of a real >30s laptop sleep.
311
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
312
+ holder,
313
+ });
314
+ installSignalHandlers(loop, deps.signalHost ?? process, err, {
315
+ role: 'hold',
316
+ drainNote: 'final breath',
317
+ stopReason: 'signal',
318
+ });
319
+ if (!parsed.ignoreStdin) {
320
+ watchStdinEof(deps.stdin ?? process.stdin, () => loop.stop('stdin-eof'));
321
+ }
322
+ const outcome = await loop.run();
323
+ return exitCodeFor(outcome);
324
+ }
@@ -0,0 +1,18 @@
1
+ import type { Keychain } from '../../../../src/hub.ts';
2
+ interface ParsedArgs {
3
+ code?: string;
4
+ hub?: string;
5
+ as?: string;
6
+ error?: string;
7
+ }
8
+ /** Parse `<code> [--hub <origin>] [--as <account>]`, both `--flag value` and `--flag=value` forms. */
9
+ export declare function parseArgs(args: string[]): ParsedArgs;
10
+ export interface RunDeps {
11
+ out?: (line: string) => void;
12
+ err?: (line: string) => void;
13
+ env?: Record<string, string | undefined>;
14
+ fetchImpl?: typeof fetch;
15
+ keychain?: Keychain;
16
+ }
17
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
18
+ export {};