@opencode/codemode 0.0.0-dev-261 → 0.0.0-dev-275

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.
@@ -1,7 +1,9 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import type { Extension } from "./extension.js";
3
+ import { scanTools } from "./scan.js";
3
4
  import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js";
4
5
  import type { Tools } from "./tools.js";
6
+ export { scanTools };
5
7
  /** A tool call admitted during an execution. */
6
8
  export type { CallResult, ExtensionInvocation, Hooks, ToolCall, ToolDescription, ToolInvocation, } from "./tool-runtime.js";
7
9
  /** Signature-construction helpers for host-owned catalog instructions. */
@@ -43,6 +45,8 @@ export type Environment<Provided extends Record<string, unknown>, Extensions ext
43
45
  export type ExecuteOptions<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = Options<Provided, Extensions> & {
44
46
  /** Source for one program in the supported JavaScript subset. */
45
47
  code: string;
48
+ /** Read-only JSON values bound in the program's outer global scope (shadowable by top-level declarations). */
49
+ bindings?: Readonly<Record<string, DataValue>>;
46
50
  };
47
51
  /** A JSON value that can cross the confined interpreter boundary. */
48
52
  export type DataValue = Schema.Json;
@@ -144,7 +148,7 @@ export type Result = typeof Result.Type;
144
148
  /** Reusable confined runtime over explicit tools. */
145
149
  export type Runtime<R = never> = {
146
150
  readonly catalog: ReadonlyArray<ToolDescription>;
147
- readonly execute: (code: string) => Effect.Effect<Result, never, R>;
151
+ readonly execute: (code: string, bindings?: Readonly<Record<string, DataValue>>) => Effect.Effect<Result, never, R>;
148
152
  };
149
153
  /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
150
154
  export declare const execute: <const Provided extends Record<string, unknown>, const Extensions extends ReadonlyArray<Extension> = []>(options: ExecuteOptions<Provided, Extensions>) => Effect.Effect<Result, never, Environment<Provided, Extensions>>;
package/dist/codemode.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { Effect, Schema } from "effect";
2
+ import { fromJson } from "./data.js";
2
3
  import { executeProgram } from "./interpreter/execute.js";
3
4
  import { extensionGlobals } from "./interpreter/extensions.js";
4
5
  import { globalNames } from "./interpreter/globals.js";
6
+ import { scanTools } from "./scan.js";
5
7
  import { ToolRuntime } from "./tool-runtime.js";
8
+ export { scanTools };
6
9
  /** Signature-construction helpers for host-owned catalog instructions. */
7
10
  export { searchSignature, toolExpression } from "./tool-runtime.js";
8
11
  /** Schema for a host tool input containing CodeMode source. */
@@ -56,7 +59,7 @@ const resolveExecutionLimits = (limits) => ({
56
59
  maxOutputBytes: validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0),
57
60
  });
58
61
  /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
