@code-yeongyu/senpi-codemode 2026.11.26 → 2026.11.27

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 (52) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +87 -0
  3. package/package.json +5 -5
  4. package/src/bridge/reserved.ts +2 -0
  5. package/src/config/feature-settings.ts +19 -0
  6. package/src/config/settings.ts +8 -0
  7. package/src/extension/eval-status-ticker.ts +5 -2
  8. package/src/extension/runtime-factory.ts +31 -5
  9. package/src/extension/session-manager.ts +4 -1
  10. package/src/index.ts +14 -6
  11. package/src/kernels/js/babel-ast.ts +64 -0
  12. package/src/kernels/js/binding-patterns.js +166 -0
  13. package/src/kernels/js/cell-run-context.js +8 -0
  14. package/src/kernels/js/declaration-extent.js +157 -0
  15. package/src/kernels/js/erase-types.ts +174 -0
  16. package/src/kernels/js/js-source-scan.js +181 -0
  17. package/src/kernels/js/kernel-contract.ts +2 -0
  18. package/src/kernels/js/last-expression.js +207 -0
  19. package/src/kernels/js/local-module-loader.ts +7 -2
  20. package/src/kernels/js/persist-declarations.js +233 -0
  21. package/src/kernels/js/rewrite-imports.ts +3 -60
  22. package/src/kernels/js/typescript-cell.ts +39 -0
  23. package/src/kernels/js/worker-core.js +1 -0
  24. package/src/kernels/js/worker-indirect-eval.js +4 -860
  25. package/src/kernels/js/worker-runtime.js +2 -0
  26. package/src/kernels/js/worker-scope.js +71 -0
  27. package/src/kernels/js/worker-startup.ts +1 -0
  28. package/src/prompt/eval-prompt-template.ts +4 -2
  29. package/src/prompt/eval-prompt.ts +4 -0
  30. package/src/skill/bun/SKILL.md +1 -0
  31. package/src/tool/cell-handler.ts +17 -1
  32. package/src/tool/detached-cell-manager.ts +42 -4
  33. package/src/tool/detached-notification-queue.ts +48 -7
  34. package/src/tool/detached-settling.ts +26 -0
  35. package/src/tool/eval-tool-options.ts +5 -1
  36. package/src/tool/eval-tool.ts +3 -1
  37. package/src/tool/js-cell-parse-message.ts +11 -3
  38. package/src/tool/managed-cell.ts +3 -0
  39. package/src/tool/run-eval-cell.ts +36 -11
  40. package/src/tool/scoped-watches.ts +53 -0
  41. package/src/tool/types.ts +14 -0
  42. package/src/written-files/model-writes.ts +55 -0
  43. package/src/written-files/ownership.ts +73 -0
  44. package/src/written-files/report.ts +63 -0
  45. package/src/written-files/scan-boundaries.ts +164 -0
  46. package/src/written-files/source-file.ts +31 -0
  47. package/src/written-files/tracker.ts +361 -0
  48. package/src/written-files/window.ts +92 -0
  49. package/src/written-files/workspace-fs.ts +104 -0
  50. package/src/written-files/workspace-scan.ts +253 -0
  51. package/src/written-files/write-hooks.ts +155 -0
  52. package/src/written-files/written-files.ts +155 -0
