@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.js ADDED
@@ -0,0 +1,773 @@
1
+ import { after } from "@yaks/fp";
2
+ import { 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
+ import { unheld } from "@yaks/graph";
29
+ import { identityEid } from "@yaks/graph/identity";
30
+ import { labelOf, MODEL, ModelError, PROVIDER, TOOL } from "@yaks/model";
31
+ import { resultTool } from "./results.js";
32
+ import { valueTools } from "@yaks/blob";
33
+ import { toolEid } from "@yaks/tools/result";
34
+ import { actorOf, admit, answer, answering, answers, children, CONTENT, currentStatus, ENTRY, handoffOf, humanCaller, live, passing, providerResolver, running, sessionViews, taskEntry, transcript, transcriptUsage, transcriptWindow, usingOf } from "@yaks/session";
35
+ import { outputView, promptEntry } from "@yaks/context";
36
+ import { lineage } from "@yaks/project";
37
+ import { render } from "@yaks/text";
38
+ import { defaultUsing, movedOn } from "./default.js";
39
+ import { modelSelection, modelUsing, selectedUsing } from "./model_selection.js";
40
+ import { entrySource } from "./detail.js";
41
+ import { inheritedInstructions } from "./legacy_instructions.js";
42
+ import { offeredTo, wornBy, wornLayers } from "./worn.js";
43
+ import { PART } from "@yaks/persona";
44
+ import { runtimeAction, runtimeRows } from "./runtime.js";
45
+ import { recoverSettled } from "./unfinished.js";
46
+ let comp = (b, name)=>b[name];
47
+ /** The provider, model and tool rows a transcript is served from, as one
48
+ * idempotent batch with identities derived from each name, and the provider's
49
+ * offering of the model is a `serves` edge. */ export let seed = (o = {})=>{
50
+ let provider = o.provider ? identityEid(PROVIDER, [
51
+ o.provider
52
+ ]) : '';
53
+ let model = o.model ? identityEid(MODEL, [
54
+ o.model
55
+ ]) : '';
56
+ return [
57
+ ...provider ? [
58
+ {
59
+ entity: {
60
+ eid: provider
61
+ },
62
+ [PROVIDER]: {
63
+ name: o.provider
64
+ }
65
+ }
66
+ ] : [],
67
+ ...model ? [
68
+ {
69
+ entity: {
70
+ eid: model
71
+ },
72
+ [MODEL]: {
73
+ name: o.model
74
+ }
75
+ }
76
+ ] : [],
77
+ ...provider && model ? [
78
+ {
79
+ entity: {
80
+ eid: edgeEid(provider, 'serves', model)
81
+ },
82
+ edge: {
83
+ from: provider,
84
+ to: model
85
+ },
86
+ serves: {
87
+ name: o.model
88
+ }
89
+ }
90
+ ] : [],
91
+ // A turn holding deferred tools is offered the loader beside them
92
+ // (@yaks/session `loading`), and its calls are named by this row too.
93
+ ...[
94
+ ...o.tools ?? [],
95
+ ...o.tools?.some((t)=>t.deferred) ? [
96
+ LOADER
97
+ ] : []
98
+ ].map((t)=>({
99
+ entity: {
100
+ eid: toolEid(t.name)
101
+ },
102
+ [TOOL]: {
103
+ name: t.name,
104
+ ...t.title ? {
105
+ title: t.title
106
+ } : {},
107
+ ...t.step ? {
108
+ step: t.step
109
+ } : {},
110
+ description: t.description
111
+ }
112
+ }))
113
+ ];
114
+ };
115
+ // Reopening a harness must not rewrite its unchanged provider/tool catalogue.
116
+ // Compare only the properties the seed owns; discovery may enrich these rows.
117
+ let seedMissing = (g, rows)=>after(g.get(rows.map((b)=>b.entity.eid), [
118
+ PROVIDER,
119
+ MODEL,
120
+ TOOL,
121
+ 'edge',
122
+ 'serves'
123
+ ]), (held)=>{
124
+ let changed = unheld(held, rows);
125
+ return changed.length ? g.apply(changed, {
126
+ trusted: true
127
+ }) : [];
128
+ });
129
+ export let LISTED = 20;
130
+ let page = (query, options = {})=>line`${sub(query)}&.order=-created.at&.limit=${Math.min(LISTED, Math.max(1, options.limit ?? LISTED))}${sub(options.after == null ? line`` : line`&.after=${options.after}`)}&*`;
131
+ // What attributes a write made here: the transcript it is about, and who
132
+ // wrote it where the caller said. The terminal says who is at its keyboard,
133
+ // the config's `person` (./backend_worker.ts); where nobody says, the
134
+ // instrument is recorded and the actor is left unset rather than guessed; a
135
+ // model turn attributes itself (@yaks/session react.ts).
136
+ export let through = (session, by)=>({
137
+ ...by ? {
138
+ by
139
+ } : {},
140
+ via: session
141
+ });
142
+ /** A new transcript, as one write: the session and its instruction files,
143
+ * followed by a message that asks for a turn when one was given. An empty
144
+ * session holds its model choice until that first message arrives. The
145
+ * session and the message are whoever began it; the instruction files are the
146
+ * harness's own, put in front of the model, and never that person's words. */ export let begin = async (g, prompt, o)=>{
147
+ let operator = await humanCaller(g, {
148
+ by: o.by,
149
+ via: o.via
150
+ });
151
+ // A session wearing no persona works as the session that started it does
152
+ // (@yaks/session `actorOf`), so what it writes still names an actor.
153
+ let actor = !o.persona && o.via ? await actorOf(g, o.via) : undefined;
154
+ let project = o.project ?? (o.work ? (await lineage(g, o.work)).find((b)=>b.project)?.entity.eid : undefined);
155
+ let session = o.eid ?? crypto.randomUUID();
156
+ let files = (o.files ?? []).map((f, i)=>({
157
+ ...promptEntry(session, i + 1, f.body, f.source, 'shared', f.revision),
158
+ $actor: through(session)
159
+ }));
160
+ let context = [
161
+ ...files,
162
+ ...prompt ? [
163
+ {
164
+ entity: {
165
+ eid: crypto.randomUUID()
166
+ },
167
+ [ENTRY]: {
168
+ session,
169
+ seq: files.length + 1
170
+ },
171
+ [CONTENT]: {
172
+ body: prompt
173
+ },
174
+ using: o.using,
175
+ $actor: through(session, o.by)
176
+ }
177
+ ] : []
178
+ ];
179
+ await g.apply([
180
+ {
181
+ entity: {
182
+ eid: session
183
+ },
184
+ session: {
185
+ id: session.slice(0, 8),
186
+ operator,
187
+ ...o.persona ? {
188
+ persona: o.persona
189
+ } : {},
190
+ ...actor ? {
191
+ actor
192
+ } : {},
193
+ ...o.topic ? {
194
+ topic: o.topic
195
+ } : {}
196
+ },
197
+ native: {},
198
+ ...o.home ? {
199
+ home: o.home
200
+ } : {},
201
+ ...project ? {
202
+ filed: {
203
+ project
204
+ }
205
+ } : {},
206
+ ...o.title ? {
207
+ doc: {
208
+ title: o.title
209
+ }
210
+ } : {},
211
+ ...prompt ? {} : {
212
+ using: o.using
213
+ },
214
+ $actor: through(session, o.by)
215
+ },
216
+ ...context
217
+ ]);
218
+ return session;
219
+ };
220
+ // The defects an agent reports, where its options name nowhere else.
221
+ let reporter = (opts)=>opts.report ?? ((error, where)=>console.error(where.phase, error));
222
+ // What serves each provider, by `provider.name`.
223
+ let served = (opts)=>({
224
+ ...opts.model && opts.provider ? {
225
+ [opts.provider]: opts.model
226
+ } : {},
227
+ ...opts.providers
228
+ });
229
+ // The runner's model where nothing resolves one: a host lent no model asks
230
+ // through `resolveModel` alone.
231
+ let unserved = ()=>Promise.reject(new ModelError('provider', 'Choose a model'));
232
+ /**
233
+ * The runner an agent's options lend (@yaks/session `Runner`), over the
234
+ * provider, model and tool rows its first step seeds: what serves each
235
+ * provider, what a transcript may call, and how a step is taken. A host registers it with
236
+ * @yaks/session `running` wherever its effects are worked.
237
+ *
238
+ * ```ts
239
+ * import { lend } from '@yaks/harness'
240
+ * import { running } from '@yaks/session'
241
+ *
242
+ * // h.fx.handle(running(h.g, lend({ h, model })))
243
+ * ```
244
+ */ export let lend = (opts)=>{
245
+ let h = opts.h;
246
+ let report = reporter(opts);
247
+ const provider = opts.provider;
248
+ let name = opts.name ?? '';
249
+ const implementations = served(opts);
250
+ let available = opts.model ? undefined : new Set(Object.keys(implementations).map((name)=>identityEid(PROVIDER, [
251
+ name
252
+ ])));
253
+ let model = opts.model ?? implementations[provider ?? ''] ?? unserved;
254
+ let tools = opts.resultText ? opts.tools ?? [] : [
255
+ ...opts.tools ?? [],
256
+ ...[
257
+ resultTool(h.g),
258
+ ...valueTools(async (id)=>(await h.g.get([
259
+ id
260
+ ]))[0])
261
+ ].filter((t)=>!opts.tools?.some((own)=>own.name == t.name))
262
+ ];
263
+ let remote = opts.remote ?? (()=>Promise.resolve([]));
264
+ let remoteSignature = '';
265
+ // The remote tools each session's newest ask was offered. A tool is its
266
+ // name, and a server reconfigured mid-ask serves that name from somewhere
267
+ // else: the calls an ask issued run on the handlers it was offered.
268
+ const offered = new Map();
269
+ const offerSessions = new Map();
270
+ // Seeded by the first step, not when lent: a host lends the runner while it
271
+ // is being put together, before anything may be written in its name.
272
+ let seeded;
273
+ let { taskDefaults, maxChildren, maxSessions, childProperties, prepareChild } = opts;
274
+ let resolveModel = providerResolver(h.g, implementations, opts.model, undefined, (error)=>report(error, {
275
+ phase: 'model-metadata'
276
+ }));
277
+ // Every system prompt composed here opens with `opens`. What a transcript
278
+ // inherited is sent as it was: it opened with it already.
279
+ let opened = (text)=>[
280
+ opts.opens,
281
+ text
282
+ ].filter(Boolean).join(PART) || undefined;
283
+ let kept = (inherited, configured)=>inheritedInstructions(inherited, undefined) ?? opened(configured);
284
+ // Compaction is a text task, even when a transcript selects a media model:
285
+ // it asks the model this agent was lent by name, else the one
286
+ // `defaultUsing` reads (./default.ts by default), read again before every
287
+ // ask.
288
+ let compact = {
289
+ model,
290
+ name,
291
+ ...provider ? {
292
+ provider: identityEid(PROVIDER, [
293
+ provider
294
+ ])
295
+ } : {}
296
+ };
297
+ return {
298
+ holder: h.me,
299
+ asyncTools: true,
300
+ ...opts.patience == null ? {} : {
301
+ patience: opts.patience
302
+ },
303
+ gone: h.gone,
304
+ taskDefaults,
305
+ maxChildren,
306
+ maxSessions,
307
+ childProperties,
308
+ prepareChild,
309
+ model,
310
+ resolveModel,
311
+ onward: (using, _error, passed)=>movedOn(h.g, using, {
312
+ available,
313
+ passed
314
+ }),
315
+ compactModel: compact,
316
+ compactWithCurrent: opts.compactWithCurrent,
317
+ elideCold: opts.elideCold,
318
+ background: opts.background,
319
+ answers: answers(h.g, implementations, opts.model),
320
+ tools,
321
+ named: opts.named,
322
+ toolSnapshot: async (phase, session, boundary, open)=>{
323
+ if (!name) {
324
+ let using = await (opts.defaultUsing?.() ?? defaultUsing(h.g));
325
+ let [row] = await h.g.get([
326
+ String(using.model)
327
+ ]);
328
+ Object.assign(compact, {
329
+ provider: undefined
330
+ }, await resolveModel(using, row));
331
+ }
332
+ await (seeded ??= seedMissing(h.g, seed({
333
+ provider,
334
+ model: name,
335
+ tools
336
+ })));
337
+ const key = boundary ?? session;
338
+ const held = phase === 'call' && offered.get(key);
339
+ if (held) return [
340
+ ...tools,
341
+ ...held
342
+ ];
343
+ const served = await remote(session);
344
+ const all = [
345
+ ...tools,
346
+ ...served
347
+ ];
348
+ const twice = [
349
+ ...new Set(all.map((t)=>t.name).filter((n, i, names)=>names.indexOf(n) != i))
350
+ ];
351
+ if (twice.length) {
352
+ throw new Error(`Two tools share a name: ${twice.join(', ')}`);
353
+ }
354
+ // Several asks may overlap older calls. Keep each original offer until
355
+ // all of its calls have final results; a later catalogue refresh must
356
+ // not redirect an in-progress call to a newly configured MCP server.
357
+ if (phase === 'ask' && offered.size) {
358
+ const asks = await h.g.get(open.flatMap((b)=>{
359
+ const source = b.call?.source;
360
+ return source == null ? [] : [
361
+ String(source)
362
+ ];
363
+ }), [
364
+ 'ask'
365
+ ]);
366
+ const outstanding = new Set(asks.flatMap((ask)=>{
367
+ const through = ask.ask?.through;
368
+ return through == null ? [] : [
369
+ String(through)
370
+ ];
371
+ }));
372
+ for (const old of offered.keys()){
373
+ if (old != key && offerSessions.get(old) == session && !outstanding.has(old)) {
374
+ offered.delete(old);
375
+ offerSessions.delete(old);
376
+ }
377
+ }
378
+ }
379
+ offered.set(key, served);
380
+ offerSessions.set(key, session);
381
+ const signature = JSON.stringify(served.map((t)=>[
382
+ t.name,
383
+ t.description,
384
+ t.parameters
385
+ ]));
386
+ if (signature !== remoteSignature) {
387
+ await seedMissing(h.g, seed({
388
+ provider,
389
+ model: name,
390
+ tools: served
391
+ }));
392
+ remoteSignature = signature;
393
+ }
394
+ return all;
395
+ },
396
+ streaming: opts.streaming,
397
+ checkpointMs: opts.checkpointMs,
398
+ typed: opts.typed,
399
+ compactAt: opts.compactAt,
400
+ compactShare: opts.compactShare,
401
+ instructions: typeof opts.instructions == 'string' ? opened(opts.instructions) : undefined,
402
+ instructionScope: opts.instructionScope,
403
+ readable: opts.readable,
404
+ requestInstructions: opts.cachePrefix && (async (session)=>{
405
+ let { persona, ...cache } = opts.cachePrefix;
406
+ let [layers, added] = await Promise.all([
407
+ wornLayers(h.g, session, opts.wear ?? {}, persona),
408
+ typeof opts.instructions == 'function' ? opts.instructions(session) : opts.instructions
409
+ ]);
410
+ let lead = [
411
+ opts.opens,
412
+ layers.shared
413
+ ].filter(Boolean).join(PART);
414
+ return {
415
+ instructions: [
416
+ lead,
417
+ layers.local,
418
+ added
419
+ ].filter(Boolean).join(PART),
420
+ ...layers.shared ? {
421
+ cachePrefix: {
422
+ ...cache,
423
+ length: lead.length
424
+ }
425
+ } : {}
426
+ };
427
+ }),
428
+ resolveInstructions: async (inherited, session)=>{
429
+ if (!opts.wear) {
430
+ return typeof opts.instructions == 'function' ? opened(await opts.instructions(session)) : kept(inherited, opts.instructions);
431
+ }
432
+ // What was sent before already says the persona, so only what the host
433
+ // adds follows the persona's text as it reads now, a part of its own.
434
+ // The two are read at once.
435
+ let reads = typeof opts.instructions == 'function' ? opts.instructions : undefined;
436
+ let [worn, added] = await Promise.all([
437
+ wornBy(h.g, session, opts.wear),
438
+ reads ? reads(session) : opts.instructions
439
+ ]);
440
+ // A transcript wearing nothing is told what it was told before: the
441
+ // instructions its first line chose (a builder's contract) stand.
442
+ if (!worn && !reads) return kept(inherited, added);
443
+ return opened([
444
+ worn,
445
+ added
446
+ ].filter(Boolean).join(PART));
447
+ },
448
+ ...opts.wear?.tools ? {
449
+ resolveTools: (session)=>offeredTo(h.g, session, opts.wear)
450
+ } : {},
451
+ inputText: async (transcript)=>inputText(transcript, await senders(h.g, transcript), opts.inputSource, opts.inputBody),
452
+ contextItems: opts.context,
453
+ requestItems: opts.requestItems,
454
+ turnItems: opts.turnItems,
455
+ resultText: opts.resultText ?? ((entry)=>outputView(h.g, entry, opts.outputLimit)),
456
+ report: (error, session, phase)=>report(error, {
457
+ session,
458
+ phase
459
+ }),
460
+ ...opts.refused ? {
461
+ refused: opts.refused
462
+ } : {},
463
+ each: opts.each,
464
+ recoverSettled: recoverSettled(h.g, h.report),
465
+ hold: opts.hold
466
+ };
467
+ };
468
+ /**
469
+ * Lend a graph the runner and work its pool, seeded with what serves it.
470
+ *
471
+ * ```ts ignore
472
+ * import { agent } from '@yaks/harness'
473
+ *
474
+ * let a = agent({ h: { g, fx, vocab, me }, model: fake })
475
+ * let s = await a.start('reply with the word pong')
476
+ * await a.idle(s)
477
+ * ```
478
+ */ export let agent = (opts)=>{
479
+ let h = opts.h;
480
+ let report = reporter(opts);
481
+ const provider = opts.provider;
482
+ let name = opts.name ?? '';
483
+ const implementations = served(opts);
484
+ let tools = opts.tools ?? [];
485
+ // The runner, taking every run this graph's commits owe it, until the agent
486
+ // closes: then no step starts, a waiting tool stops waiting, and the step in
487
+ // flight is let finish.
488
+ let stopping = new AbortController();
489
+ let r = {
490
+ ...lend(opts),
491
+ stopping: stopping.signal
492
+ };
493
+ seedMissing(h.g, seed({
494
+ provider,
495
+ model: name,
496
+ tools
497
+ }));
498
+ h.fx.handle(running(h.g, r));
499
+ let working = h.fx.work(h.g, stopping.signal).catch((error)=>report(error, {
500
+ phase: 'effects'
501
+ }));
502
+ // What this agent was lent by name; the default stands in for no model.
503
+ let using = {
504
+ ...provider ? {
505
+ provider: identityEid(PROVIDER, [
506
+ provider
507
+ ])
508
+ } : {},
509
+ ...name ? {
510
+ model: identityEid(MODEL, [
511
+ name
512
+ ])
513
+ } : {}
514
+ };
515
+ let names = {
516
+ ...using.model ? {
517
+ [using.model]: name
518
+ } : {},
519
+ ...Object.fromEntries(tools.map((t)=>[
520
+ toolEid(t.name),
521
+ t.name
522
+ ]))
523
+ };
524
+ // Every model this graph holds, by its label (@yaks/model `labelOf`): an
525
+ // ask may reach any of them, not only the one lent. A test's stand-in
526
+ // models have none, so one without is not reported here.
527
+ let naming = Promise.resolve(h.g.read('.model&.fields=model')).then((rows)=>{
528
+ for (let b of rows){
529
+ let model = b[MODEL];
530
+ if (model?.name) {
531
+ names[b.entity.eid] = labelOf(model);
532
+ }
533
+ }
534
+ }, (error)=>report(error, {
535
+ phase: 'model-label'
536
+ }));
537
+ // Lifecycle bookkeeping only; all application state remains in the graph.
538
+ let refusal;
539
+ let shutdown;
540
+ let operations = new Set();
541
+ let admitted = (work)=>(...args)=>{
542
+ if (refusal) return Promise.reject(refusal);
543
+ let pending = work(...args);
544
+ operations.add(pending);
545
+ let done = ()=>operations.delete(pending);
546
+ pending.then(done, done);
547
+ return pending;
548
+ };
549
+ // The request in force on a transcript: what a line said to it asks a turn
550
+ // with, since a turn is asked for by a `using` on an entry.
551
+ let asking = async (session)=>{
552
+ let using = await usingOf(h.g, session) ?? await selectedUsing(h.g, session);
553
+ return using ? {
554
+ using
555
+ } : {};
556
+ };
557
+ // Whether a transcript has nothing more to do that this agent is doing or
558
+ // owes: no pass of its own over it, nothing waiting for a place, and no turn
559
+ // it answers outstanding.
560
+ let quiet = async (session)=>{
561
+ if (passing(h.g, session)) return false;
562
+ let [self] = await h.g.get([
563
+ session
564
+ ], [
565
+ 'dispatch',
566
+ 'waiting',
567
+ 'admitted'
568
+ ]);
569
+ if (dispatchStatus(self) == 'queued') return false;
570
+ let status = await currentStatus(h.g, session);
571
+ if (status != 'pending' && status != 'running') return true;
572
+ return !await answering(h.g, session, r);
573
+ };
574
+ let a = {
575
+ h,
576
+ tools,
577
+ names,
578
+ naming,
579
+ get model () {
580
+ return String(using.model ?? '');
581
+ },
582
+ admitted,
583
+ personas: async ()=>(await h.g.read('.persona')).sort((a, b)=>String(a.doc?.title ?? '').localeCompare(String(b.doc?.title ?? ''))),
584
+ models: async (session)=>modelSelection(h.g, session, using.model ? using : await defaultUsing(h.g)),
585
+ selectModel: async (session, model)=>{
586
+ const [owner] = await h.g.get([
587
+ session
588
+ ]);
589
+ if (!owner?.session) throw new Error('Unknown session');
590
+ const chosen = await modelUsing(h.g, model, implementations);
591
+ const prior = await selectedUsing(h.g, session);
592
+ // A conversation another harness ran until now is taken over here, and
593
+ // the model is told so (@yaks/session `handoffOf`).
594
+ const note = await handoffOf(h.g, session);
595
+ await h.g.apply([
596
+ {
597
+ entity: {
598
+ eid: crypto.randomUUID()
599
+ },
600
+ entry: {
601
+ session
602
+ },
603
+ notice: {},
604
+ ...note ? {
605
+ [CONTENT]: {
606
+ body: note
607
+ }
608
+ } : {},
609
+ using: {
610
+ ...using,
611
+ ...prior,
612
+ ...chosen
613
+ },
614
+ $actor: through(session)
615
+ }
616
+ ]);
617
+ },
618
+ start: admitted((prompt, o = {})=>admit(h.g, undefined, opts, async ()=>{
619
+ const chosen = o.model ? await modelUsing(h.g, o.model, implementations) : using.model ? {} : await defaultUsing(h.g);
620
+ let eid = crypto.randomUUID();
621
+ return begin(h.g, prompt, {
622
+ eid,
623
+ ...await opts.opening?.(o.persona, eid),
624
+ ...o.persona ? {
625
+ persona: o.persona
626
+ } : {},
627
+ by: o.by,
628
+ using: {
629
+ ...using,
630
+ ...chosen,
631
+ ...o.effort ? {
632
+ effort: o.effort
633
+ } : {}
634
+ }
635
+ });
636
+ })),
637
+ send: admitted(async (session, text, by)=>{
638
+ // Admission is independent of the provider/tool execution queue. The
639
+ // session plugin assigns seq inside this write's transaction.
640
+ let eid = crypto.randomUUID();
641
+ await h.g.apply([
642
+ {
643
+ entity: {
644
+ eid
645
+ },
646
+ [ENTRY]: {
647
+ session
648
+ },
649
+ [CONTENT]: {
650
+ body: text
651
+ },
652
+ ...await asking(session),
653
+ $actor: through(session, by)
654
+ }
655
+ ]);
656
+ return eid;
657
+ }),
658
+ taskEntry: admitted((session, text)=>taskEntry(h.g, session, text, opts)),
659
+ archive: admitted(async (session, archived)=>{
660
+ let rows = await h.g.read('.session');
661
+ if (!rows.some((b)=>b.entity.eid == session)) {
662
+ throw new Error('Unknown session');
663
+ }
664
+ // The mark is written bare: when it happened, and through what, are the
665
+ // graph's to stamp (@yaks/graph stamp.ts), never this clock's.
666
+ await h.g.apply([
667
+ {
668
+ entity: {
669
+ eid: session
670
+ },
671
+ archived: archived ? {} : null,
672
+ $actor: through(session)
673
+ }
674
+ ]);
675
+ }),
676
+ sessions: admitted(async (selected, options)=>{
677
+ let rows = options || !selected ? await h.g.read(page(line`.session`, options)) : [
678
+ ...(await h.g.get([
679
+ selected
680
+ ])).filter((b)=>b.session),
681
+ // The closed browser is a selected-session tree, not an archive page.
682
+ // Include direct children even before they start (spawned.call may be
683
+ // null), without scanning or titling every historical session.
684
+ ...await h.g.read(line`.session&.spawned.parent=${selected}&*`)
685
+ ];
686
+ // A selected session need not belong to the current page.
687
+ if (selected && !rows.some((b)=>b.entity.eid == selected)) {
688
+ rows = [
689
+ ...(await h.g.get([
690
+ selected
691
+ ])).filter((b)=>b.session),
692
+ ...rows
693
+ ];
694
+ }
695
+ return await Promise.all(rows.map(async (b)=>({
696
+ ...b,
697
+ session: {
698
+ ...b.session,
699
+ title: await sessionTitle(h.g, b)
700
+ }
701
+ })));
702
+ }),
703
+ runtime: (session)=>runtimeRows(h.g, session),
704
+ control: (session, action)=>runtimeAction(a, session, action),
705
+ children: admitted((session)=>children(h.g, session)),
706
+ tasks: admitted(async (options)=>await h.g.read(page(line`.task.status=open,wip`, options))),
707
+ entrySource: (session, eid, request)=>entrySource(h.g, session, eid, request),
708
+ transcript: admitted((session)=>transcript(h.g, session)),
709
+ usage: (session)=>transcriptUsage(h.g, session),
710
+ transcriptWindow: (session, request)=>transcriptWindow(h.g, session, request),
711
+ resume: admitted(async ()=>{
712
+ // A child stays active until its receipt lands. Waking that dispatch
713
+ // retries an interrupted delivery without revisiting finished children.
714
+ let woken = [
715
+ ...new Set((await h.g.read(line`${sub(live)}|.session&.dispatch.status=active,queued,waiting`)).map((b)=>b.entity.eid))
716
+ ];
717
+ await opts.resuming?.();
718
+ for (let s of woken){
719
+ answer(h.g, s, r).catch((error)=>report(error, {
720
+ phase: 'resume',
721
+ session: s
722
+ }));
723
+ }
724
+ return woken;
725
+ }),
726
+ idle: admitted(async (session)=>{
727
+ while(!stopping.signal.aborted && !await quiet(session)){
728
+ await (passing(h.g, session)?.catch(()=>{}) ?? new Promise((go)=>setTimeout(go, 10)));
729
+ }
730
+ }),
731
+ line: (b, view = 'Line', ctx = {})=>render(sessionViews, b, view, h.vocab, {
732
+ names,
733
+ anchor: r.model.anchor,
734
+ ...ctx
735
+ }, 'plain'),
736
+ instruct: admitted(async (session, text, source = 'explicit')=>{
737
+ let entry = promptEntry(session, undefined, text, source, 'local');
738
+ await h.g.apply([
739
+ {
740
+ ...entry,
741
+ ...await asking(session)
742
+ }
743
+ ]);
744
+ return entry.entity.eid;
745
+ }),
746
+ // Admission stops, the runner takes no new step and leaves the pool, and
747
+ // what was admitted and the step in flight drain before the host lets go.
748
+ close: (reason)=>shutdown ??= (async ()=>{
749
+ refusal ??= reason ?? new Error('Agent is closing');
750
+ stopping.abort();
751
+ await Promise.allSettled([
752
+ ...operations
753
+ ]);
754
+ await h.fx.stop();
755
+ await working;
756
+ await opts.release?.();
757
+ })()
758
+ };
759
+ return a;
760
+ };
761
+ /** Child assignment is explicit admission data; copied fork context is not its title. */ export let sessionTitle = async (g, session)=>{
762
+ if (session.spawned) {
763
+ const [assignment] = await g.get([
764
+ session.entity.eid + ':input'
765
+ ]);
766
+ if (assignment?.content) return titleOf([
767
+ assignment
768
+ ]);
769
+ }
770
+ return titleOf(await g.read(line`.entry.session=${session.entity.eid}&.content&!prompt&!notice&.order=entry.seq&.limit=1`));
771
+ };
772
+ /** What a transcript is called in a listing: the first message sent to it. */ export let titleOf = (entries)=>String(comp(entries.find((b)=>CONTENT in b && !b.prompt && !b.notice) ?? {}, CONTENT)?.body ?? '').split('\n')[0].slice(0, 60);
773
+ //# sourceMappingURL=agent.js.map