owenloop 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +58 -31
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{cli.d.ts → src/cli.d.ts} +18 -3
  109. package/dist/{cli.js → src/cli.js} +770 -114
  110. package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
  111. package/dist/{credentials.js → src/credentials.js} +14 -12
  112. package/dist/{defs.js → src/defs.js} +36 -36
  113. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  114. package/dist/{engine.js → src/engine.js} +14 -14
  115. package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
  116. package/dist/{hub.js → src/hub.js} +370 -12
  117. package/dist/{index.d.ts → src/index.d.ts} +1 -1
  118. package/dist/{index.js → src/index.js} +1 -1
  119. package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
  120. package/dist/{mcp → src/mcp}/serve.js +168 -31
  121. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  122. package/dist/{mcp → src/mcp}/server.js +6 -9
  123. package/dist/{model.js → src/model.js} +1 -1
  124. package/dist/{types.d.ts → src/types.d.ts} +18 -18
  125. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  126. package/dist/{util.js → src/util.js} +3 -2
  127. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  128. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  129. package/docs/authoring.md +93 -53
  130. package/docs/cli.md +597 -76
  131. package/docs/design.md +33 -33
  132. package/docs/embedding.md +10 -9
  133. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  134. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  135. package/examples/workflows/judges/gate-sharpness.md +39 -0
  136. package/examples/workflows/judges/security.md +34 -0
  137. package/package.json +17 -8
  138. /package/dist/{add.d.ts → src/add.d.ts} +0 -0
  139. /package/dist/{add.js → src/add.js} +0 -0
  140. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  141. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  142. /package/dist/{factory.js → src/factory.js} +0 -0
  143. /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
  144. /package/dist/{lock.js → src/lock.js} +0 -0
  145. /package/dist/{model.d.ts → src/model.d.ts} +0 -0
  146. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  147. /package/dist/{paths.js → src/paths.js} +0 -0
  148. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  149. /package/dist/{schema.js → src/schema.js} +0 -0
  150. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  151. /package/dist/{store.js → src/store.js} +0 -0
  152. /package/dist/{types.js → src/types.js} +0 -0
  153. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  154. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The `owenloop work hold --mcp` stdio-MCP mount (plan part 2).
