@langchain/quickjs 0.2.5 → 0.3.0

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/dist/index.d.ts CHANGED
@@ -1,40 +1,26 @@
1
1
  import * as _$langchain from "langchain";
2
2
  import { AgentMiddleware } from "langchain";
3
3
  import { z } from "zod/v4";
4
- import { AnyBackendProtocol, BackendFactory, BackendProtocolV2 } from "deepagents";
4
+ import { AnyBackendProtocol, BackendFactory, SkillMetadata } from "deepagents";
5
5
  import { StructuredToolInterface } from "@langchain/core/tools";
6
6
 
7
7
  //#region src/types.d.ts
8
8
  /**
9
- * Configuration options for the QuickJS REPL middleware.
9
+ * Configuration options for the REPL middleware.
10
10
  */
11
- interface QuickJSMiddlewareOptions {
12
- /**
13
- * Backend for file I/O (readFile/writeFile) inside the REPL.
14
- * Accepts a AnyBackendProtocol instance or a BackendFactory function.
15
- * Defaults to StateBackend (reads/writes LangGraph checkpoint state).
16
- * @default StateBackend
17
- */
18
- backend?: AnyBackendProtocol | BackendFactory;
11
+ interface REPLMiddlewareOptions {
19
12
  /**
20
13
  * Enable programmatic tool calling from within the REPL.
21
14
  *
22
- * - `false` disabled (default)
23
- * - `true` expose all agent tools except standard vfs tools
24
- * - `string[]` — expose only these tools (alias for `{ include }`)
25
- * - `{ include: string[] }` — expose only these tools
26
- * - `{ exclude: string[] }` — expose all agent tools except these
15
+ * Array of tools to expose; strings are resolved from agent tools, instances
16
+ * are injected directly without needing to be registered on the agent.
27
17
  *
28
- * @default false
18
+ * Omit to disable PTC entirely (default).
29
19
  */
30
- ptc?: boolean | string[] | {
31
- include: string[];
32
- } | {
33
- exclude: string[];
34
- };
20
+ ptc?: (string | StructuredToolInterface)[];
35
21
  /**
36
22
  * Memory limit in bytes.
37
- * @default 52428800 (50MB)
23
+ * @default 67108864 (64MB)
38
24
  */
39
25
  memoryLimitBytes?: number;
40
26
  /**
@@ -45,7 +31,7 @@ interface QuickJSMiddlewareOptions {
45
31
  /**
46
32
  * Execution timeout in milliseconds per evaluation.
47
33
  * Set to a negative value to disable the timeout entirely.
48
- * @default 30000 (30s)
34
+ * @default 5000 (5s)
49
35
  */
50
36
  executionTimeoutMs?: number;
51
37
  /**
@@ -53,6 +39,45 @@ interface QuickJSMiddlewareOptions {
53
39
  * @default null (uses built-in prompt)
54
40
  */
55
41
  systemPrompt?: string | null;
42
+ /**
43
+ * Backend the REPL reads skill module sources from. When provided alongside
44
+ * `SkillsMiddleware`, skills with a `module:` key become dynamic-importable.
45
+ */
46
+ skillsBackend?: AnyBackendProtocol | BackendFactory;
47
+ /**
48
+ * Maximum number of `tools.*` bridge calls allowed per `eval()` invocation.
49
+ *
50
+ * Each call to any function in the `tools` namespace decrements the counter.
51
+ * Once exhausted the next call rejects with a `PTCCallBudgetExceeded` error.
52
+ * The budget resets to this value at the start of every new `eval()` call.
53
+ *
54
+ * Set to `null` to disable the limit entirely (unsafe — increases DoS risk).
55
+ * Must be >= 1 when provided as a number.
56
+ *
57
+ * @default 256
58
+ */
59
+ maxPtcCalls?: number | null;
60
+ /**
61
+ * Maximum characters to retain from console output per evaluation.
62
+ * Output exceeding this limit is dropped at capture time and a
63
+ * `[truncated N chars]` marker is appended to the tool response.
64
+ * The same limit also caps result and error strings in the formatted output.
65
+ *
66
+ * @default 4000
67
+ */
68
+ maxResultChars?: number;
69
+ /**
70
+ * Name of the tool exposed to the model.
71
+ * @default "eval"
72
+ */
73
+ toolName?: string;
74
+ /**
75
+ * If true, install a `console` object that buffers `console.log/warn/error`
76
+ * calls and emits them alongside the result. If false, console output is
77
+ * silently discarded.
78
+ * @default true
79
+ */
80
+ captureConsole?: boolean;
56
81
  }
57
82
  /**
58
83
  * Options for creating a ReplSession.
@@ -60,8 +85,11 @@ interface QuickJSMiddlewareOptions {
60
85
  interface ReplSessionOptions {
61
86
  memoryLimitBytes?: number;
62
87
  maxStackSizeBytes?: number;
63
- backend?: AnyBackendProtocol;
64
88
  tools?: StructuredToolInterface[];
89
+ skillsEnabled?: boolean;
90
+ maxPtcCalls?: number | null;
91
+ maxResultChars?: number;
92
+ captureConsole?: boolean;
65
93
  }
66
94
  /**
67
95
  * Result of a single REPL evaluation.
@@ -75,34 +103,67 @@ interface ReplResult {
75
103
  stack?: string;
76
104
  };
77
105
  logs: string[];
106
+ logsDroppedChars: number;
78
107
  }
79
- //#endregion
80
- //#region src/middleware.d.ts
81
108
  /**
82
- * Backend-provided tools excluded from PTC by default.
83
- * These are redundant inside the REPL since VFS helpers (readFile/writeFile)
84
- * already cover file I/O against the agent's in-memory working set.
109
+ * Metadata + backend pair the session needs to resolve skill imports.
85
110
  */
86
- declare const DEFAULT_PTC_EXCLUDED_TOOLS: readonly ["ls", "read_file", "write_file", "edit_file", "glob", "grep", "execute"];
111
+ interface SkillsContext {
112
+ /**
113
+ * Per-eval snapshot of `state.skillsMetadata`.
114
+ */
115
+ metadata: SkillMetadata[];
116
+ /**
117
+ * Backend the session fetches skill source files from.
118
+ */
119
+ backend: AnyBackendProtocol;
120
+ }
121
+ //#endregion
122
+ //#region src/middleware.d.ts
87
123
  /**
88
- * Create the QuickJS REPL middleware.
124
+ * Create the REPL middleware.
89
125
  */
90
- declare function createQuickJSMiddleware(options?: QuickJSMiddlewareOptions): AgentMiddleware<undefined, undefined, unknown, readonly [_$langchain.DynamicStructuredTool<z.ZodObject<{
126
+ declare function createREPLMiddleware(options?: REPLMiddlewareOptions): AgentMiddleware<undefined, undefined, unknown, readonly [_$langchain.DynamicStructuredTool<z.ZodObject<{
91
127
  code: z.ZodString;
92
128
  }, z.core.$strip>, {
93
129
  code: string;
94
130
  }, {
95
131
  code: string;
96
- }, string, unknown, "js_eval">]>;
132
+ }, string, unknown, string>]>;
133
+ //#endregion
134
+ //#region src/errors.d.ts
135
+ /**
136
+ * Options for constructing a {@link PTCCallBudgetExceededError}.
137
+ */
138
+ interface PTCCallBudgetExceededOptions {
139
+ /**
140
+ * The configured per-eval PTC call limit.
141
+ */
142
+ limit: number;
143
+ /**
144
+ * The call number that triggered the violation (always `limit + 1`).
145
+ */
146
+ attempted: number;
147
+ /**
148
+ * The name of the tool function that was called over budget.
149
+ */
150
+ functionName: string;
151
+ }
152
+ /**
153
+ * Thrown when a single eval exhausts its configured PTC call budget.
154
+ */
155
+ declare class PTCCallBudgetExceededError extends Error {
156
+ readonly limit: number;
157
+ readonly attempted: number;
158
+ readonly functionName: string;
159
+ constructor(options: PTCCallBudgetExceededOptions);
160
+ }
97
161
  //#endregion
98
162
  //#region src/session.d.ts
99
163
  declare const DEFAULT_MEMORY_LIMIT: number;
100
164
  declare const DEFAULT_MAX_STACK_SIZE: number;
101
- declare const DEFAULT_EXECUTION_TIMEOUT = 30000;
102
- interface PendingWrite {
103
- path: string;
104
- content: string;
105
- }
165
+ declare const DEFAULT_EXECUTION_TIMEOUT = 5000;
166
+ declare const DEFAULT_MAX_PTC_CALLS = 256;
106
167
  /**
107
168
  * Sandboxed JavaScript REPL session backed by QuickJS WASM.
108
169
  *
@@ -110,23 +171,45 @@ interface PendingWrite {
110
171
  * The QuickJS runtime is lazily started on the first `.eval()` call
111
172
  * and reconnected if a session with the same id already exists.
112
173
  * This makes it safe to store in LangGraph state across interrupts.
113
- *
114
- * File writes are buffered during execution and flushed via
115
- * `flushWrites(backend)` after eval completes.
116
174
  */
117
175
  declare class ReplSession {
118
176
  private static sessions;
119
177
  readonly id: string;
120
- readonly pendingWrites: PendingWrite[];
121
178
  private runtime;
122
179
  private context;
123
- private logs;
124
- private _options;
125
- private _backend;
180
+ private consoleBuffer;
181
+ private options;
182
+ private skillsContext;
183
+ private skillsLoaded;
184
+ private skillsFailed;
185
+ private readonly maxPtcCalls;
186
+ private ptcCallsRemaining;
126
187
  constructor(id: string, options?: ReplSessionOptions);
127
- get backend(): BackendProtocolV2 | null;
128
- set backend(b: AnyBackendProtocol | null);
129
188
  private ensureStarted;
189
+ /**
190
+ * Load the skill into cache on first access and replay cached errors.
191
+ */
192
+ private ensureSkillLoaded;
193
+ private resolveSpecifier;
194
+ /**
195
+ * Canonicalize an `import` specifier. Bare specifiers pass through;
196
+ * relative specifiers are resolved against the importing module's path.
197
+ * Traversal out of a skill's `@/skills/<name>/` namespace is rejected.
198
+ */
199
+ private normalizeSpecifier;
200
+ /**
201
+ * Wire the QuickJS module loader and normalizer on this session's runtime.
202
+ */
203
+ private installModuleLoader;
204
+ /**
205
+ * Initialise the per-eval PTC counter. Called at the top of every `eval()`.
206
+ */
207
+ private resetPtcBudget;
208
+ /**
209
+ * Decrement the PTC call counter and throw if the budget is exhausted.
210
+ * `null` budget means unlimited — returns immediately without decrementing.
211
+ */
212
+ private consumePtcBudget;
130
213
  /**
131
214
  * Get or create a session for the given id.
132
215
  *
@@ -139,6 +222,22 @@ declare class ReplSession {
139
222
  * Retrieve an existing session by id, or null if none exists.
140
223
  */
141
224
  static get(id: string): ReplSession | null;
225
+ /**
226
+ * Returns true if any session exists whose key equals `threadId` or starts
227
+ * with `threadId:`. Useful for tests that need to confirm a session was
228
+ * created without knowing the full `threadId:middlewareId` key.
229
+ */
230
+ static hasAnyForThread(threadId: string): boolean;
231
+ /**
232
+ * Dispose and remove the session with the given key, if it exists.
233
+ */
234
+ static deleteSession(key: string): void;
235
+ /**
236
+ * Push the current skills metadata + backend into the session.
237
+ * Called by the middleware once per `eval` invocation, before eval runs.
238
+ * Pass `undefined` to clear the context (no skill imports will resolve).
239
+ */
240
+ setSkillsContext(ctx?: SkillsContext): void;
142
241
  /**
143
242
  * Evaluate code in this session.
144
243
  *
@@ -149,7 +248,6 @@ declare class ReplSession {
149
248
  * async IIFE.
150
249
  */
151
250
  eval(code: string, timeoutMs: number): Promise<ReplResult>;
152
- flushWrites(backend: AnyBackendProtocol): Promise<void>;
153
251
  dispose(): void;
154
252
  toJSON(): {
155
253
  id: string;
@@ -163,7 +261,6 @@ declare class ReplSession {
163
261
  */
164
262
  static clearCache(): void;
165
263
  private setupConsole;
166
- private injectVfs;
167
264
  private injectTools;
168
265
  }
169
266
  //#endregion
@@ -176,6 +273,10 @@ declare function toCamelCase(name: string): string;
176
273
  * Format the result of a REPL evaluation for the agent.
177
274
  */
178
275
  declare function formatReplResult(result: ReplResult): string;
276
+ /**
277
+ * Render a pre-eval error when referenced skills are not available on the agent.
278
+ */
279
+ declare function formatSkillNotAvailable(missing: readonly string[]): string;
179
280
  //#endregion
180
281
  //#region src/transform.d.ts
181
282
  /**
@@ -199,6 +300,61 @@ declare function formatReplResult(result: ReplResult): string;
199
300
  * - Wraps in async IIFE for top-level await support
200
301
  */
201
302
  declare function transformForEval(code: string): string;
303
+ /**
304
+ * Strip TypeScript type syntax from an ES-module source so QuickJS can
305
+ * evaluate it as a standard JS module.
306
+ *
307
+ * Unlike `transformForEval`, this keeps `import`/`export` declarations,
308
+ * does not hoist to `globalThis`, and does not wrap in an IIFE.
309
+ * On parse failure the original source is returned unchanged.
310
+ */
311
+ declare function stripTypeSyntax(code: string): string;
312
+ //#endregion
313
+ //#region src/skills.d.ts
314
+ /**
315
+ * File extensions the loader will enumerate from a skill directory.
316
+ */
317
+ declare const SKILL_MODULE_EXTENSIONS: string[];
318
+ /**
319
+ * Hard cap on total bytes pulled for one skill's bundle (1 MiB).
320
+ */
321
+ declare const MAX_SKILL_BUNDLE_BYTES: number;
322
+ /**
323
+ * Install-ready state for a single skill, produced by `loadSkill`.
324
+ */
325
+ interface LoadedSkill {
326
+ /**
327
+ * Spec-validated kebab-case skill name.
328
+ */
329
+ name: string;
330
+ /**
331
+ * Bare specifier the skill installs under: `"@/skills/<name>"`.
332
+ */
333
+ specifier: string;
334
+ /**
335
+ * Relative POSIX path of the entrypoint file (e.g. `"index.ts"`).
336
+ */
337
+ entryRel: string;
338
+ /**
339
+ * File contents keyed by relative POSIX path, with TS syntax stripped.
340
+ */
341
+ files: Map<string, string>;
342
+ }
343
+ /**
344
+ * Build a `LoadedSkill` from a skill's metadata and a backend handle.
345
+ *
346
+ * Enumerates code files under the skill directory, downloads them,
347
+ * strips TypeScript syntax, and validates the entrypoint is present.
348
+ */
349
+ declare function loadSkill(metadata: SkillMetadata, backend: AnyBackendProtocol): Promise<LoadedSkill>;
350
+ /**
351
+ * Extract skill names referenced by `"@/skills/<name>"` literals in source.
352
+ *
353
+ * Used as a pre-eval scan so the middleware can surface `SkillNotAvailable`
354
+ * before evaluation starts. Dynamic imports with computed specifiers are
355
+ * not detected.
356
+ */
357
+ declare function scanSkillReferences(source: string): Set<string>;
202
358
  //#endregion
203
- export { DEFAULT_EXECUTION_TIMEOUT, DEFAULT_MAX_STACK_SIZE, DEFAULT_MEMORY_LIMIT, DEFAULT_PTC_EXCLUDED_TOOLS, type PendingWrite, type QuickJSMiddlewareOptions, type ReplResult, ReplSession, type ReplSessionOptions, createQuickJSMiddleware, formatReplResult, toCamelCase, transformForEval };
359
+ export { DEFAULT_EXECUTION_TIMEOUT, DEFAULT_MAX_PTC_CALLS, DEFAULT_MAX_STACK_SIZE, DEFAULT_MEMORY_LIMIT, type LoadedSkill, MAX_SKILL_BUNDLE_BYTES, PTCCallBudgetExceededError, type REPLMiddlewareOptions, type ReplResult, ReplSession, type ReplSessionOptions, SKILL_MODULE_EXTENSIONS, createREPLMiddleware, formatReplResult, formatSkillNotAvailable, loadSkill, scanSkillReferences, stripTypeSyntax, toCamelCase, transformForEval };
204
360
  //# sourceMappingURL=index.d.ts.map