owenloop 0.4.1 → 0.5.1

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 (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Brief rendering + the born-bound work-holder MCP mount, for the `agent-run`
3
+ * worker (Phase 3).
4
+ *
5
+ * Two pure functions, no I/O:
6
+ *
7
+ * - `renderBrief(templateContent, spec)` — the SAME four-token substitution the
8
+ * legacy stamp path performs when it writes a per-order Step Agent file,
9
+ * minus the file. The worker hands the result straight to
10
+ * `HarnessAdapter.start` as `StartArgs.brief`.
11
+ * - `buildOwenloopMcp(spec)` — the `{command, args}` stdio mount for owenloop's
12
+ * own full work-holder MCP surface, byte-identical to the
13
+ * `mcpServers.owenloop` literal the legacy host adapter injects into stamped
14
+ * frontmatter today. A restricted adapter may append the hold role's positive
15
+ * tool selector without changing the born-bound identity arguments.
16
+ *
17
+ * WHY THE TOKENS ARE DECLARED HERE AND NOT IMPORTED (plan D4): the legacy
18
+ * host-adapter module under `src/adapters/` is what Phase 5 deletes, and it is
19
+ * vendor-named. Importing from it would point new code at a module on its way
20
+ * out. The duplication is deliberate and `test/agent-brief.test.ts` asserts the
21
+ * two sets are equal strings, so it cannot drift silently.
22
+ *
23
+ * Phase 4 adds a third pure function, `renderRejection` — see its own header.
24
+ *
25
+ * CREDENTIAL STANCE: `buildOwenloopMcp` puts NO credential in argv. The mount
26
+ * carries `--as <account>` — a Scoped Identity *selector*, not a secret — and
27
+ * the mounted work-holder resolves its own bearer from owenloop's credential
28
+ * store. `test/agent-brief.test.ts` asserts this. `renderRejection` reads only
29
+ * `OrderPacket.owes`, which carries no credential either, and
30
+ * `test/agent-rejection.test.ts` asserts that too. The separate, environmental
31
+ * `OWENLOOP_TOKEN` inheritance problem — Phase 3 pointed it at Phase 4, Phase 4
32
+ * re-deferred it — is CLOSED as of Phase 6: `filterOwenloopEnv`
33
+ * (`src/harness/child-env.ts`) is an allowlist over the `OWENLOOP_*` namespace,
34
+ * both adapters pass their child `env` through it, and `agent-run` stopped
35
+ * honouring the override on its own side in the same commit so the two sides
36
+ * cannot authenticate as different principals. See `docs/agent-runner.md`.
37
+ */
38
+ import type { OrderPacket } from '../hub/types.ts';
39
+ /** The composite `<workflow>/<run>` order id token. */
40
+ export declare const ORDER_TOKEN = "__OWENLOOP_ORDER__";
41
+ /** The hub origin token. */
42
+ export declare const ORIGIN_TOKEN = "__OWENLOOP_ORIGIN__";
43
+ /** The Scoped Identity account token. */
44
+ export declare const ACCOUNT_TOKEN = "__OWENLOOP_ACCOUNT__";
45
+ /** The dispatching Shift's self-declared id token (advisory only). */
46
+ export declare const SHIFT_TOKEN = "__OWENLOOP_SHIFT__";
47
+ /**
48
+ * Everything the four-token substitution and the MCP mount need.
49
+ *
50
+ * `run` is the BARE run id; it composes with `workflow` into the
51
+ * `<workflow>/<run>` composite every hub verb wants. `shiftId` is advisory
52
+ * attribution only (D8/INV-82) and absent resolves to the empty string.
53
+ */
54
+ export interface BriefSpec {
55
+ workflow: string;
56
+ run: string;
57
+ origin: string;
58
+ account: string;
59
+ shiftId?: string;
60
+ }
61
+ /**
62
+ * Substitute the four dispatch tokens into a step template.
63
+ *
64
+ * `split(...).join(...)` rather than a regex replace, mirroring the legacy
65
+ * stamp exactly: it replaces every occurrence and treats the token as a literal
66
+ * (no accidental `$&` expansion from template text the author controls).
67
+ */
68
+ export declare function renderBrief(templateContent: string, spec: BriefSpec): string;
69
+ /**
70
+ * The born-bound work-holder mount handed to `HarnessAdapter.start` as
71
+ * `StartArgs.owenloopMcp`. The adapter never constructs or changes the bound
72
+ * identity. A restricted adapter may append the hold role's positive MCP tool
73
+ * selector before mounting the command.
74
+ *
75
+ * `--shift=<cid>` is ONE argv element, not two. An absent cid then degrades
76
+ * to the single well-formed string `"--shift="` instead of a dangling flag
77
+ * with no value or a null array entry, which is what `hold`'s parser expects.
78
+ * (The shape originated with the deleted stamp path, which had to survive a YAML
79
+ * args array; it is kept because it is still the correct, unambiguous form.)
80
+ */
81
+ export declare function buildOwenloopMcp(spec: BriefSpec, binPath?: string, execPath?: string): {
82
+ command: string;
83
+ args: string[];
84
+ };
85
+ /**
86
+ * What `renderRejection` produced, plus the watermark the caller must persist.
87
+ *
88
+ * `message` is `''` EXACTLY WHEN nothing new needed saying. The caller treats
89
+ * that as "cold-start with the ordinary brief", never as "resume with an empty
90
+ * message" — a resume that says nothing spends a whole turn to communicate
91
+ * nothing.
92
+ *
93
+ * `deliveredReasonAt` is the largest `ReasonEntry.at` included in `message`, or
94
+ * `undefined` when `message` is empty. It becomes `SessionRecord.deliveredReasonAt`
95
+ * on the row written for the attempt this message opened.
96
+ */
97
+ export interface RejectionDelta {
98
+ message: string;
99
+ deliveredReasonAt?: number;
100
+ /** How many reason entries the message actually carries. Lets a caller log or
101
+ * assert the delta size without re-parsing the rendered text. */
102
+ count: number;
103
+ }
104
+ /** Options for `renderRejection`. */
105
+ export interface RejectionSpec {
106
+ /** The re-offered packet. Only `owes` is read. */
107
+ packet: Pick<OrderPacket, 'owes'>;
108
+ /**
109
+ * The `at` of the newest reason ALREADY delivered into this session, from the
110
+ * last `SessionRecord` for this `(workflow, run, step)`. Absent means nothing
111
+ * has been delivered yet, so every reason is new — which is the correct read
112
+ * for a record written before Phase 4 added the field.
113
+ */
114
+ deliveredReasonAt?: number;
115
+ /**
116
+ * Restrict rendering to these owed paths. Absent renders a section for EVERY
117
+ * owed path that has new reasons, which is what a re-offer owing several paths
118
+ * needs (one section per path, still delta-only, still one watermark).
119
+ */
120
+ paths?: readonly string[];
121
+ }
122
+ /** Rough token budget for the cold-replay brief, per the Phase 4 plan. */
123
+ export declare const REPLAY_TOKEN_BUDGET = 100000;
124
+ /** chars/4 — the cheap, deliberately approximate token estimate. Nothing here
125
+ * needs a real tokenizer: the cap exists to avoid a pathological brief, not to
126
+ * hit a byte-exact ceiling. */
127
+ export declare function estimateTokens(text: string): number;
128
+ /**
129
+ * Render the REJECTION DELTA — the whole point of Phase 4.
130
+ *
131
+ * THE CENTRAL DESIGN POINT: this message is SHORT, and it deliberately does NOT
132
+ * contain the brief. The session being resumed already holds the original brief,
133
+ * the file reads, the tool results and the prior submission — that is the entire
134
+ * reason the worker resumes instead of restarting. Re-sending the brief would
135
+ * spend exactly the tokens this phase exists to save, and would leave the model
136
+ * with two copies of its instructions and no way to tell which is current.
137
+ *
138
+ * WHAT IT MAY NOT CONTAIN, and why each is named rather than left to judgement:
139
+ * - `brief` / `material.templateContent` / `packet.prompt` — see above.
140
+ * - `packet.consumes` and any submit hint — the resumed session already has them.
141
+ * - any credential material. `OrderPacket.owes` carries none, and this function
142
+ * reads nothing else, so the property holds by construction rather than by
143
+ * filtering. `test/agent-rejection.test.ts` asserts it anyway.
144
+ *
145
+ * REASON SELECTION, restated from `docs/agent-runner.md` (c): the reasons come
146
+ * from `OrderPacket.owes[].reasons`, filtered to `at > deliveredReasonAt` and, when
147
+ * `spec.paths` is given, to those owed paths. NEVER from `WorkOrder.feedback` —
148
+ * that is the flattened `whats_next` shape, it carries no `at`, and a shape with
149
+ * no timestamp cannot be diffed against a watermark.
150
+ *
151
+ * PURE: packet + watermark in, string out. No I/O, no clock, no harness.
152
+ */
153
+ export declare function renderRejection(spec: RejectionSpec): RejectionDelta;
154
+ /**
155
+ * Assemble a COLD-REPLAY brief: the ordinary rendered brief plus the same
156
+ * rejection body as a trailing section.
157
+ *
158
+ * Used when resume is impossible (no prior session, a different harness, a dead
159
+ * session, a reaped cwd, a `replay`-tier adapter, or the provider rejecting the
160
+ * resume with `ResumeUnavailableError`). The session is gone, so the brief has to
161
+ * come back — but the reasons still have to arrive, or the fresh agent repeats
162
+ * the rejected submission verbatim.
163
+ *
164
+ * THE CAP. The assembled text is held to roughly `REPLAY_TOKEN_BUDGET` tokens by
165
+ * a chars/4 estimate. When it is over, WHOLE reason entries are dropped from the
166
+ * OLDEST end first and the message says how many were dropped. Never a mid-entry
167
+ * truncation: the kanna `handoff.ts` rule — never orphan a tool result from its
168
+ * call — generalizes here to "never emit half a structured item", because half a
169
+ * reason reads as a complete but different instruction.
170
+ *
171
+ * The BRIEF is never trimmed. If the brief alone exceeds the budget, the brief
172
+ * wins and the rejection section is reduced to as many of the NEWEST reasons as
173
+ * still fit, possibly none — losing the brief would leave the agent with no task
174
+ * at all, which is strictly worse than losing old reasons.
175
+ */
176
+ export declare function renderReplayBrief(brief: string, spec: RejectionSpec): string;
@@ -0,0 +1,197 @@
1
+ import { resolveOwenloopBin } from "../owenloop-bin.js";
2
+ /** The composite `<workflow>/<run>` order id token. */
3
+ export const ORDER_TOKEN = '__OWENLOOP_ORDER__';
4
+ /** The hub origin token. */
5
+ export const ORIGIN_TOKEN = '__OWENLOOP_ORIGIN__';
6
+ /** The Scoped Identity account token. */
7
+ export const ACCOUNT_TOKEN = '__OWENLOOP_ACCOUNT__';
8
+ /** The dispatching Shift's self-declared id token (advisory only). */
9
+ export const SHIFT_TOKEN = '__OWENLOOP_SHIFT__';
10
+ /** The composite order id — the only form the hub verbs accept. */
11
+ function composite(spec) {
12
+ return `${spec.workflow}/${spec.run}`;
13
+ }
14
+ /**
15
+ * Substitute the four dispatch tokens into a step template.
16
+ *
17
+ * `split(...).join(...)` rather than a regex replace, mirroring the legacy
18
+ * stamp exactly: it replaces every occurrence and treats the token as a literal
19
+ * (no accidental `$&` expansion from template text the author controls).
20
+ */
21
+ export function renderBrief(templateContent, spec) {
22
+ return templateContent
23
+ .split(ORDER_TOKEN)
24
+ .join(composite(spec))
25
+ .split(ORIGIN_TOKEN)
26
+ .join(spec.origin)
27
+ .split(ACCOUNT_TOKEN)
28
+ .join(spec.account)
29
+ .split(SHIFT_TOKEN)
30
+ .join(spec.shiftId ?? '');
31
+ }
32
+ /**
33
+ * The born-bound work-holder mount handed to `HarnessAdapter.start` as
34
+ * `StartArgs.owenloopMcp`. The adapter never constructs or changes the bound
35
+ * identity. A restricted adapter may append the hold role's positive MCP tool
36
+ * selector before mounting the command.
37
+ *
38
+ * `--shift=<cid>` is ONE argv element, not two. An absent cid then degrades
39
+ * to the single well-formed string `"--shift="` instead of a dangling flag
40
+ * with no value or a null array entry, which is what `hold`'s parser expects.
41
+ * (The shape originated with the deleted stamp path, which had to survive a YAML
42
+ * args array; it is kept because it is still the correct, unambiguous form.)
43
+ */
44
+ export function buildOwenloopMcp(spec, binPath = resolveOwenloopBin(), execPath = process.execPath) {
45
+ return {
46
+ command: execPath,
47
+ args: [
48
+ binPath,
49
+ 'work',
50
+ 'hold',
51
+ '--order',
52
+ composite(spec),
53
+ '--origin',
54
+ spec.origin,
55
+ '--as',
56
+ spec.account,
57
+ `--shift=${spec.shiftId ?? ''}`,
58
+ '--mcp',
59
+ ],
60
+ };
61
+ }
62
+ /** Rough token budget for the cold-replay brief, per the Phase 4 plan. */
63
+ export const REPLAY_TOKEN_BUDGET = 100_000;
64
+ /** chars/4 — the cheap, deliberately approximate token estimate. Nothing here
65
+ * needs a real tokenizer: the cap exists to avoid a pathological brief, not to
66
+ * hit a byte-exact ceiling. */
67
+ export function estimateTokens(text) {
68
+ return Math.ceil(text.length / 4);
69
+ }
70
+ /** One rendered reason line. `kind`/`by` are attribution the model needs to weigh
71
+ * a reason; `text` is the reason itself. */
72
+ function reasonLine(index, r) {
73
+ return `${index}. [${r.kind}, by ${r.by}] ${r.text}`;
74
+ }
75
+ /**
76
+ * Render the REJECTION DELTA — the whole point of Phase 4.
77
+ *
78
+ * THE CENTRAL DESIGN POINT: this message is SHORT, and it deliberately does NOT
79
+ * contain the brief. The session being resumed already holds the original brief,
80
+ * the file reads, the tool results and the prior submission — that is the entire
81
+ * reason the worker resumes instead of restarting. Re-sending the brief would
82
+ * spend exactly the tokens this phase exists to save, and would leave the model
83
+ * with two copies of its instructions and no way to tell which is current.
84
+ *
85
+ * WHAT IT MAY NOT CONTAIN, and why each is named rather than left to judgement:
86
+ * - `brief` / `material.templateContent` / `packet.prompt` — see above.
87
+ * - `packet.consumes` and any submit hint — the resumed session already has them.
88
+ * - any credential material. `OrderPacket.owes` carries none, and this function
89
+ * reads nothing else, so the property holds by construction rather than by
90
+ * filtering. `test/agent-rejection.test.ts` asserts it anyway.
91
+ *
92
+ * REASON SELECTION, restated from `docs/agent-runner.md` (c): the reasons come
93
+ * from `OrderPacket.owes[].reasons`, filtered to `at > deliveredReasonAt` and, when
94
+ * `spec.paths` is given, to those owed paths. NEVER from `WorkOrder.feedback` —
95
+ * that is the flattened `whats_next` shape, it carries no `at`, and a shape with
96
+ * no timestamp cannot be diffed against a watermark.
97
+ *
98
+ * PURE: packet + watermark in, string out. No I/O, no clock, no harness.
99
+ */
100
+ export function renderRejection(spec) {
101
+ const since = spec.deliveredReasonAt;
102
+ const wanted = spec.paths === undefined ? undefined : new Set(spec.paths);
103
+ const sections = [];
104
+ let newest;
105
+ let count = 0;
106
+ for (const owed of spec.packet.owes) {
107
+ if (wanted !== undefined && !wanted.has(owed.path))
108
+ continue;
109
+ const fresh = owed.reasons.filter((r) => since === undefined || r.at > since);
110
+ // A schema reject with no text is a real shape: the owed entry exists, the
111
+ // reason thread is empty. Filtering to nothing here is what makes the caller
112
+ // cold-start rather than resume with a bare "you were rejected".
113
+ if (fresh.length === 0)
114
+ continue;
115
+ const lines = fresh.map((r, i) => reasonLine(i + 1, r));
116
+ sections.push(`Your submission for \`${owed.path}\` was rejected. Reasons:\n\n${lines.join('\n')}`);
117
+ count += fresh.length;
118
+ for (const r of fresh) {
119
+ if (newest === undefined || r.at > newest)
120
+ newest = r.at;
121
+ }
122
+ }
123
+ if (sections.length === 0)
124
+ return { message: '', count: 0 };
125
+ const message = [
126
+ ...sections,
127
+ 'Revise and submit again to the same path with the same tool. Do not start over —\n' +
128
+ 'keep everything you already have that was not called out above.',
129
+ ].join('\n\n');
130
+ return { message, count, ...(newest !== undefined ? { deliveredReasonAt: newest } : {}) };
131
+ }
132
+ /**
133
+ * Assemble a COLD-REPLAY brief: the ordinary rendered brief plus the same
134
+ * rejection body as a trailing section.
135
+ *
136
+ * Used when resume is impossible (no prior session, a different harness, a dead
137
+ * session, a reaped cwd, a `replay`-tier adapter, or the provider rejecting the
138
+ * resume with `ResumeUnavailableError`). The session is gone, so the brief has to
139
+ * come back — but the reasons still have to arrive, or the fresh agent repeats
140
+ * the rejected submission verbatim.
141
+ *
142
+ * THE CAP. The assembled text is held to roughly `REPLAY_TOKEN_BUDGET` tokens by
143
+ * a chars/4 estimate. When it is over, WHOLE reason entries are dropped from the
144
+ * OLDEST end first and the message says how many were dropped. Never a mid-entry
145
+ * truncation: the kanna `handoff.ts` rule — never orphan a tool result from its
146
+ * call — generalizes here to "never emit half a structured item", because half a
147
+ * reason reads as a complete but different instruction.
148
+ *
149
+ * The BRIEF is never trimmed. If the brief alone exceeds the budget, the brief
150
+ * wins and the rejection section is reduced to as many of the NEWEST reasons as
151
+ * still fit, possibly none — losing the brief would leave the agent with no task
152
+ * at all, which is strictly worse than losing old reasons.
153
+ */
154
+ export function renderReplayBrief(brief, spec) {
155
+ const full = renderRejection(spec);
156
+ if (full.message === '')
157
+ return brief;
158
+ const join = (body, dropped) => {
159
+ const note = dropped > 0
160
+ ? `\n\n(${dropped} older rejection reason${dropped === 1 ? '' : 's'} omitted to fit the context budget.)`
161
+ : '';
162
+ return `${brief}\n\n---\n\n${body}${note}`;
163
+ };
164
+ let assembled = join(full.message, 0);
165
+ if (estimateTokens(assembled) <= REPLAY_TOKEN_BUDGET)
166
+ return assembled;
167
+ // Over budget: re-render with progressively fewer reasons, oldest dropped
168
+ // first. `ordered` is every candidate entry in ascending `at`, so slicing off
169
+ // the FRONT drops the oldest and keeps whole entries.
170
+ const since = spec.deliveredReasonAt;
171
+ const wanted = spec.paths === undefined ? undefined : new Set(spec.paths);
172
+ const ordered = spec.packet.owes
173
+ .filter((o) => wanted === undefined || wanted.has(o.path))
174
+ .flatMap((o) => o.reasons)
175
+ .filter((r) => since === undefined || r.at > since)
176
+ .sort((a, b) => a.at - b.at);
177
+ for (let drop = 1; drop <= ordered.length; drop += 1) {
178
+ const keep = new Set(ordered.slice(drop));
179
+ const trimmed = renderRejection({
180
+ ...spec,
181
+ packet: {
182
+ owes: spec.packet.owes.map((o) => ({ ...o, reasons: o.reasons.filter((r) => keep.has(r)) })),
183
+ },
184
+ // The watermark filter already ran; re-applying it is harmless but the
185
+ // `keep` set is now the authority on which entries survive.
186
+ ...(since !== undefined ? { deliveredReasonAt: since } : {}),
187
+ });
188
+ if (trimmed.message === '')
189
+ break;
190
+ assembled = join(trimmed.message, drop);
191
+ if (estimateTokens(assembled) <= REPLAY_TOKEN_BUDGET)
192
+ return assembled;
193
+ }
194
+ // Everything was dropped and it still does not fit — the brief alone is over
195
+ // budget. Return the brief: an agent with a task and no reasons can still work.
196
+ return brief;
197
+ }
@@ -0,0 +1,141 @@
1
+ import type { HubClient } from '../hub/client.ts';
2
+ import type { ContactHolder, OrderPacket } from '../hub/types.ts';
3
+ import type { ConsumedVerifier } from '../consumed-verifier.ts';
4
+ import type { NormalizedStepSpec } from '../bundle/types.ts';
5
+ import type { HarnessAdapter } from '../harness/contract.ts';
6
+ import { type SessionRecord } from '../harness/session-store.ts';
7
+ import { type ModelPolicy } from './model-policy.ts';
8
+ /** Discriminated result of one worker life; the role maps these to exit codes. */
9
+ export type AgentRunOutcome = 'submitted' | 'completed' | 'misroute' | 'no-template' | 'no-harness' | 'incompatible-harness-policy' | 'unverified-consumed' | 'session-store-failed' | 'no-submit' | 'killed' | 'lease-lost' | 'ownership-error' | 'hub-unreachable' | 'stopped';
10
+ /**
11
+ * Locate the normalized step spec for an order. Injected because the lookup is
12
+ * I/O (the verified workflow store) and because resolving the local definition
13
+ * is the role's business, not the loop's. `null` means instruction resolution
14
+ * refused; the loop releases and leaves the order for the pickup window.
15
+ *
16
+ * The spec arrives already normalized from the verified `StepDef` — brief,
17
+ * harness id, and `StepPermissions`. The loop stays vendor-neutral: it never
18
+ * reaches into a step definition's extension bag, so there is no key to name.
19
+ */
20
+ export type StepLoader = (order: OrderPacket) => Promise<NormalizedStepSpec | null>;
21
+ /**
22
+ * The outcome of resolving which adapter hosts this step agent.
23
+ *
24
+ * The loop never reads a registry and never names a harness: the role
25
+ * (`src/roles/agent-run.ts`, the composition root) owns the precedence
26
+ * `--harness` > `OWENLOOP_HARNESS` > the step def's `harness` field > the
27
+ * built-in default, and hands back the id it picked plus the adapter, if any.
28
+ * `registered` is only ever used to make the failure message actionable.
29
+ */
30
+ export interface AdapterResolution {
31
+ id: string;
32
+ adapter?: HarnessAdapter;
33
+ registered: string[];
34
+ }
35
+ /** `stepHarness` is the step def's `harness` field, the third precedence rank. */
36
+ export type AdapterResolver = (stepHarness: string | undefined) => AdapterResolution;
37
+ /** Default confirm-phase cadence: one `get_order` per second. */
38
+ export declare const DEFAULT_CONFIRM_INTERVAL_MS = 1000;
39
+ /** Default confirm-phase bound: give the hub 15s to show the submit's outcome. */
40
+ export declare const DEFAULT_SUBMIT_GRACE_MS = 15000;
41
+ export interface AgentRunLoopOptions {
42
+ hub: HubClient;
43
+ workflow: string;
44
+ run: string;
45
+ /** The worker's holder tag `{kind:'exec', id}` — `'exec'` is drain-exempt. */
46
+ holder: ContactHolder;
47
+ /** Hub origin — rides the mounted work-holder's `--origin`. */
48
+ origin: string;
49
+ /** Scoped Identity account — rides the mounted work-holder's `--as`. */
50
+ account: string;
51
+ /** Advisory Shift attribution — rides `--shift=<cid>` (may be absent). */
52
+ shiftId?: string;
53
+ /** cwd for the step agent when the order packet carries no `workdir`. */
54
+ cwd: string;
55
+ loadStep: StepLoader;
56
+ resolveAdapter: AdapterResolver;
57
+ /** Resolve authored model tiers and retry escalation before dispatch. */
58
+ modelPolicy?: ModelPolicy;
59
+ /** Gate dynamic values and rejection reasons before any prompt rendering. */
60
+ consumedVerifier?: ConsumedVerifier;
61
+ /** Append one session record. Wired to `appendSession` by the role. */
62
+ appendSession: (rec: SessionRecord) => void;
63
+ /** The attempt number for this `(workflow, run, step)`. Wired to `latestFor`. */
64
+ nextAttempt: (workflow: string, run: string, step: string) => number;
65
+ /**
66
+ * PHASE 4 — the last session record for this `(workflow, run, step)`, or `null`
67
+ * when the step has never run here. Wired to `latestFor(sessionsFile, ...)` by
68
+ * the role, the same reader `nextAttempt` already uses.
69
+ *
70
+ * It is what makes a resume possible at all: the prior `token` to resume, the
71
+ * `harness` that minted it, the `cwd` it is scoped to, and the
72
+ * `deliveredReasonAt` watermark that says which reasons the session has already
73
+ * heard. Absent (or returning `null`) ⇒ every firing is a cold start, which is
74
+ * exactly the pre-Phase-4 behaviour.
75
+ */
76
+ latestSession?: (workflow: string, run: string, step: string) => SessionRecord | null;
77
+ /**
78
+ * Does this directory still exist? Injected for the same reason every other
79
+ * side effect here is: a unit test drives the "the work dir was reaped, so the
80
+ * session cannot resume" branch without touching a filesystem. Defaults to
81
+ * `node:fs` `existsSync`.
82
+ */
83
+ dirExists?: (path: string) => boolean;
84
+ sleep: (ms: number) => Promise<void>;
85
+ now: () => number;
86
+ random?: () => number;
87
+ out: (line: string) => void;
88
+ err: (line: string) => void;
89
+ heartbeatIntervalMs?: number;
90
+ jumpToleranceMs?: number;
91
+ failureWindowMs?: number;
92
+ /** Confirm-phase poll cadence (default `DEFAULT_CONFIRM_INTERVAL_MS`). */
93
+ confirmIntervalMs?: number;
94
+ /** Confirm-phase upper bound (default `DEFAULT_SUBMIT_GRACE_MS`). */
95
+ submitGraceMs?: number;
96
+ }
97
+ export interface AgentRunLoop {
98
+ run(): Promise<AgentRunOutcome>;
99
+ /** Final breath: tear the session down and release. Wired to SIGINT/SIGTERM. */
100
+ stop(reason?: string): void;
101
+ }
102
+ /** How the bounded confirm phase ended. */
103
+ export type ConfirmResult = 'submitted' | 'lease-lost' | 'no-submit';
104
+ export interface ConfirmOptions {
105
+ hub: HubClient;
106
+ workflow: string;
107
+ run: string;
108
+ holder: ContactHolder;
109
+ sleep: (ms: number) => Promise<void>;
110
+ now: () => number;
111
+ err: (line: string) => void;
112
+ intervalMs: number;
113
+ graceMs: number;
114
+ /**
115
+ * Bail out early. Set once the caller's race is already decided (the lease
116
+ * loop settled, or a signal arrived), so a pending poll cannot hold the event
117
+ * loop open for the rest of the grace. The returned value is discarded in
118
+ * that case.
119
+ */
120
+ cancelled?: () => boolean;
121
+ }
122
+ /**
123
+ * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
124
+ * question: did the hub see the agent's `submit`?
125
+ *
126
+ * - `lease.outcome` present ⇒ `'submitted'` — the run closed.
127
+ * - `lease.claimed === false` with no outcome ⇒ `'lease-lost'` — something
128
+ * else took the run; releasing would be wrong and a submit would race it.
129
+ * - the grace expires, still claimed, still no outcome ⇒ `'no-submit'`.
130
+ *
131
+ * It calls `hub.getOrder` DIRECTLY rather than poking the lease loop:
132
+ * `LeaseLoop`'s public surface is `{run, stop}` with no probe-now method, and
133
+ * `src/lease/loop.ts` is load-bearing for six existing drills and must stay
134
+ * unchanged. Re-calling `get_order` while already holding the claim is exactly
135
+ * what the lease loop's own heartbeat does, so this adds no new hub semantics.
136
+ *
137
+ * A throwing `get_order` is transient by assumption: it is logged and the poll
138
+ * continues until the grace expires. Nothing here releases; only the caller does.
139
+ */
140
+ export declare function confirmOutcome(o: ConfirmOptions): Promise<ConfirmResult>;
141
+ export declare function createAgentRunLoop(opts: AgentRunLoopOptions): AgentRunLoop;