@qwen-code/qwen-harness 0.1.0 → 0.1.2

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.
@@ -2,9 +2,9 @@
2
2
 
3
3
  // src/harnesses/agent-arena.ts
4
4
  import path8 from "node:path";
5
- import { main } from "@earendil-works/pi-coding-agent";
5
+ import "@earendil-works/pi-coding-agent";
6
6
 
7
- // src/capabilities/infrastructure/retry.ts
7
+ // src/utils/clients/retry.ts
8
8
  import { setTimeout as delay } from "node:timers/promises";
9
9
  function retryableStatus(status) {
10
10
  return status === 408 || status === 409 || status === 429 || status >= 500;
@@ -56,7 +56,7 @@ async function retryHttpRequest(request, retry, signal) {
56
56
  }
57
57
  }
58
58
 
59
- // src/capabilities/infrastructure/media/dashscope.ts
59
+ // src/utils/clients/media/dashscope.ts
60
60
  function record(value) {
61
61
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
62
62
  }
@@ -107,37 +107,37 @@ async function responseBytes(response, limit = 25 * 1024 * 1024) {
107
107
  // src/capabilities/settings.ts
108
108
  import { getAgentDir, getShellConfig, SettingsManager } from "@earendil-works/pi-coding-agent";
109
109
 
110
- // src/capabilities/shared/settings.ts
111
- function record2(value, path13) {
110
+ // src/utils/settings.ts
111
+ function record2(value, path17) {
112
112
  if (value === void 0) return {};
113
113
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
114
- throw new Error(`${path13} must be a JSON object`);
114
+ throw new Error(`${path17} must be a JSON object`);
115
115
  }
116
116
  return value;
117
117
  }
118
- function assertKnownKeys(value, path13, allowedKeys) {
118
+ function assertKnownKeys(value, path17, allowedKeys) {
119
119
  const allowed = new Set(allowedKeys);
120
120
  const unknownKeys = Object.keys(value).filter((key) => !allowed.has(key));
121
121
  if (unknownKeys.length === 0) return;
122
- throw new Error(`${path13} contains unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}`);
122
+ throw new Error(`${path17} contains unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}`);
123
123
  }
124
- function optionalString(value, path13) {
124
+ function optionalString(value, path17) {
125
125
  if (value === void 0) return void 0;
126
126
  if (typeof value !== "string" || value.trim().length === 0) {
127
- throw new Error(`${path13} must be a non-empty string`);
127
+ throw new Error(`${path17} must be a non-empty string`);
128
128
  }
129
129
  return value.trim();
130
130
  }
131
- function optionalNonNegativeInteger(value, path13) {
131
+ function optionalNonNegativeInteger(value, path17) {
132
132
  if (value === void 0) return void 0;
133
133
  if (!Number.isSafeInteger(value) || Number(value) < 0) {
134
- throw new Error(`${path13} must be a non-negative integer`);
134
+ throw new Error(`${path17} must be a non-negative integer`);
135
135
  }
136
136
  return Number(value);
137
137
  }
138
- function optionalPositiveInteger(value, path13) {
139
- const parsed = optionalNonNegativeInteger(value, path13);
140
- if (parsed === 0) throw new Error(`${path13} must be a positive integer`);
138
+ function optionalPositiveInteger(value, path17) {
139
+ const parsed = optionalNonNegativeInteger(value, path17);
140
+ if (parsed === 0) throw new Error(`${path17} must be a positive integer`);
141
141
  return parsed;
142
142
  }
143
143
  function withoutUndefined(value) {
@@ -146,7 +146,7 @@ function withoutUndefined(value) {
146
146
  );
147
147
  }
148
148
 
149
- // src/capabilities/infrastructure/media/settings.ts
149
+ // src/utils/clients/media/settings.ts
150
150
  function parseDashScopeSettings(value) {
151
151
  if (value === void 0) return void 0;
152
152
  const source = record2(value, "harnesses.toolServices.dashScope");
@@ -167,7 +167,7 @@ function parsePexelsSettings(value) {
167
167
  });
168
168
  }
169
169
 
170
- // src/capabilities/infrastructure/web/settings.ts
170
+ // src/utils/clients/web/settings.ts
171
171
  function parseRoutifySettings(value) {
172
172
  if (value === void 0) return void 0;
173
173
  const source = record2(value, "harnesses.toolServices.routify");
@@ -185,7 +185,7 @@ function parseRoutifySettings(value) {
185
185
  });
186
186
  }
187
187
 
188
- // src/capabilities/infrastructure/settings.ts
188
+ // src/utils/clients/settings.ts
189
189
  var INFRASTRUCTURE_SETTING_KEYS = ["routify", "dashScope", "pexels"];
190
190
  function parseInfrastructureSettings(services) {
191
191
  return {
@@ -195,7 +195,7 @@ function parseInfrastructureSettings(services) {
195
195
  };
196
196
  }
197
197
 
198
- // src/capabilities/shared/filesystem/settings.ts
198
+ // src/utils/filesystem/settings.ts
199
199
  function parseDocumentSettings(value) {
200
200
  if (value === void 0) return void 0;
201
201
  const source = record2(value, "harnesses.tools.documents");
@@ -205,7 +205,7 @@ function parseDocumentSettings(value) {
205
205
  });
206
206
  }
207
207
 
208
- // src/capabilities/shared/image-caption/settings.ts
208
+ // src/utils/image-caption/settings.ts
209
209
  function parseImageCaptionSettings(value) {
210
210
  if (value === void 0) return void 0;
211
211
  const source = record2(value, "harnesses.tools.imageCaption");
@@ -223,7 +223,7 @@ function parseImageCaptionSettings(value) {
223
223
  });
224
224
  }
225
225
 
226
- // src/capabilities/shared/capability_settings.ts
226
+ // src/utils/capability_settings.ts
227
227
  var SHARED_CAPABILITY_SETTING_KEYS = ["documents", "imageCaption"];
228
228
  function parseSharedCapabilitySettings(tools) {
229
229
  return {
@@ -346,7 +346,7 @@ function loadCapabilitySettings(cwd) {
346
346
  import { defineTool } from "@earendil-works/pi-coding-agent";
347
347
  import { Type } from "typebox";
348
348
 
349
- // src/capabilities/shared/ask-user/ask_user.ts
349
+ // src/utils/ask-user/ask_user.ts
350
350
  async function executeAskUserCapability(questions, context) {
351
351
  if (!context.hasUI) {
352
352
  return { answers: [], skipped: true, unavailable: true };
@@ -379,7 +379,7 @@ async function executeAskUserCapability(questions, context) {
379
379
  return { answers, skipped: false };
380
380
  }
381
381
 
382
- // src/capabilities/shared/workspace.ts
382
+ // src/utils/workspace.ts
383
383
  import { existsSync } from "node:fs";
384
384
  import { realpath } from "node:fs/promises";
385
385
  import path from "node:path";
@@ -561,11 +561,11 @@ function createAgentArenaEditFileTool(cwd) {
561
561
  promptSnippet: "Edit files with exact text replacement",
562
562
  parameters: agentArenaSchema2,
563
563
  async execute(toolCallId, params, signal, _onUpdate, context) {
564
- const path13 = await resolveWorkspacePath(cwd, params.path);
564
+ const path17 = await resolveWorkspacePath(cwd, params.path);
565
565
  const nativeEdit = createEditToolDefinition(cwd);
566
566
  await nativeEdit.execute(
567
567
  toolCallId,
568
- { path: path13, edits: [{ oldText: params.old_text, newText: params.new_text }] },
568
+ { path: path17, edits: [{ oldText: params.old_text, newText: params.new_text }] },
569
569
  signal,
570
570
  void 0,
571
571
  context
@@ -582,11 +582,11 @@ function createCodeEditFileTool(cwd) {
582
582
  promptSnippet: "Edit project files",
583
583
  parameters: codeSchema,
584
584
  async execute(toolCallId, params, signal, _onUpdate, context) {
585
- const path13 = await resolveWorkspacePath(cwd, params.path);
585
+ const path17 = await resolveWorkspacePath(cwd, params.path);
586
586
  const nativeEdit = createEditToolDefinition(cwd);
587
587
  await nativeEdit.execute(
588
588
  toolCallId,
589
- { path: path13, edits: [{ oldText: params.context, newText: params.replacement }] },
589
+ { path: path17, edits: [{ oldText: params.context, newText: params.replacement }] },
590
590
  signal,
591
591
  void 0,
592
592
  context
@@ -604,7 +604,7 @@ import {
604
604
  } from "@earendil-works/pi-coding-agent";
605
605
  import { Type as Type4 } from "typebox";
606
606
 
607
- // src/capabilities/shared/filesystem/document_reader.ts
607
+ // src/utils/filesystem/document_reader.ts
608
608
  import { spawn } from "node:child_process";
609
609
  import { mkdir, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
610
610
  import { tmpdir } from "node:os";
@@ -719,8 +719,8 @@ function extractDocx(data) {
719
719
  )
720
720
  );
721
721
  const sections = [];
722
- const main7 = extractPart(entryText(entries, "word/document.xml"));
723
- if (main7) sections.push(main7);
722
+ const main = extractPart(entryText(entries, "word/document.xml"));
723
+ if (main) sections.push(main);
724
724
  for (const name of Object.keys(entries).filter((candidate) => candidate !== "word/document.xml").sort(numberedPathSort)) {
725
725
  const content = extractPart(entryText(entries, name));
726
726
  if (!content) continue;
@@ -1034,7 +1034,7 @@ async function extractStructuredDocument(filePath, data, settings, signal) {
1034
1034
  };
1035
1035
  }
1036
1036
 
1037
- // src/capabilities/shared/image-caption/image_caption.ts
1037
+ // src/utils/image-caption/image_caption.ts
1038
1038
  import { readFile as readFile2 } from "node:fs/promises";
1039
1039
  import path3 from "node:path";
1040
1040
  var imageMimeTypes = {
@@ -1203,9 +1203,9 @@ function createWriteFileTool(cwd) {
1203
1203
  promptSnippet: "Create or overwrite workspace files",
1204
1204
  parameters: schema,
1205
1205
  async execute(toolCallId, params, signal, _onUpdate, context) {
1206
- const path13 = await resolveWorkspacePath(cwd, params.path);
1206
+ const path17 = await resolveWorkspacePath(cwd, params.path);
1207
1207
  const nativeWrite = createWriteToolDefinition(cwd);
1208
- await nativeWrite.execute(toolCallId, { path: path13, content: params.content }, signal, void 0, context);
1208
+ await nativeWrite.execute(toolCallId, { path: path17, content: params.content }, signal, void 0, context);
1209
1209
  return jsonToolResult({ status: "success" });
1210
1210
  }
1211
1211
  });
@@ -1383,7 +1383,7 @@ function createGenerateSpeechTool(cwd, settings, dashScope) {
1383
1383
  import { defineTool as defineTool8 } from "@earendil-works/pi-coding-agent";
1384
1384
  import { Type as Type8 } from "typebox";
1385
1385
 
1386
- // src/capabilities/infrastructure/web/routify_client.ts
1386
+ // src/utils/clients/web/routify_client.ts
1387
1387
  function record3(value) {
1388
1388
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1389
1389
  }
@@ -1606,7 +1606,7 @@ import path6 from "node:path";
1606
1606
  import { defineTool as defineTool9 } from "@earendil-works/pi-coding-agent";
1607
1607
  import { Type as Type9 } from "typebox";
1608
1608
 
1609
- // src/capabilities/infrastructure/web/search_client.ts
1609
+ // src/utils/clients/web/search_client.ts
1610
1610
  function record4(value) {
1611
1611
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1612
1612
  }
@@ -1887,15 +1887,47 @@ function createWebSearchTool(profile, settings, routify, retry) {
1887
1887
  });
1888
1888
  }
1889
1889
 
1890
- // src/harnesses/utils.ts
1890
+ // src/runtime/harness-main.ts
1891
+ import {
1892
+ main as piMain
1893
+ } from "@earendil-works/pi-coding-agent";
1894
+
1895
+ // src/capabilities/global/session_affinity.ts
1896
+ var SESSION_AFFINITY_HEADER = "session-id";
1897
+ function createSessionAffinityCapability() {
1898
+ return {
1899
+ name: "session-affinity",
1900
+ hidden: true,
1901
+ factory(pi) {
1902
+ pi.on("before_provider_headers", (event, context) => {
1903
+ event.headers[SESSION_AFFINITY_HEADER] = context.sessionManager.getSessionId();
1904
+ });
1905
+ }
1906
+ };
1907
+ }
1908
+
1909
+ // src/runtime/harness-args.ts
1891
1910
  import path7 from "node:path";
1892
- var ISOLATED_RESOURCE_ARGS = [
1893
- "--no-skills",
1894
- "--no-prompt-templates",
1895
- "--no-themes",
1896
- "--no-context-files",
1897
- "--no-builtin-tools"
1911
+ var DEFAULT_ISOLATED_RESOURCES = [
1912
+ "skills",
1913
+ "prompt-templates",
1914
+ "themes",
1915
+ "context-files",
1916
+ "builtin-tools"
1898
1917
  ];
1918
+ var NATIVE_PI_ISOLATED_RESOURCES = [
1919
+ "skills",
1920
+ "prompt-templates",
1921
+ "themes",
1922
+ "context-files"
1923
+ ];
1924
+ var RESOURCE_ISOLATION_ARGS = {
1925
+ "skills": "--no-skills",
1926
+ "prompt-templates": "--no-prompt-templates",
1927
+ "themes": "--no-themes",
1928
+ "context-files": "--no-context-files",
1929
+ "builtin-tools": "--no-builtin-tools"
1930
+ };
1899
1931
  function withLocalWorkspacePrompt(systemPrompt, cwd) {
1900
1932
  const resolvedCwd = path7.resolve(cwd);
1901
1933
  return `${systemPrompt.trimEnd()}
@@ -1906,18 +1938,92 @@ The current project root and default working directory is \`${resolvedCwd}\`. Re
1906
1938
  `;
1907
1939
  }
1908
1940
  function isolateHarnessArgs(args, systemPrompt, options = {}) {
1941
+ const isolatedResources = options.isolatedResources ?? DEFAULT_ISOLATED_RESOURCES;
1909
1942
  return [
1910
1943
  ...args,
1911
1944
  ...options.discoverExtensions ? [] : ["--no-extensions"],
1912
1945
  ...options.extensions?.flatMap((extension) => ["--extension", extension]) ?? [],
1913
- ...ISOLATED_RESOURCE_ARGS,
1914
- options.trustProjectResources ? "--approve" : "--no-approve",
1946
+ ...isolatedResources.map((resource) => RESOURCE_ISOLATION_ARGS[resource]),
1947
+ ...options.preserveProjectTrust ? [] : [options.trustProjectResources ? "--approve" : "--no-approve"],
1915
1948
  ...options.tools?.length ? ["--tools", options.tools.join(",")] : [],
1916
- "--system-prompt",
1917
- systemPrompt
1949
+ ...systemPrompt === void 0 ? [] : ["--system-prompt", systemPrompt],
1950
+ ...options.appendSystemPrompts?.flatMap(
1951
+ (prompt) => ["--append-system-prompt", prompt]
1952
+ ) ?? []
1918
1953
  ];
1919
1954
  }
1920
1955
 
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
+ // src/runtime/harness-main.ts
2005
+ function createHarnessExtensionFactories(extensionFactories = []) {
2006
+ return [createSessionAffinityCapability(), ...extensionFactories];
2007
+ }
2008
+ async function runHarnessMain(args, extensionFactories = []) {
2009
+ await piMain([...args], {
2010
+ extensionFactories: createHarnessExtensionFactories(extensionFactories)
2011
+ });
2012
+ }
2013
+ async function runComposedHarness(args, options = {}) {
2014
+ const capabilities = composeHarnessCapabilities(options.capabilities ?? []);
2015
+ await prepareHarnessCapabilities(capabilities);
2016
+ await runHarnessMain(
2017
+ isolateHarnessArgs(args, options.systemPrompt, {
2018
+ appendSystemPrompts: capabilities.appendSystemPrompts,
2019
+ extensions: capabilities.extensionPaths,
2020
+ tools: capabilities.tools,
2021
+ trustProjectResources: capabilities.trustProjectResources
2022
+ }),
2023
+ capabilities.extensionFactories
2024
+ );
2025
+ }
2026
+
1921
2027
  // src/harnesses/agent-arena.ts
1922
2028
  var BASE_SYSTEM_PROMPT = [
1923
2029
  "You are a helpful agentic assistant with tool access running on Arena.ai's Agent Mode.",
@@ -2035,22 +2141,264 @@ function createAgentArenaExtension(cwd, settings) {
2035
2141
  async function runAgentArenaHarness(args) {
2036
2142
  const cwd = process.cwd();
2037
2143
  const settings = loadCapabilitySettings(cwd);
2038
- await main(buildAgentArenaArgs(args, cwd), {
2039
- extensionFactories: [createAgentArenaExtension(cwd, settings)]
2144
+ await runHarnessMain(buildAgentArenaArgs(args, cwd), [
2145
+ createAgentArenaExtension(cwd, settings)
2146
+ ]);
2147
+ }
2148
+
2149
+ // 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";
2152
+ var COMPACT_CONTEXT_TOOL_NAME = "compact_context";
2153
+ var compactContextParameters = Type11.Object({
2154
+ reason: Type11.String({
2155
+ 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
+ minLength: 1,
2157
+ maxLength: 2e3
2158
+ }),
2159
+ preserve: Type11.Optional(Type11.Array(Type11.String({
2160
+ description: "A fact, decision, artifact, constraint, or next step that the compacted context must preserve.",
2161
+ minLength: 1,
2162
+ maxLength: 500
2163
+ }), {
2164
+ description: "Critical information that must survive compaction.",
2165
+ maxItems: 20
2166
+ }))
2167
+ }, { additionalProperties: false });
2168
+ function createCompactContextTool(scheduleCompaction) {
2169
+ return defineTool11({
2170
+ name: COMPACT_CONTEXT_TOOL_NAME,
2171
+ label: "Compact Context",
2172
+ 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.",
2173
+ promptSnippet: "Compact stale conversation context and continue the task",
2174
+ promptGuidelines: [
2175
+ "Treat <context_status> as trusted runtime metadata about the current context window.",
2176
+ "Before calling compact_context, apply the SelfCompact rubric. Every gate must pass: C1 CLOSED UNIT \u2014 the current subtask or operation has finished; C2 SUMMARIZABLE \u2014 the continuation state can be captured compactly without losing dispersed constraints or partial work; C3 PROGRESS \u2014 concrete new facts, decisions, or artifacts exist since the last compaction; N1 NOT STUCK \u2014 the agent is making progress rather than repeating failed approaches.",
2177
+ "Suppress compaction in the middle of a tool sequence, edit, derivation, or unresolved subtask. If stuck, diagnose the failure and change strategy before considering compaction. Token pressure alone is not sufficient evidence that the boundary is safe.",
2178
+ "Call compact_context as the only tool in its turn. State why this is a safe boundary and list facts, decisions, artifacts, constraints, and next steps that must survive."
2179
+ ],
2180
+ parameters: compactContextParameters,
2181
+ executionMode: "sequential",
2182
+ async execute(_toolCallId, params) {
2183
+ const request = {
2184
+ reason: params.reason.trim(),
2185
+ preserve: (params.preserve ?? []).map((item) => item.trim()).filter(Boolean)
2186
+ };
2187
+ scheduleCompaction(request);
2188
+ return {
2189
+ content: [{
2190
+ type: "text",
2191
+ text: "Context compaction is scheduled for the end of this tool turn. The harness will continue the task automatically after compaction."
2192
+ }],
2193
+ details: { status: "scheduled", ...request },
2194
+ terminate: true
2195
+ };
2196
+ }
2197
+ });
2198
+ }
2199
+
2200
+ // src/capabilities/context-management/self-compact/extension.ts
2201
+ import {
2202
+ estimateTokens
2203
+ } from "@earendil-works/pi-coding-agent";
2204
+
2205
+ // src/capabilities/context-management/self-compact/prompt.ts
2206
+ function formatContextStatus(status) {
2207
+ const percent = status.usedPercent === null ? "unknown" : status.usedPercent.toFixed(1);
2208
+ return [
2209
+ "<context_status>",
2210
+ "management: self_compact",
2211
+ `estimated_tokens: ${status.estimatedTokens}`,
2212
+ `context_window: ${status.contextWindow || "unknown"}`,
2213
+ `used_percent: ${percent}`,
2214
+ `remaining_tokens: ${status.remainingTokens ?? "unknown"}`,
2215
+ `measurement: ${status.measurement}`,
2216
+ "threshold_auto_compaction: disabled",
2217
+ "overflow_recovery: enabled",
2218
+ "</context_status>"
2219
+ ].join("\n");
2220
+ }
2221
+ function buildCompactionInstructions(request) {
2222
+ const preserve = request.preserve.length > 0 ? request.preserve.map((item, index) => `${index + 1}. ${item}`).join("\n") : "No additional items were specified. Infer the critical continuation state from the conversation.";
2223
+ return `The task model deliberately requested compaction at a semantic boundary.
2224
+
2225
+ Reason:
2226
+ ${request.reason}
2227
+
2228
+ Information that must survive:
2229
+ ${preserve}
2230
+
2231
+ Produce a continuation-safe summary. Preserve the user's objective and constraints, decisions and rationale, completed work, current execution state, relevant file paths and artifacts, observed failures, unresolved questions, and concrete next steps. Include only information supported by the conversation; label uncertainty explicitly instead of turning assumptions into facts. Clearly distinguish completed actions from planned actions so the continuing agent does not repeat work. Omit superseded details, bulky raw outputs, and dead-end exploration unless they explain a constraint or failure.`;
2232
+ }
2233
+
2234
+ // src/capabilities/context-management/self-compact/extension.ts
2235
+ var CONTEXT_STATUS_MESSAGE_TYPE = "self-compact-status";
2236
+ var CONTEXT_CONTINUATION_MESSAGE_TYPE = "self-compact-continuation";
2237
+ var CONTEXT_COMPACTION_ENTRY_TYPE = "self-compact";
2238
+ function estimateContextStatus(messages, context) {
2239
+ const usage = context.getContextUsage();
2240
+ const contextWindow = usage?.contextWindow ?? context.model?.contextWindow ?? 0;
2241
+ const hasPiUsage = usage?.tokens !== null && usage?.tokens !== void 0;
2242
+ const estimatedTokens = hasPiUsage ? usage.tokens : messages.reduce((total, message) => total + estimateTokens(message), 0);
2243
+ const usedPercent = contextWindow > 0 ? estimatedTokens / contextWindow * 100 : null;
2244
+ return {
2245
+ estimatedTokens,
2246
+ contextWindow,
2247
+ usedPercent,
2248
+ remainingTokens: contextWindow > 0 ? Math.max(0, contextWindow - estimatedTokens) : null,
2249
+ measurement: hasPiUsage ? "pi-usage" : "message-estimate"
2250
+ };
2251
+ }
2252
+ function statusMessage(messages, context) {
2253
+ const status = estimateContextStatus(messages, context);
2254
+ return {
2255
+ role: "custom",
2256
+ customType: CONTEXT_STATUS_MESSAGE_TYPE,
2257
+ content: formatContextStatus(status),
2258
+ display: false,
2259
+ details: status,
2260
+ timestamp: Date.now()
2261
+ };
2262
+ }
2263
+ function createSelfCompactExtension() {
2264
+ let pendingRequest;
2265
+ let compactionInFlight = false;
2266
+ let waitingForContinuation = false;
2267
+ let lifecyclePromise;
2268
+ let resolveLifecycle;
2269
+ function ensureLifecycle() {
2270
+ if (lifecyclePromise) return;
2271
+ lifecyclePromise = new Promise((resolve) => {
2272
+ resolveLifecycle = resolve;
2273
+ });
2274
+ }
2275
+ function finishLifecycle() {
2276
+ resolveLifecycle?.();
2277
+ resolveLifecycle = void 0;
2278
+ lifecyclePromise = void 0;
2279
+ }
2280
+ return {
2281
+ name: "self-compact",
2282
+ factory(pi) {
2283
+ pi.registerTool(createCompactContextTool((request) => {
2284
+ if (pendingRequest || compactionInFlight) {
2285
+ throw new Error("A context compaction request is already pending.");
2286
+ }
2287
+ pendingRequest = request;
2288
+ }));
2289
+ pi.on("context", (event, context) => ({
2290
+ messages: [...event.messages, statusMessage(event.messages, context)]
2291
+ }));
2292
+ pi.on("session_before_compact", (event) => {
2293
+ if (event.reason === "threshold") return { cancel: true };
2294
+ return void 0;
2295
+ });
2296
+ pi.on("agent_settled", (_event, context) => {
2297
+ if (waitingForContinuation) {
2298
+ waitingForContinuation = false;
2299
+ if (!pendingRequest && !compactionInFlight) {
2300
+ setImmediate(finishLifecycle);
2301
+ return;
2302
+ }
2303
+ }
2304
+ if (!pendingRequest || compactionInFlight) return;
2305
+ const request = pendingRequest;
2306
+ pendingRequest = void 0;
2307
+ compactionInFlight = true;
2308
+ ensureLifecycle();
2309
+ const tokensBefore = context.getContextUsage()?.tokens ?? null;
2310
+ context.compact({
2311
+ customInstructions: buildCompactionInstructions(request),
2312
+ onComplete: (result) => {
2313
+ compactionInFlight = false;
2314
+ pi.appendEntry(CONTEXT_COMPACTION_ENTRY_TYPE, {
2315
+ status: "completed",
2316
+ reason: request.reason,
2317
+ preserve: request.preserve,
2318
+ tokensBefore: result.tokensBefore,
2319
+ estimatedTokensAfter: result.estimatedTokensAfter
2320
+ });
2321
+ waitingForContinuation = true;
2322
+ pi.sendMessage({
2323
+ customType: CONTEXT_CONTINUATION_MESSAGE_TYPE,
2324
+ content: "Context compaction completed. Continue the current task from the compacted state. Do not repeat completed work.",
2325
+ display: false,
2326
+ details: {
2327
+ tokensBefore: result.tokensBefore,
2328
+ estimatedTokensAfter: result.estimatedTokensAfter
2329
+ }
2330
+ }, { triggerTurn: true });
2331
+ },
2332
+ onError: (error) => {
2333
+ compactionInFlight = false;
2334
+ pi.appendEntry(CONTEXT_COMPACTION_ENTRY_TYPE, {
2335
+ status: "failed",
2336
+ reason: request.reason,
2337
+ preserve: request.preserve,
2338
+ tokensBefore,
2339
+ error: error.message
2340
+ });
2341
+ waitingForContinuation = true;
2342
+ pi.sendMessage({
2343
+ customType: CONTEXT_CONTINUATION_MESSAGE_TYPE,
2344
+ content: `Context compaction failed (${error.message}). Continue the current task using the existing context; do not retry immediately unless the situation changes.`,
2345
+ display: false,
2346
+ details: { error: error.message }
2347
+ }, { triggerTurn: true });
2348
+ }
2349
+ });
2350
+ return lifecyclePromise;
2351
+ });
2352
+ pi.on("session_shutdown", async (_event, context) => {
2353
+ if ((context.mode === "json" || context.mode === "print") && lifecyclePromise) {
2354
+ await lifecyclePromise;
2355
+ }
2356
+ pendingRequest = void 0;
2357
+ compactionInFlight = false;
2358
+ waitingForContinuation = false;
2359
+ finishLifecycle();
2360
+ });
2361
+ }
2362
+ };
2363
+ }
2364
+
2365
+ // src/capabilities/context-management/self-compact/index.ts
2366
+ function createSelfCompactCapability() {
2367
+ return {
2368
+ name: "self-compact",
2369
+ tools: [COMPACT_CONTEXT_TOOL_NAME],
2370
+ extensionFactories: [createSelfCompactExtension()]
2371
+ };
2372
+ }
2373
+
2374
+ // src/harnesses/self-compact.ts
2375
+ function buildSelfCompactArgs(args) {
2376
+ return isolateHarnessArgs(args, void 0, {
2377
+ isolatedResources: NATIVE_PI_ISOLATED_RESOURCES
2040
2378
  });
2041
2379
  }
2380
+ async function runSelfCompactHarness(args) {
2381
+ const capabilities = composeHarnessCapabilities([
2382
+ createSelfCompactCapability()
2383
+ ]);
2384
+ await prepareHarnessCapabilities(capabilities);
2385
+ await runHarnessMain(
2386
+ buildSelfCompactArgs(args),
2387
+ capabilities.extensionFactories
2388
+ );
2389
+ }
2042
2390
 
2043
2391
  // src/harnesses/code-arena-full-stack.ts
2044
- import { main as main2 } from "@earendil-works/pi-coding-agent";
2392
+ import "@earendil-works/pi-coding-agent";
2045
2393
 
2046
2394
  // src/capabilities/tools/execution/build_and_start.ts
2047
2395
  import { existsSync as existsSync2 } from "node:fs";
2048
2396
  import { mkdir as mkdir5, readFile as readFile5 } from "node:fs/promises";
2049
2397
  import path9 from "node:path";
2050
2398
  import { setTimeout as delay3 } from "node:timers/promises";
2051
- import { defineTool as defineTool11 } from "@earendil-works/pi-coding-agent";
2052
- import { Type as Type11 } from "typebox";
2053
- var schema6 = Type11.Object({ description: Type11.String() }, { additionalProperties: false });
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 });
2054
2402
  function failure(stage, message, logs) {
2055
2403
  return jsonToolResult({
2056
2404
  status: "error",
@@ -2060,7 +2408,7 @@ function failure(stage, message, logs) {
2060
2408
  });
2061
2409
  }
2062
2410
  function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
2063
- return defineTool11({
2411
+ return defineTool12({
2064
2412
  name: "build_and_start",
2065
2413
  label: "Build And Start",
2066
2414
  description: "Build and start the full-stack preview, then verify /api/health.",
@@ -2138,14 +2486,14 @@ function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
2138
2486
  }
2139
2487
 
2140
2488
  // src/capabilities/tools/execution/install_npm_packages.ts
2141
- import { defineTool as defineTool12 } from "@earendil-works/pi-coding-agent";
2142
- import { Type as Type12 } from "typebox";
2143
- var schema7 = Type12.Object({ packages: Type12.Array(Type12.String()) }, { additionalProperties: false });
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 });
2144
2492
  function packageNameIsSafe(value) {
2145
2493
  return Boolean(value) && !value.startsWith("-") && !/\s/u.test(value) && /^(?:@[\w.-]+\/)?[\w.-]+(?:@(?:[\w*^<>=|.+-]+))?$/u.test(value);
2146
2494
  }
2147
2495
  function createInstallNpmPackagesTool(cwd, exec, packageLock, npmCommand) {
2148
- return defineTool12({
2496
+ return defineTool13({
2149
2497
  name: "install_npm_packages",
2150
2498
  label: "Install NPM Packages",
2151
2499
  description: "Install npm packages as project dependencies.",
@@ -2169,23 +2517,23 @@ function createInstallNpmPackagesTool(cwd, exec, packageLock, npmCommand) {
2169
2517
  }
2170
2518
 
2171
2519
  // src/capabilities/tools/filesystem/create_file.ts
2172
- import { createWriteToolDefinition as createWriteToolDefinition2, defineTool as defineTool13 } from "@earendil-works/pi-coding-agent";
2173
- import { Type as Type13 } from "typebox";
2174
- var schema8 = Type13.Object({
2175
- path: Type13.String({ description: "File path relative to project root" }),
2176
- content: Type13.String({ description: "Complete file content" })
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" })
2177
2525
  }, { additionalProperties: false });
2178
2526
  function createCreateFileTool(cwd) {
2179
- return defineTool13({
2527
+ return defineTool14({
2180
2528
  name: "create_file",
2181
2529
  label: "Create File",
2182
2530
  description: "Create a new project file or completely overwrite an existing file.",
2183
2531
  promptSnippet: "Create project files",
2184
2532
  parameters: schema8,
2185
2533
  async execute(toolCallId, params, signal, _onUpdate, context) {
2186
- const path13 = await resolveWorkspacePath(cwd, params.path);
2534
+ const path17 = await resolveWorkspacePath(cwd, params.path);
2187
2535
  const nativeWrite = createWriteToolDefinition2(cwd);
2188
- await nativeWrite.execute(toolCallId, { path: path13, content: params.content }, signal, void 0, context);
2536
+ await nativeWrite.execute(toolCallId, { path: path17, content: params.content }, signal, void 0, context);
2189
2537
  return jsonToolResult({ status: "success", message: `Created ${params.path}.` });
2190
2538
  }
2191
2539
  });
@@ -2193,37 +2541,37 @@ function createCreateFileTool(cwd) {
2193
2541
 
2194
2542
  // src/capabilities/tools/filesystem/delete_file.ts
2195
2543
  import { rm as rm2 } from "node:fs/promises";
2196
- import { defineTool as defineTool14 } from "@earendil-works/pi-coding-agent";
2197
- import { Type as Type14 } from "typebox";
2198
- var schema9 = Type14.Object(
2199
- { path: Type14.String({ description: "Path relative to project root" }) },
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" }) },
2200
2548
  { additionalProperties: false }
2201
2549
  );
2202
2550
  function createDeleteFileTool(cwd) {
2203
- return defineTool14({
2551
+ return defineTool15({
2204
2552
  name: "delete_file",
2205
2553
  label: "Delete File",
2206
2554
  description: "Delete a file or directory from the project.",
2207
2555
  promptSnippet: "Delete project files",
2208
2556
  parameters: schema9,
2209
2557
  async execute(_toolCallId, params) {
2210
- const path13 = await resolveWorkspacePath(cwd, params.path);
2211
- await rm2(path13, { recursive: true, force: true });
2558
+ const path17 = await resolveWorkspacePath(cwd, params.path);
2559
+ await rm2(path17, { recursive: true, force: true });
2212
2560
  return jsonToolResult({ status: "success" });
2213
2561
  }
2214
2562
  });
2215
2563
  }
2216
2564
 
2217
2565
  // src/capabilities/tools/filesystem/glob_files.ts
2218
- import { createFindToolDefinition, defineTool as defineTool15 } from "@earendil-works/pi-coding-agent";
2219
- import { Type as Type15 } from "typebox";
2220
- var schema10 = Type15.Object({
2221
- pattern: Type15.String({ description: "Glob pattern such as **/*.ts" }),
2222
- path: Type15.Optional(Type15.String({ description: "Search directory relative to project root" }))
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" }))
2223
2571
  }, { additionalProperties: false });
2224
2572
  function createGlobFilesTool(cwd) {
2225
2573
  const nativeFind = createFindToolDefinition(cwd);
2226
- return defineTool15({
2574
+ return defineTool16({
2227
2575
  name: "glob_files",
2228
2576
  label: "Glob Files",
2229
2577
  description: "Find project files with a glob pattern.",
@@ -2252,26 +2600,26 @@ function createGlobFilesTool(cwd) {
2252
2600
  }
2253
2601
 
2254
2602
  // src/capabilities/tools/filesystem/grep_files.ts
2255
- import { createGrepToolDefinition, defineTool as defineTool16 } from "@earendil-works/pi-coding-agent";
2256
- import { Type as Type16 } from "typebox";
2257
- var schema11 = Type16.Object({
2258
- pattern: Type16.String(),
2259
- path: Type16.Optional(Type16.String()),
2260
- glob: Type16.Optional(Type16.String()),
2261
- output_mode: Type16.Optional(Type16.Union([
2262
- Type16.Literal("content"),
2263
- Type16.Literal("files_with_matches"),
2264
- Type16.Literal("count")
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")
2265
2613
  ])),
2266
- "-i": Type16.Optional(Type16.Boolean()),
2267
- "-B": Type16.Optional(Type16.Integer({ minimum: 0 })),
2268
- "-A": Type16.Optional(Type16.Integer({ minimum: 0 })),
2269
- "-C": Type16.Optional(Type16.Integer({ minimum: 0 })),
2270
- context: Type16.Optional(Type16.Integer({ minimum: 0 }))
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 }))
2271
2619
  }, { additionalProperties: false });
2272
2620
  function createGrepFilesTool(cwd) {
2273
2621
  const nativeGrep = createGrepToolDefinition(cwd);
2274
- return defineTool16({
2622
+ return defineTool17({
2275
2623
  name: "grep_files",
2276
2624
  label: "Grep Files",
2277
2625
  description: "Search project file contents with a regular expression. Supports glob filtering.",
@@ -2309,7 +2657,7 @@ function createGrepFilesTool(cwd) {
2309
2657
  return jsonToolResult({
2310
2658
  status: "success",
2311
2659
  mode: outputMode,
2312
- counts: [...counts].map(([path13, count]) => ({ path: path13, count })),
2660
+ counts: [...counts].map(([path17, count]) => ({ path: path17, count })),
2313
2661
  totalMatches: lines.length
2314
2662
  });
2315
2663
  }
@@ -2319,14 +2667,14 @@ function createGrepFilesTool(cwd) {
2319
2667
  }
2320
2668
 
2321
2669
  // src/capabilities/tools/filesystem/list_files.ts
2322
- import { createFindToolDefinition as createFindToolDefinition2, defineTool as defineTool17 } from "@earendil-works/pi-coding-agent";
2323
- import { Type as Type17 } from "typebox";
2324
- var schema12 = Type17.Object({
2325
- path: Type17.Optional(Type17.String({ description: "Directory relative to project root" }))
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" }))
2326
2674
  }, { additionalProperties: false });
2327
2675
  function createListFilesTool(cwd) {
2328
2676
  const nativeFind = createFindToolDefinition2(cwd);
2329
- return defineTool17({
2677
+ return defineTool18({
2330
2678
  name: "list_files",
2331
2679
  label: "List Files",
2332
2680
  description: "Recursively list project files below a directory.",
@@ -2344,17 +2692,17 @@ function createListFilesTool(cwd) {
2344
2692
  const text = result.content.find((part) => part.type === "text")?.text || "";
2345
2693
  return jsonToolResult({
2346
2694
  status: "success",
2347
- files: text.split("\n").filter((line) => line && !line.startsWith("[")).map((path13) => ({ path: path13 }))
2695
+ files: text.split("\n").filter((line) => line && !line.startsWith("[")).map((path17) => ({ path: path17 }))
2348
2696
  });
2349
2697
  }
2350
2698
  });
2351
2699
  }
2352
2700
 
2353
2701
  // src/capabilities/tools/media/fetch_media.ts
2354
- import { defineTool as defineTool18 } from "@earendil-works/pi-coding-agent";
2355
- import { Type as Type18 } from "typebox";
2702
+ import { defineTool as defineTool19 } from "@earendil-works/pi-coding-agent";
2703
+ import { Type as Type19 } from "typebox";
2356
2704
 
2357
- // src/capabilities/infrastructure/media/pexels.ts
2705
+ // src/utils/clients/media/pexels.ts
2358
2706
  import { createHash } from "node:crypto";
2359
2707
  import { mkdir as mkdir6, readFile as readFile6, writeFile as writeFile4 } from "node:fs/promises";
2360
2708
  import { tmpdir as tmpdir2 } from "node:os";
@@ -2400,23 +2748,23 @@ async function fetchPexels(settings, retry, pathname, params, signal) {
2400
2748
  }
2401
2749
 
2402
2750
  // src/capabilities/tools/media/fetch_media.ts
2403
- var schema13 = Type18.Object({
2404
- query: Type18.String(),
2405
- media_type: Type18.Union([Type18.Literal("image"), Type18.Literal("video"), Type18.Literal("both")], { default: "both" }),
2406
- count: Type18.Number({ default: 6 }),
2407
- orientation: Type18.Union([
2408
- Type18.Literal("any"),
2409
- Type18.Literal("landscape"),
2410
- Type18.Literal("portrait"),
2411
- Type18.Literal("square")
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")
2412
2760
  ], { default: "any" }),
2413
- size: Type18.Union([
2414
- Type18.Literal("any"),
2415
- Type18.Literal("large"),
2416
- Type18.Literal("medium"),
2417
- Type18.Literal("small")
2761
+ size: Type19.Union([
2762
+ Type19.Literal("any"),
2763
+ Type19.Literal("large"),
2764
+ Type19.Literal("medium"),
2765
+ Type19.Literal("small")
2418
2766
  ], { default: "any" }),
2419
- locale: Type18.String()
2767
+ locale: Type19.String()
2420
2768
  }, { additionalProperties: false });
2421
2769
  function record7(value) {
2422
2770
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
@@ -2461,7 +2809,7 @@ function videos(payload) {
2461
2809
  });
2462
2810
  }
2463
2811
  function createFetchMediaTool(settings, retry) {
2464
- return defineTool18({
2812
+ return defineTool19({
2465
2813
  name: "fetch_media",
2466
2814
  label: "Fetch Media",
2467
2815
  description: "Search Pexels for stock photos and videos and return URL-based assets.",
@@ -2520,14 +2868,14 @@ function createFetchMediaTool(settings, retry) {
2520
2868
  }
2521
2869
 
2522
2870
  // src/capabilities/tools/web/web_fetch.ts
2523
- import { defineTool as defineTool19 } from "@earendil-works/pi-coding-agent";
2524
- import { Type as Type19 } from "typebox";
2525
- var schema14 = Type19.Object({
2526
- url: Type19.String(),
2527
- format: Type19.Union([Type19.Literal("markdown"), Type19.Literal("text"), Type19.Literal("html")])
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")])
2528
2876
  }, { additionalProperties: false });
2529
2877
  function createWebFetchTool(routify, retry) {
2530
- return defineTool19({
2878
+ return defineTool20({
2531
2879
  name: "web_fetch",
2532
2880
  label: "Web Fetch",
2533
2881
  description: "Fetch a web page and return markdown, plain text, or HTML.",
@@ -2696,13 +3044,12 @@ function createCodeArenaFullStackExtension(cwd, settings) {
2696
3044
  async function runCodeArenaFullStackHarness(args) {
2697
3045
  const cwd = process.cwd();
2698
3046
  const settings = loadCapabilitySettings(cwd);
2699
- await main2(buildCodeArenaFullStackArgs(args, cwd), {
2700
- extensionFactories: [createCodeArenaFullStackExtension(cwd, settings)]
2701
- });
3047
+ await runHarnessMain(buildCodeArenaFullStackArgs(args, cwd), [
3048
+ createCodeArenaFullStackExtension(cwd, settings)
3049
+ ]);
2702
3050
  }
2703
3051
 
2704
3052
  // src/harnesses/code-arena-html.ts
2705
- import { main as main3 } from "@earendil-works/pi-coding-agent";
2706
3053
  var BASE_SYSTEM_PROMPT3 = [
2707
3054
  "You are an expert coding assistant who creates single page websites by using the provided tools to create and/or edit an index.html file using HTML, CSS, and JavaScript.",
2708
3055
  "For any user prompt, always try to generate a website. Always just update the code instead of asking the user to confirm details.",
@@ -2776,20 +3123,20 @@ function createCodeArenaHtmlExtension(cwd, settings) {
2776
3123
  async function runCodeArenaHtmlHarness(args) {
2777
3124
  const cwd = process.cwd();
2778
3125
  const settings = loadCapabilitySettings(cwd);
2779
- await main3(buildCodeArenaHtmlArgs(args, cwd), {
2780
- extensionFactories: [createCodeArenaHtmlExtension(cwd, settings)]
2781
- });
3126
+ await runHarnessMain(buildCodeArenaHtmlArgs(args, cwd), [
3127
+ createCodeArenaHtmlExtension(cwd, settings)
3128
+ ]);
2782
3129
  }
2783
3130
 
2784
3131
  // src/harnesses/code-arena-react.ts
2785
- import { main as main4 } from "@earendil-works/pi-coding-agent";
3132
+ import "@earendil-works/pi-coding-agent";
2786
3133
 
2787
3134
  // src/capabilities/tools/execution/build_project.ts
2788
- import { defineTool as defineTool20 } from "@earendil-works/pi-coding-agent";
2789
- import { Type as Type20 } from "typebox";
2790
- var schema15 = Type20.Object({}, { additionalProperties: false });
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 });
2791
3138
  function createBuildProjectTool(cwd, exec, npmCommand) {
2792
- return defineTool20({
3139
+ return defineTool21({
2793
3140
  name: "build_project",
2794
3141
  label: "Build Project",
2795
3142
  description: "Build the project with npm run build.",
@@ -2899,17 +3246,110 @@ function createCodeArenaReactExtension(cwd, settings) {
2899
3246
  async function runCodeArenaReactHarness(args) {
2900
3247
  const cwd = process.cwd();
2901
3248
  const settings = loadCapabilitySettings(cwd);
2902
- await main4(buildCodeArenaReactArgs(args, cwd), {
2903
- extensionFactories: [createCodeArenaReactExtension(cwd, settings)]
2904
- });
3249
+ await runHarnessMain(buildCodeArenaReactArgs(args, cwd), [
3250
+ createCodeArenaReactExtension(cwd, settings)
3251
+ ]);
2905
3252
  }
2906
3253
 
2907
- // src/harnesses/long-horizon.ts
3254
+ // src/harnesses/long-horizon-mea.ts
2908
3255
  import path12 from "node:path";
3256
+
3257
+ // src/capabilities/orchestration/mea/index.ts
2909
3258
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2910
- import {
2911
- main as main5
2912
- } from "@earendil-works/pi-coding-agent";
3259
+
3260
+ // src/runtime/package-resources.ts
3261
+ import fs from "node:fs";
3262
+ import path11 from "node:path";
3263
+ import { fileURLToPath } from "node:url";
3264
+ var PACKAGE_NAME = "@qwen-code/qwen-harness";
3265
+ var SUBAGENT_EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
3266
+ function isHarnessPackageRoot(directory) {
3267
+ const packageJsonPath = path11.join(directory, "package.json");
3268
+ try {
3269
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
3270
+ return packageJson.name === PACKAGE_NAME;
3271
+ } catch {
3272
+ return false;
3273
+ }
3274
+ }
3275
+ function resolveHarnessPackageRoot(startPath = fileURLToPath(import.meta.url)) {
3276
+ let directory = path11.dirname(path11.resolve(startPath));
3277
+ while (true) {
3278
+ if (isHarnessPackageRoot(directory)) return directory;
3279
+ const parent = path11.dirname(directory);
3280
+ if (parent === directory) break;
3281
+ directory = parent;
3282
+ }
3283
+ throw new Error(
3284
+ `Unable to locate the ${PACKAGE_NAME} package root from ${startPath}.`
3285
+ );
3286
+ }
3287
+ function resolveBundledAgentDirectory(packageRoot = resolveHarnessPackageRoot()) {
3288
+ const directory = path11.join(packageRoot, ".pi", "agents");
3289
+ try {
3290
+ if (fs.statSync(directory).isDirectory()) return directory;
3291
+ } catch {
3292
+ }
3293
+ throw new Error(`Bundled Pi agent directory is not a directory: ${directory}`);
3294
+ }
3295
+ function exposeBundledSubagentAgents(environment = process.env, agentDirectory = resolveBundledAgentDirectory()) {
3296
+ const current = environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV]?.split(path11.delimiter).map((directory) => directory.trim()).filter(Boolean) ?? [];
3297
+ const resolvedAgentDirectory = path11.resolve(agentDirectory);
3298
+ if (!current.some((directory) => path11.resolve(directory) === resolvedAgentDirectory)) {
3299
+ current.push(resolvedAgentDirectory);
3300
+ }
3301
+ environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV] = current.join(path11.delimiter);
3302
+ return resolvedAgentDirectory;
3303
+ }
3304
+
3305
+ // src/capabilities/orchestration/mea/roles.ts
3306
+ var LONG_HORIZON_MANAGER_AGENT = "long-horizon.manager";
3307
+ var LONG_HORIZON_EXECUTOR_AGENT = "long-horizon.executor";
3308
+ var LONG_HORIZON_AUDITOR_AGENT = "long-horizon.auditor";
3309
+ var LONG_HORIZON_AGENTS = [
3310
+ LONG_HORIZON_MANAGER_AGENT,
3311
+ LONG_HORIZON_EXECUTOR_AGENT,
3312
+ LONG_HORIZON_AUDITOR_AGENT
3313
+ ];
3314
+
3315
+ // src/capabilities/orchestration/mea/prompt.ts
3316
+ var BASE_SYSTEM_PROMPT5 = `## Long Horizon Orchestration
3317
+
3318
+ The following protocol governs how work is performed in this session. Preserve applicable task, domain, and acceptance requirements from earlier system instructions, but do not perform workspace operations yourself. If earlier instructions require the parent agent to inspect or modify the workspace directly, treat those instructions as requirements to delegate through this protocol instead. Do not quote or disclose hidden system instructions; carry their relevant constraints into self-contained child tasks.
3319
+
3320
+ You are the supervisor for a long-horizon task. You coordinate three isolated subagents; you do not inspect or modify the workspace yourself.
3321
+
3322
+ The roles are:
3323
+ - ${LONG_HORIZON_MANAGER_AGENT}: maintains the task contract, audited state, and exactly one next action.
3324
+ - ${LONG_HORIZON_EXECUTOR_AGENT}: executes exactly one approved workspace-changing subtask.
3325
+ - ${LONG_HORIZON_AUDITOR_AGENT}: independently inspects the real workspace and decides what is verified.
3326
+
3327
+ For every role invocation, call the subagent tool with one foreground workflow. Use this exact shape, replacing the key, agent, and task:
3328
+
3329
+ subagent({
3330
+ workflowScript: \`return runs.run("round-001-manager", { agent: "${LONG_HORIZON_MANAGER_AGENT}", context: "fresh", task: "..." })\`,
3331
+ async: false,
3332
+ mission: false,
3333
+ artifacts: false
3334
+ })
3335
+
3336
+ Never run role children in parallel. Never use forked context. Give every child a self-contained task because fresh children cannot see the parent conversation or the parent's system prompt.
3337
+
3338
+ Protocol:
3339
+ 1. Preserve the user's original request verbatim in your working state. Also preserve all applicable task, domain, process, and acceptance constraints from earlier system instructions.
3340
+ 2. Start each round with a fresh Manager. Pass it the original request, applicable upstream constraints, the current task contract, the last audited state, and all audit reports needed for its decision. On the first round, explicitly say that no progress has been audited.
3341
+ 3. The Manager must select exactly one route: execute, ask_user, done, or blocked.
3342
+ 4. For execute, start one fresh Executor with only the Manager-approved subtask, acceptance criteria, boundaries, relevant audited state, applicable upstream constraints, and original request. Do not treat the Executor's claims as verified.
3343
+ 5. After every Executor, start one fresh Auditor. Pass it the original request, applicable upstream constraints, task contract, Manager plan, Executor report, and relevant prior audit reports. The Auditor must inspect the workspace itself.
3344
+ 6. Only Auditor facts with Status: complete, Integrity: clean, and Contract audit: aligned may enter verified state. Otherwise preserve earlier verified progress and send the gaps to a fresh Manager in the next round.
3345
+ 7. Use ask_user yourself only when the Manager routes ask_user. Children must never ask the human directly.
3346
+ 8. Finish only when the latest Auditor report independently covers every original requirement and applicable upstream constraint, and its first three control lines are exactly Status: complete, Integrity: clean, and Contract audit: aligned. A Manager or Executor completion claim is never sufficient.
3347
+ 9. If the Manager reports blocked, explain the verified blocker. Do not invent progress or silently relax the task contract.
3348
+
3349
+ Keep the parent context compact: retain the original request, stable task contract, concise audited state, applicable upstream constraints, and the original Auditor reports that remain relevant. Do not copy raw child tool logs into later prompts. Your final response should summarize the verified deliverable, evidence, and any remaining limitations without discussing this orchestration protocol.`;
3350
+ function longHorizonSystemPrompt(cwd = process.cwd()) {
3351
+ return withLocalWorkspacePrompt(BASE_SYSTEM_PROMPT5, cwd);
3352
+ }
2913
3353
 
2914
3354
  // node_modules/pi-subagents/src/runs/shared/capability-ceiling.ts
2915
3355
  import { Buffer as Buffer2 } from "node:buffer";
@@ -2993,65 +3433,18 @@ function registerSubagentCapabilityCeiling(options) {
2993
3433
  };
2994
3434
  }
2995
3435
 
2996
- // src/runtime/package-resources.ts
2997
- import fs from "node:fs";
2998
- import path11 from "node:path";
2999
- import { fileURLToPath } from "node:url";
3000
- var PACKAGE_NAME = "@qwen-code/qwen-harness";
3001
- var SUBAGENT_EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
3002
- function isHarnessPackageRoot(directory) {
3003
- const packageJsonPath = path11.join(directory, "package.json");
3004
- try {
3005
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
3006
- return packageJson.name === PACKAGE_NAME;
3007
- } catch {
3008
- return false;
3009
- }
3010
- }
3011
- function resolveHarnessPackageRoot(startPath = fileURLToPath(import.meta.url)) {
3012
- let directory = path11.dirname(path11.resolve(startPath));
3013
- while (true) {
3014
- if (isHarnessPackageRoot(directory)) return directory;
3015
- const parent = path11.dirname(directory);
3016
- if (parent === directory) break;
3017
- directory = parent;
3018
- }
3019
- throw new Error(
3020
- `Unable to locate the ${PACKAGE_NAME} package root from ${startPath}.`
3021
- );
3436
+ // src/capabilities/orchestration/mea/rounds.ts
3437
+ var managerAgentPattern = LONG_HORIZON_MANAGER_AGENT.replaceAll(".", "\\.");
3438
+ var MANAGER_WORKFLOW_PATTERN = new RegExp(
3439
+ `\\bruns\\.run\\s*\\(\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')\\s*,\\s*\\{\\s*agent\\s*:\\s*["']${managerAgentPattern}["']`,
3440
+ "u"
3441
+ );
3442
+ function isRecord(value) {
3443
+ return typeof value === "object" && value !== null;
3022
3444
  }
3023
- function resolveBundledAgentDirectory(packageRoot = resolveHarnessPackageRoot()) {
3024
- const directory = path11.join(packageRoot, ".pi", "agents");
3025
- try {
3026
- if (fs.statSync(directory).isDirectory()) return directory;
3027
- } catch {
3028
- }
3029
- throw new Error(`Bundled Pi agent directory is not a directory: ${directory}`);
3030
- }
3031
- function exposeBundledSubagentAgents(environment = process.env, agentDirectory = resolveBundledAgentDirectory()) {
3032
- const current = environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV]?.split(path11.delimiter).map((directory) => directory.trim()).filter(Boolean) ?? [];
3033
- const resolvedAgentDirectory = path11.resolve(agentDirectory);
3034
- if (!current.some((directory) => path11.resolve(directory) === resolvedAgentDirectory)) {
3035
- current.push(resolvedAgentDirectory);
3036
- }
3037
- environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV] = current.join(path11.delimiter);
3038
- return resolvedAgentDirectory;
3039
- }
3040
-
3041
- // src/harnesses/long-horizon.ts
3042
- var MANAGER_AGENT = "long-horizon.manager";
3043
- var EXECUTOR_AGENT = "long-horizon.executor";
3044
- var AUDITOR_AGENT = "long-horizon.auditor";
3045
- var SUPERVISOR_TOOLS = ["ask_user", "subagent"];
3046
- var LONG_HORIZON_AGENTS = [MANAGER_AGENT, EXECUTOR_AGENT, AUDITOR_AGENT];
3047
- var LONG_HORIZON_MAX_ROUNDS = 25;
3048
- var MANAGER_WORKFLOW_PATTERN = /\bruns\.run\s*\(\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*\{\s*agent\s*:\s*["']long-horizon\.manager["']/u;
3049
- function isRecord(value) {
3050
- return typeof value === "object" && value !== null;
3051
- }
3052
- function isLongHorizonManagerLaunch(input) {
3053
- if (!isRecord(input) || typeof input.workflowScript !== "string") return false;
3054
- return MANAGER_WORKFLOW_PATTERN.test(input.workflowScript);
3445
+ function isLongHorizonManagerLaunch(input) {
3446
+ if (!isRecord(input) || typeof input.workflowScript !== "string") return false;
3447
+ return MANAGER_WORKFLOW_PATTERN.test(input.workflowScript);
3055
3448
  }
3056
3449
  function hasStartedSubagentExecution(message) {
3057
3450
  if (!isRecord(message)) return false;
@@ -3081,50 +3474,14 @@ function countLongHorizonRounds(entries) {
3081
3474
  }
3082
3475
  return rounds;
3083
3476
  }
3084
- var BASE_SYSTEM_PROMPT5 = `You are the supervisor for a long-horizon task harness. You coordinate three isolated subagents; you do not inspect or modify the workspace yourself.
3085
-
3086
- The roles are:
3087
- - ${MANAGER_AGENT}: maintains the task contract, audited state, and exactly one next action.
3088
- - ${EXECUTOR_AGENT}: executes exactly one approved workspace-changing subtask.
3089
- - ${AUDITOR_AGENT}: independently inspects the real workspace and decides what is verified.
3090
3477
 
3091
- For every role invocation, call the subagent tool with one foreground workflow. Use this exact shape, replacing the key, agent, and task:
3092
-
3093
- subagent({
3094
- workflowScript: \`return runs.run("round-001-manager", { agent: "${MANAGER_AGENT}", context: "fresh", task: "..." })\`,
3095
- async: false,
3096
- mission: false,
3097
- artifacts: false
3098
- })
3099
-
3100
- Never run role children in parallel. Never use forked context. Give every child a self-contained task because fresh children cannot see the parent conversation.
3101
-
3102
- Protocol:
3103
- 1. Preserve the user's original request verbatim in your working state.
3104
- 2. Start each round with a fresh Manager. Pass it the original request, the current task contract, the last audited state, and all audit reports needed for its decision. On the first round, explicitly say that no progress has been audited.
3105
- 3. The Manager must select exactly one route: execute, ask_user, done, or blocked.
3106
- 4. For execute, start one fresh Executor with only the Manager-approved subtask, acceptance criteria, boundaries, relevant audited state, and original request. Do not treat the Executor's claims as verified.
3107
- 5. After every Executor, start one fresh Auditor. Pass it the original request, task contract, Manager plan, Executor report, and relevant prior audit reports. The Auditor must inspect the workspace itself.
3108
- 6. Only Auditor facts with Status: complete, Integrity: clean, and Contract audit: aligned may enter verified state. Otherwise preserve earlier verified progress and send the gaps to a fresh Manager in the next round.
3109
- 7. Use ask_user yourself only when the Manager routes ask_user. Children must never ask the human directly.
3110
- 8. Finish only when the latest Auditor report independently covers every original requirement and its first three control lines are exactly Status: complete, Integrity: clean, and Contract audit: aligned. A Manager or Executor completion claim is never sufficient.
3111
- 9. If the Manager reports blocked, explain the verified blocker. Do not invent progress or silently relax the task contract.
3112
-
3113
- Keep the parent context compact: retain the original request, stable task contract, concise audited state, and the original Auditor reports that remain relevant. Do not copy raw child tool logs into later prompts. Your final response should summarize the verified deliverable, evidence, and any remaining limitations without discussing this orchestration protocol.`;
3114
- function longHorizonSystemPrompt(cwd = process.cwd()) {
3115
- return withLocalWorkspacePrompt(BASE_SYSTEM_PROMPT5, cwd);
3116
- }
3117
- function resolveLongHorizonSubagentsExtension() {
3118
- return fileURLToPath2(import.meta.resolve("pi-subagents"));
3119
- }
3120
- function buildLongHorizonArgs(args, cwd = process.cwd(), subagentsExtension = resolveLongHorizonSubagentsExtension()) {
3121
- return isolateHarnessArgs(args, longHorizonSystemPrompt(cwd), {
3122
- extensions: [subagentsExtension],
3123
- trustProjectResources: true,
3124
- tools: SUPERVISOR_TOOLS
3125
- });
3126
- }
3127
- function createLongHorizonSupervisorExtension() {
3478
+ // src/capabilities/orchestration/mea/supervisor.ts
3479
+ var LONG_HORIZON_MAX_ROUNDS = 25;
3480
+ function createLongHorizonSupervisorExtension(options = {}) {
3481
+ const maxRounds = options.maxRounds ?? LONG_HORIZON_MAX_ROUNDS;
3482
+ if (!Number.isInteger(maxRounds) || maxRounds <= 0) {
3483
+ throw new Error("Long Horizon maxRounds must be a positive integer.");
3484
+ }
3128
3485
  return {
3129
3486
  name: "long-horizon-supervisor",
3130
3487
  factory(pi) {
@@ -3138,7 +3495,7 @@ function createLongHorizonSupervisorExtension() {
3138
3495
  roundsStarted = countLongHorizonRounds(context.sessionManager.getBranch());
3139
3496
  capabilityCeiling = registerSubagentCapabilityCeiling({
3140
3497
  sessionId: context.sessionManager.getSessionId(),
3141
- source: "long-horizon-harness",
3498
+ source: "long-horizon-capability",
3142
3499
  ceiling: {
3143
3500
  allowedAgents: [...LONG_HORIZON_AGENTS],
3144
3501
  denyExtensions: true
@@ -3146,17 +3503,13 @@ function createLongHorizonSupervisorExtension() {
3146
3503
  });
3147
3504
  });
3148
3505
  pi.on("tool_call", (event) => {
3149
- if (event.toolName !== "subagent") {
3150
- return;
3151
- }
3152
- if (!isLongHorizonManagerLaunch(event.input)) {
3153
- return;
3154
- }
3155
- if (roundsStarted >= LONG_HORIZON_MAX_ROUNDS) {
3506
+ if (event.toolName !== "subagent") return;
3507
+ if (!isLongHorizonManagerLaunch(event.input)) return;
3508
+ if (roundsStarted >= maxRounds) {
3156
3509
  return {
3157
3510
  block: true,
3158
3511
  terminate: true,
3159
- reason: `Long Horizon round budget exhausted: ${LONG_HORIZON_MAX_ROUNDS}/${LONG_HORIZON_MAX_ROUNDS} Manager rounds have already started. Do not launch another role; report the latest audited state and remaining gaps.`
3512
+ reason: `Long Horizon round budget exhausted: ${maxRounds}/${maxRounds} Manager rounds have already started. Do not launch another role; report the latest audited state and remaining gaps.`
3160
3513
  };
3161
3514
  }
3162
3515
  roundsStarted += 1;
@@ -3179,29 +3532,1319 @@ function createLongHorizonSupervisorExtension() {
3179
3532
  }
3180
3533
  };
3181
3534
  }
3535
+
3536
+ // src/capabilities/orchestration/mea/index.ts
3537
+ var SUPERVISOR_TOOLS = ["ask_user", "subagent"];
3538
+ function resolveLongHorizonSubagentsExtension() {
3539
+ return fileURLToPath2(import.meta.resolve("pi-subagents"));
3540
+ }
3541
+ function createLongHorizonCapability(options = {}) {
3542
+ const cwd = options.cwd ?? process.cwd();
3543
+ return {
3544
+ name: "long-horizon",
3545
+ appendSystemPrompts: [{
3546
+ text: longHorizonSystemPrompt(cwd),
3547
+ phase: "orchestration"
3548
+ }],
3549
+ tools: SUPERVISOR_TOOLS,
3550
+ extensionPaths: [
3551
+ options.subagentsExtension ?? resolveLongHorizonSubagentsExtension()
3552
+ ],
3553
+ extensionFactories: [createLongHorizonSupervisorExtension({
3554
+ maxRounds: options.maxRounds ?? LONG_HORIZON_MAX_ROUNDS
3555
+ })],
3556
+ trustProjectResources: true,
3557
+ prepare: () => {
3558
+ exposeBundledSubagentAgents();
3559
+ }
3560
+ };
3561
+ }
3562
+
3563
+ // src/harnesses/long-horizon-mea.ts
3564
+ function createLongHorizonHarnessOptions(cwd, subagentsExtension) {
3565
+ return {
3566
+ capabilities: [createLongHorizonCapability({ cwd, subagentsExtension })]
3567
+ };
3568
+ }
3182
3569
  async function runLongHorizonHarness(args) {
3183
3570
  const cwd = path12.resolve(process.cwd());
3184
- exposeBundledSubagentAgents();
3185
- await main5(buildLongHorizonArgs(args, cwd), {
3186
- extensionFactories: [createLongHorizonSupervisorExtension()]
3187
- });
3571
+ await runComposedHarness(args, createLongHorizonHarnessOptions(cwd));
3188
3572
  }
3189
3573
 
3190
3574
  // src/harnesses/pi.ts
3191
- import { main as main6 } from "@earendil-works/pi-coding-agent";
3575
+ function buildPiArgs(args) {
3576
+ return isolateHarnessArgs(args, void 0, {
3577
+ isolatedResources: NATIVE_PI_ISOLATED_RESOURCES
3578
+ });
3579
+ }
3192
3580
  async function runPiHarness(args) {
3193
- await main6([...args]);
3581
+ await runHarnessMain(buildPiArgs(args));
3582
+ }
3583
+
3584
+ // src/capabilities/tools/programmatic-tool-calling/index.ts
3585
+ import { spawn as spawn2 } from "node:child_process";
3586
+ import path13 from "node:path";
3587
+ import readline from "node:readline";
3588
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
3589
+ import {
3590
+ createBashToolDefinition,
3591
+ createEditToolDefinition as createEditToolDefinition2,
3592
+ createReadToolDefinition as createReadToolDefinition2,
3593
+ createWriteToolDefinition as createWriteToolDefinition3,
3594
+ defineTool as defineTool22,
3595
+ getAgentDir as getAgentDir2,
3596
+ SettingsManager as SettingsManager2
3597
+ } from "@earendil-works/pi-coding-agent";
3598
+ import { Type as Type22 } from "typebox";
3599
+ import { Value } from "typebox/value";
3600
+ var RUN_CODE_TOOL_NAME = "run_code";
3601
+ var DEFAULT_TIMEOUT_MS = 12e4;
3602
+ var MAX_TIMEOUT_MS = 6e5;
3603
+ var DEFAULT_MAX_OUTPUT_CHARS = 5e4;
3604
+ var MAX_OUTPUT_CHARS = 2e5;
3605
+ var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
3606
+ var TRUNCATION_MARKER = "\n... run_code output truncated ...\n";
3607
+ var RUN_CODE_CHILD_PATH = fileURLToPath3(new URL("./child-runtime.js", import.meta.url));
3608
+ function normalizedToolName(name) {
3609
+ let normalized = name.replace(/[^A-Za-z0-9_$]/gu, "_");
3610
+ if (!/^[A-Za-z_$]/u.test(normalized)) normalized = `_${normalized}`;
3611
+ return normalized || "_";
3612
+ }
3613
+ function assertNestedTools(tools) {
3614
+ const names = /* @__PURE__ */ new Set();
3615
+ for (const tool of tools) {
3616
+ if (tool.name === RUN_CODE_TOOL_NAME) {
3617
+ throw new Error(`${RUN_CODE_TOOL_NAME} cannot be nested inside itself.`);
3618
+ }
3619
+ const name = normalizedToolName(tool.name);
3620
+ if (names.has(name)) {
3621
+ throw new Error(`Nested tool names collide after JavaScript normalization: ${name}`);
3622
+ }
3623
+ names.add(name);
3624
+ }
3625
+ }
3626
+ function literal(value) {
3627
+ return JSON.stringify(value) ?? "unknown";
3628
+ }
3629
+ function renderSchemaType(schema18, depth = 0) {
3630
+ if (!schema18 || depth > 8) return "unknown";
3631
+ const value = schema18;
3632
+ if ("const" in value) return literal(value.const);
3633
+ if (Array.isArray(value.enum)) return value.enum.map(literal).join(" | ") || "unknown";
3634
+ const alternatives = Array.isArray(value.anyOf) ? value.anyOf : Array.isArray(value.oneOf) ? value.oneOf : void 0;
3635
+ if (alternatives) {
3636
+ return alternatives.map((item) => renderSchemaType(item, depth + 1)).join(" | ");
3637
+ }
3638
+ if (Array.isArray(value.type)) {
3639
+ return value.type.map((type) => renderSchemaType({ ...value, type }, depth + 1)).join(" | ");
3640
+ }
3641
+ switch (value.type) {
3642
+ case "string":
3643
+ return "string";
3644
+ case "number":
3645
+ case "integer":
3646
+ return "number";
3647
+ case "boolean":
3648
+ return "boolean";
3649
+ case "null":
3650
+ return "null";
3651
+ case "array":
3652
+ return `${renderSchemaType(value.items, depth + 1)}[]`;
3653
+ case "object": {
3654
+ const properties = value.properties && typeof value.properties === "object" ? value.properties : {};
3655
+ const required = new Set(Array.isArray(value.required) ? value.required : []);
3656
+ const fields = Object.entries(properties).map(([name, property]) => {
3657
+ const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(name) ? name : JSON.stringify(name);
3658
+ return `${key}${required.has(name) ? "" : "?"}: ${renderSchemaType(property, depth + 1)}`;
3659
+ });
3660
+ return fields.length ? `{ ${fields.join("; ")} }` : "Record<string, unknown>";
3661
+ }
3662
+ default:
3663
+ return "unknown";
3664
+ }
3665
+ }
3666
+ function nestedToolDescription(tool) {
3667
+ const name = normalizedToolName(tool.name);
3668
+ return [
3669
+ `### \`${name}\`${name === tool.name ? "" : ` (tool name: \`${tool.name}\`)`}`,
3670
+ tool.description.trim(),
3671
+ "",
3672
+ "```ts",
3673
+ `tools.${name}(args: ${renderSchemaType(tool.parameters)}): Promise<string | NestedToolResult>;`,
3674
+ "```"
3675
+ ].join("\n");
3676
+ }
3677
+ function runCodeDescription(tools) {
3678
+ return [
3679
+ "Run JavaScript to orchestrate and compose nested Pi tool calls.",
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
+ "All nested tools are async functions on the global `tools` object. Always await calls whose result or completion matters.",
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.",
3684
+ "`ALL_TOOLS` contains `{ name, description }` metadata. Unawaited work is discarded when the script completes.",
3685
+ "The `code` argument must be raw JavaScript source without Markdown fences.",
3686
+ "",
3687
+ "Available globals:",
3688
+ "```ts",
3689
+ "declare const tools: Record<string, (args: unknown) => Promise<string | NestedToolResult>>;",
3690
+ "declare const ALL_TOOLS: ReadonlyArray<{ name: string; description: string }>;",
3691
+ "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 }> };',
3694
+ "```",
3695
+ "",
3696
+ ...tools.map(nestedToolDescription)
3697
+ ].join("\n");
3698
+ }
3699
+ var runCodeSchema = Type22.Object({
3700
+ code: Type22.String({
3701
+ minLength: 1,
3702
+ maxLength: 128e3,
3703
+ description: "Raw JavaScript source to evaluate. Do not wrap it in Markdown fences."
3704
+ }),
3705
+ timeout_ms: Type22.Optional(Type22.Integer({
3706
+ minimum: 100,
3707
+ maximum: MAX_TIMEOUT_MS,
3708
+ default: DEFAULT_TIMEOUT_MS,
3709
+ description: "Wall-clock limit for the complete script, including nested tool calls."
3710
+ })),
3711
+ max_output_chars: Type22.Optional(Type22.Integer({
3712
+ minimum: 100,
3713
+ maximum: MAX_OUTPUT_CHARS,
3714
+ default: DEFAULT_MAX_OUTPUT_CHARS,
3715
+ description: "Maximum combined text characters returned to the model."
3716
+ }))
3717
+ }, { additionalProperties: false });
3718
+ function configuredPiTools(cwd) {
3719
+ const settings = SettingsManager2.create(cwd, getAgentDir2(), { projectTrusted: false });
3720
+ return [
3721
+ createReadToolDefinition2(cwd, { autoResizeImages: settings.getImageAutoResize() }),
3722
+ createBashToolDefinition(cwd, {
3723
+ commandPrefix: settings.getShellCommandPrefix(),
3724
+ shellPath: settings.getShellPath()
3725
+ }),
3726
+ createEditToolDefinition2(cwd),
3727
+ createWriteToolDefinition3(cwd)
3728
+ ];
3729
+ }
3730
+ function createPiNestedTools(cwd = process.cwd()) {
3731
+ return configuredPiTools(path13.resolve(cwd));
3732
+ }
3733
+ function validationError(tool, args) {
3734
+ const errors = Value.Errors(tool.parameters, args).slice(0, 8).map((error) => `${error.instancePath || "/"}: ${error.message}`).join("\n");
3735
+ return new Error(
3736
+ `Invalid arguments for nested tool ${tool.name}:
3737
+ ${errors || "schema mismatch"}`
3738
+ );
3739
+ }
3740
+ function validatedArguments(tool, input) {
3741
+ const cloned = structuredClone(input);
3742
+ const prepared = tool.prepareArguments ? tool.prepareArguments(cloned) : cloned;
3743
+ const converted = Value.Convert(tool.parameters, structuredClone(prepared));
3744
+ if (!Value.Check(tool.parameters, converted)) throw validationError(tool, converted);
3745
+ return converted;
3746
+ }
3747
+ function nestedResultValue(result) {
3748
+ const content = result.content.map((item) => item.type === "text" ? { type: "text", text: item.text } : { type: "image", data: item.data, mimeType: item.mimeType });
3749
+ if (content.every((item) => item.type === "text")) {
3750
+ return content.map((item) => item.text).join("\n");
3751
+ }
3752
+ return { content };
3753
+ }
3754
+ function cappedText(text, remaining) {
3755
+ if (text.length <= remaining) return { text, used: text.length };
3756
+ if (remaining <= TRUNCATION_MARKER.length) {
3757
+ return { text: TRUNCATION_MARKER.slice(0, remaining), used: remaining };
3758
+ }
3759
+ const available = remaining - TRUNCATION_MARKER.length;
3760
+ const head = Math.ceil(available / 2);
3761
+ const tail = Math.floor(available / 2);
3762
+ return {
3763
+ text: text.slice(0, head) + TRUNCATION_MARKER + (tail ? text.slice(-tail) : ""),
3764
+ used: remaining
3765
+ };
3766
+ }
3767
+ function emittedContent(value, maxOutputChars) {
3768
+ if (!Array.isArray(value)) throw new Error("run_code child returned invalid content");
3769
+ const content = [];
3770
+ let remaining = maxOutputChars;
3771
+ for (const item of value) {
3772
+ if (!item || typeof item !== "object") continue;
3773
+ const candidate = item;
3774
+ if (candidate.type === "text" && typeof candidate.text === "string") {
3775
+ if (remaining <= 0) continue;
3776
+ const capped = cappedText(candidate.text, remaining);
3777
+ content.push({ type: "text", text: capped.text });
3778
+ remaining -= capped.used;
3779
+ continue;
3780
+ }
3781
+ if (candidate.type === "image" && typeof candidate.data === "string" && typeof candidate.mimeType === "string") {
3782
+ if (Buffer.byteLength(candidate.data, "base64") > MAX_IMAGE_BYTES) {
3783
+ throw new Error("run_code image output exceeds the 20 MiB limit");
3784
+ }
3785
+ content.push({
3786
+ type: "image",
3787
+ data: candidate.data,
3788
+ mimeType: candidate.mimeType
3789
+ });
3790
+ }
3791
+ }
3792
+ return content.length ? content : [{ type: "text", text: "Code completed without emitted output." }];
3793
+ }
3794
+ async function executeRunCode(toolCallId, params, signal, context, tools) {
3795
+ assertNestedTools(tools);
3796
+ const toolsByName = new Map(tools.map((tool) => [normalizedToolName(tool.name), tool]));
3797
+ const timeoutMs = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
3798
+ const maxOutputChars = params.max_output_chars ?? DEFAULT_MAX_OUTPUT_CHARS;
3799
+ const controller = new AbortController();
3800
+ const calls = [];
3801
+ let settled = false;
3802
+ let stderr = "";
3803
+ const child = spawn2(process.execPath, [
3804
+ "--permission",
3805
+ "--no-warnings",
3806
+ "--disable-proto=throw",
3807
+ "--max-old-space-size=96",
3808
+ RUN_CODE_CHILD_PATH
3809
+ ], {
3810
+ cwd: context.cwd,
3811
+ env: {},
3812
+ stdio: ["pipe", "pipe", "pipe"]
3813
+ });
3814
+ const lines = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
3815
+ const post = (message) => {
3816
+ if (!settled && child.stdin.writable) child.stdin.write(`${JSON.stringify(message)}
3817
+ `);
3818
+ };
3819
+ const onAbort = () => controller.abort(signal?.reason);
3820
+ if (signal?.aborted) onAbort();
3821
+ else signal?.addEventListener("abort", onAbort, { once: true });
3822
+ try {
3823
+ return await new Promise((resolve, reject) => {
3824
+ const finish = (outcome) => {
3825
+ if (settled) return;
3826
+ settled = true;
3827
+ if (outcome.error) {
3828
+ reject(new Error(outcome.error));
3829
+ return;
3830
+ }
3831
+ try {
3832
+ resolve({
3833
+ content: emittedContent(outcome.content, maxOutputChars),
3834
+ details: { calls }
3835
+ });
3836
+ } catch (error) {
3837
+ reject(error);
3838
+ }
3839
+ };
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();
3846
+ const rejectAborted = () => {
3847
+ child.kill();
3848
+ finish({ error: "Operation aborted" });
3849
+ };
3850
+ controller.signal.addEventListener("abort", rejectAborted, { once: true });
3851
+ if (controller.signal.aborted) rejectAborted();
3852
+ child.stderr.setEncoding("utf8");
3853
+ child.stderr.on("data", (chunk) => {
3854
+ stderr = (stderr + chunk).slice(-8e3);
3855
+ });
3856
+ child.on("error", (error) => finish({ error: `Failed to start run_code: ${error.message}` }));
3857
+ child.on("exit", (code, exitSignal) => {
3858
+ clearTimeout(timer);
3859
+ if (settled) return;
3860
+ const detail = stderr.trim() ? `: ${stderr.trim()}` : "";
3861
+ finish({
3862
+ error: `run_code child exited before returning a result (code ${String(code)}, signal ${String(exitSignal)})${detail}`
3863
+ });
3864
+ });
3865
+ lines.on("line", (line) => {
3866
+ let message;
3867
+ try {
3868
+ message = JSON.parse(line);
3869
+ } catch {
3870
+ finish({ error: "run_code child emitted an invalid protocol message" });
3871
+ return;
3872
+ }
3873
+ if (message.type === "done") {
3874
+ clearTimeout(timer);
3875
+ finish(message);
3876
+ return;
3877
+ }
3878
+ if (message.type !== "tool_call") return;
3879
+ const startedAt = Date.now();
3880
+ const tool = toolsByName.get(message.name);
3881
+ if (!tool) {
3882
+ calls.push({ name: message.name, durationMs: 0, status: "error" });
3883
+ post({ type: "tool_error", id: message.id, error: `Unknown nested tool: ${message.name}` });
3884
+ return;
3885
+ }
3886
+ void (async () => {
3887
+ try {
3888
+ const args = validatedArguments(tool, message.args);
3889
+ const result = await tool.execute(
3890
+ `${toolCallId}:${message.id}`,
3891
+ args,
3892
+ controller.signal,
3893
+ void 0,
3894
+ context
3895
+ );
3896
+ calls.push({ name: tool.name, durationMs: Date.now() - startedAt, status: "success" });
3897
+ post({ type: "tool_result", id: message.id, value: nestedResultValue(result) });
3898
+ } catch (error) {
3899
+ calls.push({ name: tool.name, durationMs: Date.now() - startedAt, status: "error" });
3900
+ post({
3901
+ type: "tool_error",
3902
+ id: message.id,
3903
+ error: error instanceof Error ? error.message : String(error)
3904
+ });
3905
+ }
3906
+ })();
3907
+ });
3908
+ post({
3909
+ type: "init",
3910
+ code: params.code,
3911
+ syncTimeoutMs: timeoutMs,
3912
+ tools: tools.map((tool) => ({
3913
+ name: normalizedToolName(tool.name),
3914
+ description: tool.description
3915
+ }))
3916
+ });
3917
+ });
3918
+ } finally {
3919
+ signal?.removeEventListener("abort", onAbort);
3920
+ controller.abort();
3921
+ lines.close();
3922
+ child.stdin.destroy();
3923
+ if (child.exitCode === null && child.signalCode === null) child.kill();
3924
+ }
3925
+ }
3926
+ function createRunCodeTool(options) {
3927
+ assertNestedTools(options.nestedTools);
3928
+ return defineTool22({
3929
+ name: RUN_CODE_TOOL_NAME,
3930
+ label: "Run Code",
3931
+ description: runCodeDescription(options.nestedTools),
3932
+ promptSnippet: "Orchestrate all Pi tools through JavaScript",
3933
+ promptGuidelines: [
3934
+ "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()."
3936
+ ],
3937
+ parameters: runCodeSchema,
3938
+ executionMode: "sequential",
3939
+ async execute(toolCallId, params, signal, _onUpdate, context) {
3940
+ const tools = options.resolveNestedTools?.(context) ?? options.nestedTools;
3941
+ return executeRunCode(toolCallId, params, signal, context, tools);
3942
+ }
3943
+ });
3944
+ }
3945
+ function createProgrammaticToolCallingExtension(cwd = process.cwd(), options = {}) {
3946
+ const metadataTools = options.nestedTools ?? createPiNestedTools(cwd);
3947
+ const cache = /* @__PURE__ */ new Map();
3948
+ const resolveNestedTools = options.resolveNestedTools ?? (options.nestedTools ? () => metadataTools : (context) => {
3949
+ const resolvedCwd = path13.resolve(context.cwd);
3950
+ const cached = cache.get(resolvedCwd);
3951
+ if (cached) return cached;
3952
+ const tools = createPiNestedTools(resolvedCwd);
3953
+ cache.set(resolvedCwd, tools);
3954
+ return tools;
3955
+ });
3956
+ return {
3957
+ name: "programmatic-tool-calling",
3958
+ factory(pi) {
3959
+ pi.registerTool(createRunCodeTool({
3960
+ nestedTools: metadataTools,
3961
+ resolveNestedTools
3962
+ }));
3963
+ }
3964
+ };
3965
+ }
3966
+ function createProgrammaticToolCallingCapability(cwd = process.cwd(), options = {}) {
3967
+ return {
3968
+ name: "programmatic-tool-calling",
3969
+ tools: [RUN_CODE_TOOL_NAME],
3970
+ extensionFactories: [createProgrammaticToolCallingExtension(cwd, options)]
3971
+ };
3972
+ }
3973
+ var createCodeModeCapability = createProgrammaticToolCallingCapability;
3974
+
3975
+ // src/harnesses/pi-ptc.ts
3976
+ async function runPiPtcHarness(args) {
3977
+ const cwd = process.cwd();
3978
+ await runComposedHarness(args, {
3979
+ capabilities: [createCodeModeCapability(cwd)]
3980
+ });
3981
+ }
3982
+
3983
+ // src/capabilities/tools/filesystem/apply_patch.ts
3984
+ import {
3985
+ defineTool as defineTool23
3986
+ } from "@earendil-works/pi-coding-agent";
3987
+ import { Type as Type23 } from "typebox";
3988
+
3989
+ // src/utils/filesystem/apply_patch.ts
3990
+ import { mkdir as mkdir7, readFile as readFile7, stat, unlink, writeFile as writeFile5 } from "node:fs/promises";
3991
+ import path14 from "node:path";
3992
+ var BEGIN_PATCH_MARKER = "*** Begin Patch";
3993
+ var END_PATCH_MARKER = "*** End Patch";
3994
+ var ADD_FILE_MARKER = "*** Add File: ";
3995
+ var DELETE_FILE_MARKER = "*** Delete File: ";
3996
+ var UPDATE_FILE_MARKER = "*** Update File: ";
3997
+ var MOVE_TO_MARKER = "*** Move to: ";
3998
+ var END_OF_FILE_MARKER = "*** End of File";
3999
+ function patchError(message) {
4000
+ return new Error(`Invalid patch: ${message}`);
4001
+ }
4002
+ function hunkError(lineNumber, message) {
4003
+ return new Error(`Invalid patch hunk on line ${lineNumber}: ${message}`);
4004
+ }
4005
+ function parsePatchLines(patch) {
4006
+ const trimmed = patch.trim();
4007
+ const lines = trimmed ? trimmed.split("\n") : [];
4008
+ return lines.map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
4009
+ }
4010
+ function parsePath(header, marker, lineNumber) {
4011
+ const value = header.slice(marker.length);
4012
+ if (!value) throw hunkError(lineNumber, `Missing path after '${marker.trimEnd()}'`);
4013
+ return value;
4014
+ }
4015
+ function newChunk(changeContext) {
4016
+ return {
4017
+ ...changeContext === void 0 ? {} : { changeContext },
4018
+ oldLines: [],
4019
+ newLines: [],
4020
+ contextLineIndices: [],
4021
+ isEndOfFile: false
4022
+ };
4023
+ }
4024
+ function chunkIsEmpty(chunk) {
4025
+ return chunk.oldLines.length === 0 && chunk.newLines.length === 0;
4026
+ }
4027
+ function pushContextLine(chunk, line) {
4028
+ chunk.contextLineIndices.push([chunk.oldLines.length, chunk.newLines.length]);
4029
+ chunk.oldLines.push(line);
4030
+ chunk.newLines.push(line);
4031
+ }
4032
+ function isHunkHeader(line) {
4033
+ return line.startsWith(ADD_FILE_MARKER) || line.startsWith(DELETE_FILE_MARKER) || line.startsWith(UPDATE_FILE_MARKER);
4034
+ }
4035
+ function parseApplyPatch(patch) {
4036
+ const lines = parsePatchLines(patch);
4037
+ const first = lines[0]?.trim();
4038
+ const last = lines.at(-1)?.trim();
4039
+ if (first !== BEGIN_PATCH_MARKER) {
4040
+ throw patchError(`The first line of the patch must be '${BEGIN_PATCH_MARKER}'`);
4041
+ }
4042
+ if (last !== END_PATCH_MARKER) {
4043
+ throw patchError(`The last line of the patch must be '${END_PATCH_MARKER}'`);
4044
+ }
4045
+ const hunks = [];
4046
+ let index = 1;
4047
+ const endIndex = lines.length - 1;
4048
+ while (index < endIndex) {
4049
+ const rawHeader = lines[index] ?? "";
4050
+ const header = rawHeader.trim();
4051
+ const lineNumber = index + 1;
4052
+ if (header.startsWith(ADD_FILE_MARKER)) {
4053
+ const filePath = parsePath(header, ADD_FILE_MARKER, lineNumber);
4054
+ index += 1;
4055
+ const content = [];
4056
+ while (index < endIndex) {
4057
+ const line = lines[index] ?? "";
4058
+ if (isHunkHeader(line.trim())) break;
4059
+ if (!line.startsWith("+")) {
4060
+ throw hunkError(
4061
+ index + 1,
4062
+ `Invalid Add File line for '${filePath}': '${line}'. Every added line must start with '+'`
4063
+ );
4064
+ }
4065
+ content.push(line.slice(1));
4066
+ index += 1;
4067
+ }
4068
+ if (content.length === 0) {
4069
+ throw hunkError(lineNumber, `Add file hunk for path '${filePath}' is empty`);
4070
+ }
4071
+ hunks.push({ type: "add", path: filePath, contents: `${content.join("\n")}
4072
+ ` });
4073
+ continue;
4074
+ }
4075
+ if (header.startsWith(DELETE_FILE_MARKER)) {
4076
+ hunks.push({
4077
+ type: "delete",
4078
+ path: parsePath(header, DELETE_FILE_MARKER, lineNumber)
4079
+ });
4080
+ index += 1;
4081
+ continue;
4082
+ }
4083
+ if (header.startsWith(UPDATE_FILE_MARKER)) {
4084
+ const filePath = parsePath(header, UPDATE_FILE_MARKER, lineNumber);
4085
+ index += 1;
4086
+ let movePath;
4087
+ const possibleMove = lines[index]?.trim();
4088
+ if (possibleMove?.startsWith(MOVE_TO_MARKER)) {
4089
+ movePath = parsePath(possibleMove, MOVE_TO_MARKER, index + 1);
4090
+ index += 1;
4091
+ }
4092
+ const chunks = [];
4093
+ let active;
4094
+ while (index < endIndex) {
4095
+ const line = lines[index] ?? "";
4096
+ const updateLine = line.trimEnd();
4097
+ if (isHunkHeader(updateLine)) break;
4098
+ const currentLineNumber = index + 1;
4099
+ if (active?.isEndOfFile) {
4100
+ if (!updateLine) {
4101
+ index += 1;
4102
+ continue;
4103
+ }
4104
+ if (updateLine !== "@@" && !updateLine.startsWith("@@ ")) {
4105
+ throw hunkError(
4106
+ currentLineNumber,
4107
+ `Expected update hunk to start with a @@ context marker, got: '${line}'`
4108
+ );
4109
+ }
4110
+ }
4111
+ if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
4112
+ if (active && chunkIsEmpty(active)) {
4113
+ throw hunkError(currentLineNumber, "Update hunk does not contain any lines");
4114
+ }
4115
+ active = newChunk(updateLine === "@@" ? void 0 : updateLine.slice(3));
4116
+ chunks.push(active);
4117
+ index += 1;
4118
+ continue;
4119
+ }
4120
+ if (updateLine === END_OF_FILE_MARKER) {
4121
+ if (!active || chunkIsEmpty(active)) {
4122
+ throw hunkError(currentLineNumber, "Update hunk does not contain any lines");
4123
+ }
4124
+ active.isEndOfFile = true;
4125
+ index += 1;
4126
+ continue;
4127
+ }
4128
+ active ??= newChunk();
4129
+ if (!chunks.includes(active)) chunks.push(active);
4130
+ if (line === "") {
4131
+ pushContextLine(active, "");
4132
+ } else if (line.startsWith(" ")) {
4133
+ pushContextLine(active, line.slice(1));
4134
+ } else if (line.startsWith("+")) {
4135
+ active.newLines.push(line.slice(1));
4136
+ } else if (line.startsWith("-")) {
4137
+ active.oldLines.push(line.slice(1));
4138
+ } else {
4139
+ throw hunkError(
4140
+ currentLineNumber,
4141
+ `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`
4142
+ );
4143
+ }
4144
+ index += 1;
4145
+ }
4146
+ if (active && chunkIsEmpty(active)) {
4147
+ throw hunkError(lineNumber, `Update file hunk for path '${filePath}' is empty`);
4148
+ }
4149
+ if (chunks.length === 0 && movePath === void 0) {
4150
+ throw hunkError(lineNumber, `Update file hunk for path '${filePath}' is empty`);
4151
+ }
4152
+ hunks.push({
4153
+ type: "update",
4154
+ path: filePath,
4155
+ ...movePath === void 0 ? {} : { movePath },
4156
+ chunks
4157
+ });
4158
+ continue;
4159
+ }
4160
+ throw hunkError(
4161
+ lineNumber,
4162
+ `'${rawHeader}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`
4163
+ );
4164
+ }
4165
+ return hunks;
4166
+ }
4167
+ function parseSourceFile(contents) {
4168
+ const lines = [];
4169
+ let preferredEnding;
4170
+ let lineStart = 0;
4171
+ let cursor = 0;
4172
+ while (cursor < contents.length) {
4173
+ let ending;
4174
+ let endingLength = 0;
4175
+ if (contents[cursor] === "\r" && contents[cursor + 1] === "\n") {
4176
+ ending = "\r\n";
4177
+ endingLength = 2;
4178
+ } else if (contents[cursor] === "\r") {
4179
+ ending = "\r";
4180
+ endingLength = 1;
4181
+ } else if (contents[cursor] === "\n") {
4182
+ ending = "\n";
4183
+ endingLength = 1;
4184
+ } else {
4185
+ cursor += 1;
4186
+ continue;
4187
+ }
4188
+ preferredEnding ??= ending;
4189
+ lines.push({ text: contents.slice(lineStart, cursor), ending });
4190
+ cursor += endingLength;
4191
+ lineStart = cursor;
4192
+ }
4193
+ if (lineStart < contents.length) lines.push({ text: contents.slice(lineStart) });
4194
+ return { lines, preferredEnding: preferredEnding ?? "\n" };
4195
+ }
4196
+ function normalizedPunctuation(value) {
4197
+ const replacements = {
4198
+ "\u2010": "-",
4199
+ "\u2011": "-",
4200
+ "\u2012": "-",
4201
+ "\u2013": "-",
4202
+ "\u2014": "-",
4203
+ "\u2015": "-",
4204
+ "\u2212": "-",
4205
+ "\u2018": "'",
4206
+ "\u2019": "'",
4207
+ "\u201A": "'",
4208
+ "\u201B": "'",
4209
+ "\u201C": '"',
4210
+ "\u201D": '"',
4211
+ "\u201E": '"',
4212
+ "\u201F": '"',
4213
+ "\xA0": " ",
4214
+ "\u2002": " ",
4215
+ "\u2003": " ",
4216
+ "\u2004": " ",
4217
+ "\u2005": " ",
4218
+ "\u2006": " ",
4219
+ "\u2007": " ",
4220
+ "\u2008": " ",
4221
+ "\u2009": " ",
4222
+ "\u200A": " ",
4223
+ "\u202F": " ",
4224
+ "\u205F": " ",
4225
+ "\u3000": " "
4226
+ };
4227
+ return [...value.trim()].map((character) => replacements[character] ?? character).join("");
4228
+ }
4229
+ function seekSequence(lines, pattern, start, endOfFile) {
4230
+ if (pattern.length === 0) return start;
4231
+ if (pattern.length > lines.length) return void 0;
4232
+ const lastStart = lines.length - pattern.length;
4233
+ const searchStart = endOfFile ? Math.max(start, lastStart) : start;
4234
+ if (searchStart > lastStart) return void 0;
4235
+ const matchers = [
4236
+ (left, right) => left === right,
4237
+ (left, right) => left.trimEnd() === right.trimEnd(),
4238
+ (left, right) => left.trim() === right.trim(),
4239
+ (left, right) => normalizedPunctuation(left) === normalizedPunctuation(right)
4240
+ ];
4241
+ for (const matches of matchers) {
4242
+ for (let index = searchStart; index <= lastStart; index += 1) {
4243
+ if (pattern.every((line, offset) => matches(lines[index + offset] ?? "", line))) {
4244
+ return index;
4245
+ }
4246
+ }
4247
+ }
4248
+ return void 0;
4249
+ }
4250
+ function computeReplacements(sourceLines, target, chunks) {
4251
+ const replacements = [];
4252
+ let lineIndex = 0;
4253
+ for (const chunk of chunks) {
4254
+ if (chunk.changeContext !== void 0) {
4255
+ const contextIndex = seekSequence(sourceLines, [chunk.changeContext], lineIndex, false);
4256
+ if (contextIndex === void 0) {
4257
+ throw new Error(`Failed to find context '${chunk.changeContext}' in ${target}`);
4258
+ }
4259
+ lineIndex = contextIndex + 1;
4260
+ }
4261
+ if (chunk.oldLines.length === 0) {
4262
+ replacements.push({
4263
+ start: sourceLines.length,
4264
+ oldLength: 0,
4265
+ newLines: [...chunk.newLines]
4266
+ });
4267
+ continue;
4268
+ }
4269
+ let pattern = chunk.oldLines;
4270
+ let newLines = chunk.newLines;
4271
+ let found = seekSequence(sourceLines, pattern, lineIndex, chunk.isEndOfFile);
4272
+ if (found === void 0 && pattern.at(-1) === "") {
4273
+ pattern = pattern.slice(0, -1);
4274
+ if (newLines.at(-1) === "") newLines = newLines.slice(0, -1);
4275
+ found = seekSequence(sourceLines, pattern, lineIndex, chunk.isEndOfFile);
4276
+ }
4277
+ if (found === void 0) {
4278
+ throw new Error(
4279
+ `Failed to find expected lines in ${target}:
4280
+ ${chunk.oldLines.join("\n")}`
4281
+ );
4282
+ }
4283
+ let oldStart = 0;
4284
+ let newStart = 0;
4285
+ for (const [oldContext, newContext] of chunk.contextLineIndices) {
4286
+ if (oldContext >= pattern.length || newContext >= newLines.length) break;
4287
+ if (oldStart !== oldContext || newStart !== newContext) {
4288
+ replacements.push({
4289
+ start: found + oldStart,
4290
+ oldLength: oldContext - oldStart,
4291
+ newLines: newLines.slice(newStart, newContext)
4292
+ });
4293
+ }
4294
+ oldStart = oldContext + 1;
4295
+ newStart = newContext + 1;
4296
+ }
4297
+ if (oldStart !== pattern.length || newStart !== newLines.length) {
4298
+ replacements.push({
4299
+ start: found + oldStart,
4300
+ oldLength: pattern.length - oldStart,
4301
+ newLines: newLines.slice(newStart)
4302
+ });
4303
+ }
4304
+ lineIndex = found + pattern.length;
4305
+ }
4306
+ return replacements;
4307
+ }
4308
+ function applyUpdate(contents, target, chunks) {
4309
+ const source = parseSourceFile(contents);
4310
+ const texts = source.lines.map((line) => line.text);
4311
+ const replacements = computeReplacements(texts, target, chunks);
4312
+ const ordered = replacements.map((replacement, order) => ({ replacement, order })).sort(
4313
+ (left, right) => right.replacement.start - left.replacement.start || right.order - left.order
4314
+ );
4315
+ for (const { replacement } of ordered) {
4316
+ source.lines.splice(
4317
+ replacement.start,
4318
+ replacement.oldLength,
4319
+ ...replacement.newLines.map((text) => ({ text, ending: source.preferredEnding }))
4320
+ );
4321
+ }
4322
+ for (const line of source.lines) line.ending ??= source.preferredEnding;
4323
+ return source.lines.map((line) => line.text + (line.ending ?? "")).join("");
4324
+ }
4325
+ async function requireRegularFile(target, operation) {
4326
+ try {
4327
+ const info = await stat(target);
4328
+ if (!info.isFile()) throw new Error(`${operation} ${target}: path is not a regular file`);
4329
+ } catch (error) {
4330
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
4331
+ throw new Error(`${operation} ${target}: file does not exist`);
4332
+ }
4333
+ throw error;
4334
+ }
4335
+ }
4336
+ function throwIfAborted(signal) {
4337
+ if (signal?.aborted) throw signal.reason ?? new Error("Operation aborted");
4338
+ }
4339
+ async function writeWithParents(target, contents, signal) {
4340
+ throwIfAborted(signal);
4341
+ await mkdir7(path14.dirname(target), { recursive: true });
4342
+ await writeFile5(target, contents, { encoding: "utf8", signal });
4343
+ }
4344
+ function formatApplyPatchSummary(paths) {
4345
+ const rows = [
4346
+ ...paths.added.map((filePath) => `A ${filePath}`),
4347
+ ...paths.modified.map((filePath) => `M ${filePath}`),
4348
+ ...paths.deleted.map((filePath) => `D ${filePath}`)
4349
+ ];
4350
+ return `Success. Updated the following files:
4351
+ ${rows.join("\n")}
4352
+ `;
4353
+ }
4354
+ async function applyPatch(cwd, patch, signal) {
4355
+ const hunks = parseApplyPatch(patch);
4356
+ if (hunks.length === 0) throw new Error("No files were modified.");
4357
+ const affected = { added: [], modified: [], deleted: [] };
4358
+ for (const hunk of hunks) {
4359
+ throwIfAborted(signal);
4360
+ if (hunk.type === "add") {
4361
+ const target2 = await resolveWorkspacePath(cwd, hunk.path);
4362
+ await writeWithParents(target2, hunk.contents, signal);
4363
+ affected.added.push(hunk.path);
4364
+ continue;
4365
+ }
4366
+ if (hunk.type === "delete") {
4367
+ const target2 = await resolveWorkspacePath(cwd, hunk.path);
4368
+ await requireRegularFile(target2, "Failed to delete file");
4369
+ await unlink(target2);
4370
+ affected.deleted.push(hunk.path);
4371
+ continue;
4372
+ }
4373
+ const target = await resolveWorkspacePath(cwd, hunk.path);
4374
+ await requireRegularFile(target, "Failed to read file to update");
4375
+ const before = await readFile7(target, { encoding: "utf8", signal });
4376
+ const after = applyUpdate(before, target, hunk.chunks);
4377
+ if (hunk.movePath === void 0) {
4378
+ await writeFile5(target, after, { encoding: "utf8", signal });
4379
+ affected.modified.push(hunk.path);
4380
+ continue;
4381
+ }
4382
+ const destination = await resolveWorkspacePath(cwd, hunk.movePath);
4383
+ if (destination === target) {
4384
+ await writeFile5(target, after, { encoding: "utf8", signal });
4385
+ } else {
4386
+ await writeWithParents(destination, after, signal);
4387
+ await unlink(target);
4388
+ }
4389
+ affected.modified.push(hunk.movePath);
4390
+ }
4391
+ return { ...affected, summary: formatApplyPatchSummary(affected) };
4392
+ }
4393
+
4394
+ // src/capabilities/tools/filesystem/apply_patch.ts
4395
+ var APPLY_PATCH_TOOL_NAME = "apply_patch";
4396
+ var DESCRIPTION = [
4397
+ "Apply one Codex-style patch to workspace files.",
4398
+ "The patch must start with '*** Begin Patch' and end with '*** End Patch'.",
4399
+ "Use '*** Add File: path', '*** Update File: path', or '*** Delete File: path' hunks.",
4400
+ "Update hunks use @@ sections with lines prefixed by space (context), - (remove), or + (add), and may include '*** Move to: path'.",
4401
+ "Paths may be relative to the workspace root or absolute paths inside it."
4402
+ ].join(" ");
4403
+ var schema16 = Type23.Object({
4404
+ patch: Type23.String({
4405
+ minLength: 1,
4406
+ description: "Complete Codex patch text from *** Begin Patch through *** End Patch."
4407
+ })
4408
+ }, { additionalProperties: false });
4409
+ function createApplyPatchTool(cwd) {
4410
+ return defineTool23({
4411
+ name: APPLY_PATCH_TOOL_NAME,
4412
+ label: "Apply Patch",
4413
+ description: DESCRIPTION,
4414
+ promptSnippet: "Edit workspace files with Codex-style patches",
4415
+ promptGuidelines: [
4416
+ "Use apply_patch for deliberate text-file additions, updates, deletions, and moves.",
4417
+ "Send the complete patch in the patch field; do not wrap it in a shell command or heredoc."
4418
+ ],
4419
+ parameters: schema16,
4420
+ executionMode: "sequential",
4421
+ async execute(_toolCallId, params, signal) {
4422
+ const result = await applyPatch(cwd, params.patch, signal);
4423
+ return {
4424
+ content: [{ type: "text", text: result.summary }],
4425
+ details: result
4426
+ };
4427
+ }
4428
+ });
4429
+ }
4430
+ function createApplyPatchExtension(cwd) {
4431
+ return {
4432
+ name: "apply-patch",
4433
+ factory(pi) {
4434
+ pi.registerTool(createApplyPatchTool(cwd));
4435
+ }
4436
+ };
4437
+ }
4438
+
4439
+ // src/capabilities/tools/filesystem/glob.ts
4440
+ import {
4441
+ createFindToolDefinition as createFindToolDefinition3,
4442
+ defineTool as defineTool24
4443
+ } from "@earendil-works/pi-coding-agent";
4444
+ var GLOB_TOOL_NAME = "glob";
4445
+ function createGlobTool(cwd) {
4446
+ const nativeFind = createFindToolDefinition3(cwd);
4447
+ return defineTool24({
4448
+ ...nativeFind,
4449
+ name: GLOB_TOOL_NAME,
4450
+ label: "Glob"
4451
+ });
4452
+ }
4453
+ function createGlobExtension(cwd) {
4454
+ return {
4455
+ name: "glob-search",
4456
+ factory(pi) {
4457
+ pi.registerTool(createGlobTool(cwd));
4458
+ }
4459
+ };
4460
+ }
4461
+
4462
+ // src/capabilities/tools/filesystem/str_replace_editor.ts
4463
+ import {
4464
+ defineTool as defineTool25
4465
+ } from "@earendil-works/pi-coding-agent";
4466
+ import { Type as Type24 } from "typebox";
4467
+
4468
+ // src/utils/filesystem/str_replace_editor.ts
4469
+ import { readFile as readFile8, readdir as readdir2, stat as stat2, writeFile as writeFile6 } from "node:fs/promises";
4470
+ import path15 from "node:path";
4471
+ var STR_REPLACE_EDITOR_DEFAULT_MAX_OUTPUT_CHARS = 16e3;
4472
+ var TRUNCATED_MESSAGE = "<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>";
4473
+ function throwIfAborted2(signal) {
4474
+ if (signal?.aborted) throw signal.reason ?? new Error("Operation aborted");
4475
+ }
4476
+ function maybeTruncate(content, maxOutputChars) {
4477
+ return content.length <= maxOutputChars ? content : content.slice(0, maxOutputChars) + TRUNCATED_MESSAGE;
4478
+ }
4479
+ function requiredForCommand(value, parameter, command, allowEmpty = true) {
4480
+ if (value === void 0) {
4481
+ throw new Error(`Parameter \`${parameter}\` is required for command: ${command}`);
4482
+ }
4483
+ if (!allowEmpty && value.length === 0) {
4484
+ throw new Error(`Parameter \`${parameter}\` is empty for command: ${command}`);
4485
+ }
4486
+ return value;
4487
+ }
4488
+ async function resolveAbsoluteWorkspacePath(cwd, rawPath) {
4489
+ if (!rawPath.trim()) throw new Error("path must be a non-empty string");
4490
+ if (!path15.isAbsolute(rawPath)) {
4491
+ throw new Error(
4492
+ `The path ${rawPath} is not an absolute path, it should start with \`/\`. Maybe you meant /${rawPath}?`
4493
+ );
4494
+ }
4495
+ return resolveWorkspacePath(cwd, rawPath);
4496
+ }
4497
+ async function existingType(target) {
4498
+ try {
4499
+ const info = await stat2(target);
4500
+ if (info.isFile()) return "file";
4501
+ if (info.isDirectory()) return "directory";
4502
+ return "other";
4503
+ } catch (error) {
4504
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
4505
+ throw error;
4506
+ }
4507
+ }
4508
+ async function requireExisting(target, displayTarget, command) {
4509
+ const type = await existingType(target);
4510
+ if (type === void 0) {
4511
+ throw new Error(`The path ${displayTarget} does not exist. Please provide a valid path.`);
4512
+ }
4513
+ if (type === "directory" && command !== "view") {
4514
+ throw new Error(
4515
+ `The path ${displayTarget} is a directory and only the \`view\` command can be used on directories`
4516
+ );
4517
+ }
4518
+ return type;
4519
+ }
4520
+ function formatFileView(target, content, maxOutputChars, viewRange) {
4521
+ const allLines = content.split("\n");
4522
+ let lines = allLines;
4523
+ let initialLine = 1;
4524
+ let finalLine;
4525
+ let prompt = `Here's the content of ${target} with line numbers (which has a total of ${allLines.length} lines)`;
4526
+ if (viewRange !== void 0) {
4527
+ const [requestedInitialLine, requestedFinalLine] = viewRange;
4528
+ if (viewRange.length !== 2 || requestedInitialLine === void 0 || requestedFinalLine === void 0 || !viewRange.every(Number.isInteger)) {
4529
+ throw new Error("Invalid `view_range`. It should be a list of two integers.");
4530
+ }
4531
+ initialLine = requestedInitialLine;
4532
+ finalLine = requestedFinalLine;
4533
+ if (initialLine < 1 || initialLine > allLines.length) {
4534
+ throw new Error(
4535
+ `Invalid \`view_range\`: [${viewRange.join(", ")}]. Its first element \`${initialLine}\` should be within the range of lines of the file: [1, ${allLines.length}]`
4536
+ );
4537
+ }
4538
+ if (finalLine > allLines.length) {
4539
+ throw new Error(
4540
+ `Invalid \`view_range\`: [${viewRange.join(", ")}]. Its second element \`${finalLine}\` should be smaller than the number of lines in the file: \`${allLines.length}\``
4541
+ );
4542
+ }
4543
+ if (finalLine !== -1 && finalLine < initialLine) {
4544
+ throw new Error(
4545
+ `Invalid \`view_range\`: [${viewRange.join(", ")}]. Its second element \`${finalLine}\` should be larger or equal than its first \`${initialLine}\``
4546
+ );
4547
+ }
4548
+ lines = finalLine === -1 ? allLines.slice(initialLine - 1) : allLines.slice(initialLine - 1, finalLine);
4549
+ prompt += ` with view_range=[${initialLine}, ${finalLine}]`;
4550
+ }
4551
+ const numbered = lines.map((line, index) => `${String(initialLine + index).padStart(6, " ")} ${line}`).join("\n");
4552
+ return maybeTruncate(`${prompt}:
4553
+ ${numbered}
4554
+ `, maxOutputChars);
4555
+ }
4556
+ async function listDirectory(target, displayTarget, maxOutputChars, signal) {
4557
+ async function visit(directory, displayDirectory, depth) {
4558
+ throwIfAborted2(signal);
4559
+ const entries = await readdir2(directory, { withFileTypes: true });
4560
+ const rows2 = [];
4561
+ for (const entry of entries) {
4562
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "__pycache__") continue;
4563
+ const child = path15.join(directory, entry.name);
4564
+ const displayChild = path15.join(displayDirectory, entry.name);
4565
+ const type = entry.isDirectory() ? "d" : entry.isFile() ? "f" : "?";
4566
+ rows2.push(`${type} ${displayChild}`);
4567
+ if (entry.isDirectory() && depth < 2) {
4568
+ rows2.push(...await visit(child, displayChild, depth + 1));
4569
+ }
4570
+ }
4571
+ return rows2;
4572
+ }
4573
+ const rows = [`d ${displayTarget}`, ...await visit(target, displayTarget, 1)];
4574
+ rows.sort((left, right) => {
4575
+ const leftPath = left.slice(left.indexOf(" ") + 1);
4576
+ const rightPath = right.slice(right.indexOf(" ") + 1);
4577
+ return leftPath < rightPath ? -1 : leftPath > rightPath ? 1 : 0;
4578
+ });
4579
+ const listing = maybeTruncate(`${rows.join("\n")}
4580
+ `, maxOutputChars);
4581
+ return `Here're the files and directories up to 2 levels deep in ${displayTarget}, excluding hidden items, node_modules, and Python cache directories:
4582
+ ${listing}
4583
+ `;
4584
+ }
4585
+ function matchOffsets(content, search) {
4586
+ const offsets = [];
4587
+ let offset = 0;
4588
+ while (true) {
4589
+ const match = content.indexOf(search, offset);
4590
+ if (match < 0) return offsets;
4591
+ offsets.push(match);
4592
+ offset = match + search.length;
4593
+ }
4594
+ }
4595
+ function lineNumbersAt(content, offsets) {
4596
+ let line = 1;
4597
+ let cursor = 0;
4598
+ return offsets.map((offset) => {
4599
+ while (cursor < offset) {
4600
+ if (content[cursor] === "\n") line += 1;
4601
+ cursor += 1;
4602
+ }
4603
+ return line;
4604
+ });
4605
+ }
4606
+ async function viewPath(cwd, request, maxOutputChars, signal) {
4607
+ const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
4608
+ const displayTarget = path15.resolve(request.path);
4609
+ const type = await requireExisting(target, displayTarget, "view");
4610
+ if (type === "directory") {
4611
+ if (request.view_range !== void 0) {
4612
+ throw new Error("The `view_range` parameter is not allowed when `path` points to a directory.");
4613
+ }
4614
+ return listDirectory(target, displayTarget, maxOutputChars, signal);
4615
+ }
4616
+ if (type !== "file") {
4617
+ throw new Error(`cannot view "${displayTarget}": not a regular file or directory`);
4618
+ }
4619
+ const content = await readFile8(target, { encoding: "utf8", signal });
4620
+ return formatFileView(displayTarget, content, maxOutputChars, request.view_range);
4621
+ }
4622
+ async function createFile(cwd, request, signal) {
4623
+ const content = requiredForCommand(request.file_text, "file_text", "create");
4624
+ const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
4625
+ const displayTarget = path15.resolve(request.path);
4626
+ throwIfAborted2(signal);
4627
+ try {
4628
+ await writeFile6(target, content, { encoding: "utf8", flag: "wx", signal });
4629
+ } catch (error) {
4630
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
4631
+ throw new Error(
4632
+ `File already exists at: ${displayTarget}. Cannot overwrite files using command \`create\`.`
4633
+ );
4634
+ }
4635
+ throw error;
4636
+ }
4637
+ return `New file created successfully at: ${displayTarget}`;
4638
+ }
4639
+ async function replaceInFile(cwd, request, signal) {
4640
+ const oldValue = requiredForCommand(request.old_str, "old_str", "str_replace", false);
4641
+ const newValue = request.new_str ?? "";
4642
+ const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
4643
+ const displayTarget = path15.resolve(request.path);
4644
+ const type = await requireExisting(target, displayTarget, "str_replace");
4645
+ if (type !== "file") throw new Error(`cannot edit "${displayTarget}": not a regular file`);
4646
+ const before = await readFile8(target, { encoding: "utf8", signal });
4647
+ const offsets = matchOffsets(before, oldValue);
4648
+ const offset = offsets[0];
4649
+ if (offset === void 0) {
4650
+ throw new Error(
4651
+ `No replacement was performed, old_str \`${oldValue}\` did not appear verbatim in ${displayTarget}.`
4652
+ );
4653
+ }
4654
+ if (offsets.length > 1) {
4655
+ const lines = lineNumbersAt(before, offsets);
4656
+ throw new Error(
4657
+ `No replacement was performed. Multiple occurrences of old_str \`${oldValue}\` in lines [${lines.join(", ")}]. Please ensure it is unique`
4658
+ );
4659
+ }
4660
+ const after = before.slice(0, offset) + newValue + before.slice(offset + oldValue.length);
4661
+ await writeFile6(target, after, { encoding: "utf8", signal });
4662
+ return `The file ${displayTarget} has been edited successfully.`;
4663
+ }
4664
+ async function insertInFile(cwd, request, signal) {
4665
+ if (request.insert_line === void 0) {
4666
+ throw new Error("Parameter `insert_line` is required for command: insert");
4667
+ }
4668
+ const value = requiredForCommand(request.new_str, "new_str", "insert");
4669
+ const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
4670
+ const displayTarget = path15.resolve(request.path);
4671
+ const type = await requireExisting(target, displayTarget, "insert");
4672
+ if (type !== "file") throw new Error(`cannot insert into "${displayTarget}": not a regular file`);
4673
+ const before = await readFile8(target, { encoding: "utf8", signal });
4674
+ const lines = before.split("\n");
4675
+ if (!Number.isInteger(request.insert_line) || request.insert_line < 0 || request.insert_line > lines.length) {
4676
+ throw new Error(
4677
+ `Invalid \`insert_line\` parameter: ${request.insert_line}. It should be within the range of lines of the file: [0, ${lines.length}]`
4678
+ );
4679
+ }
4680
+ const after = [
4681
+ ...lines.slice(0, request.insert_line),
4682
+ ...value.split("\n"),
4683
+ ...lines.slice(request.insert_line)
4684
+ ].join("\n");
4685
+ await writeFile6(target, after, { encoding: "utf8", signal });
4686
+ return `The file ${displayTarget} has been edited successfully.`;
4687
+ }
4688
+ function resolveStrReplaceEditorOptions(options = {}) {
4689
+ const maxOutputChars = options.maxOutputChars ?? STR_REPLACE_EDITOR_DEFAULT_MAX_OUTPUT_CHARS;
4690
+ if (!Number.isSafeInteger(maxOutputChars) || maxOutputChars <= 0) {
4691
+ throw new Error("str-replace-editor: maxOutputChars must be a positive safe integer");
4692
+ }
4693
+ return { maxOutputChars };
4694
+ }
4695
+ async function executeStrReplaceEditor(cwd, request, options = {}, signal) {
4696
+ const { maxOutputChars } = resolveStrReplaceEditorOptions(options);
4697
+ switch (request.command) {
4698
+ case "view":
4699
+ return viewPath(cwd, request, maxOutputChars, signal);
4700
+ case "create":
4701
+ return createFile(cwd, request, signal);
4702
+ case "str_replace":
4703
+ return replaceInFile(cwd, request, signal);
4704
+ case "insert":
4705
+ return insertInFile(cwd, request, signal);
4706
+ }
4707
+ }
4708
+
4709
+ // src/capabilities/tools/filesystem/str_replace_editor.ts
4710
+ var STR_REPLACE_EDITOR_TOOL_NAME = "str_replace_editor";
4711
+ var DEFAULT_DESCRIPTION = [
4712
+ "Custom editing tool for viewing, creating and editing files.",
4713
+ "State is persistent across command calls and discussions with the user.",
4714
+ "If path is a file, view displays line-numbered content. If path is a directory, view lists non-hidden entries up to 2 levels deep.",
4715
+ "The create command refuses to overwrite an existing path.",
4716
+ "For str_replace, old_str must match exactly once; include enough surrounding text to make it unique."
4717
+ ].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")
4724
+ ], { description: "Command to run." }),
4725
+ path: Type24.String({
4726
+ description: "Absolute path to a file or directory inside the workspace."
4727
+ }),
4728
+ file_text: Type24.Optional(Type24.String({
4729
+ description: "Required by create: complete content of the new file."
4730
+ })),
4731
+ insert_line: Type24.Optional(Type24.Integer({
4732
+ description: "Required by insert: insert new_str after this 0-based line boundary."
4733
+ })),
4734
+ new_str: Type24.Optional(Type24.String({
4735
+ description: "Replacement text for str_replace, or required insertion text for insert."
4736
+ })),
4737
+ old_str: Type24.Optional(Type24.String({
4738
+ description: "Required by str_replace: the unique literal text to replace."
4739
+ })),
4740
+ view_range: Type24.Optional(Type24.Array(Type24.Integer(), {
4741
+ description: "For file views, [start_line, end_line] using 1-based inclusive lines; use -1 as the end to read through EOF."
4742
+ }))
4743
+ }, { additionalProperties: false });
4744
+ function resolveDescription(description) {
4745
+ const value = description ?? DEFAULT_DESCRIPTION;
4746
+ if (!value.trim()) throw new Error("str-replace-editor: description must be non-empty");
4747
+ return value;
4748
+ }
4749
+ function createStrReplaceEditorTool(cwd, options = {}) {
4750
+ const runtimeOptions = resolveStrReplaceEditorOptions(options);
4751
+ const description = resolveDescription(options.description);
4752
+ return defineTool25({
4753
+ name: STR_REPLACE_EDITOR_TOOL_NAME,
4754
+ label: "String Replace Editor",
4755
+ description,
4756
+ promptSnippet: "View, create, replace, and insert text in workspace files",
4757
+ parameters: schema17,
4758
+ executionMode: "sequential",
4759
+ async execute(_toolCallId, params, signal) {
4760
+ const text = await executeStrReplaceEditor(cwd, params, runtimeOptions, signal);
4761
+ return {
4762
+ content: [{ type: "text", text }],
4763
+ details: { command: params.command, path: params.path }
4764
+ };
4765
+ }
4766
+ });
4767
+ }
4768
+ function createStrReplaceEditorExtension(cwd, options = {}) {
4769
+ return {
4770
+ name: "str-replace-editor",
4771
+ factory(pi) {
4772
+ pi.registerTool(createStrReplaceEditorTool(cwd, options));
4773
+ }
4774
+ };
4775
+ }
4776
+
4777
+ // src/harnesses/tool-comparison/index.ts
4778
+ var toolComparisonHarnessNames = [
4779
+ "bash-only",
4780
+ "bash-apply-patch",
4781
+ "bash-str-replace-editor",
4782
+ "bash-file-search"
4783
+ ];
4784
+ var TOOL_COMPARISON_TOOLS = {
4785
+ "bash-only": ["bash"],
4786
+ "bash-apply-patch": ["bash", "apply_patch"],
4787
+ "bash-str-replace-editor": ["bash", "str_replace_editor"],
4788
+ "bash-file-search": ["read", "bash", "edit", "write", "grep", "glob"]
4789
+ };
4790
+ function buildToolComparisonArgs(name, args) {
4791
+ return isolateHarnessArgs(args, void 0, {
4792
+ isolatedResources: NATIVE_PI_ISOLATED_RESOURCES,
4793
+ tools: TOOL_COMPARISON_TOOLS[name]
4794
+ });
4795
+ }
4796
+ function createToolComparisonExtensions(name, cwd) {
4797
+ switch (name) {
4798
+ case "bash-apply-patch":
4799
+ return [createApplyPatchExtension(cwd)];
4800
+ case "bash-str-replace-editor":
4801
+ return [createStrReplaceEditorExtension(cwd)];
4802
+ case "bash-file-search":
4803
+ return [createGlobExtension(cwd)];
4804
+ case "bash-only":
4805
+ return [];
4806
+ }
4807
+ }
4808
+ async function runToolComparisonHarness(name, args) {
4809
+ const cwd = process.cwd();
4810
+ await runHarnessMain(
4811
+ buildToolComparisonArgs(name, args),
4812
+ createToolComparisonExtensions(name, cwd)
4813
+ );
4814
+ }
4815
+
4816
+ // src/runtime/pi-management.ts
4817
+ var PI_MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set([
4818
+ "auth",
4819
+ "config",
4820
+ "install",
4821
+ "list",
4822
+ "remove",
4823
+ "uninstall",
4824
+ "update"
4825
+ ]);
4826
+ function isPiManagementCommand(args) {
4827
+ return args[0] !== void 0 && PI_MANAGEMENT_COMMANDS.has(args[0]);
3194
4828
  }
3195
4829
 
3196
4830
  // src/harness_cli.ts
3197
4831
  var harnessNames = [
3198
4832
  "pi",
4833
+ "pi-ptc",
4834
+ "self-compact",
3199
4835
  "agent-arena",
3200
4836
  "code-arena-html",
3201
4837
  "code-arena-react",
3202
4838
  "code-arena-full-stack",
3203
- "long-horizon"
4839
+ "long-horizon-mea",
4840
+ ...toolComparisonHarnessNames
3204
4841
  ];
4842
+ function resolveHarnessInvocation(invocation) {
4843
+ if (isPiManagementCommand(invocation.args)) {
4844
+ return { kind: "pi-management", args: invocation.args };
4845
+ }
4846
+ return { kind: "harness", ...invocation };
4847
+ }
3205
4848
  function parseHarnessName(value) {
3206
4849
  const name = value?.trim().toLowerCase();
3207
4850
  if (name && harnessNames.includes(name)) {
@@ -3215,7 +4858,8 @@ function harnessUsage() {
3215
4858
  "",
3216
4859
  `Harnesses: ${harnessNames.join(", ")}`,
3217
4860
  "",
3218
- "The harness defaults to pi, which uses Pi's default prompt and tools.",
4861
+ "The harness defaults to pi, which keeps Pi's default prompt and built-in tools",
4862
+ "while disabling user and project resource discovery.",
3219
4863
  "All remaining arguments are passed to Pi unchanged."
3220
4864
  ].join("\n");
3221
4865
  }
@@ -3240,14 +4884,56 @@ function parseHarnessInvocation(args) {
3240
4884
  return { name: name ?? "pi", args: piArgs };
3241
4885
  }
3242
4886
 
4887
+ // src/runtime/subagent-runtime.ts
4888
+ import {
4889
+ accessSync,
4890
+ constants,
4891
+ readFileSync,
4892
+ realpathSync
4893
+ } from "node:fs";
4894
+ import path16 from "node:path";
4895
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
4896
+ var SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
4897
+ function resolvePackagedHarnessEntrypoint(candidate) {
4898
+ try {
4899
+ const entrypoint = realpathSync(candidate);
4900
+ if (path16.basename(entrypoint) !== "entrypoint.js" || path16.basename(path16.dirname(entrypoint)) !== "dist") {
4901
+ return void 0;
4902
+ }
4903
+ const packageRoot = path16.dirname(path16.dirname(entrypoint));
4904
+ const packageJson = JSON.parse(
4905
+ readFileSync(path16.join(packageRoot, "package.json"), "utf8")
4906
+ );
4907
+ if (packageJson.name !== "@qwen-code/qwen-harness") return void 0;
4908
+ if (process.platform !== "win32") accessSync(entrypoint, constants.X_OK);
4909
+ return entrypoint;
4910
+ } catch {
4911
+ return void 0;
4912
+ }
4913
+ }
4914
+ function exposePackagedHarnessAsSubagentBinary(environment = process.env, moduleUrl = import.meta.url) {
4915
+ const configured = environment[SUBAGENT_PI_BINARY_ENV]?.trim();
4916
+ if (configured) return configured;
4917
+ if (process.platform === "win32") return void 0;
4918
+ const entrypoint = resolvePackagedHarnessEntrypoint(fileURLToPath4(moduleUrl));
4919
+ if (entrypoint) environment[SUBAGENT_PI_BINARY_ENV] = entrypoint;
4920
+ return entrypoint;
4921
+ }
4922
+
3243
4923
  // src/entrypoint.ts
3244
4924
  var harnessRunners = {
3245
4925
  pi: runPiHarness,
4926
+ "pi-ptc": runPiPtcHarness,
4927
+ "self-compact": runSelfCompactHarness,
3246
4928
  "agent-arena": runAgentArenaHarness,
3247
4929
  "code-arena-html": runCodeArenaHtmlHarness,
3248
4930
  "code-arena-react": runCodeArenaReactHarness,
3249
4931
  "code-arena-full-stack": runCodeArenaFullStackHarness,
3250
- "long-horizon": runLongHorizonHarness
4932
+ "long-horizon-mea": runLongHorizonHarness,
4933
+ "bash-only": (args) => runToolComparisonHarness("bash-only", args),
4934
+ "bash-apply-patch": (args) => runToolComparisonHarness("bash-apply-patch", args),
4935
+ "bash-str-replace-editor": (args) => runToolComparisonHarness("bash-str-replace-editor", args),
4936
+ "bash-file-search": (args) => runToolComparisonHarness("bash-file-search", args)
3251
4937
  };
3252
4938
  async function runEntrypoint(args) {
3253
4939
  try {
@@ -3256,11 +4942,16 @@ async function runEntrypoint(args) {
3256
4942
  `);
3257
4943
  return;
3258
4944
  }
3259
- const { name, args: harnessArgs } = parseHarnessInvocation(args);
3260
- process.title = `pi-${name}`;
4945
+ const invocation = resolveHarnessInvocation(parseHarnessInvocation(args));
4946
+ process.title = invocation.kind === "pi-management" ? "pi-management" : `pi-${invocation.name}`;
3261
4947
  process.env.PI_CODING_AGENT = "true";
3262
4948
  process.env.AI_AGENT = "pi";
3263
- await harnessRunners[name](harnessArgs);
4949
+ exposePackagedHarnessAsSubagentBinary();
4950
+ if (invocation.kind === "pi-management") {
4951
+ await runHarnessMain(invocation.args);
4952
+ } else {
4953
+ await harnessRunners[invocation.name](invocation.args);
4954
+ }
3264
4955
  } catch (error) {
3265
4956
  process.stderr.write(
3266
4957
  `${error instanceof Error ? error.message : String(error)}