@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
@@ -0,0 +1,186 @@
1
+ /** File snapshots and explicit image context: @yaks/blob artifacts, each an
2
+ * entity named by its bytes' address, the bytes in the graph's byte store. */ import { line } from "@yaks/query";
3
+ import { ToolError } from "@yaks/session";
4
+ import { artifactBytes, mediaTypeOf, sizeOf } from "@yaks/blob";
5
+ import { artifactStore } from "@yaks/blob/identify";
6
+ const MAX = 20 * 1024 * 1024;
7
+ const VISION = [
8
+ 'image/png',
9
+ 'image/jpeg',
10
+ 'image/webp'
11
+ ];
12
+ /** Supported vision formats with a stated size; SVG, GIF and malformed headers
13
+ * are never image inputs. */ export let imageType = (b)=>{
14
+ let type = mediaTypeOf(b);
15
+ return type && VISION.includes(type) && sizeOf(b) ? type : undefined;
16
+ };
17
+ /** A registered artifact's bytes. Graph authorization is applied before
18
+ * resolving an external address. */ export let registered = async (g, eid, blobs)=>{
19
+ let [row] = await g.read(line`.entity.eid=${eid}`);
20
+ let a = row?.artifact;
21
+ if (!a || typeof a.address != 'string' || !/^[a-f0-9]{64}$/.test(a.address) || typeof a.size != 'number' || a.size < 0 || a.size > MAX) {
22
+ throw new ToolError('artifact', 'Missing, unauthorized, or oversized artifact');
23
+ }
24
+ if (!blobs) throw new ToolError('artifact', 'No artifact store here');
25
+ let bytes;
26
+ try {
27
+ bytes = await artifactBytes(blobs, {
28
+ address: a.address,
29
+ media_type: String(a.media_type),
30
+ size: a.size
31
+ });
32
+ } catch {
33
+ throw new ToolError('artifact', 'Artifact integrity check failed');
34
+ }
35
+ if (!bytes) throw new ToolError('artifact', 'Artifact bytes unavailable');
36
+ return {
37
+ bytes,
38
+ mediaType: String(a.media_type),
39
+ revision: a.address
40
+ };
41
+ };
42
+ export let artifactTools = (g, opts = {})=>[
43
+ {
44
+ name: 'artifact_import',
45
+ description: 'Snapshot a file from the session machine into external artifact storage (maximum 20 MiB). Relative paths use this session’s cwd. Does not attach or send it to the model.',
46
+ parameters: {
47
+ type: 'object',
48
+ properties: {
49
+ path: {
50
+ type: 'string'
51
+ }
52
+ },
53
+ required: [
54
+ 'path'
55
+ ]
56
+ },
57
+ run: async (args, ctx)=>{
58
+ if (!ctx) throw new ToolError('artifact', 'Session context required');
59
+ let path = String(args.path ?? '');
60
+ if (!path) throw new ToolError('artifact', 'A file path is required');
61
+ if (!opts.artifacts) {
62
+ throw new ToolError('artifact', 'No artifact store here');
63
+ }
64
+ if (!opts.machines) {
65
+ throw new ToolError('artifact', 'No workspace export binding here');
66
+ }
67
+ let bytes;
68
+ try {
69
+ for await (let file of opts.machines.files(ctx.session, [
70
+ path
71
+ ])){
72
+ if (bytes) throw new ToolError('artifact', 'Expected one file');
73
+ if (file.bytes.length > MAX) {
74
+ throw new ToolError('artifact', 'Expected a file up to 20 MiB');
75
+ }
76
+ bytes = file.bytes;
77
+ }
78
+ } catch (error) {
79
+ if (error instanceof ToolError) throw error;
80
+ throw new ToolError('artifact', 'Cannot export file from session machine');
81
+ }
82
+ if (!bytes) {
83
+ throw new ToolError('artifact', 'Cannot export file from session machine');
84
+ }
85
+ let artifact = await artifactStore(opts.artifacts)(bytes, imageType(bytes) ?? 'application/octet-stream');
86
+ let eid = artifact.address;
87
+ await g.apply([
88
+ {
89
+ entity: {
90
+ eid
91
+ },
92
+ artifact
93
+ }
94
+ ]);
95
+ return JSON.stringify({
96
+ artifact: eid,
97
+ ...artifact
98
+ });
99
+ }
100
+ },
101
+ ...[
102
+ 'user',
103
+ 'model'
104
+ ].map((audience)=>({
105
+ name: audience == 'user' ? 'artifact_attach' : 'image_view',
106
+ description: audience == 'user' ? 'Attach a registered artifact to this conversation for the user. Images may render inline; this does not send image pixels to the model.' : 'Inspect a registered PNG, JPEG or WebP artifact as vision input on the next model turn. Stores only the reference; never returns base64 text.',
107
+ parameters: {
108
+ type: 'object',
109
+ properties: {
110
+ artifact: {
111
+ type: 'string'
112
+ }
113
+ },
114
+ required: [
115
+ 'artifact'
116
+ ]
117
+ },
118
+ run: async (args, ctx)=>{
119
+ if (!ctx) throw new ToolError('artifact', 'Session context required');
120
+ let eid = String(args.artifact ?? '');
121
+ let { bytes, mediaType, revision } = await registered(g, eid, opts.artifacts);
122
+ if (audience == 'model' && imageType(bytes) != mediaType) {
123
+ throw new ToolError('image', 'Unsupported or invalid image type');
124
+ }
125
+ // The existing call entry provides stable identity and ordering. Replays patch the same attachment.
126
+ await g.apply([
127
+ {
128
+ entity: {
129
+ eid: ctx.call.entity.eid
130
+ },
131
+ attachment: {
132
+ artifact: eid,
133
+ audience,
134
+ revision
135
+ },
136
+ content: {
137
+ body: (audience == 'model' ? 'Inspect image: ' : 'Attached artifact: ') + eid
138
+ }
139
+ }
140
+ ]);
141
+ return JSON.stringify({
142
+ artifact: eid,
143
+ media_type: mediaType,
144
+ size: bytes.length,
145
+ audience
146
+ });
147
+ }
148
+ }))
149
+ ];
150
+ /** Add pixels only for successful inspection results in the request window. */ export let imageContext = async (g, window, entries, blobs)=>{
151
+ let items = new Map();
152
+ let total = 0;
153
+ let byId = new Map(entries.map((b)=>[
154
+ b.entity.eid,
155
+ b
156
+ ]));
157
+ for (let entry of window){
158
+ let result = entry.result;
159
+ if (!result) continue;
160
+ let call = byId.get(String(result.call));
161
+ let attachment = call?.attachment;
162
+ if (attachment?.audience != 'model') continue;
163
+ let eid = String(attachment.artifact);
164
+ let { bytes, mediaType, revision } = await registered(g, eid, blobs);
165
+ if (attachment.revision != revision) {
166
+ throw new ToolError('image', 'Image reference changed since admission');
167
+ }
168
+ total += bytes.length;
169
+ if (total > MAX) {
170
+ throw new ToolError('image', 'Image context exceeds 20 MiB; start a new session');
171
+ }
172
+ if (imageType(bytes) != mediaType) {
173
+ throw new ToolError('image', 'Unsupported or invalid image type');
174
+ }
175
+ items.set(entry.entity.eid, [
176
+ {
177
+ kind: 'image',
178
+ bytes,
179
+ mediaType,
180
+ label: 'Image requested by tool call ' + String(call?.call?.id) + ': ' + eid
181
+ }
182
+ ]);
183
+ }
184
+ return items;
185
+ };
186
+ //# sourceMappingURL=artifact_tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"artifact_tools.js","sources":["./artifact_tools.ts"],"names":[],"mappings":"AAAA;4EAC4E,GAE5E,SAAS,IAAI,2BAAgC;AAE7C,SAAoB,SAAS,6BAAkC;AAC/D,SAAS,aAAa,EAAc,WAAW,EAAE,MAAM,0BAA+B;AACtF,SAAS,aAAa,mCAAwC;AAG9D,MAAM,MAAM,KAAK,OAAO;AACxB,MAAM,SAAS;EAAC;EAAa;EAAc;CAAa;AAExD;2BAC2B,GAC3B,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,OAAO,YAAY;EACvB,OAAO,QAAQ,OAAO,QAAQ,CAAC,SAAS,OAAO,KAAK,OAAO;AAC7D,EAAC;AAED;kCACkC,GAClC,OAAO,IAAI,aAAa,OAAO,GAAU,KAAa;EACpD,IAAI,CAAC,IAAI,GAAG,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC;EACjD,IAAI,IAAI,KAAK;EACb,IACE,CAAC,KAAK,OAAO,EAAE,OAAO,IAAI,YAAY,CAAC,iBAAiB,IAAI,CAAC,EAAE,OAAO,KACtE,OAAO,EAAE,IAAI,IAAI,YAAY,EAAE,IAAI,GAAG,KAAK,EAAE,IAAI,GAAG,KACpD;IACA,MAAM,IAAI,UACR,YACA;EAEJ;EACA,IAAI,CAAC,OAAO,MAAM,IAAI,UAAU,YAAY;EAC5C,IAAI;EACJ,IAAI;IACF,QAAQ,MAAM,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AAI,QAAQ,GAAG,CAAC,CAAC,IAAM;MAAC,EAAE,MAAM,CAAC,GAAG;MAAE;KAAE;EACvD,KAAK,IAAI,SAAS,OAAQ;IACxB,IAAI,SAAS,MAAM,MAAM;IACzB,IAAI,CAAC,QAAQ;IACb,IAAI,OAAO,KAAK,GAAG,CAAC,OAAO,OAAO,IAAI;IACtC,IAAI,aAAa,MAAM;IACvB,IAAI,YAAY,YAAY,SAAS;IACrC,IAAI,MAAM,OAAO,WAAW,QAAQ;IACpC,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,MAAM,WAAW,GAAG,KAAK;IAC9D,IAAI,WAAW,QAAQ,IAAI,UAAU;MACnC,MAAM,IAAI,UAAU,SAAS;IAC/B;IACA,SAAS,MAAM,MAAM;IACrB,IAAI,QAAQ,KAAK;MACf,MAAM,IAAI,UACR,SACA;IAEJ;IACA,IAAI,UAAU,UAAU,WAAW;MACjC,MAAM,IAAI,UAAU,SAAS;IAC/B;IACA,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,EAAE;MAAC;QAC3B,MAAM;QACN;QACA;QACA,OAAO,kCACL,OAAQ,MAAM,MAAe,MAAM,OAAO;MAC9C;KAAE;EACJ;EACA,OAAO;AACT,EAAC"}
@@ -0,0 +1,190 @@
1
+ /** File snapshots and explicit image context: @yaks/blob artifacts, each an
2
+ * entity named by its bytes' address, the bytes in the graph's byte store. */
3
+ import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
4
+ import { line } from '@yaks/query'
5
+ import type { Item } from 'jsr:@yaks/model@0.2.36'
6
+ import { type Tool, ToolError } from '@yaks/session'
7
+ import { artifactBytes, type Blobs, mediaTypeOf, sizeOf } from '@yaks/blob'
8
+ import { artifactStore } from '@yaks/blob/identify'
9
+ import type { WorkspaceFile } from './session_machines.ts'
10
+
11
+ const MAX = 20 * 1024 * 1024
12
+ const VISION = ['image/png', 'image/jpeg', 'image/webp']
13
+
14
+ /** Supported vision formats with a stated size; SVG, GIF and malformed headers
15
+ * are never image inputs. */
16
+ export let imageType = (b: Uint8Array): string | undefined => {
17
+ let type = mediaTypeOf(b)
18
+ return type && VISION.includes(type) && sizeOf(b) ? type : undefined
19
+ }
20
+
21
+ /** A registered artifact's bytes. Graph authorization is applied before
22
+ * resolving an external address. */
23
+ export let registered = async (g: Graph, eid: string, blobs?: Blobs) => {
24
+ let [row] = await g.read(line`.entity.eid=${eid}`)
25
+ let a = row?.artifact as Comp | undefined
26
+ if (
27
+ !a || typeof a.address != 'string' || !/^[a-f0-9]{64}$/.test(a.address) ||
28
+ typeof a.size != 'number' || a.size < 0 || a.size > MAX
29
+ ) {
30
+ throw new ToolError(
31
+ 'artifact',
32
+ 'Missing, unauthorized, or oversized artifact',
33
+ )
34
+ }
35
+ if (!blobs) throw new ToolError('artifact', 'No artifact store here')
36
+ let bytes: Uint8Array | undefined
37
+ try {
38
+ bytes = await artifactBytes(blobs, {
39
+ address: a.address,
40
+ media_type: String(a.media_type),
41
+ size: a.size,
42
+ })
43
+ } catch {
44
+ throw new ToolError('artifact', 'Artifact integrity check failed')
45
+ }
46
+ if (!bytes) throw new ToolError('artifact', 'Artifact bytes unavailable')
47
+ return { bytes, mediaType: String(a.media_type), revision: a.address }
48
+ }
49
+
50
+ export let artifactTools = (
51
+ g: Graph,
52
+ opts: {
53
+ artifacts?: Blobs
54
+ machines?: {
55
+ files(session: string, paths: string[]): AsyncIterable<WorkspaceFile>
56
+ }
57
+ } = {},
58
+ ): Tool[] => [
59
+ {
60
+ name: 'artifact_import',
61
+ description:
62
+ 'Snapshot a file from the session machine into external artifact storage (maximum 20 MiB). Relative paths use this session’s cwd. Does not attach or send it to the model.',
63
+ parameters: {
64
+ type: 'object',
65
+ properties: { path: { type: 'string' } },
66
+ required: ['path'],
67
+ },
68
+ run: async (args, ctx) => {
69
+ if (!ctx) throw new ToolError('artifact', 'Session context required')
70
+ let path = String(args.path ?? '')
71
+ if (!path) throw new ToolError('artifact', 'A file path is required')
72
+ if (!opts.artifacts) {
73
+ throw new ToolError('artifact', 'No artifact store here')
74
+ }
75
+ if (!opts.machines) {
76
+ throw new ToolError('artifact', 'No workspace export binding here')
77
+ }
78
+ let bytes: Uint8Array | undefined
79
+ try {
80
+ for await (let file of opts.machines.files(ctx.session, [path])) {
81
+ if (bytes) throw new ToolError('artifact', 'Expected one file')
82
+ if (file.bytes.length > MAX) {
83
+ throw new ToolError('artifact', 'Expected a file up to 20 MiB')
84
+ }
85
+ bytes = file.bytes
86
+ }
87
+ } catch (error) {
88
+ if (error instanceof ToolError) throw error
89
+ throw new ToolError(
90
+ 'artifact',
91
+ 'Cannot export file from session machine',
92
+ )
93
+ }
94
+ if (!bytes) {
95
+ throw new ToolError(
96
+ 'artifact',
97
+ 'Cannot export file from session machine',
98
+ )
99
+ }
100
+ let artifact = await artifactStore(opts.artifacts)(
101
+ bytes,
102
+ imageType(bytes) ?? 'application/octet-stream',
103
+ )
104
+ let eid = artifact.address
105
+ await g.apply([{ entity: { eid }, artifact }])
106
+ return JSON.stringify({ artifact: eid, ...artifact })
107
+ },
108
+ },
109
+ ...(['user', 'model'] as const).map((audience): Tool => ({
110
+ name: audience == 'user' ? 'artifact_attach' : 'image_view',
111
+ description: audience == 'user'
112
+ ? 'Attach a registered artifact to this conversation for the user. Images may render inline; this does not send image pixels to the model.'
113
+ : 'Inspect a registered PNG, JPEG or WebP artifact as vision input on the next model turn. Stores only the reference; never returns base64 text.',
114
+ parameters: {
115
+ type: 'object',
116
+ properties: { artifact: { type: 'string' } },
117
+ required: ['artifact'],
118
+ },
119
+ run: async (args, ctx) => {
120
+ if (!ctx) throw new ToolError('artifact', 'Session context required')
121
+ let eid = String(args.artifact ?? '')
122
+ let { bytes, mediaType, revision } = await registered(
123
+ g,
124
+ eid,
125
+ opts.artifacts,
126
+ )
127
+ if (audience == 'model' && imageType(bytes) != mediaType) {
128
+ throw new ToolError('image', 'Unsupported or invalid image type')
129
+ }
130
+ // The existing call entry provides stable identity and ordering. Replays patch the same attachment.
131
+ await g.apply([{
132
+ entity: { eid: ctx.call.entity.eid },
133
+ attachment: { artifact: eid, audience, revision },
134
+ content: {
135
+ body:
136
+ (audience == 'model' ? 'Inspect image: ' : 'Attached artifact: ') +
137
+ eid,
138
+ },
139
+ }])
140
+ return JSON.stringify({
141
+ artifact: eid,
142
+ media_type: mediaType,
143
+ size: bytes.length,
144
+ audience,
145
+ })
146
+ },
147
+ })),
148
+ ]
149
+
150
+ /** Add pixels only for successful inspection results in the request window. */
151
+ export let imageContext = async (
152
+ g: Graph,
153
+ window: Bundle[],
154
+ entries: Bundle[],
155
+ blobs?: Blobs,
156
+ ): Promise<Map<string, Item[]>> => {
157
+ let items = new Map<string, Item[]>()
158
+ let total = 0
159
+ let byId = new Map(entries.map((b) => [b.entity.eid, b]))
160
+ for (let entry of window) {
161
+ let result = entry.result as Comp | undefined
162
+ if (!result) continue
163
+ let call = byId.get(String(result.call))
164
+ let attachment = call?.attachment as Comp | undefined
165
+ if (attachment?.audience != 'model') continue
166
+ let eid = String(attachment.artifact)
167
+ let { bytes, mediaType, revision } = await registered(g, eid, blobs)
168
+ if (attachment.revision != revision) {
169
+ throw new ToolError('image', 'Image reference changed since admission')
170
+ }
171
+ total += bytes.length
172
+ if (total > MAX) {
173
+ throw new ToolError(
174
+ 'image',
175
+ 'Image context exceeds 20 MiB; start a new session',
176
+ )
177
+ }
178
+ if (imageType(bytes) != mediaType) {
179
+ throw new ToolError('image', 'Unsupported or invalid image type')
180
+ }
181
+ items.set(entry.entity.eid, [{
182
+ kind: 'image',
183
+ bytes,
184
+ mediaType,
185
+ label: 'Image requested by tool call ' +
186
+ String((call?.call as Comp)?.id) + ': ' + eid,
187
+ }])
188
+ }
189
+ return items
190
+ }
@@ -0,0 +1,286 @@
1
+ import type { SourceRequest } from './detail.ts'
2
+ import {
3
+ transcriptPlan,
4
+ transcriptSegments,
5
+ type TranscriptWindow,
6
+ } from 'jsr:@yaks/session@0.2.36'
7
+ import type { ListPage } from './agent.ts'
8
+ /** Worker owns the authoritative database and all agent execution: the graph
9
+ * the config it is handed names, composed as any `yak` process composes it.
10
+ *
11
+ * It serves a backend on each MessagePort it is sent (remote.ts): the one a
12
+ * frontend that started this Worker for itself sends, or one after another
13
+ * for a test process, which starts the Worker's module graph once and hosts
14
+ * every test's backend in it (testing.ts `worker`). A backend's state is its
15
+ * own; what the Worker holds is the modules, and the observer that reports
16
+ * what escapes all of them. */
17
+ import { portLink } from 'jsr:@yaks/sync@0.2.36/port'
18
+ import { subscriptions } from 'jsr:@yaks/api@0.2.36'
19
+ import { compose, type Config, person, type Served } from 'jsr:@yaks/cli@0.2.36/host'
20
+ import { type Local, local } from './local.ts'
21
+ import { hosted } from './store.ts'
22
+ import { diagnostics, uncaught } from './diagnostics.ts'
23
+ import type { Eid } from 'jsr:@yaks/graph@0.2.36'
24
+ uncaught(diagnostics(), self)
25
+
26
+ /** One backend, on `port`: the graph its `init` names, and every command
27
+ * after it, until its `close`. */
28
+ let serve = (port: MessagePort) => {
29
+ let closing = false
30
+ let host: Served | undefined
31
+ let a: Local | undefined
32
+ // Who types at this keyboard: what the frontend submits is theirs.
33
+ let typist: Eid | undefined
34
+ let subs: ReturnType<typeof subscriptions> | undefined
35
+ let active = new Set<Promise<unknown>>()
36
+ let fake = false
37
+ let started = Promise.withResolvers<boolean>()
38
+ let released = Promise.withResolvers<void>()
39
+ let link = portLink(port, {
40
+ report: (error) => diagnostics().report(error, { phase: 'worker-command' }),
41
+ receive: (method, value) => {
42
+ let pending = handle(method, value)
43
+ active.add(pending)
44
+ pending.then(() => active.delete(pending), () => active.delete(pending))
45
+ return pending
46
+ },
47
+ })
48
+ async function handle(method: string, value: unknown): Promise<unknown> {
49
+ // Releasing the test provider must also work while close drains its turn.
50
+ if (method == 'fakeRelease' && fake) {
51
+ released.resolve()
52
+ return true
53
+ }
54
+ // Ended where it stands, while a close may still be draining: the
55
+ // frontend is about to let this Worker go, and its pid goes on, so it
56
+ // writes its own ending first (@yaks/cli `Host.end`) — its leases
57
+ // released, its `exit` stamped — and what it held is had at once.
58
+ if (method == 'end') {
59
+ await host?.end(
60
+ host.me,
61
+ 'interrupted: its backend was ended where it stood',
62
+ )
63
+ return true
64
+ }
65
+ if (closing) throw new Error('Worker is shutting down')
66
+ let args = (value ?? []) as unknown[]
67
+ if (method == 'init') {
68
+ if (a) throw new Error('Already initialized')
69
+ let options = args[0] as {
70
+ provider?: string
71
+ name?: string
72
+ config: Config
73
+ cwd?: string
74
+ streaming?: boolean
75
+ migrationPollMs?: number
76
+ hold?: number
77
+ instructions?: string
78
+ fake?: boolean | 'stuck' | 'held' | {
79
+ deltas?: number
80
+ held?: boolean
81
+ }
82
+ }
83
+ fake = Boolean(options.fake)
84
+ // The graph role alone: this worker handles the one effect it lends code
85
+ // (the session runner, below), and leaves every other run the graph owes
86
+ // to a process serving the effects role.
87
+ let served = host = await compose(
88
+ { ...options.config, ...options.hold ? { lease: options.hold } : {} },
89
+ ['graph'],
90
+ )
91
+ a = await local({
92
+ h: hosted(served, () => served.close()),
93
+ hold: options.hold,
94
+ cwd: options.cwd,
95
+ streaming: options.streaming,
96
+ instructions: options.instructions,
97
+ provider: options.provider,
98
+ name: options.name,
99
+ migrationPollMs: options.migrationPollMs,
100
+ ...(options.fake
101
+ ? {
102
+ name: 'fake',
103
+ model: async (req: import('jsr:@yaks/model@0.2.36').Request) => {
104
+ started.resolve(req.onText != null)
105
+ if (typeof options.fake == 'object' && options.fake.deltas) {
106
+ for (let i = 0; i < options.fake.deltas; i++) {
107
+ req.onText?.({ index: 0, text: 'x' })
108
+ }
109
+ }
110
+ if (options.fake == 'stuck') {
111
+ return new Promise(() => {})
112
+ }
113
+ if (
114
+ options.fake == 'held' ||
115
+ (typeof options.fake == 'object' && options.fake.held)
116
+ ) await released.promise
117
+ return {
118
+ id: 'test',
119
+ model: 'fake',
120
+ items: [{
121
+ kind: 'assistant' as const,
122
+ text: typeof options.fake == 'object' && options.fake.deltas
123
+ ? 'x'.repeat(options.fake.deltas)
124
+ : 'ok',
125
+ }],
126
+ }
127
+ },
128
+ }
129
+ : {}),
130
+ })
131
+ typist = await person(served)
132
+ subs = subscriptions(a.h.g, {
133
+ invalidate: (query, applied) =>
134
+ query.startsWith('.session') &&
135
+ applied.some((b) =>
136
+ b.entry != null || 'task' in b || 'claim' in b ||
137
+ 'completed' in b || 'cancelled' in b || '$delete' in b
138
+ ),
139
+ })
140
+ // What other processes and threads commit to the same store reaches the
141
+ // terminal too: the pool working a transcript's turn elsewhere, a `yak`
142
+ // command run beside it. The feed stops when the host closes.
143
+ let fed = subs
144
+ served.feed?.(fed.hear)
145
+ await a.naming
146
+ return { names: a.names }
147
+ }
148
+ if (!a || !subs) throw new Error('Worker not initialized')
149
+ if (method == 'fakeStarted' && fake) return await started.promise
150
+ if (method == 'subscribe') {
151
+ await subs.open(link.frame, String(args[0]), args[1] as string)
152
+ return true
153
+ }
154
+ if (method == 'unsubscribe') {
155
+ subs.close(link.frame, String(args[0]))
156
+ return true
157
+ }
158
+ if (method == 'close') {
159
+ closing = true
160
+ await Promise.allSettled([...active])
161
+ // Closing drains the step in flight before SQLite is let go, and the
162
+ // subscribers stay attached through the final writes it makes.
163
+ await a.close()
164
+ subs.drop(link.frame)
165
+ a = undefined
166
+ return true
167
+ }
168
+ // Narrow command/projection API: never evaluate caller-provided code.
169
+ switch (method) {
170
+ case 'report': {
171
+ if (!a.h.report) throw new Error('The host has no diagnostic reporter')
172
+ let thrown = args[0] as {
173
+ name: string
174
+ message: string
175
+ stack?: string
176
+ }
177
+ let error = new Error(thrown.message)
178
+ error.name = thrown.name
179
+ error.stack = thrown.stack
180
+ return await a.h.report(
181
+ error,
182
+ args[1] as Parameters<NonNullable<typeof a.h.report>>[1],
183
+ )
184
+ }
185
+ case 'runtime':
186
+ return a.runtime(String(args[0]))
187
+ case 'control':
188
+ return a.control(
189
+ String(args[0]),
190
+ args[1] as import('./runtime.ts').RuntimeAction,
191
+ )
192
+ case 'authorizeMCP':
193
+ return a.authorizeMCP(
194
+ args[0] as import('./mcp_auth.ts').MCPAuthAction,
195
+ String(args[1] ?? ''),
196
+ String(args[2] ?? ''),
197
+ )
198
+ case 'image':
199
+ return await a.image(String(args[0]))
200
+ case 'models':
201
+ return a.models(args[0] == null ? undefined : String(args[0]))
202
+ case 'personas':
203
+ return a.personas()
204
+ case 'selectModel':
205
+ return a.selectModel(String(args[0]), String(args[1]))
206
+ case 'start':
207
+ return a.start(String(args[0]), {
208
+ ...args[1] as
209
+ | { effort?: string; model?: string; persona?: string }
210
+ | undefined,
211
+ by: typist,
212
+ })
213
+ case 'send':
214
+ return a.send(String(args[0]), String(args[1]), typist)
215
+ case 'taskEntry':
216
+ return a.taskEntry(String(args[0]), String(args[1]))
217
+ case 'archive':
218
+ return a.archive(String(args[0]), Boolean(args[1]))
219
+ case 'resume':
220
+ return a.resume()
221
+ case 'idle':
222
+ return a.idle(String(args[0]))
223
+ case 'sessions':
224
+ return a.sessions(
225
+ args[0] == null ? undefined : String(args[0]),
226
+ args[1] as ListPage | undefined,
227
+ )
228
+ case 'usage':
229
+ return a.usage(String(args[0]))
230
+ case 'tasks':
231
+ return a.tasks(args[0] as ListPage | undefined)
232
+ case 'children':
233
+ return a.children(String(args[0]))
234
+ case 'entrySource':
235
+ return a.entrySource(
236
+ String(args[0]),
237
+ String(args[1]),
238
+ args[2] as SourceRequest,
239
+ )
240
+ case 'transcriptWindowPlan': {
241
+ let session = String(args[0])
242
+ let plan = await transcriptPlan(
243
+ a.h.g,
244
+ session,
245
+ args[1] as TranscriptWindow,
246
+ )
247
+ let frontiers = (await transcriptSegments(a.h.g, session)).map((s) =>
248
+ '.entry.session=' + s.session +
249
+ (Number.isFinite(s.through) ? '&.entry.seq<=' + s.through : '') +
250
+ '&.fields=entry.seq&.order=-entry.seq&.limit=1'
251
+ )
252
+ return { ...plan, frontiers }
253
+ }
254
+ case 'transcriptPlan': {
255
+ let id = String(args[0]), plans: string[] = []
256
+ let limit: number | undefined
257
+ let seen = new Set<string>()
258
+ while (!seen.has(id)) {
259
+ seen.add(id)
260
+ plans.unshift(
261
+ '.entry.session=' + id +
262
+ (limit == null ? '' : '&.entry.seq<=' + limit) + '&*',
263
+ )
264
+ let [row] = await a.h.g.get([id])
265
+ let from = (row?.fork as { from?: string })?.from
266
+ if (!from) break
267
+ let [anchor] = await a.h.g.get([from])
268
+ if (!anchor?.entry) break
269
+ id = String((anchor.entry as { session: string }).session)
270
+ limit = Math.min(
271
+ limit ?? Infinity,
272
+ Number((anchor.entry as { seq: number }).seq),
273
+ )
274
+ }
275
+ return plans
276
+ }
277
+ default:
278
+ throw new Error('Unknown worker operation: ' + method)
279
+ }
280
+ }
281
+ }
282
+
283
+ self.addEventListener('message', (event) => {
284
+ let port = (event as MessageEvent).data?.backend
285
+ if (port instanceof MessagePort) serve(port)
286
+ })