@@ -0,0 +1,207 @@
1
+ import { REGEX_PREFIX_KEYWORDS, isDecimalDigit, isDeclarationContinuation, isExpressionOperator, isIdentifierStart, isLineTerminator, nextSignificantIndex, readIdentifier, skipBlockComment, skipLineComment, skipNumberLiteral, skipQuotedLiteral, skipRegexLiteral, skipTemplateLiteral } from "./js-source-scan.js";
2
+
3
+ /** True when the cell has a `return` outside any nested function: the cell's own return value wins. */
4
+ export function hasTopLevelReturn(code) {
5
+ return scanTopLevelStatements(code).hasTopLevelReturn;
6
+ }
7
+
8
+ /** Returns the cell's last statement as its value when that statement is an expression. */
9
+ export function captureLastExpression(code) {
10
+ const { lastStatementStart: start, lastStatementIsBlock } = scanTopLevelStatements(code);
11
+ const head = code.slice(0, start);
12
+ const tail = code.slice(start).trim();
13
+ if (!tail || lastStatementIsBlock || isStatementOnly(tail)) return code;
14
+ return `${head}return ${tail.replace(/;+$/u, "")};`;
15
+ }
16
+
17
+ // oxlint-disable-next-line eslint/no-misleading-character-class -- ECMAScript identifiers permit ZWNJ and ZWJ as individual continuation characters.
18
+ const LABEL_PREFIX_RE = /^[\p{ID_Start}$_][\p{ID_Continue}\u200c\u200d$]*\s*:/u;
19
+ // `using x = ...` / `await using x = ...`: no line break may separate the keywords and the binding (senpi#7381).
20
+ const USING_DECLARATION_RE = /^(?:await[ \t]+)?using[ \t]+(?!(?:in|of|instanceof)\b)[\p{ID_Start}$_]/u;
21
+
22
+ function isStatementOnly(source) {
23
+ if (
24
+ /^(?:const|let|var|if|for|while|switch|try|catch|finally|class|function|import|export|throw|return|do|break|continue|debugger)\b/u.test(
25
+ source,
26
+ )
27
+ )
28
+ return true;
29
+ return USING_DECLARATION_RE.test(source) || LABEL_PREFIX_RE.test(source);
30
+ }
31
+
32
+ const CONTROL_PAREN_KEYWORDS = new Set(["catch", "for", "if", "switch", "while", "with"]);
33
+ // A `{` right after one of these opens a block statement, never an object literal.
34
+ const BLOCK_KEYWORDS = new Set(["catch", "do", "else", "finally", "try"]);
35
+ const STATEMENT_CONTINUATION_KEYWORDS = new Set(["catch", "else", "finally"]);
36
+
37
+ /**
38
+ * Finds where the cell's last top-level statement starts. A top-level `{` in statement position (statement start, a
39
+ * control statement's body, a function or class declaration's body) is a block statement: its `}` ends the statement,
40
+ * so whatever follows on the same line starts the next one.
41
+ */
42
+ function scanTopLevelStatements(code) {
43
+ let start = 0;
44
+ let round = 0;
45
+ let square = 0;
46
+ let curly = 0;
47
+ let canStartRegex = true;
48
+ let lastSignificant = "";
49
+ let lastToken = "";
50
+ let pendingControlParen = false;
51
+ let afterControlParen = false;
52
+ let declarationHead = false;
53
+ let asyncAtStatementStart = false;
54
+ let topBlock = null;
55
+ let pendingStatementEnd = false;
56
+ let pendingDoWhile = false;
57
+ let hasTopLevelReturn = false;
58
+ const controlParens = [];
59
+ const blockStarts = new Set();
60
+ const atStatementStart = (index) => nextSignificantIndex(code, start) === index;
61
+ for (let index = 0; index < code.length; index += 1) {
62
+ const char = code[index];
63
+ const next = code[index + 1];
64
+ if (char === "/" && next === "/") {
65
+ index = skipLineComment(code, index) - 1;
66
+ continue;
67
+ }
68
+ if (char === "/" && next === "*") {
69
+ index = skipBlockComment(code, index) - 1;
70
+ continue;
71
+ }
72
+ if (isLineTerminator(char)) {
73
+ if (round === 0 && square === 0 && curly === 0) {
74
+ if (!canStartRegex) {
75
+ const nextIndex = nextSignificantIndex(code, index + 1);
76
+ if (nextIndex < code.length && !isStatementContinuation(code, nextIndex, lastSignificant)) start = nextIndex;
77
+ }
78
+ canStartRegex = true;
79
+ }
80
+ continue;
81
+ }
82
+ if (/\s/u.test(char)) continue;
83
+ const previousToken = lastToken;
84
+ const previousControlClose = afterControlParen;
85
+ lastToken = "";
86
+ afterControlParen = false;
87
+ if (pendingStatementEnd) {
88
+ pendingStatementEnd = false;
89
+ const token = isIdentifierStart(char) ? code.slice(index, readIdentifier(code, index)) : "";
90
+ const continues = STATEMENT_CONTINUATION_KEYWORDS.has(token) || (pendingDoWhile && token === "while");
91
+ if (!continues && char !== ";") start = index;
92
+ }
93
+ if (char === "'" || char === '"' || char === "`") {
94
+ index = (char === "`" ? skipTemplateLiteral(code, index) : skipQuotedLiteral(code, index)) - 1;
95
+ canStartRegex = false;
96
+ lastSignificant = char;
97
+ pendingControlParen = false;
98
+ continue;
99
+ }
100
+ if (char === "/" && canStartRegex) {
101
+ index = skipRegexLiteral(code, index) - 1;
102
+ canStartRegex = false;
103
+ lastSignificant = char;
104
+ pendingControlParen = false;
105
+ continue;
106
+ }
107
+ if (isIdentifierStart(char)) {
108
+ const end = readIdentifier(code, index);
109
+ const token = code.slice(index, end);
110
+ const isPropertyName = lastSignificant === ".";
111
+ const atTopLevel = round === 0 && square === 0 && curly === 0;
112
+ if (token === "return" && atTopLevel && !isPropertyName) hasTopLevelReturn = true;
113
+ if (atTopLevel && !isPropertyName) {
114
+ if (token === "async") asyncAtStatementStart = atStatementStart(index);
115
+ if (token === "function" || token === "class") {
116
+ declarationHead = atStatementStart(index) || (previousToken === "async" && asyncAtStatementStart);
117
+ }
118
+ }
119
+ canStartRegex = !isPropertyName && REGEX_PREFIX_KEYWORDS.has(token);
120
+ pendingControlParen = !isPropertyName && CONTROL_PAREN_KEYWORDS.has(token);
121
+ lastToken = isPropertyName ? "" : token;
122
+ lastSignificant = code[end - 1];
123
+ index = end - 1;
124
+ continue;
125
+ }
126
+ if (isDecimalDigit(char)) {
127
+ index = skipNumberLiteral(code, index) - 1;
128
+ canStartRegex = false;
129
+ lastSignificant = char;
130
+ pendingControlParen = false;
131
+ continue;
132
+ }
133
+ if (char === "(") {
134
+ round += 1;
135
+ controlParens.push(pendingControlParen);
136
+ pendingControlParen = false;
137
+ canStartRegex = true;
138
+ lastSignificant = char;
139
+ continue;
140
+ }
141
+ if (char === ")") {
142
+ round = Math.max(0, round - 1);
143
+ const closesControl = controlParens.pop() === true;
144
+ canStartRegex = closesControl;
145
+ afterControlParen = closesControl && round === 0 && square === 0 && curly === 0;
146
+ lastSignificant = char;
147
+ continue;
148
+ }
149
+ if (char === "{" && round === 0 && square === 0 && curly === 0) {
150
+ const block = declarationHead || previousControlClose || BLOCK_KEYWORDS.has(previousToken) || atStatementStart(index);
151
+ if (block && atStatementStart(index)) blockStarts.add(index);
152
+ topBlock = block ? { doWhile: previousToken === "do" } : null;
153
+ declarationHead = false;
154
+ }
155
+ if (char === "[" || char === "{") {
156
+ if (char === "[") square += 1;
157
+ else curly += 1;
158
+ canStartRegex = true;
159
+ lastSignificant = char;
160
+ pendingControlParen = false;
161
+ continue;
162
+ }
163
+ if (char === "]" || char === "}") {
164
+ if (char === "]") square = Math.max(0, square - 1);
165
+ else curly = Math.max(0, curly - 1);
166
+ const closesBlock = char === "}" && topBlock !== null && round === 0 && square === 0 && curly === 0;
167
+ if (closesBlock) {
168
+ pendingStatementEnd = true;
169
+ pendingDoWhile = topBlock.doWhile;
170
+ topBlock = null;
171
+ }
172
+ canStartRegex = closesBlock;
173
+ lastSignificant = char;
174
+ pendingControlParen = false;
175
+ continue;
176
+ }
177
+ if (char === ";" && round === 0 && square === 0 && curly === 0) {
178
+ const nextIndex = nextSignificantIndex(code, index + 1);
179
+ if (nextIndex < code.length && !isContinuationKeyword(code, nextIndex)) start = nextIndex;
180
+ canStartRegex = true;
181
+ lastSignificant = char;
182
+ pendingControlParen = false;
183
+ continue;
184
+ }
185
+ canStartRegex = isExpressionOperator(char) || char === ",";
186
+ lastSignificant = char;
187
+ pendingControlParen = false;
188
+ }
189
+ return {
190
+ lastStatementStart: start,
191
+ lastStatementIsBlock: blockStarts.has(nextSignificantIndex(code, start)),
192
+ hasTopLevelReturn,
193
+ };
194
+ }
195
+
196
+ function isContinuationKeyword(code, index) {
197
+ if (!isIdentifierStart(code[index])) return false;
198
+ return STATEMENT_CONTINUATION_KEYWORDS.has(code.slice(index, readIdentifier(code, index)));
199
+ }
200
+
201
+ function isStatementContinuation(code, index, previousChar) {
202
+ const char = code[index];
203
+ if (char === "(" || char === "[" || char === "`") return previousChar !== "}" && previousChar !== "";
204
+ if (char === "!" || char === "~") return false;
205
+ if (char !== undefined && isDeclarationContinuation(char)) return true;
206
+ return isContinuationKeyword(code, index);
207
+ }
@@ -11,7 +11,8 @@ import {
11
11
  } from "../../bridge/reserved.ts";
