@asterxsk/kiln 0.1.0 → 0.2.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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,300 +1,300 @@
1
- /**
2
- * Scripted stub sessions shared by all three backend implementations while
3
- * the real integrations are pending. A stub session:
4
- *
5
- * - streams a plausible turn (thinking deltas, one fake tool cycle, text
6
- * deltas, usage ramp, a final assistant message, RunSettled) over a few
7
- * seconds so streaming UI, wait, and the footer counters are observable;
8
- * - supports send() while running (queued-steer rendering) and while idle
9
- * (fresh run);
10
- * - supports interrupt (RunSettled Interrupted -> status "error", matching v1);
11
- * - fails the run when the prompt starts with "FAIL:" (error-path testing);
12
- * - appends every event to a JSONL "session file" in tmpdir so the
13
- * "full transcript in session file" pointers resolve.
14
- */
15
-
16
- import * as fs from "node:fs";
17
- import * as os from "node:os";
18
- import * as path from "node:path";
19
- import type { Cause, Scope } from "effect";
20
- import { Duration, Effect, Fiber, Queue, Ref, Stream } from "effect";
21
- import type { SubagentBackend, SubagentSession } from "../backend.ts";
22
- import type {
23
- BackendName,
24
- QueuedMessage,
25
- SpawnTask,
26
- SubagentEvent,
27
- SubagentMeta,
28
- } from "../domain.ts";
29
- import { SendError } from "../domain.ts";
30
-
31
- export interface StubProfile {
32
- readonly backend: BackendName;
33
- readonly defaultModelLabel: string;
34
- readonly contextWindow: number;
35
- readonly toolName: string;
36
- /** Delay between scripted events; varies per backend so streams differ. */
37
- readonly cadenceMs: number;
38
- }
39
-
40
- const STUB_DIR = path.join(os.tmpdir(), "subagents-stub");
41
- let sessionCounter = 0;
42
-
43
- export function makeStubBackend(profile: StubProfile): SubagentBackend {
44
- return {
45
- name: profile.backend,
46
- capabilities: {
47
- steering: true,
48
- modelSelection: true,
49
- reasoningEffort: true,
50
- },
51
- // Real impls probe binary-on-PATH / SDK import / credentials here.
52
- available: Effect.succeed(true),
53
- spawn: (task) => makeStubSession(profile, task),
54
- };
55
- }
56
-
57
- function firstLine(text: string): string {
58
- return (
59
- text
60
- .split("\n")
61
- .find((line) => line.trim())
62
- ?.trim() ?? ""
63
- );
64
- }
65
-
66
- function chunked(text: string, size: number): string[] {
67
- const chunks: string[] = [];
68
- for (let i = 0; i < text.length; i += size)
69
- chunks.push(text.slice(i, i + size));
70
- return chunks;
71
- }
72
-
73
- const makeStubSession = (
74
- profile: StubProfile,
75
- task: SpawnTask,
76
- ): Effect.Effect<SubagentSession, never, Scope.Scope> =>
77
- Effect.gen(function* () {
78
- const sessionId = `stub-${profile.backend}-${++sessionCounter}`;
79
- const sessionFile = path.join(STUB_DIR, `${sessionId}.jsonl`);
80
-
81
- const state = {
82
- meta: {
83
- backend: profile.backend,
84
- modelLabel: task.model ?? profile.defaultModelLabel,
85
- contextWindow: profile.contextWindow,
86
- sessionFilePath: sessionFile,
87
- nativeSessionId: sessionId,
88
- } satisfies SubagentMeta as SubagentMeta,
89
- pending: [] as string[],
90
- turnCount: 0,
91
- closed: false,
92
- /** True between the driver dequeuing a prompt and registering its turn fiber. */
93
- dispatching: false,
94
- };
95
-
96
- const events = yield* Queue.make<SubagentEvent, Cause.Done>();
97
- const inbox = yield* Queue.make<string, Cause.Done>();
98
- const activeTurn = yield* Ref.make<Fiber.Fiber<void> | undefined>(
99
- undefined,
100
- );
101
-
102
- const emit = (event: SubagentEvent) =>
103
- Effect.suspend(() => {
104
- try {
105
- fs.appendFileSync(sessionFile, `${JSON.stringify(event)}\n`);
106
- } catch {
107
- // The fake session file is best-effort.
108
- }
109
- if (event._tag === "MetaChanged") {
110
- state.meta = { ...state.meta, ...event.meta };
111
- }
112
- return Queue.offer(events, event);
113
- }).pipe(Effect.asVoid);
114
-
115
- const pause = Effect.sleep(Duration.millis(profile.cadenceMs));
116
-
117
- const runTurn = (userText: string, turn: number) =>
118
- Effect.gen(function* () {
119
- yield* emit({ _tag: "RunStarted" });
120
- const failing = userText.trimStart().startsWith("FAIL:");
121
-
122
- const thinking = "Looking at the task and planning an approach...";
123
- for (const delta of chunked(thinking, 16)) {
124
- yield* emit({ _tag: "AssistantDelta", kind: "thinking", delta });
125
- yield* pause;
126
- }
127
-
128
- const toolId = `${sessionId}-tool-${turn}`;
129
- const argsPreview = `{"command":"ls ${task.cwd}"}`;
130
- yield* emit({
131
- _tag: "AssistantMessage",
132
- parts: [
133
- { type: "thinking", text: thinking },
134
- {
135
- type: "text",
136
- text: `I'll run ${profile.toolName} to look around first.`,
137
- },
138
- { type: "toolCall", toolId, name: profile.toolName, argsPreview },
139
- ],
140
- });
141
- yield* emit({
142
- _tag: "ToolStart",
143
- toolId,
144
- name: profile.toolName,
145
- argsPreview,
146
- });
147
- yield* pause;
148
- yield* emit({
149
- _tag: "ToolUpdate",
150
- toolId,
151
- outputPreview: "src docs package.json",
152
- });
153
- yield* pause;
154
- yield* emit({
155
- _tag: "ToolEnd",
156
- toolId,
157
- name: profile.toolName,
158
- isError: false,
159
- outputPreview: "src docs package.json",
160
- });
161
- yield* emit({
162
- _tag: "UsageChanged",
163
- tokens: Math.min(profile.contextWindow, 2400 * (turn + 1)),
164
- contextWindow: profile.contextWindow,
165
- });
166
-
167
- if (failing) {
168
- yield* pause;
169
- yield* emit({
170
- _tag: "RunSettled",
171
- outcome: {
172
- _tag: "Failed",
173
- errorText: `[stub:${profile.backend}] task failed as requested by FAIL: prefix`,
174
- },
175
- });
176
- return;
177
- }
178
-
179
- const finalText =
180
- `[stub:${profile.backend}] completed: ${firstLine(userText).slice(0, 200)}\n\n` +
181
- `This is a stubbed ${profile.backend} subagent turn ${turn + 1}. ` +
182
- `The real backend integration will replace this scripted output.`;
183
- for (const delta of chunked(finalText, 24)) {
184
- yield* emit({ _tag: "AssistantDelta", kind: "text", delta });
185
- yield* pause;
186
- }
187
- yield* emit({
188
- _tag: "AssistantMessage",
189
- parts: [{ type: "text", text: finalText }],
190
- });
191
- yield* emit({
192
- _tag: "UsageChanged",
193
- tokens: Math.min(profile.contextWindow, 2400 * (turn + 1) + 900),
194
- contextWindow: profile.contextWindow,
195
- });
196
- yield* emit({
197
- _tag: "RunSettled",
198
- outcome: { _tag: "Completed", finalText },
199
- });
200
- });
201
-
202
- const queuedView = (): ReadonlyArray<QueuedMessage> =>
203
- state.pending.map((text) => ({ text, kind: "steer" as const }));
204
-
205
- // Driver: one turn at a time, in submission order. Turns run as child
206
- // fibers so interrupt() stops the turn without killing the driver.
207
- const driver = Effect.gen(function* () {
208
- while (true) {
209
- const text = yield* Queue.take(inbox);
210
- state.dispatching = true;
211
- state.pending.shift();
212
- yield* emit({ _tag: "QueueChanged", queued: queuedView() });
213
- yield* emit({ _tag: "UserMessage", text });
214
- const turn = state.turnCount++;
215
- const fiber = yield* Effect.forkChild(
216
- runTurn(text, turn).pipe(
217
- Effect.onInterrupt(() =>
218
- emit({
219
- _tag: "RunSettled",
220
- outcome: { _tag: "Interrupted" },
221
- }).pipe(Effect.ignore),
222
- ),
223
- ),
224
- );
225
- yield* Ref.set(activeTurn, fiber);
226
- state.dispatching = false;
227
- yield* Fiber.await(fiber);
228
- yield* Ref.set(activeTurn, undefined);
229
- }
230
- });
231
- yield* Effect.forkScoped(driver.pipe(Effect.ignore));
232
-
233
- yield* Effect.addFinalizer(() =>
234
- Effect.gen(function* () {
235
- state.closed = true;
236
- yield* Queue.end(inbox).pipe(Effect.ignore);
237
- yield* Queue.end(events).pipe(Effect.ignore);
238
- }),
239
- );
240
-
241
- const submit = (text: string) =>
242
- Effect.gen(function* () {
243
- if (state.closed) {
244
- return yield* new SendError({
245
- message: "Subagent session is closed.",
246
- });
247
- }
248
- state.pending.push(text);
249
- const busy = (yield* Ref.get(activeTurn)) !== undefined;
250
- if (busy) {
251
- // Show the queued steer line until the driver picks it up.
252
- yield* emit({ _tag: "QueueChanged", queued: queuedView() });
253
- }
254
- yield* Queue.offer(inbox, text);
255
- });
256
-
257
- // Announce metadata, then kick off the initial run.
258
- yield* Effect.try(() => fs.mkdirSync(STUB_DIR, { recursive: true })).pipe(
259
- Effect.ignore, // The fake session file directory is best-effort.
260
- );
261
- yield* emit({ _tag: "MetaChanged", meta: state.meta });
262
- // The session cannot be closed yet, so the initial submit cannot fail.
263
- yield* submit(task.prompt).pipe(Effect.orDie);
264
-
265
- return {
266
- meta: Effect.sync(() => state.meta),
267
- events: Stream.fromQueue(events),
268
- send: submit,
269
- interrupt: Effect.gen(function* () {
270
- // Drop queued prompts so interrupting cannot immediately start
271
- // another turn, then stop the active turn. A prompt may be mid-flight
272
- // between the driver dequeuing it and registering its fiber, so wait
273
- // that window out instead of silently missing the turn.
274
- const cleared = yield* Queue.clear(inbox).pipe(
275
- Effect.orElseSucceed(() => []),
276
- );
277
- state.pending = [];
278
- yield* emit({ _tag: "QueueChanged", queued: [] });
279
- while (true) {
280
- const fiber = yield* Ref.get(activeTurn);
281
- if (fiber) {
282
- yield* Fiber.interrupt(fiber);
283
- return;
284
- }
285
- if (!state.dispatching) {
286
- // No turn ever started. If we cancelled queued prompts, the run
287
- // still needs a terminal event or it would look running forever.
288
- if (cleared.length > 0) {
289
- yield* emit({
290
- _tag: "RunSettled",
291
- outcome: { _tag: "Interrupted" },
292
- });
293
- }
294
- return;
295
- }
296
- yield* Effect.sleep(Duration.millis(5));
297
- }
298
- }),
299
- } satisfies SubagentSession;
300
- });
1
+ /**
2
+ * Scripted stub sessions shared by all three backend implementations while
3
+ * the real integrations are pending. A stub session:
4
+ *
5
+ * - streams a plausible turn (thinking deltas, one fake tool cycle, text
6
+ * deltas, usage ramp, a final assistant message, RunSettled) over a few
7
+ * seconds so streaming UI, wait, and the footer counters are observable;
8
+ * - supports send() while running (queued-steer rendering) and while idle
9
+ * (fresh run);
10
+ * - supports interrupt (RunSettled Interrupted -> status "error", matching v1);
11
+ * - fails the run when the prompt starts with "FAIL:" (error-path testing);
12
+ * - appends every event to a JSONL "session file" in tmpdir so the
13
+ * "full transcript in session file" pointers resolve.
14
+ */
15
+
16
+ import * as fs from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import type { Cause, Scope } from "effect";
20
+ import { Duration, Effect, Fiber, Queue, Ref, Stream } from "effect";
21
+ import type { SubagentBackend, SubagentSession } from "../backend.ts";
22
+ import type {
23
+ BackendName,
24
+ QueuedMessage,
25
+ SpawnTask,
26
+ SubagentEvent,
27
+ SubagentMeta,
28
+ } from "../domain.ts";
29
+ import { SendError } from "../domain.ts";
30
+
31
+ export interface StubProfile {
32
+ readonly backend: BackendName;
33
+ readonly defaultModelLabel: string;
34
+ readonly contextWindow: number;
35
+ readonly toolName: string;
36
+ /** Delay between scripted events; varies per backend so streams differ. */
37
+ readonly cadenceMs: number;
38
+ }
39
+
40
+ const STUB_DIR = path.join(os.tmpdir(), "subagents-stub");
41
+ let sessionCounter = 0;
42
+
43
+ export function makeStubBackend(profile: StubProfile): SubagentBackend {
44
+ return {
45
+ name: profile.backend,
46
+ capabilities: {
47
+ steering: true,
48
+ modelSelection: true,
49
+ reasoningEffort: true,
50
+ },
51
+ // Real impls probe binary-on-PATH / SDK import / credentials here.
52
+ available: Effect.succeed(true),
53
+ spawn: (task) => makeStubSession(profile, task),
54
+ };
55
+ }
56
+
57
+ function firstLine(text: string): string {
58
+ return (
59
+ text
60
+ .split("\n")
61
+ .find((line) => line.trim())
62
+ ?.trim() ?? ""
63
+ );
64
+ }
65
+
66
+ function chunked(text: string, size: number): string[] {
67
+ const chunks: string[] = [];
68
+ for (let i = 0; i < text.length; i += size)
69
+ chunks.push(text.slice(i, i + size));
70
+ return chunks;
71
+ }
72
+
73
+ const makeStubSession = (
74
+ profile: StubProfile,
75
+ task: SpawnTask,
76
+ ): Effect.Effect<SubagentSession, never, Scope.Scope> =>
77
+ Effect.gen(function* () {
78
+ const sessionId = `stub-${profile.backend}-${++sessionCounter}`;
79
+ const sessionFile = path.join(STUB_DIR, `${sessionId}.jsonl`);
80
+
81
+ const state = {
82
+ meta: {
83
+ backend: profile.backend,
84
+ modelLabel: task.model ?? profile.defaultModelLabel,
85
+ contextWindow: profile.contextWindow,
86
+ sessionFilePath: sessionFile,
87
+ nativeSessionId: sessionId,
88
+ } satisfies SubagentMeta as SubagentMeta,
89
+ pending: [] as string[],
90
+ turnCount: 0,
91
+ closed: false,
92
+ /** True between the driver dequeuing a prompt and registering its turn fiber. */
93
+ dispatching: false,
94
+ };
95
+
96
+ const events = yield* Queue.make<SubagentEvent, Cause.Done>();
97
+ const inbox = yield* Queue.make<string, Cause.Done>();
98
+ const activeTurn = yield* Ref.make<Fiber.Fiber<void> | undefined>(
99
+ undefined,
100
+ );
101
+
102
+ const emit = (event: SubagentEvent) =>
103
+ Effect.suspend(() => {
104
+ try {
105
+ fs.appendFileSync(sessionFile, `${JSON.stringify(event)}\n`);
106
+ } catch {
107
+ // The fake session file is best-effort.
108
+ }
109
+ if (event._tag === "MetaChanged") {
110
+ state.meta = { ...state.meta, ...event.meta };
111
+ }
112
+ return Queue.offer(events, event);
113
+ }).pipe(Effect.asVoid);
114
+
115
+ const pause = Effect.sleep(Duration.millis(profile.cadenceMs));
116
+
117
+ const runTurn = (userText: string, turn: number) =>
118
+ Effect.gen(function* () {
119
+ yield* emit({ _tag: "RunStarted" });
120
+ const failing = userText.trimStart().startsWith("FAIL:");
121
+
122
+ const thinking = "Looking at the task and planning an approach...";
123
+ for (const delta of chunked(thinking, 16)) {
124
+ yield* emit({ _tag: "AssistantDelta", kind: "thinking", delta });
125
+ yield* pause;
126
+ }
127
+
128
+ const toolId = `${sessionId}-tool-${turn}`;
129
+ const argsPreview = `{"command":"ls ${task.cwd}"}`;
130
+ yield* emit({
131
+ _tag: "AssistantMessage",
132
+ parts: [
133
+ { type: "thinking", text: thinking },
134
+ {
135
+ type: "text",
136
+ text: `I'll run ${profile.toolName} to look around first.`,
137
+ },
138
+ { type: "toolCall", toolId, name: profile.toolName, argsPreview },
139
+ ],
140
+ });
141
+ yield* emit({
142
+ _tag: "ToolStart",
143
+ toolId,
144
+ name: profile.toolName,
145
+ argsPreview,
146
+ });
147
+ yield* pause;
148
+ yield* emit({
149
+ _tag: "ToolUpdate",
150
+ toolId,
151
+ outputPreview: "src docs package.json",
152
+ });
153
+ yield* pause;
154
+ yield* emit({
155
+ _tag: "ToolEnd",
156
+ toolId,
157
+ name: profile.toolName,
158
+ isError: false,
159
+ outputPreview: "src docs package.json",
160
+ });
161
+ yield* emit({
162
+ _tag: "UsageChanged",
163
+ tokens: Math.min(profile.contextWindow, 2400 * (turn + 1)),
164
+ contextWindow: profile.contextWindow,
165
+ });
166
+
167
+ if (failing) {
168
+ yield* pause;
169
+ yield* emit({
170
+ _tag: "RunSettled",
171
+ outcome: {
172
+ _tag: "Failed",
173
+ errorText: `[stub:${profile.backend}] task failed as requested by FAIL: prefix`,
174
+ },
175
+ });
176
+ return;
177
+ }
178
+
179
+ const finalText =
180
+ `[stub:${profile.backend}] completed: ${firstLine(userText).slice(0, 200)}\n\n` +
181
+ `This is a stubbed ${profile.backend} subagent turn ${turn + 1}. ` +
182
+ `The real backend integration will replace this scripted output.`;
183
+ for (const delta of chunked(finalText, 24)) {
184
+ yield* emit({ _tag: "AssistantDelta", kind: "text", delta });
185
+ yield* pause;
186
+ }
187
+ yield* emit({
188
+ _tag: "AssistantMessage",
189
+ parts: [{ type: "text", text: finalText }],
190
+ });
191
+ yield* emit({
192
+ _tag: "UsageChanged",
193
+ tokens: Math.min(profile.contextWindow, 2400 * (turn + 1) + 900),
194
+ contextWindow: profile.contextWindow,
195
+ });
196
+ yield* emit({
197
+ _tag: "RunSettled",
198
+ outcome: { _tag: "Completed", finalText },
199
+ });
200
+ });
201
+
202
+ const queuedView = (): ReadonlyArray<QueuedMessage> =>
203
+ state.pending.map((text) => ({ text, kind: "steer" as const }));
204
+
205
+ // Driver: one turn at a time, in submission order. Turns run as child
206
+ // fibers so interrupt() stops the turn without killing the driver.
207
+ const driver = Effect.gen(function* () {
208
+ while (true) {
209
+ const text = yield* Queue.take(inbox);
210
+ state.dispatching = true;
211
+ state.pending.shift();
212
+ yield* emit({ _tag: "QueueChanged", queued: queuedView() });
213
+ yield* emit({ _tag: "UserMessage", text });
214
+ const turn = state.turnCount++;
215
+ const fiber = yield* Effect.forkChild(
216
+ runTurn(text, turn).pipe(
217
+ Effect.onInterrupt(() =>
218
+ emit({
219
+ _tag: "RunSettled",
220
+ outcome: { _tag: "Interrupted" },
221
+ }).pipe(Effect.ignore),
222
+ ),
223
+ ),
224
+ );
225
+ yield* Ref.set(activeTurn, fiber);
226
+ state.dispatching = false;
227
+ yield* Fiber.await(fiber);
228
+ yield* Ref.set(activeTurn, undefined);
229
+ }
230
+ });
231
+ yield* Effect.forkScoped(driver.pipe(Effect.ignore));
232
+
233
+ yield* Effect.addFinalizer(() =>
234
+ Effect.gen(function* () {
235
+ state.closed = true;
236
+ yield* Queue.end(inbox).pipe(Effect.ignore);
237
+ yield* Queue.end(events).pipe(Effect.ignore);
238
+ }),
239
+ );
240
+
241
+ const submit = (text: string) =>
242
+ Effect.gen(function* () {
243
+ if (state.closed) {
244
+ return yield* new SendError({
245
+ message: "Subagent session is closed.",
246
+ });
247
+ }
248
+ state.pending.push(text);
249
+ const busy = (yield* Ref.get(activeTurn)) !== undefined;
250
+ if (busy) {
251
+ // Show the queued steer line until the driver picks it up.
252
+ yield* emit({ _tag: "QueueChanged", queued: queuedView() });
253
+ }
254
+ yield* Queue.offer(inbox, text);
255
+ });
256
+
257
+ // Announce metadata, then kick off the initial run.
258
+ yield* Effect.try(() => fs.mkdirSync(STUB_DIR, { recursive: true })).pipe(
259
+ Effect.ignore, // The fake session file directory is best-effort.
260
+ );
261
+ yield* emit({ _tag: "MetaChanged", meta: state.meta });
262
+ // The session cannot be closed yet, so the initial submit cannot fail.
263
+ yield* submit(task.prompt).pipe(Effect.orDie);
264
+
265
+ return {
266
+ meta: Effect.sync(() => state.meta),
267
+ events: Stream.fromQueue(events),
268
+ send: submit,
269
+ interrupt: Effect.gen(function* () {
270
+ // Drop queued prompts so interrupting cannot immediately start
271
+ // another turn, then stop the active turn. A prompt may be mid-flight
272
+ // between the driver dequeuing it and registering its fiber, so wait
273
+ // that window out instead of silently missing the turn.
274
+ const cleared = yield* Queue.clear(inbox).pipe(
275
+ Effect.orElseSucceed(() => []),
276
+ );
277
+ state.pending = [];
278
+ yield* emit({ _tag: "QueueChanged", queued: [] });
279
+ while (true) {
280
+ const fiber = yield* Ref.get(activeTurn);
281
+ if (fiber) {
282
+ yield* Fiber.interrupt(fiber);
283
+ return;
284
+ }
285
+ if (!state.dispatching) {
286
+ // No turn ever started. If we cancelled queued prompts, the run
287
+ // still needs a terminal event or it would look running forever.
288
+ if (cleared.length > 0) {
289
+ yield* emit({
290
+ _tag: "RunSettled",
291
+ outcome: { _tag: "Interrupted" },
292
+ });
293
+ }
294
+ return;
295
+ }
296
+ yield* Effect.sleep(Duration.millis(5));
297
+ }
298
+ }),
299
+ } satisfies SubagentSession;
300
+ });
@@ -1,21 +1,21 @@
1
- import type { SubagentOrigin } from "./domain.ts";
2
-
3
- export const BTW_TITLE_MAX_LENGTH = 60;
4
-
5
- /** Build a compact dashboard title from the first non-empty prompt line. */
6
- export function deriveBtwTitle(prompt: string) {
7
- const firstLine = prompt
8
- .split("\n")
9
- .find((line) => line.trim())
10
- ?.trim();
11
- const title = firstLine?.replace(/\s+/g, " ") ?? "";
12
- if (!title) return "by the way";
13
- const codePoints = Array.from(title);
14
- if (codePoints.length <= BTW_TITLE_MAX_LENGTH) return title;
15
- return `${codePoints.slice(0, BTW_TITLE_MAX_LENGTH - 1).join("")}…`;
16
- }
17
-
18
- /** User asides remain visible in the dashboard but hidden from model tools. */
19
- export function isModelVisible(snap: { readonly origin: SubagentOrigin }) {
20
- return snap.origin === "model";
21
- }
1
+ import type { SubagentOrigin } from "./domain.ts";
2
+
3
+ export const BTW_TITLE_MAX_LENGTH = 60;
4
+
5
+ /** Build a compact dashboard title from the first non-empty prompt line. */
6
+ export function deriveBtwTitle(prompt: string) {
7
+ const firstLine = prompt
8
+ .split("\n")
9
+ .find((line) => line.trim())
10
+ ?.trim();
11
+ const title = firstLine?.replace(/\s+/g, " ") ?? "";
12
+ if (!title) return "by the way";
13
+ const codePoints = Array.from(title);
14
+ if (codePoints.length <= BTW_TITLE_MAX_LENGTH) return title;
15
+ return `${codePoints.slice(0, BTW_TITLE_MAX_LENGTH - 1).join("")}…`;
16
+ }
17
+
18
+ /** User asides remain visible in the dashboard but hidden from model tools. */
19
+ export function isModelVisible(snap: { readonly origin: SubagentOrigin }) {
20
+ return snap.origin === "model";
21
+ }