@yaks/harness 0.0.0-stage → 0.2.36

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 (230) hide show
  1. package/FRONTEND.md +170 -0
  2. package/LICENSE +202 -0
  3. package/MCPAuthPanel.js +166 -0
  4. package/MCPAuthPanel.js.map +1 -0
  5. package/MCPAuthPanel.ts +184 -0
  6. package/ModelPanel.js +124 -0
  7. package/ModelPanel.js.map +1 -0
  8. package/ModelPanel.ts +143 -0
  9. package/PersonaPanel.js +106 -0
  10. package/PersonaPanel.js.map +1 -0
  11. package/PersonaPanel.ts +110 -0
  12. package/README.md +1570 -2
  13. package/RuntimePanel.js +180 -0
  14. package/RuntimePanel.js.map +1 -0
  15. package/RuntimePanel.ts +205 -0
  16. package/STREAMING.md +101 -0
  17. package/WINDOWS.md +78 -0
  18. package/WORKER.md +221 -0
  19. package/_dist/agent.d.ts +197 -0
  20. package/_dist/agent.d.ts.map +1 -0
  21. package/_dist/cli.d.ts +10 -0
  22. package/_dist/cli.d.ts.map +1 -0
  23. package/_dist/conversations.d.ts +45 -0
  24. package/_dist/conversations.d.ts.map +1 -0
  25. package/_dist/default.d.ts +32 -0
  26. package/_dist/default.d.ts.map +1 -0
  27. package/_dist/detail.d.ts +16 -0
  28. package/_dist/detail.d.ts.map +1 -0
  29. package/_dist/diagnostics.d.ts +5 -0
  30. package/_dist/diagnostics.d.ts.map +1 -0
  31. package/_dist/effects.d.ts +35 -0
  32. package/_dist/effects.d.ts.map +1 -0
  33. package/_dist/http.d.ts +12 -0
  34. package/_dist/http.d.ts.map +1 -0
  35. package/_dist/isolated.d.ts +6 -0
  36. package/_dist/isolated.d.ts.map +1 -0
  37. package/_dist/local.d.ts +74 -0
  38. package/_dist/local.d.ts.map +1 -0
  39. package/_dist/machine.d.ts +3 -0
  40. package/_dist/machine.d.ts.map +1 -0
  41. package/_dist/mcp_auth.d.ts +8 -0
  42. package/_dist/mcp_auth.d.ts.map +1 -0
  43. package/_dist/mod.d.ts +43 -0
  44. package/_dist/mod.d.ts.map +1 -0
  45. package/_dist/model_selection.d.ts +8 -0
  46. package/_dist/model_selection.d.ts.map +1 -0
  47. package/_dist/routes.d.ts +11 -0
  48. package/_dist/routes.d.ts.map +1 -0
  49. package/_dist/runs.d.ts +7 -0
  50. package/_dist/runs.d.ts.map +1 -0
  51. package/_dist/runtime.d.ts +2 -0
  52. package/_dist/runtime.d.ts.map +1 -0
  53. package/_dist/session_machines.d.ts +18 -0
  54. package/_dist/session_machines.d.ts.map +1 -0
  55. package/_dist/skills.d.ts +11 -0
  56. package/_dist/skills.d.ts.map +1 -0
  57. package/_dist/store.d.ts +38 -0
  58. package/_dist/store.d.ts.map +1 -0
  59. package/_dist/tools.d.ts +28 -0
  60. package/_dist/tools.d.ts.map +1 -0
  61. package/_dist/view.d.ts +5 -0
  62. package/_dist/view.d.ts.map +1 -0
  63. package/_dist/vocab.d.ts +7 -0
  64. package/_dist/vocab.d.ts.map +1 -0
  65. package/_dist/worn.d.ts +52 -0
  66. package/_dist/worn.d.ts.map +1 -0
  67. package/agent.js +773 -0
  68. package/agent.js.map +1 -0
  69. package/agent.ts +959 -0
  70. package/app.js +811 -0
  71. package/app.js.map +1 -0
  72. package/app.ts +868 -0
  73. package/artifact_tools.js +186 -0
  74. package/artifact_tools.js.map +1 -0
  75. package/artifact_tools.ts +190 -0
  76. package/backend_worker.ts +286 -0
  77. package/cli.js +43 -0
  78. package/cli.js.map +1 -0
  79. package/cli.ts +48 -0
  80. package/conversations.js +526 -0
  81. package/conversations.js.map +1 -0
  82. package/conversations.ts +576 -0
  83. package/conversations_testing.ts +162 -0
  84. package/default.js +162 -0
  85. package/default.js.map +1 -0
  86. package/default.ts +168 -0
  87. package/deferred_model.ts +1 -0
  88. package/deno.json +1 -0
  89. package/detail.js +50 -0
  90. package/detail.js.map +1 -0
  91. package/detail.ts +75 -0
  92. package/diagnostics.js +132 -0
  93. package/diagnostics.js.map +1 -0
  94. package/diagnostics.ts +150 -0
  95. package/draft_vault.js +149 -0
  96. package/draft_vault.js.map +1 -0
  97. package/draft_vault.ts +176 -0
  98. package/effects.js +233 -0
  99. package/effects.js.map +1 -0
  100. package/effects.ts +250 -0
  101. package/frontend/vocab.json +376 -0
  102. package/frontend.js +511 -0
  103. package/frontend.js.map +1 -0
  104. package/frontend.ts +389 -0
  105. package/http.js +107 -0
  106. package/http.js.map +1 -0
  107. package/http.ts +105 -0
  108. package/input_text.js +91 -0
  109. package/input_text.js.map +1 -0
  110. package/input_text.ts +99 -0
  111. package/instructions.js +111 -0
  112. package/instructions.js.map +1 -0
  113. package/instructions.ts +145 -0
  114. package/isolated.js +512 -0
  115. package/isolated.js.map +1 -0
  116. package/isolated.ts +502 -0
  117. package/keyboard.js +544 -0
  118. package/keyboard.js.map +1 -0
  119. package/keyboard.ts +403 -0
  120. package/legacy_instructions.js +3 -0
  121. package/legacy_instructions.js.map +1 -0
  122. package/legacy_instructions.ts +13 -0
  123. package/local.js +181 -0
  124. package/local.js.map +1 -0
  125. package/local.ts +282 -0
  126. package/machine.js +3 -0
  127. package/machine.js.map +1 -0
  128. package/machine.ts +8 -0
  129. package/mcp.js +123 -0
  130. package/mcp.js.map +1 -0
  131. package/mcp.ts +141 -0
  132. package/mcp_auth.js +63 -0
  133. package/mcp_auth.js.map +1 -0
  134. package/mcp_auth.ts +91 -0
  135. package/mcp_authorize.js +17 -0
  136. package/mcp_authorize.js.map +1 -0
  137. package/mcp_authorize.ts +18 -0
  138. package/mcp_registry.js +178 -0
  139. package/mcp_registry.js.map +1 -0
  140. package/mcp_registry.ts +193 -0
  141. package/mod.js +43 -0
  142. package/mod.js.map +1 -0
  143. package/mod.ts +45 -0
  144. package/model_selection.js +72 -0
  145. package/model_selection.js.map +1 -0
  146. package/model_selection.ts +86 -0
  147. package/numbers.js +6 -0
  148. package/numbers.js.map +1 -0
  149. package/numbers.ts +8 -0
  150. package/package.json +106 -4
  151. package/panels.js +119 -0
  152. package/panels.js.map +1 -0
  153. package/panels.ts +259 -0
  154. package/patch.js +329 -0
  155. package/patch.js.map +1 -0
  156. package/patch.ts +325 -0
  157. package/perf.ts +65 -0
  158. package/providers.js +36 -0
  159. package/providers.js.map +1 -0
  160. package/providers.ts +53 -0
  161. package/remote.js +441 -0
  162. package/remote.js.map +1 -0
  163. package/remote.ts +446 -0
  164. package/results.js +49 -0
  165. package/results.js.map +1 -0
  166. package/results.ts +39 -0
  167. package/routes.js +64 -0
  168. package/routes.js.map +1 -0
  169. package/routes.ts +87 -0
  170. package/runs.js +478 -0
  171. package/runs.js.map +1 -0
  172. package/runs.ts +479 -0
  173. package/runtime/vocab.json +36 -0
  174. package/runtime.js +105 -0
  175. package/runtime.js.map +1 -0
  176. package/runtime.ts +112 -0
  177. package/session_machines.js +203 -0
  178. package/session_machines.js.map +1 -0
  179. package/session_machines.ts +216 -0
  180. package/sheet.js +55 -0
  181. package/sheet.js.map +1 -0
  182. package/sheet.ts +31 -0
  183. package/shutdown.js +7 -0
  184. package/shutdown.js.map +1 -0
  185. package/shutdown.ts +7 -0
  186. package/skills.js +116 -0
  187. package/skills.js.map +1 -0
  188. package/skills.ts +114 -0
  189. package/startup_bench.ts +140 -0
  190. package/status.js +82 -0
  191. package/status.js.map +1 -0
  192. package/status.ts +97 -0
  193. package/steps.baseline.json +28 -0
  194. package/steps_bench.ts +155 -0
  195. package/store.js +31 -0
  196. package/store.js.map +1 -0
  197. package/store.ts +82 -0
  198. package/streaming.js +3 -0
  199. package/streaming.js.map +1 -0
  200. package/streaming.ts +8 -0
  201. package/streaming_bench.ts +76 -0
  202. package/switch_bench.ts +97 -0
  203. package/testing.ts +177 -0
  204. package/tools.js +287 -0
  205. package/tools.js.map +1 -0
  206. package/tools.ts +313 -0
  207. package/transcript.js +149 -0
  208. package/transcript.js.map +1 -0
  209. package/transcript.ts +187 -0
  210. package/tree.js +97 -0
  211. package/tree.js.map +1 -0
  212. package/tree.ts +114 -0
  213. package/unfinished.js +186 -0
  214. package/unfinished.js.map +1 -0
  215. package/unfinished.ts +198 -0
  216. package/view.js +92 -0
  217. package/view.js.map +1 -0
  218. package/view.ts +102 -0
  219. package/vocab.js +23 -0
  220. package/vocab.js.map +1 -0
  221. package/vocab.json +494 -0
  222. package/vocab.ts +22 -0
  223. package/window_bench.ts +114 -0
  224. package/worker_bench.ts +72 -0
  225. package/workspace.js +21 -0
  226. package/workspace.js.map +1 -0
  227. package/workspace.ts +17 -0
  228. package/worn.js +194 -0
  229. package/worn.js.map +1 -0
  230. package/worn.ts +246 -0