12
12
  import { type KernelPreludePlan, KernelPreludeTracker } from "../shared/kernel-prelude-plan.ts";
13
13
  import type { JavaScriptKernelOptions as BaseJavaScriptKernelOptions } from "./kernel-contract.ts";
14
- import { hasDynamicCodeCapability, rewriteImports } from "./rewrite-imports.ts";
14
+ import { hasDynamicCodeCapability } from "./rewrite-imports.ts";
15
+ import { javaScriptCellSource } from "./typescript-cell.ts";
15
16
 
16
17
  const PREPARED_CELL_PREFIX = "/*senpi:prepared-cell*/";
17
18
 
@@ -19,6 +20,8 @@ export interface LocalModuleLoaderOptions {
19
20
  readonly cwd: string;
20
21
  readonly localRoots?: Readonly<Record<string, string>>;
21
22
  readonly artifactsDir?: string;
23
+ /** `jsCells.typescript`: run cells written in TypeScript with their types erased. */
24
+ readonly typescriptCells?: boolean;
22
25
  }
23
26
 
24
27
  export type JavaScriptKernelOptions = BaseJavaScriptKernelOptions & LocalModuleLoaderOptions;
@@ -139,11 +142,13 @@ function contributionPrelude(plan: KernelPreludePlan): string {
139
142
  export class LocalModuleLoader {
140
143
  readonly #prelude: string;
141
144
  readonly #cwdUrl: string;
145
+ readonly #typescriptCells: boolean;
142
146
  readonly #contributions = new KernelPreludeTracker();
143
147
 
144
148
  constructor(options: LocalModuleLoaderOptions) {
145
149
  this.#prelude = loaderPrelude(runtimeContext(options));
146
150
  this.#cwdUrl = directoryUrl(options.cwd);
151
+ this.#typescriptCells = options.typescriptCells === true;
147
152
  }
148
153
 
149
154
  prepareCell(
@@ -156,6 +161,6 @@ export class LocalModuleLoader {
156
161
  const cwdUrl = sourceFile === undefined ? this.#cwdUrl : directoryUrl(dirname(sourceFile));
157
162
  const base = `\nglobalThis.__senpi_module_context__ = { ...globalThis.__senpi_module_context__, cwdUrl: ${JSON.stringify(cwdUrl)}, packageRootUrl: ${JSON.stringify(packageRoot === undefined ? null : directoryUrl(packageRoot))} };`;
158
163
  const prelude = `${this.#prelude}${base}\n${contributionPrelude(this.#contributions.plan(contributions))}`;
159
- return `${PREPARED_CELL_PREFIX}${JSON.stringify({ prelude, code: rewriteImports(code), dynamicCodeCapability: hasDynamicCodeCapability(code), ...(sourceFile === undefined ? {} : { sourceFile }) })}`;
164
+ return `${PREPARED_CELL_PREFIX}${JSON.stringify({ prelude, code: javaScriptCellSource(code, this.#typescriptCells), dynamicCodeCapability: hasDynamicCodeCapability(code), ...(sourceFile === undefined ? {} : { sourceFile }) })}`;
160
165
  }
161
166
  }
@@ -0,0 +1,233 @@
1
+ import { isKernelGlobal } from "./worker-shadow-guard.js";
2
+ import { collectPatternNames, findTopLevelColon, findTopLevelEquals, splitPatternElements, trimPattern } from "./binding-patterns.js";
3
+ import { findDeclarationEnd, splitDeclarators } from "./declaration-extent.js";
4
+ import { IDENTIFIER_RE, REGEX_PREFIX_KEYWORDS, isDecimalDigit, isExpressionOperator, isIdentifierStart, isLineTerminator, readIdentifier, skipBlockComment, skipLineComment, skipNumberLiteral, skipQuotedLiteral, skipRegexLiteral, skipTemplateLiteral } from "./js-source-scan.js";
5
+
6
+ export const USER_SCOPE = "__senpiUserScope";
7
+
8
+ // The persistence rewrite itself writes through `globalThis`, so that one name cannot be shadowed.
9
+ const UNSHADOWABLE = new Set(["globalThis"]);
10
+
11
+ let shadowedNames = null;
12
+
13
+ function persistTarget(name) {
14
+ if (UNSHADOWABLE.has(name)) {
15
+ throw new Error(
16
+ `eval cell declares top-level \`${name}\`, which the JS kernel needs to keep cell variables between cells. Rename the binding (for example \`${name}Local\`).`,
17
+ );
18
+ }
19
+ if (!isKernelGlobal(name)) return `globalThis[${JSON.stringify(name)}]`;
20
+ if (shadowedNames !== null && !shadowedNames.includes(name)) shadowedNames.push(name);
21
+ return `${USER_SCOPE}[${JSON.stringify(name)}]`;
22
+ }
23
+
24
+ const DECLARATION_KEYWORDS = new Set(["const", "let", "var"]);
25
+
26
+ /**
27
+ * Rewrites top-level `const`/`let`/`var` onto `globalThis` (or the user scope for a kernel global) so later cells see
28
+ * them; `shadowed` receives the kernel-global names the cell declares. `using` declarations are not rewritten: they
29
+ * belong to the cell and are disposed when it ends.
30
+ */
31
+ export function persistTopLevelDeclarations(code, shadowed) {
32
+ shadowedNames = shadowed;
33
+ try {
34
+ return rewriteTopLevelDeclarations(code);
35
+ } finally {
36
+ shadowedNames = null;
37
+ }
38
+ }
39
+
40
+ function rewriteTopLevelDeclarations(code) {
41
+ const edits = [];
42
+ let round = 0;
43
+ let square = 0;
44
+ let curly = 0;
45
+ let statementStart = true;
46
+ let canStartRegex = true;
47
+
48
+ for (let index = 0; index < code.length; index += 1) {
49
+ const char = code[index];
50
+ const next = code[index + 1];
51
+ if (char === "/" && next === "/") {
52
+ index = skipLineComment(code, index) - 1;
53
+ continue;
54
+ }
55
+ if (char === "/" && next === "*") {
56
+ index = skipBlockComment(code, index) - 1;
57
+ continue;
58
+ }
59
+ if (char === "'" || char === '"') {
60
+ index = skipQuotedLiteral(code, index) - 1;
61
+ statementStart = false;
62
+ canStartRegex = false;
63
+ continue;
64
+ }
65
+ if (char === "`") {
66
+ index = skipTemplateLiteral(code, index) - 1;
67
+ statementStart = false;
68
+ canStartRegex = false;
69
+ continue;
70
+ }
71
+ if (char === "/" && canStartRegex) {
72
+ index = skipRegexLiteral(code, index) - 1;
73
+ statementStart = false;
74
+ canStartRegex = false;
75
+ continue;
76
+ }
77
+ if (isIdentifierStart(char)) {
78
+ const end = readIdentifier(code, index);
79
+ const token = code.slice(index, end);
80
+ if (round === 0 && square === 0 && curly === 0 && statementStart && DECLARATION_KEYWORDS.has(token)) {
81
+ const declarationEnd = findDeclarationEnd(code, end);
82
+ const replacement = rewriteDeclaration(code, index, end, declarationEnd, token);
83
+ if (replacement !== undefined) edits.push({ start: index, end: declarationEnd, text: replacement });
84
+ }
85
+ statementStart = false;
86
+ canStartRegex = REGEX_PREFIX_KEYWORDS.has(token);
87
+ index = end - 1;
88
+ continue;
89
+ }
90
+ if (isDecimalDigit(char)) {
91
+ index = skipNumberLiteral(code, index) - 1;
92
+ statementStart = false;
93
+ canStartRegex = false;
94
+ continue;
95
+ }
96
+ if (char === "(") {
97
+ round += 1;
98
+ statementStart = false;
99
+ canStartRegex = true;
100
+ continue;
101
+ }
102
+ if (char === ")") {
103
+ round = Math.max(0, round - 1);
104
+ statementStart = false;
105
+ canStartRegex = false;
106
+ continue;
107
+ }
108
+ if (char === "[") {
109
+ square += 1;
110
+ statementStart = false;
111
+ canStartRegex = true;
112
+ continue;
113
+ }
114
+ if (char === "]") {
115
+ square = Math.max(0, square - 1);
116
+ statementStart = false;
117
+ canStartRegex = false;
118
+ continue;
119
+ }
120
+ if (char === "{") {
121
+ curly += 1;
122
+ statementStart = false;
123
+ canStartRegex = true;
124
+ continue;
125
+ }
126
+ if (char === "}") {
127
+ curly = Math.max(0, curly - 1);
128
+ statementStart = curly === 0 && round === 0 && square === 0;
129
+ canStartRegex = false;
130
+ continue;
131
+ }
132
+ if (char === ";") {
133
+ statementStart = round === 0 && square === 0 && curly === 0;
134
+ canStartRegex = true;
135
+ continue;
136
+ }
137
+ if (isLineTerminator(char) && round === 0 && square === 0 && curly === 0) {
138
+ statementStart = true;
139
+ canStartRegex = true;
140
+ continue;
141
+ }
142
+ if (!/\s/u.test(char)) {
143
+ statementStart = false;
144
+ canStartRegex = isExpressionOperator(char);
145
+ }
146
+ }
147
+
148
+ return applyTextEdits(code, edits);
149
+ }
150
+
151
+ function rewriteDeclaration(code, declarationStart, start, end, keyword) {
152
+ const source = code.slice(declarationStart, end);
153
+ const assignments = [];
154
+ const preserveDeclaration = source.includes("//") || source.includes("/*");
155
+ for (const [segmentStart, segmentEnd] of splitDeclarators(code, start, end)) {
156
+ const segment = code.slice(segmentStart, segmentEnd);
157
+ if (!segment.trim()) return undefined;
158
+ const initializerStart = findTopLevelEquals(segment);
159
+ if (initializerStart < 0 && keyword === "const") return undefined;
160
+ const pattern = trimPattern(initializerStart < 0 ? segment : segment.slice(0, initializerStart));
161
+ const bindings = [];
162
+ collectPatternNames(pattern, bindings);
163
+ if (bindings.length === 0) return undefined;
164
+ if (preserveDeclaration) {
165
+ for (const name of bindings) assignments.push(`${persistTarget(name)} = ${name};`);
166
+ continue;
167
+ }
168
+ const target = rewriteBindingPattern(pattern);
169
+ if (target === undefined) return undefined;
170
+ const initializer = initializerStart < 0 ? "undefined" : segment.slice(initializerStart + 1).trim();
171
+ assignments.push(
172
+ `${target.startsWith("{") || target.startsWith("[") ? `;(${target} = ${initializer})` : `${target} = ${initializer}`};`,
173
+ );
174
+ }
175
+ if (assignments.length === 0) return undefined;
176
+ return preserveDeclaration ? `${source}\n${assignments.join("\n")}` : assignments.join("\n");
177
+ }
178
+
179
+ function rewriteBindingPattern(source) {
180
+ const pattern = trimPattern(source);
181
+ if (!pattern) return undefined;
182
+ const defaultStart = findTopLevelEquals(pattern);
183
+ if (defaultStart >= 0) {
184
+ const target = rewriteBindingPattern(pattern.slice(0, defaultStart));
185
+ return target === undefined ? undefined : `${target} = ${pattern.slice(defaultStart + 1).trim()}`;
186
+ }
187
+ if (IDENTIFIER_RE.test(pattern)) return persistTarget(pattern);
188
+ if (pattern.startsWith("{") && pattern.endsWith("}")) {
189
+ const properties = splitPatternElements(pattern.slice(1, -1)).map((property) => rewriteObjectBinding(property));
190
+ if (properties.some((property) => property === undefined)) return undefined;
191
+ return `{${properties.filter((property) => property !== undefined).join(", ")}}`;
192
+ }
193
+ if (pattern.startsWith("[") && pattern.endsWith("]")) {
194
+ const elements = splitPatternElements(pattern.slice(1, -1)).map((element) => {
195
+ if (!element.trim()) return "";
196
+ const rest = trimPattern(element).startsWith("...");
197
+ const target = rewriteBindingPattern(rest ? trimPattern(element).slice(3) : element);
198
+ return target === undefined ? undefined : rest ? `...${target}` : target;
199
+ });
200
+ if (elements.some((element) => element === undefined)) return undefined;
201
+ return `[${elements.join(", ")}]`;
202
+ }
203
+ return undefined;
204
+ }
205
+
206
+ function rewriteObjectBinding(source) {
207
+ const property = trimPattern(source);
208
+ if (!property) return "";
209
+ if (property.startsWith("...")) {
210
+ const target = rewriteBindingPattern(property.slice(3));
211
+ return target === undefined ? undefined : `...${target}`;
212
+ }
213
+ const initializerStart = findTopLevelEquals(property);
214
+ const colon = findTopLevelColon(property);
215
+ if (colon >= 0 && (initializerStart < 0 || colon < initializerStart)) {
216
+ const target = rewriteBindingPattern(property.slice(colon + 1));
217
+ return target === undefined ? undefined : `${property.slice(0, colon + 1).trim()} ${target}`;
218
+ }
219
+ if (initializerStart >= 0) {
220
+ const target = rewriteBindingPattern(property.slice(0, initializerStart));
221
+ return target === undefined ? undefined : `${property.slice(0, initializerStart).trim()}: ${target} = ${property.slice(initializerStart + 1).trim()}`;
222
+ }
223
+ const target = rewriteBindingPattern(property);
224
+ return target === undefined ? undefined : `${property}: ${target}`;
225
+ }
226
+
227
+ function applyTextEdits(code, edits) {
228
+ let output = code;
229
+ for (const edit of edits.toSorted((left, right) => right.start - left.start)) {
230
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
231
+ }
232
+ return output;
233
+ }
@@ -1,16 +1,9 @@
1
- import { parse } from "@babel/parser";
2
1
  import type { ImportDeclaration } from "@babel/types";
2
+ import { type AstNode, nodeFrom, parseCellProgram, walkNodes } from "./babel-ast.ts";
3
3
 
4
4
  const DYNAMIC_IMPORT_CALLEE =
5
5
  '(typeof __senpi_import__ === "function" ? __senpi_import__ : (specifier, options) => import(specifier, options))';
6
6
 
7
- type AstNode = {
8
- readonly type: string;
9
- readonly start: number;
10
- readonly end: number;
11
- readonly value: Readonly<Record<string, unknown>>;
12
- };
13
-
14
7
  type TextEdit = {
15
8
  readonly start: number;
16
9
  readonly end: number;
@@ -25,56 +18,6 @@ function assertNever(_value: never): never {
25
18
  throw new UnexpectedImportSpecifierError("Unsupported import specifier");
26
19
  }
27
20
 
28
- function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
29
- return value !== null && typeof value === "object" && !Array.isArray(value);
30
- }
31
-
32
- function nodeFrom(value: unknown): AstNode | undefined {
33
- if (!isRecord(value)) return undefined;
34
- const type = value.type;
35
- const start = value.start;
36
- const end = value.end;
37
- if (typeof type !== "string" || typeof start !== "number" || typeof end !== "number") return undefined;
38
- return { type, start, end, value };
39
- }
40
-
41
- function parseProgram(code: string): ReturnType<typeof parse> | undefined {
42
- try {
43
- return parse(code, {
44
- sourceType: "module",
45
- allowAwaitOutsideFunction: true,
46
- allowReturnOutsideFunction: true,
47
- allowImportExportEverywhere: true,
48
- allowNewTargetOutsideFunction: true,
49
- allowSuperOutsideMethod: true,
50
- allowUndeclaredExports: true,
51
- errorRecovery: true,
52
- plugins: ["typescript"],
53
- });
54
- } catch (error) {
55
- if (error instanceof SyntaxError) return undefined;
56
- throw error;
57
- }
58
- }
59
-
60
- function walkNodes(root: unknown, visit: (node: AstNode) => void): void {
61
- const stack: unknown[] = [root];
62
- while (stack.length > 0) {
63
- const current = stack.pop();
64
- if (Array.isArray(current)) {
65
- for (let index = current.length - 1; index >= 0; index -= 1) stack.push(current[index]);
66
- continue;
67
- }
68
- if (!isRecord(current)) continue;
69
- const node = nodeFrom(current);
70
- if (node) visit(node);
71
- for (const [key, value] of Object.entries(current)) {
72
- if (key === "loc" || key === "extra" || key === "range" || key.endsWith("Comments")) continue;
73
- if (value !== null && typeof value === "object") stack.push(value);
74
- }
75
- }
76
- }
77
-
78
21
  function importOptions(node: ImportDeclaration): string | undefined {
79
22
  if (!node.attributes || node.attributes.length === 0) return undefined;
80
23
  const pairs = node.attributes.map((attribute) => {
@@ -161,7 +104,7 @@ const DYNAMIC_IMPORT_SYNTAX = /\bimport\s*[(/]/u;
161
104
 
162
105
  export function rewriteImports(code: string): string {
163
106
  if (!IMPORT_SYNTAX.test(code)) return code;
164
- const ast = parseProgram(code);
107
+ const ast = parseCellProgram(code);
165
108
  if (!ast) return code;
166
109
  const edits: TextEdit[] = [];
167
110
 
@@ -181,7 +124,7 @@ export function rewriteImports(code: string): string {
181
124
  /** Host-side preflight: worker assets stay dependency-free, and direct eval keeps native lexical scope. */
182
125
  export function hasDynamicCodeCapability(code: string): boolean {
183
126
  if (!/\b(?:eval|Function|plugin)\b/u.test(code)) return false;
184
- const ast = parseProgram(code);
127
+ const ast = parseCellProgram(code);
185
128
  if (!ast) return false;
186
129
  let unsupported = false;
187
130
  walkNodes(ast.program, (node) => {
@@ -0,0 +1,39 @@
1
+ import { eraseTypeScript } from "./erase-types.ts";
2
+ import { rewriteImports } from "./rewrite-imports.ts";
3
+
4
+ const AsyncFunction: FunctionConstructor = Object.getPrototypeOf(async () => {}).constructor;
5
+
6
+ function compilesAsJavaScript(code: string): boolean {
7
+ try {
8
+ // oxlint-disable-next-line eslint/no-new-func -- compile-only probe: the function is never called.
9
+ new AsyncFunction(code);
10
+ return true;
11
+ } catch (error) {
12
+ if (error instanceof SyntaxError) return false;
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ const UNSUPPORTED_REMEDY =
18
+ "eval only erases types, so write it as JavaScript (a const object for an enum, assigned fields for a parameter property) or import it from a checked .ts module";
19
+
20
+ /**
21
+ * The cell text the JS kernel runs. With `typescript` on, a cell the engine rejects as JavaScript but Babel accepts as
22
+ * TypeScript runs with its types erased in place; valid JavaScript is never reinterpreted (`a < b > (c)` stays a
23
+ * comparison), and a cell that is neither keeps its source so the kernel reports the JavaScript syntax error.
24
+ */
25
+ export function javaScriptCellSource(code: string, typescript: boolean): string {
26
+ const rewritten = rewriteImports(code);
27
+ if (!typescript || compilesAsJavaScript(rewritten)) return rewritten;
28
+ const erasure = eraseTypeScript(code);
29
+ switch (erasure.kind) {
30
+ case "erased":
31
+ return rewriteImports(erasure.code);
32
+ case "invalid":
33
+ return rewritten;
34
+ case "unsupported": {
35
+ const message = `TypeScript ${erasure.construct} at line ${erasure.line}, column ${erasure.column} generates runtime code; ${UNSUPPORTED_REMEDY}.`;
36
+ return `throw new SyntaxError(${JSON.stringify(message)});`;
37
+ }
38
+ }
39
+ }
@@ -194,6 +194,7 @@ export function createWorkerCore(transport, options) {
194
194
  hostToolNames: message.hostToolNames ?? [],
195
195
  foreignLanguageNames: message.foreignLanguageNames ?? [],
196
196
  kernelToolsDisabled: message.kernelToolsDisabled === true,
197
+ scopeHelper: message.scopeHelper === true,
197
198
  ...(killGuard?.guard === undefined ? {} : { killGuard: killGuard.guard }),
198
199
  onChildEvent: (event) => emit({ type: "status", event: { op: CHILD_LIFECYCLE_OP, ...event } }),
199
200
  onShellWaitChange: () => {