@qwen-code/qwen-harness 0.1.3 → 0.1.5

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.
@@ -461,105 +461,80 @@ function createAskUserTool() {
461
461
  }
462
462
 
463
463
  // src/capabilities/tools/execution/bash.ts
464
- import { defineTool as defineTool2 } from "@earendil-works/pi-coding-agent";
465
- import { Type as Type2 } from "typebox";
466
- function agentArenaSchema(cwd) {
467
- return Type2.Object({
468
- command: Type2.String({ maxLength: 64e3 }),
469
- cwd: Type2.Optional(Type2.String({ minLength: 1, default: cwd })),
470
- timeout: Type2.Optional(Type2.Integer({ minimum: 1, maximum: 1800, default: 30 }))
471
- }, { additionalProperties: false });
472
- }
473
- var codeArenaFullStackSchema = Type2.Object({
474
- command: Type2.String(),
475
- workdir: Type2.String(),
476
- description: Type2.String()
477
- }, { additionalProperties: false });
478
- var outputLimit = 2e4;
479
- var truncationMarker = "\n... output truncated ...\n";
480
- function capOutput(value) {
481
- if (value.length <= outputLimit) return { text: value, truncated: false };
482
- const half = Math.floor((outputLimit - truncationMarker.length) / 2);
464
+ import {
465
+ createBashToolDefinition as createPiBashToolDefinition,
466
+ getAgentDir as getAgentDir2,
467
+ SettingsManager as SettingsManager2
468
+ } from "@earendil-works/pi-coding-agent";
469
+ var DEFAULT_BASH_TIMEOUT_SECONDS = 120;
470
+ function applyDefaultTimeout(input, timeoutSeconds) {
471
+ if (input.timeout === void 0) input.timeout = timeoutSeconds;
472
+ return input;
473
+ }
474
+ function createBashToolDefinition(cwd = process.cwd(), options = {}) {
475
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
476
+ const settings = SettingsManager2.create(cwd, getAgentDir2(), { projectTrusted: false });
477
+ const piBash = createPiBashToolDefinition(cwd, {
478
+ commandPrefix: settings.getShellCommandPrefix(),
479
+ shellPath: settings.getShellPath()
480
+ });
481
+ const preparePiArguments = piBash.prepareArguments;
482
+ const timeoutSchema = piBash.parameters.properties.timeout;
483
483
  return {
484
- text: value.slice(0, half) + truncationMarker + value.slice(-half),
485
- truncated: true
484
+ ...piBash,
485
+ parameters: {
486
+ ...piBash.parameters,
487
+ properties: {
488
+ ...piBash.parameters.properties,
489
+ timeout: {
490
+ ...timeoutSchema,
491
+ default: timeoutSeconds,
492
+ description: `Timeout in seconds (default: ${timeoutSeconds})`
493
+ }
494
+ }
495
+ },
496
+ prepareArguments(input) {
497
+ const prepared = preparePiArguments ? preparePiArguments(input) : structuredClone(input);
498
+ return applyDefaultTimeout(prepared, timeoutSeconds);
499
+ }
486
500
  };
487
501
  }
488
- function createAgentArenaBashTool(cwd, exec, shell) {
489
- return defineTool2({
502
+ function createBashExtension(cwd = process.cwd(), options = {}) {
503
+ return {
490
504
  name: "bash",
491
- label: "Bash",
492
- description: "Run a bash command in the workspace. Each call is isolated and returns separate stdout and stderr.",
493
- promptSnippet: "Run shell commands in the workspace",
494
- parameters: agentArenaSchema(cwd),
495
- async execute(_toolCallId, params, signal) {
496
- const workdir = await resolveWorkspacePath(cwd, params.cwd || ".");
497
- const startedAt = Date.now();
498
- const result = await exec(shell.command, [...shell.args, params.command], {
499
- cwd: workdir,
500
- timeout: (params.timeout || 30) * 1e3,
501
- signal
502
- });
503
- const stdout = capOutput(result.stdout);
504
- const stderr = capOutput(result.stderr);
505
- return jsonToolResult({
506
- status: "completed",
507
- stdout: stdout.text,
508
- stderr: stderr.text,
509
- exit_code: result.killed ? null : result.code,
510
- duration_ms: Date.now() - startedAt,
511
- stdout_truncated: stdout.truncated,
512
- stderr_truncated: stderr.truncated
513
- });
505
+ factory(pi) {
506
+ pi.registerTool(createBashToolDefinition(cwd, options));
514
507
  }
515
- });
508
+ };
516
509
  }
517
- function createCodeArenaFullStackBashTool(cwd, exec, settings, shell) {
518
- return defineTool2({
510
+ function createBashCapability(cwd = process.cwd(), options = {}) {
511
+ return {
519
512
  name: "bash",
520
- label: "Bash",
521
- description: "Execute a bash command directly in the local project workspace.",
522
- promptSnippet: "Run shell commands in the project",
523
- parameters: codeArenaFullStackSchema,
524
- async execute(_toolCallId, params, signal) {
525
- const workdir = await resolveWorkspacePath(cwd, params.workdir || ".");
526
- const timeoutSeconds = settings?.bashTimeoutSeconds || 300;
527
- const result = await exec(shell.command, [...shell.args, params.command], {
528
- cwd: workdir,
529
- timeout: timeoutSeconds * 1e3,
530
- signal
531
- });
532
- const value = result.code === 0 && !result.killed ? { status: "success", stdout: result.stdout, stderr: result.stderr } : {
533
- status: "error",
534
- message: `Command exited with code ${result.killed ? -1 : result.code}`,
535
- stdout: result.stdout,
536
- stderr: result.stderr
537
- };
538
- return jsonToolResult(value);
539
- }
540
- });
513
+ tools: ["bash"],
514
+ extensionFactories: [createBashExtension(cwd, options)]
515
+ };
541
516
  }
542
517
 
543
518
  // src/capabilities/tools/filesystem/edit_file.ts
544
- import { createEditToolDefinition, defineTool as defineTool3 } from "@earendil-works/pi-coding-agent";
545
- import { Type as Type3 } from "typebox";
546
- var agentArenaSchema2 = Type3.Object({
547
- path: Type3.String(),
548
- old_text: Type3.String({ minLength: 1 }),
549
- new_text: Type3.String()
519
+ import { createEditToolDefinition, defineTool as defineTool2 } from "@earendil-works/pi-coding-agent";
520
+ import { Type as Type2 } from "typebox";
521
+ var agentArenaSchema = Type2.Object({
522
+ path: Type2.String(),
523
+ old_text: Type2.String({ minLength: 1 }),
524
+ new_text: Type2.String()
550
525
  }, { additionalProperties: false });
551
- var codeSchema = Type3.Object({
552
- path: Type3.String(),
553
- context: Type3.String(),
554
- replacement: Type3.String()
526
+ var codeSchema = Type2.Object({
527
+ path: Type2.String(),
528
+ context: Type2.String(),
529
+ replacement: Type2.String()
555
530
  }, { additionalProperties: false });
556
531
  function createAgentArenaEditFileTool(cwd) {
557
- return defineTool3({
532
+ return defineTool2({
558
533
  name: "edit_file",
559
534
  label: "Edit File",
560
535
  description: "Edit an existing file by replacing one exact text block.",
561
536
  promptSnippet: "Edit files with exact text replacement",
562
- parameters: agentArenaSchema2,
537
+ parameters: agentArenaSchema,
563
538
  async execute(toolCallId, params, signal, _onUpdate, context) {
564
539
  const path17 = await resolveWorkspacePath(cwd, params.path);
565
540
  const nativeEdit = createEditToolDefinition(cwd);
@@ -575,7 +550,7 @@ function createAgentArenaEditFileTool(cwd) {
575
550
  });
576
551
  }
577
552
  function createCodeEditFileTool(cwd) {
578
- return defineTool3({
553
+ return defineTool2({
579
554
  name: "edit_file",
580
555
  label: "Edit File",
581
556
  description: "Replace one exact section of content in a project file.",
@@ -600,9 +575,9 @@ function createCodeEditFileTool(cwd) {
600
575
  import { readFile as readFile3 } from "node:fs/promises";
601
576
  import {
602
577
  createReadToolDefinition,
603
- defineTool as defineTool4
578
+ defineTool as defineTool3
604
579
  } from "@earendil-works/pi-coding-agent";
605
- import { Type as Type4 } from "typebox";
580
+ import { Type as Type3 } from "typebox";
606
581
 
607
582
  // src/utils/filesystem/document_reader.ts
608
583
  import { spawn } from "node:child_process";
@@ -1101,13 +1076,13 @@ async function captionImageRead(params, signal, context, settings) {
1101
1076
  }
1102
1077
 
1103
1078
  // src/capabilities/tools/filesystem/read_file.ts
1104
- var agentArenaReadFileSchema = Type4.Object({
1105
- path: Type4.String({ description: "File path inside the workspace" })
1079
+ var agentArenaReadFileSchema = Type3.Object({
1080
+ path: Type3.String({ description: "File path inside the workspace" })
1106
1081
  }, { additionalProperties: false });
1107
- var codeReadFileSchema = Type4.Object({
1108
- path: Type4.String({ description: "File path relative to project root" }),
1109
- offset: Type4.Optional(Type4.Integer({ minimum: 1, description: "1-indexed start line" })),
1110
- limit: Type4.Optional(Type4.Integer({ minimum: 1, description: "Maximum lines to read" }))
1082
+ var codeReadFileSchema = Type3.Object({
1083
+ path: Type3.String({ description: "File path relative to project root" }),
1084
+ offset: Type3.Optional(Type3.Integer({ minimum: 1, description: "1-indexed start line" })),
1085
+ limit: Type3.Optional(Type3.Integer({ minimum: 1, description: "Maximum lines to read" }))
1111
1086
  }, { additionalProperties: false });
1112
1087
  function imageCaptionToolResult(caption) {
1113
1088
  return {
@@ -1132,7 +1107,7 @@ function imageCaptionToolResult(caption) {
1132
1107
  }
1133
1108
  function createAgentArenaReadFileTool(cwd, imageCaptionSettings, documentSettings) {
1134
1109
  const nativeRead = createReadToolDefinition(cwd);
1135
- return defineTool4({
1110
+ return defineTool3({
1136
1111
  name: "read_file",
1137
1112
  label: "Read File",
1138
1113
  description: "Read a workspace file. Pi's native read tool handles text and images; structured documents use the document extractor.",
@@ -1167,7 +1142,7 @@ function createAgentArenaReadFileTool(cwd, imageCaptionSettings, documentSetting
1167
1142
  }
1168
1143
  function createCodeReadFileTool(cwd, imageCaptionSettings) {
1169
1144
  const nativeRead = createReadToolDefinition(cwd);
1170
- return defineTool4({
1145
+ return defineTool3({
1171
1146
  name: "read_file",
1172
1147
  label: "Read File",
1173
1148
  description: "Read an existing project file. Supports Pi's native offset and limit parameters.",
@@ -1189,14 +1164,14 @@ function createCodeReadFileTool(cwd, imageCaptionSettings) {
1189
1164
  }
1190
1165
 
1191
1166
  // src/capabilities/tools/filesystem/write_file.ts
1192
- import { createWriteToolDefinition, defineTool as defineTool5 } from "@earendil-works/pi-coding-agent";
1193
- import { Type as Type5 } from "typebox";
1194
- var schema = Type5.Object(
1195
- { path: Type5.String(), content: Type5.String() },
1167
+ import { createWriteToolDefinition, defineTool as defineTool4 } from "@earendil-works/pi-coding-agent";
1168
+ import { Type as Type4 } from "typebox";
1169
+ var schema = Type4.Object(
1170
+ { path: Type4.String(), content: Type4.String() },
1196
1171
  { additionalProperties: false }
1197
1172
  );
1198
1173
  function createWriteFileTool(cwd) {
1199
- return defineTool5({
1174
+ return defineTool4({
1200
1175
  name: "write_file",
1201
1176
  label: "Write File",
1202
1177
  description: "Create or overwrite a workspace file with complete content.",
@@ -1215,16 +1190,16 @@ function createWriteFileTool(cwd) {
1215
1190
  import { mkdir as mkdir2, readFile as readFile4, writeFile } from "node:fs/promises";
1216
1191
  import path4 from "node:path";
1217
1192
  import { setTimeout as delay2 } from "node:timers/promises";
1218
- import { defineTool as defineTool6 } from "@earendil-works/pi-coding-agent";
1219
- import { Type as Type6 } from "typebox";
1220
- var agentArenaSchema3 = Type6.Object({
1221
- file_path: Type6.String(),
1222
- prompt: Type6.String(),
1223
- images: Type6.Optional(Type6.Array(Type6.String(), { maxItems: 10 }))
1193
+ import { defineTool as defineTool5 } from "@earendil-works/pi-coding-agent";
1194
+ import { Type as Type5 } from "typebox";
1195
+ var agentArenaSchema2 = Type5.Object({
1196
+ file_path: Type5.String(),
1197
+ prompt: Type5.String(),
1198
+ images: Type5.Optional(Type5.Array(Type5.String(), { maxItems: 10 }))
1224
1199
  }, { additionalProperties: false });
1225
- var codeSchema2 = Type6.Object({
1226
- file_path: Type6.String(),
1227
- prompt: Type6.String()
1200
+ var codeSchema2 = Type5.Object({
1201
+ file_path: Type5.String(),
1202
+ prompt: Type5.String()
1228
1203
  }, { additionalProperties: false });
1229
1204
  var imageMimeTypes2 = {
1230
1205
  ".jpg": "image/jpeg",
@@ -1234,8 +1209,8 @@ var imageMimeTypes2 = {
1234
1209
  };
1235
1210
  function createGenerateImageTool(cwd, variant, settings, dashScope) {
1236
1211
  let generatedCount = 0;
1237
- const parameters = variant === "agent-arena" ? agentArenaSchema3 : codeSchema2;
1238
- return defineTool6({
1212
+ const parameters = variant === "agent-arena" ? agentArenaSchema2 : codeSchema2;
1213
+ return defineTool5({
1239
1214
  name: "generate_image",
1240
1215
  label: "Generate Image",
1241
1216
  description: "Generate an image with DashScope and save it into the workspace.",
@@ -1319,27 +1294,27 @@ function createGenerateImageTool(cwd, variant, settings, dashScope) {
1319
1294
  // src/capabilities/tools/media/generate_speech.ts
1320
1295
  import { mkdir as mkdir3, writeFile as writeFile2 } from "node:fs/promises";
1321
1296
  import path5 from "node:path";
1322
- import { defineTool as defineTool7 } from "@earendil-works/pi-coding-agent";
1323
- import { Type as Type7 } from "typebox";
1324
- var schema2 = Type7.Object({
1325
- file_path: Type7.String(),
1326
- text: Type7.String({ minLength: 1, maxLength: 1500 }),
1327
- language: Type7.String(),
1328
- voice_identity: Type7.Optional(Type7.Object({
1329
- gender: Type7.Optional(Type7.Union([Type7.Literal("feminine"), Type7.Literal("masculine")])),
1330
- use_case: Type7.Optional(Type7.Union([
1331
- Type7.Literal("narration"),
1332
- Type7.Literal("conversational"),
1333
- Type7.Literal("advertising"),
1334
- Type7.Literal("entertainment"),
1335
- Type7.Literal("educational"),
1336
- Type7.Literal("characters")
1297
+ import { defineTool as defineTool6 } from "@earendil-works/pi-coding-agent";
1298
+ import { Type as Type6 } from "typebox";
1299
+ var schema2 = Type6.Object({
1300
+ file_path: Type6.String(),
1301
+ text: Type6.String({ minLength: 1, maxLength: 1500 }),
1302
+ language: Type6.String(),
1303
+ voice_identity: Type6.Optional(Type6.Object({
1304
+ gender: Type6.Optional(Type6.Union([Type6.Literal("feminine"), Type6.Literal("masculine")])),
1305
+ use_case: Type6.Optional(Type6.Union([
1306
+ Type6.Literal("narration"),
1307
+ Type6.Literal("conversational"),
1308
+ Type6.Literal("advertising"),
1309
+ Type6.Literal("entertainment"),
1310
+ Type6.Literal("educational"),
1311
+ Type6.Literal("characters")
1337
1312
  ])),
1338
- index: Type7.Optional(Type7.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }))
1313
+ index: Type6.Optional(Type6.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }))
1339
1314
  }, { additionalProperties: false }))
1340
1315
  }, { additionalProperties: false });
1341
1316
  function createGenerateSpeechTool(cwd, settings, dashScope) {
1342
- return defineTool7({
1317
+ return defineTool6({
1343
1318
  name: "generate_speech",
1344
1319
  label: "Generate Speech",
1345
1320
  description: "Synthesize spoken audio with DashScope and save it into the workspace.",
@@ -1380,8 +1355,8 @@ function createGenerateSpeechTool(cwd, settings, dashScope) {
1380
1355
  }
1381
1356
 
1382
1357
  // src/capabilities/tools/web/fetch_page.ts
1383
- import { defineTool as defineTool8 } from "@earendil-works/pi-coding-agent";
1384
- import { Type as Type8 } from "typebox";
1358
+ import { defineTool as defineTool7 } from "@earendil-works/pi-coding-agent";
1359
+ import { Type as Type7 } from "typebox";
1385
1360
 
1386
1361
  // src/utils/clients/web/routify_client.ts
1387
1362
  function record3(value) {
@@ -1515,9 +1490,9 @@ async function executeRoutifyWebFetch(url, format, options) {
1515
1490
  // src/capabilities/tools/web/fetch_page.ts
1516
1491
  var CHUNK_SIZE = 8e3;
1517
1492
  var MAX_CACHE_ENTRIES = 16;
1518
- var schema3 = Type8.Object({
1519
- url: Type8.String({ format: "uri" }),
1520
- chunkIndex: Type8.Optional(Type8.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, default: 0 }))
1493
+ var schema3 = Type7.Object({
1494
+ url: Type7.String({ format: "uri" }),
1495
+ chunkIndex: Type7.Optional(Type7.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, default: 0 }))
1521
1496
  }, { additionalProperties: false });
1522
1497
  function splitMarkdown(value) {
1523
1498
  const markdown = value.replace(/\r\n?/g, "\n").trim();
@@ -1558,7 +1533,7 @@ function normalizedUrl(value) {
1558
1533
  }
1559
1534
  function createFetchPageTool(routify, retry) {
1560
1535
  const cache = /* @__PURE__ */ new Map();
1561
- return defineTool8({
1536
+ return defineTool7({
1562
1537
  name: "fetch_page",
1563
1538
  label: "Fetch Page",
1564
1539
  description: "Retrieve a web page as chunked markdown.",
@@ -1603,8 +1578,8 @@ function createFetchPageTool(routify, retry) {
1603
1578
  // src/capabilities/tools/web/image_search.ts
1604
1579
  import { mkdir as mkdir4, writeFile as writeFile3 } from "node:fs/promises";
1605
1580
  import path6 from "node:path";
1606
- import { defineTool as defineTool9 } from "@earendil-works/pi-coding-agent";
1607
- import { Type as Type9 } from "typebox";
1581
+ import { defineTool as defineTool8 } from "@earendil-works/pi-coding-agent";
1582
+ import { Type as Type8 } from "typebox";
1608
1583
 
1609
1584
  // src/utils/clients/web/search_client.ts
1610
1585
  function record4(value) {
@@ -1807,15 +1782,15 @@ async function executeBraveWebSearch(query, depth, options) {
1807
1782
  }
1808
1783
 
1809
1784
  // src/capabilities/tools/web/image_search.ts
1810
- var schema4 = Type9.Object({
1811
- query: Type9.String({ minLength: 1, maxLength: 400 }),
1812
- count: Type9.Integer({ minimum: 1, maximum: 5 })
1785
+ var schema4 = Type8.Object({
1786
+ query: Type8.String({ minLength: 1, maxLength: 400 }),
1787
+ count: Type8.Integer({ minimum: 1, maximum: 5 })
1813
1788
  }, { additionalProperties: false });
1814
1789
  function record5(value) {
1815
1790
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1816
1791
  }
1817
1792
  function createImageSearchTool(cwd, routify, retry) {
1818
- return defineTool9({
1793
+ return defineTool8({
1819
1794
  name: "image_search",
1820
1795
  label: "Image Search",
1821
1796
  description: "Search the web for images and save the selected results into the workspace.",
@@ -1861,14 +1836,14 @@ function createImageSearchTool(cwd, routify, retry) {
1861
1836
  }
1862
1837
 
1863
1838
  // src/capabilities/tools/web/web_search.ts
1864
- import { defineTool as defineTool10 } from "@earendil-works/pi-coding-agent";
1865
- import { Type as Type10 } from "typebox";
1866
- var schema5 = Type10.Object({
1867
- query: Type10.String({ minLength: 1, maxLength: 400 }),
1868
- depth: Type10.Union([Type10.Literal("1"), Type10.Literal("2"), Type10.Literal("3")])
1839
+ import { defineTool as defineTool9 } from "@earendil-works/pi-coding-agent";
1840
+ import { Type as Type9 } from "typebox";
1841
+ var schema5 = Type9.Object({
1842
+ query: Type9.String({ minLength: 1, maxLength: 400 }),
1843
+ depth: Type9.Union([Type9.Literal("1"), Type9.Literal("2"), Type9.Literal("3")])
1869
1844
  }, { additionalProperties: false });
1870
1845
  function createWebSearchTool(profile, settings, routify, retry) {
1871
- return defineTool10({
1846
+ return defineTool9({
1872
1847
  name: "web_search",
1873
1848
  label: "Web Search",
1874
1849
  description: "Search the web for current information and return relevant titles, URLs, and content snippets.",
@@ -1887,6 +1862,54 @@ function createWebSearchTool(profile, settings, routify, retry) {
1887
1862
  });
1888
1863
  }
1889
1864
 
1865
+ // src/runtime/harness-capabilities.ts
1866
+ function unique(items) {
1867
+ return [...new Set(items)];
1868
+ }
1869
+ function promptPhaseRank(prompt) {
1870
+ return prompt.phase === "orchestration" ? 1 : 0;
1871
+ }
1872
+ function composeHarnessCapabilities(capabilities) {
1873
+ const names = /* @__PURE__ */ new Set();
1874
+ for (const capability of capabilities) {
1875
+ if (!capability.name.trim()) {
1876
+ throw new Error("Harness capability names must not be empty.");
1877
+ }
1878
+ if (names.has(capability.name)) {
1879
+ throw new Error(`Duplicate harness capability: ${capability.name}`);
1880
+ }
1881
+ names.add(capability.name);
1882
+ }
1883
+ const prompts = capabilities.flatMap(
1884
+ (capability, capabilityIndex) => (capability.appendSystemPrompts ?? []).map((prompt, promptIndex) => ({
1885
+ capabilityIndex,
1886
+ prompt,
1887
+ promptIndex
1888
+ }))
1889
+ ).filter(({ prompt }) => prompt.text.trim().length > 0).sort(
1890
+ (left, right) => promptPhaseRank(left.prompt) - promptPhaseRank(right.prompt) || left.capabilityIndex - right.capabilityIndex || left.promptIndex - right.promptIndex
1891
+ ).map(({ prompt }) => prompt.text);
1892
+ return {
1893
+ appendSystemPrompts: prompts,
1894
+ extensionFactories: capabilities.flatMap(
1895
+ (capability) => capability.extensionFactories ?? []
1896
+ ),
1897
+ extensionPaths: unique(capabilities.flatMap(
1898
+ (capability) => capability.extensionPaths ?? []
1899
+ )),
1900
+ prepare: capabilities.flatMap(
1901
+ (capability) => capability.prepare ? [capability.prepare] : []
1902
+ ),
1903
+ tools: unique(capabilities.flatMap((capability) => capability.tools ?? [])),
1904
+ trustProjectResources: capabilities.some(
1905
+ (capability) => capability.trustProjectResources === true
1906
+ )
1907
+ };
1908
+ }
1909
+ async function prepareHarnessCapabilities(capabilities) {
1910
+ for (const prepare of capabilities.prepare) await prepare();
1911
+ }
1912
+
1890
1913
  // src/runtime/harness-main.ts
1891
1914
  import {
1892
1915
  main as piMain
@@ -1953,54 +1976,6 @@ function isolateHarnessArgs(args, systemPrompt, options = {}) {
1953
1976
  ];
1954
1977
  }
1955
1978
 
1956
- // src/runtime/harness-capabilities.ts
1957
- function unique(items) {
1958
- return [...new Set(items)];
1959
- }
1960
- function promptPhaseRank(prompt) {
1961
- return prompt.phase === "orchestration" ? 1 : 0;
1962
- }
1963
- function composeHarnessCapabilities(capabilities) {
1964
- const names = /* @__PURE__ */ new Set();
1965
- for (const capability of capabilities) {
1966
- if (!capability.name.trim()) {
1967
- throw new Error("Harness capability names must not be empty.");
1968
- }
1969
- if (names.has(capability.name)) {
1970
- throw new Error(`Duplicate harness capability: ${capability.name}`);
1971
- }
1972
- names.add(capability.name);
1973
- }
1974
- const prompts = capabilities.flatMap(
1975
- (capability, capabilityIndex) => (capability.appendSystemPrompts ?? []).map((prompt, promptIndex) => ({
1976
- capabilityIndex,
1977
- prompt,
1978
- promptIndex
1979
- }))
1980
- ).filter(({ prompt }) => prompt.text.trim().length > 0).sort(
1981
- (left, right) => promptPhaseRank(left.prompt) - promptPhaseRank(right.prompt) || left.capabilityIndex - right.capabilityIndex || left.promptIndex - right.promptIndex
1982
- ).map(({ prompt }) => prompt.text);
1983
- return {
1984
- appendSystemPrompts: prompts,
1985
- extensionFactories: capabilities.flatMap(
1986
- (capability) => capability.extensionFactories ?? []
1987
- ),
1988
- extensionPaths: unique(capabilities.flatMap(
1989
- (capability) => capability.extensionPaths ?? []
1990
- )),
1991
- prepare: capabilities.flatMap(
1992
- (capability) => capability.prepare ? [capability.prepare] : []
1993
- ),
1994
- tools: unique(capabilities.flatMap((capability) => capability.tools ?? [])),
1995
- trustProjectResources: capabilities.some(
1996
- (capability) => capability.trustProjectResources === true
1997
- )
1998
- };
1999
- }
2000
- async function prepareHarnessCapabilities(capabilities) {
2001
- for (const prepare of capabilities.prepare) await prepare();
2002
- }
2003
-
2004
1979
  // src/runtime/harness-main.ts
2005
1980
  function createHarnessExtensionFactories(extensionFactories = []) {
2006
1981
  return [createSessionAffinityCapability(), ...extensionFactories];
@@ -2095,12 +2070,10 @@ function createAgentArenaExtension(cwd, settings) {
2095
2070
  return {
2096
2071
  name: "agent-arena-tools",
2097
2072
  factory(pi) {
2098
- const exec = (command, args, options) => pi.exec(command, args, options);
2099
2073
  const dashScope = createDashScopeClient(
2100
2074
  settings.infrastructure.dashScope,
2101
2075
  settings.pi.retry
2102
2076
  );
2103
- pi.registerTool(createAgentArenaBashTool(cwd, exec, settings.pi.shell));
2104
2077
  pi.registerTool(createAskUserTool());
2105
2078
  pi.registerTool(createAgentArenaEditFileTool(cwd));
2106
2079
  pi.registerTool(createAgentArenaReadFileTool(
@@ -2138,25 +2111,35 @@ function createAgentArenaExtension(cwd, settings) {
2138
2111
  }
2139
2112
  };
2140
2113
  }
2114
+ function createAgentArenaExtensions(cwd, settings) {
2115
+ const capabilities = composeHarnessCapabilities([
2116
+ createBashCapability(cwd)
2117
+ ]);
2118
+ return [
2119
+ ...capabilities.extensionFactories,
2120
+ createAgentArenaExtension(cwd, settings)
2121
+ ];
2122
+ }
2141
2123
  async function runAgentArenaHarness(args) {
2142
2124
  const cwd = process.cwd();
2143
2125
  const settings = loadCapabilitySettings(cwd);
2144
- await runHarnessMain(buildAgentArenaArgs(args, cwd), [
2145
- createAgentArenaExtension(cwd, settings)
2146
- ]);
2126
+ await runHarnessMain(
2127
+ buildAgentArenaArgs(args, cwd),
2128
+ createAgentArenaExtensions(cwd, settings)
2129
+ );
2147
2130
  }
2148
2131
 
2149
2132
  // src/capabilities/tools/context-management/compact_context.ts
2150
- import { defineTool as defineTool11 } from "@earendil-works/pi-coding-agent";
2151
- import { Type as Type11 } from "typebox";
2133
+ import { defineTool as defineTool10 } from "@earendil-works/pi-coding-agent";
2134
+ import { Type as Type10 } from "typebox";
2152
2135
  var COMPACT_CONTEXT_TOOL_NAME = "compact_context";
2153
- var compactContextParameters = Type11.Object({
2154
- reason: Type11.String({
2136
+ var compactContextParameters = Type10.Object({
2137
+ reason: Type10.String({
2155
2138
  description: "Why all SelfCompact gates pass now: identify the closed work unit, concrete progress, why the state is safely summarizable, and evidence that the task is not stuck.",
2156
2139
  minLength: 1,
2157
2140
  maxLength: 2e3
2158
2141
  }),
2159
- preserve: Type11.Optional(Type11.Array(Type11.String({
2142
+ preserve: Type10.Optional(Type10.Array(Type10.String({
2160
2143
  description: "A fact, decision, artifact, constraint, or next step that the compacted context must preserve.",
2161
2144
  minLength: 1,
2162
2145
  maxLength: 500
@@ -2166,7 +2149,7 @@ var compactContextParameters = Type11.Object({
2166
2149
  }))
2167
2150
  }, { additionalProperties: false });
2168
2151
  function createCompactContextTool(scheduleCompaction) {
2169
- return defineTool11({
2152
+ return defineTool10({
2170
2153
  name: COMPACT_CONTEXT_TOOL_NAME,
2171
2154
  label: "Compact Context",
2172
2155
  description: "Compact the accumulated conversation at a useful semantic boundary. The runtime finishes the current tool turn, runs Pi's native compactor, and then automatically continues the task from the compacted context. Call this as the only tool in the turn.",
@@ -2377,10 +2360,14 @@ function buildSelfCompactArgs(args) {
2377
2360
  isolatedResources: NATIVE_PI_ISOLATED_RESOURCES
2378
2361
  });
2379
2362
  }
2380
- async function runSelfCompactHarness(args) {
2381
- const capabilities = composeHarnessCapabilities([
2363
+ function createSelfCompactHarnessCapabilities(cwd = process.cwd()) {
2364
+ return composeHarnessCapabilities([
2365
+ createBashCapability(cwd),
2382
2366
  createSelfCompactCapability()
2383
2367
  ]);
2368
+ }
2369
+ async function runSelfCompactHarness(args) {
2370
+ const capabilities = createSelfCompactHarnessCapabilities();
2384
2371
  await prepareHarnessCapabilities(capabilities);
2385
2372
  await runHarnessMain(
2386
2373
  buildSelfCompactArgs(args),
@@ -2396,9 +2383,9 @@ import { existsSync as existsSync2 } from "node:fs";
2396
2383
  import { mkdir as mkdir5, readFile as readFile5 } from "node:fs/promises";
2397
2384
  import path9 from "node:path";
2398
2385
  import { setTimeout as delay3 } from "node:timers/promises";
2399
- import { defineTool as defineTool12 } from "@earendil-works/pi-coding-agent";
2400
- import { Type as Type12 } from "typebox";
2401
- var schema6 = Type12.Object({ description: Type12.String() }, { additionalProperties: false });
2386
+ import { defineTool as defineTool11 } from "@earendil-works/pi-coding-agent";
2387
+ import { Type as Type11 } from "typebox";
2388
+ var schema6 = Type11.Object({ description: Type11.String() }, { additionalProperties: false });
2402
2389
  function failure(stage, message, logs) {
2403
2390
  return jsonToolResult({
2404
2391
  status: "error",
@@ -2408,7 +2395,7 @@ function failure(stage, message, logs) {
2408
2395
  });
2409
2396
  }
2410
2397
  function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
2411
- return defineTool12({
2398
+ return defineTool11({
2412
2399
  name: "build_and_start",
2413
2400
  label: "Build And Start",
2414
2401
  description: "Build and start the full-stack preview, then verify /api/health.",
@@ -2486,14 +2473,14 @@ function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
2486
2473
  }
2487
2474
 
2488
2475
  // src/capabilities/tools/execution/install_npm_packages.ts
2489
- import { defineTool as defineTool13 } from "@earendil-works/pi-coding-agent";
2490
- import { Type as Type13 } from "typebox";
2491
- var schema7 = Type13.Object({ packages: Type13.Array(Type13.String()) }, { additionalProperties: false });
2476
+ import { defineTool as defineTool12 } from "@earendil-works/pi-coding-agent";
2477
+ import { Type as Type12 } from "typebox";
2478
+ var schema7 = Type12.Object({ packages: Type12.Array(Type12.String()) }, { additionalProperties: false });
2492
2479
  function packageNameIsSafe(value) {
2493
2480
  return Boolean(value) && !value.startsWith("-") && !/\s/u.test(value) && /^(?:@[\w.-]+\/)?[\w.-]+(?:@(?:[\w*^<>=|.+-]+))?$/u.test(value);
2494
2481
  }
2495
2482
  function createInstallNpmPackagesTool(cwd, exec, packageLock, npmCommand) {
2496
- return defineTool13({
2483
+ return defineTool12({
2497
2484
  name: "install_npm_packages",
2498
2485
  label: "Install NPM Packages",
2499
2486
  description: "Install npm packages as project dependencies.",
@@ -2517,14 +2504,14 @@ function createInstallNpmPackagesTool(cwd, exec, packageLock, npmCommand) {
2517
2504
  }
2518
2505
 
2519
2506
  // src/capabilities/tools/filesystem/create_file.ts
2520
- import { createWriteToolDefinition as createWriteToolDefinition2, defineTool as defineTool14 } from "@earendil-works/pi-coding-agent";
2521
- import { Type as Type14 } from "typebox";
2522
- var schema8 = Type14.Object({
2523
- path: Type14.String({ description: "File path relative to project root" }),
2524
- content: Type14.String({ description: "Complete file content" })
2507
+ import { createWriteToolDefinition as createWriteToolDefinition2, defineTool as defineTool13 } from "@earendil-works/pi-coding-agent";
2508
+ import { Type as Type13 } from "typebox";
2509
+ var schema8 = Type13.Object({
2510
+ path: Type13.String({ description: "File path relative to project root" }),
2511
+ content: Type13.String({ description: "Complete file content" })
2525
2512
  }, { additionalProperties: false });
2526
2513
  function createCreateFileTool(cwd) {
2527
- return defineTool14({
2514
+ return defineTool13({
2528
2515
  name: "create_file",
2529
2516
  label: "Create File",
2530
2517
  description: "Create a new project file or completely overwrite an existing file.",
@@ -2541,14 +2528,14 @@ function createCreateFileTool(cwd) {
2541
2528
 
2542
2529
  // src/capabilities/tools/filesystem/delete_file.ts
2543
2530
  import { rm as rm2 } from "node:fs/promises";
2544
- import { defineTool as defineTool15 } from "@earendil-works/pi-coding-agent";
2545
- import { Type as Type15 } from "typebox";
2546
- var schema9 = Type15.Object(
2547
- { path: Type15.String({ description: "Path relative to project root" }) },
2531
+ import { defineTool as defineTool14 } from "@earendil-works/pi-coding-agent";
2532
+ import { Type as Type14 } from "typebox";
2533
+ var schema9 = Type14.Object(
2534
+ { path: Type14.String({ description: "Path relative to project root" }) },
2548
2535
  { additionalProperties: false }
2549
2536
  );
2550
2537
  function createDeleteFileTool(cwd) {
2551
- return defineTool15({
2538
+ return defineTool14({
2552
2539
  name: "delete_file",
2553
2540
  label: "Delete File",
2554
2541
  description: "Delete a file or directory from the project.",
@@ -2563,15 +2550,15 @@ function createDeleteFileTool(cwd) {
2563
2550
  }
2564
2551
 
2565
2552
  // src/capabilities/tools/filesystem/glob_files.ts
2566
- import { createFindToolDefinition, defineTool as defineTool16 } from "@earendil-works/pi-coding-agent";
2567
- import { Type as Type16 } from "typebox";
2568
- var schema10 = Type16.Object({
2569
- pattern: Type16.String({ description: "Glob pattern such as **/*.ts" }),
2570
- path: Type16.Optional(Type16.String({ description: "Search directory relative to project root" }))
2553
+ import { createFindToolDefinition, defineTool as defineTool15 } from "@earendil-works/pi-coding-agent";
2554
+ import { Type as Type15 } from "typebox";
2555
+ var schema10 = Type15.Object({
2556
+ pattern: Type15.String({ description: "Glob pattern such as **/*.ts" }),
2557
+ path: Type15.Optional(Type15.String({ description: "Search directory relative to project root" }))
2571
2558
  }, { additionalProperties: false });
2572
2559
  function createGlobFilesTool(cwd) {
2573
2560
  const nativeFind = createFindToolDefinition(cwd);
2574
- return defineTool16({
2561
+ return defineTool15({
2575
2562
  name: "glob_files",
2576
2563
  label: "Glob Files",
2577
2564
  description: "Find project files with a glob pattern.",
@@ -2600,26 +2587,26 @@ function createGlobFilesTool(cwd) {
2600
2587
  }
2601
2588
 
2602
2589
  // src/capabilities/tools/filesystem/grep_files.ts
2603
- import { createGrepToolDefinition, defineTool as defineTool17 } from "@earendil-works/pi-coding-agent";
2604
- import { Type as Type17 } from "typebox";
2605
- var schema11 = Type17.Object({
2606
- pattern: Type17.String(),
2607
- path: Type17.Optional(Type17.String()),
2608
- glob: Type17.Optional(Type17.String()),
2609
- output_mode: Type17.Optional(Type17.Union([
2610
- Type17.Literal("content"),
2611
- Type17.Literal("files_with_matches"),
2612
- Type17.Literal("count")
2590
+ import { createGrepToolDefinition, defineTool as defineTool16 } from "@earendil-works/pi-coding-agent";
2591
+ import { Type as Type16 } from "typebox";
2592
+ var schema11 = Type16.Object({
2593
+ pattern: Type16.String(),
2594
+ path: Type16.Optional(Type16.String()),
2595
+ glob: Type16.Optional(Type16.String()),
2596
+ output_mode: Type16.Optional(Type16.Union([
2597
+ Type16.Literal("content"),
2598
+ Type16.Literal("files_with_matches"),
2599
+ Type16.Literal("count")
2613
2600
  ])),
2614
- "-i": Type17.Optional(Type17.Boolean()),
2615
- "-B": Type17.Optional(Type17.Integer({ minimum: 0 })),
2616
- "-A": Type17.Optional(Type17.Integer({ minimum: 0 })),
2617
- "-C": Type17.Optional(Type17.Integer({ minimum: 0 })),
2618
- context: Type17.Optional(Type17.Integer({ minimum: 0 }))
2601
+ "-i": Type16.Optional(Type16.Boolean()),
2602
+ "-B": Type16.Optional(Type16.Integer({ minimum: 0 })),
2603
+ "-A": Type16.Optional(Type16.Integer({ minimum: 0 })),
2604
+ "-C": Type16.Optional(Type16.Integer({ minimum: 0 })),
2605
+ context: Type16.Optional(Type16.Integer({ minimum: 0 }))
2619
2606
  }, { additionalProperties: false });
2620
2607
  function createGrepFilesTool(cwd) {
2621
2608
  const nativeGrep = createGrepToolDefinition(cwd);
2622
- return defineTool17({
2609
+ return defineTool16({
2623
2610
  name: "grep_files",
2624
2611
  label: "Grep Files",
2625
2612
  description: "Search project file contents with a regular expression. Supports glob filtering.",
@@ -2667,14 +2654,14 @@ function createGrepFilesTool(cwd) {
2667
2654
  }
2668
2655
 
2669
2656
  // src/capabilities/tools/filesystem/list_files.ts
2670
- import { createFindToolDefinition as createFindToolDefinition2, defineTool as defineTool18 } from "@earendil-works/pi-coding-agent";
2671
- import { Type as Type18 } from "typebox";
2672
- var schema12 = Type18.Object({
2673
- path: Type18.Optional(Type18.String({ description: "Directory relative to project root" }))
2657
+ import { createFindToolDefinition as createFindToolDefinition2, defineTool as defineTool17 } from "@earendil-works/pi-coding-agent";
2658
+ import { Type as Type17 } from "typebox";
2659
+ var schema12 = Type17.Object({
2660
+ path: Type17.Optional(Type17.String({ description: "Directory relative to project root" }))
2674
2661
  }, { additionalProperties: false });
2675
2662
  function createListFilesTool(cwd) {
2676
2663
  const nativeFind = createFindToolDefinition2(cwd);
2677
- return defineTool18({
2664
+ return defineTool17({
2678
2665
  name: "list_files",
2679
2666
  label: "List Files",
2680
2667
  description: "Recursively list project files below a directory.",
@@ -2699,8 +2686,8 @@ function createListFilesTool(cwd) {
2699
2686
  }
2700
2687
 
2701
2688
  // src/capabilities/tools/media/fetch_media.ts
2702
- import { defineTool as defineTool19 } from "@earendil-works/pi-coding-agent";
2703
- import { Type as Type19 } from "typebox";
2689
+ import { defineTool as defineTool18 } from "@earendil-works/pi-coding-agent";
2690
+ import { Type as Type18 } from "typebox";
2704
2691
 
2705
2692
  // src/utils/clients/media/pexels.ts
2706
2693
  import { createHash } from "node:crypto";
@@ -2748,23 +2735,23 @@ async function fetchPexels(settings, retry, pathname, params, signal) {
2748
2735
  }
2749
2736
 
2750
2737
  // src/capabilities/tools/media/fetch_media.ts
2751
- var schema13 = Type19.Object({
2752
- query: Type19.String(),
2753
- media_type: Type19.Union([Type19.Literal("image"), Type19.Literal("video"), Type19.Literal("both")], { default: "both" }),
2754
- count: Type19.Number({ default: 6 }),
2755
- orientation: Type19.Union([
2756
- Type19.Literal("any"),
2757
- Type19.Literal("landscape"),
2758
- Type19.Literal("portrait"),
2759
- Type19.Literal("square")
2738
+ var schema13 = Type18.Object({
2739
+ query: Type18.String(),
2740
+ media_type: Type18.Union([Type18.Literal("image"), Type18.Literal("video"), Type18.Literal("both")], { default: "both" }),
2741
+ count: Type18.Number({ default: 6 }),
2742
+ orientation: Type18.Union([
2743
+ Type18.Literal("any"),
2744
+ Type18.Literal("landscape"),
2745
+ Type18.Literal("portrait"),
2746
+ Type18.Literal("square")
2760
2747
  ], { default: "any" }),
2761
- size: Type19.Union([
2762
- Type19.Literal("any"),
2763
- Type19.Literal("large"),
2764
- Type19.Literal("medium"),
2765
- Type19.Literal("small")
2748
+ size: Type18.Union([
2749
+ Type18.Literal("any"),
2750
+ Type18.Literal("large"),
2751
+ Type18.Literal("medium"),
2752
+ Type18.Literal("small")
2766
2753
  ], { default: "any" }),
2767
- locale: Type19.String()
2754
+ locale: Type18.String()
2768
2755
  }, { additionalProperties: false });
2769
2756
  function record7(value) {
2770
2757
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
@@ -2809,7 +2796,7 @@ function videos(payload) {
2809
2796
  });
2810
2797
  }
2811
2798
  function createFetchMediaTool(settings, retry) {
2812
- return defineTool19({
2799
+ return defineTool18({
2813
2800
  name: "fetch_media",
2814
2801
  label: "Fetch Media",
2815
2802
  description: "Search Pexels for stock photos and videos and return URL-based assets.",
@@ -2868,14 +2855,14 @@ function createFetchMediaTool(settings, retry) {
2868
2855
  }
2869
2856
 
2870
2857
  // src/capabilities/tools/web/web_fetch.ts
2871
- import { defineTool as defineTool20 } from "@earendil-works/pi-coding-agent";
2872
- import { Type as Type20 } from "typebox";
2873
- var schema14 = Type20.Object({
2874
- url: Type20.String(),
2875
- format: Type20.Union([Type20.Literal("markdown"), Type20.Literal("text"), Type20.Literal("html")])
2858
+ import { defineTool as defineTool19 } from "@earendil-works/pi-coding-agent";
2859
+ import { Type as Type19 } from "typebox";
2860
+ var schema14 = Type19.Object({
2861
+ url: Type19.String(),
2862
+ format: Type19.Union([Type19.Literal("markdown"), Type19.Literal("text"), Type19.Literal("html")])
2876
2863
  }, { additionalProperties: false });
2877
2864
  function createWebFetchTool(routify, retry) {
2878
- return defineTool20({
2865
+ return defineTool19({
2879
2866
  name: "web_fetch",
2880
2867
  label: "Web Fetch",
2881
2868
  description: "Fetch a web page and return markdown, plain text, or HTML.",
@@ -3005,12 +2992,6 @@ function createCodeArenaFullStackExtension(cwd, settings) {
3005
2992
  true,
3006
2993
  settings.pi.npmCommand
3007
2994
  ));
3008
- pi.registerTool(createCodeArenaFullStackBashTool(
3009
- cwd,
3010
- exec,
3011
- settings.tools.execution,
3012
- settings.pi.shell
3013
- ));
3014
2995
  pi.registerTool(createBuildAndStartTool(
3015
2996
  cwd,
3016
2997
  exec,
@@ -3041,12 +3022,24 @@ function createCodeArenaFullStackExtension(cwd, settings) {
3041
3022
  }
3042
3023
  };
3043
3024
  }
3025
+ function createCodeArenaFullStackExtensions(cwd, settings) {
3026
+ const capabilities = composeHarnessCapabilities([
3027
+ createBashCapability(cwd, {
3028
+ timeoutSeconds: settings.tools.execution?.bashTimeoutSeconds
3029
+ })
3030
+ ]);
3031
+ return [
3032
+ ...capabilities.extensionFactories,
3033
+ createCodeArenaFullStackExtension(cwd, settings)
3034
+ ];
3035
+ }
3044
3036
  async function runCodeArenaFullStackHarness(args) {
3045
3037
  const cwd = process.cwd();
3046
3038
  const settings = loadCapabilitySettings(cwd);
3047
- await runHarnessMain(buildCodeArenaFullStackArgs(args, cwd), [
3048
- createCodeArenaFullStackExtension(cwd, settings)
3049
- ]);
3039
+ await runHarnessMain(
3040
+ buildCodeArenaFullStackArgs(args, cwd),
3041
+ createCodeArenaFullStackExtensions(cwd, settings)
3042
+ );
3050
3043
  }
3051
3044
 
3052
3045
  // src/harnesses/code-arena-html.ts
@@ -3132,11 +3125,11 @@ async function runCodeArenaHtmlHarness(args) {
3132
3125
  import "@earendil-works/pi-coding-agent";
3133
3126
 
3134
3127
  // src/capabilities/tools/execution/build_project.ts
3135
- import { defineTool as defineTool21 } from "@earendil-works/pi-coding-agent";
3136
- import { Type as Type21 } from "typebox";
3137
- var schema15 = Type21.Object({}, { additionalProperties: false });
3128
+ import { defineTool as defineTool20 } from "@earendil-works/pi-coding-agent";
3129
+ import { Type as Type20 } from "typebox";
3130
+ var schema15 = Type20.Object({}, { additionalProperties: false });
3138
3131
  function createBuildProjectTool(cwd, exec, npmCommand) {
3139
- return defineTool21({
3132
+ return defineTool20({
3140
3133
  name: "build_project",
3141
3134
  label: "Build Project",
3142
3135
  description: "Build the project with npm run build.",
@@ -3577,8 +3570,15 @@ function buildPiArgs(args) {
3577
3570
  isolatedResources: NATIVE_PI_ISOLATED_RESOURCES
3578
3571
  });
3579
3572
  }
3573
+ function createPiHarnessCapabilities(cwd = process.cwd()) {
3574
+ return composeHarnessCapabilities([
3575
+ createBashCapability(cwd)
3576
+ ]);
3577
+ }
3580
3578
  async function runPiHarness(args) {
3581
- await runHarnessMain(buildPiArgs(args));
3579
+ const capabilities = createPiHarnessCapabilities();
3580
+ await prepareHarnessCapabilities(capabilities);
3581
+ await runHarnessMain(buildPiArgs(args), capabilities.extensionFactories);
3582
3582
  }
3583
3583
 
3584
3584
  // src/capabilities/tools/programmatic-tool-calling/index.ts
@@ -3587,18 +3587,18 @@ import path13 from "node:path";
3587
3587
  import readline from "node:readline";
3588
3588
  import { fileURLToPath as fileURLToPath3 } from "node:url";
3589
3589
  import {
3590
- createBashToolDefinition,
3591
3590
  createEditToolDefinition as createEditToolDefinition2,
3592
3591
  createReadToolDefinition as createReadToolDefinition2,
3593
3592
  createWriteToolDefinition as createWriteToolDefinition3,
3594
- defineTool as defineTool22,
3595
- getAgentDir as getAgentDir2,
3596
- SettingsManager as SettingsManager2
3593
+ defineTool as defineTool21,
3594
+ getAgentDir as getAgentDir3,
3595
+ SettingsManager as SettingsManager3
3597
3596
  } from "@earendil-works/pi-coding-agent";
3598
- import { Type as Type22 } from "typebox";
3597
+ import { Type as Type21 } from "typebox";
3599
3598
  import { Value } from "typebox/value";
3600
3599
  var RUN_CODE_TOOL_NAME = "run_code";
3601
- var DEFAULT_TIMEOUT_MS = 12e4;
3600
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
3601
+ var DEFAULT_SYNC_TIMEOUT_MS = 5e3;
3602
3602
  var MAX_TIMEOUT_MS = 6e5;
3603
3603
  var DEFAULT_MAX_OUTPUT_CHARS = 5e4;
3604
3604
  var MAX_OUTPUT_CHARS = 2e5;
@@ -3680,7 +3680,10 @@ function runCodeDescription(tools) {
3680
3680
  "The code runs in a fresh, short-lived child process. Node globals, filesystem APIs, network APIs, and console are not exposed to the script; use nested tools for side effects.",
3681
3681
  "All nested tools are async functions on the global `tools` object. Always await calls whose result or completion matters.",
3682
3682
  "Use `text(value)` to emit model-visible text. Non-string values are JSON-encoded when possible.",
3683
- "Use `image(value)` to forward an image content block with string `data` and `mimeType` fields.",
3683
+ "Use `image(value)` to forward either an image content block or a nested tool result containing images.",
3684
+ "Use `setTimeout` and `clearTimeout` for bounded waits; timer delays are limited to 10 minutes.",
3685
+ "Set timeouts on the nested tool that performs the work. The top-level `timeout_ms` is only an optional hard deadline for the entire orchestration and normally should be omitted.",
3686
+ "When a JavaScript template literal contains shell parameter expansion such as `${name}`, escape the dollar sign as `\\${name}` so JavaScript does not treat it as interpolation.",
3684
3687
  "`ALL_TOOLS` contains `{ name, description }` metadata. Unawaited work is discarded when the script completes.",
3685
3688
  "The `code` argument must be raw JavaScript source without Markdown fences.",
3686
3689
  "",
@@ -3689,26 +3692,28 @@ function runCodeDescription(tools) {
3689
3692
  "declare const tools: Record<string, (args: unknown) => Promise<string | NestedToolResult>>;",
3690
3693
  "declare const ALL_TOOLS: ReadonlyArray<{ name: string; description: string }>;",
3691
3694
  "declare function text(value: unknown): void;",
3692
- 'declare function image(value: { type?: "image"; data: string; mimeType: string }): void;',
3693
- 'type NestedToolResult = { content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }> };',
3695
+ 'type ImageContent = { type?: "image"; data: string; mimeType: string };',
3696
+ "declare function image(value: ImageContent | NestedToolResult): void;",
3697
+ "declare function setTimeout(callback: (...args: unknown[]) => void, delayMs?: number, ...args: unknown[]): string;",
3698
+ "declare function clearTimeout(handle: string): void;",
3699
+ 'type NestedToolResult = { content: Array<{ type: "text"; text: string } | ImageContent> };',
3694
3700
  "```",
3695
3701
  "",
3696
3702
  ...tools.map(nestedToolDescription)
3697
3703
  ].join("\n");
3698
3704
  }
3699
- var runCodeSchema = Type22.Object({
3700
- code: Type22.String({
3705
+ var runCodeSchema = Type21.Object({
3706
+ code: Type21.String({
3701
3707
  minLength: 1,
3702
3708
  maxLength: 128e3,
3703
3709
  description: "Raw JavaScript source to evaluate. Do not wrap it in Markdown fences."
3704
3710
  }),
3705
- timeout_ms: Type22.Optional(Type22.Integer({
3711
+ timeout_ms: Type21.Optional(Type21.Integer({
3706
3712
  minimum: 100,
3707
3713
  maximum: MAX_TIMEOUT_MS,
3708
- default: DEFAULT_TIMEOUT_MS,
3709
- description: "Wall-clock limit for the complete script, including nested tool calls."
3714
+ description: "Optional hard wall-clock deadline for the complete orchestration. This is independent of nested tool timeouts; normally omit it and set timeout on the nested tool instead."
3710
3715
  })),
3711
- max_output_chars: Type22.Optional(Type22.Integer({
3716
+ max_output_chars: Type21.Optional(Type21.Integer({
3712
3717
  minimum: 100,
3713
3718
  maximum: MAX_OUTPUT_CHARS,
3714
3719
  default: DEFAULT_MAX_OUTPUT_CHARS,
@@ -3716,13 +3721,10 @@ var runCodeSchema = Type22.Object({
3716
3721
  }))
3717
3722
  }, { additionalProperties: false });
3718
3723
  function configuredPiTools(cwd) {
3719
- const settings = SettingsManager2.create(cwd, getAgentDir2(), { projectTrusted: false });
3724
+ const settings = SettingsManager3.create(cwd, getAgentDir3(), { projectTrusted: false });
3720
3725
  return [
3721
3726
  createReadToolDefinition2(cwd, { autoResizeImages: settings.getImageAutoResize() }),
3722
- createBashToolDefinition(cwd, {
3723
- commandPrefix: settings.getShellCommandPrefix(),
3724
- shellPath: settings.getShellPath()
3725
- }),
3727
+ createBashToolDefinition(cwd),
3726
3728
  createEditToolDefinition2(cwd),
3727
3729
  createWriteToolDefinition3(cwd)
3728
3730
  ];
@@ -3791,15 +3793,17 @@ function emittedContent(value, maxOutputChars) {
3791
3793
  }
3792
3794
  return content.length ? content : [{ type: "text", text: "Code completed without emitted output." }];
3793
3795
  }
3794
- async function executeRunCode(toolCallId, params, signal, context, tools) {
3796
+ async function executeRunCode(toolCallId, params, signal, context, tools, limits) {
3795
3797
  assertNestedTools(tools);
3796
3798
  const toolsByName = new Map(tools.map((tool) => [normalizedToolName(tool.name), tool]));
3797
- const timeoutMs = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
3799
+ const explicitTimeoutMs = params.timeout_ms;
3798
3800
  const maxOutputChars = params.max_output_chars ?? DEFAULT_MAX_OUTPUT_CHARS;
3799
3801
  const controller = new AbortController();
3800
3802
  const calls = [];
3801
3803
  let settled = false;
3802
3804
  let stderr = "";
3805
+ let activeTimerCount = 0;
3806
+ const activeCalls = /* @__PURE__ */ new Map();
3803
3807
  const child = spawn2(process.execPath, [
3804
3808
  "--permission",
3805
3809
  "--no-warnings",
@@ -3821,9 +3825,18 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3821
3825
  else signal?.addEventListener("abort", onAbort, { once: true });
3822
3826
  try {
3823
3827
  return await new Promise((resolve, reject) => {
3828
+ let idleTimer;
3829
+ let wallTimer;
3830
+ const clearWatchdogs = () => {
3831
+ if (idleTimer) clearTimeout(idleTimer);
3832
+ if (wallTimer) clearTimeout(wallTimer);
3833
+ idleTimer = void 0;
3834
+ wallTimer = void 0;
3835
+ };
3824
3836
  const finish = (outcome) => {
3825
3837
  if (settled) return;
3826
3838
  settled = true;
3839
+ clearWatchdogs();
3827
3840
  if (outcome.error) {
3828
3841
  reject(new Error(outcome.error));
3829
3842
  return;
@@ -3837,12 +3850,40 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3837
3850
  reject(error);
3838
3851
  }
3839
3852
  };
3840
- const timer = setTimeout(() => {
3841
- finish({ error: `run_code exceeded its ${timeoutMs} ms timeout` });
3842
- controller.abort(new Error(`run_code exceeded its ${timeoutMs} ms timeout`));
3843
- child.kill();
3844
- }, timeoutMs);
3845
- timer.unref();
3853
+ const activeCallSummary = () => {
3854
+ if (!activeCalls.size) return "none";
3855
+ return [...activeCalls.values()].map((call) => `${call.name} (${Date.now() - call.startedAt} ms)`).join(", ");
3856
+ };
3857
+ const armIdleWatchdog = () => {
3858
+ if (idleTimer) clearTimeout(idleTimer);
3859
+ idleTimer = void 0;
3860
+ if (settled || activeCalls.size || activeTimerCount) return;
3861
+ idleTimer = setTimeout(() => {
3862
+ const message = [
3863
+ `run_code made no progress for ${limits.idleTimeoutMs} ms with no active nested tools or timers.`,
3864
+ "This usually means the script is waiting on an unresolved promise or running JavaScript outside a nested tool."
3865
+ ].join(" ");
3866
+ finish({ error: message });
3867
+ controller.abort(new Error(message));
3868
+ child.kill();
3869
+ }, limits.idleTimeoutMs);
3870
+ idleTimer.unref();
3871
+ };
3872
+ if (explicitTimeoutMs !== void 0) {
3873
+ wallTimer = setTimeout(() => {
3874
+ const message = [
3875
+ `run_code explicit outer wall-clock timeout expired after ${explicitTimeoutMs} ms.`,
3876
+ "This deadline is independent of nested tool timeouts.",
3877
+ `Active nested calls: ${activeCallSummary()}.`,
3878
+ "Increase top-level timeout_ms, or omit it and set timeout on the nested tool instead."
3879
+ ].join(" ");
3880
+ finish({ error: message });
3881
+ controller.abort(new Error(message));
3882
+ child.kill();
3883
+ }, explicitTimeoutMs);
3884
+ wallTimer.unref();
3885
+ }
3886
+ armIdleWatchdog();
3846
3887
  const rejectAborted = () => {
3847
3888
  child.kill();
3848
3889
  finish({ error: "Operation aborted" });
@@ -3855,7 +3896,6 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3855
3896
  });
3856
3897
  child.on("error", (error) => finish({ error: `Failed to start run_code: ${error.message}` }));
3857
3898
  child.on("exit", (code, exitSignal) => {
3858
- clearTimeout(timer);
3859
3899
  if (settled) return;
3860
3900
  const detail = stderr.trim() ? `: ${stderr.trim()}` : "";
3861
3901
  finish({
@@ -3871,18 +3911,29 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3871
3911
  return;
3872
3912
  }
3873
3913
  if (message.type === "done") {
3874
- clearTimeout(timer);
3875
3914
  finish(message);
3876
3915
  return;
3877
3916
  }
3917
+ if (message.type === "timer_state") {
3918
+ if (!Number.isSafeInteger(message.active) || message.active < 0) {
3919
+ finish({ error: "run_code child emitted an invalid timer state" });
3920
+ return;
3921
+ }
3922
+ activeTimerCount = message.active;
3923
+ armIdleWatchdog();
3924
+ return;
3925
+ }
3878
3926
  if (message.type !== "tool_call") return;
3879
3927
  const startedAt = Date.now();
3880
3928
  const tool = toolsByName.get(message.name);
3881
3929
  if (!tool) {
3882
3930
  calls.push({ name: message.name, durationMs: 0, status: "error" });
3883
3931
  post({ type: "tool_error", id: message.id, error: `Unknown nested tool: ${message.name}` });
3932
+ armIdleWatchdog();
3884
3933
  return;
3885
3934
  }
3935
+ activeCalls.set(message.id, { name: tool.name, startedAt });
3936
+ armIdleWatchdog();
3886
3937
  void (async () => {
3887
3938
  try {
3888
3939
  const args = validatedArguments(tool, message.args);
@@ -3902,13 +3953,16 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3902
3953
  id: message.id,
3903
3954
  error: error instanceof Error ? error.message : String(error)
3904
3955
  });
3956
+ } finally {
3957
+ activeCalls.delete(message.id);
3958
+ armIdleWatchdog();
3905
3959
  }
3906
3960
  })();
3907
3961
  });
3908
3962
  post({
3909
3963
  type: "init",
3910
3964
  code: params.code,
3911
- syncTimeoutMs: timeoutMs,
3965
+ syncTimeoutMs: limits.syncTimeoutMs,
3912
3966
  tools: tools.map((tool) => ({
3913
3967
  name: normalizedToolName(tool.name),
3914
3968
  description: tool.description
@@ -3925,20 +3979,25 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
3925
3979
  }
3926
3980
  function createRunCodeTool(options) {
3927
3981
  assertNestedTools(options.nestedTools);
3928
- return defineTool22({
3982
+ return defineTool21({
3929
3983
  name: RUN_CODE_TOOL_NAME,
3930
3984
  label: "Run Code",
3931
3985
  description: runCodeDescription(options.nestedTools),
3932
3986
  promptSnippet: "Orchestrate all Pi tools through JavaScript",
3933
3987
  promptGuidelines: [
3934
3988
  "Use run_code for every tool operation; direct nested tools are intentionally unavailable.",
3935
- "Compose and filter nested tool results in JavaScript, then emit only the information needed with text() or image()."
3989
+ "Compose and filter nested tool results in JavaScript, then emit only the information needed with text() or image().",
3990
+ "Set timeout on the nested tool that performs the work; normally omit run_code timeout_ms because it is only an independent hard deadline for the whole orchestration.",
3991
+ "Escape shell parameter expansion inside JavaScript template literals, for example write \\${name} instead of ${name}."
3936
3992
  ],
3937
3993
  parameters: runCodeSchema,
3938
3994
  executionMode: "sequential",
3939
3995
  async execute(toolCallId, params, signal, _onUpdate, context) {
3940
3996
  const tools = options.resolveNestedTools?.(context) ?? options.nestedTools;
3941
- return executeRunCode(toolCallId, params, signal, context, tools);
3997
+ return executeRunCode(toolCallId, params, signal, context, tools, {
3998
+ idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
3999
+ syncTimeoutMs: options.syncTimeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS
4000
+ });
3942
4001
  }
3943
4002
  });
3944
4003
  }
@@ -3982,9 +4041,9 @@ async function runPiPtcHarness(args) {
3982
4041
 
3983
4042
  // src/capabilities/tools/filesystem/apply_patch.ts
3984
4043
  import {
3985
- defineTool as defineTool23
4044
+ defineTool as defineTool22
3986
4045
  } from "@earendil-works/pi-coding-agent";
3987
- import { Type as Type23 } from "typebox";
4046
+ import { Type as Type22 } from "typebox";
3988
4047
 
3989
4048
  // src/utils/filesystem/apply_patch.ts
3990
4049
  import { mkdir as mkdir7, readFile as readFile7, stat, unlink, writeFile as writeFile5 } from "node:fs/promises";
@@ -4400,14 +4459,14 @@ var DESCRIPTION = [
4400
4459
  "Update hunks use @@ sections with lines prefixed by space (context), - (remove), or + (add), and may include '*** Move to: path'.",
4401
4460
  "Paths may be relative to the workspace root or absolute paths inside it."
4402
4461
  ].join(" ");
4403
- var schema16 = Type23.Object({
4404
- patch: Type23.String({
4462
+ var schema16 = Type22.Object({
4463
+ patch: Type22.String({
4405
4464
  minLength: 1,
4406
4465
  description: "Complete Codex patch text from *** Begin Patch through *** End Patch."
4407
4466
  })
4408
4467
  }, { additionalProperties: false });
4409
4468
  function createApplyPatchTool(cwd) {
4410
- return defineTool23({
4469
+ return defineTool22({
4411
4470
  name: APPLY_PATCH_TOOL_NAME,
4412
4471
  label: "Apply Patch",
4413
4472
  description: DESCRIPTION,
@@ -4439,12 +4498,12 @@ function createApplyPatchExtension(cwd) {
4439
4498
  // src/capabilities/tools/filesystem/glob.ts
4440
4499
  import {
4441
4500
  createFindToolDefinition as createFindToolDefinition3,
4442
- defineTool as defineTool24
4501
+ defineTool as defineTool23
4443
4502
  } from "@earendil-works/pi-coding-agent";
4444
4503
  var GLOB_TOOL_NAME = "glob";
4445
4504
  function createGlobTool(cwd) {
4446
4505
  const nativeFind = createFindToolDefinition3(cwd);
4447
- return defineTool24({
4506
+ return defineTool23({
4448
4507
  ...nativeFind,
4449
4508
  name: GLOB_TOOL_NAME,
4450
4509
  label: "Glob"
@@ -4461,9 +4520,9 @@ function createGlobExtension(cwd) {
4461
4520
 
4462
4521
  // src/capabilities/tools/filesystem/str_replace_editor.ts
4463
4522
  import {
4464
- defineTool as defineTool25
4523
+ defineTool as defineTool24
4465
4524
  } from "@earendil-works/pi-coding-agent";
4466
- import { Type as Type24 } from "typebox";
4525
+ import { Type as Type23 } from "typebox";
4467
4526
 
4468
4527
  // src/utils/filesystem/str_replace_editor.ts
4469
4528
  import { readFile as readFile8, readdir as readdir2, stat as stat2, writeFile as writeFile6 } from "node:fs/promises";
@@ -4715,29 +4774,29 @@ var DEFAULT_DESCRIPTION = [
4715
4774
  "The create command refuses to overwrite an existing path.",
4716
4775
  "For str_replace, old_str must match exactly once; include enough surrounding text to make it unique."
4717
4776
  ].join(" ");
4718
- var schema17 = Type24.Object({
4719
- command: Type24.Union([
4720
- Type24.Literal("view"),
4721
- Type24.Literal("create"),
4722
- Type24.Literal("str_replace"),
4723
- Type24.Literal("insert")
4777
+ var schema17 = Type23.Object({
4778
+ command: Type23.Union([
4779
+ Type23.Literal("view"),
4780
+ Type23.Literal("create"),
4781
+ Type23.Literal("str_replace"),
4782
+ Type23.Literal("insert")
4724
4783
  ], { description: "Command to run." }),
4725
- path: Type24.String({
4784
+ path: Type23.String({
4726
4785
  description: "Absolute path to a file or directory inside the workspace."
4727
4786
  }),
4728
- file_text: Type24.Optional(Type24.String({
4787
+ file_text: Type23.Optional(Type23.String({
4729
4788
  description: "Required by create: complete content of the new file."
4730
4789
  })),
4731
- insert_line: Type24.Optional(Type24.Integer({
4790
+ insert_line: Type23.Optional(Type23.Integer({
4732
4791
  description: "Required by insert: insert new_str after this 0-based line boundary."
4733
4792
  })),
4734
- new_str: Type24.Optional(Type24.String({
4793
+ new_str: Type23.Optional(Type23.String({
4735
4794
  description: "Replacement text for str_replace, or required insertion text for insert."
4736
4795
  })),
4737
- old_str: Type24.Optional(Type24.String({
4796
+ old_str: Type23.Optional(Type23.String({
4738
4797
  description: "Required by str_replace: the unique literal text to replace."
4739
4798
  })),
4740
- view_range: Type24.Optional(Type24.Array(Type24.Integer(), {
4799
+ view_range: Type23.Optional(Type23.Array(Type23.Integer(), {
4741
4800
  description: "For file views, [start_line, end_line] using 1-based inclusive lines; use -1 as the end to read through EOF."
4742
4801
  }))
4743
4802
  }, { additionalProperties: false });
@@ -4749,7 +4808,7 @@ function resolveDescription(description) {
4749
4808
  function createStrReplaceEditorTool(cwd, options = {}) {
4750
4809
  const runtimeOptions = resolveStrReplaceEditorOptions(options);
4751
4810
  const description = resolveDescription(options.description);
4752
- return defineTool25({
4811
+ return defineTool24({
4753
4812
  name: STR_REPLACE_EDITOR_TOOL_NAME,
4754
4813
  label: "String Replace Editor",
4755
4814
  description,
@@ -4794,15 +4853,18 @@ function buildToolComparisonArgs(name, args) {
4794
4853
  });
4795
4854
  }
4796
4855
  function createToolComparisonExtensions(name, cwd) {
4856
+ const bashExtensions = composeHarnessCapabilities([
4857
+ createBashCapability(cwd)
4858
+ ]).extensionFactories;
4797
4859
  switch (name) {
4798
4860
  case "bash-apply-patch":
4799
- return [createApplyPatchExtension(cwd)];
4861
+ return [...bashExtensions, createApplyPatchExtension(cwd)];
4800
4862
  case "bash-str-replace-editor":
4801
- return [createStrReplaceEditorExtension(cwd)];
4863
+ return [...bashExtensions, createStrReplaceEditorExtension(cwd)];
4802
4864
  case "bash-file-search":
4803
- return [createGlobExtension(cwd)];
4865
+ return [...bashExtensions, createGlobExtension(cwd)];
4804
4866
  case "bash-only":
4805
- return [];
4867
+ return bashExtensions;
4806
4868
  }
4807
4869
  }
4808
4870
  async function runToolComparisonHarness(name, args) {