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,249 @@
1
+ /**
2
+ * `owenloop work prepare <workflow> [--origin <url>]` — fetch a published workflow
3
+ * def from the hub, cache it by content hash, and normalize each agent step
4
+ * into a harness-neutral `steps/<step>.json` spec. Then prune superseded cache
5
+ * revisions.
6
+ *
7
+ * NORMALIZED, NOT COMPILED (Phase 5 / D4): prepare no longer renders any
8
+ * harness-specific artifact. Per agent step it writes a `NormalizedStepSpec` —
9
+ * the step body verbatim as `brief`, the declared harness id, and
10
+ * `normalizeStepPermissions(step.harnessOptions, step)`. The four substitution
11
+ * tokens and the owenloop MCP mount are NOT baked in; `src/agent/brief.ts`
12
+ * builds those at run time from the live order, so a bundle is order-independent
13
+ * and reusable across every order of that step.
14
+ *
15
+ * HASH-PINNED CHILDREN (E): when the fetched parent pins its `calls:` children
16
+ * (the wire carries `pins` + a flat hash-keyed `children` map — see
17
+ * bundle/fetch.ts), the SAME round-trip brings the frozen child closure. prepare
18
+ * caches each child (and grandchild — the map is flat) as its OWN bundle at
19
+ * `bundles/<childName>/<childHash>/`, persists the parent WITH its `pins` but
20
+ * WITHOUT the children map (DD-2), and prunes pin-aware so a superseded-but-still-
21
+ * pinned hash survives (DD-3). An UNPINNED calls step (pre-feature publish) keeps
22
+ * a visible "not pinned" gap line.
23
+ *
24
+ * Resolution (D4/D5):
25
+ * origin — `--origin` flag → `settings.hubOrigin` → usage error (exit 2)
26
+ * bearer — owenloop's store via `resolveBearer`: the `agent:<account>` slot for
27
+ * `OWENLOOP_ACCOUNT` (default `default`), with `OWENLOOP_TOKEN` as a
28
+ * documented dev-only override. A missing Scoped Identity key is a refuse
29
+ * (exit 2) naming the origin + a runnable `owenloop login` command. prepare
30
+ * has no `--as` flag — a Shift sets `OWENLOOP_ACCOUNT` for a
31
+ * non-default account.
32
+ * cache — `OWENLOOP_CACHE_DIR` env → `settings.cacheDir` → XDG default.
33
+ *
34
+ * Exit codes: 0 ok · 1 runtime failure (fetch/hub-gap/cache write) · 2 usage.
35
+ * prepare is the entry point, NOT fail-open: a real fetch or cache error surfaces.
36
+ */
37
+ import { fetchDef } from "../bundle/fetch.js";
38
+ import { resolveBearer } from "../credentials/resolve.js";
39
+ import { readBundle, resolveCacheDir, pruneSupersededHashes, writeBundle } from "../bundle/cache.js";
40
+ import { normalizeStepPermissions } from "../harness/permissions.js";
41
+ import { loadSettings } from "../settings/settings.js";
42
+ import { HubError } from "../hub/types.js";
43
+ function parseArgs(args) {
44
+ let workflow;
45
+ let origin;
46
+ for (let i = 0; i < args.length; i++) {
47
+ const a = args[i];
48
+ if (a === '--origin') {
49
+ const v = args[i + 1];
50
+ if (v === undefined)
51
+ return { error: 'missing value for --origin' };
52
+ origin = v;
53
+ i++;
54
+ }
55
+ else if (a.startsWith('--origin=')) {
56
+ origin = a.slice('--origin='.length);
57
+ }
58
+ else if (a.startsWith('-')) {
59
+ return { error: `unknown option '${a}'` };
60
+ }
61
+ else if (workflow === undefined) {
62
+ workflow = a;
63
+ }
64
+ else {
65
+ return { error: `unexpected argument '${a}'` };
66
+ }
67
+ }
68
+ return { workflow, origin };
69
+ }
70
+ export async function run(args) {
71
+ const parsed = parseArgs(args);
72
+ if (parsed.error !== undefined) {
73
+ process.stderr.write(`owenloop work prepare: ${parsed.error}\n`);
74
+ process.stderr.write('usage: owenloop work prepare <workflow> [--origin <url>]\n');
75
+ return 2;
76
+ }
77
+ if (parsed.workflow === undefined) {
78
+ process.stderr.write('owenloop work prepare: missing required <workflow>\n');
79
+ process.stderr.write('usage: owenloop work prepare <workflow> [--origin <url>]\n');
80
+ return 2;
81
+ }
82
+ const workflow = parsed.workflow;
83
+ const env = process.env;
84
+ let settings;
85
+ try {
86
+ settings = loadSettings(env);
87
+ }
88
+ catch (err) {
89
+ process.stderr.write(`owenloop work prepare: ${errMsg(err)}\n`);
90
+ return 1;
91
+ }
92
+ const origin = parsed.origin ?? settings.hubOrigin;
93
+ if (origin === undefined || origin.trim() === '') {
94
+ process.stderr.write('owenloop work prepare: no hub origin — pass --origin <url> or set hubOrigin in settings\n');
95
+ return 2;
96
+ }
97
+ const account = env['OWENLOOP_ACCOUNT'] ?? 'default';
98
+ const bearer = await resolveBearer({ origin, account, env });
99
+ if (!bearer.ok) {
100
+ process.stderr.write(`owenloop work prepare: ${bearer.message}\n`);
101
+ return bearer.code;
102
+ }
103
+ const token = bearer.token;
104
+ let cacheDir;
105
+ try {
106
+ cacheDir = resolveCacheDir(env, settings.cacheDir);
107
+ }
108
+ catch (err) {
109
+ process.stderr.write(`owenloop work prepare: ${errMsg(err)}\n`);
110
+ return 1;
111
+ }
112
+ // Fetch + validate (throws HubError on non-2xx, Error on the D1 hub gap).
113
+ let def;
114
+ try {
115
+ def = await fetchDef({ origin, name: workflow, getToken: async () => token });
116
+ }
117
+ catch (err) {
118
+ if (err instanceof HubError) {
119
+ process.stderr.write(`owenloop work prepare: hub error ${err.status}: ${err.message}\n`);
120
+ }
121
+ else {
122
+ process.stderr.write(`owenloop work prepare: ${errMsg(err)}\n`);
123
+ }
124
+ return 1;
125
+ }
126
+ const out = process.stdout;
127
+ out.write(`prepare ${workflow} @ ${origin}\n`);
128
+ out.write(` def hash ${def.hash}${def.version !== undefined ? ` (version ${def.version})` : ''}\n`);
129
+ const already = readBundle(cacheDir, def.name, def.hash);
130
+ const idempotent = already !== null;
131
+ // Normalize the parent's agent steps into per-step specs.
132
+ const parent = normalizeDef(def);
133
+ // Persist the parent (unless byte-identical hash already cached). Strip the
134
+ // `children` map from what we persist (DD-2) — children are cached as their own
135
+ // bundles below; the parent keeps only its `pins`.
136
+ const { children, ...parentDefRaw } = def;
137
+ const parentDef = parentDefRaw;
138
+ let cacheLocation = '';
139
+ if (!idempotent) {
140
+ const bundle = { def: parentDef, fetchedAt: Date.now(), origin };
141
+ try {
142
+ cacheLocation = writeBundle(cacheDir, bundle, parent.specs);
143
+ }
144
+ catch (err) {
145
+ process.stderr.write(`owenloop work prepare: cache write failed: ${errMsg(err)}\n`);
146
+ return 1;
147
+ }
148
+ }
149
+ // Cache every hash-pinned child (and grandchild — the map is flat and already
150
+ // proven closed by validateFetchedDef, so a plain iteration suffices; no
151
+ // recursion). Each child is written as its own first-class bundle at
152
+ // bundles/<childName>/<childHash>/, skipping any hash already cached
153
+ // (idempotent — a re-prepare, or a child shared across parents). ALL writes
154
+ // land before ANY prune, so the fresh parent's pins protect the fresh children.
155
+ const childLines = [];
156
+ const childNames = new Set();
157
+ const childEntries = Object.entries(children ?? {});
158
+ for (const [childHash, childDef] of childEntries) {
159
+ childNames.add(childDef.name);
160
+ const childAlready = readBundle(cacheDir, childDef.name, childHash);
161
+ if (childAlready !== null) {
162
+ childLines.push(` cached pinned child '${childDef.name}'@${childHash} (idempotent — already cached)`);
163
+ continue;
164
+ }
165
+ const normalized = normalizeDef(childDef);
166
+ try {
167
+ writeBundle(cacheDir, { def: childDef, fetchedAt: Date.now(), origin }, normalized.specs);
168
+ }
169
+ catch (err) {
170
+ process.stderr.write(`owenloop work prepare: cache write failed for child '${childDef.name}'@${childHash}: ${errMsg(err)}\n`);
171
+ return 1;
172
+ }
173
+ childLines.push(` cached pinned child '${childDef.name}'@${childHash} (${normalized.specs.length} step spec(s))`);
174
+ }
175
+ // Prune AFTER all writes: parent name first, then each DISTINCT child name
176
+ // (keepHash = that child's own cached hash). pruneSupersededHashes is pin-aware
177
+ // (DD-3), so a superseded-but-still-pinned hash survives.
178
+ const pruned = pruneSupersededHashes(cacheDir, def.name, def.hash);
179
+ const childPruned = [];
180
+ for (const childName of childNames) {
181
+ if (childName === def.name)
182
+ continue; // parent name already pruned above
183
+ // keepHash = the hash of this child we just cached under this parent.
184
+ const keep = childEntries.find(([, cd]) => cd.name === childName)?.[0] ?? '';
185
+ for (const h of pruneSupersededHashes(cacheDir, childName, keep))
186
+ childPruned.push(`${childName}@${h}`);
187
+ }
188
+ // Summary.
189
+ out.write(` normalized ${parent.specs.length} step spec(s)${idempotent ? ' (idempotent — hash already cached, not rewritten)' : ` -> ${cacheLocation}`}\n`);
190
+ if (parent.noHarnessOptions.length > 0)
191
+ out.write(` no harness options declared: ${parent.noHarnessOptions.join(', ')}\n`);
192
+ if (parent.commandSkipped.length > 0)
193
+ out.write(` skipped (executor:command): ${parent.commandSkipped.join(', ')}\n`);
194
+ // calls-step messaging (DD-6): pinned children are cached (per-child lines);
195
+ // an UNPINNED calls step (pre-feature publish, no children on the wire) keeps a
196
+ // visible gap line.
197
+ for (const line of childLines)
198
+ out.write(`${line}\n`);
199
+ if (children === undefined) {
200
+ for (const child of parent.callsSteps) {
201
+ out.write(` calls-step child '${child}' not pinned — child not included in bundle\n`);
202
+ }
203
+ }
204
+ if (pruned.length > 0)
205
+ out.write(` pruned superseded hash(es): ${pruned.join(', ')}\n`);
206
+ if (childPruned.length > 0)
207
+ out.write(` pruned superseded child hash(es): ${childPruned.join(', ')}\n`);
208
+ return 0;
209
+ }
210
+ /**
211
+ * Normalize every agent step of one def into a `NormalizedStepSpec`, classifying
212
+ * the rest (command / calls). Pure over the cache — the caller persists. Shared
213
+ * by the parent path and each pinned child.
214
+ *
215
+ * There is no adapter lookup and no "empty compile" case any more: every agent
216
+ * step yields exactly one spec. A step with no `x.harness` is completely normal
217
+ * and simply gets empty permissions. A step with no `body` cannot reach here —
218
+ * `validateFetchedDef` already refused the def (the D1 hub gap).
219
+ */
220
+ function normalizeDef(def) {
221
+ const specs = [];
222
+ const noHarnessOptions = [];
223
+ const commandSkipped = [];
224
+ const callsSteps = [];
225
+ for (const step of def.steps) {
226
+ if (step.executor === 'command') {
227
+ commandSkipped.push(step.name);
228
+ continue;
229
+ }
230
+ if (step.calls !== undefined) {
231
+ callsSteps.push(step.calls);
232
+ continue;
233
+ }
234
+ if (step.harnessOptions === undefined)
235
+ noHarnessOptions.push(step.name);
236
+ const spec = {
237
+ step: step.name,
238
+ brief: step.body ?? '',
239
+ permissions: normalizeStepPermissions(step.harnessOptions, step),
240
+ };
241
+ if (step.harness !== undefined)
242
+ spec.harness = step.harness;
243
+ specs.push(spec);
244
+ }
245
+ return { specs, noHarnessOptions, commandSkipped, callsSteps };
246
+ }
247
+ function errMsg(err) {
248
+ return err instanceof Error ? err.message : String(err);
249
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `owenloop work release --session <id>` (C6) — session drain. Releases every claim
3
+ * held by a session id via the hub's by-session release verb so those orders
4
+ * re-offer immediately instead of stranding until their leases expire.
5
+ *
6
+ * B3 DRAIN SEMANTICS: the hub releases AGENT-held claims for the session and
7
+ * leaves EXEC-held claims untouched (a running command is doing real work — a
8
+ * session going away must not kill it). The hub enforces the exemption in SQL
9
+ * and does NOT enumerate the exempt claims, so this client can only NOTE that
10
+ * exec-held claims are drain-exempt; it cannot list them.
11
+ *
12
+ * Session identity resolves like `hold`: `--session <id>`, else env
13
+ * `OWENLOOP_SESSION`; an empty string counts as missing (matches `resolveHolder`).
14
+ * Missing both is a usage error (exit 2). Origin resolves like the other roles
15
+ * (`--origin` → `settings.hubOrigin`); the bearer comes from owenloop's store
16
+ * via `resolveBearer`, reading the `agent:<account>` slot for `OWENLOOP_ACCOUNT`
17
+ * (default `default`), with `OWENLOOP_TOKEN` as a documented dev-only override.
18
+ * release has no `--as` flag — a Shift sets `OWENLOOP_ACCOUNT` for a
19
+ * non-default account.
20
+ *
21
+ * Docs call ONLY for the session form; there is deliberately no targeted CLI
22
+ * form (hold/exec release their own targeted claims internally).
23
+ *
24
+ * Exit codes: 0 on a successful drain (including an empty release list) · 1 on
25
+ * a hub/network error · 2 on a usage error (missing session or origin, no Scoped
26
+ * Identity key, or an unknown flag).
27
+ */
28
+ import { type HubClient } from '../hub/client.ts';
29
+ interface ParsedArgs {
30
+ session?: string;
31
+ origin?: string;
32
+ error?: string;
33
+ }
34
+ /** Parse `--session`/`--origin` in both `--flag value` and `--flag=value` forms. */
35
+ export declare function parseArgs(args: string[]): ParsedArgs;
36
+ /**
37
+ * Resolve the session id to drain: explicit `--session`, else env
38
+ * `OWENLOOP_SESSION`; an empty string is treated as missing.
39
+ */
40
+ export declare function resolveSession(session: string | undefined, env: Record<string, string | undefined>): string | undefined;
41
+ export interface RunDeps {
42
+ hub?: HubClient;
43
+ out?: (line: string) => void;
44
+ err?: (line: string) => void;
45
+ env?: Record<string, string | undefined>;
46
+ }
47
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
48
+ export {};
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `owenloop work release --session <id>` (C6) — session drain. Releases every claim
3
+ * held by a session id via the hub's by-session release verb so those orders
4
+ * re-offer immediately instead of stranding until their leases expire.
5
+ *
6
+ * B3 DRAIN SEMANTICS: the hub releases AGENT-held claims for the session and
7
+ * leaves EXEC-held claims untouched (a running command is doing real work — a
8
+ * session going away must not kill it). The hub enforces the exemption in SQL
9
+ * and does NOT enumerate the exempt claims, so this client can only NOTE that
10
+ * exec-held claims are drain-exempt; it cannot list them.
11
+ *
12
+ * Session identity resolves like `hold`: `--session <id>`, else env
13
+ * `OWENLOOP_SESSION`; an empty string counts as missing (matches `resolveHolder`).
14
+ * Missing both is a usage error (exit 2). Origin resolves like the other roles
15
+ * (`--origin` → `settings.hubOrigin`); the bearer comes from owenloop's store
16
+ * via `resolveBearer`, reading the `agent:<account>` slot for `OWENLOOP_ACCOUNT`
17
+ * (default `default`), with `OWENLOOP_TOKEN` as a documented dev-only override.
18
+ * release has no `--as` flag — a Shift sets `OWENLOOP_ACCOUNT` for a
19
+ * non-default account.
20
+ *
21
+ * Docs call ONLY for the session form; there is deliberately no targeted CLI
22
+ * form (hold/exec release their own targeted claims internally).
23
+ *
24
+ * Exit codes: 0 on a successful drain (including an empty release list) · 1 on
25
+ * a hub/network error · 2 on a usage error (missing session or origin, no Scoped
26
+ * Identity key, or an unknown flag).
27
+ */
28
+ import { createHubClient } from "../hub/client.js";
29
+ import { resolveBearer } from "../credentials/resolve.js";
30
+ import { loadSettings } from "../settings/settings.js";
31
+ /** Parse `--session`/`--origin` in both `--flag value` and `--flag=value` forms. */
32
+ export function parseArgs(args) {
33
+ const parsed = {};
34
+ const takeValue = (a, i) => {
35
+ const eq = a.indexOf('=');
36
+ if (eq !== -1)
37
+ return { value: a.slice(eq + 1), next: i };
38
+ const v = args[i + 1];
39
+ if (v === undefined)
40
+ return { error: `missing value for ${a}` };
41
+ return { value: v, next: i + 1 };
42
+ };
43
+ for (let i = 0; i < args.length; i++) {
44
+ const a = args[i];
45
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
46
+ switch (name) {
47
+ case '--session':
48
+ case '--origin': {
49
+ const r = takeValue(a, i);
50
+ if ('error' in r)
51
+ return { error: r.error };
52
+ i = r.next;
53
+ if (name === '--session')
54
+ parsed.session = r.value;
55
+ else
56
+ parsed.origin = r.value;
57
+ break;
58
+ }
59
+ default:
60
+ return { error: `unknown option '${a}'` };
61
+ }
62
+ }
63
+ return parsed;
64
+ }
65
+ /**
66
+ * Resolve the session id to drain: explicit `--session`, else env
67
+ * `OWENLOOP_SESSION`; an empty string is treated as missing.
68
+ */
69
+ export function resolveSession(session, env) {
70
+ const id = session ?? env['OWENLOOP_SESSION'];
71
+ return id !== undefined && id !== '' ? id : undefined;
72
+ }
73
+ function usage(err) {
74
+ err('usage: owenloop work release --session <id> [--origin <url>]');
75
+ }
76
+ function errMsg(err) {
77
+ return err instanceof Error ? err.message : String(err);
78
+ }
79
+ /** Narrow a release response to the by-session form (the only form this role posts). */
80
+ function releasedList(res) {
81
+ const released = res.released;
82
+ return Array.isArray(released) ? released : [];
83
+ }
84
+ export async function run(args, deps = {}) {
85
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
86
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
87
+ const env = deps.env ?? process.env;
88
+ const parsed = parseArgs(args);
89
+ if (parsed.error !== undefined) {
90
+ err(`owenloop work release: ${parsed.error}`);
91
+ usage(err);
92
+ return 2;
93
+ }
94
+ const session = resolveSession(parsed.session, env);
95
+ if (session === undefined) {
96
+ err('owenloop work release: no session id — pass --session <id> or set OWENLOOP_SESSION');
97
+ usage(err);
98
+ return 2;
99
+ }
100
+ let settings;
101
+ try {
102
+ settings = loadSettings(env);
103
+ }
104
+ catch (e) {
105
+ err(`owenloop work release: ${errMsg(e)}`);
106
+ return 1;
107
+ }
108
+ const origin = parsed.origin ?? settings.hubOrigin;
109
+ if (origin === undefined || origin.trim() === '') {
110
+ err('owenloop work release: no hub origin — pass --origin <url> or set hubOrigin in settings');
111
+ return 2;
112
+ }
113
+ const account = env['OWENLOOP_ACCOUNT'] ?? 'default';
114
+ const bearer = await resolveBearer({ origin, account, env });
115
+ if (!bearer.ok) {
116
+ err(`owenloop work release: ${bearer.message}`);
117
+ return bearer.code;
118
+ }
119
+ const token = bearer.token;
120
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
121
+ let res;
122
+ try {
123
+ res = await hub.release({ session });
124
+ }
125
+ catch (e) {
126
+ err(`owenloop work release: ${errMsg(e)}`);
127
+ return 1;
128
+ }
129
+ if (res.text !== '')
130
+ out(res.text);
131
+ const released = releasedList(res);
132
+ for (const claim of released) {
133
+ out(`released ${claim.workflow}/${claim.run}`);
134
+ }
135
+ out('note: exec-held claims are drain-exempt and are not listed');
136
+ return 0;
137
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `owenloop work sessions` — list the harness sessions this machine has recorded, and
3
+ * print the command a human would run to re-open one.
4
+ *
5
+ * WHY IT EXISTS. `sessions.jsonl` is the only record that a provider-side
6
+ * session ever existed; the tokens in it are machine-local and are never sent to
7
+ * the hub. Before this subcommand the only way to answer "is anything still
8
+ * open on this box, and how do I get into it?" was to read the JSONL by hand.
9
+ * That matters most in exactly the situation where reading files by hand is
10
+ * hardest: a run that failed, whose worker is gone, and whose session may or may
11
+ * not still be resumable.
12
+ *
13
+ * WHY NO VENDOR NAME APPEARS IN THIS FILE. The harness id on a `SessionRecord`
14
+ * is DATA. Turning that data into a runnable command is BEHAVIOR, and vendor
15
+ * behavior lives behind the adapter contract — see `resumeCommand?` in
16
+ * `src/harness/contract.ts`. A `switch (rec.harness)` here would read fine and
17
+ * would still be the exact layering violation the harness boundary exists to
18
+ * prevent; `test/vendor-gate.test.ts` fails any shipped file outside
19
+ * `src/harness/` that names a vendor.
20
+ *
21
+ * WHY `dead` IS HIDDEN BY DEFAULT. `src/agent/loop.ts` refuses to resume a
22
+ * session whose newest record is `dead`, so a dead row is not actionable — and
23
+ * the store is append-only, so dead rows accumulate. `--all` shows them for
24
+ * forensics.
25
+ *
26
+ * Exit codes: 0 always on a successful read, INCLUDING an empty or missing store
27
+ * (a box that has run no agent orders is not in an error state) · 1 the cache
28
+ * dir could not be resolved or the store could not be read · 2 usage.
29
+ */
30
+ import '../harnesses.ts';
31
+ import { type SessionRecord } from '../harness/session-store.ts';
32
+ interface ParsedArgs {
33
+ cacheDir?: string;
34
+ json: boolean;
35
+ all: boolean;
36
+ error?: string;
37
+ }
38
+ export declare function parseArgs(args: string[]): ParsedArgs;
39
+ /** The newest record per `(workflow, run, step)` — the store is last-wins. */
40
+ export declare function newestPerKey(records: readonly SessionRecord[]): SessionRecord[];
41
+ /**
42
+ * A coarse human age: whole seconds under a minute, then minutes, hours, days.
43
+ * Deliberately lossy — this column exists to answer "is this from today or from
44
+ * last week?", and a precise timestamp is one `--json` away.
45
+ */
46
+ export declare function formatAge(ms: number): string;
47
+ /**
48
+ * The resume command for one record, or `undefined` when there is none.
49
+ *
50
+ * Three separate reasons there may be none, all rendered the same way in the
51
+ * table because the operator's next move is identical in each: the record names
52
+ * a harness this build does not register (an old row after an adapter was
53
+ * removed); the adapter registers but implements no interactive resume; or the
54
+ * adapter threw. The throw is caught rather than propagated because this is a
55
+ * LISTING — one bad row must not take down the other rows with it.
56
+ */
57
+ export declare function resumeCommandFor(rec: SessionRecord): string | undefined;
58
+ /** Render the table. Exported for the unit test; `run` does the I/O. */
59
+ export declare function renderTable(records: readonly SessionRecord[], now: number): string;
60
+ export declare function run(args: string[]): Promise<number>;
61
+ export {};
@@ -0,0 +1,180 @@
1
+ /**
2
+ * `owenloop work sessions` — list the harness sessions this machine has recorded, and
3
+ * print the command a human would run to re-open one.
4
+ *
5
+ * WHY IT EXISTS. `sessions.jsonl` is the only record that a provider-side
6
+ * session ever existed; the tokens in it are machine-local and are never sent to
7
+ * the hub. Before this subcommand the only way to answer "is anything still
8
+ * open on this box, and how do I get into it?" was to read the JSONL by hand.
9
+ * That matters most in exactly the situation where reading files by hand is
10
+ * hardest: a run that failed, whose worker is gone, and whose session may or may
11
+ * not still be resumable.
12
+ *
13
+ * WHY NO VENDOR NAME APPEARS IN THIS FILE. The harness id on a `SessionRecord`
14
+ * is DATA. Turning that data into a runnable command is BEHAVIOR, and vendor
15
+ * behavior lives behind the adapter contract — see `resumeCommand?` in
16
+ * `src/harness/contract.ts`. A `switch (rec.harness)` here would read fine and
17
+ * would still be the exact layering violation the harness boundary exists to
18
+ * prevent; `test/vendor-gate.test.ts` fails any shipped file outside
19
+ * `src/harness/` that names a vendor.
20
+ *
21
+ * WHY `dead` IS HIDDEN BY DEFAULT. `src/agent/loop.ts` refuses to resume a
22
+ * session whose newest record is `dead`, so a dead row is not actionable — and
23
+ * the store is append-only, so dead rows accumulate. `--all` shows them for
24
+ * forensics.
25
+ *
26
+ * Exit codes: 0 always on a successful read, INCLUDING an empty or missing store
27
+ * (a box that has run no agent orders is not in an error state) · 1 the cache
28
+ * dir could not be resolved or the store could not be read · 2 usage.
29
+ */
30
+ import "../harnesses.js";
31
+ import { adapterFor } from "../harness/registry.js";
32
+ import { readSessions, sessionsPath } from "../harness/session-store.js";
33
+ import { resolveCacheDir } from "../bundle/cache.js";
34
+ import { loadSettings } from "../settings/settings.js";
35
+ export function parseArgs(args) {
36
+ const parsed = { json: false, all: false };
37
+ for (let i = 0; i < args.length; i++) {
38
+ const a = args[i];
39
+ switch (a) {
40
+ case '--json':
41
+ parsed.json = true;
42
+ break;
43
+ case '--all':
44
+ parsed.all = true;
45
+ break;
46
+ case '--cache-dir': {
47
+ const v = args[i + 1];
48
+ if (v === undefined || v.startsWith('-')) {
49
+ parsed.error = `--cache-dir requires a value`;
50
+ return parsed;
51
+ }
52
+ parsed.cacheDir = v;
53
+ i++;
54
+ break;
55
+ }
56
+ default:
57
+ parsed.error = `unknown option '${a}'`;
58
+ return parsed;
59
+ }
60
+ }
61
+ return parsed;
62
+ }
63
+ function usage() {
64
+ process.stderr.write('usage: owenloop work sessions [--all] [--json] [--cache-dir <p>]\n');
65
+ }
66
+ /** The newest record per `(workflow, run, step)` — the store is last-wins. */
67
+ export function newestPerKey(records) {
68
+ const newest = new Map();
69
+ for (const rec of records)
70
+ newest.set(JSON.stringify([rec.workflow, rec.run, rec.step]), rec);
71
+ return [...newest.values()];
72
+ }
73
+ /**
74
+ * A coarse human age: whole seconds under a minute, then minutes, hours, days.
75
+ * Deliberately lossy — this column exists to answer "is this from today or from
76
+ * last week?", and a precise timestamp is one `--json` away.
77
+ */
78
+ export function formatAge(ms) {
79
+ if (!Number.isFinite(ms) || ms < 0)
80
+ return '?';
81
+ const s = Math.floor(ms / 1000);
82
+ if (s < 60)
83
+ return `${String(s)}s`;
84
+ const m = Math.floor(s / 60);
85
+ if (m < 60)
86
+ return `${String(m)}m`;
87
+ const h = Math.floor(m / 60);
88
+ if (h < 24)
89
+ return `${String(h)}h`;
90
+ return `${String(Math.floor(h / 24))}d`;
91
+ }
92
+ /** Single-quote for a POSIX shell only when a token needs it. */
93
+ function shellQuote(s) {
94
+ if (s !== '' && /^[A-Za-z0-9_@%+=:,./-]+$/.test(s))
95
+ return s;
96
+ return `'${s.replace(/'/g, `'\\''`)}'`;
97
+ }
98
+ /**
99
+ * The resume command for one record, or `undefined` when there is none.
100
+ *
101
+ * Three separate reasons there may be none, all rendered the same way in the
102
+ * table because the operator's next move is identical in each: the record names
103
+ * a harness this build does not register (an old row after an adapter was
104
+ * removed); the adapter registers but implements no interactive resume; or the
105
+ * adapter threw. The throw is caught rather than propagated because this is a
106
+ * LISTING — one bad row must not take down the other rows with it.
107
+ */
108
+ export function resumeCommandFor(rec) {
109
+ const adapter = adapterFor(rec.harness);
110
+ if (adapter?.resumeCommand === undefined)
111
+ return undefined;
112
+ try {
113
+ const cmd = adapter.resumeCommand({ harness: rec.harness, token: rec.token });
114
+ return [cmd.command, ...cmd.args].map(shellQuote).join(' ');
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ /** Render the table. Exported for the unit test; `run` does the I/O. */
121
+ export function renderTable(records, now) {
122
+ const rows = records.map((rec) => [
123
+ rec.order,
124
+ rec.step,
125
+ rec.harness,
126
+ rec.status,
127
+ String(rec.attempt),
128
+ formatAge(now - rec.updatedAt),
129
+ resumeCommandFor(rec) ?? '—',
130
+ ]);
131
+ const header = ['ORDER', 'STEP', 'HARNESS', 'STATUS', 'ATTEMPT', 'AGE', 'RESUME'];
132
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
133
+ // The last column is not padded: trailing spaces on a command an operator is
134
+ // about to copy are noise, and a resume command can be long.
135
+ const line = (cells) => cells.map((c, i) => (i === cells.length - 1 ? c : c.padEnd(widths[i]))).join(' ').trimEnd();
136
+ return [line(header), ...rows.map(line)].join('\n') + '\n';
137
+ }
138
+ export async function run(args) {
139
+ const parsed = parseArgs(args);
140
+ if (parsed.error !== undefined) {
141
+ process.stderr.write(`owenloop work sessions: ${parsed.error}\n`);
142
+ usage();
143
+ return 2;
144
+ }
145
+ let cacheDir;
146
+ try {
147
+ cacheDir = parsed.cacheDir ?? resolveCacheDir(process.env, loadSettings(process.env).cacheDir);
148
+ }
149
+ catch (err) {
150
+ process.stderr.write(`owenloop work sessions: ${err instanceof Error ? err.message : String(err)}\n`);
151
+ return 1;
152
+ }
153
+ let all;
154
+ try {
155
+ all = readSessions(sessionsPath(cacheDir));
156
+ }
157
+ catch (err) {
158
+ process.stderr.write(`owenloop work sessions: ${err instanceof Error ? err.message : String(err)}\n`);
159
+ return 1;
160
+ }
161
+ const visible = newestPerKey(all).filter((r) => parsed.all || r.status !== 'dead');
162
+ // Newest first: the session an operator is looking for is almost always the
163
+ // one that just failed.
164
+ visible.sort((a, b) => b.updatedAt - a.updatedAt);
165
+ if (parsed.json) {
166
+ // The RAW records, tokens included. This is machine-local data an operator
167
+ // already owns, and withholding the token would make the output useless for
168
+ // exactly the scripting this flag exists for.
169
+ process.stdout.write(`${JSON.stringify(visible, null, 2)}\n`);
170
+ return 0;
171
+ }
172
+ if (visible.length === 0) {
173
+ process.stdout.write(all.length === 0
174
+ ? 'no sessions recorded\n'
175
+ : 'no live sessions — every recorded session is dead (pass --all to see them)\n');
176
+ return 0;
177
+ }
178
+ process.stdout.write(renderTable(visible, Date.now()));
179
+ return 0;
180
+ }
@@ -0,0 +1,6 @@
1
+ export interface RunDeps {
2
+ out?: (line: string) => void;
3
+ err?: (line: string) => void;
4
+ env?: Record<string, string | undefined>;
5
+ }
6
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;