package/agent.ts ADDED
@@ -0,0 +1,959 @@
1
+ import { after } from '@yaks/fp'
2
+ import { type Built, line, sub } from '@yaks/query'
3
+ import { edgeEid } from '@yaks/edge'
4
+ import { inputText, senders } from './input_text.js'
5
+ import { dispatchStatus } from '@yaks/session/admission'
6
+ import { LOADER } from '@yaks/session/deferred'
7
+ // The harness is its agent: the rows every transcript is read from, the runner
8
+ // it lends them (@yaks/session run.ts), and the operations a caller needs —
9
+ // start a session, send it a message, list sessions, read one back. It runs
10
+ // wherever a graph does: on a box over a SQLite file (./local.ts), or on
11
+ // Cloudflare over D1 or a Durable Object's storage. So nothing here names a
12
+ // machine. What runs on one — the shell, a checkout per child, the instruction
13
+ // files on disk, where a defect is written — is lent by the host as an option,
14
+ // and a host that lends none of it still runs a transcript to the end.
15
+ //
16
+ // Everything in and out of here is a bundle or a query. Nothing writes SQL,
17
+ // nothing reads a table, and no state lives in this process that the graph does
18
+ // not already hold: which sessions are running is `.session.status=running`,
19
+ // what was written is `.entry.session=<s>`. The one thing kept in memory is
20
+ // which transcripts this process is running, and that is the runner's.
21
+ //
22
+ // Seeding is idempotent because the ids are derived from the names — the
23
+ // vocabulary declares `name` the identity of a provider, a model and a tool,
24
+ // and a provider's offering of a model is a `serves` edge, whose id is derived
25
+ // from its two ends — so a second startup patches the rows the first one wrote
26
+ // instead of creating a second set. That is what makes `using{model}` on an
27
+ // entry mean the same thing across restarts.
28
+
29
+ import {
30
+ type Bundle,
31
+ type Comp,
32
+ type Eid,
33
+ type Graph,
34
+ unheld,
35
+ } from '@yaks/graph'
36
+ import { identityEid } from '@yaks/graph/identity'
37
+ import type { Effects } from 'jsr:@yaks/effects@0.2.36'
38
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
39
+ import {
40
+ labelOf,
41
+ MODEL,
42
+ type Model,
43
+ ModelError,
44
+ PROVIDER,
45
+ type Request,
46
+ TOOL,
47
+ } from '@yaks/model'
48
+ import { resultTool } from './results.js'
49
+ import { valueTools } from '@yaks/blob'
50
+ import { toolEid } from '@yaks/tools/result'
51
+ import {
52
+ actorOf,
53
+ admit,
54
+ answer,
55
+ answering,
56
+ answers,
57
+ type ChildLimits,
58
+ children,
59
+ CONTENT,
60
+ currentStatus,
61
+ type Deps,
62
+ ENTRY,
63
+ handoffOf,
64
+ humanCaller,
65
+ live,
66
+ passing,
67
+ providerResolver,
68
+ type Runner,
69
+ running,
70
+ sessionViews,
71
+ type Step,
72
+ taskEntry,
73
+ type Tool,
74
+ transcript,
75
+ type TranscriptPage,
76
+ transcriptUsage,
77
+ type TranscriptWindow,
78
+ transcriptWindow,
79
+ usingOf,
80
+ } from '@yaks/session'
81
+ import { outputView, promptEntry, type Snapshot } from '@yaks/context'
82
+ import { lineage } from '@yaks/project'
83
+ import { render } from '@yaks/text'
84
+ import { defaultUsing, movedOn } from './default.js'
85
+ import {
86
+ type ModelSelection,
87
+ modelSelection,
88
+ modelUsing,
89
+ selectedUsing,
90
+ } from './model_selection.js'
91
+ import { type EntrySource, entrySource, type SourceRequest } from './detail.js'
92
+ import { inheritedInstructions } from './legacy_instructions.js'
93
+ import { offeredTo, type Wear, wornBy, wornLayers } from './worn.js'
94
+ import { PART } from '@yaks/persona'
95
+ import { type RuntimeAction, runtimeAction, runtimeRows } from './runtime.js'
96
+ import { recoverSettled } from './unfinished.js'
97
+ import type { Harness } from './store.ts'
98
+
99
+ let comp = (b: Bundle, name: string) => b[name] as Comp | undefined
100
+
101
+ /** The provider, model and tool rows a transcript is served from, as one
102
+ * idempotent batch with identities derived from each name, and the provider's
103
+ * offering of the model is a `serves` edge. */
104
+ export let seed = (
105
+ o: { provider?: string; model?: string; tools?: Tool[] } = {},
106
+ ): Bundle[] => {
107
+ let provider = o.provider ? identityEid(PROVIDER, [o.provider]) : ''
108
+ let model = o.model ? identityEid(MODEL, [o.model]) : ''
109
+ return [
110
+ ...provider
111
+ ? [{ entity: { eid: provider }, [PROVIDER]: { name: o.provider } }]
112
+ : [],
113
+ ...model ? [{ entity: { eid: model }, [MODEL]: { name: o.model } }] : [],
114
+ ...provider && model
115
+ ? [{
116
+ entity: { eid: edgeEid(provider, 'serves', model) },
117
+ edge: { from: provider, to: model },
118
+ serves: { name: o.model },
119
+ }]
120
+ : [],
121
+ // A turn holding deferred tools is offered the loader beside them
122
+ // (@yaks/session `loading`), and its calls are named by this row too.
123
+ ...[
124
+ ...o.tools ?? [],
125
+ ...o.tools?.some((t) => t.deferred) ? [LOADER] : [],
126
+ ].map((t: Pick<Tool, 'name' | 'title' | 'step' | 'description'>) => ({
127
+ entity: { eid: toolEid(t.name) },
128
+ [TOOL]: {
129
+ name: t.name,
130
+ ...t.title ? { title: t.title } : {},
131
+ ...t.step ? { step: t.step } : {},
132
+ description: t.description,
133
+ },
134
+ })),
135
+ ]
136
+ }
137
+
138
+ // Reopening a harness must not rewrite its unchanged provider/tool catalogue.
139
+ // Compare only the properties the seed owns; discovery may enrich these rows.
140
+ let seedMissing = (g: Graph, rows: Bundle[]) =>
141
+ after(
142
+ g.get(rows.map((b) => b.entity.eid), [
143
+ PROVIDER,
144
+ MODEL,
145
+ TOOL,
146
+ 'edge',
147
+ 'serves',
148
+ ]),
149
+ (held) => {
150
+ let changed = unheld(held, rows)
151
+ return changed.length ? g.apply(changed, { trusted: true }) : []
152
+ },
153
+ )
154
+
155
+ /** What an agent runs over: a graph, the effects its commits raise, the
156
+ * vocabulary it reads them with, the process working it, which a run's lease
157
+ * names as its holder, and, where the host can tell, whether another holder is
158
+ * over, so a run it held is taken over now rather than at its expiry. */
159
+ export type Host = {
160
+ g: Graph
161
+ fx: Effects
162
+ vocab: Vocab
163
+ me: Eid
164
+ gone?: (holder: Eid) => boolean | Promise<boolean>
165
+ report?: Harness['report']
166
+ }
167
+
168
+ /** Where a defect happened: what was running, and in which transcript. */
169
+ export type Where = { phase: string; session?: Eid }
170
+
171
+ /** What a new session opens with: where it lives, the instruction files
172
+ * found there, each snapshotted into the transcript ahead of the first
173
+ * message, the persona it wears and the topic it is opened on (@yaks/topic's
174
+ * `session.topic`). */
175
+ export type Opening = {
176
+ home?: Comp
177
+ files?: Snapshot[]
178
+ persona?: Eid
179
+ topic?: Eid
180
+ }
181
+
182
+ /** How an agent is started: the graph it runs over, what serves it, what it
183
+ * may do, and what its host lends it. */
184
+ export type Opts<H extends Host = Host> = ChildLimits & {
185
+ h: H
186
+ /** one model for every provider (a test's, an embedder's) */
187
+ model?: Model
188
+ /** implementations keyed by `provider.name` */
189
+ providers?: Record<string, Model>
190
+ /** the model to ask for by name (otherwise `defaultUsing`'s) */
191
+ name?: string
192
+ /** where the agent is lent no `name`, the `using{provider, model}` (eids)
193
+ * it asks, read again before every ask: by default the graph's own
194
+ * (./default.ts) */
195
+ defaultUsing?: () => Promise<Comp>
196
+ /** When compaction must use the model selected for the session. */
197
+ compactWithCurrent?: Deps['compactWithCurrent']
198
+ /** the provider to ask, by name, and the one `model` serves */
199
+ provider?: string
200
+ /** what the agent may call */
201
+ tools?: Tool[]
202
+ /** tools served from elsewhere, offered afresh to every ask of the
203
+ * transcript named */
204
+ remote?: (session: Eid) => Promise<Tool[]>
205
+ /** tools offered only to a transcript whose `sending.tools` names them
206
+ * (@yaks/session `Deps.named`) */
207
+ named?: () => Tool[]
208
+ streaming?: boolean
209
+ checkpointMs?: number
210
+ /** each piece of a streamed reply, once it is stored (@yaks/session
211
+ * `Deps.typed`) */
212
+ typed?: Runner['typed']
213
+ /** The system prompt every ask carries, or what reads each transcript's:
214
+ * read again for every ask, so what it reads (a name, the apps in reach)
215
+ * is current in a transcript that runs for weeks. */
216
+ instructions?: string | ((session: Eid) => Promise<string>)
217
+ /** Changing this scope refreshes instructions even with a warm prefix cache. */
218
+ instructionScope?: Deps['instructionScope']
219
+ /** Which of a transcript's lines a turn reads, for whom it acts. */
220
+ readable?: Deps['readable']
221
+ /** The persona base shared by this application's transcripts. */
222
+ cachePrefix?: Omit<NonNullable<Request['cachePrefix']>, 'length'> & {
223
+ persona: Eid
224
+ }
225
+ /** What every system prompt this agent composes opens with, ahead of the
226
+ * persona and `instructions`: the same for every transcript and every ask,
227
+ * so it stays in a provider's cached prefix (the box's kinds index, @yaks/vocab
228
+ * `kindsIndex`). */
229
+ opens?: string
230
+ /** Wear each transcript's persona on every ask (`session.persona`, or that
231
+ * of the session that started it): its text (@yaks/persona `voice`) leads
232
+ * the system prompt and `instructions` follows it, both read again for
233
+ * every ask, so an edit to the persona reaches a transcript on its next
234
+ * turn. `bases` is where a persona's base (`persona.base`) is kept when this
235
+ * graph does not keep it, and `topic` says the tree of the topic the
236
+ * transcript is opened on (`session.topic`) after the persona. A transcript
237
+ * that wears nothing keeps the instructions it was given. `tools` offers
238
+ * each ask exactly the registered tools that persona contains, as it
239
+ * contains them then, where no line of the transcript selected its own
240
+ * (`sending.tools`); a persona containing none leaves the runner's set. */
241
+ wear?: Wear
242
+ /** Maximum tool-result UTF-8 bytes before model-facing handle projection. */
243
+ outputLimit?: number
244
+ /** A multi-user host supplies its scoped result storage at the same model boundary. */
245
+ resultText?: Deps['resultText']
246
+ /** the share of its model's context window a transcript fills before it is
247
+ * compacted, for every model (@yaks/session `Deps.compactAt`) */
248
+ compactAt?: number
249
+ compactShare?: Deps['compactShare']
250
+ elideCold?: Deps['elideCold']
251
+ background?: Deps['background']
252
+ /** each step of every transcript, as it lands */
253
+ each?: (step: Step, session?: string) => void | Promise<void>
254
+ opening?: (persona?: Eid, session?: Eid) => Promise<Opening>
255
+ /** context an ask carries without storing its bytes in entries */
256
+ context?: Deps['contextItems']
257
+ /** Dynamic context independent of source-bound image items. */
258
+ inputSource?: (entry: Bundle) => string | undefined
259
+ /** Render host context around the words when the model reads the input. */
260
+ inputBody?: (entry: Bundle, body: string) => string
261
+ requestItems?: Deps['requestItems']
262
+ turnItems?: Deps['turnItems']
263
+ /** defects, apart from refusals (default `console.error`) */
264
+ report?: (error: unknown, where: Where) => void
265
+ /** each refusal a tool call met, apart from defects (@yaks/session
266
+ * `Deps.refused`) */
267
+ refused?: Deps['refused']
268
+ /** what the host reconciles when the agent resumes */
269
+ resuming?: () => Promise<void>
270
+ /** what the host lets go of once every admitted operation has drained */
271
+ release?: () => Promise<void> | void
272
+ /** how long a transcript's lease stands between renewals, so how long a
273
+ * process that died running it holds it up (ms; default @yaks/effects') */
274
+ hold?: number
275
+ /** how long a background call runs before the model may take a turn while
276
+ * it runs (ms; default @yaks/session `PATIENCE`) */
277
+ patience?: number
278
+ }
279
+
280
+ /** A running agent. */
281
+ export type Agent<H extends Host = Host> = {
282
+ h: H
283
+ tools: Tool[]
284
+ /** the model entity every new session is started under */
285
+ model: Eid
286
+ /** what to call a model or tool entity, for the views: every model by its
287
+ * label once `naming` settles */
288
+ names: Record<string, string>
289
+ naming: Promise<void>
290
+ /** start a transcript with one instruction; the runner takes it from there.
291
+ * `by` is who wrote the instruction, where the caller knows. */
292
+ start: (
293
+ prompt: string,
294
+ o?: { effort?: string; model?: Eid; persona?: Eid; by?: Eid },
295
+ ) => Promise<Eid>
296
+ /** personas this graph offers for a new session */
297
+ personas: () => Promise<Bundle[]>
298
+ /** the configured models, and what this session asks for next */
299
+ models: (session?: Eid) => Promise<ModelSelection>
300
+ /** record a passive model choice; the next request honours it */
301
+ selectModel: (session: Eid, model: Eid) => Promise<void>
302
+ /** say something more to a transcript that is already going, as `by` where
303
+ * the caller knows who wrote it */
304
+ send: (session: Eid, text: string, by?: Eid) => Promise<Eid>
305
+ /** mint and delegate unfiled work under an existing session */
306
+ taskEntry: (session: Eid, text: string) => Promise<{ task: Eid; child: Eid }>
307
+ archive: (session: Eid, archived: boolean) => Promise<void>
308
+ /** selected session or a bounded, cursor-paged list */
309
+ sessions: (selected?: Eid, page?: ListPage) => Promise<Bundle[]>
310
+ /** A bounded page of open/wip tasks, requested explicitly. */
311
+ tasks: (page?: ListPage) => Promise<Bundle[]>
312
+ /** direct delegated sessions, including forks */
313
+ children: (session: Eid) => Promise<Bundle[]>
314
+ /** one transcript's entries, in order */
315
+ transcript: (session: Eid) => Promise<Bundle[]>
316
+ transcriptWindow: (
317
+ session: Eid,
318
+ request?: TranscriptWindow,
319
+ ) => Promise<TranscriptPage>
320
+ entrySource: (
321
+ session: Eid,
322
+ eid: Eid,
323
+ request?: SourceRequest,
324
+ ) => Promise<EntrySource>
325
+ usage: (session: Eid) => Promise<Bundle[]>
326
+ /** run every transcript left owed a turn that nothing wrote a run for, and
327
+ * answer which they were */
328
+ resume: () => Promise<Eid[]>
329
+ /** wait for a transcript to run out of things to do */
330
+ idle: (session: Eid) => Promise<void>
331
+ /** one bundle as a line of text, through @yaks/render's session views */
332
+ line: (b: Bundle, view?: string, ctx?: Record<string, unknown>) => string
333
+ /** Explicit instruction admission; appends a snapshot, never a user turn. */
334
+ instruct: (session: Eid, text: string, source?: string) => Promise<Eid>
335
+ runtime: (session: Eid) => Promise<Bundle[]>
336
+ control: (session: Eid, action: RuntimeAction) => Promise<string>
337
+ /** an operation the host adds, admitted like these: refused once the agent
338
+ * is closing, and drained before the host lets go of anything */
339
+ admitted: <A extends unknown[], T>(
340
+ work: (...args: A) => Promise<T>,
341
+ ) => (...args: A) => Promise<T>
342
+ /** stop admitting, drain, and release; `reason` is what later calls get */
343
+ close: (reason?: Error) => Promise<void>
344
+ }
345
+
346
+ /** A page of sidebar rows. A selected session only queries its direct children. */
347
+ export type ListPage = { after?: string | number; limit?: number }
348
+ export let LISTED = 20
349
+ let page = (query: Built, options: ListPage = {}) =>
350
+ line`${sub(query)}&.order=-created.at&.limit=${
351
+ Math.min(LISTED, Math.max(1, options.limit ?? LISTED))
352
+ }${sub(options.after == null ? line`` : line`&.after=${options.after}`)}&*`
353
+
354
+ // What attributes a write made here: the transcript it is about, and who
355
+ // wrote it where the caller said. The terminal says who is at its keyboard,
356
+ // the config's `person` (./backend_worker.ts); where nobody says, the
357
+ // instrument is recorded and the actor is left unset rather than guessed; a
358
+ // model turn attributes itself (@yaks/session react.ts).
359
+ export let through = (session: Eid, by?: Eid) => ({
360
+ ...by ? { by } : {},
361
+ via: session,
362
+ })
363
+
364
+ /** A new transcript, as one write: the session and its instruction files,
365
+ * followed by a message that asks for a turn when one was given. An empty
366
+ * session holds its model choice until that first message arrives. The
367
+ * session and the message are whoever began it; the instruction files are the
368
+ * harness's own, put in front of the model, and never that person's words. */
369
+ export let begin = async (
370
+ g: Graph,
371
+ prompt: string | undefined,
372
+ o: Opening & {
373
+ using: Comp
374
+ eid?: Eid
375
+ by?: Eid
376
+ via?: Eid
377
+ project?: Eid
378
+ work?: Eid
379
+ title?: string
380
+ },
381
+ ): Promise<Eid> => {
382
+ let operator = await humanCaller(g, { by: o.by, via: o.via })
383
+ // A session wearing no persona works as the session that started it does
384
+ // (@yaks/session `actorOf`), so what it writes still names an actor.
385
+ let actor = !o.persona && o.via ? await actorOf(g, o.via) : undefined
386
+ let project = o.project ??
387
+ (o.work
388
+ ? (await lineage(g, o.work)).find((b) => b.project)?.entity.eid
389
+ : undefined)
390
+ let session = o.eid ?? crypto.randomUUID() as Eid
391
+ let files = (o.files ?? []).map((f, i) => ({
392
+ ...promptEntry(session, i + 1, f.body, f.source, 'shared', f.revision),
393
+ $actor: through(session),
394
+ }))
395
+ let context = [
396
+ ...files,
397
+ ...prompt
398
+ ? [{
399
+ entity: { eid: crypto.randomUUID() as Eid },
400
+ [ENTRY]: { session, seq: files.length + 1 },
401
+ [CONTENT]: { body: prompt },
402
+ using: o.using,
403
+ $actor: through(session, o.by),
404
+ }]
405
+ : [],
406
+ ]
407
+ await g.apply([
408
+ {
409
+ entity: { eid: session },
410
+ session: {
411
+ id: session.slice(0, 8),
412
+ operator,
413
+ ...o.persona ? { persona: o.persona } : {},
414
+ ...actor ? { actor } : {},
415
+ ...o.topic ? { topic: o.topic } : {},
416
+ },
417
+ native: {},
418
+ ...o.home ? { home: o.home } : {},
419
+ ...project ? { filed: { project } } : {},
420
+ ...o.title ? { doc: { title: o.title } } : {},
421
+ ...prompt ? {} : { using: o.using },
422
+ $actor: through(session, o.by),
423
+ },
424
+ ...context,
425
+ ])
426
+ return session
427
+ }
428
+
429
+ // The defects an agent reports, where its options name nowhere else.
430
+ let reporter = (opts: { report?: (error: unknown, where: Where) => void }) =>
431
+ opts.report ??
432
+ ((error: unknown, where: Where) => console.error(where.phase, error))
433
+
434
+ // What serves each provider, by `provider.name`.
435
+ let served = (opts: Pick<Opts, 'model' | 'providers' | 'provider'>) => ({
436
+ ...opts.model && opts.provider ? { [opts.provider]: opts.model } : {},
437
+ ...opts.providers,
438
+ })
439
+
440
+ // The runner's model where nothing resolves one: a host lent no model asks
441
+ // through `resolveModel` alone.
442
+ let unserved: Model = () =>
443
+ Promise.reject(new ModelError('provider', 'Choose a model'))
444
+
445
+ /**
446
+ * The runner an agent's options lend (@yaks/session `Runner`), over the
447
+ * provider, model and tool rows its first step seeds: what serves each
448
+ * provider, what a transcript may call, and how a step is taken. A host registers it with
449
+ * @yaks/session `running` wherever its effects are worked.
450
+ *
451
+ * ```ts
452
+ * import { lend } from '@yaks/harness'
453
+ * import { running } from '@yaks/session'
454
+ *
455
+ * // h.fx.handle(running(h.g, lend({ h, model })))
456
+ * ```
457
+ */
458
+ export let lend = <H extends Host>(opts: Opts<H>): Runner => {
459
+ let h = opts.h
460
+ let report = reporter(opts)
461
+ const provider = opts.provider
462
+ let name = opts.name ?? ''
463
+ const implementations = served(opts)
464
+ let available = opts.model ? undefined : new Set(
465
+ Object.keys(implementations).map((name) => identityEid(PROVIDER, [name])),
466
+ )
467
+ let model = opts.model ?? implementations[provider ?? ''] ?? unserved
468
+ let tools = opts.resultText ? opts.tools ?? [] : [
469
+ ...opts.tools ?? [],
470
+ ...[resultTool(h.g), ...valueTools(async (id) => (await h.g.get([id]))[0])]
471
+ .filter((t) => !opts.tools?.some((own) => own.name == t.name)),
472
+ ]
473
+ let remote = opts.remote ?? (() => Promise.resolve([]))
474
+ let remoteSignature = ''
475
+ // The remote tools each session's newest ask was offered. A tool is its
476
+ // name, and a server reconfigured mid-ask serves that name from somewhere
477
+ // else: the calls an ask issued run on the handlers it was offered.
478
+ const offered = new Map<Eid, Tool[]>()
479
+ const offerSessions = new Map<Eid, Eid>()
480
+ // Seeded by the first step, not when lent: a host lends the runner while it
481
+ // is being put together, before anything may be written in its name.
482
+ let seeded: unknown
483
+ let {
484
+ taskDefaults,
485
+ maxChildren,
486
+ maxSessions,
487
+ childProperties,
488
+ prepareChild,
489
+ } = opts
490
+ let resolveModel = providerResolver(
491
+ h.g,
492
+ implementations,
493
+ opts.model,
494
+ undefined,
495
+ (error) => report(error, { phase: 'model-metadata' }),
496
+ )
497
+ // Every system prompt composed here opens with `opens`. What a transcript
498
+ // inherited is sent as it was: it opened with it already.
499
+ let opened = (text?: string) =>
500
+ [opts.opens, text].filter(Boolean).join(PART) || undefined
501
+ let kept = (inherited?: string, configured?: string) =>
502
+ inheritedInstructions(inherited, undefined) ?? opened(configured)
503
+ // Compaction is a text task, even when a transcript selects a media model:
504
+ // it asks the model this agent was lent by name, else the one
505
+ // `defaultUsing` reads (./default.ts by default), read again before every
506
+ // ask.
507
+ let compact: NonNullable<Deps['compactModel']> = {
508
+ model,
509
+ name,
510
+ ...provider ? { provider: identityEid(PROVIDER, [provider]) } : {},
511
+ }
512
+ return {
513
+ holder: h.me,
514
+ asyncTools: true,
515
+ ...opts.patience == null ? {} : { patience: opts.patience },
516
+ gone: h.gone,
517
+ taskDefaults,
518
+ maxChildren,
519
+ maxSessions,
520
+ childProperties,
521
+ prepareChild,
522
+ model,
523
+ resolveModel,
524
+ onward: (using, _error, passed) =>
525
+ movedOn(h.g, using, { available, passed }),
526
+ compactModel: compact,
527
+ compactWithCurrent: opts.compactWithCurrent,
528
+ elideCold: opts.elideCold,
529
+ background: opts.background,
530
+ answers: answers(h.g, implementations, opts.model),
531
+ tools,
532
+ named: opts.named,
533
+ toolSnapshot: async (phase, session, boundary, open) => {
534
+ if (!name) {
535
+ let using = await (opts.defaultUsing?.() ?? defaultUsing(h.g))
536
+ let [row] = await h.g.get([String(using.model)])
537
+ Object.assign(
538
+ compact,
539
+ { provider: undefined },
540
+ await resolveModel(using, row),
541
+ )
542
+ }
543
+ await (seeded ??= seedMissing(
544
+ h.g,
545
+ seed({ provider, model: name, tools }),
546
+ ))
547
+ const key = boundary ?? session
548
+ const held = phase === 'call' && offered.get(key)
549
+ if (held) return [...tools, ...held]
550
+ const served = await remote(session)
551
+ const all = [...tools, ...served]
552
+ const twice = [
553
+ ...new Set(
554
+ all.map((t) => t.name).filter((n, i, names) => names.indexOf(n) != i),
555
+ ),
556
+ ]
557
+ if (twice.length) {
558
+ throw new Error(`Two tools share a name: ${twice.join(', ')}`)
559
+ }
560
+ // Several asks may overlap older calls. Keep each original offer until
561
+ // all of its calls have final results; a later catalogue refresh must
562
+ // not redirect an in-progress call to a newly configured MCP server.
563
+ if (phase === 'ask' && offered.size) {
564
+ const asks = await h.g.get(
565
+ open.flatMap((b) => {
566
+ const source = (b.call as Comp)?.source
567
+ return source == null ? [] : [String(source)]
568
+ }),
569
+ ['ask'],
570
+ )
571
+ const outstanding = new Set(
572
+ asks.flatMap((ask) => {
573
+ const through = (ask.ask as Comp | undefined)?.through
574
+ return through == null ? [] : [String(through)]
575
+ }),
576
+ )
577
+ for (const old of offered.keys()) {
578
+ if (
579
+ old != key && offerSessions.get(old) == session &&
580
+ !outstanding.has(old)
581
+ ) {
582
+ offered.delete(old)
583
+ offerSessions.delete(old)
584
+ }
585
+ }
586
+ }
587
+ offered.set(key, served)
588
+ offerSessions.set(key, session)
589
+ const signature = JSON.stringify(
590
+ served.map((t) => [t.name, t.description, t.parameters]),
591
+ )
592
+ if (signature !== remoteSignature) {
593
+ await seedMissing(h.g, seed({ provider, model: name, tools: served }))
594
+ remoteSignature = signature
595
+ }
596
+ return all
597
+ },
598
+ streaming: opts.streaming,
599
+ checkpointMs: opts.checkpointMs,
600
+ typed: opts.typed,
601
+ compactAt: opts.compactAt,
602
+ compactShare: opts.compactShare,
603
+ instructions: typeof opts.instructions == 'string'
604
+ ? opened(opts.instructions)
605
+ : undefined,
606
+ instructionScope: opts.instructionScope,
607
+ readable: opts.readable,
608
+ requestInstructions: opts.cachePrefix && (async (session) => {
609
+ let { persona, ...cache } = opts.cachePrefix!
610
+ let [layers, added] = await Promise.all([
611
+ wornLayers(h.g, session, opts.wear ?? {}, persona),
612
+ typeof opts.instructions == 'function'
613
+ ? opts.instructions(session)
614
+ : opts.instructions,
615
+ ])
616
+ let lead = [opts.opens, layers.shared].filter(Boolean).join(PART)
617
+ return {
618
+ instructions: [lead, layers.local, added].filter(Boolean).join(PART),
619
+ ...layers.shared
620
+ ? { cachePrefix: { ...cache, length: lead.length } }
621
+ : {},
622
+ }
623
+ }),
624
+ resolveInstructions: async (inherited, session) => {
625
+ if (!opts.wear) {
626
+ return typeof opts.instructions == 'function'
627
+ ? opened(await opts.instructions(session))
628
+ : kept(inherited, opts.instructions)
629
+ }
630
+ // What was sent before already says the persona, so only what the host
631
+ // adds follows the persona's text as it reads now, a part of its own.
632
+ // The two are read at once.
633
+ let reads = typeof opts.instructions == 'function'
634
+ ? opts.instructions
635
+ : undefined
636
+ let [worn, added] = await Promise.all([
637
+ wornBy(h.g, session, opts.wear),
638
+ reads ? reads(session) : opts.instructions as string | undefined,
639
+ ])
640
+ // A transcript wearing nothing is told what it was told before: the
641
+ // instructions its first line chose (a builder's contract) stand.
642
+ if (!worn && !reads) return kept(inherited, added)
643
+ return opened([worn, added].filter(Boolean).join(PART))
644
+ },
645
+ ...opts.wear?.tools
646
+ ? { resolveTools: (session) => offeredTo(h.g, session, opts.wear) }
647
+ : {},
648
+ inputText: async (transcript) =>
649
+ inputText(
650
+ transcript,
651
+ await senders(h.g, transcript),
652
+ opts.inputSource,
653
+ opts.inputBody,
654
+ ),
655
+ contextItems: opts.context,
656
+ requestItems: opts.requestItems,
657
+ turnItems: opts.turnItems,
658
+ resultText: opts.resultText ??
659
+ ((entry) => outputView(h.g, entry, opts.outputLimit)),
660
+ report: (error, session, phase) => report(error, { session, phase }),
661
+ ...opts.refused ? { refused: opts.refused } : {},
662
+ each: opts.each,
663
+ recoverSettled: recoverSettled(h.g, h.report),
664
+ hold: opts.hold,
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Lend a graph the runner and work its pool, seeded with what serves it.
670
+ *
671
+ * ```ts ignore
672
+ * import { agent } from '@yaks/harness'
673
+ *
674
+ * let a = agent({ h: { g, fx, vocab, me }, model: fake })
675
+ * let s = await a.start('reply with the word pong')
676
+ * await a.idle(s)
677
+ * ```
678
+ */
679
+ export let agent = <H extends Host>(opts: Opts<H>): Agent<H> => {
680
+ let h = opts.h
681
+ let report = reporter(opts)
682
+ const provider = opts.provider
683
+ let name = opts.name ?? ''
684
+ const implementations = served(opts)
685
+ let tools = opts.tools ?? []
686
+ // The runner, taking every run this graph's commits owe it, until the agent
687
+ // closes: then no step starts, a waiting tool stops waiting, and the step in
688
+ // flight is let finish.
689
+ let stopping = new AbortController()
690
+ let r: Runner = { ...lend(opts), stopping: stopping.signal }
691
+ seedMissing(h.g, seed({ provider, model: name, tools }))
692
+ h.fx.handle(running(h.g, r))
693
+ let working = h.fx.work(h.g, stopping.signal).catch((error) =>
694
+ report(error, { phase: 'effects' })
695
+ )
696
+
697
+ // What this agent was lent by name; the default stands in for no model.
698
+ let using: { provider?: Eid; model?: Eid } = {
699
+ ...provider ? { provider: identityEid(PROVIDER, [provider]) } : {},
700
+ ...name ? { model: identityEid(MODEL, [name]) } : {},
701
+ }
702
+ let names: Record<string, string> = {
703
+ ...using.model ? { [using.model]: name } : {},
704
+ ...Object.fromEntries(tools.map((t) => [toolEid(t.name), t.name])),
705
+ }
706
+ // Every model this graph holds, by its label (@yaks/model `labelOf`): an
707
+ // ask may reach any of them, not only the one lent. A test's stand-in
708
+ // models have none, so one without is not reported here.
709
+ let naming = Promise.resolve(h.g.read('.model&.fields=model')).then(
710
+ (rows) => {
711
+ for (let b of rows) {
712
+ let model = b[MODEL] as Comp | undefined
713
+ if (model?.name) {
714
+ names[b.entity.eid] = labelOf(model)
715
+ }
716
+ }
717
+ },
718
+ (error) => report(error, { phase: 'model-label' }),
719
+ )
720
+ // Lifecycle bookkeeping only; all application state remains in the graph.
721
+ let refusal: Error | undefined
722
+ let shutdown: Promise<void> | undefined
723
+ let operations = new Set<Promise<unknown>>()
724
+ let admitted =
725
+ <A extends unknown[], T>(work: (...args: A) => Promise<T>) =>
726
+ (...args: A): Promise<T> => {
727
+ if (refusal) return Promise.reject(refusal)
728
+ let pending = work(...args)
729
+ operations.add(pending)
730
+ let done = () => operations.delete(pending)
731
+ pending.then(done, done)
732
+ return pending
733
+ }
734
+
735
+ // The request in force on a transcript: what a line said to it asks a turn
736
+ // with, since a turn is asked for by a `using` on an entry.
737
+ let asking = async (session: Eid) => {
738
+ let using = await usingOf(h.g, session) ??
739
+ await selectedUsing(h.g, session)
740
+ return using ? { using } : {}
741
+ }
742
+ // Whether a transcript has nothing more to do that this agent is doing or
743
+ // owes: no pass of its own over it, nothing waiting for a place, and no turn
744
+ // it answers outstanding.
745
+ let quiet = async (session: Eid) => {
746
+ if (passing(h.g, session)) return false
747
+ let [self] = await h.g.get([session], [
748
+ 'dispatch',
749
+ 'waiting',
750
+ 'admitted',
751
+ ])
752
+ if (dispatchStatus(self) == 'queued') return false
753
+ let status = await currentStatus(h.g, session)
754
+ if (status != 'pending' && status != 'running') return true
755
+ return !await answering(h.g, session, r)
756
+ }
757
+
758
+ let a: Agent<H> = {
759
+ h,
760
+ tools,
761
+ names,
762
+ naming,
763
+ get model() {
764
+ return String(using.model ?? '')
765
+ },
766
+ admitted,
767
+ personas: async () =>
768
+ (await h.g.read('.persona')).sort((a, b) =>
769
+ String((a.doc as Comp | undefined)?.title ?? '').localeCompare(
770
+ String((b.doc as Comp | undefined)?.title ?? ''),
771
+ )
772
+ ),
773
+ models: async (session) =>
774
+ modelSelection(
775
+ h.g,
776
+ session,
777
+ using.model ? using : await defaultUsing(h.g),
778
+ ),
779
+ selectModel: async (session, model) => {
780
+ const [owner] = await h.g.get([session])
781
+ if (!owner?.session) throw new Error('Unknown session')
782
+ const chosen = await modelUsing(h.g, model, implementations)
783
+ const prior = await selectedUsing(h.g, session)
784
+ // A conversation another harness ran until now is taken over here, and
785
+ // the model is told so (@yaks/session `handoffOf`).
786
+ const note = await handoffOf(h.g, session)
787
+ await h.g.apply([{
788
+ entity: { eid: crypto.randomUUID() },
789
+ entry: { session },
790
+ notice: {},
791
+ ...note ? { [CONTENT]: { body: note } } : {},
792
+ using: { ...using, ...prior, ...chosen },
793
+ $actor: through(session),
794
+ }])
795
+ },
796
+ start: admitted((
797
+ prompt: string,
798
+ o: { effort?: string; model?: Eid; persona?: Eid; by?: Eid } = {},
799
+ ) =>
800
+ admit(h.g, undefined, opts, async () => {
801
+ const chosen = o.model
802
+ ? await modelUsing(h.g, o.model, implementations)
803
+ : using.model
804
+ ? {}
805
+ : await defaultUsing(h.g)
806
+ let eid = crypto.randomUUID()
807
+ return begin(h.g, prompt, {
808
+ eid,
809
+ ...await opts.opening?.(o.persona, eid),
810
+ ...o.persona ? { persona: o.persona } : {},
811
+ by: o.by,
812
+ using: {
813
+ ...using,
814
+ ...chosen,
815
+ ...o.effort ? { effort: o.effort } : {},
816
+ },
817
+ })
818
+ })
819
+ ),
820
+ send: admitted(async (session: Eid, text: string, by?: Eid) => {
821
+ // Admission is independent of the provider/tool execution queue. The
822
+ // session plugin assigns seq inside this write's transaction.
823
+ let eid = crypto.randomUUID() as Eid
824
+ await h.g.apply([{
825
+ entity: { eid },
826
+ [ENTRY]: { session },
827
+ [CONTENT]: { body: text },
828
+ ...await asking(session),
829
+ $actor: through(session, by),
830
+ }])
831
+ return eid
832
+ }),
833
+ taskEntry: admitted((session: Eid, text: string) =>
834
+ taskEntry(h.g, session, text, opts)
835
+ ),
836
+ archive: admitted(async (session: Eid, archived: boolean) => {
837
+ let rows = await h.g.read('.session')
838
+ if (!rows.some((b) => b.entity.eid == session)) {
839
+ throw new Error('Unknown session')
840
+ }
841
+ // The mark is written bare: when it happened, and through what, are the
842
+ // graph's to stamp (@yaks/graph stamp.ts), never this clock's.
843
+ await h.g.apply([{
844
+ entity: { eid: session },
845
+ archived: archived ? {} : null,
846
+ $actor: through(session),
847
+ }])
848
+ }),
849
+ sessions: admitted(async (selected?: Eid, options?: ListPage) => {
850
+ let rows = options || !selected
851
+ ? await h.g.read(page(line`.session`, options))
852
+ : [
853
+ ...(await h.g.get([selected])).filter((b) => b.session),
854
+ // The closed browser is a selected-session tree, not an archive page.
855
+ // Include direct children even before they start (spawned.call may be
856
+ // null), without scanning or titling every historical session.
857
+ ...await h.g.read(line`.session&.spawned.parent=${selected}&*`),
858
+ ]
859
+ // A selected session need not belong to the current page.
860
+ if (selected && !rows.some((b) => b.entity.eid == selected)) {
861
+ rows = [
862
+ ...(await h.g.get([selected])).filter((b) => b.session),
863
+ ...rows,
864
+ ]
865
+ }
866
+ return await Promise.all(rows.map(async (b) => ({
867
+ ...b,
868
+ session: { ...b.session as Comp, title: await sessionTitle(h.g, b) },
869
+ })))
870
+ }),
871
+ runtime: (session) => runtimeRows(h.g, session),
872
+ control: (session, action) => runtimeAction(a, session, action),
873
+ children: admitted((session: Eid) => children(h.g, session)),
874
+ tasks: admitted(async (options?: ListPage) =>
875
+ await h.g.read(page(line`.task.status=open,wip`, options))
876
+ ),
877
+ entrySource: (session, eid, request) =>
878
+ entrySource(h.g, session, eid, request),
879
+ transcript: admitted((session: Eid) => transcript(h.g, session)),
880
+ usage: (session) => transcriptUsage(h.g, session),
881
+ transcriptWindow: (session, request) =>
882
+ transcriptWindow(h.g, session, request),
883
+ resume: admitted(async () => {
884
+ // A child stays active until its receipt lands. Waking that dispatch
885
+ // retries an interrupted delivery without revisiting finished children.
886
+ let woken = [
887
+ ...new Set((await h.g.read(
888
+ line`${sub(live)}|.session&.dispatch.status=active,queued,waiting`,
889
+ )).map((b) => b.entity.eid)),
890
+ ]
891
+ await opts.resuming?.()
892
+ for (let s of woken) {
893
+ answer(h.g, s, r).catch((error) =>
894
+ report(error, { phase: 'resume', session: s })
895
+ )
896
+ }
897
+ return woken
898
+ }),
899
+ idle: admitted(async (session: Eid) => {
900
+ while (!stopping.signal.aborted && !await quiet(session)) {
901
+ await (passing(h.g, session)?.catch(() => {}) ??
902
+ new Promise((go) => setTimeout(go, 10)))
903
+ }
904
+ }),
905
+ line: (b, view = 'Line', ctx = {}) =>
906
+ render(sessionViews, b, view, h.vocab, {
907
+ names,
908
+ anchor: r.model.anchor,
909
+ ...ctx,
910
+ }, 'plain'),
911
+ instruct: admitted(
912
+ async (session: Eid, text: string, source = 'explicit') => {
913
+ let entry = promptEntry(session, undefined, text, source, 'local')
914
+ await h.g.apply([{ ...entry, ...await asking(session) }])
915
+ return entry.entity.eid
916
+ },
917
+ ),
918
+ // Admission stops, the runner takes no new step and leaves the pool, and
919
+ // what was admitted and the step in flight drain before the host lets go.
920
+ close: (reason) =>
921
+ shutdown ??= (async () => {
922
+ refusal ??= reason ?? new Error('Agent is closing')
923
+ stopping.abort()
924
+ await Promise.allSettled([...operations])
925
+ await h.fx.stop()
926
+ await working
927
+ await opts.release?.()
928
+ })(),
929
+ }
930
+ return a
931
+ }
932
+
933
+ /** Child assignment is explicit admission data; copied fork context is not its title. */
934
+ export let sessionTitle = async (
935
+ g: Graph,
936
+ session: Bundle,
937
+ ): Promise<string> => {
938
+ if (session.spawned) {
939
+ const [assignment] = await g.get([session.entity.eid + ':input'])
940
+ if (assignment?.content) return titleOf([assignment])
941
+ }
942
+ return titleOf(
943
+ await g.read(
944
+ line`.entry.session=${session.entity.eid}&.content&!prompt&!notice&.order=entry.seq&.limit=1`,
945
+ ),
946
+ )
947
+ }
948
+
949
+ /** What a transcript is called in a listing: the first message sent to it. */
950
+ export let titleOf = (entries: Bundle[]): string =>
951
+ String(
952
+ comp(
953
+ entries.find((b) => CONTENT in b && !b.prompt && !b.notice) ??
954
+ {} as Bundle,
955
+ CONTENT,
956
+ )
957
+ ?.body ?? '',
958
+ )
959
+ .split('\n')[0].slice(0, 60)