3
+ *
4
+ * A born-bound work-holder: the D2 stamped Step Agent's frontmatter declares
5
+ * `mcpServers.owenloop = owenloop work hold --order <wf>/<run> --origin <url> --mcp`,
6
+ * so when the Step Agent session boots it launches THIS as a stdio MCP server. The
7
+ * server exposes two bare tools the model uses to do its order:
8
+ * - `get_order` → the order packet (prompt, inputs, owed outputs) for the run
9
+ * this holder is bound to. No ids are arguments — they came in on argv, never
10
+ * through the model.
11
+ * - `submit` → post a receipt for an owed output path; when the hub reports
12
+ * the submit CLOSED the run, the lease loop is stopped with `release:false`
13
+ * (the claim is already gone).
14
+ *
15
+ * Underneath the tools, the SAME lease loop the CLI `hold` runs keeps the order's
16
+ * lease warm: `createHoldMcp` builds the loop with `onOrder` wired to capture the
17
+ * first-contact packet (so `get_order` needn't re-fetch) and both output sinks
18
+ * routed to stderr (stdout is the JSON-RPC channel). The role starts the loop and
19
+ * pumps stdin into the server; loop and server share one process, and stdin EOF
20
+ * (the session died) stops the loop for its final-breath release.
21
+ *
22
+ * This module is pure wiring + tool handlers — no stdio, no process, no timers of
23
+ * its own — so a unit test drives the tools with a fake hub and a scriptable
24
+ * clock. The role (`src/roles/hold.ts`) owns the real stdin/stdout pump.
25
+ */
26
+ import { type ToolRegistration } from '../mcp/server.ts';
27
+ import type { HubClient } from '../hub/client.ts';
28
+ import type { ContactHolder } from '../hub/types.ts';
29
+ import { type HoldLoop } from './loop.ts';
30
+ export interface HoldMcpDeps {
31
+ hub: HubClient;
32
+ workflow: string;
33
+ run: string;
34
+ /** B3 holder tag; rides get_order/heartbeat when known. */
35
+ holder?: ContactHolder;
36
+ sleep: (ms: number) => Promise<void>;
37
+ now: () => number;
38
+ /** Diagnostics sink — stderr (stdout is the MCP transport). */
39
+ err: (line: string) => void;
40
+ heartbeatIntervalMs?: number;
41
+ /** Wall-gap slack before a tick is treated as a clock jump (default 30_000). */
42
+ jumpToleranceMs?: number;
43
+ }
44
+ export interface HoldMcpMount {
45
+ /** The two tools (`get_order`, `submit`) for the MCP server. */
46
+ tools: ToolRegistration[];
47
+ /** The lease loop kept warm underneath — the role runs and stops it. */
48
+ loop: HoldLoop;
49
+ }
50
+ /**
51
+ * Build the hold MCP mount: the lease loop plus its two tools. The caller (the
52
+ * role) creates the MCP server around `tools`, starts `loop.run()`, and pumps
53
+ * stdin — stopping the loop on stdin EOF.
54
+ */
55
+ export declare function createHoldMcp(deps: HoldMcpDeps): HoldMcpMount;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The `owenloop work hold --mcp` stdio-MCP mount (plan part 2).
3
+ *
4
+ * A born-bound work-holder: the D2 stamped Step Agent's frontmatter declares
5
+ * `mcpServers.owenloop = owenloop work hold --order <wf>/<run> --origin <url> --mcp`,
6
+ * so when the Step Agent session boots it launches THIS as a stdio MCP server. The
7
+ * server exposes two bare tools the model uses to do its order:
8
+ * - `get_order` → the order packet (prompt, inputs, owed outputs) for the run
9
+ * this holder is bound to. No ids are arguments — they came in on argv, never
10
+ * through the model.
11
+ * - `submit` → post a receipt for an owed output path; when the hub reports
12
+ * the submit CLOSED the run, the lease loop is stopped with `release:false`
13
+ * (the claim is already gone).
14
+ *
15
+ * Underneath the tools, the SAME lease loop the CLI `hold` runs keeps the order's
16
+ * lease warm: `createHoldMcp` builds the loop with `onOrder` wired to capture the
17
+ * first-contact packet (so `get_order` needn't re-fetch) and both output sinks
18
+ * routed to stderr (stdout is the JSON-RPC channel). The role starts the loop and
19
+ * pumps stdin into the server; loop and server share one process, and stdin EOF
20
+ * (the session died) stops the loop for its final-breath release.
21
+ *
22
+ * This module is pure wiring + tool handlers — no stdio, no process, no timers of
23
+ * its own — so a unit test drives the tools with a fake hub and a scriptable
24
+ * clock. The role (`src/roles/hold.ts`) owns the real stdin/stdout pump.
25
+ */
26
+ import { textResult } from "../mcp/server.js";
27
+ import { createHoldLoop } from "./loop.js";
28
+ function errMsg(e) {
29
+ return e instanceof Error ? e.message : String(e);
30
+ }
31
+ /** A lean, model-facing view of the order packet. */
32
+ function orderView(res) {
33
+ return { workflow: res.workflow, run: res.run, order: res.order, text: res.text };
34
+ }
35
+ /**
36
+ * Build the hold MCP mount: the lease loop plus its two tools. The caller (the
37
+ * role) creates the MCP server around `tools`, starts `loop.run()`, and pumps
38
+ * stdin — stopping the loop on stdin EOF.
39
+ */
40
+ export function createHoldMcp(deps) {
41
+ const { hub, workflow, run } = deps;
42
+ const holderReq = deps.holder !== undefined ? { holder: deps.holder } : {};
43
+ // Captured from the loop's first contact so `get_order` needn't re-fetch (and
44
+ // re-contend the pickup window). Falls back to a live fetch if a tool call
45
+ // beats first contact.
46
+ let captured;
47
+ // Set the moment the lease loop's run() settles (lease-lost, completed,
48
+ // released, …): from then on this mount no longer holds the order, so BOTH
49
+ // tools fast-fail with isError and never touch the hub again (plan section 4
50
+ // — a lost claim must not be worked or double-submitted).
51
+ let terminal;
52
+ const inner = createHoldLoop({
53
+ hub,
54
+ workflow,
55
+ run,
56
+ sleep: deps.sleep,
57
+ now: deps.now,
58
+ // Both sinks to stderr: stdout is the JSON-RPC frame channel.
59
+ out: deps.err,
60
+ err: deps.err,
61
+ onOrder: (res) => {
62
+ captured = res;
63
+ },
64
+ ...(deps.holder !== undefined ? { holder: deps.holder } : {}),
65
+ ...(deps.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: deps.heartbeatIntervalMs } : {}),
66
+ ...(deps.jumpToleranceMs !== undefined ? { jumpToleranceMs: deps.jumpToleranceMs } : {}),
67
+ });
68
+ // The loop the role runs is a thin wrapper that records the terminal outcome
69
+ // when run() settles, so the tool guards see it without the role's help.
70
+ const loop = {
71
+ run: async () => {
72
+ const outcome = await inner.run();
73
+ terminal = outcome;
74
+ return outcome;
75
+ },
76
+ stop: (reason, stopOpts) => inner.stop(reason, stopOpts),
77
+ };
78
+ /** The fast-fail both tools apply once the hold is over. */
79
+ function terminalGuard() {
80
+ if (terminal === undefined)
81
+ return undefined;
82
+ return textResult({ error: `order no longer held (${terminal}) — stop` }, true);
83
+ }
84
+ const getOrderTool = {
85
+ name: 'get_order',
86
+ description: "Return this work-holder's order — the prompt, consumed inputs, and owed output paths for the run it is bound to. Takes no arguments (the run is fixed at launch).",
87
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
88
+ handler: async () => {
89
+ const gone = terminalGuard();
90
+ if (gone !== undefined)
91
+ return gone;
92
+ if (captured !== undefined)
93
+ return textResult(orderView(captured));
94
+ try {
95
+ const res = await hub.getOrder({ workflow, run, ...holderReq });
96
+ captured = res;
97
+ return textResult(orderView(res));
98
+ }
99
+ catch (e) {
100
+ return textResult({ error: errMsg(e) }, true);
101
+ }
102
+ },
103
+ };
104
+ const submitTool = {
105
+ name: 'submit',
106
+ description: 'Submit a receipt for one owed output path of this order. Set done=true when this is the final value for the path. When the hub reports the run has closed, the holder releases and exits.',
107
+ inputSchema: {
108
+ type: 'object',
109
+ required: ['path', 'value'],
110
+ properties: {
111
+ path: { type: 'string', description: 'The owed output path to submit a receipt for.' },
112
+ value: { description: 'The receipt value (any JSON).' },
113
+ done: { type: 'boolean', description: 'Mark this the final submit for the path.' },
114
+ },
115
+ additionalProperties: false,
116
+ },
117
+ handler: async (args) => {
118
+ const gone = terminalGuard();
119
+ if (gone !== undefined)
120
+ return gone;
121
+ const path = args['path'];
122
+ if (typeof path !== 'string' || path === '') {
123
+ return textResult({ error: 'submit requires a non-empty string "path"' }, true);
124
+ }
125
+ if (!('value' in args)) {
126
+ return textResult({ error: 'submit requires a "value"' }, true);
127
+ }
128
+ const done = args['done'];
129
+ try {
130
+ const res = await hub.submit({
131
+ workflow,
132
+ run,
133
+ path,
134
+ value: args['value'],
135
+ ...(typeof done === 'boolean' ? { done } : {}),
136
+ ...holderReq,
137
+ });
138
+ // The run closed — stop holding WITHOUT releasing (the claim is gone).
139
+ if (res.closed === true)
140
+ loop.stop('submitted', { release: false });
141
+ return textResult({ outcome: res.outcome, closed: res.closed ?? false, text: res.text });
142
+ }
143
+ catch (e) {
144
+ return textResult({ error: errMsg(e) }, true);
145
+ }
146
+ },
147
+ };
148
+ return { tools: [getOrderTool, submitTool], loop };
149
+ }
@@ -0,0 +1,22 @@
1
+ import type { GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, SubmitRequest, SubmitResponse, WakeResponse, WhatsNextRequest, WhatsNextResponse, WhoamiResponse } from './types.ts';
2
+ export interface HubClientOptions {
3
+ /** Hub origin, e.g. `https://hub.owenloop.dev` (no trailing slash needed). */
4
+ origin: string;
5
+ /** Resolves the bearer token per call — the CredentialReader seam. */
6
+ getToken: () => Promise<string>;
7
+ /** Override the transport in tests; defaults to the global `fetch`. */
8
+ fetchImpl?: typeof fetch;
9
+ }
10
+ export interface HubClient {
11
+ whatsNext(req?: WhatsNextRequest): Promise<WhatsNextResponse>;
12
+ getOrder(req: GetOrderRequest): Promise<GetOrderResponse>;
13
+ heartbeat(req: HeartbeatRequest): Promise<HeartbeatResponse>;
14
+ release(req: ReleaseRequest): Promise<ReleaseResponse>;
15
+ submit(req: SubmitRequest): Promise<SubmitResponse>;
16
+ whoami(): Promise<WhoamiResponse>;
17
+ /** B5 cheap wake pre-check; `cursor` rides the query string only when set. */
18
+ wake(cursor?: number): Promise<WakeResponse>;
19
+ /** B4 Shift presence register/refresh. */
20
+ presencePing(req: PresencePingRequest): Promise<PresencePingResponse>;
21
+ }
22
+ export declare function createHubClient(opts: HubClientOptions): HubClient;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Typed hub client for the verb surface the roles call. Transport and auth
3
+ * wiring are real; in tests the client is exercised only against a fake
4
+ * `fetchImpl` or a throwaway `node:http` server (never a live hub).
5
+ *
6
+ * Every call sends `Authorization: Bearer <token>` (from the injected
7
+ * `getToken` — the seam where a CredentialReader plugs in later) and
8
+ * `content-type: application/json`, POSTs JSON to `<origin>/api/<verb>` (GET
9
+ * for `whoami`), and parses the `{ text, ...data }` envelope. Non-2xx becomes a
10
+ * `HubError`.
11
+ *
12
+ * PRESENCE (B4) + WAKE (B5): the C1 client deliberately omitted these because
13
+ * their hub surface did not exist yet. Both are merged now, so C3 adds
14
+ * `presencePing` (POST `/api/presence_ping`) and `wake` (GET `/api/wake`,
15
+ * cursor in the query string) matching the hub-edge shapes.
16
+ *
17
+ * No retries/backoff and no token refresh in C1 — the roles own their retry
18
+ * policy later, and oauth-kind token refresh stays inside owenloop.
19
+ */
20
+ import { HubError } from "./types.js";
21
+ export function createHubClient(opts) {
22
+ const base = opts.origin.replace(/\/+$/, '');
23
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
24
+ async function authHeaders() {
25
+ const token = await opts.getToken();
26
+ return {
27
+ authorization: `Bearer ${token}`,
28
+ 'content-type': 'application/json',
29
+ };
30
+ }
31
+ async function parse(res) {
32
+ const raw = await res.text();
33
+ if (!res.ok) {
34
+ let code;
35
+ let message = raw;
36
+ try {
37
+ const body = JSON.parse(raw);
38
+ if (body && typeof body === 'object') {
39
+ code = body.error;
40
+ message = body.message ?? raw;
41
+ }
42
+ }
43
+ catch {
44
+ // Not JSON — keep the raw text as the message.
45
+ }
46
+ throw new HubError(res.status, message, code);
47
+ }
48
+ return JSON.parse(raw);
49
+ }
50
+ async function post(verb, body) {
51
+ const res = await fetchImpl(`${base}/api/${verb}`, {
52
+ method: 'POST',
53
+ headers: await authHeaders(),
54
+ body: JSON.stringify(body),
55
+ });
56
+ return parse(res);
57
+ }
58
+ async function get(verb, query) {
59
+ const url = query !== undefined && query !== '' ? `${base}/api/${verb}?${query}` : `${base}/api/${verb}`;
60
+ const res = await fetchImpl(url, {
61
+ method: 'GET',
62
+ headers: await authHeaders(),
63
+ });
64
+ return parse(res);
65
+ }
66
+ return {
67
+ whatsNext: (req = {}) => post('whats_next', req),
68
+ getOrder: (req) => post('get_order', req),
69
+ heartbeat: (req) => post('heartbeat', req),
70
+ release: (req) => post('release', req),
71
+ submit: (req) => post('submit', req),
72
+ whoami: () => get('whoami'),
73
+ // Cursor is an opaque non-negative integer; omit it entirely to bootstrap
74
+ // (the hub treats missing/invalid as a `changed: true` first sweep).
75
+ wake: (cursor) => get('wake', typeof cursor === 'number' ? `cursor=${encodeURIComponent(String(cursor))}` : undefined),
76
+ presencePing: (req) => post('presence_ping', req),
77
+ };
78
+ }
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Typed request/response shapes for the hub verb surface owenloop's roles call.
3
+ *
4
+ * These mirror `apps/hub-edge/src/api/routes.ts` on owenloop-service `origin/main`
5
+ * (B3 lifecycle verbs are merged). Every REST verb returns `{ text, ...data }`
6
+ * where `data` is always an object, so each response extends `HubResponse`.
7
+ *
8
+ * Response payloads are typed LOOSELY on purpose: the roles that consume the
9
+ * data fields (whats_next orders, get_order body, …) land in C3–C5. Honest-loose
10
+ * (`unknown[]` + a TODO) beats invented-precise shapes no consumer reads yet.
11
+ */
12
+ /** Common envelope: every verb returns a human-readable `text` plus verb data. */
13
+ export interface HubResponse {
14
+ text: string;
15
+ }
16
+ export interface WhatsNextRequest {
17
+ workflow?: string;
18
+ /** Server-side filter for which serve crews this caller will accept. */
19
+ serve_crews?: string[];
20
+ }
21
+ /**
22
+ * One work order from a per-workflow `whats_next` sweep. Mirrors hub-core
23
+ * `verbs/whats-next.ts` `WorkOrder` exactly. `run` IS the order id used by
24
+ * every other hub verb; `step` is the def step name (matched against the
25
+ * cached bundle to classify command vs agent). Fields the shift does not
26
+ * read yet (consumes/expected_outputs/feedback/advisory/submit_hint) are
27
+ * mirrored for completeness — C4/C5 consume them.
28
+ */
29
+ export interface WorkOrder {
30
+ workflow: string;
31
+ run: string;
32
+ step: string;
33
+ prompt: string;
34
+ consumes: Record<string, unknown>;
35
+ expected_outputs: Array<{
36
+ path: string;
37
+ schema?: unknown;
38
+ }>;
39
+ feedback: string[];
40
+ advisory: {
41
+ model?: string;
42
+ tools?: string[];
43
+ };
44
+ submit_hint: string;
45
+ }
46
+ /** One instance row from an inbox-mode (`workflow` omitted) `whats_next`. */
47
+ export interface InboxInstance {
48
+ workflow: string;
49
+ def: string;
50
+ done: boolean;
51
+ eligible: number;
52
+ blocked: number;
53
+ owedSeededInputs: string[];
54
+ }
55
+ /**
56
+ * The `{ text, ...data }` envelope of a `whats_next` response, flattened as
57
+ * the REST layer serves it (`c.json({ text, ...data })`). Per-workflow mode
58
+ * carries `workflow`/`def`/`orders`; inbox mode carries `instances`. Both are
59
+ * optional because a single type covers both modes.
60
+ */
61
+ export interface WhatsNextResponse extends HubResponse {
62
+ /** Per-workflow mode: the instance id echoed back. */
63
+ workflow?: string;
64
+ /** Per-workflow mode: the def name (used to locate the cached bundle). */
65
+ def?: string;
66
+ /** Per-workflow mode: the served work orders (empty when nothing eligible). */
67
+ orders?: WorkOrder[];
68
+ /** Inbox mode (no `workflow`): the caller's servable instances. */
69
+ instances?: InboxInstance[];
70
+ }
71
+ /**
72
+ * B5 `GET /api/wake?cursor=<n>` response. The cursor is the org's current max
73
+ * `events.seq` (monotonic, never reused). `changed` is true when a servable
74
+ * event exists strictly after the client's cursor; a missing/invalid cursor
75
+ * bootstraps to `changed: true` with the real max seq. Always adopt the
76
+ * returned cursor — it is monotonic by construction (source: hub-core
77
+ * `verbs/wake.ts`).
78
+ */
79
+ export interface WakeResponse extends HubResponse {
80
+ cursor: number;
81
+ changed: boolean;
82
+ }
83
+ /**
84
+ * B4 `POST /api/presence_ping` body. `name` is non-empty, ≤200 chars.
85
+ * `serve_crews` omitted means OVERWRITE-to-empty hub-side (a ping is the full
86
+ * current truth about a Shift), so always send the crews this shift
87
+ * serves (source: hub-core `verbs/presence-ping.ts`).
88
+ *
89
+ * `shift_id`/`started_at` are W7's self-declared attribution fields — the
90
+ * Shift process incarnation id (`shf_<uuid>`, regenerated every restart,
91
+ * never persisted) and its process start time. Advisory only (D8/INV-82):
92
+ * never used for authorization, routing, dispatch, or claim correctness.
93
+ *
94
+ * WIRE CONVENTION (deliberate, do not "normalize"): these two top-level fields
95
+ * are snake_case even in TS, mirroring the hub's wire body verbatim — unlike
96
+ * `ContactHolder.shiftId` below, whose nested object keys are camelCase on
97
+ * the wire. Both conventions are correct for where they live.
98
+ */
99
+ export interface PresencePingRequest {
100
+ name: string;
101
+ serve_crews?: string[];
102
+ shift_id?: string;
103
+ started_at?: number;
104
+ /** Epoch-millisecond timestamp of the last accepted local shift attendance. */
105
+ attended_at?: number;
106
+ }
107
+ /** B4 `presence_ping` response envelope (flattened `{ text, ...data }`). */
108
+ export interface PresencePingResponse extends HubResponse {
109
+ ok: true;
110
+ name: string;
111
+ lastSeen: number;
112
+ }
113
+ /**
114
+ * The holder identity a contacting process (`get_order`/`heartbeat`) tags its
115
+ * claim with. Mirrors hub-core `claim-holders-table.ts` `ContactHolder`
116
+ * exactly — the wire shape is an OBJECT, not a string (hub-edge passes
117
+ * `body.holder` through verbatim). `kind` selects the drain policy (`exec` is
118
+ * exempt from release-by-session, C6); `id` is the session id or exec process
119
+ * identity. C4's `hold` always presents `{ kind: 'session', id }` (D5: `id`
120
+ * falls back to `anon:<hostname>:<pid>` when no session id is configured — a
121
+ * holder is now ALWAYS sent, never omitted).
122
+ *
123
+ * `shiftId` (W7) is the self-declared Shift process incarnation id
124
+ * (`shf_<uuid>`) that dispatched this holder, when known — advisory only
125
+ * (D8/INV-82), never used for authorization/routing/dispatch/claim decisions.
126
+ * Nested-object convention: camelCase on the wire (unlike `PresencePingRequest`'s
127
+ * top-level snake_case fields above) — this asymmetry is deliberate.
128
+ */
129
+ export interface ContactHolder {
130
+ kind: 'session' | 'exec';
131
+ id: string;
132
+ shiftId?: string;
133
+ }
134
+ export interface GetOrderRequest {
135
+ workflow: string;
136
+ run: string;
137
+ /** B3 holder tag distinguishing a session-hold from an exec run. */
138
+ holder?: ContactHolder;
139
+ }
140
+ /**
141
+ * Live lease state for a run, mirroring hub-core `get-order.ts`'s `lease`:
142
+ * `claimed` is whether THIS run still holds its task's claim (with no terminal
143
+ * `outcome`); `outcome` is set once the run has closed. hold reads these two to
144
+ * classify a heartbeat failure — `outcome` set ⇒ the order finished (benign);
145
+ * `claimed: false` with no outcome ⇒ the lease was lost.
146
+ */
147
+ export interface Lease {
148
+ claimed: boolean;
149
+ claimedAt?: number;
150
+ heartbeatAt?: number;
151
+ outcome?: string;
152
+ }
153
+ /**
154
+ * The persisted A1 order packet get_order re-serves, mirroring owenloop engine
155
+ * `Order` (verified against owenloop-service `packages/engine-do/dist/vendor/
156
+ * engine/engine.d.ts` on 2026-07-17). exec reads `command`/`executor`/`workdir`
157
+ * to run the order and `owes` to know which output paths to submit the receipt
158
+ * to; every other field is carried for completeness. `command` is opaque — the
159
+ * engine never parses it; exec is the one process that shells it out.
160
+ */
161
+ export interface OrderPacket {
162
+ run: string;
163
+ workflow: string;
164
+ step: string;
165
+ key: string;
166
+ index?: number;
167
+ inputs: string[];
168
+ outputs: string[];
169
+ /** Opaque location hint — exec's command cwd when set. */
170
+ workdir?: string;
171
+ model?: string;
172
+ /** Executor kind; `'command'` for a command order, absent = `'agent'`. */
173
+ executor?: string;
174
+ /** The command string for a `executor: command` order (opaque). */
175
+ command?: string;
176
+ spec?: Record<string, unknown>;
177
+ x?: Record<string, unknown>;
178
+ prompt: string;
179
+ consumes: Record<string, unknown>;
180
+ /** The owed outputs + their reason threads — exec submits the receipt to each. */
181
+ owes: Array<{
182
+ path: string;
183
+ acceptance: string;
184
+ judgmentRejects: number;
185
+ schemaRejects: number;
186
+ reasons: ReasonEntry[];
187
+ }>;
188
+ cause?: string;
189
+ }
190
+ /** One entry in an artifact's append-only reason thread (loose mirror). */
191
+ export interface ReasonEntry {
192
+ at: number;
193
+ action: string;
194
+ kind: string;
195
+ by: string;
196
+ text: string;
197
+ fromVersion?: number;
198
+ }
199
+ export interface GetOrderResponse extends HubResponse {
200
+ workflow: string;
201
+ run: string;
202
+ /** The persisted order packet, or `null` for a pre-v7 run. */
203
+ order: OrderPacket | null;
204
+ lease: Lease;
205
+ }
206
+ export interface HeartbeatRequest {
207
+ workflow: string;
208
+ run: string;
209
+ holder?: ContactHolder;
210
+ }
211
+ export type HeartbeatResponse = HubResponse;
212
+ export type ReleaseRequest = {
213
+ session: string;
214
+ } | {
215
+ workflow: string;
216
+ run: string;
217
+ };
218
+ /**
219
+ * Response shapes mirror hub-core `verbs/release.ts` (verified 2026-07-18):
220
+ * - by-session: `{ released: Array<{workflow, run}> }` — the agent-held claims
221
+ * that were re-offered (empty when nothing was held). Exec-held claims are
222
+ * excluded server-side (SQL `holder_kind = 'exec'` is not in the session
223
+ * set); the hub does NOT enumerate them, so the client can only NOTE the
224
+ * drain-exempt-ion, never list which claims were exempt.
225
+ * - targeted: `{ released: boolean, reason?, workflow?, run? }` — idempotent
226
+ * (a not-held target is `released: false`, not an error).
227
+ *
228
+ * The by-session form's `released` array is REQUIRED (the drain role reads it);
229
+ * the targeted form's fields are all optional so callers that only do a
230
+ * fire-and-forget targeted release (hold/exec's final breath) need not model
231
+ * the payload — they ignore the response entirely.
232
+ */
233
+ export interface ReleaseSessionResponse extends HubResponse {
234
+ released: Array<{
235
+ workflow: string;
236
+ run: string;
237
+ }>;
238
+ }
239
+ export interface ReleaseTargetedResponse extends HubResponse {
240
+ released?: boolean;
241
+ reason?: string;
242
+ workflow?: string;
243
+ run?: string;
244
+ }
245
+ export type ReleaseResponse = ReleaseSessionResponse | ReleaseTargetedResponse;
246
+ export interface SubmitRequest {
247
+ workflow: string;
248
+ run: string;
249
+ path: string;
250
+ value: unknown;
251
+ done?: boolean;
252
+ /** W7: who produced this submission (D4) — carried on all three submit paths. */
253
+ holder?: ContactHolder;
254
+ }
255
+ /**
256
+ * submit's flattened `{ text, ...data }` envelope (verified against hub-core
257
+ * `verbs/submit.ts` + hub-edge `routes.ts` on 2026-07-17). `outcome` is the
258
+ * commit verdict: `green`/`submitted` are success (the value landed);
259
+ * `schema-rejected`/`born-rejected`/`artifact-too-large`/
260
+ * `artifact-normalization-failed` are failures. `closed` reports whether that
261
+ * submit closed the run (only present on a `green`/`submitted` outcome). exec
262
+ * treats any non-green/submitted outcome as a failed submit (exit 1).
263
+ */
264
+ export interface SubmitResponse extends HubResponse {
265
+ outcome?: string;
266
+ closed?: boolean;
267
+ }
268
+ export interface WhoamiResponse extends HubResponse {
269
+ orgId: string;
270
+ orgName: string;
271
+ actor: {
272
+ id: string;
273
+ kind: 'member' | 'agent';
274
+ role: 'admin' | 'author' | 'operator' | 'agent';
275
+ scopes: string[];
276
+ };
277
+ tokenStatus: 'active';
278
+ authMethod: 'token' | 'oauth' | 'session' | 'debug';
279
+ email?: string;
280
+ }
281
+ /**
282
+ * Thrown for any non-2xx hub response. `code` is the hub's `error` slug
283
+ * (e.g. `bad_request`) when the body parsed as the hub's `{ error, message }`
284
+ * JSON; otherwise `message` carries the raw response text.
285
+ */
286
+ export declare class HubError extends Error {
287
+ readonly status: number;
288
+ readonly code?: string;
289
+ constructor(status: number, message: string, code?: string);
290
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Typed request/response shapes for the hub verb surface owenloop's roles call.
3
+ *
4
+ * These mirror `apps/hub-edge/src/api/routes.ts` on owenloop-service `origin/main`
5
+ * (B3 lifecycle verbs are merged). Every REST verb returns `{ text, ...data }`
6
+ * where `data` is always an object, so each response extends `HubResponse`.
7
+ *
8
+ * Response payloads are typed LOOSELY on purpose: the roles that consume the
9
+ * data fields (whats_next orders, get_order body, …) land in C3–C5. Honest-loose
10
+ * (`unknown[]` + a TODO) beats invented-precise shapes no consumer reads yet.
11
+ */
12
+ // ---- errors -----------------------------------------------------------------
13
+ /**
14
+ * Thrown for any non-2xx hub response. `code` is the hub's `error` slug
15
+ * (e.g. `bad_request`) when the body parsed as the hub's `{ error, message }`
16
+ * JSON; otherwise `message` carries the raw response text.
17
+ */
18
+ export class HubError extends Error {
19
+ status;
20
+ code;
21
+ constructor(status, message, code) {
22
+ super(message);
23
+ this.name = 'HubError';
24
+ this.status = status;
25
+ if (code !== undefined)
26
+ this.code = code;
27
+ }
28
+ }