@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/local.ts ADDED
@@ -0,0 +1,282 @@
1
+ // Provider-backed capabilities lent to the native runner. Sessions see the
2
+ // graph and machines, never a host checkout. Credentials, MCP and diagnostics
3
+ // remain host integrations; shell and file work is routed through providers.
4
+
5
+ import * as systemProcess from '@yaks/process/system'
6
+
7
+ import type { Model } from 'jsr:@yaks/model@0.2.36'
8
+ import { type Bundle } from '@yaks/graph'
9
+ import type { ChildLimits, Step, Tool } from 'jsr:@yaks/session@0.2.36'
10
+ import { watchMigrations } from '@yaks/sqlite/migration'
11
+ import { render as tree } from '@yaks/react'
12
+ /* @ts-types="npm:@types/react@19.3.0" */ import type { ReactElement } from 'npm:react@19.3.0'
13
+ import { type Agent, agent, type Opts as AgentOpts } from './agent.js'
14
+ import { authorize } from './mcp_authorize.js'
15
+ import type { MCPAuthAction, MCPAuthReply } from './mcp_auth.ts'
16
+ import { mcpTools } from './mcp.js'
17
+ import { streamingEnabled } from './streaming.js'
18
+ import { imageContext, registered } from './artifact_tools.js'
19
+ import { diagnostics, type FailureContext } from './diagnostics.js'
20
+ import { homeAt, machines } from './session_machines.js'
21
+ import { homeAt as checkoutHome } from './workspace.js'
22
+ import { openingFor } from './instructions.js'
23
+ import { transcriptViews } from './transcript.js'
24
+ import type { Harness } from './store.js'
25
+ import { graphTools, harnessTools, skillTools } from './tools.js'
26
+ import { skillItems } from './skills.js'
27
+ import { pooledHttp } from './http.js'
28
+ import { configured, lending } from './providers.js'
29
+ import { kindsIndex } from '@yaks/vocab/runtime'
30
+
31
+ export { type Harness, hosted } from './store.js'
32
+ export { graphTools, harnessTools } from './tools.js'
33
+
34
+ // A Harness must be passed under `h`, never spread into the options. Explicit
35
+ // exclusions also catch spreads, which TypeScript's excess-property check skips.
36
+ type NotHarness = {
37
+ [K in Exclude<keyof Harness, 'sandboxes' | 'workspaces'>]?: never
38
+ }
39
+
40
+ /** How the harness is started here: what it stores in, what serves it, and
41
+ * what the agent may do. */
42
+ export type Opts = ChildLimits & NotHarness & {
43
+ /** Local root openings select the checkout containing this command directory. */
44
+ cwd?: string
45
+ /** the graph to run over */
46
+ h: Harness
47
+ /** what serves every ask (default: the providers the config names) */
48
+ model?: Model
49
+ /** the model to ask for by name (otherwise the graph's `defaultUsing`) */
50
+ name?: string
51
+ /** the provider to ask, by name, and the one `model` serves */
52
+ provider?: string
53
+ /** Implementations keyed by provider.name, over the configured ones, for
54
+ * embedding and testing. */
55
+ providers?: Record<string, Model>
56
+ /** what the agent may call (default: the shell and the graph) */
57
+ tools?: Tool[]
58
+ /** Stream responses by default; false overrides HARNESS_STREAM. */
59
+ streaming?: boolean
60
+ /** Alias for streaming. If both are supplied, streaming takes precedence. */
61
+ stream?: boolean
62
+ /** where settings such as `HARNESS_STREAM` are read (default this process's
63
+ * environment) */
64
+ env?: (name: string) => string | undefined
65
+ /** Transport and connection lifetime lent to the provider pool. */
66
+ http?: Parameters<typeof pooledHttp>[0]
67
+ /** Cooperating migrations must allow at least this polling interval, which
68
+ * the migration monitor keeps by `clock`. */
69
+ migrationPollMs?: number
70
+ /** how long a transcript's lease stands between renewals, so how long a
71
+ * process that died running it holds it up (ms) */
72
+ hold?: number
73
+ checkpointMs?: number
74
+ /** The system prompt every ask carries. */
75
+ instructions?: string
76
+ /** Maximum tool-result UTF-8 bytes before model-facing handle projection. */
77
+ outputLimit?: number
78
+ /** the share of its model's context window a transcript fills before it is
79
+ * compacted, for every model (@yaks/session `Deps.compactAt`) */
80
+ compactAt?: number
81
+ /** each step of every transcript, as it lands */
82
+ each?: (step: Step, session?: string) => void | Promise<void>
83
+ /** Override the workspace and sandbox bindings explicitly lent by the host. */
84
+ sandboxes?: Harness['sandboxes']
85
+ workspaces?: Harness['workspaces']
86
+ workspace?: string
87
+ }
88
+
89
+ /** The harness running here: the agent, and what only a box offers it. */
90
+ export type Local = Agent<Harness> & {
91
+ authorizeMCP: (
92
+ action: MCPAuthAction,
93
+ name?: string,
94
+ callback?: string,
95
+ ) => Promise<MCPAuthReply>
96
+ image: (eid: string) => Promise<Uint8Array>
97
+ /** one bundle as the terminal draws it */
98
+ entry: (b: Bundle) => ReactElement | null
99
+ }
100
+
101
+ /** What this machine lends an agent: its options, and what answers a person
102
+ * here. */
103
+ export type Here = {
104
+ /** the agent's options; their `release` lets go of what was opened for
105
+ * them, and leaves the graph open */
106
+ lent: AgentOpts<Harness>
107
+ /** a person authorizing a sign-in: an MCP server or model provider */
108
+ authorize: (
109
+ action: MCPAuthAction,
110
+ name?: string,
111
+ callback?: string,
112
+ ) => Promise<MCPAuthReply>
113
+ /** how the model lent names the reply a request continues */
114
+ anchor: Model['anchor']
115
+ report: (error: unknown, where: FailureContext) => void
116
+ }
117
+
118
+ /** What this machine lends an agent over `h`: the models of the providers its
119
+ * config names, over its credentials and sign-ins, the workspace and sandbox
120
+ * bindings, the MCP servers, the pictures, the instruction files where a
121
+ * session opens, the persona and topic each of its asks is told afresh, and
122
+ * where a defect is written. */
123
+ export let here = async (
124
+ h: Harness,
125
+ opts: Omit<Opts, 'h'> = {},
126
+ ): Promise<Here> => {
127
+ let env = opts.env ?? systemProcess.env.get
128
+ let http = pooledHttp(opts.http)
129
+ let auth = authorize(h)
130
+ let providers = await configured(
131
+ h.plugins,
132
+ lending(h, auth.signin, http.fetch, env),
133
+ ).catch(async (error) => {
134
+ http.close()
135
+ await auth.close()
136
+ throw error
137
+ })
138
+ let detach = h.report ? diagnostics().attach(h.report) : () => {}
139
+ let report = (error: unknown, where: FailureContext) =>
140
+ diagnostics().report(error, where)
141
+ let binding = machines(
142
+ h.g,
143
+ opts.sandboxes ?? h.sandboxes,
144
+ h.resolveHome,
145
+ opts.workspaces ?? h.workspaces,
146
+ )
147
+ const mcp = mcpTools(h, auth.signin, auth.mcp)
148
+ h.fx.created('mcp_server', mcp.refresh).changed('mcp_server', mcp.refresh)
149
+ .removed('mcp_server', mcp.refresh)
150
+ let named: Tool[] | undefined
151
+ let lent: AgentOpts<Harness> = {
152
+ ...binding.limits,
153
+ ...opts,
154
+ h,
155
+ model: opts.model,
156
+ providers: { ...providers, ...opts.providers },
157
+ tools: opts.tools ??
158
+ [
159
+ ...harnessTools(h.g, {
160
+ ...opts,
161
+ machines: binding,
162
+ workspaceEffects: !opts.workspaces &&
163
+ h.fx.slots().some((s) => s.id == 'shell' && !!s.run),
164
+ workspaces: opts.workspaces ?? h.workspaces,
165
+ artifacts: h.artifacts,
166
+ reply: h.reply,
167
+ }),
168
+ ...skillTools(h.g, h.reply),
169
+ ],
170
+ remote: mcp.snapshot,
171
+ // The host's other tools, its plugins' own among them, adapted the first
172
+ // time a transcript is offered one by name: a session whose persona
173
+ // contains task_new and search carries those and nothing else, as a
174
+ // builder's offered memory_around and memory_save does.
175
+ named: () =>
176
+ named ??= graphTools(h.g, { tools: h.hostTools?.(), reply: h.reply }),
177
+ streaming: streamingEnabled(opts, env),
178
+ // A session here may run for weeks, so no ask is told a snapshot from the
179
+ // day it opened: each says the persona it wears and the topic it is
180
+ // opened on, and is offered the tools that persona contains, as they read
181
+ // now, once its cached prefix has expired.
182
+ wear: { topic: true, tools: true },
183
+ // Each ask opens with the kinds this graph makes, as an MCP connection's
184
+ // instructions carry them (@yaks/mcp), so a session writes whole ones.
185
+ opens: kindsIndex(h.vocab),
186
+ opening: async (persona) => {
187
+ let home = opts.workspace
188
+ ? { workspace: opts.workspace, ...opts.cwd ? { cwd: opts.cwd } : {} }
189
+ : opts.cwd
190
+ ? await checkoutHome(h.g, opts.cwd)
191
+ : homeAt()
192
+ return {
193
+ home,
194
+ ...await openingFor(
195
+ h.g,
196
+ home,
197
+ opts.workspaces ?? h.workspaces,
198
+ { persona },
199
+ ),
200
+ }
201
+ },
202
+ context: (window, entries) =>
203
+ imageContext(h.g, window, entries, h.artifacts),
204
+ requestItems: (_, _entries, current) => skillItems(h.g, current),
205
+ report,
206
+ release: async () => {
207
+ http.close()
208
+ await auth.close()
209
+ await diagnostics().drain()
210
+ detach()
211
+ },
212
+ }
213
+ return { lent, authorize: auth.run, anchor: opts.model?.anchor, report }
214
+ }
215
+
216
+ /**
217
+ * Start the harness here, over a graph a `yak` config composed: lend the agent
218
+ * this machine, and work the runs its commits owe.
219
+ *
220
+ * ```ts ignore
221
+ * import { hosted, local } from '@yaks/harness/local'
222
+ *
223
+ * let a = await local({ h: hosted(host), model: fake })
224
+ * let s = await a.start('reply with the word pong')
225
+ * await a.idle(s)
226
+ * ```
227
+ */
228
+ export let local = async (opts: Opts): Promise<Local> => {
229
+ // A harness spread into the options is refused, including for untyped
230
+ // JavaScript callers, whose options TypeScript never saw.
231
+ for (let key of ['path', 'db', 'store', 'g', 'fx', 'vocab', 'close']) {
232
+ if (Object.hasOwn(opts, key)) {
233
+ throw new TypeError(
234
+ 'Pass the harness as local({ h: hosted(host) }), not spread options',
235
+ )
236
+ }
237
+ }
238
+ let h = opts.h
239
+ let env = opts.env ?? systemProcess.env.get
240
+ let { lent, authorize, anchor, report } = await here(h, opts)
241
+ let watch: { stop: () => void } | undefined
242
+ let a = agent({
243
+ ...lent,
244
+ release: async () => {
245
+ watch?.stop()
246
+ await lent.release?.()
247
+ await h.close()
248
+ },
249
+ })
250
+ let l: Local = Object.assign(a, {
251
+ authorizeMCP: a.admitted(authorize),
252
+ // What the terminal draws inline: a PNG, and not a large one.
253
+ image: a.admitted(async (eid: string) => {
254
+ let { bytes, mediaType } = await registered(h.g, eid, h.artifacts)
255
+ if (mediaType != 'image/png' || bytes.length > 4 * 1024 * 1024) {
256
+ throw new Error('Not a displayable PNG artifact')
257
+ }
258
+ return bytes
259
+ }),
260
+ entry: (b: Bundle) =>
261
+ tree(transcriptViews, b, 'Transcript', h.vocab, {
262
+ inlineImages: env('HARNESS_GRAPHICS') == 'kitty',
263
+ image: (eid: string) => l.image(eid),
264
+ names: a.names,
265
+ anchor,
266
+ }),
267
+ })
268
+ watch = h.migrations && watchMigrations(
269
+ h.migrations,
270
+ (reason) => {
271
+ // Stop scheduling immediately, but leave SQLite open for admitted work to
272
+ // drain. Restart is an explicit owner action, not a migration side effect.
273
+ void l.close(reason).catch((error) =>
274
+ report(error, { phase: 'migration-drain' })
275
+ )
276
+ console.error(reason.message)
277
+ },
278
+ opts.migrationPollMs ?? 1000,
279
+ opts.clock,
280
+ )
281
+ return l
282
+ }
package/machine.js ADDED
@@ -0,0 +1,3 @@
1
+ // Compatibility subpath; file-and-command verbs belong to @yaks/machine.
2
+ export { machineDeclared, machineTools, rooted, workspaceTools } from "@yaks/machine/tools";
3
+ //# sourceMappingURL=machine.js.map
package/machine.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.js","sources":["./machine.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,SACE,eAAe,EACf,YAAY,EACZ,MAAM,EACN,cAAc,mCACuB"}
package/machine.ts ADDED
@@ -0,0 +1,8 @@
1
+ // Compatibility subpath; file-and-command verbs belong to @yaks/machine.
2
+ export {
3
+ machineDeclared,
4
+ machineTools,
5
+ rooted,
6
+ workspaceTools,
7
+ } from '@yaks/machine/tools'
8
+ export type { MachineOpts, MachineTool } from '@yaks/machine/tools'
package/mcp.js ADDED
@@ -0,0 +1,123 @@
1
+ /** Host composition: shared MCP connections, signed in through their connections. */ import { graphMCP } from "./mcp_registry.js";
2
+ import { unsaid } from "@yaks/mcp-client";
3
+ import { toolName } from "@yaks/graph/call";
4
+ import { derivedEid } from "@yaks/graph/identity";
5
+ import { ToolError } from "@yaks/session";
6
+ import { artifactStore } from "@yaks/blob/identify";
7
+ export const mcpTools = (h, signin, connections = graphMCP(h, signin))=>{
8
+ const g = h.g;
9
+ const store = artifactStore(h.artifacts);
10
+ const render = async (value, call)=>{
11
+ const result = value;
12
+ if (!Array.isArray(result.content)) {
13
+ throw new ToolError('mcp_result', 'Invalid MCP tool result');
14
+ }
15
+ const parts = [];
16
+ for (const block of result.content){
17
+ if (block.type === 'text') parts.push(String(block.text ?? ''));
18
+ else if (block.type === 'image' || block.type === 'audio' || block.type === 'resource' && typeof block.resource?.blob === 'string') {
19
+ const item = block.type === 'resource' ? block.resource : block;
20
+ const data = String(item.data ?? item.blob ?? '');
21
+ if (data.length > 28 * 1024 * 1024) {
22
+ throw new ToolError('mcp_result', 'MCP binary result exceeds 20 MiB limit');
23
+ }
24
+ let bytes;
25
+ try {
26
+ bytes = Uint8Array.from(atob(data), (c)=>c.charCodeAt(0));
27
+ } catch {
28
+ throw new ToolError('mcp_result', 'Invalid base64 MCP result');
29
+ }
30
+ if (bytes.length > 20 * 1024 * 1024) {
31
+ throw new ToolError('mcp_result', 'MCP binary result exceeds 20 MiB limit');
32
+ }
33
+ const record = await store(bytes, String(item.mimeType ?? 'application/octet-stream'));
34
+ const eid = record.address;
35
+ await g.apply([
36
+ {
37
+ entity: {
38
+ eid
39
+ },
40
+ artifact: record
41
+ }
42
+ ]);
43
+ if (call) {
44
+ await g.apply([
45
+ {
46
+ entity: {
47
+ eid: derivedEid('mcp-attachment:' + call.call.entity.eid + ':' + parts.length)
48
+ },
49
+ entry: {
50
+ session: call.session
51
+ },
52
+ attachment: {
53
+ artifact: eid,
54
+ audience: 'user',
55
+ call: call.call.entity.eid
56
+ },
57
+ content: {
58
+ body: `MCP artifact: ${eid}`
59
+ },
60
+ output: {
61
+ source: call.call.entity.eid
62
+ }
63
+ }
64
+ ]);
65
+ }
66
+ parts.push(`Artifact: ${eid} (${record.media_type}, ${record.size} bytes)`);
67
+ } else if (block.type === 'resource') {
68
+ const r = block.resource;
69
+ parts.push(JSON.stringify({
70
+ uri: r?.uri,
71
+ mimeType: r?.mimeType,
72
+ text: r?.text
73
+ }));
74
+ } else if (block.type === 'resource_link') {
75
+ parts.push(JSON.stringify({
76
+ type: block.type,
77
+ uri: block.uri,
78
+ name: block.name,
79
+ mimeType: block.mimeType
80
+ }));
81
+ } else parts.push(`Unsupported MCP content type: ${String(block.type)}`);
82
+ }
83
+ const structured = unsaid(result);
84
+ if (structured) parts.push(structured);
85
+ const text = parts.join('\n');
86
+ if (result.isError) {
87
+ throw new ToolError('mcp_tool', text || 'Remote tool returned an error');
88
+ }
89
+ return {
90
+ text,
91
+ with: {
92
+ output: {
93
+ ...call ? {
94
+ source: call.call.entity.eid
95
+ } : {},
96
+ value: result
97
+ }
98
+ }
99
+ };
100
+ };
101
+ return {
102
+ refresh: connections.refresh,
103
+ snapshot: async ()=>(await connections.tools()).map((t)=>({
104
+ name: toolName(t),
105
+ ...t.title ? {
106
+ title: t.title
107
+ } : {},
108
+ description: t.description,
109
+ parameters: t.inputSchema,
110
+ run: async (args, call)=>{
111
+ try {
112
+ return await render(await t.reply(args), call);
113
+ } catch (error) {
114
+ if (error instanceof ToolError) throw error;
115
+ throw new ToolError('mcp_transport', error instanceof Error ? error.message : 'MCP request failed');
116
+ }
117
+ }
118
+ })),
119
+ close: connections.close,
120
+ authorize: connections.control
121
+ };
122
+ };
123
+ //# sourceMappingURL=mcp.js.map
package/mcp.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sources":["./mcp.ts"],"names":[],"mappings":"AAAA,mFAAmF,GACnF,SAAS,QAAQ,4BAA2B;AAC5C,SAAS,MAAM,gCAAqC;AACpD,SAAS,QAAQ,gCAAqC;AACtD,SAAS,UAAU,oCAAyC;AAE5D,SAAsC,SAAS,6BAAkC;AACjF,SAAS,aAAa,mCAAwC;AAG9D,OAAO,MAAM,WAAW,CACtB,GACA,QACA,cAAc,SAAS,GAAG,OAAO;EAEjC,MAAM,IAAI,EAAE,CAAC;EACb,MAAM,QAAQ,cAAc,EAAE,SAAS;EAC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;UACtC,MAAM,SAAS;UACf,GAAG,EAAE,KAAK,GAAG;YAAE,OAAO,EAAE,KAAK;UAAC,IAAI,CAAC,CAAC;UACpC,aAAa,EAAE,WAAW;UAC1B,YAAY,EAAE,WAAW;UACzB,KAAK,OAAO,MAAM;YAChB,IAAI;cACF,OAAO,MAAM,OAAO,MAAM,EAAE,KAAK,CAAC,OAAO;YAC3C,EAAE,OAAO,OAAO;cACd,IAAI,iBAAiB,WAAW,MAAM;cACtC,MAAM,IAAI,UACR,iBACA,iBAAiB,QAAQ,MAAM,OAAO,GAAG;YAE7C;UACF;QACF,CAAC;IACH,OAAO,YAAY,KAAK;IACxB,WAAW,YAAY,OAAO;EAChC;AACF,EAAC"}
package/mcp.ts ADDED
@@ -0,0 +1,141 @@
1
+ /** Host composition: shared MCP connections, signed in through their connections. */
2
+ import { graphMCP } from './mcp_registry.js'
3
+ import { unsaid } from '@yaks/mcp-client'
4
+ import { toolName } from '@yaks/graph/call'
5
+ import { derivedEid } from '@yaks/graph/identity'
6
+ import type { Harness } from './store.ts'
7
+ import { type Tool, type ToolContext, ToolError } from '@yaks/session'
8
+ import { artifactStore } from '@yaks/blob/identify'
9
+ import type { SignIns } from 'jsr:@yaks/connections@0.2.36'
10
+
11
+ export const mcpTools = (
12
+ h: Pick<Harness, 'g' | 'vault' | 'artifacts'>,
13
+ signin: SignIns,
14
+ connections = graphMCP(h, signin),
15
+ ) => {
16
+ const g = h.g
17
+ const store = artifactStore(h.artifacts)
18
+ const render = async (
19
+ value: unknown,
20
+ call?: ToolContext,
21
+ ): Promise<import('@yaks/session').Told> => {
22
+ const result = value as {
23
+ content?: Record<string, unknown>[]
24
+ structuredContent?: unknown
25
+ isError?: boolean
26
+ }
27
+ if (!Array.isArray(result.content)) {
28
+ throw new ToolError('mcp_result', 'Invalid MCP tool result')
29
+ }
30
+ const parts: string[] = []
31
+ for (const block of result.content) {
32
+ if (block.type === 'text') parts.push(String(block.text ?? ''))
33
+ else if (
34
+ block.type === 'image' || block.type === 'audio' ||
35
+ (block.type === 'resource' &&
36
+ typeof (block.resource as Record<string, unknown>)?.blob === 'string')
37
+ ) {
38
+ const item = block.type === 'resource'
39
+ ? block.resource as Record<string, unknown>
40
+ : block
41
+ const data = String(item.data ?? item.blob ?? '')
42
+ if (data.length > 28 * 1024 * 1024) {
43
+ throw new ToolError(
44
+ 'mcp_result',
45
+ 'MCP binary result exceeds 20 MiB limit',
46
+ )
47
+ }
48
+ let bytes: Uint8Array
49
+ try {
50
+ bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0))
51
+ } catch {
52
+ throw new ToolError('mcp_result', 'Invalid base64 MCP result')
53
+ }
54
+ if (bytes.length > 20 * 1024 * 1024) {
55
+ throw new ToolError(
56
+ 'mcp_result',
57
+ 'MCP binary result exceeds 20 MiB limit',
58
+ )
59
+ }
60
+ const record = await store(
61
+ bytes,
62
+ String(item.mimeType ?? 'application/octet-stream'),
63
+ )
64
+ const eid = record.address
65
+ await g.apply([{ entity: { eid }, artifact: record }])
66
+ if (call) {
67
+ await g.apply([{
68
+ entity: {
69
+ eid: derivedEid(
70
+ 'mcp-attachment:' + call.call.entity.eid + ':' + parts.length,
71
+ ),
72
+ },
73
+ entry: { session: call.session },
74
+ attachment: {
75
+ artifact: eid,
76
+ audience: 'user',
77
+ call: call.call.entity.eid,
78
+ },
79
+ content: { body: `MCP artifact: ${eid}` },
80
+ output: { source: call.call.entity.eid },
81
+ }])
82
+ }
83
+ parts.push(
84
+ `Artifact: ${eid} (${record.media_type}, ${record.size} bytes)`,
85
+ )
86
+ } else if (block.type === 'resource') {
87
+ const r = block.resource as Record<string, unknown>
88
+ parts.push(
89
+ JSON.stringify({ uri: r?.uri, mimeType: r?.mimeType, text: r?.text }),
90
+ )
91
+ } else if (block.type === 'resource_link') {
92
+ parts.push(
93
+ JSON.stringify({
94
+ type: block.type,
95
+ uri: block.uri,
96
+ name: block.name,
97
+ mimeType: block.mimeType,
98
+ }),
99
+ )
100
+ } else parts.push(`Unsupported MCP content type: ${String(block.type)}`)
101
+ }
102
+ const structured = unsaid(result)
103
+ if (structured) parts.push(structured)
104
+ const text = parts.join('\n')
105
+ if (result.isError) {
106
+ throw new ToolError('mcp_tool', text || 'Remote tool returned an error')
107
+ }
108
+ return {
109
+ text,
110
+ with: {
111
+ output: {
112
+ ...call ? { source: call.call.entity.eid } : {},
113
+ value: result,
114
+ },
115
+ },
116
+ }
117
+ }
118
+ return {
119
+ refresh: connections.refresh,
120
+ snapshot: async (): Promise<Tool[]> =>
121
+ (await connections.tools()).map((t) => ({
122
+ name: toolName(t),
123
+ ...t.title ? { title: t.title } : {},
124
+ description: t.description,
125
+ parameters: t.inputSchema!,
126
+ run: async (args, call) => {
127
+ try {
128
+ return await render(await t.reply(args), call)
129
+ } catch (error) {
130
+ if (error instanceof ToolError) throw error
131
+ throw new ToolError(
132
+ 'mcp_transport',
133
+ error instanceof Error ? error.message : 'MCP request failed',
134
+ )
135
+ }
136
+ },
137
+ })),
138
+ close: connections.close,
139
+ authorize: connections.control,
140
+ }
141
+ }
package/mcp_auth.js ADDED
@@ -0,0 +1,63 @@
1
+ /** MCP connections that carry the harness's sign-in to each server, and
2
+ * reconnect after one. No authorization input enters a transcript. */ import { connect, MCPAuthorizationRequired } from "@yaks/mcp-client";
3
+ export const authorizedMCP = (servers, token)=>{
4
+ const connections = new Map();
5
+ const challenges = new Map();
6
+ const retired = [];
7
+ const get = (s)=>{
8
+ let c = connections.get(s.name);
9
+ if (!c) {
10
+ c = connect(s, {
11
+ token: async ()=>await token(s) ?? null
12
+ });
13
+ connections.set(s.name, c);
14
+ }
15
+ return c;
16
+ };
17
+ return {
18
+ /** What the server asked for when it last refused, asking it again. */ challenge: async (s)=>{
19
+ try {
20
+ await get(s).list();
21
+ } catch (error) {
22
+ if (error instanceof MCPAuthorizationRequired) {
23
+ challenges.set(s.name, error.challenge);
24
+ }
25
+ }
26
+ return challenges.get(s.name) ?? {};
27
+ },
28
+ /** A new connection after a sign-in. Already-issued calls keep the old. */ reconnect: async (s)=>{
29
+ const previous = connections.get(s.name);
30
+ connections.delete(s.name);
31
+ if (previous) retired.push(previous);
32
+ await get(s).list();
33
+ },
34
+ // Each tool wearing the connection that listed it (`reply`). A tool on
35
+ // another server is a request to that server, not a function this graph
36
+ // holds, and the harness renders the reply whole — artifacts and all — so
37
+ // it asks here rather than through the graph-tool projection. The capture
38
+ // is the point: a call issued from an older listing keeps its original
39
+ // transport even after a refresh replaced the connection.
40
+ tools: async ()=>(await Promise.all(servers.map(async (s)=>{
41
+ try {
42
+ const conn = get(s);
43
+ return (await conn.tools()).map((tool)=>({
44
+ ...tool,
45
+ reply: (args)=>conn.call(String(tool.meta?.remoteName ?? tool.name), args)
46
+ }));
47
+ } catch (error) {
48
+ if (!(error instanceof MCPAuthorizationRequired)) throw error;
49
+ challenges.set(s.name, error.challenge);
50
+ // An unauthenticated optional server must not prevent ordinary conversation.
51
+ // A new connection is made after explicit successful authorization.
52
+ return [];
53
+ }
54
+ }))).flat(),
55
+ close: async ()=>{
56
+ await Promise.all([
57
+ ...connections.values(),
58
+ ...retired
59
+ ].map((c)=>c.close()));
60
+ }
61
+ };
62
+ };
63
+ //# sourceMappingURL=mcp_auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp_auth.js","sources":["./mcp_auth.ts"],"names":[],"mappings":"AAAA;oEACoE,GACpE,SACE,OAAO,EAEP,wBAAwB,gCAEU;AAuBpC,OAAO,MAAM,gBAAgB,CAAC,SAAmB;EAC/C,MAAM,cAAc,IAAI;EACxB,MAAM,aAAa,IAAI;EACvB,MAAM,UAAwB,EAAE;EAChC,MAAM,MAAM,CAAC;IACX,IAAI,IAAI,YAAY,GAAG,CAAC,EAAE,IAAI;IAC9B,IAAI,CAAC,GAAG;MACN,IAAI,QAAQ,GAAG;QAAE,OAAO,UAAY,MAAM,MAAM,MAAM;MAAK;MAC3D,YAAY,GAAG,CAAC,EAAE,IAAI,EAAE;IAC1B;IACA,OAAO;EACT;EACA,O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