@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/runs.ts ADDED
@@ -0,0 +1,479 @@
1
+ // The functions behind the harness's own tools, exported as
2
+ // `@yaks/harness/tools`: the facet a `yak` host takes from the harness when a
3
+ // config lists it as a plugin (@yaks/cli `compose`), beside every other
4
+ // package's.
5
+ //
6
+ // `session_new` and `session_send` write a line that asks a transcript for a
7
+ // turn, and wait for the reply: the entry the transcript settles on. Neither
8
+ // runs the transcript. A session whose run goes on outside the graph gives no
9
+ // reply until that run ends, so a send to it knocks instead, and it hears the
10
+ // knock at its next tool call (@yaks/session's bus); a send that starts such a
11
+ // run again answers once it has started. The runner does, wherever the host's effects are
12
+ // worked (./effects.ts): a box's `yak serve`, or another process explicitly
13
+ // serving the effects role. Drawing the reply is the caller's: a line
14
+ // on a command line, the harness itself under `--tui` (./view.ts).
15
+ // `model_list` lists a configured provider's catalog, signed in as the
16
+ // harness signs in to it, and `model_pin` pins the default to one routed
17
+ // model or clears the pin. A tool answers, it does not write to a terminal.
18
+
19
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
20
+ import { argsOf, who } from '@yaks/graph/call'
21
+ import { identityEid } from '@yaks/graph/identity'
22
+ import { Refused } from '@yaks/graph/errors'
23
+ import { edgeEid } from '@yaks/edge'
24
+ import { BEST, type Runs } from '@yaks/graph/tools'
25
+ import type { Host } from 'jsr:@yaks/host@0.2.36'
26
+
27
+ import { MODEL, PROVIDER, windows } from '@yaks/model'
28
+ import {
29
+ absent,
30
+ and,
31
+ conjoin,
32
+ eq,
33
+ fields,
34
+ line,
35
+ list,
36
+ parse,
37
+ stringify,
38
+ sub,
39
+ } from '@yaks/query'
40
+ import { ask, askedOf, handoffOf, newestOf, usingOf } from '@yaks/session'
41
+ import { human } from '@yaks/id'
42
+ import { changes } from '@yaks/session/wait'
43
+ import { begin, seed, through } from './agent.js'
44
+ import { defaultUsing, pin, routing } from './default.js'
45
+ import { selectedUsing } from './model_selection.js'
46
+ import { configured, lending } from './providers.js'
47
+ import { signins } from '@yaks/connections'
48
+ import * as systemProcess from '@yaks/process/system'
49
+ import { hosted } from './store.js'
50
+ import { homeAt } from './session_machines.js'
51
+ import { conversations } from './conversations.js'
52
+ import { openingFor } from './instructions.js'
53
+ import { ORACLE } from '@yaks/topic'
54
+ import { sessionHome } from '@yaks/machine/targets'
55
+
56
+ type Args = Record<string, unknown>
57
+ let word = (args: Args, name: string): string | undefined => {
58
+ let v = args[name]
59
+ return typeof v == 'string' ? v : undefined
60
+ }
61
+
62
+ let nameOf = (row: Bundle | undefined, comp: string) =>
63
+ (row?.[comp] as Comp | undefined)?.name as string | undefined
64
+
65
+ // The `using` a call asks for by provider and model name, its rows seeded. A
66
+ // model named alone is asked wherever it is served, and only one nothing
67
+ // serves yet goes to the default's provider (./default.ts); a
68
+ // provider named alone takes the default model only where it is the
69
+ // default's.
70
+ let named = async (
71
+ graph: Graph,
72
+ provider?: string,
73
+ model?: string,
74
+ ): Promise<Comp> => {
75
+ if (!provider && !model) return await defaultUsing(graph)
76
+ if (!provider) {
77
+ let eid = identityEid(MODEL, [model!])
78
+ let served = await graph.read(line`.serves .edge.to=${eid} .limit=1`)
79
+ if (served.length) return { model: eid }
80
+ }
81
+ let fallback = provider && model ? undefined : await defaultUsing(graph)
82
+ let [p, m] = fallback
83
+ ? await graph.get([String(fallback.provider), String(fallback.model)])
84
+ : []
85
+ if (provider && !model && provider != nameOf(p, PROVIDER)) {
86
+ throw new Refused(`Choose a model for ${provider}`)
87
+ }
88
+ provider ??= nameOf(p, PROVIDER)!
89
+ model ??= nameOf(m, MODEL)!
90
+ await graph.apply(seed({ provider, model }), { trusted: true })
91
+ return {
92
+ provider: identityEid(PROVIDER, [provider]),
93
+ model: identityEid(MODEL, [model]),
94
+ }
95
+ }
96
+
97
+ // The `using` a follow-up asks with: the one in force, changed only by what
98
+ // the send names. A provider named alone keeps the model in force, and a model
99
+ // named alone keeps the provider in force while it serves that model, so a
100
+ // session spawned on a command line goes on there.
101
+ let following = async (
102
+ graph: Graph,
103
+ prior: Comp | undefined,
104
+ provider?: string,
105
+ model?: string,
106
+ ): Promise<Comp> => {
107
+ if (!prior) return await named(graph, provider, model)
108
+ let [p, m] = await graph.get([
109
+ String(prior.provider ?? ''),
110
+ String(prior.model ?? ''),
111
+ ])
112
+ let held = nameOf(p, PROVIDER)
113
+ if (!model && (!provider || provider == held)) return prior
114
+ if (model && !provider && prior.provider) {
115
+ let edge = edgeEid(
116
+ String(prior.provider),
117
+ 'serves',
118
+ identityEid(MODEL, [model]),
119
+ )
120
+ let [served] = await graph.get([edge], ['serves'])
121
+ if (served?.serves) provider = held
122
+ }
123
+ return await named(graph, provider, model ?? nameOf(m, MODEL))
124
+ }
125
+
126
+ // What a session is doing while it is still working: owing a turn, owing a
127
+ // tool's answer, or waiting for a place to run.
128
+ let WORKING = ['pending', 'running', 'queued']
129
+
130
+ // A transcript's newest entry, read alone: a reply to a long transcript never
131
+ // reads the rest of it.
132
+ let newest = async (graph: Graph, s: Eid): Promise<Bundle[]> => {
133
+ let last = await newestOf(graph, s)
134
+ return last ? [last] : []
135
+ }
136
+
137
+ // Wait for the reply: once the session's own computed status (@yaks/session
138
+ // status.ts, one statement over the store) says it is no longer working, where
139
+ // it settled — the newest entry, which is the model's reply, or the error or
140
+ // stop it ended on. A host winding down stops waiting and answers the newest
141
+ // entry as it stands; the session goes on wherever it runs.
142
+ let settled = async (
143
+ graph: Graph,
144
+ s: Eid,
145
+ stopping?: AbortSignal,
146
+ ): Promise<Bundle[]> => {
147
+ for await (let done of changes(graph, { signal: stopping })) {
148
+ let [self] = await graph.get([s], ['session'])
149
+ let status = (self?.session as Comp | undefined)?.status
150
+ if (!WORKING.includes(String(status)) || done) {
151
+ return await newest(graph, s)
152
+ }
153
+ }
154
+ throw new Error('wait ended without a final read')
155
+ }
156
+
157
+ // Wait for the run a send asked a command to start: once its process is
158
+ // launched (@yaks/spawn stamps a pid and clears the last run's exit), the
159
+ // session as it stands, for that run gives no reply until it ends; one that
160
+ // failed to launch answers where it settled.
161
+ let begun = async (
162
+ graph: Graph,
163
+ s: Eid,
164
+ stopping?: AbortSignal,
165
+ ): Promise<Bundle[]> => {
166
+ let comps = ['process', 'exit', 'session'].filter((c) => graph.vocab.comp(c))
167
+ for await (let done of changes(graph, { signal: stopping })) {
168
+ let [row] = await graph.get([s], comps)
169
+ let status = (row?.session as Comp | undefined)?.status
170
+ if ((row?.process as Comp | undefined)?.pid != null && !row?.exit) {
171
+ return await graph.get([s])
172
+ }
173
+ if (!WORKING.includes(String(status)) || done) {
174
+ return await newest(graph, s)
175
+ }
176
+ }
177
+ throw new Error('wait ended without a final read')
178
+ }
179
+
180
+ // Whether a provider is a command its runs are processes of (@yaks/spawn).
181
+ let commanded = async (graph: Graph, using?: Comp): Promise<boolean> => {
182
+ if (!using?.provider) return false
183
+ let [p] = await graph.get([String(using.provider)], [PROVIDER])
184
+ return (p?.[PROVIDER] as Comp | undefined)?.transport == 'process'
185
+ }
186
+
187
+ // A transcript's statuses once its run is over.
188
+ let OVER = ['stopped', 'failed']
189
+
190
+ // Whether a session's run goes on outside the graph: a command its provider
191
+ // runs (@yaks/spawn), started or about to be, or a harness that reads its own
192
+ // file. One that has ended is asked for its next run instead.
193
+ export let outside = async (
194
+ graph: Graph,
195
+ s: Eid,
196
+ using?: Comp,
197
+ ): Promise<boolean> => {
198
+ if (!graph.vocab.comp('knock')) return false
199
+ let comps = ['native', 'process', 'exit', 'session']
200
+ let [row] = await graph.get([s], comps.filter((c) => graph.vocab.comp(c)))
201
+ let self = row?.session as Comp | undefined
202
+ if (
203
+ !row || row.native || row.exit || self?.ended == true ||
204
+ OVER.includes(String(self?.status))
205
+ ) return false
206
+ return !!row.process || !!self?.transcript || await commanded(graph, using)
207
+ }
208
+
209
+ // Who called: what they asked a session is theirs (@yaks/tools signs the call
210
+ // with its caller).
211
+ let caller = (call: Bundle): Eid | undefined => who(call)?.by
212
+
213
+ let text = (call: Bundle, body: string): Bundle => ({
214
+ entity: { eid: crypto.randomUUID() },
215
+ content: { body },
216
+ output: { source: call.entity.eid },
217
+ })
218
+
219
+ export type { Listed } from '@yaks/model'
220
+
221
+ // The sessions not over, the ones a caller most likely means: a graph holds
222
+ // tens of thousands of finished ones, more than one answer may hold. The mark
223
+ // answers this without reading an entry (@yaks/session/ended).
224
+ let LIVE = '.session !session.ended'
225
+ // What a row of the page carries: the session, its status among it, when and by
226
+ // whom it began, what it was spawned under, its title and how its process
227
+ // exited. Its command line and the sizes of its context are kilobytes each, so
228
+ // they are read from the session itself (`graph_show`), or by a query naming
229
+ // `*`.
230
+ let SHOWN = line`?created ?spawned ?doc ?exit`
231
+
232
+ // One room reading applies to the queue, so report it once for the sessions
233
+ // in this page whose start is still owed.
234
+ let waitingStarts = async (graph: Graph, page: Bundle[]): Promise<string> => {
235
+ let waiting = page.filter((b) =>
236
+ WORKING.includes(String((b.session as Comp).status)) &&
237
+ (b.session as Comp).status != 'running'
238
+ )
239
+ if (!waiting.length || !graph.vocab.prop('effect', 'waiting')) return ''
240
+ // The queue's head is the one that last asked for room: the start it last
241
+ // deferred says why, whichever task's priority put it first.
242
+ let [head] = await graph.read(
243
+ line`.effect.handler=spawn_start .effect.state=pending .effect.waiting .order=-effect.next .limit=1`,
244
+ )
245
+ let reason = (head?.effect as Comp | undefined)?.waiting
246
+ if (typeof reason != 'string') return ''
247
+ let runs = await graph.read(and(
248
+ eq('effect.handler', 'spawn_start'),
249
+ eq('effect.state', 'pending'),
250
+ absent('effect.target.entry.session.native'),
251
+ eq(
252
+ 'effect.target.entry.session',
253
+ list(...waiting.map((b) => b.entity.eid)),
254
+ ),
255
+ fields('effect.target.entry.session'),
256
+ ))
257
+ let pending = new Set(runs.map((b) => (b.entry as Comp | undefined)?.session))
258
+ let shown = waiting.filter((b) => pending.has(b.entity.eid)).map(
259
+ human(graph.vocab),
260
+ )
261
+ return shown.length ? `${shown.join(', ')} — ${reason}.` : ''
262
+ }
263
+
264
+ // One page of sessions, newest first unless the query orders them, and a last
265
+ // row saying how to read on when more match. The page reads one row past its
266
+ // size to learn that; a query with a `.limit` of its own has chosen its window
267
+ // and comes back as it asked.
268
+ let sessionList: Runs[string] = async (call, graph) => {
269
+ let args = argsOf(call)
270
+ let query = String(args.query ?? '').trim() || LIVE
271
+ let size = Number(args.limit) > 0 ? Math.floor(Number(args.limit)) : BEST
272
+ // The caller's line is parsed, never spliced: its clauses sit beside the
273
+ // page's own, so nothing it says can reach past `.session`.
274
+ let asked = parse(query)
275
+ let rows = await graph.read(and(
276
+ ...parse(line`.session`).clauses,
277
+ ...asked.clauses,
278
+ ...parse(line`.order=-created.at .limit=${size + 1} ${sub(SHOWN)}`)
279
+ .clauses,
280
+ ))
281
+ let page = rows.slice(0, size)
282
+ let waiting = await waitingStarts(graph, page)
283
+ if (rows.length <= size && !waiting) return page
284
+ // The first `.after` of a query is the one it reads from, so the next page's
285
+ // query replaces the cursor this one arrived with.
286
+ let rest = asked.clauses.filter((c) => c.kind != 'after')
287
+ let next = rows.length > size && conjoin(
288
+ stringify(and(...rest)),
289
+ `.after=${page.at(-1)!.entity.eid}`,
290
+ )
291
+ return [...page, {
292
+ entity: { eid: '$said' },
293
+ content: {
294
+ body: [
295
+ waiting,
296
+ next && (
297
+ `More sessions match than this page of ${size}. Query ` +
298
+ `\`${next}\` reads the next page, a larger limit a longer one, and ` +
299
+ `query \`.session\` every status.`
300
+ ),
301
+ ].filter(Boolean).join('\n\n'),
302
+ },
303
+ output: { source: call.entity.eid },
304
+ }]
305
+ }
306
+
307
+ /** The functions behind the tools the harness declares (./vocab.json). */
308
+ export let runs = (host?: Host): Runs => ({
309
+ ...conversations(host),
310
+ session_home: async (call, graph) => {
311
+ let args = argsOf(call)
312
+ return await sessionHome(
313
+ graph,
314
+ String(args.session),
315
+ String(args.workspace),
316
+ word(args, 'cwd'),
317
+ )
318
+ },
319
+ session_list: sessionList,
320
+ session_new: async (call, graph) => {
321
+ let args = argsOf(call)
322
+ let prompt = word(args, 'prompt')
323
+ if (!prompt && args.tui !== true) {
324
+ throw new Refused('session new needs a prompt without --tui')
325
+ }
326
+ let using = await named(graph, word(args, 'provider'), word(args, 'model'))
327
+ let effort = word(args, 'effort')
328
+ // A session opened on a topic wears the oracle unless it names another.
329
+ let topic = word(args, 'topic')
330
+ let persona = word(args, 'persona') ?? (topic ? ORACLE : undefined)
331
+ let work = word(args, 'work')
332
+ let home = args.workspace
333
+ ? {
334
+ workspace: String(args.workspace),
335
+ ...args.cwd ? { cwd: String(args.cwd) } : {},
336
+ }
337
+ : homeAt(undefined, word(args, 'cwd'))
338
+ let id = crypto.randomUUID()
339
+ let via = who(call)?.via
340
+ let opened = await openingFor(
341
+ graph,
342
+ home,
343
+ host?.workspaces,
344
+ { persona, work, topic, starter: via },
345
+ )
346
+ let s = await begin(graph, prompt || undefined, {
347
+ eid: id,
348
+ home,
349
+ ...opened,
350
+ work,
351
+ ...topic ? { topic } : {},
352
+ by: caller(call),
353
+ via,
354
+ using: { ...using, ...effort ? { effort } : {} },
355
+ })
356
+ return prompt && args.wait !== false
357
+ ? await settled(graph, s, host?.stopping)
358
+ : await graph.get([s])
359
+ },
360
+ session_send: async (call, graph) => {
361
+ let args = argsOf(call)
362
+ // The session arrives as its eid: @yaks/tools resolved what was typed (an
363
+ // eid, `S-81`, a run's own id) and refused one that names no session.
364
+ let s = String(args.session)
365
+ let prior = await usingOf(graph, s) ?? await selectedUsing(graph, s)
366
+ // Words about a task's work are kept on the task as well (@yaks/session
367
+ // ./asks.ts), so its next run starts from every ask, not the newest.
368
+ let actor = who(call)
369
+ let body = String(args.text)
370
+ let about = await askedOf(graph, s, word(args, 'task'))
371
+ let provider = word(args, 'provider')
372
+ let model = word(args, 'model')
373
+ let using = prior
374
+ if (provider || model || !prior) {
375
+ using = {
376
+ ...prior?.effort ? { effort: prior.effort } : {},
377
+ ...await following(graph, prior, provider, model),
378
+ }
379
+ }
380
+ // A knock needs no model: the run going on chose its own. One that names
381
+ // a model this graph asks takes the conversation over here, whatever
382
+ // harness ran it so far: that harness may have run out.
383
+ let over = (provider || model) && !await commanded(graph, using)
384
+ if (!over && await outside(graph, s, prior)) {
385
+ return await graph.apply([{
386
+ ...about ? ask(s, about, body, actor?.by) : {
387
+ entity: { eid: crypto.randomUUID() },
388
+ doc: { body },
389
+ knock: { target: s, ...actor?.by ? { from: actor.by } : {} },
390
+ },
391
+ ...actor ? { $actor: actor } : {},
392
+ }])
393
+ }
394
+ // Taking over another harness's conversation, the model is told so.
395
+ let note = over ? await handoffOf(graph, s) : undefined
396
+ await graph.apply([
397
+ ...note
398
+ ? [{
399
+ entity: { eid: crypto.randomUUID() },
400
+ entry: { session: s },
401
+ content: { body: note },
402
+ notice: {},
403
+ $actor: through(s),
404
+ }]
405
+ : [],
406
+ {
407
+ entity: { eid: crypto.randomUUID() },
408
+ entry: { session: s },
409
+ content: { body },
410
+ ...using ? { using } : {},
411
+ $actor: through(s, caller(call)),
412
+ },
413
+ // The request says it to the session, so its copy on the task is
414
+ // marked said: nothing hears it a second time.
415
+ ...about
416
+ ? [{
417
+ ...ask(s, about, body, actor?.by),
418
+ ...graph.vocab.comp('notified') ? { notified: {} } : {},
419
+ ...actor ? { $actor: actor } : {},
420
+ }]
421
+ : [],
422
+ ])
423
+ if (args.wait === false) return await graph.get([s])
424
+ return await commanded(graph, using)
425
+ ? await begun(graph, s, host?.stopping)
426
+ : await settled(graph, s, host?.stopping)
427
+ },
428
+ model_list: async (call, graph) => {
429
+ if (!host) throw new Error('model list needs a host')
430
+ let provider = word(argsOf(call), 'provider') ??
431
+ nameOf(
432
+ (await graph.get([String((await defaultUsing(graph)).provider)]))[0],
433
+ PROVIDER,
434
+ )
435
+ let h = hosted(host)
436
+ let served = await configured(
437
+ h.plugins,
438
+ lending(h, signins(h), fetch, systemProcess.env.get),
439
+ )
440
+ let model = provider ? served[provider] : undefined
441
+ if (!model?.list) {
442
+ throw new Refused(
443
+ `${provider ?? 'The default provider'} is not a provider this ` +
444
+ `config names: ${Object.keys(served).join(', ') || 'none'}`,
445
+ )
446
+ }
447
+ let models = await windows(graph, await model.list())
448
+ return [text(
449
+ call,
450
+ [
451
+ `models from ${provider}`,
452
+ ...models.map(({ name, context }) =>
453
+ ` ${name}` + (context ? ` ${context} tokens` : '')
454
+ ),
455
+ ].join('\n'),
456
+ )]
457
+ },
458
+ model_pin: async (call, graph) => {
459
+ let args = argsOf(call)
460
+ let model = word(args, 'model')
461
+ if (model && args.clear) {
462
+ throw new Refused('Name a model to pin, or --clear, not both')
463
+ }
464
+ if (model || args.clear) await pin(graph, model, { by: caller(call) })
465
+ let routes = (await routing(graph)).map((r) => r.name)
466
+ let using = await defaultUsing(graph)
467
+ let name = nameOf((await graph.get([String(using.model)]))[0], MODEL)
468
+ let now = `${name}${using.why ? ` (${using.why})` : ''}`
469
+ return [text(
470
+ call,
471
+ model
472
+ ? `The default is pinned to ${model}. Every native session that ` +
473
+ `names no model asks it, heal's fixers among them, until ` +
474
+ `\`yak model pin --clear\`.`
475
+ : `${args.clear ? 'The pin is cleared. ' : ''}The default is ${now}.` +
476
+ ` It routes: ${routes.join(', ') || 'no models'}.`,
477
+ )]
478
+ },
479
+ })
@@ -0,0 +1,36 @@
1
+ {
2
+ "$id": "urn:uuid:668d6b13-f14a-4f0a-9bc1-f9a026a9ca7a",
3
+ "title": "runtime projection",
4
+ "$defs": {
5
+ "session": {
6
+ "$id": "urn:uuid:96e3396f-d74e-4fb8-8e4c-0d2b25c78331",
7
+ "component": true,
8
+ "properties": {
9
+ "status": {
10
+ "$id": "urn:uuid:867e4f98-7482-4b2a-b7b3-ac7cd4cb07b0",
11
+ "type": "string"
12
+ }
13
+ }
14
+ },
15
+ "attempt": {
16
+ "$id": "urn:uuid:85b4b112-2fad-4c4c-b35a-033d6f6b1f9b",
17
+ "component": true,
18
+ "properties": {
19
+ "by": {
20
+ "$id": "urn:uuid:1023852d-6cda-4df4-aef0-5f181bde057a",
21
+ "type": "string"
22
+ }
23
+ }
24
+ },
25
+ "call": {
26
+ "$id": "urn:uuid:eb4360c1-1e93-4678-9d97-79a787a8478c",
27
+ "component": true,
28
+ "properties": {}
29
+ },
30
+ "refusal": {
31
+ "component": true,
32
+ "extends": true,
33
+ "properties": {}
34
+ }
35
+ }
36
+ }
package/runtime.js ADDED
@@ -0,0 +1,105 @@
1
+ /** Runtime inspection and explicit actions. Reads never wake a session; an
2
+ * action is a write, which whoever runs the transcript reads. */ import { line } from "@yaks/query";
3
+ import { dispatchStatus, swap } from "@yaks/session/admission";
4
+ export let runtimeRows = async (g, session)=>{
5
+ let [selected, children] = await Promise.all([
6
+ g.read(line`.session&.entity.eid=${session}&*`),
7
+ g.read(line`.session&.spawned.parent=${session}&*`)
8
+ ]);
9
+ return await Promise.all([
10
+ ...selected,
11
+ ...children
12
+ ].map(async (b)=>{
13
+ let id = b.entity.eid;
14
+ let [attempt] = await g.read(line`.entry.session=${id}&.attempt.state=inflight&.order=-entry.seq&.limit=1&*`);
15
+ let [tail] = await g.read(line`.entry.session=${id}&!notice&.order=-entry.seq&.limit=1&*`);
16
+ let [call] = await g.read(line`.entry.session=${id}&.call&.order=-entry.seq&.limit=1`);
17
+ let waiting = call && !(await g.read(line`.result.call=${call.entity.eid}&.limit=1`)).length;
18
+ // Project existing facts only; nothing is written back as duplicate status.
19
+ return {
20
+ ...b,
21
+ ...attempt ? {
22
+ attempt: attempt.attempt
23
+ } : {},
24
+ ...waiting ? {
25
+ call: call.call
26
+ } : {},
27
+ ...tail?.interrupted ? {
28
+ interrupted: tail.interrupted
29
+ } : {},
30
+ ...tail?.failed ? {
31
+ failed: tail.failed
32
+ } : {},
33
+ // A result carrying its call's refusal answered the call; the turn
34
+ // goes on.
35
+ ...tail?.refusal && !tail.result ? {
36
+ refusal: tail.refusal
37
+ } : {},
38
+ ...(attempt ?? tail)?.created ? {
39
+ updated: (attempt ?? tail).created
40
+ } : {}
41
+ };
42
+ }));
43
+ };
44
+ export let runtimeAction = async (a, session, action)=>{
45
+ let [row] = await a.h.g.read(line`.session&.entity.eid=${session}`);
46
+ if (!row) throw new Error('Session not found');
47
+ if (action == 'interrupt') {
48
+ let [attempt] = await a.h.g.read(line`.entry.session=${session}&.attempt.state=inflight`);
49
+ if (!attempt) return 'No cancellable model request is running.';
50
+ // The run holding the transcript sees the withdrawal and aborts the
51
+ // request (@yaks/session run.ts).
52
+ await a.h.g.apply([
53
+ {
54
+ entity: {
55
+ eid: crypto.randomUUID()
56
+ },
57
+ entry: {
58
+ session
59
+ },
60
+ notice: {},
61
+ cancel: {
62
+ target: attempt.entity.eid
63
+ }
64
+ }
65
+ ]);
66
+ return 'Cancellation requested. Provider must acknowledge abort; independent processes are unchanged.';
67
+ }
68
+ if (action == 'cancel-queued') {
69
+ let [row] = await a.h.g.read(line`.session&.entity.eid=${session}&*`);
70
+ if (!row) throw new Error('Session not found');
71
+ if (dispatchStatus(row) != 'queued') {
72
+ throw new Error('Only queued work can be cancelled here');
73
+ }
74
+ // Preconditions prevent cancelling a child that started while the view was open.
75
+ if (!await swap(a.h.g, session, 'queued', {
76
+ state: 'settled'
77
+ }, [
78
+ {
79
+ entity: {
80
+ eid: crypto.randomUUID()
81
+ },
82
+ entry: {
83
+ session
84
+ },
85
+ stop: {},
86
+ content: {
87
+ body: 'Queued session cancelled by the user; task state is unchanged.'
88
+ }
89
+ }
90
+ ])) {
91
+ throw new Error('Only queued work can be cancelled here');
92
+ }
93
+ return 'Queued session cancelled. Its task was not cancelled.';
94
+ }
95
+ if (action != 'resume') throw new Error('Unknown runtime action');
96
+ let [tail] = await a.h.g.read(line`.entry.session=${session}&!notice&.order=-entry.seq&.limit=1&*`);
97
+ let [ask] = await a.h.g.read(line`.entry.session=${session}&.ask&.order=-entry.seq&.limit=1&*`);
98
+ let interrupted = ask?.interrupted != null && !(tail?.refusal && !tail.result) && !tail?.exception;
99
+ if (row.session.status != 'settled' && !interrupted) {
100
+ throw new Error('Continue requires idle or interrupted work; other failures and stopped work are not replayed');
101
+ }
102
+ await a.send(session, 'Continue from the current state. Preserve completed work; do not repeat completed tool operations.');
103
+ return 'Continuation input submitted; the previous request was not replayed.';
104
+ };
105
+ //# sourceMappingURL=runtime.js.map
package/runtime.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sources":["./runtime.ts"],"names":[],"mappings":"AAAA;+DAC+D,GAE/D,SAAS,IAAI,2BAAgC;AAC7C,SAAS,cAAc,EAAE,IAAI,uCAA4C;AAIzE,OAAO,IAAI,cAAc,OACvB,GACA;EAEA,IAAI,CAAC,UAAU,SAAS,GAAG,MAAM,QAAQ,GAAG,CAAC;IAC3C,EAAE,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,QAAQ,EAAE,CAAC;IAC9C,EAAE,IAAI,CAAC,IAAI,CAAC,yBAAyB,EAAE,QAAQ,EAAE,CAAC;GACnD;EACD,OAAO,MAAM,QAAQ,GAAG,CAAC;OAAI;OAAa;GAAS,CAAC,GAAG,CAAC,OAAO;IAC7D,IAAI,KAAK,EAAE,MAAM,CAAC,GAAG;IACrB,IAAI,CAAC,QAAQ,GAAG,MAAM,EAAE,IAAI,CAC1B,IAAI,CAAC,eAAe,EAAE,GAAG,qDAAqD,CAAC;IAEjF,IAAI,CAAC,KAAK,GAAG,MAAM,EAAE,IAAI,CACvB,IAAI,CAAC,eAAe,EAAE,GAAG,qCAAqC,CAAC;IAEjE,IAAI,CAAC,KAAK,GAAG,MAAM,EAAE,IAAI,CACvB,IAAI,CAAC,eAAe,EAAE,GAAG,iCAAiC,CAAC;IAE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