@qwen-code/qwen-harness 0.1.9 → 0.1.11

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/README.md CHANGED
@@ -142,6 +142,9 @@ The concrete adaptations are:
142
142
  still apply. REPL state survives cells;
143
143
  compaction, Notes handoff, session replacement/resume, cancellation, and execution
144
144
  errors reset it. Unawaited work is cancelled when a cell ends.
145
+ Emitted images use Pi codemode's Base64 and format-signature checks; the actual
146
+ image signature determines the MIME type. Invalid output returns a tool error
147
+ so the model can correct it before another request.
145
148
  - **C2:** follows the local Qwen Code branch
146
149
  `dragon/local-notes-compaction@7ee219f032`: `session_notes` saves a versioned
147
150
  checkpoint, `new_context` stages a switch using that revision, and
@@ -180,9 +183,14 @@ The concrete adaptations are:
180
183
  in one ledger, with no extra call or child-count ceiling.
181
184
 
182
185
  All configurations use an 8,000-character observation preview and a 64,000-character
183
- ceiling for an individual feedback text payload. O runs before a result enters either
184
- the model or its JavaScript program; native structured output and internal spool paths
185
- cannot bypass O2. O3 saves the complete tool text or native Bash spool to a session-associated
186
+ ceiling for an individual feedback text payload. O applies only immediately before model
187
+ delivery: to the direct tool result in TC1, or the completed program output in TC2/TC3.
188
+ Internal `tools.xxx` calls keep their native content, structured output, error details,
189
+ limits and spool paths. Only explicitly emitted output enters the model's observation/history.
190
+ Typed image blocks are never text-cropped. Each delivered image is actually decoded;
191
+ an invalid image is replaced by error text without discarding other valid content.
192
+ Valid images, including 1×1 images, are not enlarged or subjected to provider minimum-size rules.
193
+ O3 saves the complete delivered text or native TC1 Bash spool to a session-associated
186
194
  file before applying the preview budget. The 64,000-character feedback ceiling does not
187
195
  truncate that file. Large native spools are copied in full and previewed with bounded reads;
188
196
  program output is also preserved before the requested display limit is applied.
@@ -191,7 +199,7 @@ O3 returns the file path and a reading hint: TS2 uses `read` with line offset/li
191
199
  `grep`; TS1/TS3 use `bash` to select lines or byte ranges. A long single-line result
192
200
  needs a byte-range read or a query of the saved data. These are the existing task tools,
193
201
  reached directly in TC1 or through `run_code`/`exec` in TC2/TC3. Every retrieval still
194
- passes through O and is included in usage accounting. Output files live under
202
+ passes through O at the model delivery boundary and is included in usage accounting. Output files live under
195
203
  `scaling-outputs/<session-id>/` in the session directory and remain available after resume.
196
204
 
197
205
  O3 output files are individual tool artifacts, so C1 can read them through its task
@@ -169,6 +169,49 @@ var init_harness_args = __esm({
169
169
  }
170
170
  });
171
171
 
172
+ // src/capabilities/tools/image-output.ts
173
+ import { PhotonImage } from "@silvia-odwyer/photon-node";
174
+ function prepareImageOutput(image, maxBytes) {
175
+ let reason;
176
+ if (typeof image.data !== "string") reason = "missing base64 image data";
177
+ else {
178
+ const data = image.data.replace(/\s+/gu, "");
179
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(data)) reason = "invalid base64 image data";
180
+ else {
181
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(data.slice(0, 16)));
182
+ if (!signature) reason = "expected PNG, JPEG, GIF, or WebP image data";
183
+ else if (maxBytes !== void 0 && Buffer.byteLength(data, "base64") > maxBytes) reason = "image exceeds the tool's byte limit";
184
+ else {
185
+ try {
186
+ const decoded = PhotonImage.new_from_byteslice(Buffer.from(data, "base64"));
187
+ decoded.free();
188
+ return { ...image, type: "image", data, mimeType: signature[0] };
189
+ } catch {
190
+ reason = "image decoder rejected the data";
191
+ }
192
+ }
193
+ }
194
+ }
195
+ return { type: "text", text: `${IMAGE_OMITTED_MESSAGE}: ${reason}.` };
196
+ }
197
+ function prepareToolOutputContent(content, maxBytes) {
198
+ return content.map((part) => part.type === "image" ? prepareImageOutput(part, maxBytes) : part);
199
+ }
200
+ var IMAGE_OMITTED_MESSAGE, MAX_EMITTED_IMAGE_BYTES, IMAGE_SIGNATURES;
201
+ var init_image_output = __esm({
202
+ "src/capabilities/tools/image-output.ts"() {
203
+ "use strict";
204
+ IMAGE_OMITTED_MESSAGE = "image content omitted because it could not be processed";
205
+ MAX_EMITTED_IMAGE_BYTES = 20 * 1024 * 1024;
206
+ IMAGE_SIGNATURES = [
207
+ ["image/png", /^iVBORw0KGg/u],
208
+ ["image/jpeg", /^[/]9j[/](?!9)/u],
209
+ ["image/gif", /^R0lGOD[dl]h/u],
210
+ ["image/webp", /^UklG.{8}RUJQ/u]
211
+ ];
212
+ }
213
+ });
214
+
172
215
  // src/capabilities/tools/programmatic-tool-calling/index.ts