59
- export const execute = (options) => make(options).execute(options.code);
62
+ export const execute = (options) => make(options).execute(options.code, options.bindings);
60
63
  /** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
61
64
  export const make = (options = {}) => {
62
65
  const prepared = ToolRuntime.prepare((options.tools ?? {}));
@@ -74,6 +77,9 @@ export const make = (options = {}) => {
74
77
  get catalog() {
75
78
  return prepared.catalog;
76
79
  },
77
- execute: (code) => executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => extensionGlobals(ctx, extensions)),
80
+ execute: (code, bindings) => executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => [
81
+ ...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)]),
82
+ ...extensionGlobals(ctx, extensions),
83
+ ]),
78
84
  };
79
85
  };
@@ -1,6 +1,14 @@
1
+ import { type Program } from "acorn";
1
2
  import { Effect } from "effect";
2
- import type { ResolvedExecutionLimits, Result } from "../codemode.js";
3
+ import type { Diagnostic, ResolvedExecutionLimits, Result } from "../codemode.js";
3
4
  import { ToolRuntime } from "../tool-runtime.js";
4
5
  import type { Value } from "./objects.js";
5
6
  import { Interpreter } from "./interpreter.js";
6
7
  export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>) => Effect.Effect<Result, never, R>;
8
+ export declare const parseProgram: (code: string) => {
9
+ ok: true;
10
+ program: Program;
11
+ } | {
12
+ ok: false;
13
+ error: Diagnostic;
14
+ };
@@ -86,7 +86,7 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
86
86
  })), Effect.map((result) => limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes)));
87
87
  });
88
88
  };
89
- const parseProgram = (code) => {
89
+ export const parseProgram = (code) => {
90
90
  try {
91
91
  const program = parse(code, {
92
92
  ecmaVersion: "latest",
package/dist/scan.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { Result } from "effect";
2
+ import type { Diagnostic } from "./codemode.js";
3
+ /**
4
+ * Extracts every `tools.<path>` referenced by a Code Mode program, in first-seen order. Fails on syntax errors,
5
+ * dynamic bracket access (`tools[name]`), or aliasing/passing `tools` rather than calling `tools.<path>(...)` directly.
6
+ */
7
+ export declare function scanTools(code: string): Result.Result<ReadonlyArray<string>, Diagnostic>;
package/dist/scan.js ADDED
@@ -0,0 +1,245 @@
1
+ import { Result } from "effect";
2
+ import { parseProgram } from "./interpreter/execute.js";
3
+ import { formatLocation } from "./interpreter/model.js";
4
+ /**
5
+ * Extracts every `tools.<path>` referenced by a Code Mode program, in first-seen order. Fails on syntax errors,
6
+ * dynamic bracket access (`tools[name]`), or aliasing/passing `tools` rather than calling `tools.<path>(...)` directly.
7
+ */
8
+ export function scanTools(code) {
9
+ if (code.trim().length === 0) {
10
+ return Result.fail({ kind: "ParseError", message: "Code cannot be empty." });
11
+ }
12
+ const parsed = parseProgram(code);
13
+ if (!parsed.ok)
14
+ return Result.fail(parsed.error);
15
+ const found = new Set();
16
+ const scopes = [collectScope(parsed.program, true)];
17
+ const ancestors = [];
18
+ const isShadowed = () => scopes.some((scope) => scope.has("tools"));
19
+ const fail = (node, message) => {
20
+ const loc = node.loc?.start ? { line: node.loc.start.line, column: node.loc.start.column + 1 } : undefined;
21
+ return {
22
+ kind: "UnsupportedSyntax",
23
+ message: `${message}${loc ? formatLocation(loc) : ""}`,
24
+ ...(loc ? { location: loc } : {}),
25
+ };
26
+ };
27
+ const visit = (node) => {
28
+ if (!node)
29
+ return undefined;
30
+ if (node.type === "Identifier" && node.name === "tools" && !isShadowed()) {
31
+ const parent = ancestors.at(-1);
32
+ if (!isReferencePosition(node, parent))
33
+ return undefined;
34
+ const chain = readStaticToolCall(node, ancestors);
35
+ if (!chain.ok)
36
+ return fail(chain.node, chain.reason);
37
+ found.add(chain.path);
38
+ return undefined;
39
+ }
40
+ const pushedScope = enterNodeScope(node);
41
+ if (pushedScope)
42
+ scopes.push(pushedScope);
43
+ ancestors.push(node);
44
+ const error = visitChildren(node, visit);
45
+ ancestors.pop();
46
+ if (pushedScope)
47
+ scopes.pop();
48
+ return error;
49
+ };
50
+ const diagnostic = visit(parsed.program);
51
+ if (diagnostic)
52
+ return Result.fail(diagnostic);
53
+ return Result.succeed(Array.from(found));
54
+ }
55
+ function isReferencePosition(node, parent) {
56
+ if (!parent)
57
+ return true;
58
+ if (parent.type === "MemberExpression" && parent.property === node && !parent.computed)
59
+ return false;
60
+ if (parent.type === "Property" && parent.key === node && !parent.computed && !parent.shorthand)
61
+ return false;
62
+ if (parent.type === "MethodDefinition" && parent.key === node && !parent.computed)
63
+ return false;
64
+ if ((parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") &&
65
+ parent.label === node) {
66
+ return false;
67
+ }
68
+ if ((parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ClassDeclaration" || parent.type === "ClassExpression") &&
69
+ parent.id === node) {
70
+ return false;
71
+ }
72
+ if (parent.type === "VariableDeclarator" && parent.id === node)
73
+ return false;
74
+ return true;
75
+ }
76
+ function readStaticToolCall(root, ancestors) {
77
+ const segments = [];
78
+ let current = root;
79
+ let index = ancestors.length - 1;
80
+ while (index >= 0) {
81
+ const parent = ancestors[index];
82
+ if (parent.type === "ChainExpression" && parent.expression === current) {
83
+ current = parent;
84
+ index -= 1;
85
+ continue;
86
+ }
87
+ if (parent.type !== "MemberExpression" || parent.object !== current)
88
+ break;
89
+ if (!parent.computed && parent.property.type === "Identifier") {
90
+ segments.push(parent.property.name);
91
+ current = parent;
92
+ index -= 1;
93
+ continue;
94
+ }
95
+ if (parent.computed && parent.property.type === "Literal" && typeof parent.property.value === "string") {
96
+ segments.push(parent.property.value);
97
+ current = parent;
98
+ index -= 1;
99
+ continue;
100
+ }
101
+ return {
102
+ ok: false,
103
+ node: parent.property,
104
+ reason: "Schedule checks must reference tools statically (e.g. tools.slack.read_thread), not with dynamic bracket expressions.",
105
+ };
106
+ }
107
+ const callParent = index >= 0 ? ancestors[index] : undefined;
108
+ if (segments.length === 0 || callParent?.type !== "CallExpression" || callParent.callee !== current) {
109
+ return {
110
+ ok: false,
111
+ node: current,
112
+ reason: "Schedule checks must call tools directly as tools.<name>(...), not alias or pass the tools object.",
113
+ };
114
+ }
115
+ return { ok: true, path: segments.join(".") };
116
+ }
117
+ function enterNodeScope(node) {
118
+ if (node.type === "FunctionDeclaration" ||
119
+ node.type === "FunctionExpression" ||
120
+ node.type === "ArrowFunctionExpression") {
121
+ const names = new Set();
122
+ if (node.id)
123
+ names.add(node.id.name);
124
+ for (const param of node.params)
125
+ collectPattern(param, names);
126
+ if (node.body.type === "BlockStatement") {
127
+ for (const name of collectScope(node.body, true))
128
+ names.add(name);
129
+ }
130
+ return names;
131
+ }
132
+ if (node.type === "BlockStatement")
133
+ return collectScope(node, false);
134
+ if (node.type === "CatchClause") {
135
+ const names = new Set();
136
+ if (node.param)
137
+ collectPattern(node.param, names);
138
+ return names;
139
+ }
140
+ if (node.type === "ForStatement" && node.init?.type === "VariableDeclaration" && node.init.kind !== "var") {
141
+ const names = new Set();
142
+ for (const decl of node.init.declarations)
143
+ collectPattern(decl.id, names);
144
+ return names;
145
+ }
146
+ if ((node.type === "ForInStatement" || node.type === "ForOfStatement") &&
147
+ node.left.type === "VariableDeclaration" &&
148
+ node.left.kind !== "var") {
149
+ const names = new Set();
150
+ for (const decl of node.left.declarations)
151
+ collectPattern(decl.id, names);
152
+ return names;
153
+ }
154
+ return undefined;
155
+ }
156
+ function collectScope(container, includeVar) {
157
+ const names = new Set();
158
+ for (const statement of container.body) {
159
+ if (statement.type === "FunctionDeclaration" && statement.id)
160
+ names.add(statement.id.name);
161
+ if (statement.type === "ClassDeclaration" && statement.id)
162
+ names.add(statement.id.name);
163
+ if (statement.type === "VariableDeclaration" && (includeVar || statement.kind !== "var")) {
164
+ for (const decl of statement.declarations)
165
+ collectPattern(decl.id, names);
166
+ }
167
+ }
168
+ if (includeVar)
169
+ collectNestedVars(container.body, names);
170
+ return names;
171
+ }
172
+ function collectNestedVars(statements, names) {
173
+ const walkStmt = (node) => {
174
+ if (!node)
175
+ return;
176
+ if (node.type === "FunctionDeclaration" ||
177
+ node.type === "FunctionExpression" ||
178
+ node.type === "ArrowFunctionExpression") {
179
+ return;
180
+ }
181
+ if (node.type === "VariableDeclaration" && node.kind === "var") {
182
+ for (const decl of node.declarations)
183
+ collectPattern(decl.id, names);
184
+ }
185
+ visitChildren(node, (child) => {
186
+ walkStmt(child);
187
+ return undefined;
188
+ });
189
+ };
190
+ for (const stmt of statements)
191
+ walkStmt(stmt);
192
+ }
193
+ function collectPattern(pattern, names) {
194
+ switch (pattern.type) {
195
+ case "Identifier":
196
+ names.add(pattern.name);
197
+ return;
198
+ case "AssignmentPattern":
199
+ collectPattern(pattern.left, names);
200
+ return;
201
+ case "RestElement":
202
+ collectPattern(pattern.argument, names);
203
+ return;
204
+ case "ArrayPattern":
205
+ for (const element of pattern.elements)
206
+ if (element)
207
+ collectPattern(element, names);
208
+ return;
209
+ case "ObjectPattern":
210
+ for (const prop of pattern.properties) {
211
+ if (prop.type === "RestElement")
212
+ collectPattern(prop.argument, names);
213
+ if (prop.type === "Property")
214
+ collectPattern(prop.value, names);
215
+ }
216
+ return;
217
+ case "MemberExpression":
218
+ return;
219
+ }
220
+ }
221
+ function visitChildren(node, visit) {
222
+ for (const [key, value] of Object.entries(node)) {
223
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range")
224
+ continue;
225
+ if (Array.isArray(value)) {
226
+ for (const item of value) {
227
+ if (isAstNode(item)) {
228
+ const error = visit(item);
229
+ if (error)
230
+ return error;
231
+ }
232
+ }
233
+ continue;
234
+ }
235
+ if (isAstNode(value)) {
236
+ const error = visit(value);
237
+ if (error)
238
+ return error;
239
+ }
240
+ }
241
+ return undefined;
242
+ }
243
+ function isAstNode(value) {
244
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
245
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/codemode",
4
- "version": "0.0.0-dev-261",
4
+ "version": "0.0.0-dev-275",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",