@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/mcp_auth.ts ADDED
@@ -0,0 +1,91 @@
1
+ /** MCP connections that carry the harness's sign-in to each server, and
2
+ * reconnect after one. No authorization input enters a transcript. */
3
+ import {
4
+ connect,
5
+ type Connection,
6
+ MCPAuthorizationRequired,
7
+ type Server,
8
+ } from '@yaks/mcp-client'
9
+ import type { AuthorizationChallenge } from 'jsr:@yaks/mcp-client@0.2.36/oauth'
10
+ import type { Tool } from 'jsr:@yaks/graph@0.2.36'
11
+ import type { CallToolResult } from 'npm:@modelcontextprotocol/sdk@^1.29.0/types'
12
+
13
+ /** A remote tool wearing the connection that listed it: `reply` is that
14
+ * server's own endpoint, recorded, so an issued call never moves to a transport
15
+ * opened after it. */
16
+ export type Remote = Tool & {
17
+ reply: (args: Record<string, unknown>) => Promise<CallToolResult>
18
+ }
19
+
20
+ export type MCPAuthAction = 'list' | 'begin' | 'complete' | 'cancel'
21
+ export type MCPAuthReply = {
22
+ servers?: string[]
23
+ url?: string
24
+ redirectUrl?: string
25
+ message?: string
26
+ }
27
+
28
+ /** The token a server is called with: its sign-in (@yaks/connections), if any. */
29
+ export type Token = (s: Server) => Promise<string | undefined>
30
+
31
+ export const authorizedMCP = (servers: Server[], token: Token) => {
32
+ const connections = new Map<string, Connection>()
33
+ const challenges = new Map<string, AuthorizationChallenge>()
34
+ const retired: Connection[] = []
35
+ const get = (s: Server) => {
36
+ let c = connections.get(s.name)
37
+ if (!c) {
38
+ c = connect(s, { token: async () => await token(s) ?? null })
39
+ connections.set(s.name, c)
40
+ }
41
+ return c
42
+ }
43
+ return {
44
+ /** What the server asked for when it last refused, asking it again. */
45
+ challenge: async (s: Server): Promise<AuthorizationChallenge> => {
46
+ try {
47
+ await get(s).list()
48
+ } catch (error) {
49
+ if (error instanceof MCPAuthorizationRequired) {
50
+ challenges.set(s.name, error.challenge)
51
+ }
52
+ }
53
+ return challenges.get(s.name) ?? {}
54
+ },
55
+ /** A new connection after a sign-in. Already-issued calls keep the old. */
56
+ reconnect: async (s: Server) => {
57
+ const previous = connections.get(s.name)
58
+ connections.delete(s.name)
59
+ if (previous) retired.push(previous)
60
+ await get(s).list()
61
+ },
62
+ // Each tool wearing the connection that listed it (`reply`). A tool on
63
+ // another server is a request to that server, not a function this graph
64
+ // holds, and the harness renders the reply whole — artifacts and all — so
65
+ // it asks here rather than through the graph-tool projection. The capture
66
+ // is the point: a call issued from an older listing keeps its original
67
+ // transport even after a refresh replaced the connection.
68
+ tools: async (): Promise<Remote[]> =>
69
+ (await Promise.all(servers.map(async (s) => {
70
+ try {
71
+ const conn = get(s)
72
+ return (await conn.tools()).map((tool): Remote => ({
73
+ ...tool,
74
+ reply: (args) =>
75
+ conn.call(String(tool.meta?.remoteName ?? tool.name), args),
76
+ }))
77
+ } catch (error) {
78
+ if (!(error instanceof MCPAuthorizationRequired)) throw error
79
+ challenges.set(s.name, error.challenge)
80
+ // An unauthenticated optional server must not prevent ordinary conversation.
81
+ // A new connection is made after explicit successful authorization.
82
+ return []
83
+ }
84
+ }))).flat(),
85
+ close: async () => {
86
+ await Promise.all(
87
+ [...connections.values(), ...retired].map((c) => c.close()),
88
+ )
89
+ },
90
+ }
91
+ }
@@ -0,0 +1,17 @@
1
+ // The harness retains MCP discovery and its terminal control, not provider sign-in.
2
+ import { signins } from "@yaks/connections";
3
+ import { graphMCP } from "./mcp_registry.js";
4
+ export let authorize = (h)=>{
5
+ let signin = signins(h);
6
+ let mcp = graphMCP(h, signin);
7
+ return {
8
+ run: mcp.control,
9
+ signin,
10
+ mcp,
11
+ close: async ()=>{
12
+ signin.cancel();
13
+ await mcp.close();
14
+ }
15
+ };
16
+ };
17
+ //# sourceMappingURL=mcp_authorize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp_authorize.js","sources":["./mcp_authorize.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,SAAS,OAAO,iCAAsC;AACtD,SAAS,QAAQ,4BAA2B;AAG5C,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,SAAS,QAAQ;EACrB,IAAI,MAAM,SAAS,GAAG;EACtB,OAAO;IACL,KAAK,IAAI,OAAO;IAChB;IACA;IACA,OAAO;MACL,OAAO,MAAM;MACb,MAAM,IAAI,KAAK;IACjB;EACF;AACF,EAAC"}
@@ -0,0 +1,18 @@
1
+ // The harness retains MCP discovery and its terminal control, not provider sign-in.
2
+ import { signins } from '@yaks/connections'
3
+ import { graphMCP } from './mcp_registry.js'
4
+ import type { Harness } from './store.ts'
5
+
6
+ export let authorize = (h: Pick<Harness, 'g' | 'vault'>) => {
7
+ let signin = signins(h)
8
+ let mcp = graphMCP(h, signin)
9
+ return {
10
+ run: mcp.control,
11
+ signin,
12
+ mcp,
13
+ close: async () => {
14
+ signin.cancel()
15
+ await mcp.close()
16
+ },
17
+ }
18
+ }
@@ -0,0 +1,178 @@
1
+ /** Graph-owned definitions; runtime handles are refreshed before discovery or
2
+ * authorization. A server's sign-in is a connection it owns (@yaks/connections),
3
+ * through an integration discovered from the server itself. */ import { checkNamespaces, checkToolNames } from "@yaks/mcp-client";
4
+ import { graphToolName, serverOf } from "@yaks/mcp-client/servers";
5
+ import { discover } from "@yaks/mcp-client/oauth";
6
+ import { registered, registration } from "@yaks/connections";
7
+ import { INTEGRATION, integrationEid } from "@yaks/connections/identity";
8
+ import { authorizedMCP } from "./mcp_auth.js";
9
+ import { REDIRECT } from "@yaks/connections";
10
+ export const graphMCP = (h, signin)=>{
11
+ const g = h.g;
12
+ // A server's name is its entity, which owns its sign-in.
13
+ const token = (s)=>signin.key(s.name, s.url);
14
+ const live = new Map();
15
+ // Already-admitted calls retain their original transport. All handles drain at host close.
16
+ const retired = [];
17
+ const errors = new Map();
18
+ let tail = Promise.resolve();
19
+ let closed = false;
20
+ const refresh = ()=>{
21
+ const next = tail.then(async ()=>{
22
+ if (closed) throw new Error('MCP registry is closed');
23
+ const rows = await g.read('.mcp_server&*');
24
+ // Validate the complete configured namespace set before opening transports.
25
+ const valid = rows.flatMap((row)=>{
26
+ try {
27
+ const c = serverOf(row);
28
+ return c ? [
29
+ c.server
30
+ ] : [];
31
+ } catch {
32
+ return [];
33
+ }
34
+ });
35
+ checkNamespaces(valid);
36
+ const wanted = new Set();
37
+ const existing = new Set(rows.map((row)=>row.entity.eid));
38
+ for (const id of errors.keys())if (!existing.has(id)) errors.delete(id);
39
+ for (const row of rows){
40
+ const id = row.entity.eid;
41
+ try {
42
+ const config = serverOf(row);
43
+ if (!config) {
44
+ errors.delete(id);
45
+ continue;
46
+ }
47
+ wanted.add(id);
48
+ const signature = JSON.stringify(config.server);
49
+ const old = live.get(id);
50
+ if (old?.signature === signature) {
51
+ old.label = config.label;
52
+ continue;
53
+ }
54
+ errors.delete(id);
55
+ if (old) {
56
+ signin.cancel(id);
57
+ retired.push(old.handle);
58
+ }
59
+ live.set(id, {
60
+ signature,
61
+ label: config.label,
62
+ server: config.server,
63
+ handle: authorizedMCP([
64
+ config.server
65
+ ], token)
66
+ });
67
+ } catch (e) {
68
+ errors.set(id, e instanceof Error ? e.message : 'Invalid MCP definition');
69
+ }
70
+ }
71
+ for (const [id, old] of live){
72
+ if (!wanted.has(id)) {
73
+ live.delete(id);
74
+ signin.cancel(id);
75
+ retired.push(old.handle);
76
+ }
77
+ }
78
+ });
79
+ tail = next.catch(()=>{});
80
+ return next;
81
+ };
82
+ return {
83
+ refresh,
84
+ tools: async ()=>{
85
+ await refresh();
86
+ const result = (await Promise.all([
87
+ ...live
88
+ ].map(async ([id, item])=>{
89
+ try {
90
+ const tools = await item.handle.tools();
91
+ errors.delete(id);
92
+ return await Promise.all(tools.map(async (tool)=>({
93
+ ...tool,
94
+ name: await graphToolName(id, item.server, String(tool.meta?.remoteName)),
95
+ description: tool.description.replace('[' + id + ']', '[' + item.label + ']')
96
+ })));
97
+ } catch (e) {
98
+ errors.set(id, e instanceof Error ? e.message : 'MCP discovery failed');
99
+ return [];
100
+ }
101
+ }))).flat();
102
+ checkToolNames(result);
103
+ return result;
104
+ },
105
+ control: async (action, name = '', callback = '')=>{
106
+ await refresh();
107
+ if (action === 'list') {
108
+ return {
109
+ servers: [
110
+ ...live
111
+ ].map(([id, item])=>`${item.label} [${id}]`),
112
+ ...errors.size ? {
113
+ message: [
114
+ ...errors
115
+ ].map(([id, error])=>`${id}: ${error}`).join('\n')
116
+ } : {}
117
+ };
118
+ }
119
+ const alias = (await g.address([
120
+ name
121
+ ])).get(name);
122
+ const found = [
123
+ ...live
124
+ ].find(([id, item])=>name === id || alias === id || name === `${item.label} [${id}]`) ?? [
125
+ ...live
126
+ ].filter(([, item])=>item.label === name).filter((_, __, all)=>all.length === 1)[0];
127
+ if (!found) throw new Error('Unknown or ambiguous configured MCP server');
128
+ const [id, { server: s, handle }] = found;
129
+ if (action === 'cancel') {
130
+ signin.cancel(id);
131
+ return {
132
+ message: 'Authorization cancelled.'
133
+ };
134
+ }
135
+ if (action === 'begin') {
136
+ // Where the server signs in, kept as its integration, and the client
137
+ // this harness registered there, kept under the integration's name.
138
+ const redirect = s.oauth?.redirectUrl ?? REDIRECT;
139
+ const { integration, register } = await discover(s.url, {
140
+ ...await handle.challenge(s),
141
+ ...s.oauth?.scope ? {
142
+ scope: s.oauth.scope
143
+ } : {}
144
+ });
145
+ const client = s.oauth?.clientId ?? s.oauth?.clientMetadataUrl ?? (await registered(h.vault, integration.name))?.id ?? await register(redirect);
146
+ await g.apply([
147
+ registration(integration.name, {
148
+ id: client
149
+ }),
150
+ {
151
+ entity: {
152
+ eid: integrationEid(integration.name)
153
+ },
154
+ [INTEGRATION]: {
155
+ ...integration,
156
+ client: integration.name
157
+ }
158
+ }
159
+ ]);
160
+ return await signin.begin(id, s.url, redirect);
161
+ }
162
+ if (action !== 'complete') throw new Error('Unknown authorization action');
163
+ await signin.complete(id, s.url, callback);
164
+ await handle.reconnect(s);
165
+ return {
166
+ message: 'Connected. Tools will be available on the next request.'
167
+ };
168
+ },
169
+ close: async ()=>{
170
+ await tail;
171
+ closed = true;
172
+ await Promise.all([
173
+ ...live.values()
174
+ ].map((v)=>v.handle).concat(retired).map((h)=>h.close()));
175
+ }
176
+ };
177
+ };
178
+ //# sourceMappingURL=mcp_registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp_registry.js","sources":["./mcp_registry.ts"],"names":[],"mappings":"AAAA;;6DAE6D,GAE7D,SAAS,eAAe,EAAE,cAAc,gCAAkD;AAE1F,SAAS,aAAa,EAAE,QAAQ,wCAA6C;AAC7E,SAAS,QAAQ,sCAA2C;AAC5D,SAAS,UAAU,EAAE,YAAY,iCAAsC;AACvE,SAAS,WAAW,EAAE,cAAc,0CAA+C;AACnF,SACE,aAAa,wBAGO;AACtB,SAAS,QAAQ,iCAAoD;AAIrE,OAAO,MAAM,WAAW,CAAC,GAAiC;EACxD,MAAM,IAAI,EAAE,CAAC;EACb,yDAAyD;EACzD,MAAM,QAAQ,CAAC,IAAc,OAAO,GAAG,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG;EACrD,MAAM,OAAO,IAAI;EACjB,2FAA2F;EAC3F,MAAM,UAAoB,EAAE;EAC5B,MAAM,SAAS,IAAI;EACnB,IAAI,OAAO,QAAQ,OAAO;EAC1B,IAAI,SAAS;EACb,MAAM,UAAU;IACd,MAAM,OAAO,KAAK,IAAI,CAAC;MACrB,IAAI,QAAQ,MAAM,IAAI,MAAM;MAC5B,MAAM,OAAO,MAAM,EAAE,IAAI,CAAC;MAC1B,4EAA4E;MAC5E,MAAM,QAAQ,KAAK,OAAO,CAAC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AAW,YAAY,MAAM,IAAI,MAAM;MAC3C,MAAM,OAAO,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE;MACjC,MAAM,OAAO,SAAS,CAAC;MACvB,OAAO;QACL,SAAS;MACX;IACF;IACA,OAAO;MACL,MAAM;MACN,SAAS;MACT,MAAM,QAAQ,GAAG,CACf;WAAI,KAAK,MAAM;OAAG,CAAC,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM,EAAE,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,IAC3D,EAAE,KAAK;IAGb;EACF;AACF,EAAC"}
@@ -0,0 +1,193 @@
1
+ /** Graph-owned definitions; runtime handles are refreshed before discovery or
2
+ * authorization. A server's sign-in is a connection it owns (@yaks/connections),
3
+ * through an integration discovered from the server itself. */
4
+ import type { Harness } from './store.ts'
5
+ import { checkNamespaces, checkToolNames, type Server } from '@yaks/mcp-client'
6
+ import type { Remote } from './mcp_auth.js'
7
+ import { graphToolName, serverOf } from '@yaks/mcp-client/servers'
8
+ import { discover } from '@yaks/mcp-client/oauth'
9
+ import { registered, registration } from '@yaks/connections'
10
+ import { INTEGRATION, integrationEid } from '@yaks/connections/identity'
11
+ import {
12
+ authorizedMCP,
13
+ type MCPAuthAction,
14
+ type MCPAuthReply,
15
+ } from './mcp_auth.js'
16
+ import { REDIRECT, type SignIns } from '@yaks/connections'
17
+
18
+ type Handle = ReturnType<typeof authorizedMCP>
19
+ type Live = { signature: string; label: string; server: Server; handle: Handle }
20
+ export const graphMCP = (h: Pick<Harness, 'g' | 'vault'>, signin: SignIns) => {
21
+ const g = h.g
22
+ // A server's name is its entity, which owns its sign-in.
23
+ const token = (s: Server) => signin.key(s.name, s.url)
24
+ const live = new Map<string, Live>()
25
+ // Already-admitted calls retain their original transport. All handles drain at host close.
26
+ const retired: Handle[] = []
27
+ const errors = new Map<string, string>()
28
+ let tail = Promise.resolve()
29
+ let closed = false
30
+ const refresh = () => {
31
+ const next = tail.then(async () => {
32
+ if (closed) throw new Error('MCP registry is closed')
33
+ const rows = await g.read('.mcp_server&*')
34
+ // Validate the complete configured namespace set before opening transports.
35
+ const valid = rows.flatMap((row) => {
36
+ try {
37
+ const c = serverOf(row)
38
+ return c ? [c.server] : []
39
+ } catch {
40
+ return []
41
+ }
42
+ })
43
+ checkNamespaces(valid)
44
+ const wanted = new Set<string>()
45
+ const existing = new Set(rows.map((row) => row.entity.eid))
46
+ for (const id of errors.keys()) if (!existing.has(id)) errors.delete(id)
47
+ for (const row of rows) {
48
+ const id = row.entity.eid
49
+ try {
50
+ const config = serverOf(row)
51
+ if (!config) {
52
+ errors.delete(id)
53
+ continue
54
+ }
55
+ wanted.add(id)
56
+ const signature = JSON.stringify(config.server)
57
+ const old = live.get(id)
58
+ if (old?.signature === signature) {
59
+ old.label = config.label
60
+ continue
61
+ }
62
+ errors.delete(id)
63
+ if (old) {
64
+ signin.cancel(id)
65
+ retired.push(old.handle)
66
+ }
67
+ live.set(id, {
68
+ signature,
69
+ label: config.label,
70
+ server: config.server,
71
+ handle: authorizedMCP([config.server], token),
72
+ })
73
+ } catch (e) {
74
+ errors.set(
75
+ id,
76
+ e instanceof Error ? e.message : 'Invalid MCP definition',
77
+ )
78
+ }
79
+ }
80
+ for (const [id, old] of live) {
81
+ if (!wanted.has(id)) {
82
+ live.delete(id)
83
+ signin.cancel(id)
84
+ retired.push(old.handle)
85
+ }
86
+ }
87
+ })
88
+ tail = next.catch(() => {})
89
+ return next
90
+ }
91
+ return {
92
+ refresh,
93
+ tools: async (): Promise<Remote[]> => {
94
+ await refresh()
95
+ const result = (await Promise.all([...live].map(async ([id, item]) => {
96
+ try {
97
+ const tools = await item.handle.tools()
98
+ errors.delete(id)
99
+ return await Promise.all(tools.map(async (tool) => ({
100
+ ...tool,
101
+ name: await graphToolName(
102
+ id,
103
+ item.server,
104
+ String(tool.meta?.remoteName),
105
+ ),
106
+ description: tool.description.replace(
107
+ '[' + id + ']',
108
+ '[' + item.label + ']',
109
+ ),
110
+ })))
111
+ } catch (e) {
112
+ errors.set(
113
+ id,
114
+ e instanceof Error ? e.message : 'MCP discovery failed',
115
+ )
116
+ return []
117
+ }
118
+ }))).flat()
119
+ checkToolNames(result)
120
+ return result
121
+ },
122
+ control: async (
123
+ action: MCPAuthAction,
124
+ name = '',
125
+ callback = '',
126
+ ): Promise<MCPAuthReply> => {
127
+ await refresh()
128
+ if (action === 'list') {
129
+ return {
130
+ servers: [...live].map(([id, item]) => `${item.label} [${id}]`),
131
+ ...(errors.size
132
+ ? {
133
+ message: [...errors].map(([id, error]) => `${id}: ${error}`).join(
134
+ '\n',
135
+ ),
136
+ }
137
+ : {}),
138
+ }
139
+ }
140
+ const alias = (await g.address([name])).get(name)
141
+ const found =
142
+ [...live].find(([id, item]) =>
143
+ name === id || alias === id || name === `${item.label} [${id}]`
144
+ ) ??
145
+ [...live].filter(([, item]) => item.label === name).filter((
146
+ _,
147
+ __,
148
+ all,
149
+ ) => all.length === 1)[0]
150
+ if (!found) throw new Error('Unknown or ambiguous configured MCP server')
151
+ const [id, { server: s, handle }] = found
152
+ if (action === 'cancel') {
153
+ signin.cancel(id)
154
+ return { message: 'Authorization cancelled.' }
155
+ }
156
+ if (action === 'begin') {
157
+ // Where the server signs in, kept as its integration, and the client
158
+ // this harness registered there, kept under the integration's name.
159
+ const redirect = s.oauth?.redirectUrl ?? REDIRECT
160
+ const { integration, register } = await discover(s.url, {
161
+ ...await handle.challenge(s),
162
+ ...s.oauth?.scope ? { scope: s.oauth.scope } : {},
163
+ })
164
+ const client = s.oauth?.clientId ?? s.oauth?.clientMetadataUrl ??
165
+ (await registered(h.vault, integration.name))?.id ??
166
+ await register(redirect)
167
+ await g.apply([
168
+ registration(integration.name, { id: client }),
169
+ {
170
+ entity: { eid: integrationEid(integration.name) },
171
+ [INTEGRATION]: { ...integration, client: integration.name },
172
+ },
173
+ ])
174
+ return await signin.begin(id, s.url, redirect)
175
+ }
176
+ if (action !== 'complete') throw new Error('Unknown authorization action')
177
+ await signin.complete(id, s.url, callback)
178
+ await handle.reconnect(s)
179
+ return {
180
+ message: 'Connected. Tools will be available on the next request.',
181
+ }
182
+ },
183
+ close: async () => {
184
+ await tail
185
+ closed = true
186
+ await Promise.all(
187
+ [...live.values()].map((v) => v.handle).concat(retired).map((h) =>
188
+ h.close()
189
+ ),
190
+ )
191
+ },
192
+ }
193
+ }
package/mod.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @yaks/harness — an agent runner over a graph, and the host that runs it on
3
+ * this machine.
4
+ *
5
+ * A session in the fleet is a transcript in the live graph, run by whichever
6
+ * process works its effects. The harness is the same session with the server
7
+ * removed: the {@link agent} loop over any graph, written in bundles and read
8
+ * in queries, so the same rows run on a box, in a Cloudflare Worker, or move
9
+ * into the fleet's graph with no export step. It composes existing packages
10
+ * rather than adding machinery —
11
+ *
12
+ * ```
13
+ * agent() the seed rows, the runner lent (@yaks/session), and the
14
+ * operations a caller needs (./agent.ts)
15
+ * local() agent() here, over a graph a config composed: the shell, a
16
+ * workspace and sandbox bindings, MCP servers, the terminal
17
+ * (@yaks/harness/local)
18
+ * tools its verbs, as `yak` tools (./runs.ts)
19
+ * effects `session_run`, lent providers, where a `yak` host
20
+ * lists the harness (./effects.ts)
21
+ * ```
22
+ *
23
+ * This door is the runner alone, and type-checks with only the web platform in
24
+ * scope; nothing it imports names a machine.
25
+ *
26
+ * ```ts ignore
27
+ * import { agent } from '@yaks/harness'
28
+ *
29
+ * let a = agent({ h: { g, fx, vocab, me }, model: fake })
30
+ * let s = await a.start('reply with the word pong')
31
+ * await a.idle(s)
32
+ * for (let e of await a.transcript(s)) console.log(a.line(e))
33
+ * ```
34
+ *
35
+ * On a command line the harness is a `yak` plugin: `yak session new`,
36
+ * `yak session send` and `yak model list` are its tools (./runs.ts), and
37
+ * `--tui` draws a session as its terminal app (./view.ts).
38
+ *
39
+ * @module
40
+ */ export * from "./agent.js";
41
+ export { defaultUsing, HARNESS, usingFor } from "./default.js";
42
+ export { selectedUsing } from "./model_selection.js";
43
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,2BAA0B;AAE1B,SAAS,YAAY,EAAE,OAAO,EAAE,QAAQ,uBAAsB;AAC9D,SAAS,aAAa,+BAA8B"}
package/mod.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @yaks/harness — an agent runner over a graph, and the host that runs it on
3
+ * this machine.
4
+ *
5
+ * A session in the fleet is a transcript in the live graph, run by whichever
6
+ * process works its effects. The harness is the same session with the server
7
+ * removed: the {@link agent} loop over any graph, written in bundles and read
8
+ * in queries, so the same rows run on a box, in a Cloudflare Worker, or move
9
+ * into the fleet's graph with no export step. It composes existing packages
10
+ * rather than adding machinery —
11
+ *
12
+ * ```
13
+ * agent() the seed rows, the runner lent (@yaks/session), and the
14
+ * operations a caller needs (./agent.ts)
15
+ * local() agent() here, over a graph a config composed: the shell, a
16
+ * workspace and sandbox bindings, MCP servers, the terminal
17
+ * (@yaks/harness/local)
18
+ * tools its verbs, as `yak` tools (./runs.ts)
19
+ * effects `session_run`, lent providers, where a `yak` host
20
+ * lists the harness (./effects.ts)
21
+ * ```
22
+ *
23
+ * This door is the runner alone, and type-checks with only the web platform in
24
+ * scope; nothing it imports names a machine.
25
+ *
26
+ * ```ts ignore
27
+ * import { agent } from '@yaks/harness'
28
+ *
29
+ * let a = agent({ h: { g, fx, vocab, me }, model: fake })
30
+ * let s = await a.start('reply with the word pong')
31
+ * await a.idle(s)
32
+ * for (let e of await a.transcript(s)) console.log(a.line(e))
33
+ * ```
34
+ *
35
+ * On a command line the harness is a `yak` plugin: `yak session new`,
36
+ * `yak session send` and `yak model list` are its tools (./runs.ts), and
37
+ * `--tui` draws a session as its terminal app (./view.ts).
38
+ *
39
+ * @module
40
+ */
41
+
42
+ export * from './agent.js'
43
+
44
+ export { defaultUsing, HARNESS, usingFor } from './default.js'
45
+ export { selectedUsing } from './model_selection.js'
@@ -0,0 +1,72 @@
1
+ /** Model choices are graph records: a choice is one provider's offering of a
2
+ * model, its `serves` edge. */ import { line, sub } from "@yaks/query";
3
+ import { edgeEid } from "@yaks/edge";
4
+ import { offerFor, offers } from "@yaks/model";
5
+ /** The `using` a choice records. `id` is an offering (a `serves` edge), which
6
+ * names the provider as well, or a model, whose provider is resolved from the
7
+ * offerings this host can reach. A configured provider is never refused here,
8
+ * and an unconfigured one fails before it is recorded. */ export const modelUsing = async (g, id, implementations)=>{
9
+ const [row] = await g.get([
10
+ id
11
+ ]);
12
+ const edge = row?.serves ? row.edge : undefined;
13
+ const model = edge ? String(edge.to) : row?.model ? id : undefined;
14
+ if (!model) throw new Error('Unknown model');
15
+ const found = offerFor(await offers(g, model, implementations), edge?.from);
16
+ if (typeof found == 'string') throw new Error(found);
17
+ return {
18
+ model,
19
+ provider: found.provider
20
+ };
21
+ };
22
+ /** Read configuration metadata only, following a fork's bounded prefix. */ export const selectedUsing = async (g, session, before, seen = new Set())=>{
23
+ if (seen.has(session)) throw new Error('Cyclic session ancestry');
24
+ seen.add(session);
25
+ const rows = await g.read(line`.entry.session=${session}&.using&!ask${sub(before == null ? line`` : line`&.entry.seq<=${before}`)}&.order=-entry.seq&.limit=1&.fields=using.model,using.provider,using.effort`);
26
+ if (rows.length) return rows[0].using;
27
+ const [owner] = await g.get([
28
+ session
29
+ ], [
30
+ 'using',
31
+ 'fork'
32
+ ]);
33
+ if (owner?.using) return owner.using;
34
+ const from = owner?.fork?.from;
35
+ if (!from) return undefined;
36
+ const [anchor] = await g.get([
37
+ String(from)
38
+ ]);
39
+ const entry = anchor?.entry;
40
+ return entry ? selectedUsing(g, String(entry.session), Number(entry.seq), seen) : undefined;
41
+ };
42
+ /** Every offering, each as its edge's id wearing the model and the provider's
43
+ * name, and the one in force: the session's, else `fallback`. */ export const modelSelection = async (g, session, fallback)=>{
44
+ const named = new Map([
45
+ ...await g.read('.provider'),
46
+ ...await g.read('.model')
47
+ ].map((b)=>[
48
+ b.entity.eid,
49
+ b
50
+ ]));
51
+ const choices = (await g.read('.serves&?edge')).flatMap((b)=>{
52
+ const { from, to } = b.edge;
53
+ const model = named.get(String(to))?.model;
54
+ const provider = named.get(String(from))?.provider;
55
+ return model && provider ? [
56
+ {
57
+ entity: b.entity,
58
+ edge: b.edge,
59
+ serves: b.serves,
60
+ model,
61
+ provider
62
+ }
63
+ ] : [];
64
+ }).sort((a, b)=>String(a.model.name).localeCompare(String(b.model.name)));
65
+ const using = (session ? await selectedUsing(g, session) : undefined) ?? fallback;
66
+ const current = using.provider ? edgeEid(String(using.provider), 'serves', String(using.model)) : choices.find((c)=>c.edge.to == using.model)?.entity.eid;
67
+ return {
68
+ choices,
69
+ current
70
+ };
71
+ };
72
+ //# sourceMappingURL=model_selection.js.map