173
216
  import { spawn as spawn2 } from "node:child_process";
174
217
  import path13 from "node:path";
@@ -275,7 +318,7 @@ function runCodeDescription(tools) {
275
318
  "declare function image(value: ImageContent | NestedToolResult): void;",
276
319
  "declare function setTimeout(callback: (...args: unknown[]) => void, delayMs?: number, ...args: unknown[]): string;",
277
320
  "declare function clearTimeout(handle: string): void;",
278
- 'type NestedToolResult = { content: Array<{ type: "text"; text: string } | ImageContent> };',
321
+ 'type NestedToolResult = { content: Array<{ type: "text"; text: string } | ImageContent>; isError?: boolean; structuredContent?: unknown; details?: unknown; terminate?: boolean };',
279
322
  "```",
280
323
  "",
281
324
  ...tools.map(nestedToolDescription)
@@ -312,6 +355,7 @@ function nestedResultValue(result, structured = false) {
312
355
  content: result.content,
313
356
  isError: result.isError ?? false,
314
357
  ...result.structuredContent === void 0 ? {} : { structuredContent: result.structuredContent },
358
+ ...result.details === void 0 ? {} : { details: result.details },
315
359
  ...result.terminate ? { terminate: true } : {}
316
360
  };
317
361
  const content = result.content.map((item) => item.type === "text" ? { type: "text", text: item.text } : { type: "image", data: item.data, mimeType: item.mimeType });
@@ -333,7 +377,7 @@ function cappedText(text, remaining) {
333
377
  used: remaining
334
378
  };
335
379
  }
