@qwen-code/qwen-harness 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -9
- package/assets/audio/FFmpeg.LICENSE +511 -0
- package/assets/audio/LAME.LICENSE +490 -0
- package/assets/audio/Opus.LICENSE +44 -0
- package/assets/audio/README.md +18 -0
- package/assets/audio/darwin-arm64/ffmpeg.gz +0 -0
- package/assets/audio/darwin-arm64/manifest.json +39 -0
- package/assets/audio/darwin-x64/ffmpeg.gz +0 -0
- package/assets/audio/darwin-x64/manifest.json +39 -0
- package/assets/audio/linux-arm64/ffmpeg.gz +0 -0
- package/assets/audio/linux-arm64/manifest.json +39 -0
- package/assets/audio/linux-x64/ffmpeg.gz +0 -0
- package/assets/audio/linux-x64/manifest.json +39 -0
- package/assets/audio/sources/ffmpeg-7.0.2.tar.xz +0 -0
- package/assets/audio/sources/lame-3.100.tar.gz +0 -0
- package/assets/audio/sources/opus-1.5.2.tar.gz +0 -0
- package/assets/audio/sources/pkgconf-2.3.0.tar.xz +0 -0
- package/assets/audio/win32-x64/ffmpeg.gz +0 -0
- package/assets/audio/win32-x64/manifest.json +39 -0
- package/dist/entrypoint.js +1371 -664
- package/dist/entrypoint.js.map +4 -4
- package/package.json +11 -8
- package/scripts/audio-sources.lock.json +30 -0
- package/scripts/build-audio-encoder.sh +76 -0
package/dist/entrypoint.js
CHANGED
|
@@ -14,148 +14,37 @@ var __export = (target, all) => {
|
|
|
14
14
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
15
|
};
|
|
16
16
|
|
|
17
|
-
// src/utils/clients/retry.ts
|
|
18
|
-
import { setTimeout as delay } from "node:timers/promises";
|
|
19
|
-
function retryableStatus(status) {
|
|
20
|
-
return status === 408 || status === 409 || status === 429 || status >= 500;
|
|
21
|
-
}
|
|
22
|
-
function retryAfterMilliseconds(response) {
|
|
23
|
-
const rawMilliseconds = response.headers.get("retry-after-ms")?.trim();
|
|
24
|
-
if (rawMilliseconds) {
|
|
25
|
-
const milliseconds = Number(rawMilliseconds);
|
|
26
|
-
if (Number.isFinite(milliseconds) && milliseconds >= 0) return milliseconds;
|
|
27
|
-
}
|
|
28
|
-
const value = response.headers.get("retry-after")?.trim();
|
|
29
|
-
if (!value) return void 0;
|
|
30
|
-
const seconds = Number(value);
|
|
31
|
-
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
32
|
-
const date = Date.parse(value);
|
|
33
|
-
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
|
|
34
|
-
}
|
|
35
|
-
function retryDelayMilliseconds(response, attempt, retry) {
|
|
36
|
-
const requested = response ? retryAfterMilliseconds(response) : void 0;
|
|
37
|
-
const exponential = Math.min(500 * 2 ** attempt, 8e3);
|
|
38
|
-
if (requested === void 0) return exponential;
|
|
39
|
-
if (retry.maxRetryDelayMs > 0 && requested > retry.maxRetryDelayMs) {
|
|
40
|
-
throw new Error(
|
|
41
|
-
`Server requested ${Math.ceil(requested / 1e3)}s retry delay (max: ${Math.ceil(retry.maxRetryDelayMs / 1e3)}s)`
|
|
42
|
-
);
|
|
43
|
-
}
|
|
44
|
-
return requested;
|
|
45
|
-
}
|
|
46
|
-
async function retryHttpRequest(request, retry, signal) {
|
|
47
|
-
for (let attempt = 0; ; attempt += 1) {
|
|
48
|
-
let response;
|
|
49
|
-
try {
|
|
50
|
-
response = await request();
|
|
51
|
-
} catch (error) {
|
|
52
|
-
if (signal?.aborted || attempt >= retry.maxRetries) throw error;
|
|
53
|
-
await delay(retryDelayMilliseconds(void 0, attempt, retry), void 0, signal ? { signal } : void 0);
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
if (!retryableStatus(response.status) || attempt >= retry.maxRetries) return response;
|
|
57
|
-
let waitMs;
|
|
58
|
-
try {
|
|
59
|
-
waitMs = retryDelayMilliseconds(response, attempt, retry);
|
|
60
|
-
} catch (error) {
|
|
61
|
-
await response.body?.cancel();
|
|
62
|
-
throw error;
|
|
63
|
-
}
|
|
64
|
-
await response.body?.cancel();
|
|
65
|
-
await delay(waitMs, void 0, signal ? { signal } : void 0);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
var init_retry = __esm({
|
|
69
|
-
"src/utils/clients/retry.ts"() {
|
|
70
|
-
"use strict";
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
// src/utils/clients/media/dashscope.ts
|
|
75
|
-
function record(value) {
|
|
76
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
77
|
-
}
|
|
78
|
-
function apiKey(settings) {
|
|
79
|
-
const value = settings?.apiKey;
|
|
80
|
-
if (!value) {
|
|
81
|
-
throw new Error("DashScope tools require harnesses.toolServices.dashScope.apiKey in settings.json");
|
|
82
|
-
}
|
|
83
|
-
return value;
|
|
84
|
-
}
|
|
85
|
-
function endpoint(settings, pathname) {
|
|
86
|
-
const configured = settings?.apiBase || "https://dashscope.aliyuncs.com";
|
|
87
|
-
const root = configured.replace(/\/+$/u, "").replace(/\/(?:api\/v1|compatible-mode\/v1)$/iu, "");
|
|
88
|
-
return `${root}/api/v1${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
|
|
89
|
-
}
|
|
90
|
-
function createDashScopeClient(settings, retry) {
|
|
91
|
-
return {
|
|
92
|
-
async json(pathname, init, label) {
|
|
93
|
-
const headers = new Headers(init.headers);
|
|
94
|
-
headers.set("authorization", `Bearer ${apiKey(settings)}`);
|
|
95
|
-
const response = await retryHttpRequest(
|
|
96
|
-
() => fetch(endpoint(settings, pathname), { ...init, headers }),
|
|
97
|
-
retry,
|
|
98
|
-
init.signal ?? void 0
|
|
99
|
-
);
|
|
100
|
-
const body = await response.text();
|
|
101
|
-
let payload = {};
|
|
102
|
-
try {
|
|
103
|
-
payload = record(JSON.parse(body));
|
|
104
|
-
} catch {
|
|
105
|
-
if (response.ok) throw new Error(`${label} returned malformed JSON`);
|
|
106
|
-
}
|
|
107
|
-
if (response.ok) return payload;
|
|
108
|
-
const detail = String(payload.message || record(payload.error).message || body);
|
|
109
|
-
throw new Error(`${label} failed (${response.status} ${response.statusText}): ${detail.slice(0, 2e3)}`);
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
function objectValue(value) {
|
|
114
|
-
return record(value);
|
|
115
|
-
}
|
|
116
|
-
async function responseBytes(response, limit = 25 * 1024 * 1024) {
|
|
117
|
-
const bytes = Buffer.from(await response.arrayBuffer());
|
|
118
|
-
if (bytes.length > limit) throw new Error(`download exceeds ${limit} bytes`);
|
|
119
|
-
return bytes;
|
|
120
|
-
}
|
|
121
|
-
var init_dashscope = __esm({
|
|
122
|
-
"src/utils/clients/media/dashscope.ts"() {
|
|
123
|
-
"use strict";
|
|
124
|
-
init_retry();
|
|
125
|
-
}
|
|
126
|
-
});
|
|
127
|
-
|
|
128
17
|
// src/utils/settings.ts
|
|
129
|
-
function
|
|
18
|
+
function record(value, path34) {
|
|
130
19
|
if (value === void 0) return {};
|
|
131
20
|
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
132
|
-
throw new Error(`${
|
|
21
|
+
throw new Error(`${path34} must be a JSON object`);
|
|
133
22
|
}
|
|
134
23
|
return value;
|
|
135
24
|
}
|
|
136
|
-
function assertKnownKeys(value,
|
|
25
|
+
function assertKnownKeys(value, path34, allowedKeys) {
|
|
137
26
|
const allowed = new Set(allowedKeys);
|
|
138
27
|
const unknownKeys = Object.keys(value).filter((key) => !allowed.has(key));
|
|
139
28
|
if (unknownKeys.length === 0) return;
|
|
140
|
-
throw new Error(`${
|
|
29
|
+
throw new Error(`${path34} contains unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}`);
|
|
141
30
|
}
|
|
142
|
-
function optionalString(value,
|
|
31
|
+
function optionalString(value, path34) {
|
|
143
32
|
if (value === void 0) return void 0;
|
|
144
33
|
if (typeof value !== "string" || value.trim().length === 0) {
|
|
145
|
-
throw new Error(`${
|
|
34
|
+
throw new Error(`${path34} must be a non-empty string`);
|
|
146
35
|
}
|
|
147
36
|
return value.trim();
|
|
148
37
|
}
|
|
149
|
-
function optionalNonNegativeInteger(value,
|
|
38
|
+
function optionalNonNegativeInteger(value, path34) {
|
|
150
39
|
if (value === void 0) return void 0;
|
|
151
40
|
if (!Number.isSafeInteger(value) || Number(value) < 0) {
|
|
152
|
-
throw new Error(`${
|
|
41
|
+
throw new Error(`${path34} must be a non-negative integer`);
|
|
153
42
|
}
|
|
154
43
|
return Number(value);
|
|
155
44
|
}
|
|
156
|
-
function optionalPositiveInteger(value,
|
|
157
|
-
const parsed = optionalNonNegativeInteger(value,
|
|
158
|
-
if (parsed === 0) throw new Error(`${
|
|
45
|
+
function optionalPositiveInteger(value, path34) {
|
|
46
|
+
const parsed = optionalNonNegativeInteger(value, path34);
|
|
47
|
+
if (parsed === 0) throw new Error(`${path34} must be a positive integer`);
|
|
159
48
|
return parsed;
|
|
160
49
|
}
|
|
161
50
|
function withoutUndefined(value) {
|
|
@@ -172,7 +61,7 @@ var init_settings = __esm({
|
|
|
172
61
|
// src/utils/clients/media/settings.ts
|
|
173
62
|
function parseDashScopeSettings(value) {
|
|
174
63
|
if (value === void 0) return void 0;
|
|
175
|
-
const source =
|
|
64
|
+
const source = record(value, "harnesses.toolServices.dashScope");
|
|
176
65
|
assertKnownKeys(source, "harnesses.toolServices.dashScope", ["apiKey", "apiBase"]);
|
|
177
66
|
return withoutUndefined({
|
|
178
67
|
apiKey: optionalString(source.apiKey, "harnesses.toolServices.dashScope.apiKey"),
|
|
@@ -181,7 +70,7 @@ function parseDashScopeSettings(value) {
|
|
|
181
70
|
}
|
|
182
71
|
function parsePexelsSettings(value) {
|
|
183
72
|
if (value === void 0) return void 0;
|
|
184
|
-
const source =
|
|
73
|
+
const source = record(value, "harnesses.toolServices.pexels");
|
|
185
74
|
assertKnownKeys(source, "harnesses.toolServices.pexels", ["apiKey", "cacheTtlMs", "cacheDir"]);
|
|
186
75
|
return withoutUndefined({
|
|
187
76
|
apiKey: optionalString(source.apiKey, "harnesses.toolServices.pexels.apiKey"),
|
|
@@ -199,15 +88,25 @@ var init_settings2 = __esm({
|
|
|
199
88
|
// src/utils/clients/web/settings.ts
|
|
200
89
|
function parseRoutifySettings(value) {
|
|
201
90
|
if (value === void 0) return void 0;
|
|
202
|
-
const source =
|
|
91
|
+
const source = record(value, "harnesses.toolServices.routify");
|
|
203
92
|
assertKnownKeys(source, "harnesses.toolServices.routify", [
|
|
204
93
|
"apiKey",
|
|
94
|
+
"webSearchApiKey",
|
|
95
|
+
"imageSearchApiKey",
|
|
96
|
+
"generateImageApiKey",
|
|
97
|
+
"openaiBaseUrl",
|
|
98
|
+
"vertexBaseUrl",
|
|
205
99
|
"webSearchUrl",
|
|
206
100
|
"imageSearchUrl",
|
|
207
101
|
"webFetchUrl"
|
|
208
102
|
]);
|
|
209
103
|
return withoutUndefined({
|
|
210
104
|
apiKey: optionalString(source.apiKey, "harnesses.toolServices.routify.apiKey"),
|
|
105
|
+
webSearchApiKey: optionalString(source.webSearchApiKey, "harnesses.toolServices.routify.webSearchApiKey"),
|
|
106
|
+
imageSearchApiKey: optionalString(source.imageSearchApiKey, "harnesses.toolServices.routify.imageSearchApiKey"),
|
|
107
|
+
generateImageApiKey: optionalString(source.generateImageApiKey, "harnesses.toolServices.routify.generateImageApiKey"),
|
|
108
|
+
openaiBaseUrl: optionalString(source.openaiBaseUrl, "harnesses.toolServices.routify.openaiBaseUrl"),
|
|
109
|
+
vertexBaseUrl: optionalString(source.vertexBaseUrl, "harnesses.toolServices.routify.vertexBaseUrl"),
|
|
211
110
|
webSearchUrl: optionalString(source.webSearchUrl, "harnesses.toolServices.routify.webSearchUrl"),
|
|
212
111
|
imageSearchUrl: optionalString(source.imageSearchUrl, "harnesses.toolServices.routify.imageSearchUrl"),
|
|
213
112
|
webFetchUrl: optionalString(source.webFetchUrl, "harnesses.toolServices.routify.webFetchUrl")
|
|
@@ -241,7 +140,7 @@ var init_settings4 = __esm({
|
|
|
241
140
|
// src/utils/filesystem/settings.ts
|
|
242
141
|
function parseDocumentSettings(value) {
|
|
243
142
|
if (value === void 0) return void 0;
|
|
244
|
-
const source =
|
|
143
|
+
const source = record(value, "harnesses.tools.documents");
|
|
245
144
|
assertKnownKeys(source, "harnesses.tools.documents", ["sofficePath"]);
|
|
246
145
|
return withoutUndefined({
|
|
247
146
|
sofficePath: optionalString(source.sofficePath, "harnesses.tools.documents.sofficePath")
|
|
@@ -257,7 +156,7 @@ var init_settings5 = __esm({
|
|
|
257
156
|
// src/utils/image-caption/settings.ts
|
|
258
157
|
function parseImageCaptionSettings(value) {
|
|
259
158
|
if (value === void 0) return void 0;
|
|
260
|
-
const source =
|
|
159
|
+
const source = record(value, "harnesses.tools.imageCaption");
|
|
261
160
|
assertKnownKeys(source, "harnesses.tools.imageCaption", ["provider", "model", "systemPrompt", "prompt"]);
|
|
262
161
|
const provider = optionalString(source.provider, "harnesses.tools.imageCaption.provider");
|
|
263
162
|
const model = optionalString(source.model, "harnesses.tools.imageCaption.model");
|
|
@@ -302,7 +201,7 @@ function commandInvocation(command) {
|
|
|
302
201
|
}
|
|
303
202
|
function parseExecutionToolSettings(value) {
|
|
304
203
|
if (value === void 0) return void 0;
|
|
305
|
-
const source =
|
|
204
|
+
const source = record(value, "harnesses.tools.code");
|
|
306
205
|
if (source.maximumRetries !== void 0) {
|
|
307
206
|
throw new Error("harnesses.tools.code.maximumRetries was removed; use Pi retry.provider.maxRetries");
|
|
308
207
|
}
|
|
@@ -334,7 +233,7 @@ var init_settings7 = __esm({
|
|
|
334
233
|
// src/capabilities/tools/media/settings.ts
|
|
335
234
|
function parseGenerateImageSettings(value) {
|
|
336
235
|
if (value === void 0) return void 0;
|
|
337
|
-
const source =
|
|
236
|
+
const source = record(value, "harnesses.tools.generateImage");
|
|
338
237
|
assertKnownKeys(source, "harnesses.tools.generateImage", ["model", "size", "taskTimeoutMs", "taskPollIntervalMs"]);
|
|
339
238
|
return withoutUndefined({
|
|
340
239
|
model: optionalString(source.model, "harnesses.tools.generateImage.model"),
|
|
@@ -345,7 +244,7 @@ function parseGenerateImageSettings(value) {
|
|
|
345
244
|
}
|
|
346
245
|
function parseGenerateSpeechSettings(value) {
|
|
347
246
|
if (value === void 0) return void 0;
|
|
348
|
-
const source =
|
|
247
|
+
const source = record(value, "harnesses.tools.generateSpeech");
|
|
349
248
|
assertKnownKeys(source, "harnesses.tools.generateSpeech", ["model", "voice"]);
|
|
350
249
|
return withoutUndefined({
|
|
351
250
|
model: optionalString(source.model, "harnesses.tools.generateSpeech.model"),
|
|
@@ -362,7 +261,7 @@ var init_settings8 = __esm({
|
|
|
362
261
|
// src/capabilities/tools/web/settings.ts
|
|
363
262
|
function parseWebSearchSettings(value) {
|
|
364
263
|
if (value === void 0) return void 0;
|
|
365
|
-
const source =
|
|
264
|
+
const source = record(value, "harnesses.tools.webSearch");
|
|
366
265
|
assertKnownKeys(source, "harnesses.tools.webSearch", ["model"]);
|
|
367
266
|
return withoutUndefined({
|
|
368
267
|
model: optionalString(source.model, "harnesses.tools.webSearch.model")
|
|
@@ -402,10 +301,10 @@ var init_settings10 = __esm({
|
|
|
402
301
|
// src/capabilities/settings.ts
|
|
403
302
|
import { getAgentDir, getShellConfig, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
404
303
|
function parseCapabilitySettings(value, pi) {
|
|
405
|
-
const harnesses =
|
|
304
|
+
const harnesses = record(value, "harnesses");
|
|
406
305
|
assertKnownKeys(harnesses, "harnesses", ["toolServices", "tools"]);
|
|
407
|
-
const services =
|
|
408
|
-
const tools =
|
|
306
|
+
const services = record(harnesses.toolServices, "harnesses.toolServices");
|
|
307
|
+
const tools = record(harnesses.tools, "harnesses.tools");
|
|
409
308
|
assertKnownKeys(services, "harnesses.toolServices", INFRASTRUCTURE_SETTING_KEYS);
|
|
410
309
|
assertKnownKeys(tools, "harnesses.tools", [...TOOL_SETTING_KEYS, ...SHARED_CAPABILITY_SETTING_KEYS]);
|
|
411
310
|
return {
|
|
@@ -1332,90 +1231,796 @@ var init_read_file = __esm({
|
|
|
1332
1231
|
}
|
|
1333
1232
|
});
|
|
1334
1233
|
|
|
1234
|
+
// src/utils/clients/media/speech_audio.ts
|
|
1235
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1236
|
+
import { createHash } from "node:crypto";
|
|
1237
|
+
import { mkdtemp as mkdtemp2, readFile as readFile4, writeFile, rm as rm2 } from "node:fs/promises";
|
|
1238
|
+
import { tmpdir as tmpdir2 } from "node:os";
|
|
1239
|
+
import path6 from "node:path";
|
|
1240
|
+
import { gunzip } from "node:zlib";
|
|
1241
|
+
import { promisify } from "node:util";
|
|
1242
|
+
function validatePcm(pcm) {
|
|
1243
|
+
if (!Number.isInteger(pcm.sampleRate) || pcm.sampleRate < 8e3 || pcm.sampleRate > 96e3 || ![1, 2].includes(pcm.channels) || !pcm.bytes.length || pcm.bytes.length > maximumBytes || pcm.bytes.length % (2 * pcm.channels) !== 0) {
|
|
1244
|
+
throw new Error("Invalid or oversized 16-bit speech PCM response");
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
function pcmToWav(pcm) {
|
|
1248
|
+
validatePcm(pcm);
|
|
1249
|
+
const header = Buffer.alloc(44);
|
|
1250
|
+
header.write("RIFF", 0);
|
|
1251
|
+
header.writeUInt32LE(36 + pcm.bytes.length, 4);
|
|
1252
|
+
header.write("WAVEfmt ", 8);
|
|
1253
|
+
header.writeUInt32LE(16, 16);
|
|
1254
|
+
header.writeUInt16LE(1, 20);
|
|
1255
|
+
header.writeUInt16LE(pcm.channels, 22);
|
|
1256
|
+
header.writeUInt32LE(pcm.sampleRate, 24);
|
|
1257
|
+
header.writeUInt32LE(pcm.sampleRate * pcm.channels * 2, 28);
|
|
1258
|
+
header.writeUInt16LE(pcm.channels * 2, 32);
|
|
1259
|
+
header.writeUInt16LE(16, 34);
|
|
1260
|
+
header.write("data", 36);
|
|
1261
|
+
header.writeUInt32LE(pcm.bytes.length, 40);
|
|
1262
|
+
return Buffer.concat([header, pcm.bytes]);
|
|
1263
|
+
}
|
|
1264
|
+
async function audioAsset(name) {
|
|
1265
|
+
const target = `${process.platform}-${process.arch}`;
|
|
1266
|
+
for (const root of ["../assets/audio/", "../../../../assets/audio/"]) {
|
|
1267
|
+
try {
|
|
1268
|
+
return await readFile4(new URL(`${root}${target}/${name}`, import.meta.url));
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
if (error.code !== "ENOENT") throw error;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
throw new Error(`Bundled speech encoder asset missing for ${target}: ${name}. Reinstall the complete qwen-harness package.`);
|
|
1274
|
+
}
|
|
1275
|
+
function checksum(bytes) {
|
|
1276
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
1277
|
+
}
|
|
1278
|
+
async function extractEncoder(directory) {
|
|
1279
|
+
const metadata = JSON.parse((await audioAsset("manifest.json")).toString("utf8"));
|
|
1280
|
+
if (metadata.target !== `${process.platform}-${process.arch}` || !Number.isSafeInteger(metadata.binaryBytes) || metadata.binaryBytes <= 0 || metadata.binaryBytes > 128 * 1024 * 1024) {
|
|
1281
|
+
throw new Error("Bundled speech encoder metadata does not match this platform");
|
|
1282
|
+
}
|
|
1283
|
+
const compressed = await audioAsset("ffmpeg.gz");
|
|
1284
|
+
if (checksum(compressed) !== metadata.compressedSha256) throw new Error("Bundled speech encoder checksum mismatch");
|
|
1285
|
+
const binary = await unzip(compressed, { maxOutputLength: metadata.binaryBytes });
|
|
1286
|
+
if (binary.length !== metadata.binaryBytes || checksum(binary) !== metadata.binarySha256) {
|
|
1287
|
+
throw new Error("Bundled speech encoder binary checksum mismatch");
|
|
1288
|
+
}
|
|
1289
|
+
const executable = path6.join(directory, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg");
|
|
1290
|
+
await writeFile(executable, binary, { flag: "wx", mode: 448 });
|
|
1291
|
+
return executable;
|
|
1292
|
+
}
|
|
1293
|
+
function executeEncoder(executable, args, signal) {
|
|
1294
|
+
signal?.throwIfAborted();
|
|
1295
|
+
return new Promise((resolve, reject) => {
|
|
1296
|
+
const child = spawn2(executable, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
|
|
1297
|
+
let diagnostic = "";
|
|
1298
|
+
let failure2;
|
|
1299
|
+
const stop = (error) => {
|
|
1300
|
+
failure2 ||= error;
|
|
1301
|
+
child.kill("SIGKILL");
|
|
1302
|
+
};
|
|
1303
|
+
const abort = () => stop(new Error("Speech encoding aborted", { cause: signal?.reason }));
|
|
1304
|
+
const timer = setTimeout(() => stop(new Error("Bundled speech encoder exceeded 60 seconds")), 6e4);
|
|
1305
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1306
|
+
if (signal?.aborted) abort();
|
|
1307
|
+
child.stderr.on("data", (chunk) => {
|
|
1308
|
+
diagnostic = (diagnostic + chunk.toString("utf8")).slice(-4096);
|
|
1309
|
+
});
|
|
1310
|
+
child.on("error", (error) => {
|
|
1311
|
+
failure2 ||= error;
|
|
1312
|
+
});
|
|
1313
|
+
child.on("close", (code) => {
|
|
1314
|
+
clearTimeout(timer);
|
|
1315
|
+
signal?.removeEventListener("abort", abort);
|
|
1316
|
+
if (failure2) reject(failure2);
|
|
1317
|
+
else if (code !== 0) reject(new Error(`Bundled speech encoder failed (${code}): ${diagnostic}`));
|
|
1318
|
+
else resolve();
|
|
1319
|
+
});
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
async function encodeSpeechPcm(pcm, format, signal) {
|
|
1323
|
+
signal?.throwIfAborted();
|
|
1324
|
+
validatePcm(pcm);
|
|
1325
|
+
if (format === "wav") return pcmToWav(pcm);
|
|
1326
|
+
if (format !== "mp3" && format !== "opus") throw new Error(`Unsupported speech format: ${format}`);
|
|
1327
|
+
const directory = await mkdtemp2(path6.join(tmpdir2(), "arena-speech-"));
|
|
1328
|
+
try {
|
|
1329
|
+
const executable = await extractEncoder(directory);
|
|
1330
|
+
signal?.throwIfAborted();
|
|
1331
|
+
const input = path6.join(directory, "input.pcm");
|
|
1332
|
+
const output = path6.join(directory, `output.${format}`);
|
|
1333
|
+
await writeFile(input, pcm.bytes, { mode: 384 });
|
|
1334
|
+
await executeEncoder(executable, [
|
|
1335
|
+
"-hide_banner",
|
|
1336
|
+
"-loglevel",
|
|
1337
|
+
"error",
|
|
1338
|
+
"-nostdin",
|
|
1339
|
+
"-y",
|
|
1340
|
+
"-f",
|
|
1341
|
+
"s16le",
|
|
1342
|
+
"-ar",
|
|
1343
|
+
String(pcm.sampleRate),
|
|
1344
|
+
"-ac",
|
|
1345
|
+
String(pcm.channels),
|
|
1346
|
+
"-i",
|
|
1347
|
+
input,
|
|
1348
|
+
"-c:a",
|
|
1349
|
+
format === "mp3" ? "libmp3lame" : "libopus",
|
|
1350
|
+
"-b:a",
|
|
1351
|
+
format === "mp3" ? "128k" : "64k",
|
|
1352
|
+
"-fs",
|
|
1353
|
+
String(maximumBytes),
|
|
1354
|
+
"-f",
|
|
1355
|
+
format === "mp3" ? "mp3" : "ogg",
|
|
1356
|
+
output
|
|
1357
|
+
], signal);
|
|
1358
|
+
signal?.throwIfAborted();
|
|
1359
|
+
const bytes = await readFile4(output);
|
|
1360
|
+
if (!bytes.length || bytes.length >= maximumBytes) throw new Error("Generated speech exceeded the output size limit");
|
|
1361
|
+
return bytes;
|
|
1362
|
+
} finally {
|
|
1363
|
+
await rm2(directory, { recursive: true, force: true });
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
var unzip, maximumBytes;
|
|
1367
|
+
var init_speech_audio = __esm({
|
|
1368
|
+
"src/utils/clients/media/speech_audio.ts"() {
|
|
1369
|
+
"use strict";
|
|
1370
|
+
unzip = promisify(gunzip);
|
|
1371
|
+
maximumBytes = 25 * 1024 * 1024;
|
|
1372
|
+
}
|
|
1373
|
+
});
|
|
1374
|
+
|
|
1375
|
+
// src/utils/clients/retry.ts
|
|
1376
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1377
|
+
function retryableStatus(status) {
|
|
1378
|
+
return status === 408 || status === 409 || status === 429 || status >= 500;
|
|
1379
|
+
}
|
|
1380
|
+
function retryAfterMilliseconds(response) {
|
|
1381
|
+
const rawMilliseconds = response.headers.get("retry-after-ms")?.trim();
|
|
1382
|
+
if (rawMilliseconds) {
|
|
1383
|
+
const milliseconds = Number(rawMilliseconds);
|
|
1384
|
+
if (Number.isFinite(milliseconds) && milliseconds >= 0) return milliseconds;
|
|
1385
|
+
}
|
|
1386
|
+
const value = response.headers.get("retry-after")?.trim();
|
|
1387
|
+
if (!value) return void 0;
|
|
1388
|
+
const seconds = Number(value);
|
|
1389
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
1390
|
+
const date = Date.parse(value);
|
|
1391
|
+
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
|
|
1392
|
+
}
|
|
1393
|
+
function retryDelayMilliseconds(response, attempt, retry) {
|
|
1394
|
+
const requested = response ? retryAfterMilliseconds(response) : void 0;
|
|
1395
|
+
const exponential = Math.min(500 * 2 ** attempt, 8e3);
|
|
1396
|
+
if (requested === void 0) return exponential;
|
|
1397
|
+
if (retry.maxRetryDelayMs > 0 && requested > retry.maxRetryDelayMs) {
|
|
1398
|
+
throw new Error(
|
|
1399
|
+
`Server requested ${Math.ceil(requested / 1e3)}s retry delay (max: ${Math.ceil(retry.maxRetryDelayMs / 1e3)}s)`
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
return requested;
|
|
1403
|
+
}
|
|
1404
|
+
async function retryHttpRequest(request, retry, signal) {
|
|
1405
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1406
|
+
let response;
|
|
1407
|
+
try {
|
|
1408
|
+
response = await request();
|
|
1409
|
+
} catch (error) {
|
|
1410
|
+
if (signal?.aborted || attempt >= retry.maxRetries) throw error;
|
|
1411
|
+
await delay(retryDelayMilliseconds(void 0, attempt, retry), void 0, signal ? { signal } : void 0);
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
if (!retryableStatus(response.status) || attempt >= retry.maxRetries) return response;
|
|
1415
|
+
let waitMs;
|
|
1416
|
+
try {
|
|
1417
|
+
waitMs = retryDelayMilliseconds(response, attempt, retry);
|
|
1418
|
+
} catch (error) {
|
|
1419
|
+
await response.body?.cancel();
|
|
1420
|
+
throw error;
|
|
1421
|
+
}
|
|
1422
|
+
await response.body?.cancel();
|
|
1423
|
+
await delay(waitMs, void 0, signal ? { signal } : void 0);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
var init_retry = __esm({
|
|
1427
|
+
"src/utils/clients/retry.ts"() {
|
|
1428
|
+
"use strict";
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1431
|
+
|
|
1432
|
+
// src/utils/clients/media/routify_media.ts
|
|
1433
|
+
import { randomUUID } from "node:crypto";
|
|
1434
|
+
function isGeminiSpeechModel(model) {
|
|
1435
|
+
return /^gemini-.*-tts(?:-|$)/.test(model);
|
|
1436
|
+
}
|
|
1437
|
+
function record2(value) {
|
|
1438
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1439
|
+
}
|
|
1440
|
+
function stringValue(value) {
|
|
1441
|
+
return typeof value === "string" ? value : "";
|
|
1442
|
+
}
|
|
1443
|
+
function modelRouterApiKey(tool, settings) {
|
|
1444
|
+
const apiKey3 = (tool === "generate_image" ? settings?.generateImageApiKey?.trim() : void 0) || settings?.apiKey?.trim();
|
|
1445
|
+
if (!apiKey3) {
|
|
1446
|
+
throw new Error("Routify media tools require harnesses.toolServices.routify.apiKey in settings.json");
|
|
1447
|
+
}
|
|
1448
|
+
return apiKey3.replace(/^Bearer\s+/i, "");
|
|
1449
|
+
}
|
|
1450
|
+
function vertexModelUrl(model, settings) {
|
|
1451
|
+
const baseUrl = (settings?.vertexBaseUrl || defaultVertexBaseUrl).replace(/\/+$/, "");
|
|
1452
|
+
return `${baseUrl}/models/${encodeURIComponent(model)}:generateContent`;
|
|
1453
|
+
}
|
|
1454
|
+
function responseDetail(payload, rawBody) {
|
|
1455
|
+
return stringValue(record2(payload.routify_response).error_message) || stringValue(record2(payload.error).message) || stringValue(payload.message) || stringValue(payload.detailMessage) || rawBody || "unknown provider error";
|
|
1456
|
+
}
|
|
1457
|
+
async function modelRouterFetch(url, init, label, options, authentication = "vertex") {
|
|
1458
|
+
const headers = new Headers(init.headers);
|
|
1459
|
+
const apiKey3 = `Bearer ${modelRouterApiKey(label, options.routify)}`;
|
|
1460
|
+
if (authentication === "bearer") headers.set("authorization", apiKey3);
|
|
1461
|
+
else headers.set("x-goog-api-key", apiKey3);
|
|
1462
|
+
const response = await retryHttpRequest(
|
|
1463
|
+
() => fetch(url, { ...init, headers }),
|
|
1464
|
+
options.retry,
|
|
1465
|
+
init.signal ?? void 0
|
|
1466
|
+
);
|
|
1467
|
+
if (response.ok) return response;
|
|
1468
|
+
const rawBody = await response.text();
|
|
1469
|
+
let payload = {};
|
|
1470
|
+
try {
|
|
1471
|
+
payload = record2(JSON.parse(rawBody));
|
|
1472
|
+
} catch {
|
|
1473
|
+
}
|
|
1474
|
+
throw new Error(`${label} failed (${response.status} ${response.statusText}): ${responseDetail(payload, rawBody).slice(0, 2e3)}`);
|
|
1475
|
+
}
|
|
1476
|
+
async function responseBytes(response, limit = maximumGeneratedFileBytes) {
|
|
1477
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
1478
|
+
if (bytes.length > limit) {
|
|
1479
|
+
throw new Error(`generated file exceeds ${limit} bytes`);
|
|
1480
|
+
}
|
|
1481
|
+
return bytes;
|
|
1482
|
+
}
|
|
1483
|
+
function parseJsonResponse(bytes, label) {
|
|
1484
|
+
try {
|
|
1485
|
+
return record2(JSON.parse(bytes.toString("utf8")));
|
|
1486
|
+
} catch {
|
|
1487
|
+
throw new Error(`${label} returned malformed JSON`);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
function responseDiagnosticMetadata(payload) {
|
|
1491
|
+
const routifyResponse = record2(payload.routify_response);
|
|
1492
|
+
const candidates = Array.isArray(payload.candidates) ? payload.candidates : [];
|
|
1493
|
+
const finishReasons = Array.from(
|
|
1494
|
+
new Set(
|
|
1495
|
+
candidates.map((candidate) => stringValue(record2(candidate).finishReason)).filter(Boolean)
|
|
1496
|
+
)
|
|
1497
|
+
);
|
|
1498
|
+
const metadata = {};
|
|
1499
|
+
const requestId = stringValue(routifyResponse.request_id) || stringValue(payload.request_id);
|
|
1500
|
+
const traceId = stringValue(routifyResponse.trace_id) || stringValue(payload.trace_id);
|
|
1501
|
+
const responseId = stringValue(payload.responseId) || stringValue(payload.response_id);
|
|
1502
|
+
const modelName = stringValue(routifyResponse.model_name) || stringValue(payload.modelVersion);
|
|
1503
|
+
const createTime = stringValue(payload.createTime) || stringValue(payload.create_time);
|
|
1504
|
+
if (requestId) metadata.request_id = requestId;
|
|
1505
|
+
if (traceId) metadata.trace_id = traceId;
|
|
1506
|
+
if (responseId) metadata.response_id = responseId;
|
|
1507
|
+
if (modelName) metadata.model_name = modelName;
|
|
1508
|
+
if (routifyResponse.status !== void 0) {
|
|
1509
|
+
metadata.provider_status = routifyResponse.status;
|
|
1510
|
+
}
|
|
1511
|
+
if (finishReasons.length) metadata.finish_reasons = finishReasons;
|
|
1512
|
+
if (createTime) metadata.create_time = createTime;
|
|
1513
|
+
if (routifyResponse.is_fall_back_triggered !== void 0) {
|
|
1514
|
+
metadata.is_fall_back_triggered = routifyResponse.is_fall_back_triggered;
|
|
1515
|
+
}
|
|
1516
|
+
return metadata;
|
|
1517
|
+
}
|
|
1518
|
+
function inlineDataFromResponse(payload, label, expectedMimePrefix) {
|
|
1519
|
+
const candidates = Array.isArray(payload.candidates) ? payload.candidates : [];
|
|
1520
|
+
for (const candidate of candidates) {
|
|
1521
|
+
const parts = Array.isArray(record2(record2(candidate).content).parts) ? record2(record2(candidate).content).parts : [];
|
|
1522
|
+
for (const part of parts) {
|
|
1523
|
+
const inlineData = record2(record2(part).inlineData);
|
|
1524
|
+
const mimeType = stringValue(inlineData.mimeType).toLowerCase();
|
|
1525
|
+
const data = stringValue(inlineData.data);
|
|
1526
|
+
if (!data || !mimeType.startsWith(expectedMimePrefix)) continue;
|
|
1527
|
+
const bytes = Buffer.from(data, "base64");
|
|
1528
|
+
if (bytes.length > maximumGeneratedFileBytes) {
|
|
1529
|
+
throw new Error(
|
|
1530
|
+
`generated file exceeds ${maximumGeneratedFileBytes} bytes`
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
return { bytes, mimeType };
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
return missingMediaData(payload, label, expectedMimePrefix);
|
|
1537
|
+
}
|
|
1538
|
+
function missingMediaData(payload, label, expectedMimePrefix) {
|
|
1539
|
+
const diagnosticMetadata = JSON.stringify(
|
|
1540
|
+
responseDiagnosticMetadata(payload)
|
|
1541
|
+
);
|
|
1542
|
+
const upstreamResponse = JSON.stringify(payload);
|
|
1543
|
+
const message = `${label} response did not include ${expectedMimePrefix} data. Diagnostic metadata: ${diagnosticMetadata}. Upstream response: ${upstreamResponse}`;
|
|
1544
|
+
console.error(`[model-router-media] ${message}`);
|
|
1545
|
+
throw new Error(message);
|
|
1546
|
+
}
|
|
1547
|
+
function geminiImageConfig(size) {
|
|
1548
|
+
const match = size.replace("*", "x").match(/^(\d+)x(\d+)$/i);
|
|
1549
|
+
const width = Number(match?.[1] || 1024);
|
|
1550
|
+
const height = Number(match?.[2] || 1024);
|
|
1551
|
+
const ratio = width > 0 && height > 0 ? width / height : 1;
|
|
1552
|
+
const [aspectRatio] = imageAspectRatios.reduce(
|
|
1553
|
+
(best, candidate) => Math.abs(Math.log(candidate[1] / ratio)) < Math.abs(Math.log(best[1] / ratio)) ? candidate : best
|
|
1554
|
+
);
|
|
1555
|
+
const maximumDimension = Math.max(width, height);
|
|
1556
|
+
const imageSize = maximumDimension > 2048 ? "4K" : maximumDimension > 1024 ? "2K" : "1K";
|
|
1557
|
+
return { aspectRatio, imageSize };
|
|
1558
|
+
}
|
|
1559
|
+
async function generateImageWithModelRouter(options) {
|
|
1560
|
+
if (options.model.startsWith("gpt-image-")) {
|
|
1561
|
+
return generateOpenAIImage(options);
|
|
1562
|
+
}
|
|
1563
|
+
const parts = [{ text: options.prompt }];
|
|
1564
|
+
for (const image of options.images || []) {
|
|
1565
|
+
parts.push({
|
|
1566
|
+
inlineData: {
|
|
1567
|
+
mimeType: image.mimeType,
|
|
1568
|
+
data: image.bytes.toString("base64")
|
|
1569
|
+
}
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
const response = await modelRouterFetch(
|
|
1573
|
+
vertexModelUrl(options.model, options.routify),
|
|
1574
|
+
{
|
|
1575
|
+
method: "POST",
|
|
1576
|
+
headers: { "content-type": "application/json" },
|
|
1577
|
+
body: JSON.stringify({
|
|
1578
|
+
contents: [{ role: "user", parts }],
|
|
1579
|
+
generationConfig: {
|
|
1580
|
+
responseModalities: ["IMAGE"],
|
|
1581
|
+
imageConfig: geminiImageConfig(options.size)
|
|
1582
|
+
}
|
|
1583
|
+
}),
|
|
1584
|
+
signal: options.signal
|
|
1585
|
+
},
|
|
1586
|
+
"generate_image",
|
|
1587
|
+
options
|
|
1588
|
+
);
|
|
1589
|
+
const payload = parseJsonResponse(
|
|
1590
|
+
await responseBytes(response, maximumJsonResponseBytes),
|
|
1591
|
+
"generate_image"
|
|
1592
|
+
);
|
|
1593
|
+
return inlineDataFromResponse(payload, "generate_image", "image/");
|
|
1594
|
+
}
|
|
1595
|
+
async function generateOpenAIImage(options) {
|
|
1596
|
+
const baseUrl = (options.routify?.openaiBaseUrl || defaultOpenAIBaseUrl).replace(/\/+$/, "");
|
|
1597
|
+
const parameters = {
|
|
1598
|
+
model: options.model,
|
|
1599
|
+
prompt: options.prompt,
|
|
1600
|
+
n: 1,
|
|
1601
|
+
size: options.size.replace("*", "x"),
|
|
1602
|
+
output_format: "png"
|
|
1603
|
+
};
|
|
1604
|
+
const images = options.images || [];
|
|
1605
|
+
const editing = images.length > 0;
|
|
1606
|
+
let body = JSON.stringify(parameters);
|
|
1607
|
+
if (editing) {
|
|
1608
|
+
const form = new FormData();
|
|
1609
|
+
for (const [name, value] of Object.entries(parameters)) {
|
|
1610
|
+
form.append(name, String(value));
|
|
1611
|
+
}
|
|
1612
|
+
for (const image of images) {
|
|
1613
|
+
form.append(
|
|
1614
|
+
"image[]",
|
|
1615
|
+
new Blob([new Uint8Array(image.bytes)], { type: image.mimeType }),
|
|
1616
|
+
image.fileName
|
|
1617
|
+
);
|
|
1618
|
+
}
|
|
1619
|
+
body = form;
|
|
1620
|
+
}
|
|
1621
|
+
const response = await modelRouterFetch(
|
|
1622
|
+
`${baseUrl}/images/${editing ? "edits" : "generations"}`,
|
|
1623
|
+
{
|
|
1624
|
+
method: "POST",
|
|
1625
|
+
...editing ? {} : { headers: { "content-type": "application/json" } },
|
|
1626
|
+
body,
|
|
1627
|
+
signal: options.signal
|
|
1628
|
+
},
|
|
1629
|
+
"generate_image",
|
|
1630
|
+
options,
|
|
1631
|
+
"bearer"
|
|
1632
|
+
);
|
|
1633
|
+
const payload = parseJsonResponse(
|
|
1634
|
+
await responseBytes(response, maximumJsonResponseBytes),
|
|
1635
|
+
"generate_image"
|
|
1636
|
+
);
|
|
1637
|
+
const data = Array.isArray(payload.data) ? payload.data : [];
|
|
1638
|
+
for (const item of data) {
|
|
1639
|
+
const encodedImage = stringValue(record2(item).b64_json);
|
|
1640
|
+
if (!encodedImage) continue;
|
|
1641
|
+
const bytes = Buffer.from(encodedImage, "base64");
|
|
1642
|
+
if (bytes.length > maximumGeneratedFileBytes) {
|
|
1643
|
+
throw new Error(`generated file exceeds ${maximumGeneratedFileBytes} bytes`);
|
|
1644
|
+
}
|
|
1645
|
+
if (bytes.length) return { bytes, mimeType: "image/png" };
|
|
1646
|
+
}
|
|
1647
|
+
return missingMediaData(payload, "generate_image", "image/");
|
|
1648
|
+
}
|
|
1649
|
+
function validateSpeechAudio(bytes, format) {
|
|
1650
|
+
const matches = format === "wav" ? bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WAVE" : format === "opus" ? bytes.length >= 4 && bytes.subarray(0, 4).toString("ascii") === "OggS" : bytes.length >= 3 && (bytes.subarray(0, 3).toString("ascii") === "ID3" || bytes[0] === 255 && (bytes[1] & 224) === 224);
|
|
1651
|
+
if (!matches) {
|
|
1652
|
+
throw new Error(
|
|
1653
|
+
`ModelRouter TTS returned data that does not match requested ${format} output`
|
|
1654
|
+
);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
async function generateSpeechWithModelRouter(options) {
|
|
1658
|
+
if (isGeminiSpeechModel(options.model)) return generateGeminiSpeech(options);
|
|
1659
|
+
if (options.model !== "doubao-tts") throw new Error(`Unsupported speech model: ${options.model}`);
|
|
1660
|
+
const response = await modelRouterFetch(
|
|
1661
|
+
doubaoSpeechUrl,
|
|
1662
|
+
{
|
|
1663
|
+
method: "POST",
|
|
1664
|
+
headers: { "content-type": "application/json" },
|
|
1665
|
+
body: JSON.stringify({
|
|
1666
|
+
app: {
|
|
1667
|
+
appid: "4972772213",
|
|
1668
|
+
token: "access_token",
|
|
1669
|
+
cluster: "volcano_tts"
|
|
1670
|
+
},
|
|
1671
|
+
user: { uid: "arena-agent" },
|
|
1672
|
+
audio: {
|
|
1673
|
+
voice_type: options.voice,
|
|
1674
|
+
encoding: options.format === "opus" ? "ogg_opus" : options.format,
|
|
1675
|
+
speed_ratio: 1
|
|
1676
|
+
},
|
|
1677
|
+
request: {
|
|
1678
|
+
reqid: randomUUID().replaceAll("-", ""),
|
|
1679
|
+
text: options.text,
|
|
1680
|
+
operation: "query"
|
|
1681
|
+
},
|
|
1682
|
+
model: options.model
|
|
1683
|
+
}),
|
|
1684
|
+
signal: options.signal
|
|
1685
|
+
},
|
|
1686
|
+
"generate_speech",
|
|
1687
|
+
options,
|
|
1688
|
+
"bearer"
|
|
1689
|
+
);
|
|
1690
|
+
const payload = parseJsonResponse(
|
|
1691
|
+
await responseBytes(response, maximumJsonResponseBytes),
|
|
1692
|
+
"generate_speech"
|
|
1693
|
+
);
|
|
1694
|
+
const code = Number(payload.code);
|
|
1695
|
+
const encodedAudio = stringValue(payload.data);
|
|
1696
|
+
if (code !== 3e3 || !encodedAudio) {
|
|
1697
|
+
throw new Error(
|
|
1698
|
+
`generate_speech failed (${Number.isFinite(code) ? code : "unknown"}): ${responseDetail(
|
|
1699
|
+
payload,
|
|
1700
|
+
""
|
|
1701
|
+
).slice(0, 2e3)}`
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
const bytes = Buffer.from(encodedAudio, "base64");
|
|
1705
|
+
if (bytes.length > maximumGeneratedFileBytes) {
|
|
1706
|
+
throw new Error(`generated file exceeds ${maximumGeneratedFileBytes} bytes`);
|
|
1707
|
+
}
|
|
1708
|
+
validateSpeechAudio(bytes, options.format);
|
|
1709
|
+
return bytes;
|
|
1710
|
+
}
|
|
1711
|
+
async function generateGeminiSpeech(options) {
|
|
1712
|
+
const response = await modelRouterFetch(vertexModelUrl(options.model, options.routify), {
|
|
1713
|
+
method: "POST",
|
|
1714
|
+
headers: { "content-type": "application/json" },
|
|
1715
|
+
body: JSON.stringify({
|
|
1716
|
+
contents: [{ role: "user", parts: [{ text: options.text }] }],
|
|
1717
|
+
generationConfig: {
|
|
1718
|
+
responseModalities: ["AUDIO"],
|
|
1719
|
+
speechConfig: {
|
|
1720
|
+
...options.language ? { languageCode: options.language } : {},
|
|
1721
|
+
voiceConfig: { prebuiltVoiceConfig: { voiceName: options.voice } }
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
}),
|
|
1725
|
+
signal: options.signal
|
|
1726
|
+
}, "generate_speech", options);
|
|
1727
|
+
const payload = parseJsonResponse(await responseBytes(response, maximumJsonResponseBytes), "generate_speech");
|
|
1728
|
+
const candidates = Array.isArray(payload.candidates) ? payload.candidates : [];
|
|
1729
|
+
const candidate = record2(candidates[0]);
|
|
1730
|
+
const promptFeedback = record2(payload.promptFeedback);
|
|
1731
|
+
const filteringReasons = /* @__PURE__ */ new Set(["SAFETY", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"]);
|
|
1732
|
+
if (filteringReasons.has(stringValue(promptFeedback.blockReason)) || filteringReasons.has(stringValue(candidate.finishReason))) {
|
|
1733
|
+
throw new Error(
|
|
1734
|
+
"The speech text was declined by a content filter and no audio was generated. Rephrase the text and try again, or deliver it as written."
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
1737
|
+
if (candidate.finishReason && candidate.finishReason !== "STOP") {
|
|
1738
|
+
throw new Error(`generate_speech did not complete: ${String(candidate.finishReason)}`);
|
|
1739
|
+
}
|
|
1740
|
+
const content = record2(candidate.content);
|
|
1741
|
+
const parts = Array.isArray(content.parts) ? content.parts : [];
|
|
1742
|
+
let pcm;
|
|
1743
|
+
const chunks = [];
|
|
1744
|
+
let length = 0;
|
|
1745
|
+
for (const rawPart of parts) {
|
|
1746
|
+
const part = record2(rawPart);
|
|
1747
|
+
if (part.thought) continue;
|
|
1748
|
+
const data = record2(part.inlineData);
|
|
1749
|
+
const mime = stringValue(data.mimeType).toLowerCase();
|
|
1750
|
+
if (!mime.startsWith("audio/")) continue;
|
|
1751
|
+
if (!/^audio\/(?:l16|pcm)(?:;|$)/.test(mime)) throw new Error(`Unsupported Gemini speech MIME type: ${mime}`);
|
|
1752
|
+
const sampleRate = Number(/(?:^|;)\s*rate\s*=\s*(\d+)\s*(?:;|$)/.exec(mime)?.[1]);
|
|
1753
|
+
const channelMatch = /(?:^|;)\s*channels\s*=\s*(\d+)\s*(?:;|$)/.exec(mime);
|
|
1754
|
+
const channels = channelMatch ? Number(channelMatch[1]) : 1;
|
|
1755
|
+
if (pcm && (pcm.sampleRate !== sampleRate || pcm.channels !== channels)) throw new Error("Gemini speech PCM format changed between parts");
|
|
1756
|
+
const bytes2 = Buffer.from(stringValue(data.data), "base64");
|
|
1757
|
+
length += bytes2.length;
|
|
1758
|
+
if (length > maximumGeneratedFileBytes) throw new Error("Gemini speech PCM exceeds the size limit");
|
|
1759
|
+
pcm = { bytes: bytes2, sampleRate, channels };
|
|
1760
|
+
chunks.push(bytes2);
|
|
1761
|
+
}
|
|
1762
|
+
if (!pcm || !length) throw new Error(`generate_speech response did not include PCM audio: ${JSON.stringify(responseDiagnosticMetadata(payload))}`);
|
|
1763
|
+
const bytes = await encodeSpeechPcm({ ...pcm, bytes: Buffer.concat(chunks) }, options.format, options.signal);
|
|
1764
|
+
validateSpeechAudio(bytes, options.format);
|
|
1765
|
+
return bytes;
|
|
1766
|
+
}
|
|
1767
|
+
var defaultVertexBaseUrl, defaultOpenAIBaseUrl, doubaoSpeechUrl, maximumGeneratedFileBytes, maximumJsonResponseBytes, imageAspectRatios;
|
|
1768
|
+
var init_routify_media = __esm({
|
|
1769
|
+
"src/utils/clients/media/routify_media.ts"() {
|
|
1770
|
+
"use strict";
|
|
1771
|
+
init_speech_audio();
|
|
1772
|
+
init_retry();
|
|
1773
|
+
defaultVertexBaseUrl = "https://routify-pub.alibaba-inc.com/protocol/vertex/v1beta";
|
|
1774
|
+
defaultOpenAIBaseUrl = "https://routify-pub.alibaba-inc.com/protocol/openai/v1";
|
|
1775
|
+
doubaoSpeechUrl = "https://routify-pub.alibaba-inc.com/protocol/volcengine/api/v1/tts";
|
|
1776
|
+
maximumGeneratedFileBytes = 25 * 1024 * 1024;
|
|
1777
|
+
maximumJsonResponseBytes = 35 * 1024 * 1024;
|
|
1778
|
+
imageAspectRatios = [
|
|
1779
|
+
["1:1", 1],
|
|
1780
|
+
["2:3", 2 / 3],
|
|
1781
|
+
["3:2", 3 / 2],
|
|
1782
|
+
["3:4", 3 / 4],
|
|
1783
|
+
["4:3", 4 / 3],
|
|
1784
|
+
["4:5", 4 / 5],
|
|
1785
|
+
["5:4", 5 / 4],
|
|
1786
|
+
["9:16", 9 / 16],
|
|
1787
|
+
["16:9", 16 / 9],
|
|
1788
|
+
["21:9", 21 / 9]
|
|
1789
|
+
];
|
|
1790
|
+
}
|
|
1791
|
+
});
|
|
1792
|
+
|
|
1793
|
+
// src/utils/clients/media/generated_image.ts
|
|
1794
|
+
import { decode as decodeWebp } from "@stacksjs/ts-webp";
|
|
1795
|
+
import * as bmp from "bmp-js";
|
|
1796
|
+
import * as jpeg from "jpeg-js";
|
|
1797
|
+
import { GifReader } from "omggif";
|
|
1798
|
+
import { PNG } from "pngjs";
|
|
1799
|
+
function pngSize(bytes) {
|
|
1800
|
+
if (bytes.length < 24 || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
1801
|
+
return void 0;
|
|
1802
|
+
}
|
|
1803
|
+
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
|
|
1804
|
+
}
|
|
1805
|
+
function jpegSize(bytes) {
|
|
1806
|
+
if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) {
|
|
1807
|
+
return void 0;
|
|
1808
|
+
}
|
|
1809
|
+
let offset = 2;
|
|
1810
|
+
while (offset + 8 < bytes.length) {
|
|
1811
|
+
if (bytes[offset] !== 255) {
|
|
1812
|
+
offset += 1;
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
while (bytes[offset] === 255) offset += 1;
|
|
1816
|
+
const marker = bytes[offset];
|
|
1817
|
+
if (marker === void 0 || marker === 217 || marker === 218) break;
|
|
1818
|
+
if (marker === 1 || marker >= 208 && marker <= 215) {
|
|
1819
|
+
offset += 1;
|
|
1820
|
+
continue;
|
|
1821
|
+
}
|
|
1822
|
+
if (offset + 2 >= bytes.length) break;
|
|
1823
|
+
const length = bytes.readUInt16BE(offset + 1);
|
|
1824
|
+
if (length < 2 || offset + 1 + length > bytes.length) break;
|
|
1825
|
+
if (marker >= 192 && marker <= 195 || marker >= 197 && marker <= 199 || marker >= 201 && marker <= 203 || marker >= 205 && marker <= 207) {
|
|
1826
|
+
return {
|
|
1827
|
+
width: bytes.readUInt16BE(offset + 6),
|
|
1828
|
+
height: bytes.readUInt16BE(offset + 4)
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
offset += 1 + length;
|
|
1832
|
+
}
|
|
1833
|
+
return void 0;
|
|
1834
|
+
}
|
|
1835
|
+
function webpSize(bytes) {
|
|
1836
|
+
if (bytes.length < 30 || bytes.subarray(0, 4).toString("ascii") !== "RIFF" || bytes.subarray(8, 12).toString("ascii") !== "WEBP") {
|
|
1837
|
+
return void 0;
|
|
1838
|
+
}
|
|
1839
|
+
const format = bytes.subarray(12, 16).toString("ascii");
|
|
1840
|
+
if (format === "VP8 ") {
|
|
1841
|
+
return {
|
|
1842
|
+
width: bytes.readUInt16LE(26) & 16383,
|
|
1843
|
+
height: bytes.readUInt16LE(28) & 16383
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
if (format === "VP8L" && bytes[20] === 47) {
|
|
1847
|
+
const bits = bytes.readUInt32LE(21);
|
|
1848
|
+
return {
|
|
1849
|
+
width: (bits & 16383) + 1,
|
|
1850
|
+
height: (bits >> 14 & 16383) + 1
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
if (format === "VP8X") {
|
|
1854
|
+
return {
|
|
1855
|
+
width: bytes.readUIntLE(24, 3) + 1,
|
|
1856
|
+
height: bytes.readUIntLE(27, 3) + 1
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
return void 0;
|
|
1860
|
+
}
|
|
1861
|
+
function normalizedImageMimeType(mimeType) {
|
|
1862
|
+
const normalized = mimeType.split(";")[0]?.trim().toLowerCase() || "";
|
|
1863
|
+
return normalized === "image/jpg" ? "image/jpeg" : normalized;
|
|
1864
|
+
}
|
|
1865
|
+
function detectedImageMimeType(bytes) {
|
|
1866
|
+
if (pngSize(bytes)) return "image/png";
|
|
1867
|
+
if (jpegSize(bytes)) return "image/jpeg";
|
|
1868
|
+
if (webpSize(bytes)) return "image/webp";
|
|
1869
|
+
if (bytes.length >= 10 && ["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii"))) {
|
|
1870
|
+
return "image/gif";
|
|
1871
|
+
}
|
|
1872
|
+
if (bytes.length >= 26 && bytes[0] === 66 && bytes[1] === 77) {
|
|
1873
|
+
return "image/bmp";
|
|
1874
|
+
}
|
|
1875
|
+
return void 0;
|
|
1876
|
+
}
|
|
1877
|
+
async function decodedImage(bytes, mimeType) {
|
|
1878
|
+
if (mimeType === "image/png") {
|
|
1879
|
+
const decoded = PNG.sync.read(bytes);
|
|
1880
|
+
return {
|
|
1881
|
+
width: decoded.width,
|
|
1882
|
+
height: decoded.height,
|
|
1883
|
+
data: decoded.data
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
if (mimeType === "image/jpeg") {
|
|
1887
|
+
return jpeg.decode(bytes, {
|
|
1888
|
+
useTArray: true,
|
|
1889
|
+
formatAsRGBA: true,
|
|
1890
|
+
tolerantDecoding: false,
|
|
1891
|
+
maxResolutionInMP: 64,
|
|
1892
|
+
maxMemoryUsageInMB: 512
|
|
1893
|
+
});
|
|
1894
|
+
}
|
|
1895
|
+
if (mimeType === "image/webp") {
|
|
1896
|
+
return decodeWebp(bytes);
|
|
1897
|
+
}
|
|
1898
|
+
if (mimeType === "image/gif") {
|
|
1899
|
+
const reader = new GifReader(bytes);
|
|
1900
|
+
const data = new Uint8Array(reader.width * reader.height * 4);
|
|
1901
|
+
reader.decodeAndBlitFrameRGBA(0, data);
|
|
1902
|
+
return { width: reader.width, height: reader.height, data };
|
|
1903
|
+
}
|
|
1904
|
+
if (mimeType === "image/bmp") {
|
|
1905
|
+
const decoded = bmp.decode(bytes);
|
|
1906
|
+
const rgba = Buffer.alloc(decoded.width * decoded.height * 4);
|
|
1907
|
+
for (let offset = 0; offset < rgba.length; offset += 4) {
|
|
1908
|
+
rgba[offset] = decoded.data[offset + 3] ?? 0;
|
|
1909
|
+
rgba[offset + 1] = decoded.data[offset + 2] ?? 0;
|
|
1910
|
+
rgba[offset + 2] = decoded.data[offset + 1] ?? 0;
|
|
1911
|
+
rgba[offset + 3] = decoded.data[offset] ?? 255;
|
|
1912
|
+
}
|
|
1913
|
+
return { width: decoded.width, height: decoded.height, data: rgba };
|
|
1914
|
+
}
|
|
1915
|
+
return void 0;
|
|
1916
|
+
}
|
|
1917
|
+
function rgbaOnWhite(source) {
|
|
1918
|
+
const result = new Uint8Array(source.data.length);
|
|
1919
|
+
for (let offset = 0; offset < source.data.length; offset += 4) {
|
|
1920
|
+
const alpha = (source.data[offset + 3] ?? 255) / 255;
|
|
1921
|
+
for (let channel = 0; channel < 3; channel += 1) {
|
|
1922
|
+
result[offset + channel] = Math.round(
|
|
1923
|
+
(source.data[offset + channel] ?? 0) * alpha + 255 * (1 - alpha)
|
|
1924
|
+
);
|
|
1925
|
+
}
|
|
1926
|
+
result[offset + 3] = 255;
|
|
1927
|
+
}
|
|
1928
|
+
return result;
|
|
1929
|
+
}
|
|
1930
|
+
async function generatedImageBytesForExtension(bytes, declaredMimeType, extension) {
|
|
1931
|
+
const targetMimeType = [".jpg", ".jpeg"].includes(extension.toLowerCase()) ? "image/jpeg" : extension.toLowerCase() === ".png" ? "image/png" : void 0;
|
|
1932
|
+
if (!targetMimeType) {
|
|
1933
|
+
throw new Error(`unsupported generated image extension: ${extension}`);
|
|
1934
|
+
}
|
|
1935
|
+
const sourceMimeType = detectedImageMimeType(bytes) || normalizedImageMimeType(declaredMimeType);
|
|
1936
|
+
if (sourceMimeType === targetMimeType) return bytes;
|
|
1937
|
+
let image;
|
|
1938
|
+
try {
|
|
1939
|
+
image = await decodedImage(bytes, sourceMimeType);
|
|
1940
|
+
} catch {
|
|
1941
|
+
}
|
|
1942
|
+
if (!image) {
|
|
1943
|
+
throw new Error(
|
|
1944
|
+
`generated ${sourceMimeType || "image"} data could not be converted to ${targetMimeType}`
|
|
1945
|
+
);
|
|
1946
|
+
}
|
|
1947
|
+
if (targetMimeType === "image/jpeg") {
|
|
1948
|
+
return Buffer.from(
|
|
1949
|
+
jpeg.encode(
|
|
1950
|
+
{
|
|
1951
|
+
data: rgbaOnWhite(image),
|
|
1952
|
+
width: image.width,
|
|
1953
|
+
height: image.height
|
|
1954
|
+
},
|
|
1955
|
+
jpegQuality
|
|
1956
|
+
).data
|
|
1957
|
+
);
|
|
1958
|
+
}
|
|
1959
|
+
const output = new PNG({ width: image.width, height: image.height });
|
|
1960
|
+
output.data = Buffer.from(image.data);
|
|
1961
|
+
return PNG.sync.write(output);
|
|
1962
|
+
}
|
|
1963
|
+
var jpegQuality;
|
|
1964
|
+
var init_generated_image = __esm({
|
|
1965
|
+
"src/utils/clients/media/generated_image.ts"() {
|
|
1966
|
+
"use strict";
|
|
1967
|
+
jpegQuality = 92;
|
|
1968
|
+
}
|
|
1969
|
+
});
|
|
1970
|
+
|
|
1335
1971
|
// src/capabilities/tools/media/generate_image.ts
|
|
1336
|
-
import { mkdir as mkdir2, readFile as
|
|
1337
|
-
import
|
|
1338
|
-
import { setTimeout as delay2 } from "node:timers/promises";
|
|
1972
|
+
import { mkdir as mkdir2, readFile as readFile5, writeFile as writeFile2 } from "node:fs/promises";
|
|
1973
|
+
import path7 from "node:path";
|
|
1339
1974
|
import { defineTool as defineTool6 } from "@earendil-works/pi-coding-agent";
|
|
1340
1975
|
import { Type as Type6 } from "typebox";
|
|
1341
|
-
function createGenerateImageTool(cwd, variant, settings,
|
|
1976
|
+
function createGenerateImageTool(cwd, variant, settings, routify, retry) {
|
|
1342
1977
|
let generatedCount = 0;
|
|
1343
|
-
const parameters = variant === "agent-arena" ? agentArenaSchema2 : codeSchema2;
|
|
1344
1978
|
return defineTool6({
|
|
1345
1979
|
name: "generate_image",
|
|
1346
1980
|
label: "Generate Image",
|
|
1347
|
-
description: "Generate an image with
|
|
1981
|
+
description: "Generate an image with Routify and save it into the workspace." + (variant === "code" ? " At most 10 generation requests per session." : ""),
|
|
1348
1982
|
promptSnippet: "Generate or edit an image",
|
|
1349
|
-
parameters,
|
|
1350
|
-
async execute(
|
|
1351
|
-
if (generatedCount >= 10) {
|
|
1352
|
-
return jsonToolResult({ status: "error", message: "generate_image can be used at most 10 times per session" });
|
|
1353
|
-
}
|
|
1354
|
-
generatedCount += 1;
|
|
1983
|
+
parameters: variant === "agent-arena" ? agentArenaSchema2 : codeSchema2,
|
|
1984
|
+
async execute(_id, rawParams, signal) {
|
|
1355
1985
|
const params = rawParams;
|
|
1356
1986
|
const target = await resolveWorkspacePath(cwd, params.file_path);
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
await mkdir2(path6.dirname(target), { recursive: true });
|
|
1361
|
-
const model = settings?.model || "qwen-image-2.0-pro";
|
|
1362
|
-
const synchronous = model.startsWith("qwen-image-2.0");
|
|
1363
|
-
const content = [];
|
|
1987
|
+
const extension = path7.extname(target).toLowerCase();
|
|
1988
|
+
if (![".jpg", ".jpeg", ".png"].includes(extension)) throw new Error("file_path must end in .jpg, .jpeg, or .png");
|
|
1989
|
+
const images = [];
|
|
1364
1990
|
for (const rawPath of params.images || []) {
|
|
1365
1991
|
const source = await resolveWorkspacePath(cwd, rawPath);
|
|
1366
|
-
const mimeType = imageMimeTypes2[
|
|
1992
|
+
const mimeType = imageMimeTypes2[path7.extname(source).toLowerCase()];
|
|
1367
1993
|
if (!mimeType) throw new Error(`unsupported reference image format: ${rawPath}`);
|
|
1368
|
-
const
|
|
1369
|
-
if (
|
|
1370
|
-
|
|
1994
|
+
const bytes2 = await readFile5(source);
|
|
1995
|
+
if (bytes2.length > 20 * 1024 * 1024) throw new Error(`reference image exceeds 20 MB: ${rawPath}`);
|
|
1996
|
+
images.push({ bytes: bytes2, fileName: path7.basename(source), mimeType });
|
|
1371
1997
|
}
|
|
1372
|
-
|
|
1373
|
-
const
|
|
1374
|
-
|
|
1375
|
-
{
|
|
1376
|
-
method: "POST",
|
|
1377
|
-
headers: {
|
|
1378
|
-
"content-type": "application/json",
|
|
1379
|
-
...synchronous ? {} : { "x-dashscope-async": "enable" }
|
|
1380
|
-
},
|
|
1381
|
-
body: JSON.stringify({
|
|
1382
|
-
model,
|
|
1383
|
-
input: { messages: [{ role: "user", content }] },
|
|
1384
|
-
parameters: {
|
|
1385
|
-
size: settings?.size || (synchronous ? "2048*2048" : "2K"),
|
|
1386
|
-
watermark: false,
|
|
1387
|
-
...synchronous ? { prompt_extend: true } : { n: 1 }
|
|
1388
|
-
}
|
|
1389
|
-
}),
|
|
1390
|
-
signal
|
|
1391
|
-
},
|
|
1392
|
-
"generate_image"
|
|
1393
|
-
);
|
|
1394
|
-
let completed = submitted;
|
|
1395
|
-
if (!synchronous) {
|
|
1396
|
-
const taskId = String(objectValue(submitted.output).task_id || "");
|
|
1397
|
-
if (!taskId) throw new Error("generate_image returned no task_id");
|
|
1398
|
-
const deadline = Date.now() + (settings?.taskTimeoutMs || 5 * 6e4);
|
|
1399
|
-
const interval = settings?.taskPollIntervalMs || 1e3;
|
|
1400
|
-
while (Date.now() <= deadline) {
|
|
1401
|
-
completed = await dashScope.json(`/tasks/${encodeURIComponent(taskId)}`, { method: "GET", signal }, "generate_image status");
|
|
1402
|
-
const status = String(objectValue(completed.output).task_status || "").toUpperCase();
|
|
1403
|
-
if (status === "SUCCEEDED") break;
|
|
1404
|
-
if (["FAILED", "CANCELED", "UNKNOWN"].includes(status)) throw new Error(`generate_image task ${status}`);
|
|
1405
|
-
await delay2(interval, void 0, signal ? { signal } : void 0);
|
|
1406
|
-
}
|
|
1998
|
+
const defaults = variant === "agent-arena" ? ["gemini-3.1-flash-image", "gpt-image-2"] : ["gpt-image-2.5-sunburst", "gpt-image-2.5-flare"];
|
|
1999
|
+
const model = settings?.model || defaults[Math.floor(Math.random() * defaults.length)];
|
|
2000
|
+
if (!/^(?:gpt-image-|gemini-)/.test(model)) {
|
|
2001
|
+
throw new Error(`Unsupported Routify image model: ${model}. Set harnesses.tools.generateImage.model to a Gemini or GPT Image model, or remove it to use Arena defaults.`);
|
|
1407
2002
|
}
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
const
|
|
1417
|
-
|
|
1418
|
-
|
|
2003
|
+
signal?.throwIfAborted();
|
|
2004
|
+
if (variant === "code") {
|
|
2005
|
+
if (generatedCount >= 10) return {
|
|
2006
|
+
...jsonToolResult({ status: "error", message: "generate_image can be used at most 10 times per session" }),
|
|
2007
|
+
isError: true
|
|
2008
|
+
};
|
|
2009
|
+
generatedCount += 1;
|
|
2010
|
+
}
|
|
2011
|
+
const generated = await generateImageWithModelRouter({
|
|
2012
|
+
model,
|
|
2013
|
+
prompt: params.prompt,
|
|
2014
|
+
images,
|
|
2015
|
+
size: settings?.size || "1024*1024",
|
|
2016
|
+
signal,
|
|
2017
|
+
routify,
|
|
2018
|
+
retry
|
|
2019
|
+
});
|
|
2020
|
+
const bytes = await generatedImageBytesForExtension(generated.bytes, generated.mimeType, extension);
|
|
2021
|
+
signal?.throwIfAborted();
|
|
2022
|
+
await mkdir2(path7.dirname(target), { recursive: true });
|
|
2023
|
+
await writeFile2(target, bytes);
|
|
1419
2024
|
const relativePath = workspaceRelativePath(cwd, target);
|
|
1420
2025
|
return jsonToolResult(variant === "agent-arena" ? { status: "success", file_path: relativePath } : { status: "success", message: `Image saved to ${relativePath}` });
|
|
1421
2026
|
}
|
|
@@ -1425,67 +2030,63 @@ var agentArenaSchema2, codeSchema2, imageMimeTypes2;
|
|
|
1425
2030
|
var init_generate_image = __esm({
|
|
1426
2031
|
"src/capabilities/tools/media/generate_image.ts"() {
|
|
1427
2032
|
"use strict";
|
|
1428
|
-
|
|
2033
|
+
init_routify_media();
|
|
2034
|
+
init_generated_image();
|
|
1429
2035
|
init_workspace();
|
|
1430
2036
|
agentArenaSchema2 = Type6.Object({
|
|
1431
2037
|
file_path: Type6.String(),
|
|
1432
2038
|
prompt: Type6.String(),
|
|
1433
2039
|
images: Type6.Optional(Type6.Array(Type6.String(), { maxItems: 10 }))
|
|
1434
2040
|
}, { additionalProperties: false });
|
|
1435
|
-
codeSchema2 = Type6.Object({
|
|
1436
|
-
file_path: Type6.String(),
|
|
1437
|
-
prompt: Type6.String()
|
|
1438
|
-
}, { additionalProperties: false });
|
|
2041
|
+
codeSchema2 = Type6.Object({ file_path: Type6.String(), prompt: Type6.String() }, { additionalProperties: false });
|
|
1439
2042
|
imageMimeTypes2 = {
|
|
1440
2043
|
".jpg": "image/jpeg",
|
|
1441
2044
|
".jpeg": "image/jpeg",
|
|
1442
2045
|
".png": "image/png",
|
|
1443
|
-
".webp": "image/webp"
|
|
2046
|
+
".webp": "image/webp",
|
|
2047
|
+
".gif": "image/gif",
|
|
2048
|
+
".bmp": "image/bmp"
|
|
1444
2049
|
};
|
|
1445
2050
|
}
|
|
1446
2051
|
});
|
|
1447
2052
|
|
|
1448
2053
|
// src/capabilities/tools/media/generate_speech.ts
|
|
1449
|
-
import { mkdir as mkdir3, writeFile as
|
|
1450
|
-
import
|
|
2054
|
+
import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
|
|
2055
|
+
import path8 from "node:path";
|
|
1451
2056
|
import { defineTool as defineTool7 } from "@earendil-works/pi-coding-agent";
|
|
1452
2057
|
import { Type as Type7 } from "typebox";
|
|
1453
|
-
function createGenerateSpeechTool(cwd, settings,
|
|
2058
|
+
function createGenerateSpeechTool(cwd, settings, routify, retry) {
|
|
1454
2059
|
return defineTool7({
|
|
1455
2060
|
name: "generate_speech",
|
|
1456
2061
|
label: "Generate Speech",
|
|
1457
|
-
description: "Synthesize spoken audio with
|
|
2062
|
+
description: "Synthesize spoken audio with Routify and save it into the workspace.",
|
|
1458
2063
|
promptSnippet: "Generate spoken audio",
|
|
1459
2064
|
parameters: schema2,
|
|
1460
|
-
async execute(
|
|
2065
|
+
async execute(_id, params, signal) {
|
|
1461
2066
|
const target = await resolveWorkspacePath(cwd, params.file_path);
|
|
1462
|
-
const format = { ".mp3": "mp3", ".wav": "wav", ".opus": "opus" }[
|
|
1463
|
-
if (!format) throw new Error("
|
|
1464
|
-
|
|
2067
|
+
const format = { ".mp3": "mp3", ".wav": "wav", ".ogg": "opus", ".opus": "opus" }[path8.extname(target).toLowerCase()];
|
|
2068
|
+
if (!format) throw new Error("Routify speech output supports .mp3, .wav, .ogg, or .opus");
|
|
2069
|
+
const model = settings?.model || "gemini-3.1-flash-tts-preview";
|
|
2070
|
+
if (!isGeminiSpeechModel(model) && model !== "doubao-tts") {
|
|
2071
|
+
throw new Error(`Unsupported Routify speech model: ${model}. Set harnesses.tools.generateSpeech.model to a Gemini TTS model or doubao-tts, or remove it to use Arena defaults.`);
|
|
2072
|
+
}
|
|
1465
2073
|
const primaryLanguage = params.language.toLowerCase().split(/[-_]/u, 1)[0] || "en";
|
|
1466
2074
|
const masculine = params.voice_identity?.gender === "masculine";
|
|
1467
|
-
const voices = primaryLanguage === "en" ? masculine ? ["
|
|
1468
|
-
const voice = settings?.voice || voices[(params.voice_identity?.index || 0) % voices.length];
|
|
1469
|
-
const
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
signal
|
|
1483
|
-
}, "generate_speech");
|
|
1484
|
-
const audioUrl = String(objectValue(objectValue(payload.output).audio).url || "");
|
|
1485
|
-
if (!audioUrl) throw new Error("generate_speech returned no audio URL");
|
|
1486
|
-
const response = await fetch(audioUrl, { signal });
|
|
1487
|
-
if (!response.ok) throw new Error(`audio download failed (${response.status})`);
|
|
1488
|
-
await writeFile2(target, await responseBytes(response));
|
|
2075
|
+
const voices = isGeminiSpeechModel(model) ? masculine ? ["Puck", "Charon"] : ["Kore", "Aoede"] : primaryLanguage === "en" ? masculine ? ["en_male_tim_uranus_bigtts", "zh_male_m191_uranus_bigtts"] : ["en_female_dacey_uranus_bigtts", "en_female_stokie_uranus_bigtts"] : masculine ? ["zh_male_m191_uranus_bigtts", "zh_male_taocheng_uranus_bigtts"] : ["zh_female_vv_uranus_bigtts", "zh_female_xiaohe_uranus_bigtts"];
|
|
2076
|
+
const voice = settings?.voice || voices[(params.voice_identity?.index || 0) * 2 % voices.length];
|
|
2077
|
+
const bytes = await generateSpeechWithModelRouter({
|
|
2078
|
+
format,
|
|
2079
|
+
model,
|
|
2080
|
+
language: params.language,
|
|
2081
|
+
text: params.text,
|
|
2082
|
+
voice,
|
|
2083
|
+
signal,
|
|
2084
|
+
routify,
|
|
2085
|
+
retry
|
|
2086
|
+
});
|
|
2087
|
+
signal?.throwIfAborted();
|
|
2088
|
+
await mkdir3(path8.dirname(target), { recursive: true });
|
|
2089
|
+
await writeFile3(target, bytes);
|
|
1489
2090
|
return jsonToolResult({ status: "success", file_path: workspaceRelativePath(cwd, target) });
|
|
1490
2091
|
}
|
|
1491
2092
|
});
|
|
@@ -1494,7 +2095,7 @@ var schema2;
|
|
|
1494
2095
|
var init_generate_speech = __esm({
|
|
1495
2096
|
"src/capabilities/tools/media/generate_speech.ts"() {
|
|
1496
2097
|
"use strict";
|
|
1497
|
-
|
|
2098
|
+
init_routify_media();
|
|
1498
2099
|
init_workspace();
|
|
1499
2100
|
schema2 = Type7.Object({
|
|
1500
2101
|
file_path: Type7.String(),
|
|
@@ -1520,11 +2121,11 @@ var init_generate_speech = __esm({
|
|
|
1520
2121
|
function record4(value) {
|
|
1521
2122
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1522
2123
|
}
|
|
1523
|
-
function
|
|
2124
|
+
function stringValue3(value) {
|
|
1524
2125
|
return typeof value === "string" ? value : "";
|
|
1525
2126
|
}
|
|
1526
|
-
function routifyApiKey(settings) {
|
|
1527
|
-
const apiKey3 = settings?.apiKey;
|
|
2127
|
+
function routifyApiKey(settings, tool) {
|
|
2128
|
+
const apiKey3 = (tool === "web_search" ? settings?.webSearchApiKey?.trim() : settings?.imageSearchApiKey?.trim()) || settings?.apiKey;
|
|
1528
2129
|
if (!apiKey3) {
|
|
1529
2130
|
throw new Error("Routify search tools require harnesses.toolServices.routify.apiKey in settings.json");
|
|
1530
2131
|
}
|
|
@@ -1536,8 +2137,8 @@ function webSearchUrl(settings) {
|
|
|
1536
2137
|
function imageSearchUrl(settings) {
|
|
1537
2138
|
return settings?.imageSearchUrl || "https://routify-pub.alibaba-inc.com/protocol/brave/res/v1/images/search";
|
|
1538
2139
|
}
|
|
1539
|
-
function
|
|
1540
|
-
return
|
|
2140
|
+
function responseDetail3(payload, rawBody) {
|
|
2141
|
+
return stringValue3(payload.message) || stringValue3(payload.detailMessage) || stringValue3(record4(payload.error).message) || rawBody || "unknown provider error";
|
|
1541
2142
|
}
|
|
1542
2143
|
function groundingResults(payload) {
|
|
1543
2144
|
const candidates = [
|
|
@@ -1558,15 +2159,15 @@ function sourceRecords(payload) {
|
|
|
1558
2159
|
);
|
|
1559
2160
|
}
|
|
1560
2161
|
function resultDescription(item, source) {
|
|
1561
|
-
const groundingSnippets = Array.isArray(item.snippets) ? item.snippets.map(
|
|
1562
|
-
const snippets = groundingSnippets.length ? groundingSnippets : [
|
|
2162
|
+
const groundingSnippets = Array.isArray(item.snippets) ? item.snippets.map(stringValue3).map((value) => value.trim()).filter(Boolean) : [];
|
|
2163
|
+
const snippets = groundingSnippets.length ? groundingSnippets : [stringValue3(source.snippet).trim()].filter(Boolean);
|
|
1563
2164
|
return snippets.join("\n\n");
|
|
1564
2165
|
}
|
|
1565
2166
|
function pageAge(item) {
|
|
1566
2167
|
for (const candidate of [item.page_age, item.age]) {
|
|
1567
2168
|
const values = Array.isArray(candidate) ? candidate : [candidate];
|
|
1568
2169
|
for (const rawValue of values) {
|
|
1569
|
-
const value =
|
|
2170
|
+
const value = stringValue3(rawValue).trim();
|
|
1570
2171
|
if (!value) continue;
|
|
1571
2172
|
const isoDate = value.match(/^(\d{4})-(\d{2})-(\d{2})/);
|
|
1572
2173
|
const namedDate = value.match(
|
|
@@ -1607,7 +2208,7 @@ async function executeBraveImageSearch(query, count, options) {
|
|
|
1607
2208
|
const headers = {
|
|
1608
2209
|
accept: "application/json",
|
|
1609
2210
|
"content-type": "application/json",
|
|
1610
|
-
"x-subscription-token": routifyApiKey(options.routify)
|
|
2211
|
+
"x-subscription-token": routifyApiKey(options.routify, "image_search")
|
|
1611
2212
|
};
|
|
1612
2213
|
const response = await retryHttpRequest(() => fetch(url, {
|
|
1613
2214
|
method: "GET",
|
|
@@ -1625,7 +2226,7 @@ async function executeBraveImageSearch(query, count, options) {
|
|
|
1625
2226
|
}
|
|
1626
2227
|
if (!response.ok) {
|
|
1627
2228
|
throw new Error(
|
|
1628
|
-
`Brave image_search failed (${response.status} ${response.statusText}): ${
|
|
2229
|
+
`Brave image_search failed (${response.status} ${response.statusText}): ${responseDetail3(
|
|
1629
2230
|
payload,
|
|
1630
2231
|
rawBody
|
|
1631
2232
|
).slice(0, 2e3)}`
|
|
@@ -1635,21 +2236,22 @@ async function executeBraveImageSearch(query, count, options) {
|
|
|
1635
2236
|
}
|
|
1636
2237
|
async function executeBraveWebSearch(query, depth, options) {
|
|
1637
2238
|
const codeArena = options.profile === "code-arena";
|
|
1638
|
-
const resultLimit =
|
|
1639
|
-
const totalTokenLimit = codeArena ? { "1": 1280, "2": 4096, "3": 6144 }[depth] || 4096 : { "1":
|
|
1640
|
-
const perUrlTokenLimit = codeArena ? { "1": 512, "2": 1280, "3": 1536 }[depth] || 1280 : { "1": 512, "2":
|
|
2239
|
+
const resultLimit = { "1": 3, "2": 5, "3": 10 }[depth] || 5;
|
|
2240
|
+
const totalTokenLimit = codeArena ? { "1": 1280, "2": 4096, "3": 6144 }[depth] || 4096 : { "1": 2048, "2": 4096, "3": 8192 }[depth] || 4096;
|
|
2241
|
+
const perUrlTokenLimit = codeArena ? { "1": 512, "2": 1280, "3": 1536 }[depth] || 1280 : { "1": 512, "2": 1024, "3": 2048 }[depth] || 1024;
|
|
1641
2242
|
const model = options.model || "brave.llm-context";
|
|
1642
2243
|
const headers = {
|
|
1643
|
-
authorization: routifyApiKey(options.routify),
|
|
2244
|
+
authorization: routifyApiKey(options.routify, "web_search"),
|
|
1644
2245
|
"content-type": "application/json"
|
|
1645
2246
|
};
|
|
1646
2247
|
const body = JSON.stringify({
|
|
1647
2248
|
model,
|
|
1648
2249
|
q: query,
|
|
1649
|
-
count: 20,
|
|
2250
|
+
count: codeArena ? 20 : { "1": 20, "2": 35, "3": 50 }[depth] || 35,
|
|
1650
2251
|
maximum_number_of_urls: resultLimit,
|
|
1651
2252
|
maximum_number_of_tokens: totalTokenLimit,
|
|
1652
|
-
maximum_number_of_tokens_per_url: perUrlTokenLimit
|
|
2253
|
+
maximum_number_of_tokens_per_url: perUrlTokenLimit,
|
|
2254
|
+
...!codeArena ? { maximum_number_of_snippets_per_url: { "1": 2, "2": 3, "3": 5 }[depth] || 3 } : {}
|
|
1653
2255
|
});
|
|
1654
2256
|
const response = await retryHttpRequest(() => fetch(webSearchUrl(options.routify), {
|
|
1655
2257
|
method: "POST",
|
|
@@ -1668,7 +2270,7 @@ async function executeBraveWebSearch(query, depth, options) {
|
|
|
1668
2270
|
}
|
|
1669
2271
|
if (!response.ok) {
|
|
1670
2272
|
throw new Error(
|
|
1671
|
-
`Brave web_search failed (${response.status} ${response.statusText}): ${
|
|
2273
|
+
`Brave web_search failed (${response.status} ${response.statusText}): ${responseDetail3(
|
|
1672
2274
|
payload,
|
|
1673
2275
|
rawBody
|
|
1674
2276
|
).slice(0, 2e3)}`
|
|
@@ -1679,13 +2281,13 @@ async function executeBraveWebSearch(query, depth, options) {
|
|
|
1679
2281
|
status: "success",
|
|
1680
2282
|
results: groundingResults(payload).slice(0, resultLimit).map((value, index) => {
|
|
1681
2283
|
const item = record4(value);
|
|
1682
|
-
const url =
|
|
2284
|
+
const url = stringValue3(item.url);
|
|
1683
2285
|
const source = record4(sources[url]);
|
|
1684
2286
|
const age = pageAge(source);
|
|
1685
2287
|
return {
|
|
1686
2288
|
id: index + 1,
|
|
1687
2289
|
url,
|
|
1688
|
-
title:
|
|
2290
|
+
title: stringValue3(item.title) || stringValue3(source.title),
|
|
1689
2291
|
description: resultDescription(item, source),
|
|
1690
2292
|
...age ? { pageAge: age } : {}
|
|
1691
2293
|
};
|
|
@@ -1723,12 +2325,66 @@ var init_search_client = __esm({
|
|
|
1723
2325
|
}
|
|
1724
2326
|
});
|
|
1725
2327
|
|
|
2328
|
+
// src/utils/clients/media/dashscope.ts
|
|
2329
|
+
function record5(value) {
|
|
2330
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
2331
|
+
}
|
|
2332
|
+
function apiKey2(settings) {
|
|
2333
|
+
const value = settings?.apiKey;
|
|
2334
|
+
if (!value) {
|
|
2335
|
+
throw new Error("DashScope tools require harnesses.toolServices.dashScope.apiKey in settings.json");
|
|
2336
|
+
}
|
|
2337
|
+
return value;
|
|
2338
|
+
}
|
|
2339
|
+
function endpoint(settings, pathname) {
|
|
2340
|
+
const configured = settings?.apiBase || "https://dashscope.aliyuncs.com";
|
|
2341
|
+
const root = configured.replace(/\/+$/u, "").replace(/\/(?:api\/v1|compatible-mode\/v1)$/iu, "");
|
|
2342
|
+
return `${root}/api/v1${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
|
|
2343
|
+
}
|
|
2344
|
+
function createDashScopeClient(settings, retry) {
|
|
2345
|
+
return {
|
|
2346
|
+
async json(pathname, init, label) {
|
|
2347
|
+
const headers = new Headers(init.headers);
|
|
2348
|
+
headers.set("authorization", `Bearer ${apiKey2(settings)}`);
|
|
2349
|
+
const response = await retryHttpRequest(
|
|
2350
|
+
() => fetch(endpoint(settings, pathname), { ...init, headers }),
|
|
2351
|
+
retry,
|
|
2352
|
+
init.signal ?? void 0
|
|
2353
|
+
);
|
|
2354
|
+
const body = await response.text();
|
|
2355
|
+
let payload = {};
|
|
2356
|
+
try {
|
|
2357
|
+
payload = record5(JSON.parse(body));
|
|
2358
|
+
} catch {
|
|
2359
|
+
if (response.ok) throw new Error(`${label} returned malformed JSON`);
|
|
2360
|
+
}
|
|
2361
|
+
if (response.ok) return payload;
|
|
2362
|
+
const detail = String(payload.message || record5(payload.error).message || body);
|
|
2363
|
+
throw new Error(`${label} failed (${response.status} ${response.statusText}): ${detail.slice(0, 2e3)}`);
|
|
2364
|
+
}
|
|
2365
|
+
};
|
|
2366
|
+
}
|
|
2367
|
+
function objectValue(value) {
|
|
2368
|
+
return record5(value);
|
|
2369
|
+
}
|
|
2370
|
+
async function responseBytes2(response, limit = 25 * 1024 * 1024) {
|
|
2371
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
2372
|
+
if (bytes.length > limit) throw new Error(`download exceeds ${limit} bytes`);
|
|
2373
|
+
return bytes;
|
|
2374
|
+
}
|
|
2375
|
+
var init_dashscope = __esm({
|
|
2376
|
+
"src/utils/clients/media/dashscope.ts"() {
|
|
2377
|
+
"use strict";
|
|
2378
|
+
init_retry();
|
|
2379
|
+
}
|
|
2380
|
+
});
|
|
2381
|
+
|
|
1726
2382
|
// src/capabilities/tools/web/image_search.ts
|
|
1727
|
-
import { mkdir as mkdir4, writeFile as
|
|
1728
|
-
import
|
|
2383
|
+
import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
|
|
2384
|
+
import path9 from "node:path";
|
|
1729
2385
|
import { defineTool as defineTool9 } from "@earendil-works/pi-coding-agent";
|
|
1730
2386
|
import { Type as Type9 } from "typebox";
|
|
1731
|
-
function
|
|
2387
|
+
function record6(value) {
|
|
1732
2388
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
1733
2389
|
}
|
|
1734
2390
|
function createImageSearchTool(cwd, routify, retry) {
|
|
@@ -1745,33 +2401,42 @@ function createImageSearchTool(cwd, routify, retry) {
|
|
|
1745
2401
|
signal
|
|
1746
2402
|
});
|
|
1747
2403
|
const candidates = Array.isArray(payload.results) ? payload.results : [];
|
|
1748
|
-
const slug = params.query.toLowerCase().replace(/[^a-z0-9]+/gu, "-").slice(0, 40) || "
|
|
2404
|
+
const slug = params.query.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 40) || "results";
|
|
1749
2405
|
const results = [];
|
|
1750
2406
|
for (const value of candidates) {
|
|
1751
2407
|
if (results.length >= params.count) break;
|
|
1752
|
-
const item =
|
|
1753
|
-
const properties =
|
|
1754
|
-
const thumbnail =
|
|
2408
|
+
const item = record6(value);
|
|
2409
|
+
const properties = record6(item.properties);
|
|
2410
|
+
const thumbnail = record6(item.thumbnail);
|
|
1755
2411
|
const url = String(properties.url || thumbnail.src || "");
|
|
2412
|
+
const thumbnailUrl = String(thumbnail.src || url);
|
|
1756
2413
|
if (!url) continue;
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
2414
|
+
for (const downloadUrl of /* @__PURE__ */ new Set([url, thumbnailUrl])) {
|
|
2415
|
+
try {
|
|
2416
|
+
const response = await fetch(downloadUrl, { signal });
|
|
2417
|
+
if (!response.ok) continue;
|
|
2418
|
+
const mimeType = (response.headers.get("content-type") || "image/jpeg").split(";", 1)[0].trim().toLowerCase();
|
|
2419
|
+
if (!mimeType.startsWith("image/")) continue;
|
|
2420
|
+
const extension = { "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", "image/bmp": ".bmp" }[mimeType] || ".jpg";
|
|
2421
|
+
const target = await resolveWorkspacePath(cwd, `image-search/${slug}-${results.length + 1}${extension}`);
|
|
2422
|
+
await mkdir4(path9.dirname(target), { recursive: true });
|
|
2423
|
+
await writeFile4(target, await responseBytes2(response));
|
|
2424
|
+
results.push({
|
|
2425
|
+
title: String(item.title || ""),
|
|
2426
|
+
file_path: workspaceRelativePath(cwd, target),
|
|
2427
|
+
source_url: String(item.url || ""),
|
|
2428
|
+
thumbnail_url: thumbnailUrl
|
|
2429
|
+
});
|
|
2430
|
+
break;
|
|
2431
|
+
} catch (error) {
|
|
2432
|
+
if (signal?.aborted) throw error;
|
|
2433
|
+
}
|
|
1773
2434
|
}
|
|
1774
2435
|
}
|
|
2436
|
+
if (!results.length) return {
|
|
2437
|
+
...jsonToolResult({ status: "error", message: "Image search failed: Strict safe search filtered all results for this query. Try a different or more specific query." }),
|
|
2438
|
+
isError: true
|
|
2439
|
+
};
|
|
1775
2440
|
return jsonToolResult({ status: "success", results });
|
|
1776
2441
|
}
|
|
1777
2442
|
});
|
|
@@ -1781,6 +2446,7 @@ var init_image_search = __esm({
|
|
|
1781
2446
|
"src/capabilities/tools/web/image_search.ts"() {
|
|
1782
2447
|
"use strict";
|
|
1783
2448
|
init_search_client();
|
|
2449
|
+
init_dashscope();
|
|
1784
2450
|
init_workspace();
|
|
1785
2451
|
init_search_client();
|
|
1786
2452
|
schema4 = Type9.Object({
|
|
@@ -1827,9 +2493,9 @@ var init_web_search = __esm({
|
|
|
1827
2493
|
});
|
|
1828
2494
|
|
|
1829
2495
|
// src/runtime/harness-args.ts
|
|
1830
|
-
import
|
|
2496
|
+
import path10 from "node:path";
|
|
1831
2497
|
function withLocalWorkspacePrompt(systemPrompt, cwd) {
|
|
1832
|
-
const resolvedCwd =
|
|
2498
|
+
const resolvedCwd = path10.resolve(cwd);
|
|
1833
2499
|
return `${systemPrompt.trimEnd()}
|
|
1834
2500
|
|
|
1835
2501
|
## Local Workspace
|
|
@@ -1880,11 +2546,11 @@ var init_harness_args = __esm({
|
|
|
1880
2546
|
});
|
|
1881
2547
|
|
|
1882
2548
|
// src/utils/clients/media/pexels.ts
|
|
1883
|
-
import { createHash } from "node:crypto";
|
|
1884
|
-
import { mkdir as mkdir6, readFile as
|
|
1885
|
-
import { tmpdir as
|
|
1886
|
-
import
|
|
1887
|
-
function
|
|
2549
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2550
|
+
import { mkdir as mkdir6, readFile as readFile7, writeFile as writeFile5 } from "node:fs/promises";
|
|
2551
|
+
import { tmpdir as tmpdir3 } from "node:os";
|
|
2552
|
+
import path13 from "node:path";
|
|
2553
|
+
function record7(value) {
|
|
1888
2554
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
1889
2555
|
}
|
|
1890
2556
|
async function fetchPexels(settings, retry, pathname, params, signal) {
|
|
@@ -1895,57 +2561,67 @@ async function fetchPexels(settings, retry, pathname, params, signal) {
|
|
|
1895
2561
|
if (value && value !== "any") url.searchParams.set(name, value);
|
|
1896
2562
|
}
|
|
1897
2563
|
const ttl = settings?.cacheTtlMs ?? 24 * 60 * 60 * 1e3;
|
|
1898
|
-
const cacheDirectory = settings?.cacheDir ||
|
|
1899
|
-
const cacheFile =
|
|
2564
|
+
const cacheDirectory = settings?.cacheDir || path13.join(tmpdir3(), "pi-training-harness", "fetch-media");
|
|
2565
|
+
const cacheFile = path13.join(cacheDirectory, `${createHash2("sha256").update(url.href).digest("hex")}.json`);
|
|
1900
2566
|
if (ttl > 0) {
|
|
1901
2567
|
try {
|
|
1902
|
-
const cached = JSON.parse(await
|
|
2568
|
+
const cached = JSON.parse(await readFile7(cacheFile, "utf8"));
|
|
1903
2569
|
if (typeof cached.cachedAt === "number" && Date.now() - cached.cachedAt < ttl) {
|
|
1904
|
-
const payload2 =
|
|
2570
|
+
const payload2 = record7(cached.payload);
|
|
1905
2571
|
if (Object.keys(payload2).length > 0) return payload2;
|
|
1906
2572
|
}
|
|
1907
2573
|
} catch {
|
|
1908
2574
|
}
|
|
1909
2575
|
}
|
|
2576
|
+
const quota = quotas.get(apiKey3);
|
|
2577
|
+
if (quota && quota.remaining <= 0 && Date.now() < quota.resetAtMs) throw new Error("fetch_media failed (429): Pexels quota exhausted");
|
|
1910
2578
|
const response = await retryHttpRequest(
|
|
1911
2579
|
() => fetch(url, { headers: { authorization: apiKey3 }, signal }),
|
|
1912
2580
|
retry,
|
|
1913
2581
|
signal
|
|
1914
2582
|
);
|
|
2583
|
+
const remaining = response.headers.get("x-ratelimit-remaining");
|
|
2584
|
+
const reset = response.headers.get("x-ratelimit-reset");
|
|
2585
|
+
if (response.ok && remaining !== null && reset !== null && Number.isFinite(Number(remaining)) && Number.isFinite(Number(reset))) {
|
|
2586
|
+
quotas.set(apiKey3, { remaining: Number(remaining), resetAtMs: Number(reset) * 1e3 });
|
|
2587
|
+
}
|
|
1915
2588
|
if (!response.ok) throw new Error(`fetch_media failed (${response.status} ${response.statusText})`);
|
|
1916
|
-
const payload =
|
|
2589
|
+
const payload = record7(await response.json());
|
|
2590
|
+
if (!Object.keys(payload).length) throw new Error("fetch_media returned an empty response");
|
|
1917
2591
|
if (ttl > 0) {
|
|
1918
2592
|
try {
|
|
1919
2593
|
await mkdir6(cacheDirectory, { recursive: true });
|
|
1920
|
-
await
|
|
2594
|
+
await writeFile5(cacheFile, JSON.stringify({ cachedAt: Date.now(), payload }), "utf8");
|
|
1921
2595
|
} catch {
|
|
1922
2596
|
}
|
|
1923
2597
|
}
|
|
1924
2598
|
return payload;
|
|
1925
2599
|
}
|
|
2600
|
+
var quotas;
|
|
1926
2601
|
var init_pexels = __esm({
|
|
1927
2602
|
"src/utils/clients/media/pexels.ts"() {
|
|
1928
2603
|
"use strict";
|
|
1929
2604
|
init_retry();
|
|
2605
|
+
quotas = /* @__PURE__ */ new Map();
|
|
1930
2606
|
}
|
|
1931
2607
|
});
|
|
1932
2608
|
|
|
1933
2609
|
// src/capabilities/tools/media/fetch_media.ts
|
|
1934
2610
|
import { defineTool as defineTool19 } from "@earendil-works/pi-coding-agent";
|
|
1935
2611
|
import { Type as Type19 } from "typebox";
|
|
1936
|
-
function
|
|
2612
|
+
function record8(value) {
|
|
1937
2613
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
1938
2614
|
}
|
|
1939
|
-
function photos(payload) {
|
|
2615
|
+
function photos(payload, orientation) {
|
|
1940
2616
|
return (Array.isArray(payload.photos) ? payload.photos : []).map((value) => {
|
|
1941
|
-
const photo =
|
|
1942
|
-
const source =
|
|
2617
|
+
const photo = record8(value);
|
|
2618
|
+
const source = record8(photo.src);
|
|
1943
2619
|
return {
|
|
1944
2620
|
type: "image",
|
|
1945
2621
|
id: Number(photo.id),
|
|
1946
2622
|
pexelsUrl: String(photo.url || ""),
|
|
1947
|
-
recommendedUrl: String(source.large2x || source.large || source.original || ""),
|
|
1948
|
-
thumbnailUrl: String(source.
|
|
2623
|
+
recommendedUrl: String((orientation === "landscape" || orientation === "portrait" ? source[orientation] : "") || source.large2x || source.large || source.original || ""),
|
|
2624
|
+
thumbnailUrl: String(source.tiny || source.medium || source.small || ""),
|
|
1949
2625
|
width: Number(photo.width),
|
|
1950
2626
|
height: Number(photo.height),
|
|
1951
2627
|
creatorName: String(photo.photographer || ""),
|
|
@@ -1956,22 +2632,29 @@ function photos(payload) {
|
|
|
1956
2632
|
}
|
|
1957
2633
|
function videos(payload) {
|
|
1958
2634
|
return (Array.isArray(payload.videos) ? payload.videos : []).map((value) => {
|
|
1959
|
-
const video =
|
|
1960
|
-
const files = (Array.isArray(video.video_files) ? video.video_files : []).map(
|
|
1961
|
-
const pictures = (Array.isArray(video.video_pictures) ? video.video_pictures : []).map(
|
|
1962
|
-
const preferred = files.
|
|
1963
|
-
const user =
|
|
2635
|
+
const video = record8(value);
|
|
2636
|
+
const files = (Array.isArray(video.video_files) ? video.video_files : []).map(record8);
|
|
2637
|
+
const pictures = (Array.isArray(video.video_pictures) ? video.video_pictures : []).map(record8);
|
|
2638
|
+
const preferred = files.filter((item) => item.file_type === "video/mp4" && item.link).sort((a, b) => (Number(b.width) || 0) * (Number(b.height) || 0) - (Number(a.width) || 0) * (Number(a.height) || 0))[0] || files[0] || {};
|
|
2639
|
+
const user = record8(video.user);
|
|
1964
2640
|
return {
|
|
1965
2641
|
type: "video",
|
|
1966
2642
|
id: Number(video.id),
|
|
1967
2643
|
pexelsUrl: String(video.url || ""),
|
|
1968
2644
|
recommendedUrl: String(preferred.link || ""),
|
|
1969
|
-
thumbnailUrl: String(pictures[0]?.picture || ""),
|
|
2645
|
+
thumbnailUrl: String(video.image || pictures[0]?.picture || ""),
|
|
1970
2646
|
width: Number(video.width),
|
|
1971
2647
|
height: Number(video.height),
|
|
1972
2648
|
duration: Number(video.duration),
|
|
1973
2649
|
creatorName: String(user.name || ""),
|
|
1974
|
-
creatorUrl: String(user.url || "")
|
|
2650
|
+
creatorUrl: String(user.url || ""),
|
|
2651
|
+
videoFile: {
|
|
2652
|
+
url: String(preferred.link || ""),
|
|
2653
|
+
width: Number(preferred.width),
|
|
2654
|
+
height: Number(preferred.height),
|
|
2655
|
+
...preferred.quality === void 0 ? {} : { quality: preferred.quality },
|
|
2656
|
+
fileType: String(preferred.file_type || "")
|
|
2657
|
+
}
|
|
1975
2658
|
};
|
|
1976
2659
|
});
|
|
1977
2660
|
}
|
|
@@ -2010,7 +2693,7 @@ function createFetchMediaTool(settings, retry) {
|
|
|
2010
2693
|
let totalResults = 0;
|
|
2011
2694
|
if (params.media_type !== "video") {
|
|
2012
2695
|
const result = await fetchPexels(settings, retry, "/v1/search", common, signal);
|
|
2013
|
-
photoResults = photos(result);
|
|
2696
|
+
photoResults = photos(result, params.orientation);
|
|
2014
2697
|
totalResults += Number(result.total_results || 0);
|
|
2015
2698
|
}
|
|
2016
2699
|
if (params.media_type !== "image") {
|
|
@@ -2104,8 +2787,8 @@ var init_image_output = __esm({
|
|
|
2104
2787
|
});
|
|
2105
2788
|
|
|
2106
2789
|
// src/capabilities/tools/programmatic-tool-calling/index.ts
|
|
2107
|
-
import { spawn as
|
|
2108
|
-
import
|
|
2790
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
2791
|
+
import path16 from "node:path";
|
|
2109
2792
|
import readline from "node:readline";
|
|
2110
2793
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
2111
2794
|
import {
|
|
@@ -2225,7 +2908,7 @@ function configuredPiTools(cwd) {
|
|
|
2225
2908
|
];
|
|
2226
2909
|
}
|
|
2227
2910
|
function createPiNestedTools(cwd = process.cwd()) {
|
|
2228
|
-
return configuredPiTools(
|
|
2911
|
+
return configuredPiTools(path16.resolve(cwd));
|
|
2229
2912
|
}
|
|
2230
2913
|
function validationError(tool, args) {
|
|
2231
2914
|
const errors = Value.Errors(tool.parameters, args).slice(0, 8).map((error) => `${error.instancePath || "/"}: ${error.message}`).join("\n");
|
|
@@ -2303,7 +2986,7 @@ async function executeRunCode(toolCallId, params, signal, context, tools, limits
|
|
|
2303
2986
|
let activeTimerCount = 0;
|
|
2304
2987
|
let terminate = false;
|
|
2305
2988
|
const activeCalls = /* @__PURE__ */ new Map();
|
|
2306
|
-
const child =
|
|
2989
|
+
const child = spawn3(
|
|
2307
2990
|
process.execPath,
|
|
2308
2991
|
["--permission", "--no-warnings", "--disable-proto=throw", "--max-old-space-size=96", RUN_CODE_CHILD_PATH],
|
|
2309
2992
|
{
|
|
@@ -2518,7 +3201,7 @@ function createProgrammaticToolCallingExtension(cwd = process.cwd(), options = {
|
|
|
2518
3201
|
const metadataTools = options.nestedTools ?? createPiNestedTools(cwd);
|
|
2519
3202
|
const cache = /* @__PURE__ */ new Map();
|
|
2520
3203
|
const resolveNestedTools = options.resolveNestedTools ?? (options.nestedTools ? () => metadataTools : (context) => {
|
|
2521
|
-
const resolvedCwd =
|
|
3204
|
+
const resolvedCwd = path16.resolve(context.cwd);
|
|
2522
3205
|
const cached = cache.get(resolvedCwd);
|
|
2523
3206
|
if (cached) return cached;
|
|
2524
3207
|
const tools = createPiNestedTools(resolvedCwd);
|
|
@@ -2608,16 +3291,16 @@ function parseScalingConfig(value) {
|
|
|
2608
3291
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2609
3292
|
throw new Error("Scaling config must be an object with S, TS, TC, O, C, W.");
|
|
2610
3293
|
}
|
|
2611
|
-
const
|
|
2612
|
-
for (const key of Object.keys(
|
|
3294
|
+
const record9 = value;
|
|
3295
|
+
for (const key of Object.keys(record9)) {
|
|
2613
3296
|
if (!SCALING_AXES.includes(key)) throw new Error(`Unknown scaling axis: ${key}`);
|
|
2614
3297
|
}
|
|
2615
3298
|
for (const axis of SCALING_AXES) {
|
|
2616
|
-
if (![`${axis}1`, `${axis}2`, `${axis}3`].includes(String(
|
|
2617
|
-
throw new Error(`Invalid ${axis} design: ${String(
|
|
3299
|
+
if (![`${axis}1`, `${axis}2`, `${axis}3`].includes(String(record9[axis]))) {
|
|
3300
|
+
throw new Error(`Invalid ${axis} design: ${String(record9[axis])}. Choose ${axis}1\u2013${axis}3; TC4 is excluded.`);
|
|
2618
3301
|
}
|
|
2619
3302
|
}
|
|
2620
|
-
return Object.fromEntries(SCALING_AXES.map((axis) => [axis,
|
|
3303
|
+
return Object.fromEntries(SCALING_AXES.map((axis) => [axis, record9[axis]]));
|
|
2621
3304
|
}
|
|
2622
3305
|
function scalingConfigId(config) {
|
|
2623
3306
|
return SCALING_AXES.map((axis) => config[axis]).join("-");
|
|
@@ -2681,7 +3364,7 @@ var init_config = __esm({
|
|
|
2681
3364
|
});
|
|
2682
3365
|
|
|
2683
3366
|
// src/capabilities/tools/programmatic-tool-calling/persistent.ts
|
|
2684
|
-
import { spawn as
|
|
3367
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
2685
3368
|
import readline2 from "node:readline";
|
|
2686
3369
|
import { defineTool as defineTool23 } from "@earendil-works/pi-coding-agent";
|
|
2687
3370
|
function createExecTool(runtime) {
|
|
@@ -2728,7 +3411,7 @@ var init_persistent = __esm({
|
|
|
2728
3411
|
if (this.child?.stdin.writable) this.child.stdin.write(JSON.stringify(message) + "\n");
|
|
2729
3412
|
}
|
|
2730
3413
|
start(cwd) {
|
|
2731
|
-
const child =
|
|
3414
|
+
const child = spawn4(
|
|
2732
3415
|
process.execPath,
|
|
2733
3416
|
["--permission", "--no-warnings", "--disable-proto=throw", RUN_CODE_CHILD_PATH],
|
|
2734
3417
|
{ cwd, env: {}, stdio: ["pipe", "pipe", "pipe"] }
|
|
@@ -3084,10 +3767,10 @@ var init_naming = __esm({
|
|
|
3084
3767
|
});
|
|
3085
3768
|
|
|
3086
3769
|
// src/harnesses/scaling/observation.ts
|
|
3087
|
-
import { randomUUID } from "node:crypto";
|
|
3770
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3088
3771
|
import { constants } from "node:fs";
|
|
3089
|
-
import { chmod, copyFile, mkdir as mkdir7, open, writeFile as
|
|
3090
|
-
import
|
|
3772
|
+
import { chmod, copyFile, mkdir as mkdir7, open, writeFile as writeFile6 } from "node:fs/promises";
|
|
3773
|
+
import path17 from "node:path";
|
|
3091
3774
|
function cropText(text2, budget) {
|
|
3092
3775
|
if (text2.length <= budget) return { text: text2, omitted: 0 };
|
|
3093
3776
|
const marker = `
|
|
@@ -3103,9 +3786,9 @@ function nativeSource(name, result) {
|
|
|
3103
3786
|
const details = result.details;
|
|
3104
3787
|
if (name === "bash" && typeof details?.fullOutputPath === "string") return { filePath: details.fullOutputPath };
|
|
3105
3788
|
if (typeof structured === "string") return { text: structured };
|
|
3106
|
-
const
|
|
3107
|
-
if (
|
|
3108
|
-
return { text:
|
|
3789
|
+
const record9 = structured;
|
|
3790
|
+
if (record9 && typeof record9 === "object" && !Array.isArray(record9) && typeof record9.output === "string")
|
|
3791
|
+
return { text: record9.output };
|
|
3109
3792
|
return { text: resultText(result) };
|
|
3110
3793
|
}
|
|
3111
3794
|
function previewText(text2, budget) {
|
|
@@ -3150,13 +3833,13 @@ async function previewSource(source, budget) {
|
|
|
3150
3833
|
}
|
|
3151
3834
|
}
|
|
3152
3835
|
async function saveOutput(source, ctx) {
|
|
3153
|
-
const directory =
|
|
3836
|
+
const directory = path17.join(ctx.sessionManager.getSessionDir(), "scaling-outputs", ctx.sessionManager.getSessionId());
|
|
3154
3837
|
await mkdir7(directory, { recursive: true, mode: 448 });
|
|
3155
|
-
const outputPath =
|
|
3838
|
+
const outputPath = path17.join(directory, `${randomUUID2()}.txt`);
|
|
3156
3839
|
if ("filePath" in source) {
|
|
3157
3840
|
await copyFile(source.filePath, outputPath, constants.COPYFILE_EXCL);
|
|
3158
3841
|
await chmod(outputPath, 384);
|
|
3159
|
-
} else await
|
|
3842
|
+
} else await writeFile6(outputPath, source.text, { encoding: "utf8", flag: "wx", mode: 384 });
|
|
3160
3843
|
return outputPath;
|
|
3161
3844
|
}
|
|
3162
3845
|
var OUTPUT_ENTRY, OBSERVATION_ENTRY, ObservationPolicy;
|
|
@@ -3299,14 +3982,14 @@ function createHistoryTool(previewChars) {
|
|
|
3299
3982
|
async execute(_id, args, _signal, _update, ctx) {
|
|
3300
3983
|
let records = sessionHistory(ctx.sessionManager.getBranch());
|
|
3301
3984
|
if (args.action === "read") {
|
|
3302
|
-
const entry = records.find((
|
|
3985
|
+
const entry = records.find((record9) => record9.ref === args.ref);
|
|
3303
3986
|
if (!entry) throw new Error("Unknown history reference in the active branch");
|
|
3304
3987
|
const offset = args.offset ?? 0;
|
|
3305
3988
|
return textResult({ ref: entry.ref, role: entry.role, text: entry.text.slice(offset, offset + pageSize), nextOffset: offset + pageSize < entry.text.length ? offset + pageSize : null, totalChars: entry.text.length });
|
|
3306
3989
|
}
|
|
3307
3990
|
if (args.action === "search") {
|
|
3308
3991
|
if (!args.query) throw new Error("query is required for search");
|
|
3309
|
-
records = records.filter((
|
|
3992
|
+
records = records.filter((record9) => record9.text.includes(args.query));
|
|
3310
3993
|
}
|
|
3311
3994
|
const cursor = args.cursor ?? 0;
|
|
3312
3995
|
const count = Math.max(1, Math.min(10, Math.floor(pageSize / 250)));
|
|
@@ -3323,7 +4006,7 @@ var init_history = __esm({
|
|
|
3323
4006
|
});
|
|
3324
4007
|
|
|
3325
4008
|
// src/harnesses/scaling/hierarchy.ts
|
|
3326
|
-
import { randomUUID as
|
|
4009
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
3327
4010
|
import { defineTool as defineTool25 } from "@earendil-works/pi-coding-agent";
|
|
3328
4011
|
import { Type as Type24 } from "typebox";
|
|
3329
4012
|
var MEMORY_NODE_ENTRY, MEMORY_FRONTIER_ENTRY, HierarchicalMemory;
|
|
@@ -3367,13 +4050,13 @@ var init_hierarchy = __esm({
|
|
|
3367
4050
|
created.push(node);
|
|
3368
4051
|
frontier.push(node.id);
|
|
3369
4052
|
};
|
|
3370
|
-
add({ id:
|
|
4053
|
+
add({ id: randomUUID3(), level: 1, summary: await summarize(text2, "segment"), sources, children: [] });
|
|
3371
4054
|
while (frontier.length >= this.fanout) {
|
|
3372
4055
|
const children = frontier.slice(-this.fanout).map((id) => nodes.get(id));
|
|
3373
4056
|
if (!children.every((node) => node.level === children[0].level)) break;
|
|
3374
4057
|
const summary = await summarize(children.map((node) => `[${node.id}] ${node.summary}`).join("\n\n"), "rollup");
|
|
3375
4058
|
frontier.splice(-this.fanout);
|
|
3376
|
-
add({ id:
|
|
4059
|
+
add({ id: randomUUID3(), level: children[0].level + 1, summary, children: children.map((node) => node.id), sources: [] });
|
|
3377
4060
|
}
|
|
3378
4061
|
this.nodes = nodes;
|
|
3379
4062
|
this.frontier = frontier;
|
|
@@ -3414,8 +4097,8 @@ ${node.summary}`).join("\n\n");
|
|
|
3414
4097
|
});
|
|
3415
4098
|
|
|
3416
4099
|
// src/harnesses/scaling/notes.ts
|
|
3417
|
-
import { randomUUID as
|
|
3418
|
-
import { rename, rm as
|
|
4100
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4101
|
+
import { rename, rm as rm4, writeFile as writeFile7 } from "node:fs/promises";
|
|
3419
4102
|
import {
|
|
3420
4103
|
defineTool as defineTool26
|
|
3421
4104
|
} from "@earendil-works/pi-coding-agent";
|
|
@@ -3505,7 +4188,7 @@ var init_notes = __esm({
|
|
|
3505
4188
|
throw new Error(`Notes must be nonempty and fit within ${tokenLimit} estimated tokens / 16 KiB`);
|
|
3506
4189
|
if (ctx.hasPendingMessages()) throw new Error("Read pending user input before saving Notes");
|
|
3507
4190
|
state.notes = {
|
|
3508
|
-
revision:
|
|
4191
|
+
revision: randomUUID4(),
|
|
3509
4192
|
text: args.text,
|
|
3510
4193
|
savedTurn: state.turn,
|
|
3511
4194
|
workVersion: state.workVersion,
|
|
@@ -3515,9 +4198,9 @@ var init_notes = __esm({
|
|
|
3515
4198
|
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
3516
4199
|
if (sessionFile) {
|
|
3517
4200
|
const notesPath = sessionFile.replace(/\.jsonl$/u, ".notes.md");
|
|
3518
|
-
const temporary = `${notesPath}.${
|
|
4201
|
+
const temporary = `${notesPath}.${randomUUID4()}.tmp`;
|
|
3519
4202
|
try {
|
|
3520
|
-
await
|
|
4203
|
+
await writeFile7(
|
|
3521
4204
|
temporary,
|
|
3522
4205
|
`<!-- Generated from the session log. Direct edits are not imported. Revision: ${state.notes.revision} -->
|
|
3523
4206
|
${state.notes.text}
|
|
@@ -3526,7 +4209,7 @@ ${state.notes.text}
|
|
|
3526
4209
|
);
|
|
3527
4210
|
await rename(temporary, notesPath);
|
|
3528
4211
|
} finally {
|
|
3529
|
-
await
|
|
4212
|
+
await rm4(temporary, { force: true });
|
|
3530
4213
|
}
|
|
3531
4214
|
}
|
|
3532
4215
|
return textResult({ revision: state.notes.revision, status: "saved" });
|
|
@@ -3937,6 +4620,12 @@ var init_codemode = __esm({
|
|
|
3937
4620
|
// src/harnesses/scaling/planning.ts
|
|
3938
4621
|
import { defineTool as defineTool29 } from "@earendil-works/pi-coding-agent";
|
|
3939
4622
|
import { Type as Type28 } from "typebox";
|
|
4623
|
+
function quoteShellArg(value) {
|
|
4624
|
+
return "'" + value.replaceAll("'", "'\\''") + "'";
|
|
4625
|
+
}
|
|
4626
|
+
function isTestCommand([name, option, subcommand]) {
|
|
4627
|
+
return name === "pytest" || (name === "python" || name === "python3") && option === "-m" && subcommand === "pytest" || name === "node" && option === "--test" || name === "npm" && (option === "test" || option === "run" && subcommand === "test") || (name === "cargo" || name === "go") && option === "test";
|
|
4628
|
+
}
|
|
3940
4629
|
function planningShell(command) {
|
|
3941
4630
|
const pipeline = [[]];
|
|
3942
4631
|
let word = "";
|
|
@@ -3985,12 +4674,20 @@ function planningShell(command) {
|
|
|
3985
4674
|
}
|
|
3986
4675
|
if (quoted) throw new Error("Unclosed Shell quote");
|
|
3987
4676
|
flush();
|
|
4677
|
+
if (isTestCommand(pipeline[0])) {
|
|
4678
|
+
if (pipeline.length !== 1) throw new Error("Run planning tests as a single command, outside a pipeline");
|
|
4679
|
+
return { command: pipeline[0].map(quoteShellArg).join(" "), test: true };
|
|
4680
|
+
}
|
|
3988
4681
|
for (const argv of pipeline) {
|
|
3989
4682
|
const [name, ...args] = argv;
|
|
3990
|
-
if (!name || !["pwd", "ls", "cat", "head", "tail", "wc", "grep", "rg", "git", "sed"].includes(name))
|
|
4683
|
+
if (!name || !["pwd", "ls", "cat", "head", "tail", "wc", "grep", "rg", "git", "sed", "find", "which"].includes(name))
|
|
3991
4684
|
throw new Error(
|
|
3992
|
-
"Planning Shell allows pwd, ls, cat, head, tail, wc, grep, rg, selected git queries,
|
|
4685
|
+
"Planning Shell allows pwd, ls, cat, head, tail, wc, grep, rg, read-only find, which, selected git queries, numeric sed -n ...p, and supported standalone tests"
|
|
3993
4686
|
);
|
|
4687
|
+
if (name === "find" && args.some((arg) => arg.startsWith("-") && !FIND_OPTIONS.has(arg)))
|
|
4688
|
+
throw new Error("Planning find supports path and type filters, depth limits, and printing");
|
|
4689
|
+
if (name === "which" && args.some((arg) => arg.startsWith("-") && arg !== "-a"))
|
|
4690
|
+
throw new Error("Planning which supports command names and the -a option");
|
|
3994
4691
|
if (name === "rg" && args.some((arg) => /^(--pre(?:=|$)|--hostname-bin(?:=|$))/u.test(arg)))
|
|
3995
4692
|
throw new Error("External search preprocessors are unavailable during planning");
|
|
3996
4693
|
if (name === "sed" && (args[0] !== "-n" || !/^\d+(?:,(?:\d+|\$))?p$/u.test(args[1] ?? "") || args.length < 2 || args.slice(2).some((arg) => arg.startsWith("-"))))
|
|
@@ -4002,9 +4699,9 @@ function planningShell(command) {
|
|
|
4002
4699
|
if (["diff", "log", "show"].includes(args[0])) argv.splice(4, 0, "--no-ext-diff", "--no-textconv");
|
|
4003
4700
|
}
|
|
4004
4701
|
}
|
|
4005
|
-
return pipeline.map((argv) => argv.map(
|
|
4702
|
+
return { command: pipeline.map((argv) => argv.map(quoteShellArg).join(" ")).join(" | "), test: false };
|
|
4006
4703
|
}
|
|
4007
|
-
var READ_ONLY_TOOLS, PlanningWorkflow;
|
|
4704
|
+
var READ_ONLY_TOOLS, FIND_OPTIONS, PlanningWorkflow;
|
|
4008
4705
|
var init_planning = __esm({
|
|
4009
4706
|
"src/harnesses/scaling/planning.ts"() {
|
|
4010
4707
|
"use strict";
|
|
@@ -4046,6 +4743,26 @@ var init_planning = __esm({
|
|
|
4046
4743
|
"exec",
|
|
4047
4744
|
"ask_user_question"
|
|
4048
4745
|
]);
|
|
4746
|
+
FIND_OPTIONS = /* @__PURE__ */ new Set([
|
|
4747
|
+
"-name",
|
|
4748
|
+
"-iname",
|
|
4749
|
+
"-path",
|
|
4750
|
+
"-ipath",
|
|
4751
|
+
"-type",
|
|
4752
|
+
"-mindepth",
|
|
4753
|
+
"-maxdepth",
|
|
4754
|
+
"-empty",
|
|
4755
|
+
"-print",
|
|
4756
|
+
"-print0",
|
|
4757
|
+
"-prune",
|
|
4758
|
+
"-xdev",
|
|
4759
|
+
"-depth",
|
|
4760
|
+
"-a",
|
|
4761
|
+
"-and",
|
|
4762
|
+
"-o",
|
|
4763
|
+
"-or",
|
|
4764
|
+
"-not"
|
|
4765
|
+
]);
|
|
4049
4766
|
PlanningWorkflow = class {
|
|
4050
4767
|
toolName;
|
|
4051
4768
|
constructor(toolName = (name) => name) {
|
|
@@ -4059,21 +4776,24 @@ var init_planning = __esm({
|
|
|
4059
4776
|
this.pending = void 0;
|
|
4060
4777
|
this.reminders = 0;
|
|
4061
4778
|
}
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
}
|
|
4065
|
-
guard(name, args) {
|
|
4066
|
-
if (this.phase === "executing") return args;
|
|
4779
|
+
async executeTool(name, args, execute2) {
|
|
4780
|
+
if (this.phase === "executing") return execute2(args);
|
|
4067
4781
|
if (name === "http_request" && ["GET", "HEAD", "OPTIONS"].includes(args.method ?? "GET"))
|
|
4068
|
-
return args;
|
|
4069
|
-
if (name === "plugins" && ["list", "inspect", "search"].includes(args.action))
|
|
4070
|
-
|
|
4071
|
-
if (
|
|
4782
|
+
return execute2(args);
|
|
4783
|
+
if (name === "plugins" && ["list", "inspect", "search"].includes(args.action))
|
|
4784
|
+
return execute2(args);
|
|
4785
|
+
if (["cron_list", "conversations_list"].includes(name)) return execute2(args);
|
|
4786
|
+
if (name === "bash") {
|
|
4787
|
+
const input = args;
|
|
4788
|
+
const parsed = planningShell(input.command);
|
|
4789
|
+
if (parsed.test && input.background) throw new Error("Run planning tests in the foreground");
|
|
4790
|
+
return execute2({ ...input, command: parsed.command });
|
|
4791
|
+
}
|
|
4072
4792
|
if (!READ_ONLY_TOOLS.has(name))
|
|
4073
4793
|
throw new Error(
|
|
4074
|
-
`Planning phase: ${name} is unavailable until submit_plan completes and the next model turn starts`
|
|
4794
|
+
`Planning phase: ${this.toolName(name)} is unavailable until ${this.toolName("submit_plan")} completes and the next model turn starts`
|
|
4075
4795
|
);
|
|
4076
|
-
return args;
|
|
4796
|
+
return execute2(args);
|
|
4077
4797
|
}
|
|
4078
4798
|
tool() {
|
|
4079
4799
|
const state = this;
|
|
@@ -4568,7 +5288,11 @@ function mechanismPrompt(config) {
|
|
|
4568
5288
|
);
|
|
4569
5289
|
if (config.W === "W2")
|
|
4570
5290
|
pieces.push(
|
|
4571
|
-
|
|
5291
|
+
[
|
|
5292
|
+
"Begin in the planning phase. Inspect the workspace and run existing tests as needed to understand the task and form a plan. Tests may produce temporary files, caches, and build artifacts.",
|
|
5293
|
+
"During planning, do not edit project files or run implementation commands.",
|
|
5294
|
+
"When ready, submit an actionable plan and verification steps with submit_plan. Execution begins automatically on the next model turn. Once the plan is accepted, implement it, verify the result, and finish the task."
|
|
5295
|
+
].join("\n\n")
|
|
4572
5296
|
);
|
|
4573
5297
|
if (config.W === "W3")
|
|
4574
5298
|
pieces.push(
|
|
@@ -4683,9 +5407,9 @@ var init_send_message = __esm({
|
|
|
4683
5407
|
});
|
|
4684
5408
|
|
|
4685
5409
|
// src/utils/storage/json_store.ts
|
|
4686
|
-
import { mkdir as mkdir8, readFile as
|
|
4687
|
-
import
|
|
4688
|
-
import { randomUUID as
|
|
5410
|
+
import { mkdir as mkdir8, readFile as readFile8, writeFile as writeFile8, rename as rename2, unlink } from "node:fs/promises";
|
|
5411
|
+
import path18 from "node:path";
|
|
5412
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
4689
5413
|
var JsonStore;
|
|
4690
5414
|
var init_json_store = __esm({
|
|
4691
5415
|
"src/utils/storage/json_store.ts"() {
|
|
@@ -4705,7 +5429,7 @@ var init_json_store = __esm({
|
|
|
4705
5429
|
}
|
|
4706
5430
|
async load() {
|
|
4707
5431
|
try {
|
|
4708
|
-
return JSON.parse(await
|
|
5432
|
+
return JSON.parse(await readFile8(this.file, "utf8"));
|
|
4709
5433
|
} catch (error) {
|
|
4710
5434
|
if (error.code !== "ENOENT") throw error;
|
|
4711
5435
|
return structuredClone(this.initial);
|
|
@@ -4716,10 +5440,10 @@ var init_json_store = __esm({
|
|
|
4716
5440
|
}).then(async () => {
|
|
4717
5441
|
const state = await this.load();
|
|
4718
5442
|
const result = await change(state);
|
|
4719
|
-
await mkdir8(
|
|
4720
|
-
const temporary = this.file + "." +
|
|
5443
|
+
await mkdir8(path18.dirname(this.file), { recursive: true });
|
|
5444
|
+
const temporary = this.file + "." + randomUUID5();
|
|
4721
5445
|
try {
|
|
4722
|
-
await
|
|
5446
|
+
await writeFile8(temporary, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
|
|
4723
5447
|
await rename2(temporary, this.file);
|
|
4724
5448
|
} finally {
|
|
4725
5449
|
await unlink(temporary).catch((e) => {
|
|
@@ -4765,7 +5489,7 @@ var init_abortable = __esm({
|
|
|
4765
5489
|
});
|
|
4766
5490
|
|
|
4767
5491
|
// src/utils/agents/agent_manager.ts
|
|
4768
|
-
import { randomUUID as
|
|
5492
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
4769
5493
|
var AgentManager;
|
|
4770
5494
|
var init_agent_manager = __esm({
|
|
4771
5495
|
"src/utils/agents/agent_manager.ts"() {
|
|
@@ -4792,12 +5516,12 @@ var init_agent_manager = __esm({
|
|
|
4792
5516
|
this.live.clear();
|
|
4793
5517
|
this.closed = false;
|
|
4794
5518
|
this.store = new JsonStore(file, { agents: [] });
|
|
4795
|
-
for (const
|
|
4796
|
-
if (
|
|
4797
|
-
|
|
4798
|
-
|
|
5519
|
+
for (const record9 of (await this.store.read()).agents) {
|
|
5520
|
+
if (record9.status === "running") {
|
|
5521
|
+
record9.status = "cancelled";
|
|
5522
|
+
record9.error = "Child execution was interrupted; start a new child to retry";
|
|
4799
5523
|
}
|
|
4800
|
-
this.records.set(
|
|
5524
|
+
this.records.set(record9.id, record9);
|
|
4801
5525
|
}
|
|
4802
5526
|
await this.save();
|
|
4803
5527
|
}
|
|
@@ -4809,27 +5533,27 @@ var init_agent_manager = __esm({
|
|
|
4809
5533
|
});
|
|
4810
5534
|
}
|
|
4811
5535
|
get(id) {
|
|
4812
|
-
const
|
|
4813
|
-
if (!
|
|
4814
|
-
return
|
|
5536
|
+
const record9 = this.records.get(id);
|
|
5537
|
+
if (!record9) throw new Error(`Unknown child agent: ${id}`);
|
|
5538
|
+
return record9;
|
|
4815
5539
|
}
|
|
4816
5540
|
list() {
|
|
4817
|
-
return [...this.records.values()].map((
|
|
4818
|
-
agent_id:
|
|
4819
|
-
task:
|
|
4820
|
-
status:
|
|
4821
|
-
session_id:
|
|
4822
|
-
collected:
|
|
5541
|
+
return [...this.records.values()].map((record9) => ({
|
|
5542
|
+
agent_id: record9.id,
|
|
5543
|
+
task: record9.task.slice(0, 240),
|
|
5544
|
+
status: record9.status,
|
|
5545
|
+
session_id: record9.sessionId,
|
|
5546
|
+
collected: record9.collected
|
|
4823
5547
|
}));
|
|
4824
5548
|
}
|
|
4825
5549
|
async start(task, context, signal) {
|
|
4826
5550
|
if (this.closed) throw new Error("Child agent manager is closed");
|
|
4827
5551
|
if (!this.store) throw new Error("Child agents require a bound session");
|
|
4828
5552
|
signal?.throwIfAborted();
|
|
4829
|
-
if ([...this.records.values()].some((
|
|
5553
|
+
if ([...this.records.values()].some((record10) => record10.status === "running"))
|
|
4830
5554
|
throw new Error("Only one child agent may run at a time; wait for the current child before starting another");
|
|
4831
|
-
const
|
|
4832
|
-
id:
|
|
5555
|
+
const record9 = {
|
|
5556
|
+
id: randomUUID6(),
|
|
4833
5557
|
task,
|
|
4834
5558
|
status: "running",
|
|
4835
5559
|
createdAt: Date.now(),
|
|
@@ -4841,7 +5565,7 @@ var init_agent_manager = __esm({
|
|
|
4841
5565
|
const abort = () => controller.abort(owner?.reason);
|
|
4842
5566
|
owner?.addEventListener("abort", abort, { once: true });
|
|
4843
5567
|
if (owner?.aborted) abort();
|
|
4844
|
-
const live = { record:
|
|
5568
|
+
const live = { record: record9, controller, settled: Promise.resolve(), delivery: Promise.resolve() };
|
|
4845
5569
|
let accepted = false;
|
|
4846
5570
|
let begin;
|
|
4847
5571
|
const committed = new Promise((resolve) => {
|
|
@@ -4854,20 +5578,20 @@ var init_agent_manager = __esm({
|
|
|
4854
5578
|
const result = await this.run(task, context, controller.signal, {
|
|
4855
5579
|
bind: (mailbox) => {
|
|
4856
5580
|
live.mailbox = mailbox;
|
|
4857
|
-
|
|
5581
|
+
record9.sessionId = mailbox.sessionId;
|
|
4858
5582
|
this.flush(live);
|
|
4859
5583
|
}
|
|
4860
5584
|
});
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
5585
|
+
record9.result = result;
|
|
5586
|
+
record9.sessionId = result.sessionId;
|
|
5587
|
+
record9.status = controller.signal.aborted ? "cancelled" : "completed";
|
|
4864
5588
|
} catch (error) {
|
|
4865
|
-
|
|
4866
|
-
|
|
5589
|
+
record9.status = controller.signal.aborted ? "cancelled" : "failed";
|
|
5590
|
+
record9.error = error instanceof Error ? error.message : String(error);
|
|
4867
5591
|
} finally {
|
|
4868
5592
|
owner?.removeEventListener("abort", abort);
|
|
4869
5593
|
await live.delivery;
|
|
4870
|
-
for (const message of
|
|
5594
|
+
for (const message of record9.messages)
|
|
4871
5595
|
if (message.status === "queued") {
|
|
4872
5596
|
message.status = "failed";
|
|
4873
5597
|
message.error = "Child ended before accepting the message";
|
|
@@ -4877,22 +5601,22 @@ var init_agent_manager = __esm({
|
|
|
4877
5601
|
});
|
|
4878
5602
|
void live.settled.catch(() => {
|
|
4879
5603
|
});
|
|
4880
|
-
this.records.set(
|
|
4881
|
-
this.live.set(
|
|
5604
|
+
this.records.set(record9.id, record9);
|
|
5605
|
+
this.live.set(record9.id, live);
|
|
4882
5606
|
try {
|
|
4883
5607
|
await this.save();
|
|
4884
5608
|
this.delegated();
|
|
4885
|
-
this.recordOperation({ operation: "create", agent_ids: [
|
|
5609
|
+
this.recordOperation({ operation: "create", agent_ids: [record9.id] });
|
|
4886
5610
|
accepted = true;
|
|
4887
5611
|
} catch (error) {
|
|
4888
5612
|
owner?.removeEventListener("abort", abort);
|
|
4889
|
-
this.records.delete(
|
|
4890
|
-
this.live.delete(
|
|
5613
|
+
this.records.delete(record9.id);
|
|
5614
|
+
this.live.delete(record9.id);
|
|
4891
5615
|
throw error;
|
|
4892
5616
|
} finally {
|
|
4893
5617
|
begin();
|
|
4894
5618
|
}
|
|
4895
|
-
return { agent_id:
|
|
5619
|
+
return { agent_id: record9.id, status: record9.status };
|
|
4896
5620
|
}
|
|
4897
5621
|
flush(live) {
|
|
4898
5622
|
if (!live.mailbox) return;
|
|
@@ -4915,12 +5639,12 @@ var init_agent_manager = __esm({
|
|
|
4915
5639
|
}
|
|
4916
5640
|
async send(id, text2, signal) {
|
|
4917
5641
|
signal?.throwIfAborted();
|
|
4918
|
-
const
|
|
5642
|
+
const record9 = this.get(id);
|
|
4919
5643
|
const live = this.live.get(id);
|
|
4920
|
-
if (
|
|
5644
|
+
if (record9.status !== "running" || !live)
|
|
4921
5645
|
throw new Error("Messages can only be sent to a running child; start a new child for another task");
|
|
4922
|
-
const message = { id:
|
|
4923
|
-
|
|
5646
|
+
const message = { id: randomUUID6(), text: text2, status: "queued" };
|
|
5647
|
+
record9.messages.push(message);
|
|
4924
5648
|
await this.save();
|
|
4925
5649
|
this.recordOperation({ operation: "send", agent_ids: [id], message_id: message.id });
|
|
4926
5650
|
this.flush(live);
|
|
@@ -4930,15 +5654,15 @@ var init_agent_manager = __esm({
|
|
|
4930
5654
|
message_id: message.id,
|
|
4931
5655
|
status: message.status,
|
|
4932
5656
|
error: message.error,
|
|
4933
|
-
agent_status:
|
|
5657
|
+
agent_status: record9.status
|
|
4934
5658
|
};
|
|
4935
5659
|
}
|
|
4936
5660
|
async wait(ids, timeoutMs, signal, automatic = false) {
|
|
4937
5661
|
signal?.throwIfAborted();
|
|
4938
5662
|
const records = [...new Set(ids)].map((id) => this.get(id));
|
|
4939
|
-
this.recordOperation({ operation: "wait", agent_ids: records.map((
|
|
5663
|
+
this.recordOperation({ operation: "wait", agent_ids: records.map((record9) => record9.id), automatic });
|
|
4940
5664
|
const settled = Promise.all(
|
|
4941
|
-
records.filter((
|
|
5665
|
+
records.filter((record9) => record9.status === "running").map((record9) => this.live.get(record9.id).settled)
|
|
4942
5666
|
);
|
|
4943
5667
|
let timer;
|
|
4944
5668
|
try {
|
|
@@ -4954,21 +5678,21 @@ var init_agent_manager = __esm({
|
|
|
4954
5678
|
} finally {
|
|
4955
5679
|
if (timer) clearTimeout(timer);
|
|
4956
5680
|
}
|
|
4957
|
-
for (const
|
|
5681
|
+
for (const record9 of records) if (record9.status !== "running") record9.collected = true;
|
|
4958
5682
|
await this.save();
|
|
4959
5683
|
return {
|
|
4960
|
-
agents: records.map((
|
|
4961
|
-
agent_id:
|
|
4962
|
-
status:
|
|
4963
|
-
session_id:
|
|
4964
|
-
result:
|
|
4965
|
-
error:
|
|
5684
|
+
agents: records.map((record9) => ({
|
|
5685
|
+
agent_id: record9.id,
|
|
5686
|
+
status: record9.status,
|
|
5687
|
+
session_id: record9.sessionId,
|
|
5688
|
+
result: record9.result,
|
|
5689
|
+
error: record9.error
|
|
4966
5690
|
})),
|
|
4967
|
-
timed_out: records.some((
|
|
5691
|
+
timed_out: records.some((record9) => record9.status === "running")
|
|
4968
5692
|
};
|
|
4969
5693
|
}
|
|
4970
5694
|
uncollected() {
|
|
4971
|
-
return [...this.records.values()].filter((
|
|
5695
|
+
return [...this.records.values()].filter((record9) => !record9.collected).map((record9) => record9.id);
|
|
4972
5696
|
}
|
|
4973
5697
|
async cancelAll() {
|
|
4974
5698
|
for (const live of this.live.values())
|
|
@@ -4984,8 +5708,8 @@ var init_agent_manager = __esm({
|
|
|
4984
5708
|
});
|
|
4985
5709
|
|
|
4986
5710
|
// src/utils/filesystem/apply_patch.ts
|
|
4987
|
-
import { mkdir as mkdir9, readFile as
|
|
4988
|
-
import
|
|
5711
|
+
import { mkdir as mkdir9, readFile as readFile9, stat, unlink as unlink2, writeFile as writeFile9 } from "node:fs/promises";
|
|
5712
|
+
import path19 from "node:path";
|
|
4989
5713
|
function patchError(message) {
|
|
4990
5714
|
return new Error(`Invalid patch: ${message}`);
|
|
4991
5715
|
}
|
|
@@ -5328,8 +6052,8 @@ function throwIfAborted(signal) {
|
|
|
5328
6052
|
}
|
|
5329
6053
|
async function writeWithParents(target, contents, signal) {
|
|
5330
6054
|
throwIfAborted(signal);
|
|
5331
|
-
await mkdir9(
|
|
5332
|
-
await
|
|
6055
|
+
await mkdir9(path19.dirname(target), { recursive: true });
|
|
6056
|
+
await writeFile9(target, contents, { encoding: "utf8", signal });
|
|
5333
6057
|
}
|
|
5334
6058
|
function formatApplyPatchSummary(paths) {
|
|
5335
6059
|
const rows = [
|
|
@@ -5362,16 +6086,16 @@ async function applyPatch(cwd, patch, signal) {
|
|
|
5362
6086
|
}
|
|
5363
6087
|
const target = await resolveWorkspacePath(cwd, hunk.path);
|
|
5364
6088
|
await requireRegularFile(target, "Failed to read file to update");
|
|
5365
|
-
const before = await
|
|
6089
|
+
const before = await readFile9(target, { encoding: "utf8", signal });
|
|
5366
6090
|
const after = applyUpdate(before, target, hunk.chunks);
|
|
5367
6091
|
if (hunk.movePath === void 0) {
|
|
5368
|
-
await
|
|
6092
|
+
await writeFile9(target, after, { encoding: "utf8", signal });
|
|
5369
6093
|
affected.modified.push(hunk.path);
|
|
5370
6094
|
continue;
|
|
5371
6095
|
}
|
|
5372
6096
|
const destination = await resolveWorkspacePath(cwd, hunk.movePath);
|
|
5373
6097
|
if (destination === target) {
|
|
5374
|
-
await
|
|
6098
|
+
await writeFile9(target, after, { encoding: "utf8", signal });
|
|
5375
6099
|
} else {
|
|
5376
6100
|
await writeWithParents(destination, after, signal);
|
|
5377
6101
|
await unlink2(target);
|
|
@@ -5517,20 +6241,20 @@ var init_grep = __esm({
|
|
|
5517
6241
|
});
|
|
5518
6242
|
|
|
5519
6243
|
// src/utils/filesystem/text_edit.ts
|
|
5520
|
-
import { readFile as
|
|
5521
|
-
import { randomUUID as
|
|
6244
|
+
import { readFile as readFile10, writeFile as writeFile10, rename as rename3, stat as stat2, unlink as unlink3 } from "node:fs/promises";
|
|
6245
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
5522
6246
|
async function updateTextFile(target, edit, signal) {
|
|
5523
6247
|
const previous = locks.get(target) ?? Promise.resolve();
|
|
5524
6248
|
const next = previous.catch(() => {
|
|
5525
6249
|
}).then(async () => {
|
|
5526
6250
|
signal?.throwIfAborted();
|
|
5527
|
-
const [original, metadata] = await Promise.all([
|
|
6251
|
+
const [original, metadata] = await Promise.all([readFile10(target, "utf8"), stat2(target)]);
|
|
5528
6252
|
const modified = edit(original);
|
|
5529
|
-
const temporary = target + ".scaling-" +
|
|
6253
|
+
const temporary = target + ".scaling-" + randomUUID7();
|
|
5530
6254
|
try {
|
|
5531
|
-
await
|
|
6255
|
+
await writeFile10(temporary, modified, { flag: "wx", mode: metadata.mode });
|
|
5532
6256
|
signal?.throwIfAborted();
|
|
5533
|
-
if (await
|
|
6257
|
+
if (await readFile10(target, "utf8") !== original)
|
|
5534
6258
|
throw new Error("File changed during edit; read it again before retrying");
|
|
5535
6259
|
await rename3(temporary, target);
|
|
5536
6260
|
} finally {
|
|
@@ -5557,7 +6281,7 @@ var init_text_edit = __esm({
|
|
|
5557
6281
|
// src/capabilities/tools/filesystem/notebook_edit.ts
|
|
5558
6282
|
import { defineTool as defineTool37 } from "@earendil-works/pi-coding-agent";
|
|
5559
6283
|
import { Type as Type35 } from "typebox";
|
|
5560
|
-
import { randomUUID as
|
|
6284
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
5561
6285
|
function createNotebookEditTool(cwd) {
|
|
5562
6286
|
return defineTool37({
|
|
5563
6287
|
name: "notebook_edit",
|
|
@@ -5584,7 +6308,7 @@ function createNotebookEditTool(cwd) {
|
|
|
5584
6308
|
if (args.action === "delete") notebook.cells.splice(index, 1);
|
|
5585
6309
|
else {
|
|
5586
6310
|
if (args.source === void 0) throw new Error("source is required for replace/insert");
|
|
5587
|
-
const cell = args.action === "insert" ? { id:
|
|
6311
|
+
const cell = args.action === "insert" ? { id: randomUUID8().slice(0, 8), metadata: {} } : notebook.cells[index];
|
|
5588
6312
|
cell.cell_type = args.cell_type ?? cell.cell_type ?? "code";
|
|
5589
6313
|
cell.source = args.source.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
5590
6314
|
if (cell.cell_type === "code") {
|
|
@@ -5947,13 +6671,13 @@ var init_read_mcp_resource = __esm({
|
|
|
5947
6671
|
});
|
|
5948
6672
|
|
|
5949
6673
|
// src/utils/execution/process_manager.ts
|
|
5950
|
-
import { spawn as
|
|
6674
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
5951
6675
|
import { closeSync, mkdtempSync, openSync, writeSync } from "node:fs";
|
|
5952
|
-
import { open as open2, rm as
|
|
5953
|
-
import { tmpdir as
|
|
5954
|
-
import
|
|
5955
|
-
import { randomUUID as
|
|
5956
|
-
import { setTimeout as
|
|
6676
|
+
import { open as open2, rm as rm5 } from "node:fs/promises";
|
|
6677
|
+
import { tmpdir as tmpdir4 } from "node:os";
|
|
6678
|
+
import path20 from "node:path";
|
|
6679
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
6680
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
5957
6681
|
import { getShellConfig as getShellConfig3 } from "@earendil-works/pi-coding-agent";
|
|
5958
6682
|
var ProcessManager;
|
|
5959
6683
|
var init_process_manager = __esm({
|
|
@@ -5971,14 +6695,14 @@ var init_process_manager = __esm({
|
|
|
5971
6695
|
if (this.disposed) throw new Error("Process manager is closed");
|
|
5972
6696
|
if ([...this.processes.values()].filter((p) => p.running).length >= 32)
|
|
5973
6697
|
throw new Error("At most 32 background processes may run at once");
|
|
5974
|
-
this.directory ??= mkdtempSync(
|
|
5975
|
-
const id =
|
|
5976
|
-
const outputPath =
|
|
6698
|
+
this.directory ??= mkdtempSync(path20.join(tmpdir4(), "scaling-processes-"));
|
|
6699
|
+
const id = randomUUID9();
|
|
6700
|
+
const outputPath = path20.join(this.directory, id + ".log");
|
|
5977
6701
|
const fd = openSync(outputPath, "wx", 384);
|
|
5978
6702
|
const shell = getShellConfig3();
|
|
5979
6703
|
let child;
|
|
5980
6704
|
try {
|
|
5981
|
-
child =
|
|
6705
|
+
child = spawn5(shell.shell, [...shell.args, command], {
|
|
5982
6706
|
cwd,
|
|
5983
6707
|
detached: process.platform !== "win32",
|
|
5984
6708
|
stdio: "pipe",
|
|
@@ -5989,7 +6713,7 @@ var init_process_manager = __esm({
|
|
|
5989
6713
|
throw error;
|
|
5990
6714
|
}
|
|
5991
6715
|
let finish;
|
|
5992
|
-
const
|
|
6716
|
+
const record9 = {
|
|
5993
6717
|
id,
|
|
5994
6718
|
command,
|
|
5995
6719
|
cwd,
|
|
@@ -6006,44 +6730,44 @@ var init_process_manager = __esm({
|
|
|
6006
6730
|
}),
|
|
6007
6731
|
listeners: /* @__PURE__ */ new Set()
|
|
6008
6732
|
};
|
|
6009
|
-
this.processes.set(id,
|
|
6733
|
+
this.processes.set(id, record9);
|
|
6010
6734
|
const append = (chunk) => {
|
|
6011
6735
|
writeSync(fd, chunk);
|
|
6012
|
-
|
|
6013
|
-
for (const listener of
|
|
6736
|
+
record9.bytes += chunk.length;
|
|
6737
|
+
for (const listener of record9.listeners) listener(chunk);
|
|
6014
6738
|
};
|
|
6015
6739
|
child.stdout.on("data", append);
|
|
6016
6740
|
child.stderr.on("data", append);
|
|
6017
6741
|
child.stdin.on("error", () => {
|
|
6018
6742
|
});
|
|
6019
6743
|
child.once("error", (error) => {
|
|
6020
|
-
|
|
6744
|
+
record9.error = error.message;
|
|
6021
6745
|
});
|
|
6022
6746
|
const timer = timeoutSeconds === void 0 ? void 0 : setTimeout(() => {
|
|
6023
|
-
|
|
6024
|
-
this.terminate(
|
|
6747
|
+
record9.error = "Process timed out";
|
|
6748
|
+
this.terminate(record9);
|
|
6025
6749
|
}, timeoutSeconds * 1e3);
|
|
6026
6750
|
timer?.unref();
|
|
6027
6751
|
child.once("close", (code, signal) => {
|
|
6028
6752
|
if (timer) clearTimeout(timer);
|
|
6029
|
-
|
|
6030
|
-
|
|
6031
|
-
|
|
6753
|
+
record9.exitCode = code;
|
|
6754
|
+
record9.exitSignal = signal;
|
|
6755
|
+
record9.running = false;
|
|
6032
6756
|
closeSync(fd);
|
|
6033
6757
|
finish();
|
|
6034
6758
|
});
|
|
6035
6759
|
return id;
|
|
6036
6760
|
}
|
|
6037
6761
|
get(id) {
|
|
6038
|
-
const
|
|
6039
|
-
if (!
|
|
6040
|
-
return
|
|
6762
|
+
const record9 = this.processes.get(id);
|
|
6763
|
+
if (!record9) throw new Error(`Unknown process: ${id}`);
|
|
6764
|
+
return record9;
|
|
6041
6765
|
}
|
|
6042
|
-
terminate(
|
|
6766
|
+
terminate(record9) {
|
|
6043
6767
|
const kill = (signal) => {
|
|
6044
6768
|
try {
|
|
6045
|
-
if (process.platform === "win32")
|
|
6046
|
-
else if (
|
|
6769
|
+
if (process.platform === "win32") record9.child.kill(signal);
|
|
6770
|
+
else if (record9.child.pid) process.kill(-record9.child.pid, signal);
|
|
6047
6771
|
} catch (error) {
|
|
6048
6772
|
if (error.code !== "ESRCH") throw error;
|
|
6049
6773
|
}
|
|
@@ -6066,21 +6790,21 @@ var init_process_manager = __esm({
|
|
|
6066
6790
|
}));
|
|
6067
6791
|
}
|
|
6068
6792
|
observe(id, listener) {
|
|
6069
|
-
const
|
|
6070
|
-
|
|
6071
|
-
return () =>
|
|
6793
|
+
const record9 = this.get(id);
|
|
6794
|
+
record9.listeners.add(listener);
|
|
6795
|
+
return () => record9.listeners.delete(listener);
|
|
6072
6796
|
}
|
|
6073
6797
|
finished(id) {
|
|
6074
6798
|
return this.get(id).finished;
|
|
6075
6799
|
}
|
|
6076
6800
|
async wait(id, milliseconds, signal) {
|
|
6077
|
-
const
|
|
6801
|
+
const record9 = this.get(id);
|
|
6078
6802
|
signal?.throwIfAborted();
|
|
6079
6803
|
const controller = new AbortController();
|
|
6080
6804
|
const abort = () => controller.abort(signal?.reason);
|
|
6081
6805
|
signal?.addEventListener("abort", abort, { once: true });
|
|
6082
6806
|
try {
|
|
6083
|
-
await Promise.race([
|
|
6807
|
+
await Promise.race([record9.finished, delay3(milliseconds, void 0, { signal: controller.signal })]);
|
|
6084
6808
|
signal?.throwIfAborted();
|
|
6085
6809
|
} finally {
|
|
6086
6810
|
controller.abort();
|
|
@@ -6088,34 +6812,34 @@ var init_process_manager = __esm({
|
|
|
6088
6812
|
}
|
|
6089
6813
|
}
|
|
6090
6814
|
async read(id, offset, maxBytes = 64e3) {
|
|
6091
|
-
const
|
|
6092
|
-
const start = offset ??
|
|
6093
|
-
if (!Number.isSafeInteger(start) || start < 0 || start >
|
|
6815
|
+
const record9 = this.get(id);
|
|
6816
|
+
const start = offset ?? record9.cursor;
|
|
6817
|
+
if (!Number.isSafeInteger(start) || start < 0 || start > record9.bytes)
|
|
6094
6818
|
throw new Error("Invalid output byte offset");
|
|
6095
|
-
const file = await open2(
|
|
6096
|
-
const buffer = Buffer.alloc(Math.min(maxBytes + 3, Math.max(0,
|
|
6819
|
+
const file = await open2(record9.outputPath, "r");
|
|
6820
|
+
const buffer = Buffer.alloc(Math.min(maxBytes + 3, Math.max(0, record9.bytes - start)));
|
|
6097
6821
|
try {
|
|
6098
6822
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
|
|
6099
6823
|
let end = Math.min(maxBytes, bytesRead);
|
|
6100
6824
|
while (end < bytesRead && (buffer[end] & 192) === 128) end++;
|
|
6101
|
-
if (
|
|
6825
|
+
if (record9.running && end === bytesRead && end > 0) {
|
|
6102
6826
|
let lead = end - 1;
|
|
6103
6827
|
while (lead > 0 && (buffer[lead] & 192) === 128) lead--;
|
|
6104
6828
|
const first = buffer[lead];
|
|
6105
6829
|
const expected = first >= 240 ? 4 : first >= 224 ? 3 : first >= 192 ? 2 : 1;
|
|
6106
6830
|
if (end - lead < expected) end = lead;
|
|
6107
6831
|
}
|
|
6108
|
-
|
|
6832
|
+
record9.cursor = start + end;
|
|
6109
6833
|
return {
|
|
6110
6834
|
process_id: id,
|
|
6111
6835
|
output: buffer.subarray(0, end).toString("utf8"),
|
|
6112
6836
|
offset: start,
|
|
6113
|
-
next_offset:
|
|
6114
|
-
output_path:
|
|
6115
|
-
running:
|
|
6116
|
-
exit_code:
|
|
6117
|
-
signal:
|
|
6118
|
-
error:
|
|
6837
|
+
next_offset: record9.cursor,
|
|
6838
|
+
output_path: record9.outputPath,
|
|
6839
|
+
running: record9.running,
|
|
6840
|
+
exit_code: record9.exitCode,
|
|
6841
|
+
signal: record9.exitSignal,
|
|
6842
|
+
error: record9.error
|
|
6119
6843
|
};
|
|
6120
6844
|
} finally {
|
|
6121
6845
|
await file.close();
|
|
@@ -6137,7 +6861,7 @@ var init_process_manager = __esm({
|
|
|
6137
6861
|
async dispose() {
|
|
6138
6862
|
this.disposed = true;
|
|
6139
6863
|
await Promise.all([...this.processes.keys()].map((id) => this.stop(id)));
|
|
6140
|
-
if (this.directory) await
|
|
6864
|
+
if (this.directory) await rm5(this.directory, { recursive: true, force: true });
|
|
6141
6865
|
}
|
|
6142
6866
|
};
|
|
6143
6867
|
}
|
|
@@ -6226,7 +6950,7 @@ var init_client_pool = __esm({
|
|
|
6226
6950
|
});
|
|
6227
6951
|
|
|
6228
6952
|
// src/utils/memory/memory_store.ts
|
|
6229
|
-
import { randomUUID as
|
|
6953
|
+
import { randomUUID as randomUUID10 } from "node:crypto";
|
|
6230
6954
|
var MemoryStore;
|
|
6231
6955
|
var init_memory_store = __esm({
|
|
6232
6956
|
"src/utils/memory/memory_store.ts"() {
|
|
@@ -6257,7 +6981,7 @@ var init_memory_store = __esm({
|
|
|
6257
6981
|
const index = input.id ? state.entries.findIndex((e) => e.id === input.id) : -1;
|
|
6258
6982
|
if (input.id && index < 0) throw new Error(`Unknown memory entry: ${input.id}`);
|
|
6259
6983
|
const entry = {
|
|
6260
|
-
id: input.id ??
|
|
6984
|
+
id: input.id ?? randomUUID10(),
|
|
6261
6985
|
title: input.title,
|
|
6262
6986
|
content: input.content,
|
|
6263
6987
|
tags: input.tags ?? (index < 0 ? [] : state.entries[index].tags),
|
|
@@ -6273,8 +6997,8 @@ var init_memory_store = __esm({
|
|
|
6273
6997
|
});
|
|
6274
6998
|
|
|
6275
6999
|
// src/utils/skills/skill_store.ts
|
|
6276
|
-
import { readFile as
|
|
6277
|
-
import
|
|
7000
|
+
import { readFile as readFile11, mkdir as mkdir10, writeFile as writeFile11, rm as rm6, realpath as realpath2 } from "node:fs/promises";
|
|
7001
|
+
import path21 from "node:path";
|
|
6278
7002
|
import { loadSkills } from "@earendil-works/pi-coding-agent";
|
|
6279
7003
|
var SkillStore;
|
|
6280
7004
|
var init_skill_store = __esm({
|
|
@@ -6289,7 +7013,7 @@ var init_skill_store = __esm({
|
|
|
6289
7013
|
constructor(cwd, managedRoot, roots = []) {
|
|
6290
7014
|
this.cwd = cwd;
|
|
6291
7015
|
this.managedRoot = managedRoot;
|
|
6292
|
-
this.roots = roots.map((root) =>
|
|
7016
|
+
this.roots = roots.map((root) => path21.resolve(cwd, root));
|
|
6293
7017
|
}
|
|
6294
7018
|
list() {
|
|
6295
7019
|
return loadSkills({
|
|
@@ -6306,7 +7030,7 @@ var init_skill_store = __esm({
|
|
|
6306
7030
|
}
|
|
6307
7031
|
async read(name) {
|
|
6308
7032
|
const skill = this.find(name);
|
|
6309
|
-
return { name: skill.name, base_directory: skill.baseDir, content: await
|
|
7033
|
+
return { name: skill.name, base_directory: skill.baseDir, content: await readFile11(skill.filePath, "utf8") };
|
|
6310
7034
|
}
|
|
6311
7035
|
async manage(input) {
|
|
6312
7036
|
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(input.name)) throw new Error("Skill name must be a lowercase slug");
|
|
@@ -6317,30 +7041,30 @@ var init_skill_store = __esm({
|
|
|
6317
7041
|
throw new Error("content must contain a complete SKILL.md with name and description frontmatter");
|
|
6318
7042
|
await mkdir10(directory);
|
|
6319
7043
|
try {
|
|
6320
|
-
await
|
|
7044
|
+
await writeFile11(path21.join(directory, "SKILL.md"), input.content, { flag: "wx" });
|
|
6321
7045
|
const skill = this.list().skills.find((s) => s.name === input.name);
|
|
6322
7046
|
if (!skill || await realpath2(skill.baseDir) !== directory)
|
|
6323
7047
|
throw new Error("Invalid SKILL.md frontmatter, or name does not match the requested skill");
|
|
6324
7048
|
} catch (error) {
|
|
6325
|
-
await
|
|
7049
|
+
await rm6(directory, { recursive: true, force: true });
|
|
6326
7050
|
throw error;
|
|
6327
7051
|
}
|
|
6328
7052
|
} else {
|
|
6329
7053
|
const skill = this.find(input.name);
|
|
6330
7054
|
if (await realpath2(skill.baseDir) !== directory)
|
|
6331
7055
|
throw new Error("Only run-owned skills can be modified; source skills are read-only");
|
|
6332
|
-
if (input.action === "delete") await
|
|
7056
|
+
if (input.action === "delete") await rm6(directory, { recursive: true });
|
|
6333
7057
|
else {
|
|
6334
7058
|
const target = await resolveWorkspacePath(directory, input.path ?? "SKILL.md");
|
|
6335
|
-
const isSkillFile = target ===
|
|
7059
|
+
const isSkillFile = target === path21.join(directory, "SKILL.md");
|
|
6336
7060
|
if (input.action === "remove_file") {
|
|
6337
7061
|
if (isSkillFile) throw new Error("Use delete to remove the whole skill");
|
|
6338
|
-
await
|
|
7062
|
+
await rm6(target);
|
|
6339
7063
|
} else if (input.action === "write_file") {
|
|
6340
7064
|
if (input.content === void 0) throw new Error("content is required");
|
|
6341
7065
|
if (isSkillFile) throw new Error("Use patch to update SKILL.md");
|
|
6342
|
-
await mkdir10(
|
|
6343
|
-
await
|
|
7066
|
+
await mkdir10(path21.dirname(target), { recursive: true });
|
|
7067
|
+
await writeFile11(target, input.content);
|
|
6344
7068
|
} else {
|
|
6345
7069
|
if (!input.old_string || input.new_string === void 0)
|
|
6346
7070
|
throw new Error("old_string and new_string are required");
|
|
@@ -6362,17 +7086,17 @@ var init_skill_store = __esm({
|
|
|
6362
7086
|
|
|
6363
7087
|
// src/utils/filesystem/worktree_manager.ts
|
|
6364
7088
|
import { execFile } from "node:child_process";
|
|
6365
|
-
import { promisify } from "node:util";
|
|
7089
|
+
import { promisify as promisify2 } from "node:util";
|
|
6366
7090
|
import { mkdir as mkdir11 } from "node:fs/promises";
|
|
6367
|
-
import { randomUUID as
|
|
6368
|
-
import
|
|
7091
|
+
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
7092
|
+
import path22 from "node:path";
|
|
6369
7093
|
var execute, WorktreeManager;
|
|
6370
7094
|
var init_worktree_manager = __esm({
|
|
6371
7095
|
"src/utils/filesystem/worktree_manager.ts"() {
|
|
6372
7096
|
"use strict";
|
|
6373
7097
|
init_json_store();
|
|
6374
7098
|
init_workspace();
|
|
6375
|
-
execute =
|
|
7099
|
+
execute = promisify2(execFile);
|
|
6376
7100
|
WorktreeManager = class {
|
|
6377
7101
|
cwd;
|
|
6378
7102
|
store;
|
|
@@ -6382,16 +7106,16 @@ var init_worktree_manager = __esm({
|
|
|
6382
7106
|
}
|
|
6383
7107
|
async enter(name, signal) {
|
|
6384
7108
|
if (/[\\/]\.pi[\\/]worktrees[\\/]/u.test(this.cwd)) throw new Error("Nested managed worktrees are not supported");
|
|
6385
|
-
const slug = name ?? "task-" +
|
|
7109
|
+
const slug = name ?? "task-" + randomUUID11().slice(0, 8);
|
|
6386
7110
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/u.test(slug))
|
|
6387
7111
|
throw new Error("Worktree name must be a slug of at most 64 characters");
|
|
6388
7112
|
const { stdout } = await execute("git", ["rev-parse", "--show-toplevel"], { cwd: this.cwd, signal });
|
|
6389
7113
|
const root = stdout.trim();
|
|
6390
|
-
const directory = await resolveWorkspacePath(root,
|
|
6391
|
-
await mkdir11(
|
|
7114
|
+
const directory = await resolveWorkspacePath(root, path22.join(".pi", "worktrees", slug));
|
|
7115
|
+
await mkdir11(path22.dirname(directory), { recursive: true });
|
|
6392
7116
|
const branch = "dragon/" + slug;
|
|
6393
7117
|
await execute("git", ["worktree", "add", "-b", branch, directory, "HEAD"], { cwd: root, signal });
|
|
6394
|
-
const worktree = { id:
|
|
7118
|
+
const worktree = { id: randomUUID11(), path: directory, branch, status: "active" };
|
|
6395
7119
|
await this.store.update((state) => {
|
|
6396
7120
|
state.worktrees.push(worktree);
|
|
6397
7121
|
});
|
|
@@ -6416,8 +7140,8 @@ var init_worktree_manager = __esm({
|
|
|
6416
7140
|
|
|
6417
7141
|
// src/utils/secrets/secret_vault.ts
|
|
6418
7142
|
import { randomBytes, createCipheriv, createDecipheriv } from "node:crypto";
|
|
6419
|
-
import { mkdir as mkdir12, readFile as
|
|
6420
|
-
import
|
|
7143
|
+
import { mkdir as mkdir12, readFile as readFile12, writeFile as writeFile12 } from "node:fs/promises";
|
|
7144
|
+
import path23 from "node:path";
|
|
6421
7145
|
var SecretVault;
|
|
6422
7146
|
var init_secret_vault = __esm({
|
|
6423
7147
|
"src/utils/secrets/secret_vault.ts"() {
|
|
@@ -6430,26 +7154,26 @@ var init_secret_vault = __esm({
|
|
|
6430
7154
|
constructor(root, parent) {
|
|
6431
7155
|
this.root = root;
|
|
6432
7156
|
this.parent = parent;
|
|
6433
|
-
this.store = new JsonStore(
|
|
7157
|
+
this.store = new JsonStore(path23.join(root, "vault.json"), { entries: [] });
|
|
6434
7158
|
}
|
|
6435
7159
|
name(name) {
|
|
6436
7160
|
if (!/^[A-Za-z0-9_-]{1,128}$/u.test(name)) throw new Error("Secret name must be an identifier");
|
|
6437
7161
|
return name;
|
|
6438
7162
|
}
|
|
6439
7163
|
async key() {
|
|
6440
|
-
const file =
|
|
7164
|
+
const file = path23.join(this.root, "key");
|
|
6441
7165
|
await mkdir12(this.root, { recursive: true, mode: 448 });
|
|
6442
7166
|
let key;
|
|
6443
7167
|
try {
|
|
6444
|
-
key = await
|
|
7168
|
+
key = await readFile12(file);
|
|
6445
7169
|
} catch (error) {
|
|
6446
7170
|
if (error.code !== "ENOENT") throw error;
|
|
6447
7171
|
try {
|
|
6448
|
-
await
|
|
7172
|
+
await writeFile12(file, randomBytes(32), { flag: "wx", mode: 384 });
|
|
6449
7173
|
} catch (writeError) {
|
|
6450
7174
|
if (writeError.code !== "EEXIST") throw writeError;
|
|
6451
7175
|
}
|
|
6452
|
-
key = await
|
|
7176
|
+
key = await readFile12(file);
|
|
6453
7177
|
}
|
|
6454
7178
|
if (key.length !== 32) throw new Error("Invalid secret vault key");
|
|
6455
7179
|
return key;
|
|
@@ -6511,12 +7235,12 @@ var init_secret_vault = __esm({
|
|
|
6511
7235
|
});
|
|
6512
7236
|
|
|
6513
7237
|
// src/capabilities/task-tool-space.ts
|
|
6514
|
-
import
|
|
7238
|
+
import path24 from "node:path";
|
|
6515
7239
|
function createBaseTaskToolSpace(options) {
|
|
6516
7240
|
const { cwd, stateDirectory } = options;
|
|
6517
7241
|
const settings = options.settings ?? loadCapabilitySettings(cwd);
|
|
6518
7242
|
const processes = new ProcessManager(cwd);
|
|
6519
|
-
const secrets = new SecretVault(
|
|
7243
|
+
const secrets = new SecretVault(path24.join(stateDirectory, "secrets"), options.parentSecrets);
|
|
6520
7244
|
const resolveRecord = async (value) => value ? Object.fromEntries(
|
|
6521
7245
|
await Promise.all(Object.entries(value).map(async ([key, text2]) => [key, await secrets.interpolate(text2)]))
|
|
6522
7246
|
) : void 0;
|
|
@@ -6529,15 +7253,15 @@ function createBaseTaskToolSpace(options) {
|
|
|
6529
7253
|
...resolved,
|
|
6530
7254
|
options: {
|
|
6531
7255
|
...resolved.options,
|
|
6532
|
-
cwd:
|
|
7256
|
+
cwd: path24.resolve(cwd, resolved.options.cwd ?? "."),
|
|
6533
7257
|
env: await resolveRecord(resolved.options.env)
|
|
6534
7258
|
}
|
|
6535
7259
|
};
|
|
6536
7260
|
}
|
|
6537
7261
|
});
|
|
6538
|
-
const memory = new MemoryStore(
|
|
6539
|
-
const skills = new SkillStore(cwd,
|
|
6540
|
-
const worktrees = new WorktreeManager(cwd,
|
|
7262
|
+
const memory = new MemoryStore(path24.join(stateDirectory, "memory.json"), options.initialMemory);
|
|
7263
|
+
const skills = new SkillStore(cwd, path24.join(stateDirectory, "skills"), options.skillPaths);
|
|
7264
|
+
const worktrees = new WorktreeManager(cwd, path24.join(stateDirectory, "worktrees.json"));
|
|
6541
7265
|
const tools = [
|
|
6542
7266
|
createReadFileTool(cwd),
|
|
6543
7267
|
createApplyPatchTool(cwd),
|
|
@@ -6614,8 +7338,8 @@ var init_task_tool_space = __esm({
|
|
|
6614
7338
|
});
|
|
6615
7339
|
|
|
6616
7340
|
// src/utils/clients/media/video_jobs.ts
|
|
6617
|
-
import { mkdir as mkdir13, writeFile as
|
|
6618
|
-
import
|
|
7341
|
+
import { mkdir as mkdir13, writeFile as writeFile13 } from "node:fs/promises";
|
|
7342
|
+
import path25 from "node:path";
|
|
6619
7343
|
var VideoJobs;
|
|
6620
7344
|
var init_video_jobs = __esm({
|
|
6621
7345
|
"src/utils/clients/media/video_jobs.ts"() {
|
|
@@ -6684,10 +7408,10 @@ var init_video_jobs = __esm({
|
|
|
6684
7408
|
const target = await resolveWorkspacePath(this.cwd, filePath);
|
|
6685
7409
|
const response = await fetch(url, { signal });
|
|
6686
7410
|
if (!response.ok) throw new Error(`Video download failed: ${response.status}`);
|
|
6687
|
-
const bytes = await
|
|
7411
|
+
const bytes = await responseBytes2(response, 200 * 1024 * 1024);
|
|
6688
7412
|
signal?.throwIfAborted();
|
|
6689
|
-
await mkdir13(
|
|
6690
|
-
await
|
|
7413
|
+
await mkdir13(path25.dirname(target), { recursive: true });
|
|
7414
|
+
await writeFile13(target, bytes, { signal });
|
|
6691
7415
|
}
|
|
6692
7416
|
return { task_id: taskId, status, video_url: url, file_path: filePath, usage: payload.usage };
|
|
6693
7417
|
}
|
|
@@ -6696,7 +7420,7 @@ var init_video_jobs = __esm({
|
|
|
6696
7420
|
});
|
|
6697
7421
|
|
|
6698
7422
|
// src/utils/scheduling/scheduler.ts
|
|
6699
|
-
import { randomUUID as
|
|
7423
|
+
import { randomUUID as randomUUID12 } from "node:crypto";
|
|
6700
7424
|
import { Cron } from "croner";
|
|
6701
7425
|
var Scheduler;
|
|
6702
7426
|
var init_scheduler = __esm({
|
|
@@ -6776,7 +7500,7 @@ var init_scheduler = __esm({
|
|
|
6776
7500
|
if (Number(input.cron !== void 0) + Number(input.at !== void 0) !== 1)
|
|
6777
7501
|
throw new Error("Provide exactly one cron expression or future timestamp");
|
|
6778
7502
|
const job = {
|
|
6779
|
-
id:
|
|
7503
|
+
id: randomUUID12(),
|
|
6780
7504
|
prompt: input.prompt,
|
|
6781
7505
|
cron: input.cron,
|
|
6782
7506
|
at: input.at,
|
|
@@ -6785,8 +7509,8 @@ var init_scheduler = __esm({
|
|
|
6785
7509
|
status: "scheduled"
|
|
6786
7510
|
};
|
|
6787
7511
|
if (job.at) {
|
|
6788
|
-
const
|
|
6789
|
-
if (!Number.isFinite(
|
|
7512
|
+
const delay4 = new Date(job.at).getTime() - Date.now();
|
|
7513
|
+
if (!Number.isFinite(delay4) || delay4 <= 0 || delay4 > 864e5)
|
|
6790
7514
|
throw new Error("Wakeup must be within the next 24 hours");
|
|
6791
7515
|
} else {
|
|
6792
7516
|
const validation = new Cron(job.cron, { paused: true, timezone: job.timezone });
|
|
@@ -6830,9 +7554,9 @@ var init_scheduler = __esm({
|
|
|
6830
7554
|
});
|
|
6831
7555
|
|
|
6832
7556
|
// src/utils/lsp/lsp_manager.ts
|
|
6833
|
-
import { spawn as
|
|
6834
|
-
import { readFile as
|
|
6835
|
-
import
|
|
7557
|
+
import { spawn as spawn6 } from "node:child_process";
|
|
7558
|
+
import { readFile as readFile13 } from "node:fs/promises";
|
|
7559
|
+
import path26 from "node:path";
|
|
6836
7560
|
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
6837
7561
|
import {
|
|
6838
7562
|
createMessageConnection,
|
|
@@ -6876,7 +7600,7 @@ var init_lsp_manager = __esm({
|
|
|
6876
7600
|
if (!config) throw new Error(`Unknown LSP server: ${name}`);
|
|
6877
7601
|
let server2 = this.servers.get(name);
|
|
6878
7602
|
if (!server2) {
|
|
6879
|
-
const child =
|
|
7603
|
+
const child = spawn6(config.command, config.args ?? [], {
|
|
6880
7604
|
cwd: this.cwd,
|
|
6881
7605
|
env: { ...process.env, ...config.env },
|
|
6882
7606
|
stdio: "pipe",
|
|
@@ -6950,7 +7674,7 @@ var init_lsp_manager = __esm({
|
|
|
6950
7674
|
const current = previous.catch(() => {
|
|
6951
7675
|
}).then(async () => {
|
|
6952
7676
|
signal?.throwIfAborted();
|
|
6953
|
-
const content = await
|
|
7677
|
+
const content = await readFile13(file, "utf8");
|
|
6954
7678
|
const opened = server2.open.get(uri);
|
|
6955
7679
|
if (!opened) {
|
|
6956
7680
|
await server2.connection.sendNotification("textDocument/didOpen", {
|
|
@@ -6975,8 +7699,8 @@ var init_lsp_manager = __esm({
|
|
|
6975
7699
|
}
|
|
6976
7700
|
async query(input, signal) {
|
|
6977
7701
|
const file = await resolveWorkspacePath(this.cwd, input.file_path);
|
|
6978
|
-
const name = input.server ?? Object.keys(this.configs).find((name2) => this.configs[name2].extensions.includes(
|
|
6979
|
-
if (!name) throw new Error(`No LSP server configured for ${
|
|
7702
|
+
const name = input.server ?? Object.keys(this.configs).find((name2) => this.configs[name2].extensions.includes(path26.extname(file)));
|
|
7703
|
+
if (!name) throw new Error(`No LSP server configured for ${path26.extname(file)}`);
|
|
6980
7704
|
const server2 = await this.server(name, signal);
|
|
6981
7705
|
const uri = pathToFileURL2(file).href;
|
|
6982
7706
|
await this.synchronize(name, server2, file, uri, signal);
|
|
@@ -7053,7 +7777,7 @@ var init_lsp_manager = __esm({
|
|
|
7053
7777
|
});
|
|
7054
7778
|
|
|
7055
7779
|
// src/utils/tasks/task_store.ts
|
|
7056
|
-
import { randomUUID as
|
|
7780
|
+
import { randomUUID as randomUUID13 } from "node:crypto";
|
|
7057
7781
|
var TaskStore;
|
|
7058
7782
|
var init_task_store = __esm({
|
|
7059
7783
|
"src/utils/tasks/task_store.ts"() {
|
|
@@ -7090,7 +7814,7 @@ var init_task_store = __esm({
|
|
|
7090
7814
|
create(input) {
|
|
7091
7815
|
return this.store.update((state) => {
|
|
7092
7816
|
const task = {
|
|
7093
|
-
id:
|
|
7817
|
+
id: randomUUID13(),
|
|
7094
7818
|
subject: input.subject,
|
|
7095
7819
|
description: input.description,
|
|
7096
7820
|
metadata: input.metadata ?? {},
|
|
@@ -7150,7 +7874,7 @@ var init_task_store = __esm({
|
|
|
7150
7874
|
});
|
|
7151
7875
|
|
|
7152
7876
|
// src/utils/goals/goal_store.ts
|
|
7153
|
-
import { randomUUID as
|
|
7877
|
+
import { randomUUID as randomUUID14 } from "node:crypto";
|
|
7154
7878
|
var GoalStore;
|
|
7155
7879
|
var init_goal_store = __esm({
|
|
7156
7880
|
"src/utils/goals/goal_store.ts"() {
|
|
@@ -7188,7 +7912,7 @@ var init_goal_store = __esm({
|
|
|
7188
7912
|
return this.store.update((state) => {
|
|
7189
7913
|
if (state.goal && ["active", "paused", "blocked"].includes(state.goal.status))
|
|
7190
7914
|
throw new Error("Finish the current goal before creating another");
|
|
7191
|
-
state.goal = { id:
|
|
7915
|
+
state.goal = { id: randomUUID14(), objective, status: "active", started: this.usage(), budget: {} };
|
|
7192
7916
|
return this.snapshot(state.goal);
|
|
7193
7917
|
});
|
|
7194
7918
|
}
|
|
@@ -7229,7 +7953,7 @@ var init_goal_store = __esm({
|
|
|
7229
7953
|
|
|
7230
7954
|
// src/utils/artifacts/artifact_store.ts
|
|
7231
7955
|
import { stat as stat3 } from "node:fs/promises";
|
|
7232
|
-
import { randomUUID as
|
|
7956
|
+
import { randomUUID as randomUUID15 } from "node:crypto";
|
|
7233
7957
|
var ArtifactStore;
|
|
7234
7958
|
var init_artifact_store = __esm({
|
|
7235
7959
|
"src/utils/artifacts/artifact_store.ts"() {
|
|
@@ -7247,7 +7971,7 @@ var init_artifact_store = __esm({
|
|
|
7247
7971
|
if (Number(input.path !== void 0) + Number(input.url !== void 0) !== 1)
|
|
7248
7972
|
throw new Error("Provide exactly one file path or URL");
|
|
7249
7973
|
const artifact = {
|
|
7250
|
-
id:
|
|
7974
|
+
id: randomUUID15(),
|
|
7251
7975
|
title: input.title,
|
|
7252
7976
|
description: input.description,
|
|
7253
7977
|
mime_type: input.mime_type
|
|
@@ -7280,7 +8004,7 @@ var init_artifact_store = __esm({
|
|
|
7280
8004
|
|
|
7281
8005
|
// src/utils/sessions/session_catalog.ts
|
|
7282
8006
|
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
7283
|
-
import
|
|
8007
|
+
import path27 from "node:path";
|
|
7284
8008
|
var SessionCatalog;
|
|
7285
8009
|
var init_session_catalog = __esm({
|
|
7286
8010
|
"src/utils/sessions/session_catalog.ts"() {
|
|
@@ -7294,7 +8018,7 @@ var init_session_catalog = __esm({
|
|
|
7294
8018
|
current;
|
|
7295
8019
|
constructor(cwd, directory, stateFile, current) {
|
|
7296
8020
|
this.cwd = cwd;
|
|
7297
|
-
this.directory =
|
|
8021
|
+
this.directory = path27.resolve(cwd, directory);
|
|
7298
8022
|
this.metadata = new JsonStore(stateFile, {});
|
|
7299
8023
|
this.current = current;
|
|
7300
8024
|
}
|
|
@@ -7455,7 +8179,7 @@ var init_connection_manager = __esm({
|
|
|
7455
8179
|
|
|
7456
8180
|
// src/utils/plugins/plugin_manager.ts
|
|
7457
8181
|
import { mkdir as mkdir14 } from "node:fs/promises";
|
|
7458
|
-
import
|
|
8182
|
+
import path28 from "node:path";
|
|
7459
8183
|
import { DefaultPackageManager, SettingsManager as SettingsManager5 } from "@earendil-works/pi-coding-agent";
|
|
7460
8184
|
var PluginManager;
|
|
7461
8185
|
var init_plugin_manager = __esm({
|
|
@@ -7469,15 +8193,15 @@ var init_plugin_manager = __esm({
|
|
|
7469
8193
|
settings;
|
|
7470
8194
|
constructor(root) {
|
|
7471
8195
|
this.root = root;
|
|
7472
|
-
this.store = new JsonStore(
|
|
8196
|
+
this.store = new JsonStore(path28.join(root, "catalog.json"), { plugins: [] });
|
|
7473
8197
|
}
|
|
7474
8198
|
async manager() {
|
|
7475
8199
|
if (!this.packageManager) {
|
|
7476
8200
|
await mkdir14(this.root, { recursive: true });
|
|
7477
|
-
this.settings = SettingsManager5.create(this.root,
|
|
8201
|
+
this.settings = SettingsManager5.create(this.root, path28.join(this.root, "agent"), { projectTrusted: true });
|
|
7478
8202
|
this.packageManager = new DefaultPackageManager({
|
|
7479
8203
|
cwd: this.root,
|
|
7480
|
-
agentDir:
|
|
8204
|
+
agentDir: path28.join(this.root, "agent"),
|
|
7481
8205
|
settingsManager: this.settings
|
|
7482
8206
|
});
|
|
7483
8207
|
}
|
|
@@ -7548,7 +8272,7 @@ var init_plugin_manager = __esm({
|
|
|
7548
8272
|
});
|
|
7549
8273
|
|
|
7550
8274
|
// src/utils/events/intent_store.ts
|
|
7551
|
-
import { randomUUID as
|
|
8275
|
+
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
7552
8276
|
var IntentStore;
|
|
7553
8277
|
var init_intent_store = __esm({
|
|
7554
8278
|
"src/utils/events/intent_store.ts"() {
|
|
@@ -7562,7 +8286,7 @@ var init_intent_store = __esm({
|
|
|
7562
8286
|
this.wake = wake;
|
|
7563
8287
|
}
|
|
7564
8288
|
async create(input) {
|
|
7565
|
-
const intent = { ...input, id:
|
|
8289
|
+
const intent = { ...input, id: randomUUID16(), max_fires: input.max_fires ?? 1, fired: 0, cancelled: false };
|
|
7566
8290
|
if (input.event_kind === "intent") throw new Error("Intents cannot trigger other intents");
|
|
7567
8291
|
await this.store.update((state) => {
|
|
7568
8292
|
state.intents.push(intent);
|
|
@@ -7612,7 +8336,7 @@ Trigger (${event.kind}, ${event.id}): ${event.content}`
|
|
|
7612
8336
|
|
|
7613
8337
|
// src/utils/network/portal_manager.ts
|
|
7614
8338
|
import { createServer, request as httpRequest } from "node:http";
|
|
7615
|
-
import { randomUUID as
|
|
8339
|
+
import { randomUUID as randomUUID17 } from "node:crypto";
|
|
7616
8340
|
var PortalManager;
|
|
7617
8341
|
var init_portal_manager = __esm({
|
|
7618
8342
|
"src/utils/network/portal_manager.ts"() {
|
|
@@ -7700,7 +8424,7 @@ Connection: close\r
|
|
|
7700
8424
|
});
|
|
7701
8425
|
});
|
|
7702
8426
|
const portal = {
|
|
7703
|
-
id:
|
|
8427
|
+
id: randomUUID17(),
|
|
7704
8428
|
port,
|
|
7705
8429
|
title,
|
|
7706
8430
|
url: `http://127.0.0.1:${server2.address().port}/`,
|
|
@@ -7733,7 +8457,7 @@ Connection: close\r
|
|
|
7733
8457
|
});
|
|
7734
8458
|
|
|
7735
8459
|
// src/utils/media/transcript_store.ts
|
|
7736
|
-
import { randomUUID as
|
|
8460
|
+
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
7737
8461
|
var TranscriptStore;
|
|
7738
8462
|
var init_transcript_store = __esm({
|
|
7739
8463
|
"src/utils/media/transcript_store.ts"() {
|
|
@@ -7750,7 +8474,7 @@ var init_transcript_store = __esm({
|
|
|
7750
8474
|
}
|
|
7751
8475
|
async start(title, provider = "manual", meetingUrl) {
|
|
7752
8476
|
if (provider !== "manual" && !this.providers[provider]) throw new Error("Unknown transcript capture provider");
|
|
7753
|
-
const session = { id:
|
|
8477
|
+
const session = { id: randomUUID18(), title, status: "recording", provider, manual: [] };
|
|
7754
8478
|
if (provider !== "manual")
|
|
7755
8479
|
session.process_id = this.processes.start(this.providers[provider].command, void 0, void 0, {
|
|
7756
8480
|
TRANSCRIPT_MEETING_URL: meetingUrl ?? ""
|
|
@@ -7773,7 +8497,7 @@ var init_transcript_store = __esm({
|
|
|
7773
8497
|
let session = id ? state.sessions.find((s) => s.id === id) : void 0;
|
|
7774
8498
|
if (id && !session) throw new Error("Unknown transcript session");
|
|
7775
8499
|
if (!session) {
|
|
7776
|
-
session = { id:
|
|
8500
|
+
session = { id: randomUUID18(), title, status: "imported", provider: "manual", manual: [] };
|
|
7777
8501
|
state.sessions.push(session);
|
|
7778
8502
|
}
|
|
7779
8503
|
session.manual.push(text2);
|
|
@@ -8355,7 +9079,7 @@ var init_transcripts = __esm({
|
|
|
8355
9079
|
});
|
|
8356
9080
|
|
|
8357
9081
|
// src/capabilities/tools/media/zoom_image.ts
|
|
8358
|
-
import { readFile as
|
|
9082
|
+
import { readFile as readFile14 } from "node:fs/promises";
|
|
8359
9083
|
import { PhotonImage as PhotonImage2, crop, resize, SamplingFilter } from "@silvia-odwyer/photon-node";
|
|
8360
9084
|
import { defineTool as defineTool64 } from "@earendil-works/pi-coding-agent";
|
|
8361
9085
|
import { Type as Type62 } from "typebox";
|
|
@@ -8375,7 +9099,7 @@ function createZoomImageTool(cwd) {
|
|
|
8375
9099
|
async execute(_id, args, signal) {
|
|
8376
9100
|
signal?.throwIfAborted();
|
|
8377
9101
|
if (args.x1 >= args.x2 || args.y1 >= args.y2) throw new Error("Region must have positive width and height");
|
|
8378
|
-
const original = PhotonImage2.new_from_byteslice(await
|
|
9102
|
+
const original = PhotonImage2.new_from_byteslice(await readFile14(await resolveWorkspacePath(cwd, args.file_path)));
|
|
8379
9103
|
let selected;
|
|
8380
9104
|
let rendered;
|
|
8381
9105
|
try {
|
|
@@ -9402,10 +10126,10 @@ var init_workflow = __esm({
|
|
|
9402
10126
|
});
|
|
9403
10127
|
|
|
9404
10128
|
// src/capabilities/expanded-task-tool-space.ts
|
|
9405
|
-
import
|
|
10129
|
+
import path29 from "node:path";
|
|
9406
10130
|
function createExpandedTaskToolSpace(options) {
|
|
9407
10131
|
const base = createBaseTaskToolSpace(options);
|
|
9408
|
-
const file = (name) =>
|
|
10132
|
+
const file = (name) => path29.join(options.stateDirectory, name);
|
|
9409
10133
|
const tasks = new TaskStore(file("tasks.json"));
|
|
9410
10134
|
const goals = new GoalStore(file("goal.json"), options.goalUsage);
|
|
9411
10135
|
const scheduler = new Scheduler(file("schedules.json"), options.wake);
|
|
@@ -9474,8 +10198,8 @@ function createExpandedTaskToolSpace(options) {
|
|
|
9474
10198
|
createSecretsTool(secrets),
|
|
9475
10199
|
createPortalTool(portals),
|
|
9476
10200
|
createWorkflowTool(tasks, options.workflowTools, options.wake),
|
|
9477
|
-
createGenerateImageTool(options.cwd, "agent-arena", base.settings.tools.media.generateImage,
|
|
9478
|
-
createGenerateSpeechTool(options.cwd, base.settings.tools.media.generateSpeech,
|
|
10201
|
+
createGenerateImageTool(options.cwd, "agent-arena", base.settings.tools.media.generateImage, base.settings.infrastructure.routify, base.settings.pi.retry),
|
|
10202
|
+
createGenerateSpeechTool(options.cwd, base.settings.tools.media.generateSpeech, base.settings.infrastructure.routify, base.settings.pi.retry),
|
|
9479
10203
|
createFetchMediaTool(base.settings.infrastructure.pexels, base.settings.pi.retry),
|
|
9480
10204
|
createImageSearchTool(options.cwd, base.settings.infrastructure.routify, base.settings.pi.retry)
|
|
9481
10205
|
];
|
|
@@ -9606,7 +10330,7 @@ var child_exports = {};
|
|
|
9606
10330
|
__export(child_exports, {
|
|
9607
10331
|
runScalingChild: () => runScalingChild
|
|
9608
10332
|
});
|
|
9609
|
-
import
|
|
10333
|
+
import path30 from "node:path";
|
|
9610
10334
|
import { InMemoryCredentialStore } from "@earendil-works/pi-ai";
|
|
9611
10335
|
import {
|
|
9612
10336
|
createAgentSession,
|
|
@@ -9666,7 +10390,7 @@ async function runScalingChild(task, parent, signal, config, limits, budget, par
|
|
|
9666
10390
|
await loader.reload();
|
|
9667
10391
|
const manager = SessionManager2.create(
|
|
9668
10392
|
parent.cwd,
|
|
9669
|
-
|
|
10393
|
+
path30.join(parent.sessionManager.getSessionDir(), "scaling-children"),
|
|
9670
10394
|
{ parentSession: parent.sessionManager.getSessionFile() }
|
|
9671
10395
|
);
|
|
9672
10396
|
const { session } = await createAgentSession({
|
|
@@ -9744,9 +10468,9 @@ var init_child = __esm({
|
|
|
9744
10468
|
});
|
|
9745
10469
|
|
|
9746
10470
|
// src/harnesses/scaling/runtime.ts
|
|
9747
|
-
import
|
|
9748
|
-
import { tmpdir as
|
|
9749
|
-
import { randomUUID as
|
|
10471
|
+
import path31 from "node:path";
|
|
10472
|
+
import { tmpdir as tmpdir5 } from "node:os";
|
|
10473
|
+
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
9750
10474
|
import {
|
|
9751
10475
|
SettingsManager as SettingsManager7,
|
|
9752
10476
|
createToolSearchExtension
|
|
@@ -9775,7 +10499,7 @@ function createScalingRuntime(input, options = {}) {
|
|
|
9775
10499
|
let turn = 0;
|
|
9776
10500
|
let disposing;
|
|
9777
10501
|
let initialized = false;
|
|
9778
|
-
let stateDirectory =
|
|
10502
|
+
let stateDirectory = path31.join(tmpdir5(), "scaling-pending-" + randomUUID19());
|
|
9779
10503
|
const toolName = (name) => visibleToolName(config.TS, name);
|
|
9780
10504
|
const makeToolSpace = (directory) => {
|
|
9781
10505
|
const common = { ...options.toolServices, cwd, stateDirectory: directory, parentSecrets: options.parentSecrets };
|
|
@@ -9896,15 +10620,18 @@ function createScalingRuntime(input, options = {}) {
|
|
|
9896
10620
|
budget.toolCall();
|
|
9897
10621
|
let result;
|
|
9898
10622
|
try {
|
|
9899
|
-
|
|
9900
|
-
|
|
9901
|
-
|
|
9902
|
-
|
|
9903
|
-
|
|
9904
|
-
|
|
10623
|
+
if (config.C === "C2") {
|
|
10624
|
+
try {
|
|
10625
|
+
context.notes.beforeTool(tool.name, args);
|
|
10626
|
+
} catch (error) {
|
|
10627
|
+
throw new Error(rewriteToolReferences(error instanceof Error ? error.message : String(error), config.TS));
|
|
10628
|
+
}
|
|
9905
10629
|
}
|
|
9906
|
-
const
|
|
9907
|
-
|
|
10630
|
+
const execute2 = (input2) => {
|
|
10631
|
+
const callArgs = outer ? { ...input2, max_output_chars: outputLimit } : input2;
|
|
10632
|
+
return tool.execute(id, callArgs, signal, void 0, ctx);
|
|
10633
|
+
};
|
|
10634
|
+
result = await (planning ? planning.executeTool(tool.name, args, execute2) : execute2(args));
|
|
9908
10635
|
} catch (error) {
|
|
9909
10636
|
if (signal?.aborted || fatal) throw error;
|
|
9910
10637
|
result = { ...textResult(error instanceof Error ? error.message : String(error)), isError: true };
|
|
@@ -10045,9 +10772,9 @@ function createScalingRuntime(input, options = {}) {
|
|
|
10045
10772
|
budget.onChange = (state) => pi.appendEntry("scaling-budget", state);
|
|
10046
10773
|
}
|
|
10047
10774
|
boundContext = ctx;
|
|
10048
|
-
const root = options.toolServices?.stateRoot ?
|
|
10049
|
-
const directory =
|
|
10050
|
-
if (savedConfig?.toolStateDirectory &&
|
|
10775
|
+
const root = options.toolServices?.stateRoot ? path31.resolve(cwd, options.toolServices.stateRoot) : path31.join(ctx.sessionManager.getSessionDir(), "scaling-tools");
|
|
10776
|
+
const directory = path31.join(root, ctx.sessionManager.getSessionId());
|
|
10777
|
+
if (savedConfig?.toolStateDirectory && path31.resolve(savedConfig.toolStateDirectory) !== path31.resolve(directory))
|
|
10051
10778
|
fail(
|
|
10052
10779
|
new Error(
|
|
10053
10780
|
"This session used a different task-tool state root; restore its service configuration or start a new session"
|
|
@@ -10065,7 +10792,7 @@ function createScalingRuntime(input, options = {}) {
|
|
|
10065
10792
|
if ("initialize" in toolSpace) await toolSpace.initialize();
|
|
10066
10793
|
initialized = true;
|
|
10067
10794
|
}
|
|
10068
|
-
await agents?.bind(
|
|
10795
|
+
await agents?.bind(path31.join(stateDirectory, "agents.json"));
|
|
10069
10796
|
if (!previous)
|
|
10070
10797
|
pi.appendEntry("scaling-config", {
|
|
10071
10798
|
version: SCALING_RUNTIME_VERSION,
|
|
@@ -10110,16 +10837,7 @@ function createScalingRuntime(input, options = {}) {
|
|
|
10110
10837
|
});
|
|
10111
10838
|
pi.on("context", (event, ctx) => {
|
|
10112
10839
|
if (fatal) return fail(fatal, ctx);
|
|
10113
|
-
|
|
10114
|
-
if (planning)
|
|
10115
|
-
messages.push({
|
|
10116
|
-
role: "custom",
|
|
10117
|
-
customType: "scaling-plan-status",
|
|
10118
|
-
content: `Workflow phase: ${planning.status()}.`,
|
|
10119
|
-
display: false,
|
|
10120
|
-
timestamp: Date.now()
|
|
10121
|
-
});
|
|
10122
|
-
return { messages };
|
|
10840
|
+
return { messages: context.requestContext(event.messages, ctx) };
|
|
10123
10841
|
});
|
|
10124
10842
|
pi.on("context_with_system", (event, ctx) => {
|
|
10125
10843
|
if (config.C === "C1") return;
|
|
@@ -10153,7 +10871,7 @@ function createScalingRuntime(input, options = {}) {
|
|
|
10153
10871
|
const remaining = agents?.uncollected();
|
|
10154
10872
|
if (remaining?.length) {
|
|
10155
10873
|
const result = await agents.wait(remaining, void 0, ctx.signal, true);
|
|
10156
|
-
const observed = await observation.apply("wait_agents", textResult(result), ctx, "settle-" +
|
|
10874
|
+
const observed = await observation.apply("wait_agents", textResult(result), ctx, "settle-" + randomUUID19());
|
|
10157
10875
|
if (config.C === "C2") context.notes.workChanged();
|
|
10158
10876
|
return {
|
|
10159
10877
|
entries: [
|
|
@@ -10296,11 +11014,10 @@ var init_runtime = __esm({
|
|
|
10296
11014
|
});
|
|
10297
11015
|
|
|
10298
11016
|
// src/harnesses/agent-arena.ts
|
|
10299
|
-
init_dashscope();
|
|
10300
11017
|
init_settings11();
|
|
10301
11018
|
init_ask_user2();
|
|
10302
11019
|
init_bash();
|
|
10303
|
-
import
|
|
11020
|
+
import path11 from "node:path";
|
|
10304
11021
|
import "@earendil-works/pi-coding-agent";
|
|
10305
11022
|
|
|
10306
11023
|
// src/capabilities/tools/filesystem/edit_file.ts
|
|
@@ -10325,11 +11042,11 @@ function createAgentArenaEditFileTool(cwd) {
|
|
|
10325
11042
|
promptSnippet: "Edit files with exact text replacement",
|
|
10326
11043
|
parameters: agentArenaSchema,
|
|
10327
11044
|
async execute(toolCallId, params, signal, _onUpdate, context) {
|
|
10328
|
-
const
|
|
11045
|
+
const path34 = await resolveWorkspacePath(cwd, params.path);
|
|
10329
11046
|
const nativeEdit = createEditToolDefinition(cwd);
|
|
10330
11047
|
await nativeEdit.execute(
|
|
10331
11048
|
toolCallId,
|
|
10332
|
-
{ path:
|
|
11049
|
+
{ path: path34, edits: [{ oldText: params.old_text, newText: params.new_text }] },
|
|
10333
11050
|
signal,
|
|
10334
11051
|
void 0,
|
|
10335
11052
|
context
|
|
@@ -10346,11 +11063,11 @@ function createCodeEditFileTool(cwd) {
|
|
|
10346
11063
|
promptSnippet: "Edit project files",
|
|
10347
11064
|
parameters: codeSchema,
|
|
10348
11065
|
async execute(toolCallId, params, signal, _onUpdate, context) {
|
|
10349
|
-
const
|
|
11066
|
+
const path34 = await resolveWorkspacePath(cwd, params.path);
|
|
10350
11067
|
const nativeEdit = createEditToolDefinition(cwd);
|
|
10351
11068
|
await nativeEdit.execute(
|
|
10352
11069
|
toolCallId,
|
|
10353
|
-
{ path:
|
|
11070
|
+
{ path: path34, edits: [{ oldText: params.context, newText: params.replacement }] },
|
|
10354
11071
|
signal,
|
|
10355
11072
|
void 0,
|
|
10356
11073
|
context
|
|
@@ -10379,9 +11096,9 @@ function createWriteFileTool(cwd) {
|
|
|
10379
11096
|
promptSnippet: "Create or overwrite workspace files",
|
|
10380
11097
|
parameters: schema,
|
|
10381
11098
|
async execute(toolCallId, params, signal, _onUpdate, context) {
|
|
10382
|
-
const
|
|
11099
|
+
const path34 = await resolveWorkspacePath(cwd, params.path);
|
|
10383
11100
|
const nativeWrite = createWriteToolDefinition(cwd);
|
|
10384
|
-
await nativeWrite.execute(toolCallId, { path:
|
|
11101
|
+
await nativeWrite.execute(toolCallId, { path: path34, content: params.content }, signal, void 0, context);
|
|
10385
11102
|
return jsonToolResult({ status: "success" });
|
|
10386
11103
|
}
|
|
10387
11104
|
});
|
|
@@ -10400,13 +11117,13 @@ init_retry();
|
|
|
10400
11117
|
function record3(value) {
|
|
10401
11118
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
10402
11119
|
}
|
|
10403
|
-
function
|
|
11120
|
+
function stringValue2(value) {
|
|
10404
11121
|
return typeof value === "string" ? value : "";
|
|
10405
11122
|
}
|
|
10406
11123
|
function errorMessage2(error) {
|
|
10407
11124
|
return error instanceof Error ? error.message : String(error);
|
|
10408
11125
|
}
|
|
10409
|
-
function
|
|
11126
|
+
function apiKey(settings) {
|
|
10410
11127
|
const value = settings?.apiKey;
|
|
10411
11128
|
if (!value) {
|
|
10412
11129
|
throw new Error("Routify page fetch requires harnesses.toolServices.routify.apiKey in settings.json");
|
|
@@ -10416,10 +11133,10 @@ function apiKey2(settings) {
|
|
|
10416
11133
|
function authorizationHeader(value) {
|
|
10417
11134
|
return /^bearer\s+/i.test(value) ? value : `Bearer ${value}`;
|
|
10418
11135
|
}
|
|
10419
|
-
function
|
|
11136
|
+
function responseDetail2(rawBody) {
|
|
10420
11137
|
try {
|
|
10421
11138
|
const payload = record3(JSON.parse(rawBody));
|
|
10422
|
-
return
|
|
11139
|
+
return stringValue2(payload.message) || stringValue2(payload.detailMessage) || stringValue2(record3(payload.error).message) || rawBody;
|
|
10423
11140
|
} catch {
|
|
10424
11141
|
return rawBody;
|
|
10425
11142
|
}
|
|
@@ -10440,7 +11157,7 @@ async function firecrawl(url, format, options) {
|
|
|
10440
11157
|
const response = await retryHttpRequest(() => fetchImpl(routifyReadPageUrl(options.settings), {
|
|
10441
11158
|
method: "POST",
|
|
10442
11159
|
headers: {
|
|
10443
|
-
authorization: authorizationHeader(
|
|
11160
|
+
authorization: authorizationHeader(apiKey(options.settings)),
|
|
10444
11161
|
"content-type": "application/json"
|
|
10445
11162
|
},
|
|
10446
11163
|
body: JSON.stringify({
|
|
@@ -10454,7 +11171,7 @@ async function firecrawl(url, format, options) {
|
|
|
10454
11171
|
const rawBody = await response.text();
|
|
10455
11172
|
if (response.status !== 200) {
|
|
10456
11173
|
throw new Error(
|
|
10457
|
-
`Firecrawl failed (${response.status} ${response.statusText}): ${
|
|
11174
|
+
`Firecrawl failed (${response.status} ${response.statusText}): ${responseDetail2(rawBody).slice(0, 1e3)}`
|
|
10458
11175
|
);
|
|
10459
11176
|
}
|
|
10460
11177
|
const payload = parseJson(rawBody, "Firecrawl");
|
|
@@ -10463,12 +11180,12 @@ async function firecrawl(url, format, options) {
|
|
|
10463
11180
|
}
|
|
10464
11181
|
const data = record3(payload.data);
|
|
10465
11182
|
const metadata = record3(data.metadata);
|
|
10466
|
-
const content =
|
|
11183
|
+
const content = stringValue2(data[requestedFormat]);
|
|
10467
11184
|
if (!content && !(requestedFormat in data)) {
|
|
10468
11185
|
throw new Error(`Firecrawl response is missing ${requestedFormat} content`);
|
|
10469
11186
|
}
|
|
10470
11187
|
return {
|
|
10471
|
-
title:
|
|
11188
|
+
title: stringValue2(metadata.title) || "No Title Found",
|
|
10472
11189
|
content
|
|
10473
11190
|
};
|
|
10474
11191
|
}
|
|
@@ -10478,7 +11195,7 @@ async function jinaReader(url, format, options) {
|
|
|
10478
11195
|
method: "POST",
|
|
10479
11196
|
headers: {
|
|
10480
11197
|
accept: "application/json",
|
|
10481
|
-
authorization: authorizationHeader(
|
|
11198
|
+
authorization: authorizationHeader(apiKey(options.settings)),
|
|
10482
11199
|
"content-type": "application/json",
|
|
10483
11200
|
"x-respond-with": format
|
|
10484
11201
|
},
|
|
@@ -10491,7 +11208,7 @@ async function jinaReader(url, format, options) {
|
|
|
10491
11208
|
const rawBody = await response.text();
|
|
10492
11209
|
if (response.status !== 200) {
|
|
10493
11210
|
throw new Error(
|
|
10494
|
-
`Jina Reader failed (${response.status} ${response.statusText}): ${
|
|
11211
|
+
`Jina Reader failed (${response.status} ${response.statusText}): ${responseDetail2(rawBody).slice(0, 1e3)}`
|
|
10495
11212
|
);
|
|
10496
11213
|
}
|
|
10497
11214
|
const payload = parseJson(rawBody, "Jina Reader");
|
|
@@ -10505,7 +11222,7 @@ async function jinaReader(url, format, options) {
|
|
|
10505
11222
|
throw new Error("Jina Reader response is missing content");
|
|
10506
11223
|
}
|
|
10507
11224
|
return {
|
|
10508
|
-
title:
|
|
11225
|
+
title: stringValue2(data.title) || "No Title Found",
|
|
10509
11226
|
content: data.content
|
|
10510
11227
|
};
|
|
10511
11228
|
}
|
|
@@ -10796,7 +11513,7 @@ function currentDate() {
|
|
|
10796
11513
|
}
|
|
10797
11514
|
function agentArenaSystemPrompt(cwd = process.cwd()) {
|
|
10798
11515
|
const context = currentDate();
|
|
10799
|
-
const resolvedCwd =
|
|
11516
|
+
const resolvedCwd = path11.resolve(cwd);
|
|
10800
11517
|
let prompt = BASE_SYSTEM_PROMPT.replace("{{currentDate}}", context.date).replace("{{timezone}}", context.timezone).replace(
|
|
10801
11518
|
"{{locationLine}}",
|
|
10802
11519
|
"The user's approximate location was not provided by the client."
|
|
@@ -10821,10 +11538,6 @@ function createAgentArenaExtension(cwd, settings) {
|
|
|
10821
11538
|
return {
|
|
10822
11539
|
name: "agent-arena-tools",
|
|
10823
11540
|
factory(pi) {
|
|
10824
|
-
const dashScope = createDashScopeClient(
|
|
10825
|
-
settings.infrastructure.dashScope,
|
|
10826
|
-
settings.pi.retry
|
|
10827
|
-
);
|
|
10828
11541
|
pi.registerTool(createAskUserTool());
|
|
10829
11542
|
pi.registerTool(createAgentArenaEditFileTool(cwd));
|
|
10830
11543
|
pi.registerTool(createAgentArenaReadFileTool(
|
|
@@ -10852,12 +11565,14 @@ function createAgentArenaExtension(cwd, settings) {
|
|
|
10852
11565
|
cwd,
|
|
10853
11566
|
"agent-arena",
|
|
10854
11567
|
settings.tools.media.generateImage,
|
|
10855
|
-
|
|
11568
|
+
settings.infrastructure.routify,
|
|
11569
|
+
settings.pi.retry
|
|
10856
11570
|
));
|
|
10857
11571
|
pi.registerTool(createGenerateSpeechTool(
|
|
10858
11572
|
cwd,
|
|
10859
11573
|
settings.tools.media.generateSpeech,
|
|
10860
|
-
|
|
11574
|
+
settings.infrastructure.routify,
|
|
11575
|
+
settings.pi.retry
|
|
10861
11576
|
));
|
|
10862
11577
|
}
|
|
10863
11578
|
};
|
|
@@ -11129,7 +11844,6 @@ async function runSelfCompactHarness(args) {
|
|
|
11129
11844
|
}
|
|
11130
11845
|
|
|
11131
11846
|
// src/harnesses/code-arena-full-stack.ts
|
|
11132
|
-
init_dashscope();
|
|
11133
11847
|
init_settings11();
|
|
11134
11848
|
import "@earendil-works/pi-coding-agent";
|
|
11135
11849
|
|
|
@@ -11137,9 +11851,9 @@ import "@earendil-works/pi-coding-agent";
|
|
|
11137
11851
|
init_workspace();
|
|
11138
11852
|
init_settings7();
|
|
11139
11853
|
import { existsSync as existsSync2 } from "node:fs";
|
|
11140
|
-
import { mkdir as mkdir5, readFile as
|
|
11141
|
-
import
|
|
11142
|
-
import { setTimeout as
|
|
11854
|
+
import { mkdir as mkdir5, readFile as readFile6 } from "node:fs/promises";
|
|
11855
|
+
import path12 from "node:path";
|
|
11856
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
11143
11857
|
import { defineTool as defineTool12 } from "@earendil-works/pi-coding-agent";
|
|
11144
11858
|
import { Type as Type12 } from "typebox";
|
|
11145
11859
|
var schema6 = Type12.Object({ description: Type12.String() }, { additionalProperties: false });
|
|
@@ -11161,7 +11875,7 @@ function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
|
|
|
11161
11875
|
async execute(_toolCallId, _params, signal) {
|
|
11162
11876
|
const timeout = settings?.fullStackBuildTimeoutMs || 5 * 6e4;
|
|
11163
11877
|
const npm = commandInvocation(npmCommand);
|
|
11164
|
-
if (!existsSync2(
|
|
11878
|
+
if (!existsSync2(path12.join(cwd, "node_modules", ".bin", "next"))) {
|
|
11165
11879
|
const installed = await exec(npm.command, [...npm.args, "install"], { cwd, timeout, signal });
|
|
11166
11880
|
if (installed.code !== 0) {
|
|
11167
11881
|
return failure("install", "Full-stack dependency installation failed.", installed.stdout + installed.stderr);
|
|
@@ -11172,12 +11886,12 @@ function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
|
|
|
11172
11886
|
if (built.code !== 0) {
|
|
11173
11887
|
return failure("build", "Full-stack production build failed.", built.stdout + built.stderr);
|
|
11174
11888
|
}
|
|
11175
|
-
const runtimeDirectory =
|
|
11176
|
-
const logPath =
|
|
11177
|
-
const pidPath =
|
|
11889
|
+
const runtimeDirectory = path12.join(cwd, ".code-harness");
|
|
11890
|
+
const logPath = path12.join(runtimeDirectory, "preview.log");
|
|
11891
|
+
const pidPath = path12.join(runtimeDirectory, "preview.pid");
|
|
11178
11892
|
await mkdir5(runtimeDirectory, { recursive: true });
|
|
11179
11893
|
try {
|
|
11180
|
-
const previousPid = Number((await
|
|
11894
|
+
const previousPid = Number((await readFile6(pidPath, "utf8")).trim());
|
|
11181
11895
|
if (Number.isInteger(previousPid) && previousPid > 1) {
|
|
11182
11896
|
process.kill(process.platform === "win32" ? previousPid : -previousPid, "SIGTERM");
|
|
11183
11897
|
}
|
|
@@ -11216,11 +11930,11 @@ function createBuildAndStartTool(cwd, exec, settings, npmCommand, shell) {
|
|
|
11216
11930
|
} catch (error) {
|
|
11217
11931
|
if (signal?.aborted) throw error;
|
|
11218
11932
|
}
|
|
11219
|
-
await
|
|
11933
|
+
await delay2(500, void 0, signal ? { signal } : void 0);
|
|
11220
11934
|
}
|
|
11221
11935
|
let logs = "";
|
|
11222
11936
|
try {
|
|
11223
|
-
logs = await
|
|
11937
|
+
logs = await readFile6(logPath, "utf8");
|
|
11224
11938
|
} catch {
|
|
11225
11939
|
logs = "Preview exited without logs";
|
|
11226
11940
|
}
|
|
@@ -11281,9 +11995,9 @@ function createCreateFileTool(cwd) {
|
|
|
11281
11995
|
promptSnippet: "Create project files",
|
|
11282
11996
|
parameters: schema8,
|
|
11283
11997
|
async execute(toolCallId, params, signal, _onUpdate, context) {
|
|
11284
|
-
const
|
|
11998
|
+
const path34 = await resolveWorkspacePath(cwd, params.path);
|
|
11285
11999
|
const nativeWrite = createWriteToolDefinition2(cwd);
|
|
11286
|
-
await nativeWrite.execute(toolCallId, { path:
|
|
12000
|
+
await nativeWrite.execute(toolCallId, { path: path34, content: params.content }, signal, void 0, context);
|
|
11287
12001
|
return jsonToolResult({ status: "success", message: `Created ${params.path}.` });
|
|
11288
12002
|
}
|
|
11289
12003
|
});
|
|
@@ -11291,7 +12005,7 @@ function createCreateFileTool(cwd) {
|
|
|
11291
12005
|
|
|
11292
12006
|
// src/capabilities/tools/filesystem/delete_file.ts
|
|
11293
12007
|
init_workspace();
|
|
11294
|
-
import { rm as
|
|
12008
|
+
import { rm as rm3 } from "node:fs/promises";
|
|
11295
12009
|
import { defineTool as defineTool15 } from "@earendil-works/pi-coding-agent";
|
|
11296
12010
|
import { Type as Type15 } from "typebox";
|
|
11297
12011
|
var schema9 = Type15.Object(
|
|
@@ -11306,8 +12020,8 @@ function createDeleteFileTool(cwd) {
|
|
|
11306
12020
|
promptSnippet: "Delete project files",
|
|
11307
12021
|
parameters: schema9,
|
|
11308
12022
|
async execute(_toolCallId, params) {
|
|
11309
|
-
const
|
|
11310
|
-
await
|
|
12023
|
+
const path34 = await resolveWorkspacePath(cwd, params.path);
|
|
12024
|
+
await rm3(path34, { recursive: true, force: true });
|
|
11311
12025
|
return jsonToolResult({ status: "success" });
|
|
11312
12026
|
}
|
|
11313
12027
|
});
|
|
@@ -11410,7 +12124,7 @@ function createGrepFilesTool(cwd) {
|
|
|
11410
12124
|
return jsonToolResult({
|
|
11411
12125
|
status: "success",
|
|
11412
12126
|
mode: outputMode,
|
|
11413
|
-
counts: [...counts].map(([
|
|
12127
|
+
counts: [...counts].map(([path34, count]) => ({ path: path34, count })),
|
|
11414
12128
|
totalMatches: lines.length
|
|
11415
12129
|
});
|
|
11416
12130
|
}
|
|
@@ -11446,7 +12160,7 @@ function createListFilesTool(cwd) {
|
|
|
11446
12160
|
const text2 = result.content.find((part) => part.type === "text")?.text || "";
|
|
11447
12161
|
return jsonToolResult({
|
|
11448
12162
|
status: "success",
|
|
11449
|
-
files: text2.split("\n").filter((line) => line && !line.startsWith("[")).map((
|
|
12163
|
+
files: text2.split("\n").filter((line) => line && !line.startsWith("[")).map((path34) => ({ path: path34 }))
|
|
11450
12164
|
});
|
|
11451
12165
|
}
|
|
11452
12166
|
});
|
|
@@ -11581,10 +12295,6 @@ function createCodeArenaFullStackExtension(cwd, settings) {
|
|
|
11581
12295
|
name: "code-arena-full-stack-tools",
|
|
11582
12296
|
factory(pi) {
|
|
11583
12297
|
const exec = (command, args, options) => pi.exec(command, args, options);
|
|
11584
|
-
const dashScope = createDashScopeClient(
|
|
11585
|
-
settings.infrastructure.dashScope,
|
|
11586
|
-
settings.pi.retry
|
|
11587
|
-
);
|
|
11588
12298
|
pi.registerTool(createCodeReadFileTool(cwd, settings.shared.imageCaption));
|
|
11589
12299
|
pi.registerTool(createCreateFileTool(cwd));
|
|
11590
12300
|
pi.registerTool(createCodeEditFileTool(cwd));
|
|
@@ -11623,7 +12333,8 @@ function createCodeArenaFullStackExtension(cwd, settings) {
|
|
|
11623
12333
|
cwd,
|
|
11624
12334
|
"code",
|
|
11625
12335
|
settings.tools.media.generateImage,
|
|
11626
|
-
|
|
12336
|
+
settings.infrastructure.routify,
|
|
12337
|
+
settings.pi.retry
|
|
11627
12338
|
));
|
|
11628
12339
|
}
|
|
11629
12340
|
};
|
|
@@ -11733,7 +12444,6 @@ async function runCodeArenaHtmlHarness(args) {
|
|
|
11733
12444
|
}
|
|
11734
12445
|
|
|
11735
12446
|
// src/harnesses/code-arena-react.ts
|
|
11736
|
-
init_dashscope();
|
|
11737
12447
|
init_settings11();
|
|
11738
12448
|
import "@earendil-works/pi-coding-agent";
|
|
11739
12449
|
|
|
@@ -11815,10 +12525,6 @@ function createCodeArenaReactExtension(cwd, settings) {
|
|
|
11815
12525
|
name: "code-arena-react-tools",
|
|
11816
12526
|
factory(pi) {
|
|
11817
12527
|
const exec = (command, args, options) => pi.exec(command, args, options);
|
|
11818
|
-
const dashScope = createDashScopeClient(
|
|
11819
|
-
settings.infrastructure.dashScope,
|
|
11820
|
-
settings.pi.retry
|
|
11821
|
-
);
|
|
11822
12528
|
pi.registerTool(createCodeReadFileTool(cwd, settings.shared.imageCaption));
|
|
11823
12529
|
pi.registerTool(createCreateFileTool(cwd));
|
|
11824
12530
|
pi.registerTool(createCodeEditFileTool(cwd));
|
|
@@ -11851,7 +12557,8 @@ function createCodeArenaReactExtension(cwd, settings) {
|
|
|
11851
12557
|
cwd,
|
|
11852
12558
|
"code",
|
|
11853
12559
|
settings.tools.media.generateImage,
|
|
11854
|
-
|
|
12560
|
+
settings.infrastructure.routify,
|
|
12561
|
+
settings.pi.retry
|
|
11855
12562
|
));
|
|
11856
12563
|
}
|
|
11857
12564
|
};
|
|
@@ -11865,19 +12572,19 @@ async function runCodeArenaReactHarness(args) {
|
|
|
11865
12572
|
}
|
|
11866
12573
|
|
|
11867
12574
|
// src/harnesses/long-horizon-mea.ts
|
|
11868
|
-
import
|
|
12575
|
+
import path15 from "node:path";
|
|
11869
12576
|
|
|
11870
12577
|
// src/capabilities/orchestration/mea/index.ts
|
|
11871
12578
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
11872
12579
|
|
|
11873
12580
|
// src/runtime/package-resources.ts
|
|
11874
12581
|
import fs from "node:fs";
|
|
11875
|
-
import
|
|
12582
|
+
import path14 from "node:path";
|
|
11876
12583
|
import { fileURLToPath } from "node:url";
|
|
11877
12584
|
var PACKAGE_NAME = "@qwen-code/qwen-harness";
|
|
11878
12585
|
var SUBAGENT_EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
|
|
11879
12586
|
function isHarnessPackageRoot(directory) {
|
|
11880
|
-
const packageJsonPath =
|
|
12587
|
+
const packageJsonPath = path14.join(directory, "package.json");
|
|
11881
12588
|
try {
|
|
11882
12589
|
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
11883
12590
|
return packageJson.name === PACKAGE_NAME;
|
|
@@ -11886,10 +12593,10 @@ function isHarnessPackageRoot(directory) {
|
|
|
11886
12593
|
}
|
|
11887
12594
|
}
|
|
11888
12595
|
function resolveHarnessPackageRoot(startPath = fileURLToPath(import.meta.url)) {
|
|
11889
|
-
let directory =
|
|
12596
|
+
let directory = path14.dirname(path14.resolve(startPath));
|
|
11890
12597
|
while (true) {
|
|
11891
12598
|
if (isHarnessPackageRoot(directory)) return directory;
|
|
11892
|
-
const parent =
|
|
12599
|
+
const parent = path14.dirname(directory);
|
|
11893
12600
|
if (parent === directory) break;
|
|
11894
12601
|
directory = parent;
|
|
11895
12602
|
}
|
|
@@ -11898,7 +12605,7 @@ function resolveHarnessPackageRoot(startPath = fileURLToPath(import.meta.url)) {
|
|
|
11898
12605
|
);
|
|
11899
12606
|
}
|
|
11900
12607
|
function resolveBundledAgentDirectory(packageRoot = resolveHarnessPackageRoot()) {
|
|
11901
|
-
const directory =
|
|
12608
|
+
const directory = path14.join(packageRoot, ".pi", "agents");
|
|
11902
12609
|
try {
|
|
11903
12610
|
if (fs.statSync(directory).isDirectory()) return directory;
|
|
11904
12611
|
} catch {
|
|
@@ -11906,12 +12613,12 @@ function resolveBundledAgentDirectory(packageRoot = resolveHarnessPackageRoot())
|
|
|
11906
12613
|
throw new Error(`Bundled Pi agent directory is not a directory: ${directory}`);
|
|
11907
12614
|
}
|
|
11908
12615
|
function exposeBundledSubagentAgents(environment = process.env, agentDirectory = resolveBundledAgentDirectory()) {
|
|
11909
|
-
const current = environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV]?.split(
|
|
11910
|
-
const resolvedAgentDirectory =
|
|
11911
|
-
if (!current.some((directory) =>
|
|
12616
|
+
const current = environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV]?.split(path14.delimiter).map((directory) => directory.trim()).filter(Boolean) ?? [];
|
|
12617
|
+
const resolvedAgentDirectory = path14.resolve(agentDirectory);
|
|
12618
|
+
if (!current.some((directory) => path14.resolve(directory) === resolvedAgentDirectory)) {
|
|
11912
12619
|
current.push(resolvedAgentDirectory);
|
|
11913
12620
|
}
|
|
11914
|
-
environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV] = current.join(
|
|
12621
|
+
environment[SUBAGENT_EXTRA_AGENT_DIRS_ENV] = current.join(path14.delimiter);
|
|
11915
12622
|
return resolvedAgentDirectory;
|
|
11916
12623
|
}
|
|
11917
12624
|
|
|
@@ -12186,7 +12893,7 @@ function createLongHorizonHarnessOptions(cwd, subagentsExtension) {
|
|
|
12186
12893
|
};
|
|
12187
12894
|
}
|
|
12188
12895
|
async function runLongHorizonHarness(args) {
|
|
12189
|
-
const cwd =
|
|
12896
|
+
const cwd = path15.resolve(process.cwd());
|
|
12190
12897
|
await runComposedHarness(args, createLongHorizonHarnessOptions(cwd));
|
|
12191
12898
|
}
|
|
12192
12899
|
|
|
@@ -12219,7 +12926,7 @@ async function runPiPtcHarness(args) {
|
|
|
12219
12926
|
}
|
|
12220
12927
|
|
|
12221
12928
|
// src/harnesses/scaling/index.ts
|
|
12222
|
-
import { readFile as
|
|
12929
|
+
import { readFile as readFile15 } from "node:fs/promises";
|
|
12223
12930
|
init_config();
|
|
12224
12931
|
init_runtime();
|
|
12225
12932
|
|
|
@@ -12368,14 +13075,14 @@ async function parseScalingInvocation(args) {
|
|
|
12368
13075
|
throw new Error(`${arg} would override the selected Components \xD7 Design; use a separate configuration`);
|
|
12369
13076
|
piArgs.push(arg);
|
|
12370
13077
|
}
|
|
12371
|
-
const config = file ? parseScalingConfig(JSON.parse(await
|
|
13078
|
+
const config = file ? parseScalingConfig(JSON.parse(await readFile15(file, "utf8"))) : SCALING_PRESETS[selection ?? "H01"];
|
|
12372
13079
|
if (!config) throw new Error(`Unknown scaling preset: ${selection}; choose H01\u2013H18`);
|
|
12373
13080
|
return {
|
|
12374
13081
|
config,
|
|
12375
13082
|
args: piArgs,
|
|
12376
13083
|
list,
|
|
12377
13084
|
describe,
|
|
12378
|
-
...toolFile ? { toolServices: parseTaskToolServices(JSON.parse(await
|
|
13085
|
+
...toolFile ? { toolServices: parseTaskToolServices(JSON.parse(await readFile15(toolFile, "utf8"))) } : {}
|
|
12379
13086
|
};
|
|
12380
13087
|
}
|
|
12381
13088
|
async function runScalingHarness(args) {
|
|
@@ -12428,8 +13135,8 @@ import { Type as Type94 } from "typebox";
|
|
|
12428
13135
|
|
|
12429
13136
|
// src/utils/filesystem/str_replace_editor.ts
|
|
12430
13137
|
init_workspace();
|
|
12431
|
-
import { readFile as
|
|
12432
|
-
import
|
|
13138
|
+
import { readFile as readFile16, readdir as readdir3, stat as stat4, writeFile as writeFile14 } from "node:fs/promises";
|
|
13139
|
+
import path32 from "node:path";
|
|
12433
13140
|
var STR_REPLACE_EDITOR_DEFAULT_MAX_OUTPUT_CHARS = 16e3;
|
|
12434
13141
|
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>";
|
|
12435
13142
|
function throwIfAborted2(signal) {
|
|
@@ -12449,7 +13156,7 @@ function requiredForCommand(value, parameter, command, allowEmpty = true) {
|
|
|
12449
13156
|
}
|
|
12450
13157
|
async function resolveAbsoluteWorkspacePath(cwd, rawPath) {
|
|
12451
13158
|
if (!rawPath.trim()) throw new Error("path must be a non-empty string");
|
|
12452
|
-
if (!
|
|
13159
|
+
if (!path32.isAbsolute(rawPath)) {
|
|
12453
13160
|
throw new Error(
|
|
12454
13161
|
`The path ${rawPath} is not an absolute path, it should start with \`/\`. Maybe you meant /${rawPath}?`
|
|
12455
13162
|
);
|
|
@@ -12522,8 +13229,8 @@ async function listDirectory(target, displayTarget, maxOutputChars, signal) {
|
|
|
12522
13229
|
const rows2 = [];
|
|
12523
13230
|
for (const entry of entries) {
|
|
12524
13231
|
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "__pycache__") continue;
|
|
12525
|
-
const child =
|
|
12526
|
-
const displayChild =
|
|
13232
|
+
const child = path32.join(directory, entry.name);
|
|
13233
|
+
const displayChild = path32.join(displayDirectory, entry.name);
|
|
12527
13234
|
const type = entry.isDirectory() ? "d" : entry.isFile() ? "f" : "?";
|
|
12528
13235
|
rows2.push(`${type} ${displayChild}`);
|
|
12529
13236
|
if (entry.isDirectory() && depth < 2) {
|
|
@@ -12567,7 +13274,7 @@ function lineNumbersAt(content, offsets) {
|
|
|
12567
13274
|
}
|
|
12568
13275
|
async function viewPath(cwd, request, maxOutputChars, signal) {
|
|
12569
13276
|
const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
|
|
12570
|
-
const displayTarget =
|
|
13277
|
+
const displayTarget = path32.resolve(request.path);
|
|
12571
13278
|
const type = await requireExisting(target, displayTarget, "view");
|
|
12572
13279
|
if (type === "directory") {
|
|
12573
13280
|
if (request.view_range !== void 0) {
|
|
@@ -12578,16 +13285,16 @@ async function viewPath(cwd, request, maxOutputChars, signal) {
|
|
|
12578
13285
|
if (type !== "file") {
|
|
12579
13286
|
throw new Error(`cannot view "${displayTarget}": not a regular file or directory`);
|
|
12580
13287
|
}
|
|
12581
|
-
const content = await
|
|
13288
|
+
const content = await readFile16(target, { encoding: "utf8", signal });
|
|
12582
13289
|
return formatFileView(displayTarget, content, maxOutputChars, request.view_range);
|
|
12583
13290
|
}
|
|
12584
13291
|
async function createFile(cwd, request, signal) {
|
|
12585
13292
|
const content = requiredForCommand(request.file_text, "file_text", "create");
|
|
12586
13293
|
const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
|
|
12587
|
-
const displayTarget =
|
|
13294
|
+
const displayTarget = path32.resolve(request.path);
|
|
12588
13295
|
throwIfAborted2(signal);
|
|
12589
13296
|
try {
|
|
12590
|
-
await
|
|
13297
|
+
await writeFile14(target, content, { encoding: "utf8", flag: "wx", signal });
|
|
12591
13298
|
} catch (error) {
|
|
12592
13299
|
if (error instanceof Error && "code" in error && error.code === "EEXIST") {
|
|
12593
13300
|
throw new Error(
|
|
@@ -12602,10 +13309,10 @@ async function replaceInFile(cwd, request, signal) {
|
|
|
12602
13309
|
const oldValue = requiredForCommand(request.old_str, "old_str", "str_replace", false);
|
|
12603
13310
|
const newValue = request.new_str ?? "";
|
|
12604
13311
|
const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
|
|
12605
|
-
const displayTarget =
|
|
13312
|
+
const displayTarget = path32.resolve(request.path);
|
|
12606
13313
|
const type = await requireExisting(target, displayTarget, "str_replace");
|
|
12607
13314
|
if (type !== "file") throw new Error(`cannot edit "${displayTarget}": not a regular file`);
|
|
12608
|
-
const before = await
|
|
13315
|
+
const before = await readFile16(target, { encoding: "utf8", signal });
|
|
12609
13316
|
const offsets = matchOffsets(before, oldValue);
|
|
12610
13317
|
const offset = offsets[0];
|
|
12611
13318
|
if (offset === void 0) {
|
|
@@ -12620,7 +13327,7 @@ async function replaceInFile(cwd, request, signal) {
|
|
|
12620
13327
|
);
|
|
12621
13328
|
}
|
|
12622
13329
|
const after = before.slice(0, offset) + newValue + before.slice(offset + oldValue.length);
|
|
12623
|
-
await
|
|
13330
|
+
await writeFile14(target, after, { encoding: "utf8", signal });
|
|
12624
13331
|
return `The file ${displayTarget} has been edited successfully.`;
|
|
12625
13332
|
}
|
|
12626
13333
|
async function insertInFile(cwd, request, signal) {
|
|
@@ -12629,10 +13336,10 @@ async function insertInFile(cwd, request, signal) {
|
|
|
12629
13336
|
}
|
|
12630
13337
|
const value = requiredForCommand(request.new_str, "new_str", "insert");
|
|
12631
13338
|
const target = await resolveAbsoluteWorkspacePath(cwd, request.path);
|
|
12632
|
-
const displayTarget =
|
|
13339
|
+
const displayTarget = path32.resolve(request.path);
|
|
12633
13340
|
const type = await requireExisting(target, displayTarget, "insert");
|
|
12634
13341
|
if (type !== "file") throw new Error(`cannot insert into "${displayTarget}": not a regular file`);
|
|
12635
|
-
const before = await
|
|
13342
|
+
const before = await readFile16(target, { encoding: "utf8", signal });
|
|
12636
13343
|
const lines = before.split("\n");
|
|
12637
13344
|
if (!Number.isInteger(request.insert_line) || request.insert_line < 0 || request.insert_line > lines.length) {
|
|
12638
13345
|
throw new Error(
|
|
@@ -12644,7 +13351,7 @@ async function insertInFile(cwd, request, signal) {
|
|
|
12644
13351
|
...value.split("\n"),
|
|
12645
13352
|
...lines.slice(request.insert_line)
|
|
12646
13353
|
].join("\n");
|
|
12647
|
-
await
|
|
13354
|
+
await writeFile14(target, after, { encoding: "utf8", signal });
|
|
12648
13355
|
return `The file ${displayTarget} has been edited successfully.`;
|
|
12649
13356
|
}
|
|
12650
13357
|
function resolveStrReplaceEditorOptions(options = {}) {
|
|
@@ -12872,18 +13579,18 @@ import {
|
|
|
12872
13579
|
readFileSync,
|
|
12873
13580
|
realpathSync
|
|
12874
13581
|
} from "node:fs";
|
|
12875
|
-
import
|
|
13582
|
+
import path33 from "node:path";
|
|
12876
13583
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
12877
13584
|
var SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
|
|
12878
13585
|
function resolvePackagedHarnessEntrypoint(candidate) {
|
|
12879
13586
|
try {
|
|
12880
13587
|
const entrypoint = realpathSync(candidate);
|
|
12881
|
-
if (
|
|
13588
|
+
if (path33.basename(entrypoint) !== "entrypoint.js" || path33.basename(path33.dirname(entrypoint)) !== "dist") {
|
|
12882
13589
|
return void 0;
|
|
12883
13590
|
}
|
|
12884
|
-
const packageRoot =
|
|
13591
|
+
const packageRoot = path33.dirname(path33.dirname(entrypoint));
|
|
12885
13592
|
const packageJson = JSON.parse(
|
|
12886
|
-
readFileSync(
|
|
13593
|
+
readFileSync(path33.join(packageRoot, "package.json"), "utf8")
|
|
12887
13594
|
);
|
|
12888
13595
|
if (packageJson.name !== "@qwen-code/qwen-harness") return void 0;
|
|
12889
13596
|
if (process.platform !== "win32") accessSync(entrypoint, constants2.X_OK);
|