@soleur/opencode 3.359.18 → 3.360.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/agents/product/design/ux-design-lead.md +49 -13
- package/package.json +1 -1
- package/skills/brainstorm/SKILL.md +3 -3
- package/skills/brainstorm/references/brainstorm-brand-workshop.md +17 -10
- package/skills/pencil-setup/SKILL.md +77 -27
- package/skills/pencil-setup/scripts/check_deps.sh +597 -132
- package/skills/pencil-setup/scripts/copy_adapter.sh +79 -11
- package/skills/pencil-setup/scripts/engine-contract-probe.sh +1132 -133
- package/skills/pencil-setup/scripts/pen-cli/package-lock.json +4359 -0
- package/skills/pencil-setup/scripts/pen-cli/package.json +13 -0
- package/skills/pencil-setup/scripts/pencil-error-enrichment.mjs +67 -14
- package/skills/pencil-setup/scripts/pencil-mcp-adapter.mjs +1283 -458
- package/skills/pencil-setup/scripts/pencil-repl-surface.mjs +377 -68
- package/skills/pencil-setup/scripts/pencil-response-classify.mjs +53 -12
- package/skills/pencil-setup/scripts/pencil-save-gate.mjs +484 -75
- package/skills/plan/SKILL.md +1 -1
|
@@ -1,15 +1,62 @@
|
|
|
1
1
|
// pencil-repl-surface.mjs — the REPL contract between the adapter and
|
|
2
|
-
// @
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// @pen.dev/cli (`pen interactive --out <f> [--in <f>]`, measured on 0.3.13), as
|
|
3
|
+
// pure functions so bun tests need no MCP SDK. Imports: node:crypto (the count nonce)
|
|
4
|
+
// and stripAnsi from pencil-response-classify.mjs (the one ANSI definition).
|
|
5
5
|
//
|
|
6
|
-
// Why this exists (#11143): the adapter sent `batch_design({ operations })`
|
|
7
|
-
// while the engine
|
|
8
|
-
//
|
|
9
|
-
// command line
|
|
10
|
-
// key that is not in
|
|
11
|
-
// `
|
|
12
|
-
//
|
|
6
|
+
// Why this exists (#11143): the adapter once sent `batch_design({ operations })`
|
|
7
|
+
// while the engine took `{ input }`; the engine dropped the unknown key and
|
|
8
|
+
// printed `OK`, so every design call "succeeded" and did nothing. Every REPL
|
|
9
|
+
// command line therefore flows through `formatReplCommand`, which refuses a
|
|
10
|
+
// tool or key that is not in the table below. The table is the signature list
|
|
11
|
+
// `pen interactive --help` prints for the REPL tools the adapter drives
|
|
12
|
+
// (`get_style` and `browser` exist in the engine but are deliberately absent:
|
|
13
|
+
// get_style was cut by CTO ruling 10, the adapter never emits browser).
|
|
14
|
+
// engine-contract-probe.sh diffs the table against the installed CLI on every
|
|
15
|
+
// pin bump; fixtures/pencil-stub-repl.mjs imports THIS table and prompt, so
|
|
16
|
+
// there is exactly one copy of the signature whitelist.
|
|
17
|
+
//
|
|
18
|
+
// Measured facts about the engine the adapter relies on (0.3.13):
|
|
19
|
+
// * The prompt is `pen > ` once ANSI is stripped. The engine colours it even
|
|
20
|
+
// on piped stdout: REPL_PROMPT_RAW is the exact byte string.
|
|
21
|
+
// * ERROR replies (`Error: ### Failure ...`, `[ERROR] ...`, `Save failed: ...`,
|
|
22
|
+
// `Unknown tool: ...`) arrive on STDERR; stdout carries only the blank line
|
|
23
|
+
// and the prompt. Success replies (`OK ...`, `Saved <path>`, app state) are
|
|
24
|
+
// on stdout. The adapter must merge both streams per command.
|
|
25
|
+
// * The `batch_design` aliases `I`/`U`/... do not exist inside `execute`;
|
|
26
|
+
// BATCH_DESIGN_PREAMBLE declares them with `var` on every call.
|
|
27
|
+
// * `--out` alone still loads an EMPTY document, so planSpawn keeps supplying
|
|
28
|
+
// `--in` for a non-empty `--out` (the #11143 hazard is unchanged).
|
|
29
|
+
//
|
|
30
|
+
// EXPORTS (the adapter wires these; do not re-implement them):
|
|
31
|
+
// ReplContractError thrown for every contract violation (never reaches the REPL)
|
|
32
|
+
// REPL_SURFACE frozen table: tool -> allowed keys (execute, get_app_state, read_skill, save)
|
|
33
|
+
// REPL_PROMPT / REPL_PROMPT_RAW `pen > ` after ANSI strip / the raw coloured bytes
|
|
34
|
+
// BATCH_DESIGN_PREAMBLE the `var I=Insert,...;` alias line
|
|
35
|
+
// NODE_FLOOR, compareVersions(a,b), nodeVersionOk(v) Node 22.19.0 numeric floor. The adapter
|
|
36
|
+
// cannot import this (its own gate runs before any import), so it
|
|
37
|
+
// carries an inline copy; a parity test pins the copies together
|
|
38
|
+
// with check_deps.sh's three NODE_FLOOR_* variables.
|
|
39
|
+
// formatReplCommand(tool, params) the ONE formatter (refuses unknown tool/key)
|
|
40
|
+
// buildBatchDesignCommand(operations) execute({ input: "<preamble>\n<ops>" })
|
|
41
|
+
// buildScreenshotCommand(nodeId) execute({ input: 'TakeScreenshot(["id"])' })
|
|
42
|
+
// buildExportCommand({nodeIds,outputDir,format,scale,quality}) execute Export(...)
|
|
43
|
+
// buildVariablesCommand() execute Print(GetVariables())
|
|
44
|
+
// buildEditorStateCommand() get_app_state()
|
|
45
|
+
// buildReadSkillCommand(path?) read_skill(...)
|
|
46
|
+
// buildSaveCommand() save() (tests and the probe; the adapter's one emission
|
|
47
|
+
// site is formatReplCommand("save", {}) inside guardedSave)
|
|
48
|
+
// newCountNonce(), buildCountSnippet(nonce), buildCountCommand(nonce) sentinel memory probe
|
|
49
|
+
// countSnippetNonce(input) recognises the snippet (the stub uses it)
|
|
50
|
+
// parseCountReply(text, nonce) -> integer | null exactly one `TOPLEVEL_COUNT:<nonce>:<n>` line
|
|
51
|
+
// validateNodeId/NodeIds/ExportFormat/Scale/Quality/SkillPath/OutputDir throw ReplContractError
|
|
52
|
+
// MAX_NODE_IDS, EXPORT_FORMATS
|
|
53
|
+
// redactionForms(secret), redactText(text, forms), createRollingRedactor(forms)
|
|
54
|
+
// a pure rolling-tail redactor: push(chunk) / flush()
|
|
55
|
+
// heldPrefixLength(text, forms) the unfinished credential prefix at the end of a reply
|
|
56
|
+
// planSpawn({outFile, initialInFile, resumeInFile, probe}) `--in` decision
|
|
57
|
+
|
|
58
|
+
import { randomBytes } from "node:crypto";
|
|
59
|
+
import { stripAnsi } from "./pencil-response-classify.mjs";
|
|
13
60
|
|
|
14
61
|
export class ReplContractError extends Error {
|
|
15
62
|
constructor(message) {
|
|
@@ -20,76 +67,61 @@ export class ReplContractError extends Error {
|
|
|
20
67
|
|
|
21
68
|
// tool -> allowed parameter keys. `save` is the REPL's own command and takes none.
|
|
22
69
|
export const REPL_SURFACE = Object.freeze({
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"parentId",
|
|
28
|
-
"patterns",
|
|
29
|
-
"readDepth",
|
|
30
|
-
"resolveInstances",
|
|
31
|
-
"resolveVariables",
|
|
32
|
-
"searchDepth",
|
|
33
|
-
],
|
|
34
|
-
export_html: [
|
|
35
|
-
"format",
|
|
36
|
-
"includeHtmlScaffold",
|
|
37
|
-
"includeLayerIds",
|
|
38
|
-
"includeLayerNames",
|
|
39
|
-
"nodeIds",
|
|
40
|
-
"outputPath",
|
|
41
|
-
],
|
|
42
|
-
export_nodes: ["format", "nodeIds", "outputDir", "quality", "scale"],
|
|
43
|
-
get_editor_state: ["include_schema"],
|
|
44
|
-
get_guidelines: ["category", "name", "params"],
|
|
45
|
-
get_screenshot: ["nodeId"],
|
|
46
|
-
get_variables: [],
|
|
47
|
-
save: [],
|
|
48
|
-
snapshot_layout: ["maxDepth", "parentId", "problemsOnly"],
|
|
70
|
+
execute: Object.freeze(["description", "editId", "edits", "input"]),
|
|
71
|
+
get_app_state: Object.freeze([]),
|
|
72
|
+
read_skill: Object.freeze(["path"]),
|
|
73
|
+
save: Object.freeze([]),
|
|
49
74
|
});
|
|
50
75
|
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
|
|
76
|
+
// Prompt after ANSI stripping, and the exact bytes the engine writes (it
|
|
77
|
+
// colours the prompt even when stdout is a pipe: measured on 0.3.13).
|
|
78
|
+
export const REPL_PROMPT = "pen > ";
|
|
79
|
+
export const REPL_PROMPT_RAW = "\x1b[36mpen\x1b[39m \x1b[2m>\x1b[22m ";
|
|
80
|
+
|
|
81
|
+
// `execute` does not define the short aliases Desktop-style scripts use
|
|
82
|
+
// (`I(...)`, `U(...)`: ReferenceError, measured). `var`, not `const`, so a
|
|
83
|
+
// preamble that runs on every call can re-declare them.
|
|
54
84
|
export const BATCH_DESIGN_PREAMBLE =
|
|
55
85
|
"var I=Insert,U=Update,C=Copy,R=Replace,M=Move,D=Delete,G=Generate;";
|
|
56
86
|
|
|
57
|
-
//
|
|
58
|
-
//
|
|
87
|
+
// @pen.dev/cli requires Node >= 22.19.0 (engines.node). Numeric compare:
|
|
88
|
+
// a string compare orders 22.9.0 after 22.19.0. The adapter's inline gate and
|
|
89
|
+
// check_deps.sh repeat these three numbers (parity test: pencil-repl-surface.test.ts).
|
|
90
|
+
export const NODE_FLOOR = Object.freeze([22, 19, 0]);
|
|
91
|
+
|
|
92
|
+
export function compareVersions(a, b) {
|
|
93
|
+
for (let i = 0; i < 3; i++) {
|
|
94
|
+
const x = Number(a[i] ?? 0);
|
|
95
|
+
const y = Number(b[i] ?? 0);
|
|
96
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
97
|
+
}
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function nodeVersionOk(version, floor = NODE_FLOOR) {
|
|
102
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version ?? ""));
|
|
103
|
+
if (!m) return false;
|
|
104
|
+
return compareVersions([Number(m[1]), Number(m[2]), Number(m[3])], floor) >= 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// JSON.stringify leaves DEL, the C1 range (U+0080..U+009F, which includes NEL
|
|
108
|
+
// U+0085) and U+2028/U+2029 literal; a line-splitting engine (readline treats
|
|
109
|
+
// some of them as line ends) would see one command as two. Escape them all.
|
|
110
|
+
// Written in escape notation (cq-regex-unicode-separators-escape-only).
|
|
59
111
|
function jsonLine(value) {
|
|
60
|
-
return JSON.stringify(value)
|
|
61
|
-
.
|
|
62
|
-
|
|
63
|
-
.replace(/\u2029/g, "\\u2029");
|
|
112
|
+
return JSON.stringify(value).replace(/[\u007f-\u009f\u2028\u2029]/g, (ch) =>
|
|
113
|
+
"\\u" + ch.charCodeAt(0).toString(16).padStart(4, "0")
|
|
114
|
+
);
|
|
64
115
|
}
|
|
65
116
|
|
|
66
117
|
export function formatReplCommand(toolName, params) {
|
|
67
118
|
if (!Object.hasOwn(REPL_SURFACE, toolName)) {
|
|
68
|
-
throw new ReplContractError(
|
|
69
|
-
`Unknown tool: ${toolName} (not in the @pencil.dev/cli 0.2.9 REPL surface)`
|
|
70
|
-
);
|
|
119
|
+
throw new ReplContractError(`Unknown tool: ${toolName} (not in the @pen.dev/cli REPL surface)`);
|
|
71
120
|
}
|
|
72
121
|
const given = {};
|
|
73
122
|
for (const [k, v] of Object.entries(params ?? {})) {
|
|
74
123
|
if (v !== undefined) given[k] = v;
|
|
75
124
|
}
|
|
76
|
-
|
|
77
|
-
if (toolName === "batch_design") {
|
|
78
|
-
const keys = Object.keys(given);
|
|
79
|
-
// The adapter's MCP schema calls the field `operations`; the engine calls
|
|
80
|
-
// it `input`. Accept only the former here so the two can never both be sent.
|
|
81
|
-
for (const k of keys) {
|
|
82
|
-
if (k !== "operations") {
|
|
83
|
-
throw new ReplContractError(`batch_design: unexpected parameter '${k}' (only 'operations' is accepted)`);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
const ops = given.operations;
|
|
87
|
-
if (typeof ops !== "string" || ops.trim() === "") {
|
|
88
|
-
throw new ReplContractError("batch_design: 'operations' must be a non-empty string");
|
|
89
|
-
}
|
|
90
|
-
return `batch_design({ input: ${jsonLine(`${BATCH_DESIGN_PREAMBLE}\n${ops}`)} })`;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
125
|
const allowed = REPL_SURFACE[toolName];
|
|
94
126
|
for (const k of Object.keys(given)) {
|
|
95
127
|
if (!allowed.includes(k)) {
|
|
@@ -98,19 +130,296 @@ export function formatReplCommand(toolName, params) {
|
|
|
98
130
|
);
|
|
99
131
|
}
|
|
100
132
|
}
|
|
133
|
+
|
|
134
|
+
if (toolName === "execute") {
|
|
135
|
+
if (!("input" in given) && !("edits" in given)) {
|
|
136
|
+
throw new ReplContractError("execute: 'input' must be a non-empty string");
|
|
137
|
+
}
|
|
138
|
+
if ("input" in given && (typeof given.input !== "string" || given.input.trim() === "")) {
|
|
139
|
+
throw new ReplContractError("execute: 'input' must be a non-empty string");
|
|
140
|
+
}
|
|
141
|
+
const keys = Object.keys(given);
|
|
142
|
+
if (keys.length === 1 && keys[0] === "input") return `execute({ input: ${jsonLine(given.input)} })`;
|
|
143
|
+
return `execute(${jsonLine(given)})`;
|
|
144
|
+
}
|
|
145
|
+
|
|
101
146
|
if (Object.keys(given).length === 0) return `${toolName}()`;
|
|
102
147
|
return `${toolName}(${jsonLine(given)})`;
|
|
103
148
|
}
|
|
104
149
|
|
|
105
|
-
//
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// Validators. Everything the agent controls is checked here before it is
|
|
152
|
+
// embedded in an `execute` snippet or handed to the engine.
|
|
153
|
+
|
|
154
|
+
export const NODE_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
|
|
155
|
+
export const MAX_NODE_IDS = 50;
|
|
156
|
+
export const EXPORT_FORMATS = Object.freeze(["png", "jpeg", "webp", "pdf"]);
|
|
157
|
+
const SKILL_PATH_RE = /^(guide\/)?[a-z0-9-]+\.md$/;
|
|
158
|
+
const MAX_SKILL_PATH = 100;
|
|
159
|
+
const MAX_OUTPUT_DIR = 4096;
|
|
160
|
+
|
|
161
|
+
export function validateNodeId(id) {
|
|
162
|
+
if (typeof id !== "string" || !NODE_ID_RE.test(id)) {
|
|
163
|
+
throw new ReplContractError("node id must match ^[A-Za-z0-9_-]{1,100}$");
|
|
164
|
+
}
|
|
165
|
+
return id;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function validateNodeIds(ids) {
|
|
169
|
+
if (!Array.isArray(ids) || ids.length < 1 || ids.length > MAX_NODE_IDS) {
|
|
170
|
+
throw new ReplContractError(`nodeIds must be an array of 1 to ${MAX_NODE_IDS} ids`);
|
|
171
|
+
}
|
|
172
|
+
return ids.map(validateNodeId);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function validateExportFormat(format) {
|
|
176
|
+
if (format === undefined) return "png";
|
|
177
|
+
if (typeof format !== "string" || !EXPORT_FORMATS.includes(format)) {
|
|
178
|
+
throw new ReplContractError(`format must be one of ${EXPORT_FORMATS.join(", ")}`);
|
|
179
|
+
}
|
|
180
|
+
return format;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function validateScale(scale) {
|
|
184
|
+
if (scale === undefined) return undefined;
|
|
185
|
+
if (typeof scale !== "number" || !Number.isFinite(scale) || scale < 0.1 || scale > 8) {
|
|
186
|
+
throw new ReplContractError("scale must be a finite number from 0.1 to 8");
|
|
187
|
+
}
|
|
188
|
+
return scale;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function validateQuality(quality) {
|
|
192
|
+
if (quality === undefined) return undefined;
|
|
193
|
+
if (typeof quality !== "number" || !Number.isInteger(quality) || quality < 1 || quality > 100) {
|
|
194
|
+
throw new ReplContractError("quality must be an integer from 1 to 100");
|
|
195
|
+
}
|
|
196
|
+
return quality;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function validateSkillPath(path) {
|
|
200
|
+
if (path === undefined) return undefined;
|
|
201
|
+
if (typeof path !== "string" || path.length > MAX_SKILL_PATH || !SKILL_PATH_RE.test(path)) {
|
|
202
|
+
throw new ReplContractError("read_skill path must match ^(guide/)?[a-z0-9-]+\\.md$");
|
|
203
|
+
}
|
|
204
|
+
return path;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Shape only (absolute, bounded, no control characters). Containment inside the
|
|
208
|
+
// allowed roots, symlink refusal and mkdir are the adapter's containedDir().
|
|
209
|
+
export function validateOutputDir(dir) {
|
|
210
|
+
const ok =
|
|
211
|
+
typeof dir === "string" &&
|
|
212
|
+
dir.length > 0 &&
|
|
213
|
+
dir.length <= MAX_OUTPUT_DIR &&
|
|
214
|
+
(dir.startsWith("/") || /^[A-Za-z]:[\\/]/.test(dir)) &&
|
|
215
|
+
!/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(dir);
|
|
216
|
+
if (!ok) {
|
|
217
|
+
throw new ReplContractError("outputDir must be an absolute path (no control characters, at most 4096 chars)");
|
|
218
|
+
}
|
|
219
|
+
return dir;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
// Builders: each returns one REPL line.
|
|
224
|
+
|
|
225
|
+
export function buildBatchDesignCommand(operations) {
|
|
226
|
+
if (typeof operations !== "string" || operations.trim() === "") {
|
|
227
|
+
throw new ReplContractError("batch_design: 'operations' must be a non-empty string");
|
|
228
|
+
}
|
|
229
|
+
return formatReplCommand("execute", { input: `${BATCH_DESIGN_PREAMBLE}\n${operations}` });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function buildScreenshotCommand(nodeId) {
|
|
233
|
+
const id = validateNodeId(nodeId);
|
|
234
|
+
return formatReplCommand("execute", { input: `TakeScreenshot([${JSON.stringify(id)}])` });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function buildExportCommand({ nodeIds, outputDir, format, scale, quality } = {}) {
|
|
238
|
+
const ids = validateNodeIds(nodeIds);
|
|
239
|
+
const fmt = validateExportFormat(format);
|
|
240
|
+
const dir = validateOutputDir(outputDir);
|
|
241
|
+
const options = {};
|
|
242
|
+
const s = validateScale(scale);
|
|
243
|
+
const q = validateQuality(quality);
|
|
244
|
+
if (s !== undefined) options.scale = s;
|
|
245
|
+
if (q !== undefined) options.quality = q;
|
|
246
|
+
const tail = Object.keys(options).length > 0 ? `,${JSON.stringify(options)}` : "";
|
|
247
|
+
return formatReplCommand("execute", {
|
|
248
|
+
input: `Export(${JSON.stringify(ids)},${JSON.stringify(fmt)},${JSON.stringify(dir)}${tail})`,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function buildVariablesCommand() {
|
|
253
|
+
return formatReplCommand("execute", { input: "Print(GetVariables())" });
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function buildEditorStateCommand() {
|
|
257
|
+
return formatReplCommand("get_app_state", {});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function buildReadSkillCommand(path) {
|
|
261
|
+
const p = validateSkillPath(path);
|
|
262
|
+
return formatReplCommand("read_skill", p === undefined ? {} : { path: p });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function buildSaveCommand() {
|
|
266
|
+
return formatReplCommand("save", {});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
// Sentinel memory probe: a read-only snippet that prints the number of
|
|
271
|
+
// top-level nodes tagged with a per-call nonce, so text from a previous reply
|
|
272
|
+
// (a node name, a read_skill page) cannot forge it.
|
|
273
|
+
|
|
274
|
+
const NONCE_RE = /^[0-9a-f]{32}$/;
|
|
275
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
276
|
+
// One self-contained IIFE using only Get and Print: a prior script that declared
|
|
277
|
+
// `var n,c,Print` or left globals behind cannot change what it counts. The
|
|
278
|
+
// literal is split so that the source echoed back in an engine error never
|
|
279
|
+
// contains a complete count line.
|
|
280
|
+
const COUNT_PRE = '(function(){var k=0;Get(function(n,c){c.skipChildren();k++;});Print("TOPLEVEL_COUNT:"+"';
|
|
281
|
+
const COUNT_POST = '"+":"+k);})();';
|
|
282
|
+
const COUNT_SNIPPET_RE = new RegExp(`^${escapeRe(COUNT_PRE)}([0-9a-f]{32})${escapeRe(COUNT_POST)}$`);
|
|
283
|
+
|
|
284
|
+
export function newCountNonce() {
|
|
285
|
+
return randomBytes(16).toString("hex");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function buildCountSnippet(nonce) {
|
|
289
|
+
if (typeof nonce !== "string" || !NONCE_RE.test(nonce)) {
|
|
290
|
+
throw new ReplContractError("count nonce must be 32 lowercase hex characters");
|
|
291
|
+
}
|
|
292
|
+
return `${COUNT_PRE}${nonce}${COUNT_POST}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export function buildCountCommand(nonce) {
|
|
296
|
+
return formatReplCommand("execute", { input: buildCountSnippet(nonce) });
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// The nonce when `input` is exactly the adapter's count snippet, else null.
|
|
300
|
+
export function countSnippetNonce(input) {
|
|
301
|
+
const m = COUNT_SNIPPET_RE.exec(String(input ?? ""));
|
|
302
|
+
return m ? m[1] : null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// The top-level node count carried by a reply to the count snippet, or null.
|
|
306
|
+
// Exactly one line `TOPLEVEL_COUNT:<this nonce>:<digits>` on an `OK` reply;
|
|
307
|
+
// zero lines, two lines, another nonce or an error reply all give null.
|
|
308
|
+
export function parseCountReply(text, nonce) {
|
|
309
|
+
if (typeof nonce !== "string" || !NONCE_RE.test(nonce)) return null;
|
|
310
|
+
const lines = stripAnsi(String(text ?? "")).split(/\r?\n/);
|
|
311
|
+
const first = lines.find((l) => l.trim() !== "");
|
|
312
|
+
if (first === undefined || first.trim() !== "OK") return null;
|
|
313
|
+
const re = new RegExp(`^TOPLEVEL_COUNT:${nonce}:(\\d{1,9})$`);
|
|
314
|
+
const hits = lines.filter((l) => re.test(l));
|
|
315
|
+
if (hits.length !== 1) return null;
|
|
316
|
+
return Number(re.exec(hits[0])[1]);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ---------------------------------------------------------------------------
|
|
320
|
+
// Redaction. `redactionForms` lists the spellings a credential can take in
|
|
321
|
+
// engine output; the rolling redactor holds back a tail so a value split
|
|
322
|
+
// across two stderr chunks is still replaced.
|
|
323
|
+
|
|
324
|
+
const REDACTED = "<redacted>";
|
|
325
|
+
const MIN_FORM_LENGTH = 4;
|
|
326
|
+
|
|
327
|
+
export function redactionForms(secret) {
|
|
328
|
+
if (typeof secret !== "string") return [];
|
|
329
|
+
const trimmed = secret.trim();
|
|
330
|
+
if (trimmed.length < MIN_FORM_LENGTH) return [];
|
|
331
|
+
const b64 = Buffer.from(trimmed).toString("base64");
|
|
332
|
+
const candidates = [
|
|
333
|
+
secret,
|
|
334
|
+
trimmed,
|
|
335
|
+
JSON.stringify(trimmed).slice(1, -1),
|
|
336
|
+
encodeURIComponent(trimmed),
|
|
337
|
+
b64,
|
|
338
|
+
b64.replace(/=+$/, ""),
|
|
339
|
+
b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""),
|
|
340
|
+
];
|
|
341
|
+
const forms = [...new Set(candidates)].filter((f) => f.length >= MIN_FORM_LENGTH);
|
|
342
|
+
return forms.sort((a, b) => b.length - a.length);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export function redactText(text, forms) {
|
|
346
|
+
let out = String(text ?? "");
|
|
347
|
+
for (const form of forms ?? []) {
|
|
348
|
+
if (form) out = out.split(form).join(REDACTED);
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// How many characters at the END of `text` are the start of a credential spelling that has
|
|
354
|
+
// not finished (a proper prefix of a form, at least MIN_FORM_LENGTH long): the part of a
|
|
355
|
+
// reply that must not be shown until the next piece proves it is not the rest of the key.
|
|
356
|
+
export function heldPrefixLength(text, forms) {
|
|
357
|
+
const s = String(text ?? "");
|
|
358
|
+
let best = 0;
|
|
359
|
+
for (const form of forms ?? []) {
|
|
360
|
+
if (!form) continue;
|
|
361
|
+
for (let k = Math.min(form.length - 1, s.length); k >= Math.max(MIN_FORM_LENGTH, best + 1); k--) {
|
|
362
|
+
if (s.endsWith(form.slice(0, k))) {
|
|
363
|
+
best = k;
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return best;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// push(chunk) returns the text that is safe to emit now; flush() returns the
|
|
372
|
+
// held-back tail (call it when the stream ends). Holds back at most
|
|
373
|
+
// (longest form - 1) characters, and never cuts through a match.
|
|
374
|
+
export function createRollingRedactor(forms) {
|
|
375
|
+
const list = [...(forms ?? [])].filter(Boolean).sort((a, b) => b.length - a.length);
|
|
376
|
+
const hold = list.length === 0 ? 0 : list[0].length - 1;
|
|
377
|
+
let pending = "";
|
|
378
|
+
|
|
379
|
+
const spansOf = (s) => {
|
|
380
|
+
const spans = [];
|
|
381
|
+
let i = 0;
|
|
382
|
+
while (i < s.length) {
|
|
383
|
+
const form = list.find((f) => s.startsWith(f, i));
|
|
384
|
+
if (form) {
|
|
385
|
+
spans.push([i, i + form.length]);
|
|
386
|
+
i += form.length;
|
|
387
|
+
} else {
|
|
388
|
+
i++;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return spans;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
push(chunk) {
|
|
396
|
+
const s = pending + String(chunk ?? "");
|
|
397
|
+
if (list.length === 0) return s;
|
|
398
|
+
let cut = Math.max(0, s.length - hold);
|
|
399
|
+
for (const [start, end] of spansOf(s)) {
|
|
400
|
+
if (start < cut && cut < end) cut = start;
|
|
401
|
+
}
|
|
402
|
+
pending = s.slice(cut);
|
|
403
|
+
return redactText(s.slice(0, cut), list);
|
|
404
|
+
},
|
|
405
|
+
flush() {
|
|
406
|
+
const rest = redactText(pending, list);
|
|
407
|
+
pending = "";
|
|
408
|
+
return rest;
|
|
409
|
+
},
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ---------------------------------------------------------------------------
|
|
414
|
+
// Decide the `--in` argument for one spawn of `pen interactive --out <outFile>`.
|
|
106
415
|
//
|
|
107
416
|
// `initialInFile` is the caller's explicit input (a template). The adapter
|
|
108
417
|
// passes it for the open_document spawn only and passes none on a respawn, so a
|
|
109
418
|
// respawn after a crash reloads `outFile` and a template can never overwrite
|
|
110
419
|
// saved edits.
|
|
111
420
|
// Without an explicit input, an existing non-empty `outFile` is reloaded:
|
|
112
|
-
//
|
|
113
|
-
//
|
|
421
|
+
// `--out` alone starts an EMPTY document and the next save would replace the
|
|
422
|
+
// file with 96 bytes (#11143; re-measured unchanged on 0.3.13).
|
|
114
423
|
//
|
|
115
424
|
// `resumeInFile` is the template a previous spawn of the SAME target loaded
|
|
116
425
|
// from. It applies only while `outFile` holds nothing saved: a child that dies
|
|
@@ -1,41 +1,82 @@
|
|
|
1
|
-
// pencil-response-classify.mjs — pure response classifier for the
|
|
1
|
+
// pencil-response-classify.mjs — pure response classifier for the pen.dev REPL
|
|
2
|
+
// (@pen.dev/cli 0.3.13).
|
|
2
3
|
// Extracted so it can be unit-tested without importing the adapter (which
|
|
3
4
|
// pulls in @modelcontextprotocol/sdk and cannot load in a bare test env).
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
// CSI sequences: any parameter bytes (digits, `;`, `:` and the private prefixes `<=>?`) and
|
|
7
|
+
// any final byte (`@`..`~`), so `ESC[?25l`, `ESC[38:2:1:2:3m` and `ESC[3~` all go. THE one
|
|
8
|
+
// definition: the adapter, the save gate and the REPL surface import stripAnsi from here.
|
|
9
|
+
const ANSI_ESCAPE = /\x1b\[[0-9;?:<=>]*[@-~]/g;
|
|
6
10
|
|
|
7
11
|
// REPL responses are bounded in practice. Cap before classification so a
|
|
8
12
|
// pathological multi-MB response can't spin the `^`-anchored multiline
|
|
9
13
|
// regexes over an arbitrarily long scan.
|
|
10
14
|
const CLASSIFY_MAX_BYTES = 64 * 1024;
|
|
11
15
|
|
|
16
|
+
// @pen.dev/cli 0.3.13 prints every failure on stderr, wrapped in colour codes
|
|
17
|
+
// (stripped before these run): red `Error: ### Failure during operation
|
|
18
|
+
// execution` plus `[ERROR] ...` lines, red `Save failed: <reason>`, yellow
|
|
19
|
+
// `Unknown tool: <name>`. All are anchored to a line start so a node name echoed
|
|
20
|
+
// back in a reply cannot trip them mid-line.
|
|
12
21
|
const ERROR_PATTERNS = [
|
|
13
22
|
/^Error:/m,
|
|
14
23
|
/^\[ERROR\]/m,
|
|
15
24
|
/^Invalid properties:/m,
|
|
16
|
-
//
|
|
17
|
-
//
|
|
25
|
+
// A tool the engine does not have. It once classified as success and the
|
|
26
|
+
// auto-save ran after it (#11143).
|
|
18
27
|
/^Unknown tool:/m,
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
//
|
|
22
|
-
// or a
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
/`pencil login`/i,
|
|
28
|
+
// A failed save prints only this line (no `Saved`, no `[ERROR]`).
|
|
29
|
+
/^Save failed:/m,
|
|
30
|
+
// Auth-failure responses. Start-of-line anchored (multiline flag) so a node
|
|
31
|
+
// name echoed back ("Unauthorized state") or a frame title cannot trip the
|
|
32
|
+
// gate. The engine's own `[ERROR] Authentication required ...` line is
|
|
33
|
+
// already covered by the `[ERROR]` pattern above.
|
|
26
34
|
/^Invalid API key\b/im,
|
|
27
35
|
/^Unauthorized\b/im,
|
|
28
36
|
/^HTTP 401\b/im,
|
|
29
37
|
];
|
|
30
38
|
|
|
39
|
+
// A successful `execute` reply starts with `OK`, a get_app_state reply with its
|
|
40
|
+
// title; neither can be an error. Their later `## ...` sections carry text the
|
|
41
|
+
// agent controls (node names, printed values), and a node name containing a
|
|
42
|
+
// newline can put `Error:` at a line start, so only the header part before the
|
|
43
|
+
// first section is scanned for those two shapes.
|
|
44
|
+
function scannedPart(text) {
|
|
45
|
+
const first = text.split("\n", 1)[0].trim();
|
|
46
|
+
if (first !== "OK" && first !== "# Current App State") return text;
|
|
47
|
+
const section = text.search(/\n## /);
|
|
48
|
+
return section === -1 ? text : text.slice(0, section);
|
|
49
|
+
}
|
|
50
|
+
|
|
31
51
|
export function stripAnsi(str) {
|
|
32
52
|
return str.replace(ANSI_ESCAPE, "");
|
|
33
53
|
}
|
|
34
54
|
|
|
55
|
+
// A stream stripper for chunked output: an escape sequence cut at a chunk boundary is held and
|
|
56
|
+
// finished by the next chunk, so no half sequence is left to split a credential across the
|
|
57
|
+
// pieces a redactor sees. push(chunk) returns the stripped text that is complete now; the
|
|
58
|
+
// unfinished tail (at most a few bytes of one escape) is dropped at the end of the stream.
|
|
59
|
+
export function createAnsiStripper() {
|
|
60
|
+
let carry = "";
|
|
61
|
+
return {
|
|
62
|
+
push(chunk) {
|
|
63
|
+
const text = stripAnsi(carry + String(chunk ?? ""));
|
|
64
|
+
carry = "";
|
|
65
|
+
const i = text.lastIndexOf("\x1b");
|
|
66
|
+
if (i !== -1 && text.length - i <= 64 && /^\x1b(\[[0-9;?:<=>]*)?$/.test(text.slice(i))) {
|
|
67
|
+
carry = text.slice(i);
|
|
68
|
+
return text.slice(0, i);
|
|
69
|
+
}
|
|
70
|
+
return text;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
35
75
|
export function classifyResponse(raw) {
|
|
36
76
|
const input = String(raw ?? "");
|
|
37
77
|
const bounded = input.length > CLASSIFY_MAX_BYTES ? input.slice(0, CLASSIFY_MAX_BYTES) : input;
|
|
38
78
|
const text = stripAnsi(bounded).trim();
|
|
39
|
-
const
|
|
79
|
+
const scanned = scannedPart(text);
|
|
80
|
+
const isError = ERROR_PATTERNS.some((pattern) => pattern.test(scanned));
|
|
40
81
|
return { text, isError };
|
|
41
82
|
}
|