336
- function emittedContent(value, maxOutputChars) {
380
+ function emittedContent(value, maxOutputChars, prepareImages = true) {
337
381
  if (!Array.isArray(value)) throw new Error("run_code child returned invalid content");
338
382
  const content = [];
339
383
  let remaining = maxOutputChars;
@@ -347,15 +391,8 @@ function emittedContent(value, maxOutputChars) {
347
391
  remaining -= capped.used;
348
392
  continue;
349
393
  }
350
- if (candidate.type === "image" && typeof candidate.data === "string" && typeof candidate.mimeType === "string") {
351
- if (Buffer.byteLength(candidate.data, "base64") > MAX_IMAGE_BYTES) {
352
- throw new Error("run_code image output exceeds the 20 MiB limit");
353
- }
354
- content.push({
355
- type: "image",
356
- data: candidate.data,
357
- mimeType: candidate.mimeType
358
- });
394
+ if (candidate.type === "image") {
395
+ content.push(prepareImages ? prepareImageOutput({ data: candidate.data, mimeType: candidate.mimeType }, MAX_EMITTED_IMAGE_BYTES) : { type: "image", data: candidate.data, mimeType: candidate.mimeType });
359
396
  }
360
397
  }
361
398
  return content.length ? content : [{ type: "text", text: "Code completed without emitted output." }];
@@ -618,18 +655,18 @@ function createProgrammaticToolCallingCapability(cwd = process.cwd(), options =
618
655
  extensionFactories: [createProgrammaticToolCallingExtension(cwd, options)]
619
656
  };
620
657
  }
621
- var RUN_CODE_TOOL_NAME, DEFAULT_IDLE_TIMEOUT_MS, DEFAULT_SYNC_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_OUTPUT_CHARS, MAX_OUTPUT_CHARS, MAX_IMAGE_BYTES, TRUNCATION_MARKER, RUN_CODE_CHILD_PATH, runCodeSchema, createCodeModeCapability;
658
+ var RUN_CODE_TOOL_NAME, DEFAULT_IDLE_TIMEOUT_MS, DEFAULT_SYNC_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_OUTPUT_CHARS, MAX_OUTPUT_CHARS, TRUNCATION_MARKER, RUN_CODE_CHILD_PATH, runCodeSchema, createCodeModeCapability;
622
659
  var init_programmatic_tool_calling = __esm({
623
660
  "src/capabilities/tools/programmatic-tool-calling/index.ts"() {
624
661
  "use strict";
625
662
  init_bash();
663
+ init_image_output();
626
664
  RUN_CODE_TOOL_NAME = "run_code";
627
665
  DEFAULT_IDLE_TIMEOUT_MS = 3e4;
628
666
  DEFAULT_SYNC_TIMEOUT_MS = 5e3;
629
667
  MAX_TIMEOUT_MS = 6e5;
630
668
  DEFAULT_MAX_OUTPUT_CHARS = 5e4;
631
669
  MAX_OUTPUT_CHARS = 2e5;
632
- MAX_IMAGE_BYTES = 20 * 1024 * 1024;
633
670
  TRUNCATION_MARKER = "\n... run_code output truncated ...\n";
634
671
  RUN_CODE_CHILD_PATH = fileURLToPath3(new URL("./child-runtime.js", import.meta.url));
635
672
  runCodeSchema = Type21.Object({
@@ -762,6 +799,7 @@ var init_persistent = __esm({
762
799
  metadata;
763
800
  idleTimeoutMs;
764
801
  retainFullOutput;
802
+ prepareImages;
765
803
  constructor(tools, idleTimeoutMs = 5e3, options = {}) {
766
804
  assertNestedTools(tools);
767
805
  if (tools.some((tool) => tool.name === "exec")) throw new Error("exec cannot call itself");
@@ -769,6 +807,7 @@ var init_persistent = __esm({
769
807
  this.tools = new Map(tools.map((tool) => [normalizedToolName(tool.name), tool]));
770
808
  this.idleTimeoutMs = idleTimeoutMs;
771
809
  this.retainFullOutput = options.retainFullOutput ?? false;
810
+ this.prepareImages = options.prepareImages ?? true;
772
811
  }
773
812
  post(message) {
774
813
  if (this.child?.stdin.writable) this.child.stdin.write(JSON.stringify(message) + "\n");
@@ -878,7 +917,7 @@ var init_persistent = __esm({
878
917
  }
879
918
  try {
880
919
  resolve({
881
- content: emittedContent(message.content, this.retainFullOutput ? Number.MAX_SAFE_INTEGER : params.max_output_chars ?? 64e3),
920
+ content: emittedContent(message.content, this.retainFullOutput ? Number.MAX_SAFE_INTEGER : params.max_output_chars ?? 64e3, this.prepareImages),
882
921
  details: { calls: cell.calls, generation: this.generation },
883
922
  ...cell.terminate ? { terminate: true } : {}
884
923
  });
@@ -1587,6 +1626,7 @@ var OUTPUT_ENTRY, OBSERVATION_ENTRY, ObservationPolicy;
1587
1626
  var init_observation = __esm({
1588
1627
  "src/harnesses/scaling/observation.ts"() {
1589
1628
  "use strict";
1629
+ init_image_output();
1590
1630
  init_tools();
1591
1631
  OUTPUT_ENTRY = "scaling-output";
1592
1632
  OBSERVATION_ENTRY = "scaling-observation";
@@ -1604,6 +1644,8 @@ var init_observation = __esm({
1604
1644
  this.pi = pi;
1605
1645
  }
1606
1646
  async apply(name, result, ctx, callId, outputLimit) {
1647
+ const prepared = prepareToolOutputContent(result.content, ["run_code", "exec"].includes(name) ? MAX_EMITTED_IMAGE_BYTES : void 0);
1648
+ const images = prepared.filter((_part, index) => result.content[index]?.type === "image");
1607
1649
  const source = nativeSource(name, result);
1608
1650
  const page = ["session_history", "memory_lookup"].includes(name);
1609
1651
  const budget = Math.min(this.design === "O1" || page ? this.limits.hardOutputChars : this.limits.previewChars, outputLimit ?? this.limits.hardOutputChars);
@@ -1629,7 +1671,7 @@ var init_observation = __esm({
1629
1671
  const readHint = this.taskTools === "TS2" ? "Use read with this path, offset (1-based line), and a small limit, or grep with path and pattern. For a long single line, use bash to read a byte range." : "Use bash with sed -n 'START,ENDp' to read selected lines or head/tail -c for byte ranges. Read bounded sections.";
1630
1672
  const content = [
1631
1673
  ...preview.text ? [{ type: "text", text: preview.text }] : [],
1632
- ...result.content.filter((part) => part.type === "image"),
1674
+ ...images,
1633
1675
  ...outputPath ? [{ type: "text", text: `Full output saved to: ${outputPath}
1634
1676
  ${readHint}` }] : [],
1635
1677
  { type: "text", text: `[tool status: ${JSON.stringify(status)}]` }
@@ -2159,7 +2201,7 @@ function createScalingCodemodeTool(tools) {
2159
2201
  description: [
2160
2202
  "Run JavaScript in Pi's codemode sandbox. Every call starts a fresh QuickJS environment.",
2161
2203
  "Call tools with tools.<name>(args) and await operations whose results or completion matter. Unawaited operations are cancelled when the script ends.",
2162
- "Each tool result includes content, isError, and optional structuredContent. Inspect isError to handle failed operations.",
2204
+ "Each tool result includes content, isError, and optional native structuredContent and details. Inspect isError to handle failed operations.",
2163
2205
  "Use text(value) or console.log(value) to emit text; use image(block) for an individual image content block or a base64 data URI. A returned value is also emitted.",
2164
2206
  "ALL_TOOLS lists the available tools. No Node, filesystem, network, setTimeout, or clearTimeout APIs are exposed; use the registered task tools.",
2165
2207
  "Variables, functions, and store/load values do not survive this call. Reconstruct needed values from the current context and available tools.",
@@ -2193,7 +2235,7 @@ function createScalingCodemodeTool(tools) {
2193
2235
  if (!result.ok) content.push({ type: "text", text: `Script ${result.error.kind}: ${result.error.message}` });
2194
2236
  return {
2195
2237
  // O receives the complete emitted output before applying its display/recovery policy.
2196
- content: emittedContent(content, Number.MAX_SAFE_INTEGER),
2238
+ content: emittedContent(content, Number.MAX_SAFE_INTEGER, false),
2197
2239
  details: { engine: "pi-codemode", calls: result.calls.map((call, index) => failedCalls.has(index) ? { ...call, status: "error" } : call) },
2198
2240
  ...result.ok ? {} : { isError: true },
2199
2241
  ...terminate ? { terminate: true } : {}
@@ -2215,7 +2257,8 @@ var init_codemode = __esm({
2215
2257
  Type27.Object({ type: Type27.Literal("image"), data: Type27.String(), mimeType: Type27.String() })
2216
2258
  ])),
2217
2259
  isError: Type27.Boolean(),
2218
- structuredContent: Type27.Optional(Type27.Record(Type27.String(), Type27.Unknown())),
2260
+ structuredContent: Type27.Optional(Type27.Unknown()),
2261
+ details: Type27.Optional(Type27.Unknown()),
2219
2262
  terminate: Type27.Optional(Type27.Boolean())
2220
2263
  });
2221
2264
  }
@@ -2579,10 +2622,12 @@ function createScalingRuntime(input, options = {}) {
2579
2622
  }
2580
2623
  };
2581
2624
  function guarded(tool, outer = false) {
2625
+ const delivered = outer || config.TC === "TC1";
2582
2626
  return {
2583
2627
  ...tool,
2584
- // O supplies a shared result schema instead of each native structured output.
2585
- outputSchema: void 0,
2628
+ // Only model delivery uses O's shared result shape. Programs retain
2629
+ // native content, structured results, and their schema.
2630
+ outputSchema: delivered ? void 0 : tool.outputSchema,
2586
2631
  exposure: outer ? "model-only" : config.TC === "TC1" ? "direct" : "codemode",
2587
2632
  async execute(id, args, signal, _update, ctx) {
2588
2633
  if (fatal) throw fatal;
@@ -2599,7 +2644,7 @@ function createScalingRuntime(input, options = {}) {
2599
2644
  if (signal?.aborted || fatal) throw error;
2600
2645
  result = { ...textResult(error instanceof Error ? error.message : String(error)), isError: true };
2601
2646
  }
2602
- const observed = await observation.apply(tool.name, result, ctx, id, outputLimit);
2647
+ const observed = delivered ? await observation.apply(tool.name, result, ctx, id, outputLimit) : result;
2603
2648
  if (config.C === "C2" && !outer && !["session_notes", "new_context", "session_history", "get_context_remaining", "memory_lookup"].includes(tool.name)) context.notes.workChanged();
2604
2649
  return observed;
2605
2650
  }
@@ -2625,7 +2670,7 @@ function createScalingRuntime(input, options = {}) {
2625
2670
  registered.push(guarded(tool, true));
2626
2671
  exposed = [tool.name];
2627
2672
  } else {
2628
- code = new PersistentCodeRuntime(registered, void 0, { retainFullOutput: true });
2673
+ code = new PersistentCodeRuntime(registered, void 0, { retainFullOutput: true, prepareImages: false });
2629
2674
  registered.push(guarded(createExecTool(code), true));
2630
2675
  exposed = ["exec"];
2631
2676
  }