@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/mod.ts ADDED
@@ -0,0 +1,576 @@
1
+ /** Short, isolated code executions over a caller's scoped registry. The host
2
+ * supplies an evaluator and reads a script's TypeScript as JavaScript; this
3
+ * package owns discovery, limits and the bridge. */
4
+ import { argsOf, type Bundle, mint, type Tool, who } from '@yaks/graph'
5
+ import { toolName } from '@yaks/graph/call'
6
+ import { system } from '@yaks/fp'
7
+ import {
8
+ answerOf,
9
+ CallError,
10
+ faulted,
11
+ heard,
12
+ type Opts,
13
+ type Provider,
14
+ refusalOf,
15
+ type Registry,
16
+ type Runner,
17
+ structured,
18
+ texts,
19
+ toolEid,
20
+ valueIn,
21
+ } from '@yaks/tools'
22
+ import { catalog, declarations } from './types.js'
23
+ import { described } from './repl.js'
24
+ import { source, timedOut, TOO } from './source.js'
25
+ import {
26
+ browserDeclarations,
27
+ FILE_BYTES,
28
+ fileDeclarations,
29
+ type FileScope,
30
+ } from './files.js'
31
+ export { catalog, declarations, type Entry } from './types.js'
32
+ export { TOO } from './source.js'
33
+ export { FILE_BYTES } from './files.js'
34
+
35
+ export let LIMITS = {
36
+ wallMs: 30_000,
37
+ cpuMs: 100,
38
+ memoryMiB: 128,
39
+ calls: 16,
40
+ systemBytes: 33_554_432,
41
+ scriptBytes: 65_536,
42
+ }
43
+ export let HOSTED_LIMITS = {
44
+ ...LIMITS,
45
+ wallMs: 120_000,
46
+ cpuMs: 30_000,
47
+ calls: 64,
48
+ }
49
+ export type Result = {
50
+ content: { type: 'text'; text: string }[]
51
+ structuredContent?: Record<string, unknown>
52
+ isError?: boolean
53
+ }
54
+ /** One nested call as the answer reports it: the script holds its result,
55
+ * and only a failure's words come back, so the model reads what the script
56
+ * returns rather than every row a read handed the sandbox. */
57
+ export type Receipt = {
58
+ id: string
59
+ path: [string, string]
60
+ isError?: boolean
61
+ error?: string
62
+ pending?: boolean
63
+ /** the tool or `Options.hears` marked the answer `heard` */
64
+ heard?: true
65
+ }
66
+ export type Answer = {
67
+ value: unknown
68
+ calls: Receipt[]
69
+ error?: string
70
+ /** the REPL the cell ran in */
71
+ repl?: string
72
+ /** the cell's top-level names whose values could not be kept */
73
+ dropped?: string[]
74
+ }
75
+ /** A nested call as an execution's `timed` hears it: its id, its tool, and
76
+ * when its tool's run began and how long it took, on the execution's clock. */
77
+ export type Called = { id: string; name: string; at: number; ms: number }
78
+ /** Hears where an execution's time went. */
79
+ export type Timed = {
80
+ /** A stage of the execution, in milliseconds: `compile` (its script read
81
+ * into modules), `reach` (finding the runner each nested call reaches),
82
+ * `calls` (the time at least one nested call was running) and, for a
83
+ * script given `browser`, `browser` (the rest of its run, which drives the
84
+ * pages it opens). */
85
+ stage(name: string, ms: number): void
86
+ /** Each nested call that reached its tool, once its run ends. */
87
+ call(call: Called): void
88
+ }
89
+ /** The host admits reads of results kept by its model-facing harness. */
90
+ export type Kept = {
91
+ keep(value: unknown, source: Bundle): Promise<unknown>
92
+ read(id: string): Promise<unknown>
93
+ }
94
+ export type Evaluate = (
95
+ modules: Record<string, string>,
96
+ bridge: {
97
+ call(set: string, name: string, args: string): Promise<Result>
98
+ read(id: string): Promise<unknown>
99
+ file?(app: string, args: string): Promise<Result>
100
+ },
101
+ signal: AbortSignal,
102
+ ) => Promise<string>
103
+ /** How the host reads a module's TypeScript as JavaScript, by its path.
104
+ * Throws a SyntaxError where the source does not parse. */
105
+ export type Strip = (path: string, source: string) => string | Promise<string>
106
+ let bytes = (v: unknown) => new TextEncoder().encode(JSON.stringify(v)).length
107
+ let message = (e: unknown) =>
108
+ (e instanceof Error ? e.message : String(e)).slice(0, 1024)
109
+ let finished = (
110
+ value: unknown,
111
+ calls: Receipt[],
112
+ error?: string,
113
+ more: Pick<Answer, 'repl' | 'dropped'> = {},
114
+ ): Answer => {
115
+ if (bytes(value) > LIMITS.systemBytes) {
116
+ throw new CallError('limit', TOO.system)
117
+ }
118
+ let out: Answer = {
119
+ value,
120
+ calls: structuredClone(calls),
121
+ ...(error ? { error } : {}),
122
+ ...more,
123
+ }
124
+ return out
125
+ }
126
+ /** What an execution is given beside its script, tools and evaluator. A
127
+ * runner's `clock`, `report` and `refused` mean here what they mean to it:
128
+ * what the bridge refuses itself (a tool outside the scope, a limit,
129
+ * arguments that are not an object, a call after the execution ended) is
130
+ * heard by `refused` with the nested call it refused, as a runner hears its
131
+ * own refusals. */
132
+ export type Options = Pick<Opts, 'clock' | 'report' | 'refused'> & {
133
+ /** The app mount's tool arguments, scoped by the host. */
134
+ files?: FileScope
135
+ /** puppeteer's module, read only for a script that names `browser`, which
136
+ * launches a browser on the evaluator's `env.BROWSER` */
137
+ browser?: () => Promise<string>
138
+ /** the REPL this execution is a cell of: its top-level values and its
139
+ * `storage` last from cell to cell (./repl.ts) */
140
+ repl?: string
141
+ /** Execution limits advertised by this host. */
142
+ limits?: typeof LIMITS
143
+ /** the runner each nested call reaches, asked once for each file app and
144
+ * again after a call that may write, since a write can change what the
145
+ * caller reaches (default: the execution's `run`) */
146
+ current?: (fileApp?: string) => Promise<Pick<Runner, 'admit'>>
147
+ /** Record a nested call's possible effects before dispatching it. */
148
+ beforeCall?: (set: string, tool: Tool) => Promise<void> | undefined
149
+ /** the results the host's harness kept, read by `results.read` */
150
+ kept?: Kept
151
+ /** whether the caller hears in a nested call's answer words it cannot
152
+ * vouch for, by the rule its direct calls take: its receipt says `heard`,
153
+ * and so does the execution's answer, as a direct call's result would */
154
+ hears?: (tool: Tool, answer: Bundle[]) => Promise<boolean>
155
+ /** hears where the execution's time went */
156
+ timed?: Timed
157
+ }
158
+ let said = (r: Result) => r.content.map((c) => c.text).join('\n').slice(0, 1024)
159
+
160
+ /** All nested calls use admitted registry implementations, the outer caller's
161
+ * stamps and the ordinary runner. Arguments cannot select an actor or session. */
162
+ export let execute = async (
163
+ script: string,
164
+ registry: Registry,
165
+ run: Runner,
166
+ asked: Bundle,
167
+ evaluate: Evaluate,
168
+ strip: Strip,
169
+ opts: Options = {},
170
+ ): Promise<Answer> => {
171
+ let {
172
+ clock = system,
173
+ current = () => Promise.resolve(run),
174
+ kept,
175
+ limits = LIMITS,
176
+ files,
177
+ } = opts
178
+ let repl = opts.repl ? { repl: opts.repl } : {}
179
+ let now = () => clock.now()
180
+ // The time spent finding nested calls' runners, and the time any nested
181
+ // call was running: parallel calls overlap, so it is the span they cover.
182
+ let reaching = 0, running = 0, busy = 0, since = 0
183
+ // The runner by file app, kept until a call that may write ends.
184
+ let runners = new Map<string | undefined, Promise<Pick<Runner, 'admit'>>>()
185
+ let runnerFor = (app?: string) => {
186
+ let live = runners.get(app)
187
+ if (live) return live
188
+ live = current(app)
189
+ runners.set(app, live)
190
+ live.catch(() => runners.get(app) == live && runners.delete(app))
191
+ return live
192
+ }
193
+ let timedRun = async <T>(
194
+ id: string,
195
+ name: string,
196
+ work: () => Promise<T>,
197
+ ) => {
198
+ let at = now()
199
+ if (!busy++) since = at
200
+ try {
201
+ return await work()
202
+ } finally {
203
+ let end = now()
204
+ if (!--busy) running += end - since
205
+ opts.timed?.call({ id, name, at, ms: end - at })
206
+ }
207
+ }
208
+ if (
209
+ script.length > LIMITS.scriptBytes || bytes(script) > LIMITS.scriptBytes
210
+ ) {
211
+ throw new CallError('limit', TOO.script)
212
+ }
213
+ let entries = catalog(registry).filter((e) => e.name != 'code_mode')
214
+ let allowed = new Map(entries.map((e) => [JSON.stringify(e.path), e]))
215
+ let calls: Receipt[] = []
216
+ let pending = new Set<Promise<unknown>>()
217
+ let controller = new AbortController()
218
+ let active = true
219
+ let actor = who(asked)
220
+ // A nested call as the runner records it. Its id is minted before the
221
+ // bridge's first check, so whether the bridge refuses it or the runner
222
+ // does, it is heard under the one id the call keeps throughout.
223
+ let nested = (id: string, name?: string, args?: unknown): Bundle => ({
224
+ entity: { eid: id },
225
+ call: {
226
+ ...(name ? { to: toolEid(name) } : {}),
227
+ ...(args === undefined ? {} : { args }),
228
+ source: asked.entity.eid,
229
+ },
230
+ ...(actor ? { $actor: actor } : {}),
231
+ })
232
+ let hear = async (e: unknown, call: Bundle, tool?: string) => {
233
+ let refusal = refusalOf(e)
234
+ if (refusal) await heard(opts, refusal, call, tool)
235
+ }
236
+ let read = async (id: string): Promise<unknown> => {
237
+ try {
238
+ if (!active) throw new CallError('expired', 'execution has ended')
239
+ if (typeof id != 'string' || !id || id.length > 256) {
240
+ throw new CallError('args', 'results.read takes a result id')
241
+ }
242
+ if (!kept) throw new CallError('result', 'kept results are unavailable')
243
+ let value = await kept.read(id)
244
+ if (bytes(value) > LIMITS.systemBytes) {
245
+ throw new CallError('limit', TOO.system)
246
+ }
247
+ if (!active) throw new CallError('expired', 'execution has ended')
248
+ return value
249
+ } catch (e) {
250
+ await hear(e, nested(mint()), 'results.read')
251
+ throw e
252
+ }
253
+ }
254
+ let call = async (
255
+ set: string,
256
+ name: string,
257
+ args: string,
258
+ app?: string,
259
+ ): Promise<Result> => {
260
+ let id = mint()
261
+ let named = typeof name == 'string' ? name : undefined
262
+ let input: unknown
263
+ let receipt: Receipt | undefined
264
+ let work: Promise<Result> | undefined
265
+ try {
266
+ if (!active) throw new CallError('expired', 'execution has ended')
267
+ if (
268
+ typeof set != 'string' || typeof name != 'string' ||
269
+ typeof args != 'string'
270
+ ) throw new CallError('args', 'bridge takes JSON text')
271
+ let most = app === undefined
272
+ ? LIMITS.scriptBytes
273
+ : Math.ceil(FILE_BYTES / 3) * 4 + LIMITS.scriptBytes
274
+ if (args.length > most || new TextEncoder().encode(args).length > most) {
275
+ throw new CallError(
276
+ 'limit',
277
+ app === undefined
278
+ ? TOO.args
279
+ : 'app files are limited to 1 MiB per fs write',
280
+ )
281
+ }
282
+ try {
283
+ input = JSON.parse(args)
284
+ } catch {
285
+ throw new CallError('args', 'tool arguments must be JSON')
286
+ }
287
+ // A refusal names the tool the script asked for, as `tools[set][name]`
288
+ // spells it, so its words say which call was refused.
289
+ let path = `${set}.${name}`
290
+ if (!allowed.has(JSON.stringify([set, name]))) {
291
+ throw new CallError(
292
+ 'tool',
293
+ `tool ${path} is outside this execution scope`,
294
+ )
295
+ }
296
+ if (calls.length >= limits.calls) {
297
+ throw new CallError(
298
+ 'limit',
299
+ TOO.calls.replace('16', String(limits.calls)),
300
+ )
301
+ }
302
+ if (!input || typeof input != 'object' || Array.isArray(input)) {
303
+ throw new CallError('args', 'tool arguments must be an object')
304
+ }
305
+ if (app !== undefined) {
306
+ let { op, path, base64, encoding } = input as Record<string, unknown>
307
+ input = {
308
+ op,
309
+ ...path === undefined ? {} : { path },
310
+ ...base64 === undefined ? {} : { base64 },
311
+ ...encoding === undefined ? {} : { encoding },
312
+ app,
313
+ ...files?.space ? { space: files.space } : {},
314
+ ...files?.app == app && files?.draft ? { draft: files.draft } : {},
315
+ }
316
+ }
317
+ let made: Receipt = { id, path: [set, name], pending: true }
318
+ receipt = made
319
+ calls.push(made)
320
+ work = (async (): Promise<Result> => {
321
+ let reached = now()
322
+ let live = await runnerFor(app)
323
+ reaching += now() - reached
324
+ if (!active) throw new CallError('expired', 'execution has ended')
325
+ let admitted = live.admit(nested(id, name, input))
326
+ if (!admitted || admitted.tool.name != name) {
327
+ throw new CallError('tool', `tool ${path} is no longer available`)
328
+ }
329
+ await admitted.ensure()
330
+ await opts.beforeCall?.(set, admitted.tool)
331
+ if (!active) throw new CallError('expired', 'execution has ended')
332
+ let landed = await timedRun(id, name, () => admitted.call())
333
+ .finally(() => admitted.tool.readOnly || runners.clear())
334
+ let answer = answerOf(landed, id)
335
+ let failed = faulted(landed, id)
336
+ let result: Result = {
337
+ content: texts(answer, Infinity).map((text) => ({
338
+ type: 'text',
339
+ text,
340
+ })),
341
+ ...(!failed || !admitted.tool.outputSchema
342
+ ? {
343
+ structuredContent: app !== undefined
344
+ ? valueIn(answer)
345
+ : structured(admitted.tool, answer),
346
+ }
347
+ : {}),
348
+ ...(failed ? { isError: true } : {}),
349
+ }
350
+ if (bytes(result) > LIMITS.systemBytes) {
351
+ throw new CallError('limit', TOO.system)
352
+ }
353
+ if (
354
+ answer.some((b) => b.heard) ||
355
+ !failed && await opts.hears?.(admitted.tool, answer)
356
+ ) {
357
+ made.heard = true
358
+ }
359
+ if (failed) Object.assign(made, { isError: true, error: said(result) })
360
+ return result
361
+ })()
362
+ pending.add(work)
363
+ return await work
364
+ } catch (e) {
365
+ if (receipt) receipt.error = message(e)
366
+ await hear(e, nested(id, named, input), named)
367
+ throw e
368
+ } finally {
369
+ if (receipt) delete receipt.pending
370
+ if (work) pending.delete(work)
371
+ }
372
+ }
373
+ let cancel = () => {}
374
+ let timeout = new Promise<never>((_, reject) => {
375
+ cancel = clock.after(limits.wallMs, () => {
376
+ active = false
377
+ controller.abort()
378
+ reject(new CallError('timeout', timedOut(limits.wallMs)))
379
+ })
380
+ })
381
+ let compiling = now()
382
+ let browses = false, evaluating = 0, evaluated = 0
383
+ try {
384
+ let text = await Promise.race([
385
+ (async () =>
386
+ source(script, entries, LIMITS.systemBytes, strip, {
387
+ wallMs: limits.wallMs,
388
+ files: !!files,
389
+ browser: opts.browser && /\bbrowser\b/.test(script)
390
+ ? await opts.browser()
391
+ : undefined,
392
+ cell: !!opts.repl,
393
+ }))()
394
+ .then((modules) => opts.repl ? described(modules) : modules)
395
+ .then((modules) => {
396
+ opts.timed?.stage('compile', now() - compiling)
397
+ controller.signal.throwIfAborted()
398
+ browses = 'puppeteer.js' in modules
399
+ evaluating = now()
400
+ return evaluate(modules, {
401
+ call: (set, name, args) => call(set, name, args),
402
+ read,
403
+ ...files
404
+ ? { file: (app, args) => call('yaks', 'app_files', args, app) }
405
+ : {},
406
+ }, controller.signal).finally(() => evaluated = now())
407
+ }),
408
+ timeout,
409
+ ])
410
+ active = false
411
+ await Promise.race([Promise.allSettled([...pending]), timeout])
412
+ if (
413
+ typeof text != 'string' || text.length > LIMITS.systemBytes ||
414
+ new TextEncoder().encode(text).length > LIMITS.systemBytes
415
+ ) throw new CallError('limit', TOO.system)
416
+ let answer = JSON.parse(text)
417
+ let error = typeof answer.unkept == 'string'
418
+ ? `the cell's values could not be kept: ${answer.unkept}`
419
+ : answer.error
420
+ return await finished(
421
+ answer.value ?? null,
422
+ calls,
423
+ typeof error == 'string' ? error.slice(0, 1024) : undefined,
424
+ {
425
+ ...repl,
426
+ ...Array.isArray(answer.dropped) && answer.dropped.length
427
+ ? { dropped: answer.dropped.map(String) }
428
+ : {},
429
+ },
430
+ )
431
+ } catch (e) {
432
+ return await finished(null, calls, message(e), repl)
433
+ } finally {
434
+ active = false
435
+ controller.abort()
436
+ cancel()
437
+ if (busy) running += now() - since
438
+ opts.timed?.stage('reach', reaching)
439
+ opts.timed?.stage('calls', running)
440
+ if (browses) {
441
+ let ran = (evaluated || now()) - evaluating
442
+ opts.timed?.stage('browser', Math.max(0, ran - running))
443
+ }
444
+ }
445
+ }
446
+
447
+ let pathsOf = (providers: readonly Provider[]): string => {
448
+ let names = providers.filter(({ tools }) =>
449
+ tools.some((t) => toolName(t) != 'code_mode')
450
+ ).map(({ name }) => name)
451
+ return names.length
452
+ ? names.map((n) => `tools.${n}.<name>(args)`).join(' or ') +
453
+ ' (the set each tool is in, never another name)'
454
+ : 'tools[set][name](args)'
455
+ }
456
+
457
+ /** How a script names a tool, by the sets it will see. */
458
+ export let sets = (registry: Registry): string => pathsOf(registry.providers())
459
+
460
+ let fields = {
461
+ name: 'code_mode',
462
+ title: 'Run code',
463
+ step: {
464
+ doing: 'Working through several steps…',
465
+ done: 'Worked through several steps',
466
+ },
467
+ inputSchema: {
468
+ type: 'object',
469
+ properties: {
470
+ script: { type: 'string' },
471
+ search: { type: 'string' },
472
+ offset: { type: 'integer', minimum: 0 },
473
+ limit: { type: 'integer', minimum: 1, maximum: 20 },
474
+ },
475
+ additionalProperties: false,
476
+ },
477
+ outputSchema: {
478
+ type: 'object',
479
+ properties: {
480
+ value: {},
481
+ calls: { type: 'array', items: { type: 'object' } },
482
+ error: { type: 'string' },
483
+ declarations: { type: 'string' },
484
+ tools: { type: 'array', items: { type: 'object' } },
485
+ limits: { type: 'object' },
486
+ next: { type: ['integer', 'null'] },
487
+ result_handle: { type: 'string' },
488
+ },
489
+ },
490
+ applied: true,
491
+ destructive: true,
492
+ openWorld: true,
493
+ }
494
+
495
+ type Definition = Omit<Tool, 'run' | 'inputSchema'> & {
496
+ inputSchema: NonNullable<Tool['inputSchema']> & {
497
+ properties: Record<string, unknown>
498
+ }
499
+ }
500
+
501
+ /** The code tool's public declaration from its providers, without building
502
+ * their registry or publishing any of the nested tools' schemas. */
503
+ export let definition = (
504
+ providers: readonly Provider[],
505
+ opts: Pick<Options, 'files' | 'limits' | 'browser'> = {},
506
+ ): Definition => ({
507
+ ...fields,
508
+ description:
509
+ (opts.files
510
+ ? 'Run JavaScript or TypeScript here. Use an async function body with return and await. Use fs for temporary files under /tmp and app draft files under /apps/<app>. Use fetch for HTTP requests. ' +
511
+ (opts.browser
512
+ ? "Use await browser.launch() for a puppeteer Browser on Cloudflare's headless Chrome; it closes when the run ends. "
513
+ : '')
514
+ : 'Use this for bulk reads, imports, reconciles and writes: keep source data and whole tool results inside a short JS/TS function body with return and await. ') +
515
+ pathsOf(providers) +
516
+ ' calls the same scoped tools, returning MCP content and structuredContent. Check isError before using a result. The answer is your return value plus a receipt per call. Large return values and tool results are kept in the graph; the answer gives their id, size, shape and preview. Use await results.read(id) to load a kept result. Omit script to read generated TypeScript declarations, with search, offset and limit for discovery. ' +
517
+ `${(opts.limits ?? LIMITS).wallMs / 1000}s wall, ${
518
+ (opts.limits ?? LIMITS).cpuMs
519
+ }ms CPU, 128MiB isolate, ${
520
+ (opts.limits ?? LIMITS).calls
521
+ } calls, 64KiB script and tool arguments. ` +
522
+ 'Started writes may complete after a script fails or times out; pending receipts mean the outcome is still unknown.',
523
+ })
524
+
525
+ /** One connector tool: omit script to discover generated declarations; supply
526
+ * a JS/TS function body to execute it with the same tool objects. */
527
+ export let tool = (
528
+ registry: Registry,
529
+ run: Runner,
530
+ evaluate: Evaluate,
531
+ strip: Strip,
532
+ opts: Options = {},
533
+ ): Tool => ({
534
+ ...definition(registry.providers(), opts),
535
+ run: async (asked) => {
536
+ let { script, search, offset = 0, limit = 20 } = argsOf(asked)
537
+ // A search lists what it finds the most fitting first.
538
+ let all = catalog(registry).filter((e) => e.name != 'code_mode')
539
+ let matches = search
540
+ ? registry.search(String(search)).flatMap((t) =>
541
+ all.filter((e) => e.name == t.name)
542
+ )
543
+ : all
544
+ let start = Number(offset), end = start + Number(limit)
545
+ let value = script === undefined
546
+ ? {
547
+ declarations: declarations(matches.slice(start, end)) +
548
+ '\ndeclare const results: { read(id: string): Promise<any> }' +
549
+ (opts.files ? fileDeclarations : '') +
550
+ (opts.browser ? browserDeclarations : ''),
551
+ tools: matches.slice(start, end).map((
552
+ { path, description, inputSchema, outputSchema },
553
+ ) => ({ path, description, inputSchema, outputSchema })),
554
+ next: end < matches.length ? end : null,
555
+ limits: opts.limits ?? LIMITS,
556
+ }
557
+ : await execute(
558
+ String(script),
559
+ registry,
560
+ run,
561
+ asked,
562
+ evaluate,
563
+ strip,
564
+ opts,
565
+ )
566
+ if (bytes(value) > LIMITS.systemBytes) {
567
+ throw new CallError('limit', TOO.system)
568
+ }
569
+ let heard = 'calls' in value && value.calls.some((c) => c.heard)
570
+ return [{
571
+ entity: { eid: mint() },
572
+ output: { source: asked.entity.eid, value },
573
+ ...heard ? { heard: {} } : {},
574
+ }]
575
+ },
576
+ })
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@yaks/code-mode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/code-mode",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./source": {
12
+ "types": "./_dist/source.d.ts",
13
+ "default": "./source.js"
14
+ },
15
+ "./repl": {
16
+ "types": "./_dist/repl.d.ts",
17
+ "default": "./repl.js"
18
+ },
19
+ "./vocab": {
20
+ "types": "./_dist/vocab.d.ts",
21
+ "default": "./vocab.js"
22
+ }
23
+ },
24
+ "license": "Apache-2.0",
25
+ "dependencies": {
26
+ "@yaks/fp": "0.2.36",
27
+ "@yaks/graph": "0.2.36",
28
+ "@yaks/tools": "0.2.36",
29
+ "@yaks/vocab": "0.2.36"
30
+ },
31
+ "description": "Typed tool objects from a scoped registry, bounded short script execution and recorded nested calls through an isolated evaluator.",
32
+ "repository": "https://github.com/yak-sh/yak.git"
33
+ }
package/repl.js ADDED
@@ -0,0 +1,85 @@
1
+ // A REPL's cells, between the host that keeps the REPL and the cell's own
2
+ // Worker. Nothing can evaluate new code into a running isolate, so each cell
3
+ // is a Worker of its own, run as the same Durable Object facet: its storage
4
+ // (`storage.sql`, `storage.kv`) lasts as long as the REPL, and the cell's
5
+ // top-level values are kept there when it ends (./source.ts `keep`). The host
6
+ // keeps what this module needs to declare them again in the next cell: the
7
+ // names kept, and the source of each function and class declared.
8
+ import { declared } from "./scan.js";
9
+ import { CARRIED } from "./source.js";
10
+ export let EMPTY = {
11
+ values: [],
12
+ declarations: {}
13
+ };
14
+ let CELL = 'cell.json';
15
+ let id = (name)=>JSON.stringify(name);
16
+ /** What a cell's own code declares, kept beside it for `carry` and `settle`. */ export let cellOf = (modules)=>JSON.parse(modules[CELL] ?? '{"names":[],"declarations":{}}');
17
+ /** The cell's modules with `declared`'s reading of its code beside them. */ export let described = (modules)=>{
18
+ let user = modules['user.js'];
19
+ let code = user.slice(user.indexOf(CARRIED) + CARRIED.length);
20
+ return {
21
+ ...modules,
22
+ [CELL]: JSON.stringify(declared(code))
23
+ };
24
+ };
25
+ /** The cell's modules as its Worker loads them, declaring first what the
26
+ * REPL carries and the cell does not declare again: each kept value by its name, then each earlier
27
+ * function and class. Its own names and the carried ones are read back when
28
+ * it ends, whichever were bound. */ export let carry = (modules, carried)=>{
29
+ let cell = cellOf(modules);
30
+ let own = new Set([
31
+ ...cell.names,
32
+ ...Object.keys(cell.declarations)
33
+ ]);
34
+ let values = carried.values.filter((name)=>!own.has(name));
35
+ let declarations = Object.entries(carried.declarations).filter(([name])=>!own.has(name));
36
+ let read = [
37
+ ...new Set([
38
+ ...cell.names,
39
+ ...values
40
+ ])
41
+ ];
42
+ let prelude = [
43
+ `function $capture() {\n const $o = {};\n${read.map((name)=>` try { $o[${id(name)}] = ${name}; } catch {}`).join('\n')}\n return $o;\n}`,
44
+ '$carried.capture = $capture;',
45
+ ...values.map((name)=>`let ${name} = $carried.values[${id(name)}];`),
46
+ ...declarations.map(([, source])=>source)
47
+ ].join('\n');
48
+ // What the cell declares is the host's to read, not a module to load.
49
+ let { [CELL]: _, ...loaded } = modules;
50
+ return {
51
+ ...loaded,
52
+ 'user.js': modules['user.js'].replace(CARRIED, ()=>prelude)
53
+ };
54
+ };
55
+ /** What the REPL carries after a cell, and the cell's answer without its
56
+ * bookkeeping. A name the cell bound again as a value is no longer a
57
+ * declaration, and one it declared is no longer a value. */ export let settle = (carried, modules, text)=>{
58
+ let { $kept, ...answer } = JSON.parse(text);
59
+ if (!$kept) return {
60
+ carried,
61
+ text
62
+ };
63
+ let cell = cellOf(modules);
64
+ let declarations = {
65
+ ...carried.declarations
66
+ };
67
+ for (let name of $kept)delete declarations[name];
68
+ Object.assign(declarations, cell.declarations);
69
+ return {
70
+ carried: {
71
+ values: $kept.filter((name)=>!(name in cell.declarations)),
72
+ declarations
73
+ },
74
+ text: JSON.stringify(answer)
75
+ };
76
+ };
77
+ /** How a REPL's host runs each cell: declared with what the REPL carries,
78
+ * run by `run` as the REPL's facet, and settled into what it carries next. */ export let cells = (kept, run)=>async (modules)=>{
79
+ let carried = kept.read() ?? EMPTY;
80
+ let text = await run(carry(modules, carried));
81
+ let settled = settle(carried, modules, text);
82
+ kept.write(settled.carried);
83
+ return settled.text;
84
+ };
85
+ //# sourceMappingURL=repl.js.map