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,38 @@
1
+ export interface FileLockHandle {
2
+ lockPath: string;
3
+ acquired: boolean;
4
+ /** Per-acquisition diagnostic identity. SQLite, not this token, owns exclusion. */
5
+ token?: string;
6
+ }
7
+ export interface AcquireFileLockOpts {
8
+ /** Max time to wait for the SQLite writer lock or legacy owner. */
9
+ waitMs?: number;
10
+ /** Retained for source compatibility. New clients never age-reclaim pathnames. */
11
+ staleMs?: number;
12
+ /** Poll interval while waiting. */
13
+ pollMs?: number;
14
+ /** Retained for source compatibility. New clients never reclaim by pid. */
15
+ isPidAlive?: (pid: number) => boolean;
16
+ /** Wall clock used only for diagnostic timestamps. */
17
+ now?: () => number;
18
+ /** Current hostname used in diagnostic metadata. */
19
+ hostname?: () => string;
20
+ /** Names the holder in timeout text. */
21
+ label?: string;
22
+ /** Test barrier immediately before opening the versioned SQLite database. */
23
+ beforeOpen?: () => void;
24
+ }
25
+ export declare class FileLockTimeoutError extends Error {
26
+ readonly lockPath: string;
27
+ readonly holderPid: number | undefined;
28
+ readonly waitMs: number;
29
+ readonly legacy: boolean;
30
+ constructor(message: string, lockPath: string, holderPid: number | undefined, waitMs: number, legacy?: boolean);
31
+ }
32
+ export declare function acquireFileLock(lockPath: string, opts?: AcquireFileLockOpts): Promise<FileLockHandle>;
33
+ export declare function acquireFileLockSync(lockPath: string, opts?: AcquireFileLockOpts): FileLockHandle;
34
+ /**
35
+ * Release only the versioned SQLite transaction. The permanent compatibility
36
+ * guard is never deleted, renamed, or replaced.
37
+ */
38
+ export declare function releaseFileLock(handle: FileLockHandle): void;
@@ -0,0 +1,325 @@
1
+ // Generic cross-process lock with a one-way mixed-version boundary.
2
+ //
3
+ // New clients hold a SQLite `BEGIN IMMEDIATE` transaction on the versioned
4
+ // database at `<lockPath>.sqlite-v2`. The logical legacy pathname remains a
5
+ // parseable JSON guard. Its deliberately impossible hostname makes pre-SQLite
6
+ // clients treat the guard as foreign-host-owned and therefore never reclaim it.
7
+ // Once a new client installs that guard, old clients fail closed and must be
8
+ // upgraded; new clients continue to serialize through SQLite.
9
+ //
10
+ // The guard is permanent. Release and crash cleanup affect only the SQLite
11
+ // transaction, so no compare/read/delete pathname race exists. A pre-existing
12
+ // old JSON owner is allowed to release normally before the guard is installed.
13
+ // A corrupt file or a pre-boundary SQLite database at the legacy pathname is
14
+ // never removed automatically: the operator must first verify that no old or
15
+ // pre-boundary process owns it, then remove that legacy pathname manually.
16
+ import { randomBytes } from 'node:crypto';
17
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, writeFileSync, renameSync, } from 'node:fs';
18
+ import { hostname } from 'node:os';
19
+ import { dirname } from 'node:path';
20
+ import { performance } from 'node:perf_hooks';
21
+ import { DatabaseSync } from 'node:sqlite';
22
+ import { setTimeout as sleep } from 'node:timers/promises';
23
+ const LOCK_WAIT_MS = 10_000;
24
+ const LOCK_POLL_MS = 100;
25
+ const LOCK_SYNC_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
26
+ const COMPATIBILITY_GUARD_FORMAT = 'owenloop-sqlite-lock-v2';
27
+ // A slash cannot occur in an operating-system hostname. Old clients compare
28
+ // this field before probing the pid and therefore hold the guard forever.
29
+ const COMPATIBILITY_GUARD_HOST = 'owenloop/sqlite-lock/v2';
30
+ export class FileLockTimeoutError extends Error {
31
+ lockPath;
32
+ holderPid;
33
+ waitMs;
34
+ legacy;
35
+ constructor(message, lockPath, holderPid, waitMs, legacy = false) {
36
+ super(message);
37
+ this.name = 'FileLockTimeoutError';
38
+ this.lockPath = lockPath;
39
+ this.holderPid = holderPid;
40
+ this.waitMs = waitMs;
41
+ this.legacy = legacy;
42
+ }
43
+ }
44
+ /** Connections are deliberately private so callers cannot commit the lock transaction. */
45
+ const heldConnections = new WeakMap();
46
+ function databasePath(lockPath) {
47
+ return `${lockPath}.sqlite-v2`;
48
+ }
49
+ function ownerPath(lockPath) {
50
+ return `${lockPath}.owner.json`;
51
+ }
52
+ function readRaw(path) {
53
+ try {
54
+ return readFileSync(path, 'utf8');
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ function parseHolder(raw) {
61
+ if (raw === null)
62
+ return null;
63
+ try {
64
+ const parsed = JSON.parse(raw);
65
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
66
+ ? parsed
67
+ : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ function isCompatibilityGuard(raw) {
74
+ const holder = parseHolder(raw);
75
+ return holder?.format === COMPATIBILITY_GUARD_FORMAT && holder.host === COMPATIBILITY_GUARD_HOST;
76
+ }
77
+ function readDiagnosticHolder(lockPath) {
78
+ return parseHolder(readRaw(ownerPath(lockPath)));
79
+ }
80
+ function legacyHolder(lockPath) {
81
+ return parseHolder(readRaw(lockPath));
82
+ }
83
+ function writeDiagnosticHolder(lockPath, holder) {
84
+ const path = ownerPath(lockPath);
85
+ const tmp = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
86
+ writeFileSync(tmp, JSON.stringify(holder));
87
+ renameSync(tmp, path);
88
+ }
89
+ /**
90
+ * Install the permanent old-client guard with one exclusive create. A crash or
91
+ * write failure may leave a partial guard, which is intentionally fail-closed
92
+ * and requires verified manual cleanup; this function never unlinks a pathname.
93
+ */
94
+ function syncDirectory(path) {
95
+ if (process.platform === 'win32')
96
+ return;
97
+ const fd = openSync(dirname(path), 'r');
98
+ try {
99
+ fsyncSync(fd);
100
+ }
101
+ finally {
102
+ closeSync(fd);
103
+ }
104
+ }
105
+ function ensureCompatibilityGuard(lockPath, now) {
106
+ let fd;
107
+ try {
108
+ fd = openSync(lockPath, 'wx', 0o600);
109
+ }
110
+ catch (error) {
111
+ if (error.code !== 'EEXIST')
112
+ throw error;
113
+ return isCompatibilityGuard(readRaw(lockPath));
114
+ }
115
+ let failure;
116
+ try {
117
+ writeFileSync(fd, JSON.stringify({
118
+ format: COMPATIBILITY_GUARD_FORMAT,
119
+ host: COMPATIBILITY_GUARD_HOST,
120
+ startedAt: now(),
121
+ }));
122
+ fsyncSync(fd);
123
+ }
124
+ catch (error) {
125
+ failure = error;
126
+ }
127
+ try {
128
+ closeSync(fd);
129
+ }
130
+ catch (error) {
131
+ if (failure === undefined)
132
+ failure = error;
133
+ }
134
+ if (failure !== undefined)
135
+ throw failure;
136
+ syncDirectory(lockPath);
137
+ return true;
138
+ }
139
+ function openLockDatabase(lockPath) {
140
+ const db = new DatabaseSync(databasePath(lockPath));
141
+ db.exec('PRAGMA busy_timeout = 0');
142
+ return db;
143
+ }
144
+ function isBusy(error) {
145
+ const candidate = error;
146
+ return candidate.errcode === 5 || /database is (?:locked|busy)/iu.test(candidate.message ?? '');
147
+ }
148
+ function beginLock(db) {
149
+ db.exec('BEGIN IMMEDIATE;\n' +
150
+ 'CREATE TABLE IF NOT EXISTS __owenloop_lock_format (id INTEGER PRIMARY KEY CHECK (id = 1));\n' +
151
+ 'INSERT OR IGNORE INTO __owenloop_lock_format (id) VALUES (1);');
152
+ }
153
+ function closeAfterFailure(db) {
154
+ if (db === undefined)
155
+ return;
156
+ try {
157
+ db.exec('ROLLBACK');
158
+ }
159
+ catch {
160
+ // No transaction began, or SQLite already rolled it back.
161
+ }
162
+ try {
163
+ db.close();
164
+ }
165
+ catch {
166
+ // Preserve the acquisition error.
167
+ }
168
+ }
169
+ function makeHandle(lockPath, db, now, currentHost) {
170
+ const token = randomBytes(16).toString('hex');
171
+ const holder = {
172
+ pid: process.pid,
173
+ startedAt: now(),
174
+ token,
175
+ host: currentHost,
176
+ active: true,
177
+ };
178
+ try {
179
+ writeDiagnosticHolder(lockPath, holder);
180
+ }
181
+ catch (error) {
182
+ closeAfterFailure(db);
183
+ throw error;
184
+ }
185
+ const handle = { lockPath, acquired: true, token };
186
+ heldConnections.set(handle, db);
187
+ return handle;
188
+ }
189
+ function timeoutError(lockPath, holder, waitMs, label, legacy) {
190
+ const suffix = legacy
191
+ ? '; found an old, corrupt, or pre-boundary lock pathname that Owenloop will not delete automatically — verify that no old process owns it, then remove it manually'
192
+ : '';
193
+ return new FileLockTimeoutError(`${inProgressMessage(lockPath, holder, waitMs, label)}${suffix}`, lockPath, typeof holder?.pid === 'number' ? holder.pid : undefined, waitMs, legacy);
194
+ }
195
+ export async function acquireFileLock(lockPath, opts = {}) {
196
+ const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
197
+ const pollMs = opts.pollMs ?? LOCK_POLL_MS;
198
+ const now = opts.now ?? Date.now;
199
+ const currentHost = (opts.hostname ?? hostname)();
200
+ const label = opts.label ?? 'owenloop process';
201
+ const deadline = performance.now() + waitMs;
202
+ mkdirSync(dirname(lockPath), { recursive: true });
203
+ for (;;) {
204
+ let db;
205
+ try {
206
+ opts.beforeOpen?.();
207
+ db = openLockDatabase(lockPath);
208
+ beginLock(db);
209
+ if (!ensureCompatibilityGuard(lockPath, now)) {
210
+ closeAfterFailure(db);
211
+ db = undefined;
212
+ const holder = legacyHolder(lockPath);
213
+ if (performance.now() >= deadline)
214
+ throw timeoutError(lockPath, holder, waitMs, label, true);
215
+ await sleep(pollMs);
216
+ continue;
217
+ }
218
+ return makeHandle(lockPath, db, now, currentHost);
219
+ }
220
+ catch (error) {
221
+ closeAfterFailure(db);
222
+ if (error instanceof FileLockTimeoutError)
223
+ throw error;
224
+ if (!isBusy(error))
225
+ throw error;
226
+ }
227
+ const holder = readDiagnosticHolder(lockPath);
228
+ if (performance.now() >= deadline)
229
+ throw timeoutError(lockPath, holder, waitMs, label, false);
230
+ await sleep(pollMs);
231
+ }
232
+ }
233
+ export function acquireFileLockSync(lockPath, opts = {}) {
234
+ const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
235
+ const pollMs = opts.pollMs ?? LOCK_POLL_MS;
236
+ const now = opts.now ?? Date.now;
237
+ const currentHost = (opts.hostname ?? hostname)();
238
+ const label = opts.label ?? 'owenloop process';
239
+ const deadline = performance.now() + waitMs;
240
+ mkdirSync(dirname(lockPath), { recursive: true });
241
+ for (;;) {
242
+ let db;
243
+ try {
244
+ opts.beforeOpen?.();
245
+ db = openLockDatabase(lockPath);
246
+ beginLock(db);
247
+ if (!ensureCompatibilityGuard(lockPath, now)) {
248
+ closeAfterFailure(db);
249
+ db = undefined;
250
+ const holder = legacyHolder(lockPath);
251
+ if (performance.now() >= deadline)
252
+ throw timeoutError(lockPath, holder, waitMs, label, true);
253
+ Atomics.wait(LOCK_SYNC_SLEEP, 0, 0, pollMs);
254
+ continue;
255
+ }
256
+ return makeHandle(lockPath, db, now, currentHost);
257
+ }
258
+ catch (error) {
259
+ closeAfterFailure(db);
260
+ if (error instanceof FileLockTimeoutError)
261
+ throw error;
262
+ if (!isBusy(error))
263
+ throw error;
264
+ }
265
+ const holder = readDiagnosticHolder(lockPath);
266
+ if (performance.now() >= deadline)
267
+ throw timeoutError(lockPath, holder, waitMs, label, false);
268
+ Atomics.wait(LOCK_SYNC_SLEEP, 0, 0, pollMs);
269
+ }
270
+ }
271
+ function inProgressMessage(lockPath, holder, waitMs, label) {
272
+ const who = typeof holder?.pid === 'number' ? `pid ${holder.pid}` : 'another process';
273
+ const heldSince = typeof holder?.startedAt === 'number' &&
274
+ Number.isFinite(holder.startedAt) &&
275
+ Math.abs(holder.startedAt) <= 8.64e15
276
+ ? `, held since ${new Date(holder.startedAt).toISOString()}`
277
+ : '';
278
+ const seconds = Math.round(waitMs / 1000);
279
+ return `another ${label} is in progress (${who}${heldSince}) — holds ${lockPath}; timed out waiting after ${seconds}s`;
280
+ }
281
+ /**
282
+ * Release only the versioned SQLite transaction. The permanent compatibility
283
+ * guard is never deleted, renamed, or replaced.
284
+ */
285
+ export function releaseFileLock(handle) {
286
+ if (!handle.acquired)
287
+ return;
288
+ const db = heldConnections.get(handle);
289
+ if (db === undefined)
290
+ return;
291
+ try {
292
+ try {
293
+ writeDiagnosticHolder(handle.lockPath, {
294
+ pid: process.pid,
295
+ token: handle.token,
296
+ host: hostname(),
297
+ active: false,
298
+ releasedAt: Date.now(),
299
+ });
300
+ }
301
+ catch {
302
+ // Diagnostics never outrank releasing the kernel lock.
303
+ }
304
+ try {
305
+ db.exec('COMMIT');
306
+ }
307
+ catch {
308
+ try {
309
+ db.exec('ROLLBACK');
310
+ }
311
+ catch {
312
+ // Closing the connection still releases the operating-system lock.
313
+ }
314
+ }
315
+ }
316
+ finally {
317
+ heldConnections.delete(handle);
318
+ try {
319
+ db.close();
320
+ }
321
+ catch {
322
+ // Release is called from finally blocks and must not mask the real error.
323
+ }
324
+ }
325
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `owenloop mcp` — the owenloop-cli-mcp stdio control-plane surface (O2).
3
+ *
4
+ * TWO-PLANE MODEL (identity-and-setup-model doc, §5/§6/§8, in the
5
+ * owenloop-service repo): owenloop runs two distinct planes. The HUMAN control
6
+ * plane is the everyday operator surface — starting runs, answering gates,
7
+ * pushing defs — and it authenticates as the logged-in human. The AGENT plane
8
+ * is what a Step Agent uses with its own `olp_` bearer. This module
9
+ * serves the HUMAN plane to a local MCP host (Claude Code) over stdio: it reads
10
+ * newline-delimited JSON-RPC 2.0 on stdin, translates each `tools/call` into one
11
+ * authenticated HTTPS request to the hub's `/api/*` REST mirror, and writes the
12
+ * JSON-RPC reply on stdout. It is spawned by hosts, never run by a human at a
13
+ * prompt.
14
+ *
15
+ * The model doc's cardinal rule (§6): the MODEL must never see a live token.
16
+ * Two consequences are load-bearing here:
17
+ * 1. Every hub call reads the stored `human` credential fresh and refreshes it
18
+ * through O1's locked path (`ensureFreshOAuth`/`refreshOAuth` in
19
+ * `src/credentials.ts`); the bearer only ever rides the `Authorization`
20
+ * header, never a tool result. The server holds NO credential state between
21
+ * calls — its only state is the resolved origin and the fixed tool list.
22
+ * 2. `create_agent` MINTS an `olp_` agent token and writes it straight to the
23
+ * local store (`storeCredential`, slot `agent:<name>`, caller-chosen scopes,
24
+ * default `['work']`);
25
+ * the token is NEVER returned in a tool result, printed, or logged. The
26
+ * mint response body carries the plaintext in TWO fields (`data.token` AND
27
+ * the human `text` "Store this secret now…"), so the handler builds its
28
+ * result object FROM SCRATCH (`{name, crews, stored:true}`) and never
29
+ * passes any field of the raw body outbound.
30
+ *
31
+ * The transport core is in `./server.ts` (a copy of owenloop's; see its header).
32
+ * Everything owenloop-specific — origin resolution, the authenticated hub
33
+ * client, the tool registrations, the enrollment capability gate, and the
34
+ * command body — lives here.
35
+ */
36
+ import { PrincipalKeyManager } from '../crypto/index.ts';
37
+ import type { CredentialIO } from '../credentials.ts';
38
+ import type { SshProcessAdapter } from '../crypto/ssh.ts';
39
+ import type { LineStream } from './server.ts';
40
+ /**
41
+ * The IO surface `runMcpCommand` needs — a strict subset of the CLI's `CliIO`,
42
+ * which structurally satisfies it, so `dispatchMcp` passes its `io` unchanged.
43
+ * `stdinStream` is the injectable transport (tests feed a `PassThrough`; the
44
+ * command falls back to `process.stdin`).
45
+ */
46
+ export interface McpIo extends CredentialIO {
47
+ out: (line: string) => void;
48
+ err: (line: string) => void;
49
+ stdinStream?: LineStream;
50
+ principalKeys?: Pick<PrincipalKeyManager, 'inspect' | 'resolveRef' | 'withSigningKey'>;
51
+ /** Injectable ssh-keygen seam for hermetic submit-proof tests. */
52
+ sshProcess?: SshProcessAdapter;
53
+ }
54
+ /**
55
+ * Resolve the hub origin this server binds to, precedence:
56
+ * 1. `--hub <origin>` flag,
57
+ * 2. `OWENLOOP_HUB` env,
58
+ * 3. `~/.owenloop/config.json` (written by `owenloop login`; see
59
+ * `src/global-config.ts`'s header for why this is a separate file from
60
+ * the execution plane's `settings.json`),
61
+ * 4. if the FILE credential backend holds exactly ONE hub with a valid
62
+ * `human` slot, use it (back-compat for a login that predates rung 3),
63
+ * 5. else `DEFAULT_HUB` (`src/hub.ts`) — the production hub.
64
+ *
65
+ * Rungs 1–2 normalize the origin (a malformed value throws a `CliError` → the
66
+ * command's exit-1 path via `mainAsync`'s catch, matching every other
67
+ * command). Rung 3 reads `home` from `io.env.HOME`/`io.env.USERPROFILE` (the
68
+ * first non-blank of the two, mirroring `src/cli.ts`'s `workflowHome`) — but
69
+ * unlike `workflowHome`, an absent home does NOT throw here: it just means
70
+ * this rung has nothing to offer, same as a missing or malformed config file
71
+ * (`readGlobalConfig` never throws; see its doc comment in
72
+ * `src/global-config.ts`). Rung 4 is file-backend-only because only the file
73
+ * backend can enumerate (`listStoredHubOrigins`); `null` (cannot enumerate —
74
+ * keychain/external), `[]` (nothing stored), and length>1 (ambiguous) are ALL
75
+ * just "this rung has nothing to offer" and fall through to rung 5 — none of
76
+ * them is an error here.
77
+ *
78
+ * This function used to stop at what is now rung 4 and exit 2 instead of
79
+ * falling through, with a comment reading: "DELIBERATELY there is NO silent
80
+ * production fallback (the CLI's `resolveHub` `DEFAULT_HUB` rung): a
81
+ * control-plane server must never bind to a hub the operator did not name."
82
+ * Two things were wrong with that rule:
83
+ * 1. `resolveHub` (`src/cli.ts:2667-2674`) — used by `login` (`:2869`),
84
+ * `logout` (`:3173`), and `connect` (`:3193`) — ALREADY falls back to
85
+ * `DEFAULT_HUB`. `capability` and `crew` use `resolveAgentHub` instead;
86
+ * that resolver has no `DEFAULT_HUB` rung and still exits 2. The `login`
87
+ * command that CREATES credentials defaults to production while MCP's
88
+ * startup origin resolution exited 2 before it could reach any read or
89
+ * write tool. That asymmetry was the real inconsistency.
90
+ * 2. The no-fallback rule bought no safety. With no credential for the
91
+ * resolved origin, the server fails at the FIRST TOOL CALL with
92
+ * `loginHint` (below): "not logged in to <origin> — run `owenloop login
93
+ * --hub <origin>` in a terminal, then retry". That is a strictly better
94
+ * failure than dying before `initialize` — the host shows an actionable
95
+ * tool error instead of a dead server.
96
+ */
97
+ export declare function resolveMcpOrigin(io: McpIo, hubFlag: string | undefined): string;
98
+ /**
99
+ * Run the `owenloop mcp` command: resolve the origin, decide the enrollment
100
+ * gate, build the tool list, construct the JSON-RPC server, and pump stdin until
101
+ * EOF. Returns the process exit code: always 0 on stdin EOF — origin
102
+ * resolution has no exit-2 path of its own anymore (see `resolveMcpOrigin`;
103
+ * it always resolves to some origin, falling back as far as `DEFAULT_HUB`).
104
+ * A malformed `--hub`/`OWENLOOP_HUB` still throws a `CliError` (exit-1 path,
105
+ * via `mainAsync`'s catch).
106
+ */
107
+ export declare function runMcpCommand(io: McpIo, opts: {
108
+ hubFlag?: string;
109
+ }): Promise<number>;