@yaks/code-mode 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.
package/source.js ADDED
@@ -0,0 +1,111 @@
1
+ import { fileModule } from "./files.js";
2
+ export let timedOut = (wallMs)=>`execution exceeded ${wallMs / 1000} seconds`;
3
+ /** What each limit says, with what to do instead. */ export let TOO = {
4
+ script: 'script exceeds 64 KiB; read large data with a tool inside the ' + 'script, or split the work across code_mode calls',
5
+ args: 'tool arguments exceed 64 KiB; split the rows across several calls',
6
+ calls: 'execution allows 16 tool calls; write many rows in one call ' + '(graph_apply takes many bundles), or continue in another code_mode call',
7
+ system: 'result exceeds the 32 MiB system safety limit; this is likely an ' + 'accidental result, so narrow the query or calculation'
8
+ };
9
+ /** Where a cell keeps its top-level values, in its storage's kv. */ export let VALUES = '$repl:values';
10
+ // The signature user code runs in, and a cell's two more: its storage and
11
+ // what it carries from the cells before it.
12
+ let signature = (cell)=>`export default async function execute(tools, results, fs, browser${cell ? ', storage, $carried' : ''}) {`;
13
+ /** Where ./repl.ts `carry` declares what a cell carries, before its code. */ export let CARRIED = '/*carried*/';
14
+ /** User code lives in its own module, its TypeScript read as JavaScript by
15
+ * the host's `strip`. The trusted entrypoint loads it inside its catch, with
16
+ * no bindings and no lexical access to the bridge. */ export let source = async (script, entries, most, strip, { wallMs = 30_000, files = false, browser, cell } = {})=>({
17
+ ...files ? {
18
+ 'files.js': fileModule
19
+ } : {},
20
+ ...browser ? {
21
+ 'puppeteer.js': browser
22
+ } : {},
23
+ 'user.js': cell ? `${signature(cell)}\n${CARRIED}\n${body(await strip('user.ts', `${signature(cell)}\n${script}\n}`))}\n}` : await strip('user.ts', `${signature()}\n${script}\n}`),
24
+ 'script.js': `import { ${cell ? 'DurableObject' : 'WorkerEntrypoint'} } from 'cloudflare:workers';
25
+ ${files ? "import { filesystem } from './files.js';" : ''}
26
+ ${browser ? "import puppeteer from './puppeteer.js';" : ''}
27
+ const wait = scheduler.wait.bind(scheduler);
28
+ const race = Promise.race.bind(Promise);
29
+ const stringify = JSON.stringify.bind(JSON);
30
+ const encode = new TextEncoder().encode.bind(new TextEncoder());
31
+ const Controller = AbortController;
32
+ ${cell ? keeping : ''}
33
+ ${cell ? 'export class Cell extends DurableObject {' : 'export default class extends WorkerEntrypoint {'}
34
+ async run(bridge) {
35
+ let timer = new Controller();
36
+ let cancel = timer.abort.bind(timer);
37
+ let deadline = wait(${wallMs}, {signal:timer.signal}).then(() => ({error:${JSON.stringify(timedOut(wallMs))}}));
38
+ let launched = [];${cell ? `
39
+ let kv = this.ctx.storage.kv;
40
+ let carried = {values: kv.get(${JSON.stringify(VALUES)}) ?? {}, capture: null};` : ''}
41
+ try {
42
+ let tools = Object.create(null);
43
+ for (let [set, name] of ${JSON.stringify(entries.map((e)=>e.path))}) {
44
+ tools[set] ??= Object.create(null);
45
+ tools[set][name] = (args) => {
46
+ let text = JSON.stringify(args);
47
+ if (new TextEncoder().encode(text).length > 65536) throw new Error(${JSON.stringify(TOO.args)});
48
+ return bridge.call(set, name, text);
49
+ };
50
+ }
51
+ // A path outside the catalog says which ones exist, rather than a
52
+ // TypeError reading a property of undefined.
53
+ let named = (of, what, list) => new Proxy(of, {
54
+ get(o, k) {
55
+ if (typeof k != 'string' || k in o || k == 'then') return o[k];
56
+ throw new Error(what(k) + list());
57
+ },
58
+ });
59
+ for (let set in tools) {
60
+ tools[set] = named(tools[set], (k) => \`tools.\${set}.\${k} is not a tool; this set has \`, () => Object.keys(tools[set]).join(', '));
61
+ }
62
+ tools = named(tools, (k) => \`tools.\${k} is not a tool set; the sets are \`, () => Object.keys(tools).map((s) => 'tools.' + s).join(', '));
63
+ let work = async () => {
64
+ let {default: execute} = await import('./user.js');
65
+ let value = await execute(tools, {read: (id) => bridge.read(id)}, ${files ? 'filesystem((app, args) => bridge.file(app, args))' : 'undefined'}, ${browser ? `{launch: async (options) => {
66
+ let opened = await puppeteer.launch(this.env.BROWSER, options);
67
+ launched.push(opened);
68
+ return opened;
69
+ }}` : 'undefined'}${cell ? ', {sql: this.ctx.storage.sql, kv}, carried' : ''});
70
+ return {value: value === undefined ? null : value};
71
+ };
72
+ let answer = await race([work(), deadline]);${cell ? '\n Object.assign(answer, keep(kv, carried));' : ''}
73
+ let text = stringify(answer);
74
+ if (encode(text).length > ${most}) throw new Error(${JSON.stringify(TOO.system)});
75
+ return text;
76
+ } catch (error) {
77
+ return stringify({error: String(error?.message ?? error).slice(0,1024)${cell ? ', ...keep(kv, carried)' : ''}});
78
+ } finally {
79
+ cancel();
80
+ await Promise.allSettled(launched.map((opened) => opened.close()));
81
+ }
82
+ }
83
+ }`
84
+ });
85
+ // The body of the function `strip` read, between its signature's line and
86
+ // its closing brace.
87
+ let body = (stripped)=>stripped.slice(stripped.indexOf('{\n') + 2, stripped.lastIndexOf('}'));
88
+ // What a cell keeps of its top-level values once it ends, however it ended:
89
+ // each a structured clone can copy, together in one value so two names for
90
+ // one object stay one object. Each other (a function, a promise, a socket)
91
+ // is dropped, and the answer names it.
92
+ let keeping = `function keep(kv, carried) {
93
+ let values = carried.capture ? carried.capture() : carried.values;
94
+ let kept = {};
95
+ let dropped = [];
96
+ for (let [name, value] of Object.entries(values)) {
97
+ try {
98
+ structuredClone(value);
99
+ kept[name] = value;
100
+ } catch {
101
+ dropped.push(name);
102
+ }
103
+ }
104
+ try {
105
+ kv.put(${JSON.stringify(VALUES)}, kept);
106
+ } catch (error) {
107
+ return {$kept: [], dropped: Object.keys(values), unkept: String(error?.message ?? error).slice(0, 1024)};
108
+ }
109
+ return {$kept: Object.keys(kept), ...dropped.length ? {dropped} : {}};
110
+ }`;
111
+ //# sourceMappingURL=source.js.map
package/source.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.js","sources":["./source.ts"],"names":[],"mappings":"AAEA,SAAS,UAAU,qBAAoB;AAEvC,OAAO,IAAI,WAAW,CAAC,SACrB,CAAC,mBAAmB,EAAE,SAAS,KAAK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AAC,CAAC,IAAM,EAAE,IAAI,GAAG;;;;6EAIE,EACzE,KAAK,SAAS,CAAC,IAAI,IAAI,EACxB;;;;;;;;;;;;;;;;;;0EAkBuE,EACtE,QAAQ,sDAAsD,YAC/D,EAAE,EACD,UACI,CAAC;;;;UAIC,CAAC,GACH,cACH,OAAO,+CAA+C,GAAG;;;kDAGZ,EAC9C,OAAO,sDAAsD,GAC9D;;gCAE6B,EAAE,KAAK,kBAAkB,EACrD,KAAK,SAAS,CAAC,IAAI,MAAM,EAC1B;;;4EAGyE,EACxE,OAAO,2BAA2B,GACnC;;;;;;CAMF,CAAC;EACF,CAAC,EAAC;AAEF,0EAA0E;AAC1E,qBAAqB;AACrB,IAAI,OAAO,CAAC,WACV,SAAS,KAAK,CAAC,SAAS,OAAO,CAAC,SAAS,GAAG,SAAS,WAAW,CAAC;AAEnE,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,uCAAuC;AACvC,IAAI,UAAU,CAAC;;;;;;;;;;;;;WAaJ,EAAE,KAAK,SAAS,CAAC,QAAQ;;;;;CAKnC,CAAC"}
package/source.ts ADDED
@@ -0,0 +1,180 @@
1
+ import type { Strip } from './mod.ts'
2
+ import type { Entry } from './types.ts'
3
+ import { fileModule } from './files.js'
4
+
5
+ export let timedOut = (wallMs: number) =>
6
+ `execution exceeded ${wallMs / 1000} seconds`
7
+
8
+ /** What each limit says, with what to do instead. */
9
+ export let TOO = {
10
+ script: 'script exceeds 64 KiB; read large data with a tool inside the ' +
11
+ 'script, or split the work across code_mode calls',
12
+ args: 'tool arguments exceed 64 KiB; split the rows across several calls',
13
+ calls: 'execution allows 16 tool calls; write many rows in one call ' +
14
+ '(graph_apply takes many bundles), or continue in another code_mode call',
15
+ system: 'result exceeds the 32 MiB system safety limit; this is likely an ' +
16
+ 'accidental result, so narrow the query or calculation',
17
+ }
18
+
19
+ /** What a script is given beside its tools. */
20
+ export type Given = {
21
+ wallMs?: number
22
+ /** `fs`, over /tmp and the app mount */
23
+ files?: boolean
24
+ /** puppeteer's module, as `puppeteer.js`, for a script given `browser`: it
25
+ * launches on the evaluator's `env.BROWSER`, and every browser it launched
26
+ * is closed when the run ends */
27
+ browser?: string
28
+ /** a REPL's cell: the Worker exports `Cell`, a Durable Object class whose
29
+ * storage is the REPL's, and keeps the cell's top-level values there
30
+ * (./repl.ts) */
31
+ cell?: boolean
32
+ }
33
+
34
+ /** Where a cell keeps its top-level values, in its storage's kv. */
35
+ export let VALUES = '$repl:values'
36
+
37
+ // The signature user code runs in, and a cell's two more: its storage and
38
+ // what it carries from the cells before it.
39
+ let signature = (cell?: boolean) =>
40
+ `export default async function execute(tools, results, fs, browser${
41
+ cell ? ', storage, $carried' : ''
42
+ }) {`
43
+ /** Where ./repl.ts `carry` declares what a cell carries, before its code. */
44
+ export let CARRIED = '/*carried*/'
45
+
46
+ /** User code lives in its own module, its TypeScript read as JavaScript by
47
+ * the host's `strip`. The trusted entrypoint loads it inside its catch, with
48
+ * no bindings and no lexical access to the bridge. */
49
+ export let source = async (
50
+ script: string,
51
+ entries: Entry[],
52
+ most: number,
53
+ strip: Strip,
54
+ { wallMs = 30_000, files = false, browser, cell }: Given = {},
55
+ ): Promise<Record<string, string>> => ({
56
+ ...files ? { 'files.js': fileModule } : {},
57
+ ...browser ? { 'puppeteer.js': browser } : {},
58
+ 'user.js': cell
59
+ ? `${signature(cell)}\n${CARRIED}\n${
60
+ body(await strip('user.ts', `${signature(cell)}\n${script}\n}`))
61
+ }\n}`
62
+ : await strip('user.ts', `${signature()}\n${script}\n}`),
63
+ 'script.js': `import { ${
64
+ cell ? 'DurableObject' : 'WorkerEntrypoint'
65
+ } } from 'cloudflare:workers';
66
+ ${files ? "import { filesystem } from './files.js';" : ''}
67
+ ${browser ? "import puppeteer from './puppeteer.js';" : ''}
68
+ const wait = scheduler.wait.bind(scheduler);
69
+ const race = Promise.race.bind(Promise);
70
+ const stringify = JSON.stringify.bind(JSON);
71
+ const encode = new TextEncoder().encode.bind(new TextEncoder());
72
+ const Controller = AbortController;
73
+ ${cell ? keeping : ''}
74
+ ${
75
+ cell
76
+ ? 'export class Cell extends DurableObject {'
77
+ : 'export default class extends WorkerEntrypoint {'
78
+ }
79
+ async run(bridge) {
80
+ let timer = new Controller();
81
+ let cancel = timer.abort.bind(timer);
82
+ let deadline = wait(${wallMs}, {signal:timer.signal}).then(() => ({error:${
83
+ JSON.stringify(timedOut(wallMs))
84
+ }}));
85
+ let launched = [];${
86
+ cell
87
+ ? `
88
+ let kv = this.ctx.storage.kv;
89
+ let carried = {values: kv.get(${
90
+ JSON.stringify(VALUES)
91
+ }) ?? {}, capture: null};`
92
+ : ''
93
+ }
94
+ try {
95
+ let tools = Object.create(null);
96
+ for (let [set, name] of ${JSON.stringify(entries.map((e) => e.path))}) {
97
+ tools[set] ??= Object.create(null);
98
+ tools[set][name] = (args) => {
99
+ let text = JSON.stringify(args);
100
+ if (new TextEncoder().encode(text).length > 65536) throw new Error(${
101
+ JSON.stringify(TOO.args)
102
+ });
103
+ return bridge.call(set, name, text);
104
+ };
105
+ }
106
+ // A path outside the catalog says which ones exist, rather than a
107
+ // TypeError reading a property of undefined.
108
+ let named = (of, what, list) => new Proxy(of, {
109
+ get(o, k) {
110
+ if (typeof k != 'string' || k in o || k == 'then') return o[k];
111
+ throw new Error(what(k) + list());
112
+ },
113
+ });
114
+ for (let set in tools) {
115
+ tools[set] = named(tools[set], (k) => \`tools.\${set}.\${k} is not a tool; this set has \`, () => Object.keys(tools[set]).join(', '));
116
+ }
117
+ tools = named(tools, (k) => \`tools.\${k} is not a tool set; the sets are \`, () => Object.keys(tools).map((s) => 'tools.' + s).join(', '));
118
+ let work = async () => {
119
+ let {default: execute} = await import('./user.js');
120
+ let value = await execute(tools, {read: (id) => bridge.read(id)}, ${
121
+ files ? 'filesystem((app, args) => bridge.file(app, args))' : 'undefined'
122
+ }, ${
123
+ browser
124
+ ? `{launch: async (options) => {
125
+ let opened = await puppeteer.launch(this.env.BROWSER, options);
126
+ launched.push(opened);
127
+ return opened;
128
+ }}`
129
+ : 'undefined'
130
+ }${cell ? ', {sql: this.ctx.storage.sql, kv}, carried' : ''});
131
+ return {value: value === undefined ? null : value};
132
+ };
133
+ let answer = await race([work(), deadline]);${
134
+ cell ? '\n Object.assign(answer, keep(kv, carried));' : ''
135
+ }
136
+ let text = stringify(answer);
137
+ if (encode(text).length > ${most}) throw new Error(${
138
+ JSON.stringify(TOO.system)
139
+ });
140
+ return text;
141
+ } catch (error) {
142
+ return stringify({error: String(error?.message ?? error).slice(0,1024)${
143
+ cell ? ', ...keep(kv, carried)' : ''
144
+ }});
145
+ } finally {
146
+ cancel();
147
+ await Promise.allSettled(launched.map((opened) => opened.close()));
148
+ }
149
+ }
150
+ }`,
151
+ })
152
+
153
+ // The body of the function `strip` read, between its signature's line and
154
+ // its closing brace.
155
+ let body = (stripped: string) =>
156
+ stripped.slice(stripped.indexOf('{\n') + 2, stripped.lastIndexOf('}'))
157
+
158
+ // What a cell keeps of its top-level values once it ends, however it ended:
159
+ // each a structured clone can copy, together in one value so two names for
160
+ // one object stay one object. Each other (a function, a promise, a socket)
161
+ // is dropped, and the answer names it.
162
+ let keeping = `function keep(kv, carried) {
163
+ let values = carried.capture ? carried.capture() : carried.values;
164
+ let kept = {};
165
+ let dropped = [];
166
+ for (let [name, value] of Object.entries(values)) {
167
+ try {
168
+ structuredClone(value);
169
+ kept[name] = value;
170
+ } catch {
171
+ dropped.push(name);
172
+ }
173
+ }
174
+ try {
175
+ kv.put(${JSON.stringify(VALUES)}, kept);
176
+ } catch (error) {
177
+ return {$kept: [], dropped: Object.keys(values), unkept: String(error?.message ?? error).slice(0, 1024)};
178
+ }
179
+ return {$kept: Object.keys(kept), ...dropped.length ? {dropped} : {}};
180
+ }`
package/types.js ADDED
@@ -0,0 +1,62 @@
1
+ import { groupBy } from "@yaks/fp";
2
+ let node = (s)=>s && typeof s == 'object' ? s : {};
3
+ let joined = (s, root, sep, seen)=>s.map((v)=>type(v, root, seen)).join(sep);
4
+ /** JSON Schema expressed as TypeScript, retaining unions, literal values,
5
+ * references, tuples and open object properties. Validation stays at dispatch. */ export let type = (value, root = node(value), seen = [])=>{
6
+ if (value === false) return 'never';
7
+ let s = node(value);
8
+ if (typeof s.$ref == 'string') {
9
+ if (!s.$ref.startsWith('#/') || seen.includes(s.$ref)) return 'unknown';
10
+ let ref = s.$ref.slice(2).split('/').reduce((v, k)=>node(v)[k.replaceAll('~1', '/').replaceAll('~0', '~')], root);
11
+ return type(ref, root, [
12
+ ...seen,
13
+ s.$ref
14
+ ]);
15
+ }
16
+ if ('const' in s) return JSON.stringify(s.const);
17
+ if (Array.isArray(s.enum)) {
18
+ return s.enum.map((v)=>JSON.stringify(v)).join(' | ') || 'never';
19
+ }
20
+ if (s.anyOf || s.oneOf) {
21
+ return `(${joined(s.anyOf ?? s.oneOf, root, ' | ', seen)})`;
22
+ }
23
+ if (s.allOf) return `(${joined(s.allOf, root, ' & ', seen)})`;
24
+ if (Array.isArray(s.type)) {
25
+ return s.type.map((t)=>type({
26
+ ...s,
27
+ type: t
28
+ }, root, seen)).join(' | ');
29
+ }
30
+ if (s.type == 'array') {
31
+ return Array.isArray(s.prefixItems ?? s.items) ? `[${joined(s.prefixItems ?? s.items, root, ', ', seen)}]` : `Array<${type(s.items, root, seen)}>`;
32
+ }
33
+ if (s.type == 'object' || s.properties) {
34
+ let required = new Set(s.required ?? []);
35
+ let props = Object.entries(node(s.properties)).map(([k, v])=>`${JSON.stringify(k)}${required.has(k) ? '' : '?'}: ${type(v, root, seen)}`);
36
+ let closed = s.additionalProperties === false;
37
+ let open = closed ? '' : ` & Record<string, ${type(s.additionalProperties, root, seen)}>`;
38
+ return `{ ${props.join('; ')} }${open}`;
39
+ }
40
+ return ({
41
+ string: 'string',
42
+ number: 'number',
43
+ integer: 'number',
44
+ boolean: 'boolean',
45
+ null: 'null'
46
+ })[String(s.type)] ?? 'unknown';
47
+ };
48
+ /** Names are preserved as object keys, including punctuation; bracket notation
49
+ * gives every registry name one unambiguous path without alias collisions. */ export let catalog = (registry)=>registry.list().map((t)=>registry.describe(t.name)).map((t)=>({
50
+ ...t,
51
+ path: [
52
+ t.provider,
53
+ t.name
54
+ ]
55
+ }));
56
+ /** Declarations are generated from the same schemas that discovery serves. */ export let declarations = (entries)=>{
57
+ let groups = groupBy(entries, (e)=>e.provider);
58
+ return 'declare const tools: {\n' + [
59
+ ...groups
60
+ ].map(([set, entries])=>` ${JSON.stringify(set)}: {\n` + entries.map((t)=>` ${JSON.stringify(t.name)}: (args: ${type(t.inputSchema)}) => Promise<{ content: Array<{type: string; [key: string]: unknown}>; structuredContent?: ${type(t.outputSchema)}; isError?: boolean }>`).join('\n') + '\n }').join('\n') + '\n}';
61
+ };
62
+ //# sourceMappingURL=types.js.map
package/types.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sources":["./types.ts"],"names":[],"mappings":"AAAA,SAAS,OAAO,wBAA6B;AAI7C,IAAI,OAAO,CAAC,IAAuB,KAAK,OAAO,KAAK,WAAW,IAAc,CAAC;AAC9E,IAAI,SAAS,CAAC,GAAY,MAAc,KAAa,OACnD,AAAC,EAAgB,GAAG,CAAC,CAAC,IAAM,KAAK,GAAG,MAAM,OAAO,IAAI,CAAC;AAExD;gFACgF,GAChF,OAAO,IAAI,OAAO,CAChB,OACA,OAAO,KAAK,MAAM,EAClB,OAAiB,EAAE;EAEnB,IAAI,UAAU,OAAO,OAAO;EAC5B,IAAI,IAAI,KAAK;EACb,IAAI,OAAO,EAAE,IAAI,IAAI,UAAU;IAC7B,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,SAAS,KAAK,QAAQ,CAAC,EAAE,IAAI,GAAG,OAAO;IAC9D,IAAI,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,MAAM,CACzC,CAAC,GAAG,IAAM,KAAK,EAAE,CAAC,EAAE,UAAU,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM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@yaks/fp'
2
+ import type { Description, Registry } from 'jsr:@yaks/tools@0.2.36'
3
+
4
+ type Schema = Record<string, unknown>
5
+ let node = (s: unknown): Schema => s && typeof s == 'object' ? s as Schema : {}
6
+ let joined = (s: unknown, root: Schema, sep: string, seen: string[]): string =>
7
+ (s as unknown[]).map((v) => type(v, root, seen)).join(sep)
8
+
9
+ /** JSON Schema expressed as TypeScript, retaining unions, literal values,
10
+ * references, tuples and open object properties. Validation stays at dispatch. */
11
+ export let type = (
12
+ value: unknown,
13
+ root = node(value),
14
+ seen: string[] = [],
15
+ ): string => {
16
+ if (value === false) return 'never'
17
+ let s = node(value)
18
+ if (typeof s.$ref == 'string') {
19
+ if (!s.$ref.startsWith('#/') || seen.includes(s.$ref)) return 'unknown'
20
+ let ref = s.$ref.slice(2).split('/').reduce<unknown>(
21
+ (v, k) => node(v)[k.replaceAll('~1', '/').replaceAll('~0', '~')],
22
+ root,
23
+ )
24
+ return type(ref, root, [...seen, s.$ref])
25
+ }
26
+ if ('const' in s) return JSON.stringify(s.const)
27
+ if (Array.isArray(s.enum)) {
28
+ return s.enum.map((v) => JSON.stringify(v)).join(' | ') || 'never'
29
+ }
30
+ if (s.anyOf || s.oneOf) {
31
+ return `(${joined(s.anyOf ?? s.oneOf, root, ' | ', seen)})`
32
+ }
33
+ if (s.allOf) return `(${joined(s.allOf, root, ' & ', seen)})`
34
+ if (Array.isArray(s.type)) {
35
+ return s.type.map((t) => type({ ...s, type: t }, root, seen)).join(' | ')
36
+ }
37
+ if (s.type == 'array') {
38
+ return Array.isArray(s.prefixItems ?? s.items)
39
+ ? `[${joined(s.prefixItems ?? s.items, root, ', ', seen)}]`
40
+ : `Array<${type(s.items, root, seen)}>`
41
+ }
42
+ if (s.type == 'object' || s.properties) {
43
+ let required = new Set(s.required as string[] ?? [])
44
+ let props = Object.entries(node(s.properties)).map(([k, v]) =>
45
+ `${JSON.stringify(k)}${required.has(k) ? '' : '?'}: ${
46
+ type(v, root, seen)
47
+ }`
48
+ )
49
+ let closed = s.additionalProperties === false
50
+ let open = closed
51
+ ? ''
52
+ : ` & Record<string, ${type(s.additionalProperties, root, seen)}>`
53
+ return `{ ${props.join('; ')} }${open}`
54
+ }
55
+ return ({
56
+ string: 'string',
57
+ number: 'number',
58
+ integer: 'number',
59
+ boolean: 'boolean',
60
+ null: 'null',
61
+ } as Record<string, string>)[String(s.type)] ?? 'unknown'
62
+ }
63
+
64
+ export type Entry = Description & { path: [string, string] }
65
+ /** Names are preserved as object keys, including punctuation; bracket notation
66
+ * gives every registry name one unambiguous path without alias collisions. */
67
+ export let catalog = (registry: Registry): Entry[] =>
68
+ registry.list()
69
+ .map((t) => registry.describe(t.name)!)
70
+ .map((t) => ({ ...t, path: [t.provider, t.name] }))
71
+
72
+ /** Declarations are generated from the same schemas that discovery serves. */
73
+ export let declarations = (entries: Entry[]): string => {
74
+ let groups = groupBy(entries, (e) => e.provider)
75
+ return 'declare const tools: {\n' +
76
+ [...groups].map(([set, entries]) =>
77
+ ` ${JSON.stringify(set)}: {\n` + entries.map((t) =>
78
+ ` ${JSON.stringify(t.name)}: (args: ${
79
+ type(t.inputSchema)
80
+ }) => Promise<{ content: Array<{type: string; [key: string]: unknown}>; structuredContent?: ${
81
+ type(t.outputSchema)
82
+ }; isError?: boolean }>`
83
+ ).join('\n') + '\n }'
84
+ ).join('\n') + '\n}'
85
+ }
package/vocab.js ADDED
@@ -0,0 +1,14 @@
1
+ // The REPL's words, and nothing else: what a store keeping REPLs and their
2
+ // cells imports at `@yaks/code-mode/vocab`.
3
+ import doc from './vocab.json' with {
4
+ type: 'json'
5
+ };
6
+ import manifest from './package.json' with {
7
+ type: 'json'
8
+ };
9
+ /** The code mode vocabulary, in the form `loadVocab` accepts. */ export let codeModeDoc = doc;
10
+ /** What this package is: its manifest's description. */ export let description = manifest.description;
11
+ /** Every document this plugin declares. */ export let docs = [
12
+ codeModeDoc
13
+ ];
14
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4CAA4C;AAE5C,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,+DAA+D,GAC/D,OAAO,IAAI,cAAwB,IAAe;AAElD,sDAAsD,GACtD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAY,CAAA"}
package/vocab.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "$id": "urn:uuid:fa38c4a3-8386-495c-924b-614410fc79ef",
3
+ "$vocabulary": {
4
+ "https://yak.sh/vocab/core": true
5
+ },
6
+ "title": "code mode",
7
+ "kinds": {
8
+ "repl": {
9
+ "$id": "urn:uuid:451d280d-87cd-4a37-94a8-4fe02fd151fc",
10
+ "description": "A REPL on yaks.app: code_mode cells whose top-level values and storage last from one cell to the next until it ends.",
11
+ "examples": [
12
+ {
13
+ "repl": {
14
+ "until": "2026-11-27T19:00:00Z"
15
+ }
16
+ }
17
+ ]
18
+ },
19
+ "cell": {
20
+ "$id": "urn:uuid:e778f3d9-17dd-4268-b268-b1c5111f0b4e",
21
+ "description": "One script run in a REPL, and what it answered.",
22
+ "examples": [
23
+ {
24
+ "cell": {
25
+ "repl": "<repl eid>",
26
+ "script": "let rows = await fs.readFile('/tmp/rows.json', 'utf8')\nreturn rows.length",
27
+ "answer": { "value": 2, "calls": [] }
28
+ }
29
+ }
30
+ ]
31
+ }
32
+ },
33
+ "$defs": {
34
+ "repl": {
35
+ "$id": "urn:uuid:451d280d-87cd-4a37-94a8-4fe02fd151fc",
36
+ "component": true,
37
+ "type": "object",
38
+ "properties": {
39
+ "app": {
40
+ "$id": "urn:uuid:bfd16d67-a577-485a-b313-d892d95a2428",
41
+ "type": "string",
42
+ "death": "keep",
43
+ "description": "the app its cells' connection sentinels and /apps draft default to, by eid; none for a REPL started without one"
44
+ },
45
+ "until": {
46
+ "$id": "urn:uuid:c0462e38-de04-4a94-8fef-8603af188b26",
47
+ "type": "string",
48
+ "format": "date-time",
49
+ "description": "when it ends unless another cell runs: an hour after its last cell. Its values and storage are dropped then."
50
+ }
51
+ },
52
+ "description": "A REPL: code_mode cells run with repl set to its id share their top-level values and `storage`, kept in a Durable Object facet of its own."
53
+ },
54
+ "cell": {
55
+ "$id": "urn:uuid:e778f3d9-17dd-4268-b268-b1c5111f0b4e",
56
+ "component": true,
57
+ "type": "object",
58
+ "properties": {
59
+ "repl": {
60
+ "$id": "urn:uuid:2487f24d-d5c0-4292-8ad1-60ced2656076",
61
+ "type": "string",
62
+ "ref": "repl",
63
+ "death": "cascade",
64
+ "description": "the REPL it ran in"
65
+ },
66
+ "script": {
67
+ "$id": "urn:uuid:9a736f4a-f8cf-41ca-b54e-c9f1b5b13b1a",
68
+ "type": "string",
69
+ "description": "the JavaScript or TypeScript it ran"
70
+ },
71
+ "answer": {
72
+ "$id": "urn:uuid:d7103cc1-0d28-4fda-b420-f1e75273de41",
73
+ "type": "object",
74
+ "description": "what code_mode answered: value, calls, error, and dropped, the top-level names whose values could not be kept"
75
+ }
76
+ },
77
+ "description": "One script run in a REPL, and its answer."
78
+ }
79
+ }
80
+ }
package/vocab.ts ADDED
@@ -0,0 +1,14 @@
1
+ // The REPL's words, and nothing else: what a store keeping REPLs and their
2
+ // cells imports at `@yaks/code-mode/vocab`.
3
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
4
+ import doc from './vocab.json' with { type: 'json' }
5
+ import manifest from './package.json' with { type: 'json' }
6
+
7
+ /** The code mode vocabulary, in the form `loadVocab` accepts. */
8
+ export let codeModeDoc: VocabDoc = doc as VocabDoc
9
+
10
+ /** What this package is: its manifest's description. */
11
+ export let description: string = manifest.description
12
+
13
+ /** Every document this plugin declares. */
14
+ export let docs: VocabDoc[] = [codeModeDoc]