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,283 @@
1
+ /**
2
+ * The harness contract — the ONLY thing every harness adapter implements, and
3
+ * the only shapes the worker speaks.
4
+ *
5
+ * Why it exists: owenloop moved from writing per-order subagent files into
6
+ * a vendor CLI's own directory and handing a lean order to an external Shift,
7
+ * to HOSTING each step agent itself behind a per-harness adapter, with a
8
+ * provider-native session token persisted per step attempt so a rejected step
9
+ * can be RESUMED rather than restarted. This file is the seam that makes the
10
+ * hosting side harness-agnostic.
11
+ *
12
+ * Failure stance: this module is pure declaration plus one error class. It
13
+ * performs no I/O, spawns nothing, and cannot fail. Every runtime concern
14
+ * (process launch, stream parsing, credential handling) belongs to an adapter.
15
+ *
16
+ * ISOLATION RULE (enforced by `test/harness-isolation.test.ts`): no file under
17
+ * `src/harness/` may name a harness vendor except the per-harness adapter
18
+ * modules themselves. That rule is why the comments in this file describe vendor
19
+ * behavior generically instead of naming the vendor.
20
+ */
21
+ import type { LintFinding } from './types.ts';
22
+ /**
23
+ * How well a harness can pick a conversation back up.
24
+ *
25
+ * - `native-token` — the provider stores the session and resumes it from an
26
+ * opaque token (the token in `HarnessSessionRef`).
27
+ * - `keep-alive` — resume only works while the adapter's own process is
28
+ * still alive; a restart loses the session.
29
+ * - `replay` — no resume at all; the caller re-sends the whole brief.
30
+ *
31
+ * Declarative metadata in Phase 1 — nothing branched on it then. Phase 4's
32
+ * resume-on-rejection decision in `src/agent/loop.ts` is the first consumer: a
33
+ * `replay`-tier adapter is never asked to `deliver`, it is always cold-started.
34
+ */
35
+ export type ResumeTier = 'native-token' | 'keep-alive' | 'replay';
36
+ /** A handle to one live-or-resumable provider session. */
37
+ export interface HarnessSessionRef {
38
+ /** Adapter id — the same string `HarnessAdapter.id` carries. */
39
+ harness: string;
40
+ /** Provider-native session/thread id. Opaque here; only its adapter parses it.
41
+ * Machine-local by design: it has no meaning off this machine and is NEVER
42
+ * sent to the hub. */
43
+ token: string;
44
+ }
45
+ /**
46
+ * Telemetry from a running turn.
47
+ *
48
+ * THE HUB IS TRUTH; THIS STREAM IS TELEMETRY + LIVENESS. The step agent signals
49
+ * TASK completion by calling the `submit` MCP tool (registered in
50
+ * `src/hold/mcp.ts` — locate `submitTool` by grep, not by line number). The
51
+ * worker learns that the order finished from `Lease.outcome` on `get_order`
52
+ * (the `outcome` field on `Lease` in `src/hub/types.ts`; the mechanism is
53
+ * mapped in `docs/agent-runner.md` §(b)) — NEVER from an `exited` event. An
54
+ * adapter that stops emitting says nothing about whether the work was accepted.
55
+ */
56
+ export type AgentEvent = {
57
+ kind: 'started';
58
+ ref: HarnessSessionRef;
59
+ }
60
+ /** Optional log line. Adapters may emit none; nothing may depend on it. */
61
+ | {
62
+ kind: 'progress';
63
+ text: string;
64
+ }
65
+ /** The harness surfaced a blocking question. Phase 1 defines the EVENT only —
66
+ * this contract has no reply channel, and adding one is Phase 3/4's call. */
67
+ | {
68
+ kind: 'needs_input';
69
+ question: string;
70
+ }
71
+ /** The model turn completed (the SDK result message on an in-process SDK
72
+ * path; `turn/completed` on an app-server path). */
73
+ | {
74
+ kind: 'turn_ended';
75
+ } | {
76
+ kind: 'exited';
77
+ exitCode: number | null;
78
+ error?: string;
79
+ };
80
+ /**
81
+ * The step-def permission fields, normalized into a harness-neutral struct.
82
+ *
83
+ * Declared HERE rather than beside its normalizer in `permissions.ts` because
84
+ * both adapters read the type as part of the contract surface: `permissions.ts`
85
+ * imports this type, giving one dependency direction and no cycle.
86
+ *
87
+ * Produced by `normalizeStepPermissions` (`./permissions.ts`).
88
+ */
89
+ export interface StepPermissions {
90
+ /** Allowed tool names. Absent (not `[]`) when the step named none. */
91
+ tools?: string[];
92
+ /** Denied tool names. Absent (not `[]`) when the step named none. */
93
+ disallowedTools?: string[];
94
+ /** Opaque, passed through verbatim; each adapter maps it to its own
95
+ * vocabulary. Not validated here — `owenloop work lint` already validates the bag. */
96
+ permissionMode?: string;
97
+ /** Only ever a positive integer; anything else was dropped in normalization. */
98
+ maxTurns?: number;
99
+ model?: string;
100
+ effort?: string;
101
+ /** Everything with no harness-neutral meaning, verbatim. Only the OWNING
102
+ * adapter reads its own keys. REQUIRED — always present, possibly `{}` — so
103
+ * no adapter needs a null check. */
104
+ extensions: Record<string, unknown>;
105
+ }
106
+ /** Everything an adapter needs to launch one step agent. */
107
+ export interface StartArgs {
108
+ /** The fully rendered step prompt. */
109
+ brief: string;
110
+ /** The order's working directory (the provisioned worktree). */
111
+ cwd: string;
112
+ /**
113
+ * PER-START OVERRIDE, not the step's configured model.
114
+ *
115
+ * PRECEDENCE — every adapter resolves `args.model ?? args.permissions.model`
116
+ * (and `args.effort ?? args.permissions.effort`). `StepPermissions.model` is
117
+ * the normalized step-def value; this field is the worker's override channel
118
+ * (e.g. escalating the model on a retry). Stated here because plan §3 puts
119
+ * `model`/`effort` on both shapes without saying which wins; left unresolved,
120
+ * the parallel adapter tracks would each pick a different answer and the
121
+ * divergence would only surface in production.
122
+ */
123
+ model?: string;
124
+ /** Per-start override for reasoning effort. Same precedence rule as `model`. */
125
+ effort?: string;
126
+ /**
127
+ * The stdio mount for owenloop's own work-holder MCP surface (bare
128
+ * `get_order`/`submit`).
129
+ *
130
+ * BUILT BY THE WORKER, NOT BY AN ADAPTER: `src/agent/brief.ts` constructs the
131
+ * born-bound `hold --order <workflow>/<run> --origin <url> --as <account>
132
+ * --shift=<cid> --mcp` argv from the live order. An adapter mounts it
133
+ * verbatim and never constructs it — the order id, origin, and account ride
134
+ * argv, never the prompt.
135
+ */
136
+ owenloopMcp: {
137
+ command: string;
138
+ args: string[];
139
+ };
140
+ /** Normalized from the step def by `normalizeStepPermissions`. */
141
+ permissions: StepPermissions;
142
+ }
143
+ /**
144
+ * Everything an adapter needs to RESUME an existing session with one message.
145
+ *
146
+ * WHY IT CARRIES `permissions` (Phase 4). Phase 2A observation 1 and Phase 2B
147
+ * observation 1 recorded the same defect from opposite ends: both adapters kept
148
+ * the resolved vendor option set in an in-process map keyed by session token, and
149
+ * `deliver` read that map as its source of truth. A resume that happens in a
150
+ * DIFFERENT PROCESS from the `start` — which is exactly the Phase 4 case, because
151
+ * a re-offer is dispatched as a fresh `owenloop work agent-run` child — misses the map
152
+ * and used to degrade silently to a minimal option set. The resumed turn then ran
153
+ * with weaker, looser permissions than the turn it was continuing.
154
+ *
155
+ * The fix is to pass the same normalized `StepPermissions` that `start` got. The
156
+ * caller already has it: `src/agent/loop.ts` computes it with
157
+ * `normalizeStepPermissions(rawBag, material.def)` from `material.def.x[<id>]` on
158
+ * the resume path too. The rejected alternative was persisting the resolved
159
+ * vendor options blob beside the `SessionRecord`, which would put vendor-shaped
160
+ * data into the deliberately vendor-free session store and would need a migration
161
+ * every time a vendor moved its option shape.
162
+ *
163
+ * CONTRACT FOR ADAPTERS: the passed `permissions` WINS. An adapter may keep its
164
+ * in-memory map as a fast path for other state (an abort controller, a live
165
+ * client), but it must map these `permissions` rather than whatever the map
166
+ * happened to hold, and it must NOT fall back to a minimal option set on a map
167
+ * miss.
168
+ */
169
+ export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort'>;
170
+ /**
171
+ * One harness implementation.
172
+ *
173
+ * TURN END, NOT PROCESS END: both `start` and `deliver` resolve when the model
174
+ * TURN ends — the SDK result message on an in-process SDK path, `turn/completed`
175
+ * on an app-server path (verified present in the pinned app-server's default
176
+ * schema, `docs/agent-runner.md` §(d)). They do NOT wait for the harness process
177
+ * to exit, and resolving says nothing about whether the task succeeded (see
178
+ * `AgentEvent`: the hub is truth).
179
+ *
180
+ * ERROR NORMALIZATION: a provider that no longer knows the session token must
181
+ * surface as a rejected promise carrying `ResumeUnavailableError`, so the caller
182
+ * can fall back to a cold replay. EVERY other failure surfaces as an `exited`
183
+ * event carrying `error`.
184
+ *
185
+ * DELIBERATELY ABSENT — do not add either without re-opening the contract:
186
+ * - an `allowApiBilling` flag on `StartArgs`. Stripping inherited provider
187
+ * API-key environment variables from a child environment (they silently
188
+ * shadow subscription OAuth and bill API credits) is MACHINE-LEVEL config,
189
+ * not per-start data; the adapter that needs the toggle reads it from
190
+ * env/settings inside its own module.
191
+ * - a reply channel for `needs_input` (see that event's own note).
192
+ */
193
+ export interface HarnessAdapter {
194
+ /** Registry key — the adapter's own harness id. Stable across versions. */
195
+ id: string;
196
+ resumeTier: ResumeTier;
197
+ /**
198
+ * Launch a NEW session. Resolves at turn end with the session ref.
199
+ *
200
+ * Emits `{kind:'started', ref}` BEFORE it resolves, and the caller is
201
+ * expected to persist the token on THAT event rather than on the resolve —
202
+ * so a mid-turn crash still leaves a resumable record behind.
203
+ */
204
+ start(args: StartArgs, onEvent: (e: AgentEvent) => void): Promise<HarnessSessionRef>;
205
+ /**
206
+ * Deliver a message into an EXISTING session (resume). Resolves at turn end.
207
+ * Rejects with `ResumeUnavailableError` when the provider no longer knows the
208
+ * token — the caller then falls back to replay. Never re-emits `started`.
209
+ *
210
+ * `args.permissions` is authoritative — see `DeliverArgs`.
211
+ */
212
+ deliver(ref: HarnessSessionRef, message: string, args: DeliverArgs, onEvent: (e: AgentEvent) => void): Promise<void>;
213
+ /** Tear the session down. Idempotent; an already-dead session is not an error. */
214
+ stop(ref: HarnessSessionRef): Promise<void>;
215
+ /**
216
+ * OPTIONAL static check of one step's harness option bag, for `owenloop work lint`.
217
+ *
218
+ * `bag` is the step's `x.harness` map with `id` already removed — the same
219
+ * option map `normalizeStepPermissions` receives at prepare time. `step` is the
220
+ * step name, used only to label findings.
221
+ *
222
+ * Optional because linting is a convenience, not part of running an order: an
223
+ * adapter that declares nothing about its option vocabulary simply omits it and
224
+ * `owenloop work lint` reports no findings for steps that select it. An adapter must
225
+ * NOT throw from here — a lint pass over a malformed bag returns findings.
226
+ */
227
+ lintStep?(bag: Record<string, unknown>, step: string): LintFinding[];
228
+ /**
229
+ * OPTIONAL — the command a HUMAN would run to open this session interactively,
230
+ * for `owenloop work sessions` to print.
231
+ *
232
+ * WHY THIS IS ON THE CONTRACT AND NOT IN THE SUBCOMMAND. The resume command is
233
+ * vendor-specific by nature. A `switch (rec.harness)` in `src/roles/sessions.ts`
234
+ * would put vendor BEHAVIOR outside `src/harness/`, which is the one thing the
235
+ * harness layer exists to prevent; `test/vendor-gate.test.ts` would fail such a
236
+ * file, correctly. The harness id in a `SessionRecord` is DATA — the mapping
237
+ * from that data to a command is behavior, and behavior lives here.
238
+ *
239
+ * WHY IT RETURNS `{command, args}` AND NOT A STRING. The caller decides how to
240
+ * render — shell-quoted, tabulated, or as JSON — so no adapter has to guess a
241
+ * display format. An adapter must honour its own binary-override variable here,
242
+ * so an operator who points an execution adapter at a non-default binary gets a command
243
+ * that actually runs on their machine.
244
+ *
245
+ * WHY IT IS NOT PERSISTED IN `SessionRecord`. The session store is
246
+ * deliberately vendor-free (see `DeliverArgs` above), and a rendered string
247
+ * would go stale the moment a vendor changes its CLI.
248
+ *
249
+ * Optional, following `lintStep?`: an adapter with no interactive resume omits
250
+ * it and `owenloop work sessions` prints a dash. An adapter must NOT throw from
251
+ * here — this is display, and a listing that crashes on one row is worse than
252
+ * a row with no command.
253
+ */
254
+ resumeCommand?(ref: HarnessSessionRef): {
255
+ command: string;
256
+ args: string[];
257
+ };
258
+ }
259
+ /** The `code` every `ResumeUnavailableError` carries. Match on THIS, not on the class. */
260
+ export declare const RESUME_UNAVAILABLE = "RESUME_UNAVAILABLE";
261
+ /**
262
+ * The provider no longer knows the session token — resume is impossible and the
263
+ * caller must fall back to a cold replay.
264
+ *
265
+ * Fields are assigned as class-field initializers / in the constructor body:
266
+ * `erasableSyntaxOnly` is on in this repo, so constructor parameter properties
267
+ * do not compile.
268
+ */
269
+ export declare class ResumeUnavailableError extends Error {
270
+ readonly code: string;
271
+ constructor(message: string);
272
+ }
273
+ /**
274
+ * The supported way to test for a resume failure. Checks the `code` FIELD, not
275
+ * `instanceof`.
276
+ *
277
+ * Reason this is not `instanceof`: tests import from `src/` while the published
278
+ * package resolves `dist/`. Two module instances of this file mean two distinct
279
+ * class objects, and `instanceof` across them silently returns `false` — which
280
+ * would make the resume fallback never fire, in exactly the dual-resolution
281
+ * setup this repo has.
282
+ */
283
+ export declare function isResumeUnavailable(err: unknown): err is ResumeUnavailableError;
@@ -0,0 +1,32 @@
1
+ /** The `code` every `ResumeUnavailableError` carries. Match on THIS, not on the class. */
2
+ export const RESUME_UNAVAILABLE = 'RESUME_UNAVAILABLE';
3
+ /**
4
+ * The provider no longer knows the session token — resume is impossible and the
5
+ * caller must fall back to a cold replay.
6
+ *
7
+ * Fields are assigned as class-field initializers / in the constructor body:
8
+ * `erasableSyntaxOnly` is on in this repo, so constructor parameter properties
9
+ * do not compile.
10
+ */
11
+ export class ResumeUnavailableError extends Error {
12
+ code = RESUME_UNAVAILABLE;
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = 'ResumeUnavailableError';
16
+ }
17
+ }
18
+ /**
19
+ * The supported way to test for a resume failure. Checks the `code` FIELD, not
20
+ * `instanceof`.
21
+ *
22
+ * Reason this is not `instanceof`: tests import from `src/` while the published
23
+ * package resolves `dist/`. Two module instances of this file mean two distinct
24
+ * class objects, and `instanceof` across them silently returns `false` — which
25
+ * would make the resume fallback never fire, in exactly the dual-resolution
26
+ * setup this repo has.
27
+ */
28
+ export function isResumeUnavailable(err) {
29
+ if (typeof err !== 'object' || err === null)
30
+ return false;
31
+ return err.code === RESUME_UNAVAILABLE;
32
+ }
@@ -0,0 +1,59 @@
1
+ import type { AgentEvent, DeliverArgs, HarnessAdapter, HarnessSessionRef, ResumeTier, StartArgs } from './contract.ts';
2
+ /** One scripted call — what `start` or a single `deliver` does. */
3
+ export interface FakeScript {
4
+ /** Events emitted, in order, before the call settles. `start` emits its own
5
+ * `started` first unless the script already supplies one. */
6
+ events?: AgentEvent[];
7
+ /** Reject with `ResumeUnavailableError` INSTEAD of running — no events at all.
8
+ * This is the "provider forgot the session" case the resume fallback needs. */
9
+ resumeUnavailable?: boolean;
10
+ /** Emit the events, THEN reject with a plain `Error` carrying this message —
11
+ * death mid-turn. Combine with a partial `events` list to model a session
12
+ * that died with work in flight. */
13
+ dieWith?: string;
14
+ }
15
+ /** The fixture a fake adapter is built from. Every field has a default. */
16
+ export interface FakeSpec {
17
+ /** Adapter id and `HarnessSessionRef.harness`. Default `'fake'`. */
18
+ id?: string;
19
+ /** Default `'native-token'`. Declarative only — nothing branches on it yet. */
20
+ resumeTier?: ResumeTier;
21
+ /** The session token handed back. Default `'fake-token-1'`. */
22
+ token?: string;
23
+ start?: FakeScript;
24
+ /** One script, or an array consumed one script per successive `deliver` call
25
+ * (the LAST entry repeats once the array is exhausted). */
26
+ deliver?: FakeScript | FakeScript[];
27
+ }
28
+ /** One recorded method call, so a test can assert WHICH method ran with what. */
29
+ export type FakeCall = {
30
+ kind: 'start';
31
+ args: StartArgs;
32
+ }
33
+ /** `args` is recorded from Phase 4 on: the widened `DeliverArgs` carries the
34
+ * `permissions` a resumed turn must run under, and "did the resume keep the
35
+ * original permission context?" is only assertable if the fake keeps it. */
36
+ | {
37
+ kind: 'deliver';
38
+ ref: HarnessSessionRef;
39
+ message: string;
40
+ args: DeliverArgs;
41
+ } | {
42
+ kind: 'stop';
43
+ ref: HarnessSessionRef;
44
+ };
45
+ /**
46
+ * A `HarnessAdapter` plus an inspectable call log.
47
+ *
48
+ * The log is what lets a drill assert, for example, that a re-armed step called
49
+ * `deliver` (resume) and NOT `start` (cold replay), carrying the rejection
50
+ * reasons as its message — the exact assertion Phase 4 needs.
51
+ */
52
+ export interface FakeAdapter extends HarnessAdapter {
53
+ readonly calls: FakeCall[];
54
+ }
55
+ /**
56
+ * Build a fake adapter from a fixture. Registers nothing — the caller decides
57
+ * whether it goes into the registry.
58
+ */
59
+ export declare function createFakeAdapter(spec?: FakeSpec): FakeAdapter;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `FakeAdapter` — a scripted `HarnessAdapter` with no I/O, no child process, and
3
+ * no real timers. It exists so Phase 3's worker and the drills can be developed
4
+ * and tested before any real adapter lands, and so failure modes that are hard
5
+ * to provoke against a real provider (an unresumable session, a death mid-turn)
6
+ * are one fixture field away.
7
+ *
8
+ * TEST-ONLY EXPORT — meaning NO PRODUCTION CALLER, not "not shipped". Three
9
+ * mechanisms enforce that, all of them live today:
10
+ * 1. This module has ZERO import side effects — in particular it does NOT call
11
+ * `register(...)`. A test constructs an adapter and registers it explicitly,
12
+ * then unregisters it in `afterEach`.
13
+ * 2. No file under `src/` imports this module, and there is no barrel/index
14
+ * under `src/harness/` through which it could leak. Do not add one.
15
+ * 3. `test/harness-isolation.test.ts` asserts (2) mechanically, by walking
16
+ * `src/` and failing on any import of `fake.ts` from outside this file.
17
+ *
18
+ * It IS compiled into `dist/` by `tsconfig.build.json`'s `src/**` include. That
19
+ * is accepted deliberately: carving it out would desynchronize `tsc --noEmit`
20
+ * from the build, and the no-caller rule is what actually matters.
21
+ *
22
+ * Failure stance: total and deterministic. Everything it does is drive the
23
+ * script it was handed; the only failures are the ones a script asks for.
24
+ */
25
+ import { ResumeUnavailableError } from "./contract.js";
26
+ const EMPTY_SCRIPT = {};
27
+ /** Pick the script for the Nth `deliver`; the last entry repeats forever. */
28
+ function scriptAt(spec, index) {
29
+ if (spec === undefined)
30
+ return EMPTY_SCRIPT;
31
+ if (!Array.isArray(spec))
32
+ return spec;
33
+ if (spec.length === 0)
34
+ return EMPTY_SCRIPT;
35
+ const clamped = index < spec.length ? index : spec.length - 1;
36
+ return spec[clamped] ?? EMPTY_SCRIPT; // noUncheckedIndexedAccess
37
+ }
38
+ /** Emit the script's events with a microtask hop between them, so an observer
39
+ * sees them arrive asynchronously the way a real stream delivers them. */
40
+ async function emit(events, onEvent) {
41
+ for (const e of events) {
42
+ await Promise.resolve();
43
+ onEvent(e);
44
+ }
45
+ }
46
+ /**
47
+ * Build a fake adapter from a fixture. Registers nothing — the caller decides
48
+ * whether it goes into the registry.
49
+ */
50
+ export function createFakeAdapter(spec = {}) {
51
+ const id = spec.id ?? 'fake';
52
+ const token = spec.token ?? 'fake-token-1';
53
+ const ref = { harness: id, token };
54
+ const calls = [];
55
+ let deliverIndex = 0;
56
+ return {
57
+ id,
58
+ resumeTier: spec.resumeTier ?? 'native-token',
59
+ calls,
60
+ async start(args, onEvent) {
61
+ calls.push({ kind: 'start', args });
62
+ const script = spec.start ?? EMPTY_SCRIPT;
63
+ if (script.resumeUnavailable === true) {
64
+ throw new ResumeUnavailableError(`fake adapter '${id}': session '${token}' is not resumable`);
65
+ }
66
+ const scripted = script.events ?? [];
67
+ const hasStarted = scripted.some((e) => e.kind === 'started');
68
+ const events = hasStarted ? scripted : [{ kind: 'started', ref }, ...scripted];
69
+ await emit(events, onEvent);
70
+ if (script.dieWith !== undefined)
71
+ throw new Error(script.dieWith);
72
+ return ref;
73
+ },
74
+ async deliver(target, message, args, onEvent) {
75
+ calls.push({ kind: 'deliver', ref: target, message, args });
76
+ const script = scriptAt(spec.deliver, deliverIndex);
77
+ deliverIndex += 1;
78
+ if (script.resumeUnavailable === true) {
79
+ throw new ResumeUnavailableError(`fake adapter '${id}': session '${target.token}' is not resumable`);
80
+ }
81
+ // `deliver` resumes an existing session, so it never re-emits `started`.
82
+ await emit(script.events ?? [], onEvent);
83
+ if (script.dieWith !== undefined)
84
+ throw new Error(script.dieWith);
85
+ },
86
+ async stop(target) {
87
+ calls.push({ kind: 'stop', ref: target });
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,108 @@
1
+ /** One decoded inbound frame. Every member is optional — see `classifyFrame`. */
2
+ export interface JsonRpcFrame {
3
+ id?: number | string | null;
4
+ method?: string;
5
+ params?: unknown;
6
+ result?: unknown;
7
+ error?: {
8
+ code: number;
9
+ message: string;
10
+ data?: unknown;
11
+ };
12
+ }
13
+ /** A JSON-RPC `error` object, surfaced as a rejection from `request`. */
14
+ export declare class JsonRpcError extends Error {
15
+ readonly code: number;
16
+ readonly data: unknown;
17
+ constructor(code: number, message: string, data?: unknown);
18
+ }
19
+ /** The dispatch callbacks both layers share. */
20
+ export interface RpcHandlers {
21
+ /** Every server→client NOTIFICATION (a frame with `method` and no `id`). */
22
+ onNotification(method: string, params: unknown): void;
23
+ /**
24
+ * Every server→client REQUEST (a frame with both `method` and `id`). Resolve
25
+ * with the result value, or throw to make the client reply with a JSON-RPC
26
+ * error. The client ALWAYS writes exactly one reply either way: an unanswered
27
+ * server request blocks the server's turn indefinitely.
28
+ */
29
+ onServerRequest(method: string, params: unknown, id: number | string): Promise<unknown>;
30
+ /**
31
+ * Diagnostics. Carries the child's stderr line by line AND this client's own
32
+ * read-path complaints (unparseable line, unknown response id, unclassifiable
33
+ * frame). A reporting channel, not an error channel — nothing on it is fatal,
34
+ * and nothing under `src/` may print.
35
+ */
36
+ onStderr(line: string): void;
37
+ }
38
+ export interface RpcCoreOptions extends RpcHandlers {
39
+ /** Sink for one outbound frame, already serialized and newline-terminated. */
40
+ write(line: string): void;
41
+ /** Per-request timeout in ms. Default 120_000. */
42
+ requestTimeoutMs?: number;
43
+ }
44
+ export interface RpcCore {
45
+ request<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T>;
46
+ notify(method: string, params?: unknown): void;
47
+ /** Feed one chunk of the inbound byte stream. Chunk boundaries are arbitrary. */
48
+ onData(chunk: Buffer | string): void;
49
+ /** Reject every in-flight request (disposal, child exit, spawn failure). */
50
+ rejectAll(err: Error): void;
51
+ /** How many requests are still awaiting a response. For tests and assertions. */
52
+ pendingCount(): number;
53
+ }
54
+ export interface StdioRpcOptions extends RpcHandlers {
55
+ /** Executable to spawn. Resolved through `PATH` when it is a bare name. */
56
+ command: string;
57
+ args: string[];
58
+ cwd?: string;
59
+ /**
60
+ * The child's environment. OMITTED means "inherit this process's environment
61
+ * untouched" (node's own `spawn` default) — that is a recorded decision for
62
+ * this transport, not an oversight. When supplied it REPLACES the child's
63
+ * environment wholesale, so a caller that supplies it must pass a full
64
+ * environment, not a set of deltas.
65
+ */
66
+ env?: Record<string, string | undefined>;
67
+ /** Per-request timeout in ms. Default 120_000. */
68
+ requestTimeoutMs?: number;
69
+ /** Child process exit. Fires once, after every pending request is rejected. */
70
+ onExit(code: number | null, signal: NodeJS.Signals | null): void;
71
+ }
72
+ export interface StdioRpcClient {
73
+ request<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T>;
74
+ notify(method: string, params?: unknown): void;
75
+ /** SIGTERM the child's process group, SIGKILL after a grace period. Idempotent. */
76
+ dispose(): Promise<void>;
77
+ readonly pid: number | undefined;
78
+ }
79
+ /** What a decoded inbound frame turns out to be. */
80
+ export type FrameKind = 'response' | 'server-request' | 'notification' | 'unknown';
81
+ /**
82
+ * Classify a decoded frame.
83
+ *
84
+ * DELIBERATELY DOES NOT LOOK AT `jsonrpc`. The server this client was written
85
+ * against omits the `jsonrpc` member from every inbound frame — responses
86
+ * arrive as `{id, result}`, errors as `{error, id}`, notifications as
87
+ * `{method, params, emittedAtMs}`. A validator that requires `jsonrpc === '2.0'`
88
+ * rejects 100% of real traffic, so classification keys on the presence of
89
+ * `id` / `method` / `result` / `error` only, in this order.
90
+ *
91
+ * Exported so a unit test can pin the rule directly.
92
+ */
93
+ export declare function classifyFrame(frame: JsonRpcFrame): FrameKind;
94
+ /**
95
+ * A line-oriented, UTF-8-safe reader over a byte stream.
96
+ *
97
+ * `StringDecoder` is what makes a multi-byte character split across two chunks
98
+ * survive: decoding each chunk independently emits replacement characters at
99
+ * the seam. Exported so the framing tests can drive it directly.
100
+ */
101
+ export declare function createLineReader(onLine: (line: string) => void): (chunk: Buffer | string) => void;
102
+ /**
103
+ * The protocol engine: framing in, correlation and dispatch out, over an
104
+ * injected `write`. Knows nothing about processes.
105
+ */
106
+ export declare function createRpcCore(opts: RpcCoreOptions): RpcCore;
107
+ /** Spawn `command args` and speak newline-delimited JSON-RPC to its stdio. */
108
+ export declare function startStdioRpc(opts: StdioRpcOptions): StdioRpcClient;