@eddyskywalker/dsh-chatgpt-subscription 0.68.1 → 0.69.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/lib/codemode.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { n as PLUGIN_MESSAGE_SOURCE_KIND } from "./llm-compat-u9mor0uu.js";
2
+ import * as dshLlm from "@deepseek-ai/dsh-llm";
2
3
  import { HarnessError, createUserMessage } from "@deepseek-ai/dsh-llm";
3
4
  import { NativeToolExecutor } from "@deepseek-ai/dsh-tool-executor-native";
4
5
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -598,7 +599,7 @@ function summarizeHidden(names) {
598
599
  */
599
600
  function buildCodemodeSectionText(input) {
600
601
  const python = input.language === "python";
601
- const retained = input.programFormat === "repl";
602
+ const retained = input.programFormat === "repl" || input.programFormat === "scoped-repl" || input.programFormat === "script";
602
603
  const listTool = input.metaTools[0] ?? "code_tools_list";
603
604
  const searchTool = input.metaTools[1] ?? "code_tools_search";
604
605
  const describeTool = input.metaTools[2] ?? "code_tools_describe";
@@ -646,13 +647,13 @@ function buildCodemodeSectionText(input) {
646
647
  ...example,
647
648
  "",
648
649
  python ? retained ? "- A retained Python REPL: top-level await and a final expression. Its variables and imported modules survive into your later programs in this session." : "- Async Python program: top-level await works; print or evaluate a final expression to produce output." : retained ? "- A retained TypeScript REPL: top-level declarations, await, and a final expression. Its variables and imported modules survive into your later programs in this session." : "- Erasable TypeScript, run as the body of an async function: top-level await and return work.",
649
- "- Only what you return or console.log reaches the conversation; every intermediate result stays in the program, so filter and aggregate there instead of returning raw payloads.",
650
+ "- Only what you inspect(...values), return, or console.log reaches the conversation; every intermediate result stays in the program, so filter and aggregate there instead of returning raw payloads.",
650
651
  "- File, search, and shell tool results are named-field objects, never bare strings — read the field, not the envelope (`job_list` and `list_agents` are the only bare arrays):",
651
652
  " `read` → `{ path, offset, lines: [{ number, text }], totalLines }` · `glob` → `{ root, paths }` · `grep` → `{ matches: [{ path, lineNumber, line }] }` · `edit` → `{ path, before, after }` · `write` → `{ path, operation, before, after }` · `win_bash` → `{ stdout, stderr, exitCode }` · `web_fetch` → `{ url, statusCode, body, truncated }` · `job_output` → `{ text, job }` · `read_image` → `{ path, image }` · `skill` → `{ name, content }`.",
652
653
  python ? "- Read the field: `page[\"lines\"]`, `match[\"text\"]`. Calling `.split()`, `.splitlines()` or `in` on the envelope itself is always wrong." : "- Read the field: `r.lines.map((l) => l.text)`. Calling `.map`, `.filter`, `.split` or `in` on the envelope itself is always wrong.",
653
654
  "- Anything not listed above (MCP tools, hidden plugin tools) answers with its **declared output schema**: call `" + describeTool + "({ name })` and read the top-level keys before picking a field. One discovery call is far cheaper than the `TypeError` that loses the whole program.",
654
655
  "- Discovery returns whole objects too: `" + listTool + "` answers `{ tools: [{ name, description, namespace }] }`, `" + searchTool + "` answers `{ tools: [{ name, namespace, description, parameters, output? }], fallback? }`, and `" + describeTool + "` answers `{ found, name?, namespace?, description?, parameters?, output? }`.",
655
- "- Tool argument objects and `return` values must be lossless JSON: **never leave `undefined` in an object property value** — `{ a: x.opt }` fails the call when `x.opt === undefined`. Omit the key, write `x.opt ?? null`, or print it with `console.log`.",
656
+ "- Tool argument objects and `return` values must be lossless JSON: **never leave `undefined` in an object property value** — `{ a: x.opt }` fails the call when `x.opt === undefined`. Omit the key, write `x.opt ?? null`, or print it with `inspect` / `console.log`.",
656
657
  "- Parameter keys: `read`, `edit`, `write`, and `read_image` take `file_path` (not `path`); `glob` and `grep` take `path`; `win_bash` takes `workdir` (not `cwd`).",
657
658
  ...python ? [] : [
658
659
  "- Paths and regexes: write a Windows path with forward slashes (`C:/Users/...`) or wrap it in `String.raw`; a literal `C:\\Users` inside an ordinary string is read as the escape `\\U` and the program never starts (`Expected unicode escape`). Regex backslashes (`\\d`, `\\.`) have the same trap — double them or use `String.raw`.",
@@ -960,6 +961,41 @@ var CodeResetFailedError = class extends HarnessError {
960
961
  };
961
962
  /** 与内核 `run_code` 一致的 `description` 参数说明。 */
962
963
  const DESCRIPTION_PARAM_DESCRIPTION = "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\".";
964
+ /** 与 `@deepseek-ai/dsh-ptc-runtime` 的 `PTC_IMAGE_TAG` 对齐的跨包协议符号。 */
965
+ const PTC_IMAGE_TAG = Symbol.for("dsh.ptc.image");
966
+ /**
967
+ * 程序内一等公民图片句柄(协议兼容 `@deepseek-ai/dsh-ptc-runtime` 的 `PtcImage`)。
968
+ *
969
+ * `ptc-runtime-node` 的 `encodeWireValue` 通过 `Symbol.for('dsh.ptc.image') === true` + `path` + `attachment`
970
+ * 判定图片句柄并在 worker 侧还原为 `PtcImage` 实例,使程序可读 `.path` / `.width` / `.height` 并传给 `inspect(img)`。
971
+ */
972
+ var PtcImageLike = class {
973
+ [PTC_IMAGE_TAG] = true;
974
+ path;
975
+ attachment;
976
+ constructor(path, attachment) {
977
+ this.path = path;
978
+ this.attachment = attachment;
979
+ }
980
+ get attachmentId() {
981
+ return this.attachment.attachmentId;
982
+ }
983
+ get mediaType() {
984
+ return this.attachment.mediaType;
985
+ }
986
+ get width() {
987
+ return this.attachment.width;
988
+ }
989
+ get height() {
990
+ return this.attachment.height;
991
+ }
992
+ };
993
+ /** 判定一个值是否为合法的 `ImageAttachmentRef`。 */
994
+ function isImageAttachmentRefLike(value) {
995
+ if (typeof value !== "object" || value === null) return false;
996
+ const candidate = value;
997
+ return candidate["kind"] === "image-attachment" && typeof candidate["attachmentId"] === "string" && candidate["attachmentId"].length > 0 && typeof candidate["mediaType"] === "string" && candidate["mediaType"].length > 0 && typeof candidate["width"] === "number" && Number.isInteger(candidate["width"]) && candidate["width"] > 0 && typeof candidate["height"] === "number" && Number.isInteger(candidate["height"]) && candidate["height"] > 0 && typeof candidate["byteLength"] === "number" && Number.isInteger(candidate["byteLength"]) && candidate["byteLength"] > 0;
998
+ }
963
999
  function buildFlavor(languageName, execution) {
964
1000
  return {
965
1001
  description: `Execute a ${languageName} program against the available tools. Takes two required arguments: \`code\`, ${execution.programDescription}, and \`description\`, a short summary of what the program does. Call tools as \`await tools.name(args)\`. ${execution.outputInstruction} Image-bearing subtool results are attached after the run.`,
@@ -981,9 +1017,12 @@ const PYTHON_FLAVOR = buildFlavor("Python", {
981
1017
  outputInstruction: "Curate the program output.",
982
1018
  codeDescription: "The Python program to execute, following this tool's execution instructions."
983
1019
  });
1020
+ function isReplFormat(programFormat) {
1021
+ return programFormat === "repl" || programFormat === "scoped-repl" || programFormat === "script";
1022
+ }
984
1023
  function resolveFlavor(runtime) {
985
1024
  if (runtime?.language === "python") return PYTHON_FLAVOR;
986
- if (runtime?.language === "typescript" && runtime.programFormat === "repl") return TYPESCRIPT_REPL_FLAVOR;
1025
+ if (runtime?.language === "typescript" && isReplFormat(runtime.programFormat)) return TYPESCRIPT_REPL_FLAVOR;
987
1026
  return TYPESCRIPT_FUNCTION_FLAVOR;
988
1027
  }
989
1028
  function escalationGuidance(sandboxMode) {
@@ -1038,6 +1077,8 @@ function buildTransportParameters(runtime) {
1038
1077
  */
1039
1078
  function createTransportDefinition(host, rules) {
1040
1079
  const runToolName = rules.options.runToolName;
1080
+ const inspections = /* @__PURE__ */ new WeakMap();
1081
+ const structuredOutputs = /* @__PURE__ */ new WeakMap();
1041
1082
  const definition = {
1042
1083
  name: runToolName,
1043
1084
  description: buildTransportDescription(void 0),
@@ -1069,6 +1110,8 @@ function createTransportDefinition(host, rules) {
1069
1110
  }
1070
1111
  },
1071
1112
  render: (_args, value) => {
1113
+ const structured = typeof value === "object" && value !== null ? structuredOutputs.get(value) : void 0;
1114
+ if (structured !== void 0) return renderStructuredOutputBlocks(structured, value.result, value.sandbox, host.runtime()?.sandboxMode, runToolName);
1072
1115
  const parts = [(value.logs ?? []).join("\n"), value.result === void 0 ? "" : renderProgramValue(value.result)].filter((part) => part.length > 0);
1073
1116
  if (value.sandbox?.enforcement === "partial") parts.push("File sandbox enforcement is partial on this host.");
1074
1117
  if (value.sandbox?.denied === true) parts.push("The " + value.sandbox.mode + " file sandbox denied an operation." + escalationGuidance(host.runtime()?.sandboxMode));
@@ -1081,6 +1124,14 @@ function createTransportDefinition(host, rules) {
1081
1124
  return { language: host.runtime()?.language === "python" ? "python" : "typescript" };
1082
1125
  }
1083
1126
  },
1127
+ projectContent(exec, toolResult) {
1128
+ if (typeof exec !== "object" || exec === null) return void 0;
1129
+ const inspection = inspections.get(exec);
1130
+ if (inspection === void 0) return void 0;
1131
+ inspections.delete(exec);
1132
+ if (inspection.appendToError === true) return [...typeof toolResult === "object" && toolResult !== null && Array.isArray(toolResult.content) ? toolResult.content : [], ...inspection.blocks];
1133
+ return [...inspection.blocks];
1134
+ },
1084
1135
  presentCall(args) {
1085
1136
  try {
1086
1137
  const input = readArguments(args);
@@ -1112,6 +1163,7 @@ function createTransportDefinition(host, rules) {
1112
1163
  const owner = host.stateOwner(exec.agent);
1113
1164
  let maxSubCalls = rules.options.maxSubCalls;
1114
1165
  let attempts = 0;
1166
+ const deferredProgramImages = [];
1115
1167
  const lane = createCommitLane(rules.options.maxParallelSubCalls, () => runController.signal.aborted);
1116
1168
  const definitions = /* @__PURE__ */ new Map();
1117
1169
  for (const entry of catalog) definitions.set(entry.name, entry);
@@ -1126,8 +1178,7 @@ function createTransportDefinition(host, rules) {
1126
1178
  runController.abort(limitErr);
1127
1179
  throw limitErr;
1128
1180
  }
1129
- const parsed = normalizeSubCallArgs(definitions.get(entry.name), losslessArgs(rawArgs));
1130
- const loggedArgs = losslessArgs(parsed);
1181
+ const { dispatched: parsed, logged: loggedArgs } = normalizeSubCallArgsPair(definitions.get(entry.name), rawArgs);
1131
1182
  const callId = String(exec.callId) + NESTED_CALL_ID_MARKER + String(n);
1132
1183
  const dispatchLog = createDispatchLog(exec.agent, {
1133
1184
  rootCallId: rootCallIdOf(String(exec.callId)),
@@ -1166,7 +1217,19 @@ function createTransportDefinition(host, rules) {
1166
1217
  }
1167
1218
  const outcome = parked.value;
1168
1219
  const isError = outcome.error !== void 0;
1169
- if (!isError && Array.isArray(outcome.content) && hasImageBlock(outcome.content)) {
1220
+ let programImageValue;
1221
+ if (!isError && (entry.name === "read_image" || entry.name === "cua") && runtime.language !== "python" && typeof host.programImage === "function" && Array.isArray(outcome.content)) {
1222
+ const imageRef = firstImageAttachmentOf(outcome.content);
1223
+ if (imageRef !== void 0) {
1224
+ const fallbackPath = isRecord(outcome.value) && typeof outcome.value["path"] === "string" ? outcome.value["path"] : isRecord(parsed) && typeof parsed["file_path"] === "string" ? parsed["file_path"] : void 0;
1225
+ programImageValue = host.programImage(imageRef, fallbackPath);
1226
+ if (programImageValue !== void 0) deferredProgramImages.push({
1227
+ attachmentId: imageRef.attachmentId,
1228
+ content: outcome.content
1229
+ });
1230
+ }
1231
+ }
1232
+ if (!isError && programImageValue === void 0 && Array.isArray(outcome.content) && hasImageBlock(outcome.content)) {
1170
1233
  const imageMsg = host.createImageContext?.(outcome.content);
1171
1234
  if (imageMsg !== void 0) exec.deferContext?.(imageMsg);
1172
1235
  }
@@ -1187,6 +1250,7 @@ function createTransportDefinition(host, rules) {
1187
1250
  });
1188
1251
  if (runController.signal.aborted) throw new Error(runToolName + " run is over; " + entry.name + " result discarded");
1189
1252
  if (outcome.error !== void 0) throw new Error(outcome.error);
1253
+ if (programImageValue !== void 0) return programImageValue;
1190
1254
  return outcome.value !== void 0 ? outcome.value : outcome.text ?? null;
1191
1255
  },
1192
1256
  abandon() {
@@ -1209,11 +1273,24 @@ function createTransportDefinition(host, rules) {
1209
1273
  * `stateOwner`,避免把单次授权固化到常驻环境中(对齐内核 `ptc.ts`)。
1210
1274
  */
1211
1275
  let approvedEscalatedMode;
1212
- /** 这次运行在入口那边的登记;结算时释放(重跑原位更新 mode,外层 finally 统一释放)。 */
1213
- let untrackRun = () => {};
1276
+ /** 提前登记在飞调用,使目录解析与沙箱提权审批等待期也能响应 `reset()` 与 `sandbox/mode` 变更。 */
1277
+ let untrackRun = host.trackRun?.({
1278
+ agent: exec.agent,
1279
+ controller: runController,
1280
+ signal: nestedSignal
1281
+ }) ?? (() => {});
1282
+ const sanitizedCode = sanitizeReplTopLevelReturn(input.code, runtime.programFormat, runtime.language);
1214
1283
  const attempt = async () => {
1284
+ deferredProgramImages.length = 0;
1215
1285
  const authority = await host.runAuthority?.(exec.agent, nestedSignal);
1216
1286
  const standingPolicy = authority?.sandboxPolicy;
1287
+ const standingMode = modeOfPolicy(standingPolicy);
1288
+ if (standingMode !== void 0) untrackRun = host.trackRun?.({
1289
+ agent: exec.agent,
1290
+ controller: runController,
1291
+ signal: nestedSignal,
1292
+ mode: standingMode
1293
+ }) ?? untrackRun;
1217
1294
  let effectivePolicy = standingPolicy;
1218
1295
  let escalated = false;
1219
1296
  if (input.sandboxPermissions !== void 0 && input.justification !== void 0) {
@@ -1226,7 +1303,7 @@ function createTransportDefinition(host, rules) {
1226
1303
  agent: exec.agent,
1227
1304
  callId: String(exec.callId),
1228
1305
  toolName: runToolName,
1229
- signal: exec.signal
1306
+ signal: nestedSignal
1230
1307
  });
1231
1308
  effectivePolicy = nextPolicy;
1232
1309
  approvedEscalatedMode = modeOfPolicy(nextPolicy);
@@ -1236,15 +1313,15 @@ function createTransportDefinition(host, rules) {
1236
1313
  };
1237
1314
  escalated = modeOfPolicy(effectivePolicy) !== modeOfPolicy(standingPolicy);
1238
1315
  }
1239
- const runMode = modeOfPolicy(effectivePolicy);
1240
- untrackRun = host.trackRun?.({
1316
+ const runMode = standingMode ?? modeOfPolicy(effectivePolicy);
1317
+ if (runMode !== void 0) untrackRun = host.trackRun?.({
1241
1318
  agent: exec.agent,
1242
1319
  controller: runController,
1243
1320
  signal: nestedSignal,
1244
- ...runMode === void 0 ? {} : { mode: runMode }
1245
- }) ?? (() => {});
1321
+ mode: runMode
1322
+ }) ?? untrackRun;
1246
1323
  const request = {
1247
- program: input.code,
1324
+ program: sanitizedCode,
1248
1325
  bindings: [{
1249
1326
  global: "tools",
1250
1327
  functions,
@@ -1278,6 +1355,18 @@ function createTransportDefinition(host, rules) {
1278
1355
  await lane.drain();
1279
1356
  untrackRun();
1280
1357
  }
1358
+ const hasStructuredOutput = Array.isArray(result.output);
1359
+ const outputBlocks = hasStructuredOutput ? result.output : [];
1360
+ const hasImages = outputBlocks.some((block) => block.type === "image");
1361
+ if (deferredProgramImages.length > 0) {
1362
+ const inspectedIds = /* @__PURE__ */ new Set();
1363
+ for (const block of outputBlocks) if (block.type === "image" && isImageAttachmentRefLike(block.attachment)) inspectedIds.add(block.attachment.attachmentId);
1364
+ for (const pending of deferredProgramImages) {
1365
+ if (pending.attachmentId !== void 0 && inspectedIds.has(pending.attachmentId)) continue;
1366
+ const imageMsg = host.createImageContext?.(pending.content);
1367
+ if (imageMsg !== void 0) exec.deferContext?.(imageMsg);
1368
+ }
1369
+ }
1281
1370
  if (result.error !== void 0) {
1282
1371
  const limitError = runController.signal.reason instanceof ToolCallLimitExceededError ? runController.signal.reason : void 0;
1283
1372
  if (result.error.kind === "abort" && exec.signal.aborted && limitError === void 0) {
@@ -1285,14 +1374,19 @@ function createTransportDefinition(host, rules) {
1285
1374
  abortError.name = "AbortError";
1286
1375
  throw abortError;
1287
1376
  }
1288
- const logsText = Array.isArray(result.logs) && result.logs.length > 0 ? "\nCaptured output:\n" + result.logs.join("\n") : "";
1377
+ if (hasImages && typeof exec === "object" && exec !== null) inspections.set(exec, {
1378
+ blocks: renderFailureOutputBlocks(outputBlocks),
1379
+ appendToError: true
1380
+ });
1381
+ const capturedLogs = extractCapturedErrorText(result, hasImages);
1382
+ const logsText = capturedLogs.length > 0 ? "\nCaptured output:\n" + capturedLogs : "";
1289
1383
  const sandboxText = result.sandbox === void 0 ? "" : "\nFile sandbox: " + result.sandbox.mode + (result.sandbox.enforcement === void 0 ? "" : "; enforcement: " + result.sandbox.enforcement) + (result.sandbox.denied ? "; operation denied" : "") + ".";
1290
1384
  const hint = result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : "";
1291
1385
  const failureText = limitError === void 0 || limitError.message === result.error.message ? result.error.message : `${limitError.message}\n${result.error.message}`;
1292
1386
  throw new CodeRunFailedError("program failed (" + result.error.kind + "): " + failureText + logsText + sandboxText + hint);
1293
1387
  }
1294
- return {
1295
- logs: [...result.logs ?? []],
1388
+ const output = {
1389
+ logs: extractLogsList(result),
1296
1390
  ...result.value === void 0 ? {} : { result: result.value },
1297
1391
  ...result.sandbox === void 0 ? {} : { sandbox: {
1298
1392
  mode: result.sandbox.mode,
@@ -1300,6 +1394,11 @@ function createTransportDefinition(host, rules) {
1300
1394
  ...result.sandbox.enforcement === void 0 ? {} : { enforcement: result.sandbox.enforcement }
1301
1395
  } }
1302
1396
  };
1397
+ if (hasStructuredOutput) {
1398
+ structuredOutputs.set(output, outputBlocks);
1399
+ if (hasImages && typeof exec === "object" && exec !== null) inspections.set(exec, { blocks: renderStructuredOutputBlocks(outputBlocks, result.value, output.sandbox, runtime.sandboxMode, runToolName) });
1400
+ }
1401
+ return output;
1303
1402
  } finally {
1304
1403
  exec.signal.removeEventListener("abort", onOuterAbort);
1305
1404
  }
@@ -1336,6 +1435,108 @@ function modeOfPolicy(policy) {
1336
1435
  function hasImageBlock(content) {
1337
1436
  return content.some((block) => typeof block === "object" && block !== null && block.type === "image");
1338
1437
  }
1438
+ function firstImageAttachmentOf(content) {
1439
+ for (const block of content) {
1440
+ if (typeof block !== "object" || block === null) continue;
1441
+ const record = block;
1442
+ if (record.type === "image" && isImageAttachmentRefLike(record.attachment)) return record.attachment;
1443
+ }
1444
+ }
1445
+ /**
1446
+ * 从运行结果提取面向 `TransportOutput.logs` 的字符串数组(兼容旧代 `logs` 与新代 `output`)。
1447
+ */
1448
+ function extractLogsList(result) {
1449
+ if (Array.isArray(result.logs)) return [...result.logs];
1450
+ if (!Array.isArray(result.output)) return [];
1451
+ const logs = [];
1452
+ for (const block of result.output) {
1453
+ if (block.type !== "text" || typeof block.text !== "string") continue;
1454
+ const trimmed = block.text.endsWith("\n") ? block.text.slice(0, -1) : block.text;
1455
+ if (trimmed.length > 0) logs.push(trimmed);
1456
+ }
1457
+ return logs;
1458
+ }
1459
+ /**
1460
+ * 提取运行失败时内联在 `CodeRunFailedError.message` 中的已捕获文本。
1461
+ *
1462
+ * 当新代 `result.output` 含有图片块时,报错前的文本与图片已通过 `projectContent` 按序附在
1463
+ * 错误内容块之后,错误消息本身不再重复拼接 `Captured output:`(对齐内核 `ptc.ts:783`)。
1464
+ */
1465
+ function extractCapturedErrorText(result, hasImages) {
1466
+ if (hasImages) return "";
1467
+ if (Array.isArray(result.logs) && result.logs.length > 0) return result.logs.join("\n");
1468
+ if (!Array.isArray(result.output) || result.output.length === 0) return "";
1469
+ const joined = result.output.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
1470
+ return joined.endsWith("\n") ? joined.slice(0, -1) : joined;
1471
+ }
1472
+ /**
1473
+ * 将新代 `result.output` 渲染为有序图文内容块列表(对齐内核 `ptc.ts` 的 `renderRunOutput`)。
1474
+ */
1475
+ function renderStructuredOutputBlocks(blocks, resultValue, sandbox, sandboxMode, runToolName) {
1476
+ const out = [];
1477
+ let pendingText = "";
1478
+ for (const block of blocks) if (block.type === "text" && typeof block.text === "string") pendingText += block.text;
1479
+ else if (block.type === "image" && block.attachment !== void 0) {
1480
+ if (pendingText.length > 0) {
1481
+ out.push({
1482
+ type: "text",
1483
+ text: pendingText
1484
+ });
1485
+ pendingText = "";
1486
+ }
1487
+ out.push({
1488
+ type: "image",
1489
+ attachment: block.attachment
1490
+ });
1491
+ }
1492
+ const renderedValue = resultValue === void 0 ? "" : renderProgramValue(resultValue);
1493
+ if (renderedValue.length > 0) {
1494
+ if ((pendingText.endsWith("\n") ? pendingText.slice(0, -1) : pendingText) !== renderedValue) pendingText = pendingText.length === 0 ? renderedValue : pendingText.endsWith("\n") ? pendingText + renderedValue : pendingText + "\n" + renderedValue;
1495
+ }
1496
+ const sandboxNotes = [];
1497
+ if (sandbox?.enforcement === "partial") sandboxNotes.push("File sandbox enforcement is partial on this host.");
1498
+ if (sandbox?.denied === true) sandboxNotes.push("The " + sandbox.mode + " file sandbox denied an operation." + escalationGuidance(sandboxMode));
1499
+ if (sandboxNotes.length > 0) {
1500
+ const noteText = sandboxNotes.join("\n");
1501
+ pendingText = pendingText.length === 0 ? noteText : pendingText.endsWith("\n") ? pendingText + noteText : pendingText + "\n" + noteText;
1502
+ }
1503
+ if (out.length === 0 && pendingText.endsWith("\n")) pendingText = pendingText.slice(0, -1);
1504
+ if (pendingText.length > 0) out.push({
1505
+ type: "text",
1506
+ text: pendingText
1507
+ });
1508
+ if (out.length === 0) return [{
1509
+ type: "text",
1510
+ text: "(" + runToolName + " completed with no output)"
1511
+ }];
1512
+ return out;
1513
+ }
1514
+ /**
1515
+ * 将失败运行已捕获的图文输出块合并为追加在错误块之后的投影块(对齐内核 `ptc.ts`)。
1516
+ */
1517
+ function renderFailureOutputBlocks(blocks) {
1518
+ const out = [];
1519
+ let pendingText = "";
1520
+ for (const block of blocks) if (block.type === "text" && typeof block.text === "string") pendingText += block.text;
1521
+ else if (block.type === "image" && block.attachment !== void 0) {
1522
+ if (pendingText.length > 0) {
1523
+ out.push({
1524
+ type: "text",
1525
+ text: pendingText
1526
+ });
1527
+ pendingText = "";
1528
+ }
1529
+ out.push({
1530
+ type: "image",
1531
+ attachment: block.attachment
1532
+ });
1533
+ }
1534
+ if (pendingText.length > 0) out.push({
1535
+ type: "text",
1536
+ text: pendingText
1537
+ });
1538
+ return out;
1539
+ }
1339
1540
  function resolveSubCallBudget(spec, rules) {
1340
1541
  if (rules.options.explicitMaxSubCalls) return rules.options.maxSubCalls;
1341
1542
  if (spec.timeoutMs === null) return Infinity;
@@ -1758,6 +1959,215 @@ function losslessArgs(value) {
1758
1959
  throw new Error("codemode: tool arguments must be lossless JSON");
1759
1960
  }
1760
1961
  }
1962
+ /**
1963
+ * 归一化子调用参数并生成两份独立深拷贝(`dispatched` 供工具执行,`logged` 供回放落盘),
1964
+ * 防止工具内部原地修改 `args` 对象污染 `tool/ptc-dispatch` 回放日志(对齐内核 `ptc.ts:864`)。
1965
+ */
1966
+ function normalizeSubCallArgsPair(entry, rawArgs) {
1967
+ const normalized = normalizeSubCallArgs(entry, losslessArgs(rawArgs));
1968
+ const serialized = JSON.stringify(normalized);
1969
+ return {
1970
+ dispatched: JSON.parse(serialized),
1971
+ logged: JSON.parse(serialized)
1972
+ };
1973
+ }
1974
+ /**
1975
+ * 在常驻 REPL(`repl` / `scoped-repl` / `script`)模式下自动剥离模型误写的末尾顶层 `return`。
1976
+ *
1977
+ * DSH 0.2.2-rc.2 起常驻模式默认使用 `scoped-repl`(直接作为顶层脚本求值,不再套外层 `async function`),
1978
+ * 顶层 `return` 会触发编译期 `SyntaxError: Return statement is not allowed here`。此函数仅在最后一条
1979
+ * 顶层语句(括号深度为 0)以 `return` 开头且其后无其他顶层语句时,将其安全改写为顶层末尾表达式(若以
1980
+ * `{` 开头则包裹 `(...)` 避免被解析为代码块),既保住顶层绑定跨调用存活,又保留末尾表达式的完成值。
1981
+ */
1982
+ function sanitizeReplTopLevelReturn(code, programFormat, language) {
1983
+ if (language === "python" || !isReplFormat(programFormat)) return code;
1984
+ let depth = 0;
1985
+ let lastTopReturn = -1;
1986
+ let i = 0;
1987
+ const len = code.length;
1988
+ while (i < len) {
1989
+ const ch = code[i];
1990
+ if (ch === "/" && code[i + 1] === "/") {
1991
+ i += 2;
1992
+ while (i < len && code[i] !== "\n") i += 1;
1993
+ continue;
1994
+ }
1995
+ if (ch === "/" && code[i + 1] === "*") {
1996
+ i += 2;
1997
+ while (i < len && !(code[i] === "*" && code[i + 1] === "/")) i += 1;
1998
+ i += 2;
1999
+ continue;
2000
+ }
2001
+ if (ch === "'" || ch === "\"") {
2002
+ i = skipQuotedLiteral(code, i);
2003
+ continue;
2004
+ }
2005
+ if (ch === "`") {
2006
+ i = skipTemplateLiteral(code, i + 1);
2007
+ continue;
2008
+ }
2009
+ if (ch === "{" || ch === "(" || ch === "[") {
2010
+ depth += 1;
2011
+ i += 1;
2012
+ continue;
2013
+ }
2014
+ if (ch === "}" || ch === ")" || ch === "]") {
2015
+ if (depth > 0) depth -= 1;
2016
+ i += 1;
2017
+ continue;
2018
+ }
2019
+ if (depth === 0 && ch === "r" && code.startsWith("return", i)) {
2020
+ const prev = i > 0 ? code[i - 1] : "";
2021
+ const next = i + 6 < len ? code[i + 6] : "";
2022
+ if (!isIdentOrDotChar(prev) && !isIdentChar(next)) {
2023
+ lastTopReturn = i;
2024
+ i += 6;
2025
+ continue;
2026
+ }
2027
+ }
2028
+ i += 1;
2029
+ }
2030
+ if (lastTopReturn < 0) return code;
2031
+ const tail = analyzeTopLevelReturnTail(code, lastTopReturn + 6);
2032
+ if (tail === void 0) return code;
2033
+ const expr = code.slice(tail.exprStart, tail.exprEnd).trim();
2034
+ const prefix = code.slice(0, lastTopReturn);
2035
+ const suffix = code.slice(tail.statementEnd);
2036
+ if (expr.length === 0) return prefix + "undefined" + suffix;
2037
+ if (expr.startsWith("{")) return prefix + "(" + expr + ")" + suffix;
2038
+ return prefix + expr + suffix;
2039
+ }
2040
+ function isIdentChar(ch) {
2041
+ return ch.length > 0 && /[A-Za-z0-9_$]/.test(ch);
2042
+ }
2043
+ function isIdentOrDotChar(ch) {
2044
+ return ch === "." || isIdentChar(ch);
2045
+ }
2046
+ function skipQuotedLiteral(code, start) {
2047
+ const quote = code[start];
2048
+ let i = start + 1;
2049
+ while (i < code.length) {
2050
+ if (code[i] === "\\") {
2051
+ i += 2;
2052
+ continue;
2053
+ }
2054
+ if (code[i] === quote) return i + 1;
2055
+ i += 1;
2056
+ }
2057
+ return i;
2058
+ }
2059
+ function skipTemplateLiteral(code, startAfterBacktick) {
2060
+ let i = startAfterBacktick;
2061
+ const len = code.length;
2062
+ while (i < len) {
2063
+ const ch = code[i];
2064
+ if (ch === "\\") {
2065
+ i += 2;
2066
+ continue;
2067
+ }
2068
+ if (ch === "`") return i + 1;
2069
+ if (ch === "$" && code[i + 1] === "{") {
2070
+ i += 2;
2071
+ let braceDepth = 1;
2072
+ while (i < len && braceDepth > 0) {
2073
+ const inner = code[i];
2074
+ if (inner === "'" || inner === "\"") {
2075
+ i = skipQuotedLiteral(code, i);
2076
+ continue;
2077
+ }
2078
+ if (inner === "`") {
2079
+ i = skipTemplateLiteral(code, i + 1);
2080
+ continue;
2081
+ }
2082
+ if (inner === "{") braceDepth += 1;
2083
+ else if (inner === "}") braceDepth -= 1;
2084
+ i += 1;
2085
+ }
2086
+ continue;
2087
+ }
2088
+ i += 1;
2089
+ }
2090
+ return i;
2091
+ }
2092
+ function analyzeTopLevelReturnTail(code, afterReturn) {
2093
+ const len = code.length;
2094
+ let i = afterReturn;
2095
+ while (i < len && (code[i] === " " || code[i] === " ")) i += 1;
2096
+ const exprStart = i;
2097
+ let depth = 0;
2098
+ let semiPos = -1;
2099
+ while (i < len) {
2100
+ const ch = code[i];
2101
+ if (ch === "/" && code[i + 1] === "/") {
2102
+ i += 2;
2103
+ while (i < len && code[i] !== "\n") i += 1;
2104
+ continue;
2105
+ }
2106
+ if (ch === "/" && code[i + 1] === "*") {
2107
+ i += 2;
2108
+ while (i < len && !(code[i] === "*" && code[i + 1] === "/")) i += 1;
2109
+ i += 2;
2110
+ continue;
2111
+ }
2112
+ if (ch === "'" || ch === "\"") {
2113
+ i = skipQuotedLiteral(code, i);
2114
+ continue;
2115
+ }
2116
+ if (ch === "`") {
2117
+ i = skipTemplateLiteral(code, i + 1);
2118
+ continue;
2119
+ }
2120
+ if (ch === "{" || ch === "(" || ch === "[") {
2121
+ depth += 1;
2122
+ i += 1;
2123
+ continue;
2124
+ }
2125
+ if (ch === "}" || ch === ")" || ch === "]") {
2126
+ if (depth === 0) return void 0;
2127
+ depth -= 1;
2128
+ i += 1;
2129
+ continue;
2130
+ }
2131
+ if (depth === 0 && ch === ";") {
2132
+ semiPos = i;
2133
+ i += 1;
2134
+ break;
2135
+ }
2136
+ i += 1;
2137
+ }
2138
+ if (depth !== 0) return void 0;
2139
+ if (semiPos >= 0) {
2140
+ while (i < len) {
2141
+ const ch = code[i];
2142
+ if (/\s/.test(ch)) {
2143
+ i += 1;
2144
+ continue;
2145
+ }
2146
+ if (ch === "/" && code[i + 1] === "/") {
2147
+ i += 2;
2148
+ while (i < len && code[i] !== "\n") i += 1;
2149
+ continue;
2150
+ }
2151
+ if (ch === "/" && code[i + 1] === "*") {
2152
+ i += 2;
2153
+ while (i < len && !(code[i] === "*" && code[i + 1] === "/")) i += 1;
2154
+ i += 2;
2155
+ continue;
2156
+ }
2157
+ return;
2158
+ }
2159
+ return {
2160
+ exprStart,
2161
+ exprEnd: semiPos,
2162
+ statementEnd: semiPos + 1
2163
+ };
2164
+ }
2165
+ return {
2166
+ exprStart,
2167
+ exprEnd: len,
2168
+ statementEnd: len
2169
+ };
2170
+ }
1761
2171
  /** 内置按单文件 `file_path` 寻址的工具名。 */
1762
2172
  const FILE_PATH_TOOLS = /* @__PURE__ */ new Set([
1763
2173
  "read",
@@ -2632,6 +3042,18 @@ function apply(ctx, config = {}) {
2632
3042
  source: { kind: PLUGIN_MESSAGE_SOURCE_KIND }
2633
3043
  });
2634
3044
  },
3045
+ programImage(attachment, fallbackPath) {
3046
+ const runtime = runtimeOf();
3047
+ if (runtime === void 0 || runtime.language === "python") return void 0;
3048
+ if (typeof runtime.executionInstructions !== "string" || !runtime.executionInstructions.includes("inspect")) return;
3049
+ if (!isImageAttachmentRefLike(attachment)) return void 0;
3050
+ const resolveAccess = dshLlm["resolveImageAttachmentAccess"];
3051
+ if (typeof resolveAccess === "function") try {
3052
+ const access = resolveAccess(attachment);
3053
+ if (typeof access?.readonlyPath === "string" && access.readonlyPath.length > 0) return new PtcImageLike(access.readonlyPath, attachment);
3054
+ } catch {}
3055
+ if (typeof fallbackPath === "string" && fallbackPath.length > 0) return new PtcImageLike(fallbackPath, attachment);
3056
+ },
2635
3057
  trackRun: (run) => retention.trackRun(run),
2636
3058
  shapeDispatchLog,
2637
3059
  async callTool(request) {