@sayknow-cli/coding-agent 0.7.19 → 0.7.20

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.
@@ -0,0 +1,330 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ClientBridge,
4
+ ClientBridgePermissionOption,
5
+ ClientBridgePermissionOutcome,
6
+ ClientBridgePermissionToolCall,
7
+ } from "../../session/client-bridge";
8
+ import type { ControlSurface } from "./control/operations";
9
+
10
+ const DEFAULT_TIMEOUT_MS = 60_000;
11
+ const DEFAULT_MAX_PENDING = 64;
12
+ const MAX_PAYLOAD_BYTES = 256 * 1024;
13
+ const MAX_AGGREGATE_REQUEST_BYTES = 192 * 1024;
14
+ const MAX_COMMENT_LENGTH = 4096;
15
+
16
+ type PermissionOutcome = ClientBridgePermissionOutcome;
17
+
18
+ export interface ExternalPermissionChannelInput {
19
+ enabled: boolean;
20
+ }
21
+
22
+ export interface ExternalPermissionResponseInput {
23
+ sessionId: string;
24
+ id: string;
25
+ optionId: string;
26
+ comment?: string;
27
+ }
28
+
29
+ export interface ExternalPermissionRequest {
30
+ id: string;
31
+ sessionId: string;
32
+ toolCall: ClientBridgePermissionToolCall;
33
+ options: ClientBridgePermissionOption[];
34
+ expiresAt: string;
35
+ }
36
+
37
+ export class ExternalPermissionError extends Error {
38
+ constructor(
39
+ readonly code: "invalid_input" | "resource_gone" | "too_many_outstanding" | "payload_too_large",
40
+ message: string,
41
+ ) {
42
+ super(message);
43
+ this.name = "ExternalPermissionError";
44
+ }
45
+ }
46
+
47
+ type PendingRequest = {
48
+ request: ExternalPermissionRequest;
49
+ resolve: (outcome: PermissionOutcome) => void;
50
+ timer: Timer;
51
+ signal?: AbortSignal;
52
+ onAbort?: () => void;
53
+ };
54
+
55
+ function invalid(message: string): never {
56
+ throw new ExternalPermissionError("invalid_input", message);
57
+ }
58
+
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return (
61
+ typeof value === "object" &&
62
+ value !== null &&
63
+ !Array.isArray(value) &&
64
+ Object.getPrototypeOf(value) === Object.prototype
65
+ );
66
+ }
67
+
68
+ function exactKeys(value: Record<string, unknown>, required: string[], optional: string[] = []): boolean {
69
+ const keys = Object.keys(value);
70
+ return (
71
+ required.every(key => Object.hasOwn(value, key)) &&
72
+ keys.every(key => required.includes(key) || optional.includes(key))
73
+ );
74
+ }
75
+
76
+ function jsonSnapshot<T>(value: T): T {
77
+ const seen = new Set<object>();
78
+ const validate = (item: unknown, depth: number): void => {
79
+ if (depth > 64) invalid("Permission payload is too deeply nested");
80
+ if (item === null || typeof item === "string" || typeof item === "boolean") return;
81
+ if (typeof item === "number" && Number.isFinite(item)) return;
82
+ if (typeof item !== "object") invalid("Permission payload must contain only JSON values");
83
+ if (seen.has(item)) invalid("Permission payload must not contain cycles");
84
+ seen.add(item);
85
+ if (!Array.isArray(item) && !isRecord(item)) invalid("Permission payload objects must be plain JSON objects");
86
+ for (const child of Array.isArray(item) ? item : Object.values(item)) validate(child, depth + 1);
87
+ seen.delete(item);
88
+ };
89
+ validate(value, 0);
90
+ let encoded: string;
91
+ try {
92
+ encoded = JSON.stringify(value);
93
+ } catch {
94
+ return invalid("Permission payload is not valid JSON");
95
+ }
96
+ if (new TextEncoder().encode(encoded).byteLength > MAX_PAYLOAD_BYTES) {
97
+ throw new ExternalPermissionError("payload_too_large", "Permission payload exceeds 256 KB");
98
+ }
99
+ return JSON.parse(encoded) as T;
100
+ }
101
+
102
+ function nonEmptyBoundedString(value: unknown, _field: string, max = 4096): value is string {
103
+ return typeof value === "string" && value.length > 0 && value.length <= max;
104
+ }
105
+
106
+ function snapshotToolCall(value: ClientBridgePermissionToolCall): ClientBridgePermissionToolCall {
107
+ if (
108
+ !isRecord(value) ||
109
+ !nonEmptyBoundedString(value.toolCallId, "toolCallId", 512) ||
110
+ !nonEmptyBoundedString(value.toolName, "toolName", 512) ||
111
+ !nonEmptyBoundedString(value.title, "title", 4096)
112
+ ) {
113
+ return invalid("Invalid permission tool call");
114
+ }
115
+ if (value.kind !== undefined && !nonEmptyBoundedString(value.kind, "kind", 512))
116
+ invalid("Invalid permission tool call kind");
117
+ if (value.status !== undefined && !["pending", "in_progress", "completed", "failed"].includes(String(value.status)))
118
+ invalid("Invalid permission tool call status");
119
+ if (value.content !== undefined && !Array.isArray(value.content)) invalid("Invalid permission tool call content");
120
+ if (
121
+ value.locations !== undefined &&
122
+ (!Array.isArray(value.locations) ||
123
+ value.locations.some(
124
+ location =>
125
+ !isRecord(location) ||
126
+ !nonEmptyBoundedString(location.path, "location.path", 4096) ||
127
+ (location.line !== undefined && (!Number.isSafeInteger(location.line) || Number(location.line) < 1)),
128
+ ))
129
+ ) {
130
+ invalid("Invalid permission tool call locations");
131
+ }
132
+ const snapshot = jsonSnapshot(value);
133
+ const allowed = new Set(["toolCallId", "toolName", "title", "kind", "status", "rawInput", "content", "locations"]);
134
+ if (Object.keys(snapshot).some(key => !allowed.has(key))) invalid("Unexpected permission tool call field");
135
+ return snapshot;
136
+ }
137
+
138
+ function snapshotOptions(value: ClientBridgePermissionOption[]): ClientBridgePermissionOption[] {
139
+ if (!Array.isArray(value) || value.length === 0 || value.length > 64) invalid("Invalid permission options");
140
+ const seen = new Set<string>();
141
+ const normalized = value.map(option => {
142
+ if (
143
+ !isRecord(option) ||
144
+ !exactKeys(option, ["optionId", "name", "kind"]) ||
145
+ !nonEmptyBoundedString(option.optionId, "optionId", 512) ||
146
+ !nonEmptyBoundedString(option.name, "name", 1024) ||
147
+ !["allow_once", "allow_always", "reject_once", "reject_always"].includes(String(option.kind))
148
+ ) {
149
+ return invalid("Invalid permission option");
150
+ }
151
+ if (seen.has(option.optionId)) invalid("Permission option IDs must be unique");
152
+ seen.add(option.optionId);
153
+ return { optionId: option.optionId, name: option.name, kind: option.kind } as ClientBridgePermissionOption;
154
+ });
155
+ return jsonSnapshot(normalized);
156
+ }
157
+
158
+ export class ExternalPermissionRuntime {
159
+ readonly #sessionId: string;
160
+ readonly #timeoutMs: number;
161
+ readonly #maxPending: number;
162
+ readonly #pending = new Map<string, PendingRequest>();
163
+ #enabled = false;
164
+ #disposed = false;
165
+
166
+ constructor(sessionId: string, options: { timeoutMs?: number; maxPending?: number } = {}) {
167
+ if (!nonEmptyBoundedString(sessionId, "sessionId", 512)) invalid("Invalid session ID");
168
+ if (!isRecord(options) || !exactKeys(options, [], ["timeoutMs", "maxPending"]))
169
+ invalid("Invalid runtime options");
170
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
171
+ const maxPending = options.maxPending ?? DEFAULT_MAX_PENDING;
172
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) invalid("Invalid timeoutMs");
173
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1 || maxPending > 1024) invalid("Invalid maxPending");
174
+ this.#sessionId = sessionId;
175
+ this.#timeoutMs = timeoutMs;
176
+ this.#maxPending = maxPending;
177
+ }
178
+
179
+ get enabled(): boolean {
180
+ return this.#enabled;
181
+ }
182
+
183
+ installControls(
184
+ surface: Pick<ControlSurface, "setPermissionMode" | "configurePermissionChannel" | "respondPermission">,
185
+ setProvider: (provider: ClientBridge["requestPermission"]) => void,
186
+ hasReverseProvider: () => boolean,
187
+ ): void {
188
+ const setPermissionMode = surface.setPermissionMode;
189
+ surface.setPermissionMode = async mode => {
190
+ const result = await setPermissionMode(mode);
191
+ if (result && typeof result === "object" && "changed" in result && result.changed === true)
192
+ this.cancelPending();
193
+ return result;
194
+ };
195
+ surface.configurePermissionChannel = async input => {
196
+ if (input.enabled === true && hasReverseProvider())
197
+ throw Object.assign(new Error("A reverse permission provider is connected."), {
198
+ code: "provider_lease_conflict",
199
+ });
200
+ const wasEnabled = this.enabled;
201
+ const result = this.configure(input);
202
+ if (result.enabled && !wasEnabled) {
203
+ try {
204
+ setProvider((toolCall, options, signal) => this.request(toolCall, options, signal));
205
+ await surface.setPermissionMode("prompt");
206
+ } catch (error) {
207
+ this.configure({ enabled: false });
208
+ setProvider(undefined);
209
+ throw error;
210
+ }
211
+ } else if (!result.enabled && !hasReverseProvider()) setProvider(undefined);
212
+ return result;
213
+ };
214
+ surface.respondPermission = input => this.respond(input);
215
+ }
216
+
217
+ configure(input: unknown): { enabled: boolean } {
218
+ if (!isRecord(input) || !exactKeys(input, ["enabled"]) || typeof input.enabled !== "boolean")
219
+ invalid("configure requires exactly { enabled: boolean }");
220
+ if (this.#disposed && input.enabled)
221
+ throw new ExternalPermissionError("resource_gone", "Permission runtime is disposed");
222
+ this.#enabled = input.enabled;
223
+ if (!this.#enabled) this.cancelPending();
224
+ return { enabled: this.#enabled };
225
+ }
226
+
227
+ request(
228
+ toolCall: ClientBridgePermissionToolCall,
229
+ options: ClientBridgePermissionOption[],
230
+ signal?: AbortSignal,
231
+ ): Promise<PermissionOutcome> {
232
+ if (this.#disposed || !this.#enabled)
233
+ throw new ExternalPermissionError("resource_gone", "External permissions are disabled");
234
+ if (signal !== undefined && !(signal instanceof AbortSignal)) invalid("Invalid abort signal");
235
+ if (signal?.aborted) return Promise.resolve({ outcome: "cancelled" });
236
+ if (this.#pending.size >= this.#maxPending)
237
+ throw new ExternalPermissionError("too_many_outstanding", "Too many pending permission requests");
238
+ const toolCallSnapshot = snapshotToolCall(toolCall);
239
+ const optionsSnapshot = snapshotOptions(options);
240
+ const id = randomUUID();
241
+ const expiresAt = new Date(Date.now() + this.#timeoutMs).toISOString();
242
+ const request = jsonSnapshot({
243
+ id,
244
+ sessionId: this.#sessionId,
245
+ toolCall: toolCallSnapshot,
246
+ options: optionsSnapshot,
247
+ expiresAt,
248
+ });
249
+ const aggregate = {
250
+ sessionId: this.#sessionId,
251
+ enabled: this.#enabled,
252
+ requests: [...this.#pending.values()].map(item => item.request).concat(request),
253
+ };
254
+ if (new TextEncoder().encode(JSON.stringify(aggregate)).byteLength > MAX_AGGREGATE_REQUEST_BYTES) {
255
+ throw new ExternalPermissionError("payload_too_large", "Aggregate pending permission requests exceed 192 KB");
256
+ }
257
+ const promise = Promise.withResolvers<PermissionOutcome>();
258
+ const pending: PendingRequest = {
259
+ request,
260
+ resolve: promise.resolve,
261
+ timer: setTimeout(() => this.#finish(id, { outcome: "cancelled" }), this.#timeoutMs),
262
+ signal,
263
+ };
264
+ if (signal) {
265
+ pending.onAbort = () => this.#finish(id, { outcome: "cancelled" });
266
+ signal.addEventListener("abort", pending.onAbort, { once: true });
267
+ }
268
+ this.#pending.set(id, pending);
269
+ return promise.promise;
270
+ }
271
+
272
+ list(input?: unknown): { sessionId: string; enabled: boolean; requests: ExternalPermissionRequest[] } {
273
+ if (input !== undefined && (!isRecord(input) || Object.keys(input).length !== 0))
274
+ invalid("list accepts only an empty object or undefined");
275
+ return jsonSnapshot({
276
+ sessionId: this.#sessionId,
277
+ enabled: this.#enabled,
278
+ requests: [...this.#pending.values()].map(item => item.request),
279
+ });
280
+ }
281
+
282
+ respond(input: unknown): { accepted: true } {
283
+ if (
284
+ !isRecord(input) ||
285
+ !exactKeys(input, ["sessionId", "id", "optionId"], ["comment"]) ||
286
+ !nonEmptyBoundedString(input.sessionId, "sessionId", 512) ||
287
+ !nonEmptyBoundedString(input.id, "id", 64) ||
288
+ !nonEmptyBoundedString(input.optionId, "optionId", 512) ||
289
+ (input.comment !== undefined &&
290
+ (typeof input.comment !== "string" || input.comment.length > MAX_COMMENT_LENGTH))
291
+ ) {
292
+ invalid("Invalid permission response");
293
+ }
294
+ if (input.sessionId !== this.#sessionId) invalid("Permission response belongs to another session");
295
+ const pending = this.#pending.get(input.id);
296
+ if (!pending) invalid("Permission request is stale or already answered");
297
+ if (Date.now() >= Date.parse(pending.request.expiresAt)) {
298
+ this.#finish(input.id, { outcome: "cancelled" });
299
+ throw new ExternalPermissionError("resource_gone", "Permission request expired");
300
+ }
301
+ const option = pending.request.options.find(candidate => candidate.optionId === input.optionId);
302
+ if (!option) invalid("Permission option was not offered");
303
+ if (input.comment !== undefined && !option.kind.startsWith("reject"))
304
+ invalid("Comments are only allowed for rejecting options");
305
+ const outcome: PermissionOutcome = { outcome: "selected", optionId: option.optionId, kind: option.kind };
306
+ if (input.comment !== undefined) outcome.comment = input.comment;
307
+ this.#finish(input.id, outcome);
308
+ return { accepted: true };
309
+ }
310
+
311
+ dispose(): void {
312
+ if (this.#disposed) return;
313
+ this.#disposed = true;
314
+ this.#enabled = false;
315
+ this.cancelPending();
316
+ }
317
+
318
+ cancelPending(): void {
319
+ for (const id of this.#pending.keys()) this.#finish(id, { outcome: "cancelled" });
320
+ }
321
+
322
+ #finish(id: string, outcome: PermissionOutcome): void {
323
+ const pending = this.#pending.get(id);
324
+ if (!pending) return;
325
+ this.#pending.delete(id);
326
+ clearTimeout(pending.timer);
327
+ if (pending.signal && pending.onAbort) pending.signal.removeEventListener("abort", pending.onAbort);
328
+ pending.resolve(outcome);
329
+ }
330
+ }
@@ -1282,6 +1282,7 @@ const PERMISSION_REQUIRED_TOOLS = new Set([
1282
1282
  "ssh",
1283
1283
  "github",
1284
1284
  "debug",
1285
+ "bisect",
1285
1286
  ]);
1286
1287
 
1287
1288
  function isShellExecutionPermissionTool(toolName: string): boolean {
@@ -1294,7 +1295,8 @@ function isExecutionPermissionTool(toolName: string): boolean {
1294
1295
  toolName === "eval" ||
1295
1296
  toolName === "python" ||
1296
1297
  toolName === "recipe" ||
1297
- toolName === "debug"
1298
+ toolName === "debug" ||
1299
+ toolName === "bisect"
1298
1300
  );
1299
1301
  }
1300
1302
 
@@ -1387,6 +1389,10 @@ function getPermissionIntent(
1387
1389
  const op = getStringProperty(a, "op")?.slice(0, 80);
1388
1390
  return { toolName, title: op && op.length > 0 ? op : "recipe", cacheKey: toolName };
1389
1391
  }
1392
+ if (toolName === "bisect") {
1393
+ const run = getStringProperty(a, "run")?.slice(0, 80);
1394
+ return { toolName, title: run && run.length > 0 ? run : "bisect", cacheKey: toolName };
1395
+ }
1390
1396
  if (toolName === "delete") {
1391
1397
  const p = getStringProperty(a, "path");
1392
1398
  return { toolName, title: p ? `Delete ${p}` : toolName, paths: p ? [p] : undefined, cacheKey: toolName };
@@ -41,7 +41,7 @@ export interface ClientBridgePermissionOption {
41
41
 
42
42
  export type ClientBridgePermissionOutcome =
43
43
  | { outcome: "cancelled" }
44
- | { outcome: "selected"; optionId: string; kind?: ClientBridgePermissionOptionKind };
44
+ | { outcome: "selected"; optionId: string; kind?: ClientBridgePermissionOptionKind; comment?: string };
45
45
 
46
46
  export interface ClientBridgeTerminalExitStatus {
47
47
  exitCode?: number | null;
@@ -1,6 +1,17 @@
1
+ import { sanitizeDisplayLine, sanitizeText } from "@sayknow-cli/utils";
1
2
  import type { CanonicalSkcWorkflowSkill } from "../skill-state/active-state";
2
3
  import type { SkillManifest } from "./workflow-manifest";
3
4
 
5
+ /** Markdown prose. Newlines stay; terminal controls are removed. */
6
+ function terminalText(value: string): string {
7
+ return sanitizeText(value);
8
+ }
9
+
10
+ /** One status row. Breaks collapse, then terminal controls are removed. */
11
+ function terminalLine(value: string): string {
12
+ return sanitizeDisplayLine(value);
13
+ }
14
+
4
15
  function scalar(value: unknown): string | undefined {
5
16
  if (typeof value === "string") return value.trim() || undefined;
6
17
  if (typeof value === "number" || typeof value === "boolean") return String(value);
@@ -215,16 +226,19 @@ export function buildStateStatusSummary(
215
226
 
216
227
  export function renderStateStatusLine(summary: StateStatusSummary): string {
217
228
  const freshness = summary.fresh ? "fresh" : "stale";
218
- return `${summary.skill}: phase=${summary.phase} ${freshness} next=${summary.next.length ? summary.next.join(",") : "none"}\n`;
229
+ const phase = terminalLine(summary.phase);
230
+ const next = summary.next.length ? summary.next.map(item => terminalLine(item)).join(",") : "none";
231
+ return `${summary.skill}: phase=${phase} ${freshness} next=${next}\n`;
219
232
  }
220
233
 
221
234
  export function renderContractMarkdown(skill: CanonicalSkcWorkflowSkill, contract: unknown): string {
222
235
  const record = isRecord(contract) ? contract : {};
223
236
  const lines = [`# ${skill} state contract`, ""];
224
237
  for (const [key, value] of Object.entries(record)) {
225
- if (Array.isArray(value)) lines.push(`- ${key}: ${value.length} entries (--json for full)`);
226
- else if (isRecord(value)) lines.push(`- ${key}: object (${Object.keys(value).length} keys, --json for full)`);
227
- else if (value !== undefined) lines.push(`- ${key}: ${String(value)}`);
238
+ const label = terminalLine(key);
239
+ if (Array.isArray(value)) lines.push(`- ${label}: ${value.length} entries (--json for full)`);
240
+ else if (isRecord(value)) lines.push(`- ${label}: object (${Object.keys(value).length} keys, --json for full)`);
241
+ else if (value !== undefined) lines.push(`- ${label}: ${terminalText(String(value))}`);
228
242
  }
229
243
  return `${lines.join("\n")}\n`;
230
244
  }
@@ -236,13 +250,13 @@ export function renderHistoryMarkdown(history: {
236
250
  truncated: boolean;
237
251
  }): string {
238
252
  const lines = ["# state audit history", "", `- entries: ${history.entries.length}`, `- limit: ${history.limit}`];
239
- if (history.since) lines.push(`- since: ${history.since}`);
253
+ if (history.since) lines.push(`- since: ${terminalLine(history.since)}`);
240
254
  lines.push(`- truncated: ${history.truncated ? "yes" : "no"}`);
241
255
  for (const entry of history.entries) {
242
256
  if (!isRecord(entry)) continue;
243
- const ts = scalar(entry.ts) ?? "unknown-time";
244
- const skill = scalar(entry.skill) ?? "unknown-skill";
245
- const verb = scalar(entry.verb) ?? "unknown-verb";
257
+ const ts = terminalLine(scalar(entry.ts) ?? "unknown-time");
258
+ const skill = terminalLine(scalar(entry.skill) ?? "unknown-skill");
259
+ const verb = terminalLine(scalar(entry.verb) ?? "unknown-verb");
246
260
  lines.push(`- ${ts} ${skill} ${verb}`);
247
261
  }
248
262
  return `${lines.join("\n")}\n`;
@@ -262,29 +276,31 @@ export function renderUltragoalStatusMarkdown(summary: {
262
276
  nudgeGoalId?: string;
263
277
  nudgeTargetKind?: string;
264
278
  }): string {
279
+ const goalsPath = terminalLine(summary.paths.goalsPath);
265
280
  if (!summary.exists)
266
- return `# ultragoal status\n\n- status: missing\n- No ultragoal plan found at ${summary.paths.goalsPath}. Run \`skc ultragoal create-goals --brief "..."\` first.\n`;
281
+ return `# ultragoal status\n\n- status: missing\n- No ultragoal plan found at ${goalsPath}. Run \`skc ultragoal create-goals --brief "..."\` first.\n`;
267
282
  const counts = Object.entries(summary.counts)
268
- .map(([key, value]) => `${key}=${value}`)
283
+ .map(([key, value]) => `${terminalLine(key)}=${value}`)
269
284
  .join(" ");
270
285
  const lines = [
271
286
  "# ultragoal status",
272
287
  "",
273
- `- status: ${summary.status}`,
288
+ `- status: ${terminalLine(summary.status)}`,
274
289
  `- goals: ${summary.goals.length} (${counts})`,
275
290
  ];
276
- if (summary.skcObjective) lines.push(`- objective: ${summary.skcObjective}`);
277
- if (summary.currentGoal) lines.push(`- current: ${summary.currentGoal.id} (${summary.currentGoal.status})`);
291
+ if (summary.skcObjective) lines.push(`- objective: ${terminalText(summary.skcObjective)}`);
292
+ if (summary.currentGoal)
293
+ lines.push(`- current: ${terminalLine(summary.currentGoal.id)} (${terminalLine(summary.currentGoal.status)})`);
278
294
  if (summary.nudgeBudget !== undefined && summary.nudgeGoalId) {
279
295
  const used = summary.nudgeCount ?? 0;
280
296
  const remaining = summary.nudgeRemaining ?? Math.max(0, summary.nudgeBudget - used);
281
- const target = summary.nudgeTargetKind ? ` target=${summary.nudgeTargetKind}` : "";
297
+ const target = summary.nudgeTargetKind ? ` target=${terminalLine(summary.nudgeTargetKind)}` : "";
282
298
  lines.push(
283
- `- nudge: ${summary.nudgeGoalId} ${used}/${summary.nudgeBudget} used (${remaining} remaining)${target}`,
299
+ `- nudge: ${terminalLine(summary.nudgeGoalId)} ${used}/${summary.nudgeBudget} used (${remaining} remaining)${target}`,
284
300
  );
285
301
  }
286
- lines.push(`- goals_path: ${summary.paths.goalsPath}`);
287
- if (summary.paths.ledgerPath) lines.push(`- ledger_path: ${summary.paths.ledgerPath}`);
302
+ lines.push(`- goals_path: ${goalsPath}`);
303
+ if (summary.paths.ledgerPath) lines.push(`- ledger_path: ${terminalLine(summary.paths.ledgerPath)}`);
288
304
  return `${lines.join("\n")}\n`;
289
305
  }
290
306
 
@@ -339,29 +355,29 @@ export function renderStateMarkdown(
339
355
  const artifacts = artifactLinks(state);
340
356
  const fields = keyStateFields(state, manifest);
341
357
 
342
- const lines = [`# ${skill} state`, "", `- Current phase: ${phase}`];
343
- lines.push(`- Valid next transitions: ${next.length ? next.join(", ") : "none"}`);
358
+ const lines = [`# ${skill} state`, "", `- Current phase: ${terminalText(phase)}`];
359
+ lines.push(`- Valid next transitions: ${next.length ? next.map(item => terminalLine(item)).join(", ") : "none"}`);
344
360
  if (fields.length) {
345
361
  lines.push("- Key fields:");
346
- for (const [key, value] of fields) lines.push(` - ${key}: ${value}`);
362
+ for (const [key, value] of fields) lines.push(` - ${terminalLine(key)}: ${terminalText(value)}`);
347
363
  } else {
348
364
  lines.push("- Key fields: none");
349
365
  }
350
- lines.push(`- Receipt: ${receiptStatus}`);
366
+ lines.push(`- Receipt: ${terminalText(receiptStatus)}`);
351
367
  if (receipt) {
352
368
  const mutationId = scalar(receipt.mutation_id);
353
369
  const freshUntil = scalar(receipt.fresh_until);
354
- if (mutationId) lines.push(` - mutation_id: ${mutationId}`);
355
- if (freshUntil) lines.push(` - fresh_until: ${freshUntil}`);
370
+ if (mutationId) lines.push(` - mutation_id: ${terminalText(mutationId)}`);
371
+ if (freshUntil) lines.push(` - fresh_until: ${terminalText(freshUntil)}`);
356
372
  }
357
373
  if (artifacts.length) {
358
374
  lines.push("- Artifacts:");
359
- for (const artifact of artifacts) lines.push(` - ${artifact}`);
375
+ for (const artifact of artifacts) lines.push(` - ${terminalText(artifact)}`);
360
376
  }
361
377
  const compactFields = compactStateFields(state);
362
378
  if (compactFields.length) {
363
379
  lines.push("- Compact elisions:");
364
- for (const [key, value] of compactFields) lines.push(` - ${key}: ${value}`);
380
+ for (const [key, value] of compactFields) lines.push(` - ${terminalLine(key)}: ${terminalText(value)}`);
365
381
  }
366
382
  return `${lines.join("\n")}\n`;
367
383
  }
@@ -2192,7 +2192,8 @@ function interpreterCodeContainsWriteApi(
2192
2192
  isInterpolated &&
2193
2193
  (api.test(skipped) ||
2194
2194
  (language === "py" && PYTHON_DYNAMIC_EXECUTION_TOKEN_RE.test(skipped)) ||
2195
- (language === "js" && JAVASCRIPT_DYNAMIC_EXECUTION_TOKEN_RE.test(skipped)))
2195
+ (language === "js" &&
2196
+ (JAVASCRIPT_DYNAMIC_EXECUTION_TOKEN_RE.test(skipped) || /\b(?:process|Bun)\b/.test(skipped))))
2196
2197
  )
2197
2198
  return true;
2198
2199
  index = next;
@@ -2211,6 +2212,21 @@ function interpreterCodeContainsWriteApi(
2211
2212
  if (INTERPRETER_OUTPUT_METHOD_ASSIGNMENT_RE.test(script.slice(index))) return true;
2212
2213
  if (language === "py" && PYTHON_DYNAMIC_EXECUTION_IDENTIFIER_RE.test(script.slice(index))) return true;
2213
2214
  if (language === "js" && JAVASCRIPT_DYNAMIC_EXECUTION_IDENTIFIER_RE.test(script.slice(index))) return true;
2215
+ if (
2216
+ language === "js" &&
2217
+ !/[\w$]/.test(script[index - 1] ?? "") &&
2218
+ /^(?:process|Bun)(?![\w$])/.test(script.slice(index))
2219
+ ) {
2220
+ const access = script.slice(index).replace(/^(?:process|Bun)\s*/, "");
2221
+ // Only direct writes retain stream identity. Aliases, argument passing,
2222
+ // destructuring and computed access can expose a mutable stream object.
2223
+ if (!/^(?:\.\s*[A-Za-z_$][\w$]*(?![\w$\\])|\[\s*["'][^"'\\]+["']\s*\])/.test(access)) return true;
2224
+ if (
2225
+ /^(?:\.\s*(?:stdout|stderr)\b|\[\s*["'`](?:stdout|stderr)["'`]\s*\])/.test(access) &&
2226
+ !/^\.\s*(?:stdout|stderr)\s*\.\s*write\s*\(/.test(access)
2227
+ )
2228
+ return true;
2229
+ }
2214
2230
  if (language === "perl" && /^open\b/.test(script.slice(index))) {
2215
2231
  // Both `open(...)` and the list form `open H, MODE, EXPR` matter; only an
2216
2232
  // explicit read mode is safe, and an unparsed open fails closed.
@@ -2223,13 +2239,7 @@ function interpreterCodeContainsWriteApi(
2223
2239
  !streamMutated &&
2224
2240
  /^\.\s*write\s*\(/.test(script.slice(index)) &&
2225
2241
  /\b(?:process|Bun)\s*\.\s*(?:stdout|stderr)\s*$/.test(script.slice(0, index));
2226
- // Aliased mutation: if process.stdout is passed through a function or parameter,
2227
- // it may be rebound. Fail closed when there are function definitions or calls
2228
- // that could capture and mutate the stream object.
2229
- const hasAliasVectors =
2230
- outputWrite &&
2231
- /[([]\s*[A-Za-z_]\w*\s*=>|\([^)]*(?:process|Bun)\s*\.\s*(?:stdout|stderr)[^)]*\)/.test(script);
2232
- if (!outputWrite || hasAliasVectors) return true;
2242
+ if (!outputWrite) return true;
2233
2243
  }
2234
2244
  index += 1;
2235
2245
  }