orkestrator 2.36.5-beta → 2.36.6-beta
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/dist/client.js +72 -20
- package/dist/main.js +64254 -62158
- package/package.json +3 -3
- package/resources/acp-bridge/dist/index.js +365 -78
- package/resources/claude-bridge/dist/index.js +411 -96
- package/resources/codex-bridge/dist/index.js +541 -148
- package/resources/cursor-bridge/dist/index.js +344 -61
- package/resources/cursor-bridge/runtime/install.json +1 -1
- package/resources/pi-bridge/dist/index.js +885 -350
- package/resources/pi-bridge/runtime/install.json +1 -1
|
@@ -490,12 +490,84 @@ var require_cross_spawn = __commonJS(function(exports, module) {
|
|
|
490
490
|
module.exports._enoent = enoent;
|
|
491
491
|
});
|
|
492
492
|
|
|
493
|
+
// ../protocol/src/node/bridge-launch-environment.ts
|
|
494
|
+
import { closeSync, fstatSync, openSync, readSync, rmSync, constants } from "node:fs";
|
|
495
|
+
var BRIDGE_LAUNCH_ENVIRONMENT_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_ENVIRONMENT";
|
|
496
|
+
var BRIDGE_LAUNCH_KEYS_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_KEYS";
|
|
497
|
+
var BRIDGE_LAUNCH_WORKDIR_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_WORKDIR";
|
|
498
|
+
var MAX_SNAPSHOT_BYTES = 1024 * 1024;
|
|
499
|
+
var MAX_SNAPSHOT_ENTRIES = 4096;
|
|
500
|
+
var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_%.-]*$/;
|
|
501
|
+
var LAUNCH_ONLY = /(?:_BRIDGE_TOKEN|_TOKEN_SHA256|_AUTHORITY_KEY)$|^ORKESTRATOR_BRIDGE_(?:LAUNCH_|EXECUTION_POLICY$)|^ORKESTRATOR_COORDINATOR_/;
|
|
502
|
+
var NOT_APPLIED = new Set(["PWD", "OLDPWD", "SHLVL", "_", "NODE_PATH"]);
|
|
503
|
+
function readSnapshot(file) {
|
|
504
|
+
let fd;
|
|
505
|
+
try {
|
|
506
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
507
|
+
} catch {
|
|
508
|
+
return null;
|
|
509
|
+
}
|
|
510
|
+
try {
|
|
511
|
+
const stat = fstatSync(fd);
|
|
512
|
+
if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
|
|
513
|
+
return null;
|
|
514
|
+
const buffer = Buffer.alloc(stat.size);
|
|
515
|
+
let offset = 0;
|
|
516
|
+
while (offset < buffer.length) {
|
|
517
|
+
const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
|
|
518
|
+
if (read === 0)
|
|
519
|
+
break;
|
|
520
|
+
offset += read;
|
|
521
|
+
}
|
|
522
|
+
return buffer.subarray(0, offset);
|
|
523
|
+
} finally {
|
|
524
|
+
closeSync(fd);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
function applyBridgeLaunchEnvironment(env = process.env, chdir = (directory) => process.chdir(directory)) {
|
|
528
|
+
const file = env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
|
|
529
|
+
if (!file)
|
|
530
|
+
return null;
|
|
531
|
+
const trusted = new Set((env[BRIDGE_LAUNCH_KEYS_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean));
|
|
532
|
+
const workdir = env[BRIDGE_LAUNCH_WORKDIR_ENV];
|
|
533
|
+
delete env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
|
|
534
|
+
delete env[BRIDGE_LAUNCH_KEYS_ENV];
|
|
535
|
+
delete env[BRIDGE_LAUNCH_WORKDIR_ENV];
|
|
536
|
+
const result = { applied: 0, refused: 0 };
|
|
537
|
+
const snapshot = readSnapshot(file);
|
|
538
|
+
rmSync(file, { force: true });
|
|
539
|
+
if (snapshot) {
|
|
540
|
+
const entries = snapshot.toString("utf8").split("\x00").slice(0, MAX_SNAPSHOT_ENTRIES);
|
|
541
|
+
for (const entry of entries) {
|
|
542
|
+
const separator = entry.indexOf("=");
|
|
543
|
+
if (separator <= 0)
|
|
544
|
+
continue;
|
|
545
|
+
const name = entry.slice(0, separator);
|
|
546
|
+
if (!NAME_PATTERN.test(name) || NOT_APPLIED.has(name))
|
|
547
|
+
continue;
|
|
548
|
+
if (trusted.has(name) || LAUNCH_ONLY.test(name)) {
|
|
549
|
+
result.refused += 1;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
env[name] = entry.slice(separator + 1);
|
|
553
|
+
result.applied += 1;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (workdir) {
|
|
557
|
+
try {
|
|
558
|
+
chdir(workdir);
|
|
559
|
+
} catch {}
|
|
560
|
+
}
|
|
561
|
+
return result;
|
|
562
|
+
}
|
|
563
|
+
applyBridgeLaunchEnvironment();
|
|
564
|
+
|
|
493
565
|
// ../../bridges/pi-bridge/src/config.ts
|
|
494
|
-
import { randomBytes as
|
|
566
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
495
567
|
import { resolve } from "node:path";
|
|
496
568
|
|
|
497
569
|
// ../protocol/src/node/bridge-credential.ts
|
|
498
|
-
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
570
|
+
import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
|
|
499
571
|
import { createRequire as createRequire2 } from "node:module";
|
|
500
572
|
|
|
501
573
|
// ../protocol/src/secret-redaction.ts
|
|
@@ -541,7 +613,7 @@ var MAX_FRAME_CHARS = 240;
|
|
|
541
613
|
var MAX_RAW_FRAME_CHARS = 1024;
|
|
542
614
|
var MAX_CAUSE_DEPTH = 2;
|
|
543
615
|
var TRUNCATED_MARKER = "...[truncated]";
|
|
544
|
-
var
|
|
616
|
+
var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
|
|
545
617
|
var CODE_PATTERN = /^[\w.:-]{1,64}$/;
|
|
546
618
|
var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
|
|
547
619
|
var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
|
|
@@ -619,7 +691,7 @@ function describe(error, includeStack, includeMessage, depth) {
|
|
|
619
691
|
if (!(error instanceof Error) && typeof rawMessage !== "string") {
|
|
620
692
|
return { name: "NonError", message: "[object]" };
|
|
621
693
|
}
|
|
622
|
-
const name = matching(read(error, "name"),
|
|
694
|
+
const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
|
|
623
695
|
const message = typeof rawMessage === "string" ? rawMessage : undefined;
|
|
624
696
|
const commandFailure = isCommandFailure(error, name, message);
|
|
625
697
|
const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
|
|
@@ -674,7 +746,7 @@ function logErrorKind(error) {
|
|
|
674
746
|
const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
|
|
675
747
|
if (safeCode !== undefined)
|
|
676
748
|
return String(safeCode);
|
|
677
|
-
return matching(read(error, "name"),
|
|
749
|
+
return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
|
|
678
750
|
}
|
|
679
751
|
|
|
680
752
|
// ../protocol/src/log-vocabulary/define.ts
|
|
@@ -1095,6 +1167,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
|
|
|
1095
1167
|
events: {
|
|
1096
1168
|
"attention-failed": "A dialog could not ask for the user's attention.",
|
|
1097
1169
|
closed: "A native dialog closed.",
|
|
1170
|
+
"hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
|
|
1098
1171
|
"open-failed": "A dialog could not open; it was answered as cancelled.",
|
|
1099
1172
|
opening: "A native dialog is opening.",
|
|
1100
1173
|
"preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
|
|
@@ -1180,6 +1253,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
|
|
|
1180
1253
|
"orphan-session.reaped": "A native session no tab references was torn down.",
|
|
1181
1254
|
"handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
|
|
1182
1255
|
"delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
|
|
1256
|
+
"delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
|
|
1183
1257
|
"delete.artifacts-left": "Graph run artifact directories were not removed.",
|
|
1184
1258
|
"delete.worktrees-kept": "Graph runs kept branch worktrees.",
|
|
1185
1259
|
"delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
|
|
@@ -1214,6 +1288,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
|
|
|
1214
1288
|
"host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
|
|
1215
1289
|
"port.fallback": "The preferred port was taken, so a nearby one is used.",
|
|
1216
1290
|
"port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
|
|
1291
|
+
"request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
|
|
1217
1292
|
"request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
|
|
1218
1293
|
"websocket.upgrade-failed": "A WebSocket upgrade failed.",
|
|
1219
1294
|
"events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
|
|
@@ -1272,6 +1347,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
|
|
|
1272
1347
|
requested: "boolean"
|
|
1273
1348
|
}
|
|
1274
1349
|
},
|
|
1350
|
+
"bridge.orphans-reaped": {
|
|
1351
|
+
description: "Processes a bridge left in its process group after exiting on its own (its agent CLI, mid-turn) were stopped. `warn` when they left; `error` when one survived SIGKILL.",
|
|
1352
|
+
essential: true,
|
|
1353
|
+
fields: { key: "label", pid: "number", result: "label" }
|
|
1354
|
+
},
|
|
1275
1355
|
"reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
|
|
1276
1356
|
"reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
|
|
1277
1357
|
"reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
|
|
@@ -2105,7 +2185,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
|
|
|
2105
2185
|
"network.list-failed": "Docker networks could not be listed.",
|
|
2106
2186
|
"network.inspect-failed": "A Docker network could not be inspected.",
|
|
2107
2187
|
"stale-containers.removing": "Stale probe containers are being removed.",
|
|
2108
|
-
"stale-networks.removing": "Stale probe networks are being removed."
|
|
2188
|
+
"stale-networks.removing": "Stale probe networks are being removed.",
|
|
2189
|
+
"peers.refused": "The agent tools server closed connections from addresses outside loopback and this backend's Docker networks (at most one entry a minute, with a count).",
|
|
2190
|
+
"peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
|
|
2191
|
+
"port.loopback-taken": "The agent tools server gave up a port because another process holds it on 127.0.0.1, where host agents call; it moves to a free port.",
|
|
2192
|
+
"peers.subnets-load-failed": "The Docker subnets the agent tools server admits could not be read; cached permissions are cleared and only loopback is admitted until a successful retry."
|
|
2109
2193
|
}
|
|
2110
2194
|
}
|
|
2111
2195
|
});
|
|
@@ -3349,33 +3433,198 @@ function createLogger(area) {
|
|
|
3349
3433
|
};
|
|
3350
3434
|
}
|
|
3351
3435
|
|
|
3436
|
+
// ../protocol/src/node/bridge-authority.ts
|
|
3437
|
+
import {
|
|
3438
|
+
createHash,
|
|
3439
|
+
createPrivateKey,
|
|
3440
|
+
createPublicKey,
|
|
3441
|
+
generateKeyPairSync,
|
|
3442
|
+
randomBytes,
|
|
3443
|
+
sign,
|
|
3444
|
+
verify
|
|
3445
|
+
} from "node:crypto";
|
|
3446
|
+
var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
|
|
3447
|
+
var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
|
|
3448
|
+
var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
|
|
3449
|
+
var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
|
|
3450
|
+
var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
3451
|
+
var SCHEME = "orkestrator-bridge-authority-v1";
|
|
3452
|
+
var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
|
|
3453
|
+
var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
|
|
3454
|
+
var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
3455
|
+
var UNSIGNED_ROUTES = [
|
|
3456
|
+
/^\/session\/[^/]+\/close$/,
|
|
3457
|
+
/^\/sessions\/activity$/,
|
|
3458
|
+
/^\/debug\/log-policy$/
|
|
3459
|
+
];
|
|
3460
|
+
function bridgeAuthorityKeyEnv(tokenEnv) {
|
|
3461
|
+
return `${tokenEnv}_AUTHORITY_KEY`;
|
|
3462
|
+
}
|
|
3463
|
+
function isBridgeAuthorityKey(value) {
|
|
3464
|
+
return typeof value === "string" && KEY_PATTERN.test(value);
|
|
3465
|
+
}
|
|
3466
|
+
function publicKeyFrom(encoded) {
|
|
3467
|
+
if (!isBridgeAuthorityKey(encoded))
|
|
3468
|
+
return null;
|
|
3469
|
+
try {
|
|
3470
|
+
const key = createPublicKey({
|
|
3471
|
+
key: Buffer.from(encoded, "base64url"),
|
|
3472
|
+
format: "der",
|
|
3473
|
+
type: "spki"
|
|
3474
|
+
});
|
|
3475
|
+
return key.asymmetricKeyType === "ed25519" ? key : null;
|
|
3476
|
+
} catch {
|
|
3477
|
+
return null;
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
function bridgeAuthorityTarget(url) {
|
|
3481
|
+
const parsed = new URL(url, "http://bridge.invalid");
|
|
3482
|
+
return `${parsed.pathname}${parsed.search}`;
|
|
3483
|
+
}
|
|
3484
|
+
function bridgeRequestNeedsAuthority(method, target) {
|
|
3485
|
+
if (READ_METHODS.has(method.toUpperCase()))
|
|
3486
|
+
return false;
|
|
3487
|
+
const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
|
|
3488
|
+
return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
|
|
3489
|
+
}
|
|
3490
|
+
function bodyDigest(body) {
|
|
3491
|
+
return createHash("sha256").update(body ?? "").digest("hex");
|
|
3492
|
+
}
|
|
3493
|
+
function signedMessage(method, target, issuedAt, nonce, digest) {
|
|
3494
|
+
return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
|
|
3495
|
+
`));
|
|
3496
|
+
}
|
|
3497
|
+
var UNENFORCED = {
|
|
3498
|
+
enforced: false,
|
|
3499
|
+
requires: () => false,
|
|
3500
|
+
check: () => ({ ok: true })
|
|
3501
|
+
};
|
|
3502
|
+
function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
|
|
3503
|
+
if (publicKey === undefined)
|
|
3504
|
+
return UNENFORCED;
|
|
3505
|
+
const key = publicKeyFrom(publicKey);
|
|
3506
|
+
const now = options.now ?? Date.now;
|
|
3507
|
+
const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
|
|
3508
|
+
const seen = new Map;
|
|
3509
|
+
let floor = -Infinity;
|
|
3510
|
+
const remember = (nonce, issuedAt, current) => {
|
|
3511
|
+
for (const [oldNonce, oldIssuedAt] of seen) {
|
|
3512
|
+
if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
|
|
3513
|
+
break;
|
|
3514
|
+
seen.delete(oldNonce);
|
|
3515
|
+
floor = Math.max(floor, oldIssuedAt);
|
|
3516
|
+
}
|
|
3517
|
+
seen.set(nonce, issuedAt);
|
|
3518
|
+
};
|
|
3519
|
+
return {
|
|
3520
|
+
enforced: true,
|
|
3521
|
+
requires: bridgeRequestNeedsAuthority,
|
|
3522
|
+
check(request) {
|
|
3523
|
+
if (!request.header)
|
|
3524
|
+
return { ok: false, reason: "missing" };
|
|
3525
|
+
const match = HEADER_PATTERN.exec(request.header.trim());
|
|
3526
|
+
if (!match)
|
|
3527
|
+
return { ok: false, reason: "malformed" };
|
|
3528
|
+
const issuedAt = Number(match[1]);
|
|
3529
|
+
const nonce = match[2];
|
|
3530
|
+
const current = now();
|
|
3531
|
+
if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
|
|
3532
|
+
return { ok: false, reason: "stale" };
|
|
3533
|
+
}
|
|
3534
|
+
if (!key)
|
|
3535
|
+
return { ok: false, reason: "invalid" };
|
|
3536
|
+
const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
|
|
3537
|
+
if (!valid)
|
|
3538
|
+
return { ok: false, reason: "invalid" };
|
|
3539
|
+
if (seen.has(nonce))
|
|
3540
|
+
return { ok: false, reason: "replayed" };
|
|
3541
|
+
remember(nonce, issuedAt, current);
|
|
3542
|
+
return { ok: true };
|
|
3543
|
+
}
|
|
3544
|
+
};
|
|
3545
|
+
}
|
|
3546
|
+
function loadBridgeAuthority(tokenEnv, options = {}) {
|
|
3547
|
+
const env = options.env ?? process.env;
|
|
3548
|
+
const name = bridgeAuthorityKeyEnv(tokenEnv);
|
|
3549
|
+
const value = env[name]?.trim();
|
|
3550
|
+
delete env[name];
|
|
3551
|
+
return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
|
|
3552
|
+
}
|
|
3553
|
+
function refusal(reason) {
|
|
3554
|
+
return {
|
|
3555
|
+
status: 403,
|
|
3556
|
+
body: {
|
|
3557
|
+
error: "This request changes an agent's authority and needs the backend's signature",
|
|
3558
|
+
code: BRIDGE_AUTHORITY_REFUSED_CODE,
|
|
3559
|
+
reason
|
|
3560
|
+
}
|
|
3561
|
+
};
|
|
3562
|
+
}
|
|
3563
|
+
var TOO_LARGE = {
|
|
3564
|
+
status: 413,
|
|
3565
|
+
body: { error: "Request body is too large" }
|
|
3566
|
+
};
|
|
3567
|
+
var admittedBodies = new WeakMap;
|
|
3568
|
+
async function admitNodeBridgeRequest(authority, request, maxBodyBytes) {
|
|
3569
|
+
const method = request.method ?? "GET";
|
|
3570
|
+
const url = request.url ?? "/";
|
|
3571
|
+
if (!authority.requires(method, url))
|
|
3572
|
+
return null;
|
|
3573
|
+
const header = request.headers[BRIDGE_AUTHORITY_HEADER];
|
|
3574
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
3575
|
+
if (!value)
|
|
3576
|
+
return refusal("missing");
|
|
3577
|
+
const chunks = [];
|
|
3578
|
+
let total = 0;
|
|
3579
|
+
for await (const chunk of request) {
|
|
3580
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
3581
|
+
total += buffer.length;
|
|
3582
|
+
if (total > maxBodyBytes)
|
|
3583
|
+
return TOO_LARGE;
|
|
3584
|
+
chunks.push(buffer);
|
|
3585
|
+
}
|
|
3586
|
+
const body = Buffer.concat(chunks);
|
|
3587
|
+
const result = authority.check({ method, url, header: value, body });
|
|
3588
|
+
if (!result.ok)
|
|
3589
|
+
return refusal(result.reason);
|
|
3590
|
+
admittedBodies.set(request, body);
|
|
3591
|
+
return null;
|
|
3592
|
+
}
|
|
3593
|
+
function takeAdmittedBody(request) {
|
|
3594
|
+
const body = admittedBodies.get(request);
|
|
3595
|
+
admittedBodies.delete(request);
|
|
3596
|
+
return body;
|
|
3597
|
+
}
|
|
3598
|
+
|
|
3352
3599
|
// ../protocol/src/node/bridge-credential.ts
|
|
3353
3600
|
var BRIDGE_TOKEN_PREFIX = "okb_";
|
|
3354
3601
|
var PR_SET_DUMPABLE = 4;
|
|
3355
3602
|
var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
|
|
3356
3603
|
var log = createLogger("bridge.lifecycle");
|
|
3357
3604
|
function mintBridgeToken() {
|
|
3358
|
-
return `${BRIDGE_TOKEN_PREFIX}${
|
|
3605
|
+
return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
|
|
3359
3606
|
}
|
|
3360
3607
|
function bridgeTokenVerifier(token) {
|
|
3361
|
-
return
|
|
3608
|
+
return createHash2("sha256").update(token).digest("hex");
|
|
3362
3609
|
}
|
|
3363
3610
|
function bridgeTokenVerifierEnv(tokenEnv) {
|
|
3364
3611
|
return `${tokenEnv}_SHA256`;
|
|
3365
3612
|
}
|
|
3366
|
-
function credentialFromVerifier(verifier, plainToken) {
|
|
3613
|
+
function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
|
|
3367
3614
|
const expected = Buffer.from(verifier, "hex");
|
|
3368
3615
|
return {
|
|
3369
3616
|
plainToken,
|
|
3617
|
+
authority,
|
|
3370
3618
|
matches(candidate) {
|
|
3371
3619
|
if (!candidate)
|
|
3372
3620
|
return false;
|
|
3373
|
-
return timingSafeEqual(expected,
|
|
3621
|
+
return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
|
|
3374
3622
|
}
|
|
3375
3623
|
};
|
|
3376
3624
|
}
|
|
3377
|
-
|
|
3378
|
-
|
|
3625
|
+
var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
|
|
3626
|
+
function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
|
|
3627
|
+
return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
|
|
3379
3628
|
}
|
|
3380
3629
|
function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
|
|
3381
3630
|
if (process.platform !== "linux" || !process.versions.bun)
|
|
@@ -3407,21 +3656,23 @@ function loadBridgeCredential(tokenEnv, options = {}) {
|
|
|
3407
3656
|
const token = env[tokenEnv]?.trim();
|
|
3408
3657
|
delete env[verifierEnv];
|
|
3409
3658
|
delete env[tokenEnv];
|
|
3659
|
+
const authority = loadBridgeAuthority(tokenEnv, { env });
|
|
3410
3660
|
if (verifier) {
|
|
3411
3661
|
(options.harden ?? markProcessNonDumpable)();
|
|
3412
|
-
return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
|
|
3662
|
+
return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
|
|
3413
3663
|
}
|
|
3414
|
-
return bridgeCredentialFromToken(token || mintBridgeToken());
|
|
3664
|
+
return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
|
|
3415
3665
|
}
|
|
3416
3666
|
|
|
3417
3667
|
// ../../bridges/pi-bridge/src/config.ts
|
|
3418
3668
|
var PROVIDER = "pi";
|
|
3419
|
-
var bridgeGeneration =
|
|
3669
|
+
var bridgeGeneration = randomBytes3(16).toString("hex");
|
|
3420
3670
|
var port = parsePort(process.env.PORT);
|
|
3421
3671
|
var hostname = process.env.HOSTNAME?.trim() || "127.0.0.1";
|
|
3422
3672
|
var workingDirectory = resolve(process.env.CWD?.trim() || process.cwd());
|
|
3423
3673
|
var bridgeCredential = loadBridgeCredential("PI_BRIDGE_TOKEN");
|
|
3424
3674
|
var authToken = bridgeCredential.plainToken ?? "";
|
|
3675
|
+
var bridgeAuthority = bridgeCredential.authority;
|
|
3425
3676
|
function stateFilePath() {
|
|
3426
3677
|
const directory = process.env.PI_BRIDGE_STATE_DIR?.trim();
|
|
3427
3678
|
return directory ? resolve(directory, "state.json") : null;
|
|
@@ -3560,7 +3811,7 @@ function promptClaimReleased(state) {
|
|
|
3560
3811
|
return claimReleases.get(state)?.promise ?? Promise.resolve();
|
|
3561
3812
|
}
|
|
3562
3813
|
function publicTurnStatus(state) {
|
|
3563
|
-
return state.promptClaim !== undefined ? "running" : state.status;
|
|
3814
|
+
return state.promptClaim !== undefined || state.compacting ? "running" : state.status;
|
|
3564
3815
|
}
|
|
3565
3816
|
function cancelRequestedFor(state, claim) {
|
|
3566
3817
|
return claim !== undefined && state.cancelRequestedClaim === claim;
|
|
@@ -3960,7 +4211,7 @@ function boundId(value) {
|
|
|
3960
4211
|
return Buffer.byteLength(trimmed) > MAX_MODEL_ID_BYTES ? "" : trimmed;
|
|
3961
4212
|
}
|
|
3962
4213
|
// ../protocol/src/node/revised-rows.ts
|
|
3963
|
-
import { createHash as
|
|
4214
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
3964
4215
|
var RECENTLY_REVISED_ROWS_MAX = 128;
|
|
3965
4216
|
|
|
3966
4217
|
class RecentlyRevisedRows {
|
|
@@ -3998,7 +4249,7 @@ class RecentlyRevisedRows {
|
|
|
3998
4249
|
function revisedRowsReconciliationToken(overflowVersion, omitted) {
|
|
3999
4250
|
if (overflowVersion === 0 && omitted.length === 0)
|
|
4000
4251
|
return;
|
|
4001
|
-
const digest =
|
|
4252
|
+
const digest = createHash3("sha256").update(String(overflowVersion));
|
|
4002
4253
|
for (const row of omitted)
|
|
4003
4254
|
digest.update(JSON.stringify(row) ?? "null");
|
|
4004
4255
|
return digest.digest("hex");
|
|
@@ -4624,7 +4875,7 @@ function firstLine(value) {
|
|
|
4624
4875
|
return line.trim() || value.trim();
|
|
4625
4876
|
}
|
|
4626
4877
|
// ../../bridges/pi-bridge/src/translate.ts
|
|
4627
|
-
import { randomBytes as
|
|
4878
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
4628
4879
|
|
|
4629
4880
|
// ../protocol/src/transcript-part-ids.ts
|
|
4630
4881
|
var TOOL_RESULT_IMAGE_PREFIX = "image:";
|
|
@@ -4659,7 +4910,7 @@ function nextPartOrdinal(message) {
|
|
|
4659
4910
|
}
|
|
4660
4911
|
|
|
4661
4912
|
// ../../bridges/pi-bridge/src/commands.ts
|
|
4662
|
-
import { randomBytes as
|
|
4913
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
4663
4914
|
|
|
4664
4915
|
// ../protocol/src/agent-platforms.ts
|
|
4665
4916
|
var AGENT_PLATFORMS = Object.freeze([
|
|
@@ -6149,7 +6400,7 @@ function settleCommandRun(state, run, requestId) {
|
|
|
6149
6400
|
return;
|
|
6150
6401
|
}
|
|
6151
6402
|
function appendCommandOutcome(state, requestId, part) {
|
|
6152
|
-
const messageId = requestId ? `command-outcome:${requestId}` : `command-outcome:${
|
|
6403
|
+
const messageId = requestId ? `command-outcome:${requestId}` : `command-outcome:${randomBytes4(12).toString("hex")}`;
|
|
6153
6404
|
if (state.messages.some((message) => message.id === messageId))
|
|
6154
6405
|
return;
|
|
6155
6406
|
const message = {
|
|
@@ -6311,7 +6562,7 @@ function applySteerDelivery(state, value) {
|
|
|
6311
6562
|
setSteerJournal(state, { ...entry, state: "delivered" });
|
|
6312
6563
|
state.currentAssistantMessageId = undefined;
|
|
6313
6564
|
state.openTextParts.clear();
|
|
6314
|
-
const messageId =
|
|
6565
|
+
const messageId = randomBytes5(12).toString("hex");
|
|
6315
6566
|
const message = {
|
|
6316
6567
|
id: messageId,
|
|
6317
6568
|
role: "user",
|
|
@@ -6601,7 +6852,7 @@ var RESUME_FELL_BACK_NOTICE = "Could not resume the previous Pi conversation, so
|
|
|
6601
6852
|
function appendResumeFallbackNotice(state) {
|
|
6602
6853
|
closeTextParts(state);
|
|
6603
6854
|
state.currentAssistantMessageId = undefined;
|
|
6604
|
-
const messageId =
|
|
6855
|
+
const messageId = randomBytes5(12).toString("hex");
|
|
6605
6856
|
const createdAt = new Date().toISOString();
|
|
6606
6857
|
const part = {
|
|
6607
6858
|
type: "status",
|
|
@@ -6709,7 +6960,7 @@ function currentAssistantMessage(state) {
|
|
|
6709
6960
|
if (last?.role === "assistant" && last.id === state.currentAssistantMessageId)
|
|
6710
6961
|
return last;
|
|
6711
6962
|
const message = {
|
|
6712
|
-
id:
|
|
6963
|
+
id: randomBytes5(12).toString("hex"),
|
|
6713
6964
|
role: "assistant",
|
|
6714
6965
|
content: "",
|
|
6715
6966
|
parts: [],
|
|
@@ -6847,7 +7098,7 @@ function readStringList(value) {
|
|
|
6847
7098
|
return value.filter((entry) => typeof entry === "string");
|
|
6848
7099
|
}
|
|
6849
7100
|
// ../../bridges/pi-bridge/src/interactions.ts
|
|
6850
|
-
import { randomBytes as
|
|
7101
|
+
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
6851
7102
|
|
|
6852
7103
|
// ../protocol/src/agent-interaction-deadline.ts
|
|
6853
7104
|
var SYSTEM_CLOCK = {
|
|
@@ -6961,6 +7212,7 @@ class InteractionDeadline {
|
|
|
6961
7212
|
}
|
|
6962
7213
|
|
|
6963
7214
|
// ../protocol/src/coordinator.ts
|
|
7215
|
+
var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
|
|
6964
7216
|
var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
|
|
6965
7217
|
var COORDINATOR_ENVIRONMENT_ORIGIN_REFUSAL = `Not done: this coordinator did not create that environment, so it may not send it work. Do not retry. Use an environment this coordinator launched, or start a new one. If the user wants this coordinator to work in environments it did not create, tell them to turn on "${COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL}" in this project's settings, under Coordinator.`;
|
|
6966
7218
|
var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
|
|
@@ -7338,7 +7590,7 @@ var DEFAULT_WORKFLOW_RESULT_TOOLS_SETTINGS = {
|
|
|
7338
7590
|
};
|
|
7339
7591
|
|
|
7340
7592
|
// ../../bridges/pi-bridge/src/mcp.ts
|
|
7341
|
-
import { createHash as
|
|
7593
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
7342
7594
|
import { readFile } from "node:fs/promises";
|
|
7343
7595
|
import { join as join3, resolve as resolvePath } from "node:path";
|
|
7344
7596
|
|
|
@@ -31187,7 +31439,7 @@ function mcpConnectionNeedsRefresh(state) {
|
|
|
31187
31439
|
}
|
|
31188
31440
|
async function fileDigest(file) {
|
|
31189
31441
|
try {
|
|
31190
|
-
return `sha256:${
|
|
31442
|
+
return `sha256:${createHash4("sha256").update(await readFile(file)).digest("base64url")}`;
|
|
31191
31443
|
} catch {
|
|
31192
31444
|
return "absent";
|
|
31193
31445
|
}
|
|
@@ -31199,7 +31451,7 @@ async function piMcpConfigRevision(state, options = {}) {
|
|
|
31199
31451
|
state.policy?.projectResources === true ? fileDigest(join3(options.cwd ?? workingDirectory, ".pi", "mcp.json")) : Promise.resolve("excluded")
|
|
31200
31452
|
]);
|
|
31201
31453
|
return {
|
|
31202
|
-
fingerprint:
|
|
31454
|
+
fingerprint: createHash4("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
|
|
31203
31455
|
sources: { user, project }
|
|
31204
31456
|
};
|
|
31205
31457
|
}
|
|
@@ -31572,7 +31824,7 @@ import { mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promise
|
|
|
31572
31824
|
import { dirname } from "node:path";
|
|
31573
31825
|
|
|
31574
31826
|
// ../../bridges/pi-bridge/src/session-factory.ts
|
|
31575
|
-
import { randomBytes as
|
|
31827
|
+
import { randomBytes as randomBytes6 } from "node:crypto";
|
|
31576
31828
|
|
|
31577
31829
|
// ../protocol/src/runtime-health.ts
|
|
31578
31830
|
var MAX_RUNTIME_NOTICE_MESSAGE_LENGTH = 1000;
|
|
@@ -31662,7 +31914,7 @@ function emptyRuntimeHealth() {
|
|
|
31662
31914
|
// ../../bridges/pi-bridge/src/session-factory.ts
|
|
31663
31915
|
function newSessionState(clientSessionKey, policy) {
|
|
31664
31916
|
return {
|
|
31665
|
-
id:
|
|
31917
|
+
id: randomBytes6(16).toString("hex"),
|
|
31666
31918
|
...policy ? { policy } : {},
|
|
31667
31919
|
...clientSessionKey ? { clientSessionKey } : {},
|
|
31668
31920
|
status: "idle",
|
|
@@ -31813,6 +32065,7 @@ function toPersisted(state) {
|
|
|
31813
32065
|
...state.promptJournalComplete ? { promptJournalComplete: true } : {},
|
|
31814
32066
|
steerJournal: Array.from(state.steerJournal.values()).map((entry) => entry.state === "prepared" || entry.state === "queued" ? { ...entry, state: "ambiguous" } : entry),
|
|
31815
32067
|
composer: state.composer,
|
|
32068
|
+
...state.autoCompaction === undefined ? {} : { autoCompaction: state.autoCompaction },
|
|
31816
32069
|
...state.usage ? { usage: state.usage } : {},
|
|
31817
32070
|
...state.slashCommands.length > 0 ? { commands: state.slashCommands } : {},
|
|
31818
32071
|
...state.commandCatalogue.truncated ? { commandsTruncated: true } : {},
|
|
@@ -31877,6 +32130,8 @@ function restoreSession(entry) {
|
|
|
31877
32130
|
state.transcriptTruncated = entry.transcriptTruncated === true;
|
|
31878
32131
|
state.revision = readCount(entry.revision);
|
|
31879
32132
|
state.composer = restoreComposer(entry.composer);
|
|
32133
|
+
if (typeof entry.autoCompaction === "boolean")
|
|
32134
|
+
state.autoCompaction = entry.autoCompaction;
|
|
31880
32135
|
const usage = restoreUsage(entry.usage);
|
|
31881
32136
|
if (usage)
|
|
31882
32137
|
state.usage = usage;
|
|
@@ -32031,6 +32286,365 @@ function readJournalState(value) {
|
|
|
32031
32286
|
return "ambiguous";
|
|
32032
32287
|
}
|
|
32033
32288
|
|
|
32289
|
+
// ../../bridges/pi-bridge/src/read-boundary.ts
|
|
32290
|
+
import { homedir as homedir3 } from "node:os";
|
|
32291
|
+
import { resolve as resolve4 } from "node:path";
|
|
32292
|
+
import { fileURLToPath } from "node:url";
|
|
32293
|
+
|
|
32294
|
+
// ../protocol/src/node/coordinator-read-boundary.ts
|
|
32295
|
+
import { realpathSync } from "node:fs";
|
|
32296
|
+
import { homedir as homedir2 } from "node:os";
|
|
32297
|
+
import { dirname as dirname2, isAbsolute, join as join4, parse as parse4, resolve as resolve2, sep } from "node:path";
|
|
32298
|
+
function canonicalPath(path) {
|
|
32299
|
+
let existing = path;
|
|
32300
|
+
const tail = [];
|
|
32301
|
+
for (;; ) {
|
|
32302
|
+
try {
|
|
32303
|
+
return join4(realpathSync.native(existing), ...tail.reverse());
|
|
32304
|
+
} catch {
|
|
32305
|
+
const parent = dirname2(existing);
|
|
32306
|
+
if (parent === existing)
|
|
32307
|
+
return path;
|
|
32308
|
+
tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
|
|
32309
|
+
existing = parent;
|
|
32310
|
+
}
|
|
32311
|
+
}
|
|
32312
|
+
}
|
|
32313
|
+
function namedAndCanonicalPaths(paths) {
|
|
32314
|
+
const named = paths.flatMap((path) => path?.trim() && isAbsolute(path) ? [path] : []);
|
|
32315
|
+
return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
|
|
32316
|
+
}
|
|
32317
|
+
function isWithin(root, path) {
|
|
32318
|
+
if (path === root)
|
|
32319
|
+
return true;
|
|
32320
|
+
const prefix = root === parse4(root).root ? root : `${root}${sep}`;
|
|
32321
|
+
return path.startsWith(prefix);
|
|
32322
|
+
}
|
|
32323
|
+
function protectedDataDirBoundary(dataDir, allowances) {
|
|
32324
|
+
const trimmed = dataDir?.trim();
|
|
32325
|
+
if (!trimmed || !isAbsolute(trimmed))
|
|
32326
|
+
return null;
|
|
32327
|
+
const deny = namedAndCanonicalPaths([trimmed]);
|
|
32328
|
+
return {
|
|
32329
|
+
deny,
|
|
32330
|
+
allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
|
|
32331
|
+
};
|
|
32332
|
+
}
|
|
32333
|
+
function deniedForm(boundary, path) {
|
|
32334
|
+
return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
|
|
32335
|
+
}
|
|
32336
|
+
function expandedHome(path) {
|
|
32337
|
+
if (path === "~")
|
|
32338
|
+
return homedir2();
|
|
32339
|
+
return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
|
|
32340
|
+
}
|
|
32341
|
+
function readBoundaryRefuses(boundary, path, cwd, options = {}) {
|
|
32342
|
+
const expanded = expandedHome(path);
|
|
32343
|
+
const raw = isAbsolute(expanded) ? expanded : `${cwd}${sep}${expanded}`;
|
|
32344
|
+
const lexical = resolve2(raw);
|
|
32345
|
+
const real = canonicalPath(raw);
|
|
32346
|
+
if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
|
|
32347
|
+
return true;
|
|
32348
|
+
return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
|
|
32349
|
+
}
|
|
32350
|
+
|
|
32351
|
+
// ../../bridges/pi-bridge/src/prompt-attachments.ts
|
|
32352
|
+
import { constants as constants2 } from "node:fs";
|
|
32353
|
+
import { lstat, open as open2, realpath } from "node:fs/promises";
|
|
32354
|
+
import { isAbsolute as isAbsolute2, join as join5, relative, resolve as resolve3, sep as sep2 } from "node:path";
|
|
32355
|
+
class PromptAttachmentError extends Error {
|
|
32356
|
+
code;
|
|
32357
|
+
name = "PromptAttachmentError";
|
|
32358
|
+
constructor(code, message) {
|
|
32359
|
+
super(message);
|
|
32360
|
+
this.code = code;
|
|
32361
|
+
}
|
|
32362
|
+
}
|
|
32363
|
+
var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
|
|
32364
|
+
var MAX_PROMPT_ATTACHMENTS = 20;
|
|
32365
|
+
var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
|
|
32366
|
+
var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
|
|
32367
|
+
var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
|
|
32368
|
+
var READ_CHUNK_BYTES = 64 * 1024;
|
|
32369
|
+
function parsePromptAttachments(value) {
|
|
32370
|
+
if (value === undefined || value === null)
|
|
32371
|
+
return [];
|
|
32372
|
+
if (!Array.isArray(value)) {
|
|
32373
|
+
throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
|
|
32374
|
+
}
|
|
32375
|
+
if (value.length > MAX_PROMPT_ATTACHMENTS) {
|
|
32376
|
+
throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
|
|
32377
|
+
}
|
|
32378
|
+
return value.map((candidate) => {
|
|
32379
|
+
if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
|
|
32380
|
+
throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
|
|
32381
|
+
}
|
|
32382
|
+
const record = candidate;
|
|
32383
|
+
if (record.type !== "image" && record.type !== "file") {
|
|
32384
|
+
throw new PromptAttachmentError("attachment_invalid", "An attachment must be an image or a file");
|
|
32385
|
+
}
|
|
32386
|
+
const path = typeof record.path === "string" ? record.path.trim() : "";
|
|
32387
|
+
if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
|
|
32388
|
+
throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
|
|
32389
|
+
}
|
|
32390
|
+
if (path.includes("\x00")) {
|
|
32391
|
+
throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
|
|
32392
|
+
}
|
|
32393
|
+
const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
|
|
32394
|
+
return { type: record.type, path, ...filename ? { filename } : {} };
|
|
32395
|
+
});
|
|
32396
|
+
}
|
|
32397
|
+
async function readPromptImages(attachments, workspaceRoot, modelResize) {
|
|
32398
|
+
const images = [];
|
|
32399
|
+
let totalBytes = 0;
|
|
32400
|
+
for (const attachment of attachments) {
|
|
32401
|
+
if (attachment.type !== "image")
|
|
32402
|
+
continue;
|
|
32403
|
+
const { bytes, absolutePath, mimeType } = await readWorkspaceImage(attachment.path, workspaceRoot);
|
|
32404
|
+
totalBytes += bytes.length;
|
|
32405
|
+
if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
|
|
32406
|
+
throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
|
|
32407
|
+
}
|
|
32408
|
+
const normalized = await normalizeImageForPi(bytes, mimeType, modelResize);
|
|
32409
|
+
images.push({
|
|
32410
|
+
data: normalized.data,
|
|
32411
|
+
mimeType: normalized.mimeType,
|
|
32412
|
+
path: attachment.path,
|
|
32413
|
+
absolutePath,
|
|
32414
|
+
...attachment.filename ? { filename: attachment.filename } : {}
|
|
32415
|
+
});
|
|
32416
|
+
}
|
|
32417
|
+
return images;
|
|
32418
|
+
}
|
|
32419
|
+
async function normalizeImageForPi(bytes, mimeType, modelResize) {
|
|
32420
|
+
const resized = await resizeImage(bytes, mimeType, {
|
|
32421
|
+
...modelResize,
|
|
32422
|
+
maxBytes: Math.min(modelResize?.maxBytes ?? Infinity, MAX_IMAGE_ATTACHMENT_BYTES)
|
|
32423
|
+
}).catch(() => null);
|
|
32424
|
+
let normalized = resized ?? { data: bytes.toString("base64"), mimeType };
|
|
32425
|
+
if (normalized.mimeType === "image/gif" || normalized.mimeType === "image/webp") {
|
|
32426
|
+
normalized = await convertToPng(normalized.data, normalized.mimeType).catch(() => null) ?? normalized;
|
|
32427
|
+
}
|
|
32428
|
+
return { data: normalized.data, mimeType: normalized.mimeType };
|
|
32429
|
+
}
|
|
32430
|
+
function attachmentErrorForFsFailure(error) {
|
|
32431
|
+
const code = error?.code;
|
|
32432
|
+
if (code === "ELOOP") {
|
|
32433
|
+
return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
32434
|
+
}
|
|
32435
|
+
return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
|
|
32436
|
+
}
|
|
32437
|
+
var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
|
|
32438
|
+
function configuredAttachmentRoot(env = process.env) {
|
|
32439
|
+
const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
|
|
32440
|
+
return value && isAbsolute2(value) ? resolve3(value) : undefined;
|
|
32441
|
+
}
|
|
32442
|
+
function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
|
|
32443
|
+
if (extraRoot && isAbsolute2(filePath) && isPathWithin(extraRoot, resolve3(filePath))) {
|
|
32444
|
+
return extraRoot;
|
|
32445
|
+
}
|
|
32446
|
+
return resolve3(workspaceRoot);
|
|
32447
|
+
}
|
|
32448
|
+
function isPathWithin(root, candidate) {
|
|
32449
|
+
if (candidate === root)
|
|
32450
|
+
return true;
|
|
32451
|
+
const childPath = relative(root, candidate);
|
|
32452
|
+
return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute2(childPath);
|
|
32453
|
+
}
|
|
32454
|
+
async function assertNoSymlinkComponents(root, targetPath) {
|
|
32455
|
+
let currentPath = root;
|
|
32456
|
+
for (const segment of relative(root, targetPath).split(sep2).filter(Boolean)) {
|
|
32457
|
+
currentPath = join5(currentPath, segment);
|
|
32458
|
+
const stats = await lstat(currentPath).catch((error) => {
|
|
32459
|
+
throw attachmentErrorForFsFailure(error);
|
|
32460
|
+
});
|
|
32461
|
+
if (stats.isSymbolicLink()) {
|
|
32462
|
+
throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
32463
|
+
}
|
|
32464
|
+
}
|
|
32465
|
+
}
|
|
32466
|
+
async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
|
|
32467
|
+
const [pathStats, canonicalTarget] = await Promise.all([
|
|
32468
|
+
lstat(targetPath),
|
|
32469
|
+
realpath(targetPath)
|
|
32470
|
+
]).catch((error) => {
|
|
32471
|
+
throw attachmentErrorForFsFailure(error);
|
|
32472
|
+
});
|
|
32473
|
+
if (pathStats.isSymbolicLink()) {
|
|
32474
|
+
throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
32475
|
+
}
|
|
32476
|
+
if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
|
|
32477
|
+
throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
|
|
32478
|
+
}
|
|
32479
|
+
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
32480
|
+
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
32481
|
+
}
|
|
32482
|
+
}
|
|
32483
|
+
function assertStableRead(initial, final, bytesRead) {
|
|
32484
|
+
if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
|
|
32485
|
+
throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
|
|
32486
|
+
}
|
|
32487
|
+
}
|
|
32488
|
+
async function readWorkspaceImage(filePath, workspaceRoot) {
|
|
32489
|
+
const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
|
|
32490
|
+
const targetPath = isAbsolute2(filePath) ? resolve3(filePath) : resolve3(lexicalRoot, filePath);
|
|
32491
|
+
if (!isPathWithin(lexicalRoot, targetPath)) {
|
|
32492
|
+
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
32493
|
+
}
|
|
32494
|
+
const canonicalRoot = await realpath(lexicalRoot).catch((error) => {
|
|
32495
|
+
throw attachmentErrorForFsFailure(error);
|
|
32496
|
+
});
|
|
32497
|
+
await assertNoSymlinkComponents(lexicalRoot, targetPath);
|
|
32498
|
+
const canonicalTarget = await realpath(targetPath).catch((error) => {
|
|
32499
|
+
throw attachmentErrorForFsFailure(error);
|
|
32500
|
+
});
|
|
32501
|
+
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
32502
|
+
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
32503
|
+
}
|
|
32504
|
+
const noFollow = constants2.O_NOFOLLOW ?? 0;
|
|
32505
|
+
const handle = await open2(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
|
|
32506
|
+
throw attachmentErrorForFsFailure(error);
|
|
32507
|
+
});
|
|
32508
|
+
try {
|
|
32509
|
+
const initialStats = await handle.stat();
|
|
32510
|
+
await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
|
|
32511
|
+
if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
32512
|
+
throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
|
|
32513
|
+
}
|
|
32514
|
+
const mimeType = await detectSupportedImageMimeTypeFromFile(targetPath).catch(() => null);
|
|
32515
|
+
if (!mimeType) {
|
|
32516
|
+
throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
|
|
32517
|
+
}
|
|
32518
|
+
const chunks = [];
|
|
32519
|
+
let totalBytes = 0;
|
|
32520
|
+
while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
32521
|
+
const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
|
|
32522
|
+
const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
|
32523
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
32524
|
+
if (bytesRead === 0)
|
|
32525
|
+
break;
|
|
32526
|
+
chunks.push(chunk.subarray(0, bytesRead));
|
|
32527
|
+
totalBytes += bytesRead;
|
|
32528
|
+
}
|
|
32529
|
+
if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
32530
|
+
throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
|
|
32531
|
+
}
|
|
32532
|
+
if (totalBytes === 0) {
|
|
32533
|
+
throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
|
|
32534
|
+
}
|
|
32535
|
+
const finalStats = await handle.stat();
|
|
32536
|
+
await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
|
|
32537
|
+
assertStableRead(initialStats, finalStats, totalBytes);
|
|
32538
|
+
return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath, mimeType };
|
|
32539
|
+
} catch (error) {
|
|
32540
|
+
if (error instanceof PromptAttachmentError)
|
|
32541
|
+
throw error;
|
|
32542
|
+
throw attachmentErrorForFsFailure(error);
|
|
32543
|
+
} finally {
|
|
32544
|
+
await handle.close();
|
|
32545
|
+
}
|
|
32546
|
+
}
|
|
32547
|
+
async function resolvePromptFiles(attachments, workspaceRoot) {
|
|
32548
|
+
const files = [];
|
|
32549
|
+
for (const attachment of attachments) {
|
|
32550
|
+
if (attachment.type !== "file")
|
|
32551
|
+
continue;
|
|
32552
|
+
const absolutePath = await resolveWorkspaceFile(attachment.path, workspaceRoot);
|
|
32553
|
+
files.push({
|
|
32554
|
+
path: attachment.path,
|
|
32555
|
+
absolutePath,
|
|
32556
|
+
...attachment.filename ? { filename: attachment.filename } : {}
|
|
32557
|
+
});
|
|
32558
|
+
}
|
|
32559
|
+
return files;
|
|
32560
|
+
}
|
|
32561
|
+
async function resolveWorkspaceFile(filePath, workspaceRoot) {
|
|
32562
|
+
const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
|
|
32563
|
+
const targetPath = isAbsolute2(filePath) ? resolve3(filePath) : resolve3(lexicalRoot, filePath);
|
|
32564
|
+
if (!isPathWithin(lexicalRoot, targetPath)) {
|
|
32565
|
+
throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
|
|
32566
|
+
}
|
|
32567
|
+
const canonicalRoot = await realpath(lexicalRoot).catch((error) => {
|
|
32568
|
+
throw attachmentErrorForFsFailure(error);
|
|
32569
|
+
});
|
|
32570
|
+
await assertNoSymlinkComponents(lexicalRoot, targetPath);
|
|
32571
|
+
const canonicalTarget = await realpath(targetPath).catch((error) => {
|
|
32572
|
+
throw attachmentErrorForFsFailure(error);
|
|
32573
|
+
});
|
|
32574
|
+
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
32575
|
+
throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
|
|
32576
|
+
}
|
|
32577
|
+
const stats = await lstat(targetPath).catch((error) => {
|
|
32578
|
+
throw attachmentErrorForFsFailure(error);
|
|
32579
|
+
});
|
|
32580
|
+
if (!stats.isFile()) {
|
|
32581
|
+
throw new PromptAttachmentError("attachment_not_regular_file", "A file attachment must name a regular workspace file");
|
|
32582
|
+
}
|
|
32583
|
+
return targetPath;
|
|
32584
|
+
}
|
|
32585
|
+
function promptFileReferences(files) {
|
|
32586
|
+
if (files.length === 0)
|
|
32587
|
+
return "";
|
|
32588
|
+
const lines = files.map((file) => file.filename && file.filename !== file.path ? `- ${file.absolutePath} (${file.filename})` : `- ${file.absolutePath}`);
|
|
32589
|
+
return `
|
|
32590
|
+
|
|
32591
|
+
Attached files:
|
|
32592
|
+
${lines.join(`
|
|
32593
|
+
`)}`;
|
|
32594
|
+
}
|
|
32595
|
+
|
|
32596
|
+
// ../../bridges/pi-bridge/src/read-boundary.ts
|
|
32597
|
+
var PI_READ_BOUNDARY_REFUSAL = "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own attachments stay readable.";
|
|
32598
|
+
function piCoordinatorReadBoundary(cwd, env = process.env) {
|
|
32599
|
+
return protectedDataDirBoundary(env[COORDINATOR_PROTECTED_DATA_DIR_ENV], [
|
|
32600
|
+
cwd,
|
|
32601
|
+
canonicalPath(cwd),
|
|
32602
|
+
configuredAttachmentRoot(env)
|
|
32603
|
+
]);
|
|
32604
|
+
}
|
|
32605
|
+
var UNICODE_SPACES = /[ - ]/g;
|
|
32606
|
+
function piPath(value) {
|
|
32607
|
+
let path = value.replace(UNICODE_SPACES, " ");
|
|
32608
|
+
if (path.startsWith("@"))
|
|
32609
|
+
path = path.slice(1);
|
|
32610
|
+
if (path.startsWith("file://")) {
|
|
32611
|
+
try {
|
|
32612
|
+
path = fileURLToPath(path);
|
|
32613
|
+
} catch {
|
|
32614
|
+
return;
|
|
32615
|
+
}
|
|
32616
|
+
}
|
|
32617
|
+
return path;
|
|
32618
|
+
}
|
|
32619
|
+
var SEARCHES = new Set(["grep", "find"]);
|
|
32620
|
+
var READERS = new Set(["read", "ls", ...SEARCHES]);
|
|
32621
|
+
function piReadToolRefused(boundary, toolName, input, cwd) {
|
|
32622
|
+
if (!READERS.has(toolName))
|
|
32623
|
+
return false;
|
|
32624
|
+
const raw = input && typeof input === "object" ? input.path : undefined;
|
|
32625
|
+
const named = typeof raw === "string" && raw.trim() ? raw : toolName === "read" ? undefined : ".";
|
|
32626
|
+
if (named === undefined)
|
|
32627
|
+
return false;
|
|
32628
|
+
const path = piPath(named);
|
|
32629
|
+
if (path === undefined)
|
|
32630
|
+
return true;
|
|
32631
|
+
if (readBoundaryRefuses(boundary, path, cwd, { traversal: SEARCHES.has(toolName) })) {
|
|
32632
|
+
return true;
|
|
32633
|
+
}
|
|
32634
|
+
if (toolName !== "read")
|
|
32635
|
+
return false;
|
|
32636
|
+
const expanded = path === "~" ? homedir3() : path.startsWith("~/") ? resolve4(homedir3(), path.slice(2)) : path;
|
|
32637
|
+
const resolved = resolve4(cwd, expanded);
|
|
32638
|
+
const nfd = resolved.normalize("NFD");
|
|
32639
|
+
return [
|
|
32640
|
+
resolved,
|
|
32641
|
+
resolved.replace(/ (AM|PM)\./gi, " $1."),
|
|
32642
|
+
nfd,
|
|
32643
|
+
resolved.replace(/'/g, "’"),
|
|
32644
|
+
nfd.replace(/'/g, "’")
|
|
32645
|
+
].some((candidate) => readBoundaryRefuses(boundary, candidate, cwd));
|
|
32646
|
+
}
|
|
32647
|
+
|
|
32034
32648
|
// ../../bridges/pi-bridge/src/interactions.ts
|
|
32035
32649
|
var READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
|
|
32036
32650
|
async function requestToolApproval(state, toolCallId, toolName, input) {
|
|
@@ -32043,6 +32657,12 @@ async function requestToolApproval(state, toolCallId, toolName, input) {
|
|
|
32043
32657
|
reason: "This review session is read-only. Read the supplied package; commands, edits, and extension tools are disabled."
|
|
32044
32658
|
};
|
|
32045
32659
|
}
|
|
32660
|
+
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
32661
|
+
const boundary = piCoordinatorReadBoundary(workingDirectory);
|
|
32662
|
+
if (boundary && piReadToolRefused(boundary, toolName, input, workingDirectory)) {
|
|
32663
|
+
return { block: true, reason: PI_READ_BOUNDARY_REFUSAL };
|
|
32664
|
+
}
|
|
32665
|
+
}
|
|
32046
32666
|
if (turnCancellationRequested(state)) {
|
|
32047
32667
|
return { block: true, reason: "The turn was cancelled before this tool call was approved." };
|
|
32048
32668
|
}
|
|
@@ -32061,7 +32681,7 @@ async function requestToolApproval(state, toolCallId, toolName, input) {
|
|
|
32061
32681
|
if (state.approvals.size >= MAX_PENDING_APPROVALS) {
|
|
32062
32682
|
return { block: true, reason: "Too many tool calls are already awaiting approval." };
|
|
32063
32683
|
}
|
|
32064
|
-
const id =
|
|
32684
|
+
const id = randomBytes7(12).toString("hex");
|
|
32065
32685
|
return new Promise((resolve) => {
|
|
32066
32686
|
let settled = false;
|
|
32067
32687
|
const settle = (decision, reason) => {
|
|
@@ -32174,7 +32794,7 @@ function readString2(value) {
|
|
|
32174
32794
|
return nonBlank(value) ? value.trim() : "";
|
|
32175
32795
|
}
|
|
32176
32796
|
// ../../bridges/pi-bridge/src/agent-session.ts
|
|
32177
|
-
import { randomBytes as
|
|
32797
|
+
import { randomBytes as randomBytes8 } from "node:crypto";
|
|
32178
32798
|
import { existsSync as existsSync2, statSync } from "node:fs";
|
|
32179
32799
|
|
|
32180
32800
|
// ../protocol/src/rich-content-policy.ts
|
|
@@ -32450,12 +33070,12 @@ function assertExecutionPolicyNotWidened(current, next) {
|
|
|
32450
33070
|
}
|
|
32451
33071
|
|
|
32452
33072
|
// ../../bridges/pi-bridge/src/agent-session.ts
|
|
32453
|
-
import { realpath, stat as stat3 } from "node:fs/promises";
|
|
32454
|
-
import { join as
|
|
33073
|
+
import { realpath as realpath2, stat as stat3 } from "node:fs/promises";
|
|
33074
|
+
import { join as join9, resolve as resolve6, sep as sep3 } from "node:path";
|
|
32455
33075
|
|
|
32456
33076
|
// ../protocol/src/node/command-change-journal.ts
|
|
32457
33077
|
import { appendFile, mkdir as mkdir2, readFile as readFile3, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
|
|
32458
|
-
import { dirname as
|
|
33078
|
+
import { dirname as dirname3 } from "node:path";
|
|
32459
33079
|
var MAX_JOURNAL_ENTRIES = 1000;
|
|
32460
33080
|
var MAX_JOURNAL_FILES_PER_ENTRY = 20;
|
|
32461
33081
|
var MAX_JOURNAL_PATH_LENGTH = 1024;
|
|
@@ -32528,7 +33148,7 @@ class CommandChangeJournal {
|
|
|
32528
33148
|
const line = `${JSON.stringify({ id, change: bounded })}
|
|
32529
33149
|
`;
|
|
32530
33150
|
this.writes = this.writes.then(async () => {
|
|
32531
|
-
await mkdir2(
|
|
33151
|
+
await mkdir2(dirname3(this.path), { recursive: true, mode: 448 });
|
|
32532
33152
|
if (!this.sizeChecked) {
|
|
32533
33153
|
this.sizeChecked = true;
|
|
32534
33154
|
const existing = await stat(this.path).catch(() => {
|
|
@@ -32622,10 +33242,10 @@ function isFileEditToolName(toolName) {
|
|
|
32622
33242
|
|
|
32623
33243
|
// ../protocol/src/node/workspace-change-probe.ts
|
|
32624
33244
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
32625
|
-
import { rmSync } from "node:fs";
|
|
32626
|
-
import { copyFile, lstat, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
|
|
33245
|
+
import { rmSync as rmSync2 } from "node:fs";
|
|
33246
|
+
import { copyFile, lstat as lstat2, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
|
|
32627
33247
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
32628
|
-
import { delimiter, isAbsolute, join as
|
|
33248
|
+
import { delimiter, isAbsolute as isAbsolute3, join as join6, resolve as resolve5 } from "node:path";
|
|
32629
33249
|
|
|
32630
33250
|
// ../protocol/src/node/command-capture.ts
|
|
32631
33251
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -32835,6 +33455,7 @@ function classifyCommandFailure(error, options = {}) {
|
|
|
32835
33455
|
import { createRequire as createRequire3 } from "node:module";
|
|
32836
33456
|
|
|
32837
33457
|
// ../protocol/src/node/shell-process-state.ts
|
|
33458
|
+
import { spawnSync } from "node:child_process";
|
|
32838
33459
|
import { readdirSync, readFileSync } from "node:fs";
|
|
32839
33460
|
import { constants as osConstants } from "node:os";
|
|
32840
33461
|
var PROCESS_INSPECTION_OPTIONS = {
|
|
@@ -32904,8 +33525,11 @@ function linuxGroupHasLiveMember(pgid) {
|
|
|
32904
33525
|
return false;
|
|
32905
33526
|
}
|
|
32906
33527
|
function psGroupHasLiveMember(pgid) {
|
|
32907
|
-
const
|
|
32908
|
-
|
|
33528
|
+
const argv = ["-A", "-o", "pgid=,stat="];
|
|
33529
|
+
const bun = bunRuntime();
|
|
33530
|
+
const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
|
|
33531
|
+
const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
|
|
33532
|
+
if (!succeeded)
|
|
32909
33533
|
return true;
|
|
32910
33534
|
return result.stdout.toString().split(`
|
|
32911
33535
|
`).some((line) => {
|
|
@@ -33267,6 +33891,7 @@ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, std
|
|
|
33267
33891
|
let limitTimer;
|
|
33268
33892
|
let stopExitWatch = () => {};
|
|
33269
33893
|
let commandExit;
|
|
33894
|
+
let pendingFailure;
|
|
33270
33895
|
const finishCapture = () => {
|
|
33271
33896
|
settled = true;
|
|
33272
33897
|
clearTimeout(timeoutTimer);
|
|
@@ -33288,13 +33913,33 @@ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, std
|
|
|
33288
33913
|
releaseCaptureFds();
|
|
33289
33914
|
}
|
|
33290
33915
|
};
|
|
33291
|
-
const
|
|
33292
|
-
if (settled)
|
|
33293
|
-
return;
|
|
33916
|
+
const rejectFailure = (error) => {
|
|
33294
33917
|
const output = finishCapture();
|
|
33295
33918
|
if (output)
|
|
33296
33919
|
reject(Object.assign(error, { ...output, killed: timedOut }));
|
|
33297
33920
|
};
|
|
33921
|
+
const awaitTermination = (delayMs) => {
|
|
33922
|
+
clearTimeout(groupTimer);
|
|
33923
|
+
if (settled)
|
|
33924
|
+
return;
|
|
33925
|
+
if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
|
|
33926
|
+
rejectFailure(pendingFailure);
|
|
33927
|
+
return;
|
|
33928
|
+
}
|
|
33929
|
+
groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
|
|
33930
|
+
};
|
|
33931
|
+
const fail = (error) => {
|
|
33932
|
+
if (settled || pendingFailure)
|
|
33933
|
+
return;
|
|
33934
|
+
if (options.waitForTermination && child.pid !== undefined) {
|
|
33935
|
+
pendingFailure = error;
|
|
33936
|
+
signalCommand(child, "SIGKILL");
|
|
33937
|
+
clearTimeout(timeoutTimer);
|
|
33938
|
+
clearInterval(limitTimer);
|
|
33939
|
+
awaitTermination(COMMAND_GROUP_POLL_MS);
|
|
33940
|
+
} else
|
|
33941
|
+
rejectFailure(error);
|
|
33942
|
+
};
|
|
33298
33943
|
const abort = () => {
|
|
33299
33944
|
timedOut = true;
|
|
33300
33945
|
signalCommand(child, "SIGKILL");
|
|
@@ -33321,11 +33966,11 @@ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, std
|
|
|
33321
33966
|
}
|
|
33322
33967
|
};
|
|
33323
33968
|
limitTimer = setInterval(() => {
|
|
33324
|
-
if (!settled && !timedOut)
|
|
33969
|
+
if (!settled && !timedOut && !pendingFailure)
|
|
33325
33970
|
failIfOverLimit();
|
|
33326
33971
|
}, COMMAND_OUTPUT_CHECK_MS);
|
|
33327
33972
|
const settleOnExit = () => {
|
|
33328
|
-
if (settled || timedOut || failIfOverLimit())
|
|
33973
|
+
if (settled || timedOut || pendingFailure || failIfOverLimit())
|
|
33329
33974
|
return;
|
|
33330
33975
|
if (commandExit?.code !== 0 || commandExit.signal !== null) {
|
|
33331
33976
|
fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
|
|
@@ -33339,7 +33984,7 @@ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, std
|
|
|
33339
33984
|
resolve(output);
|
|
33340
33985
|
};
|
|
33341
33986
|
const awaitGroupExit = (delayMs) => {
|
|
33342
|
-
if (settled || timedOut)
|
|
33987
|
+
if (settled || timedOut || pendingFailure)
|
|
33343
33988
|
return;
|
|
33344
33989
|
if (commandGroupAlive(child)) {
|
|
33345
33990
|
groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
|
|
@@ -33352,14 +33997,16 @@ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, std
|
|
|
33352
33997
|
return;
|
|
33353
33998
|
commandExit = exit;
|
|
33354
33999
|
stopExitWatch();
|
|
33355
|
-
if (
|
|
34000
|
+
if (pendingFailure)
|
|
34001
|
+
awaitTermination(COMMAND_GROUP_POLL_MS);
|
|
34002
|
+
else if (options.waitForDescendants)
|
|
33356
34003
|
awaitGroupExit(COMMAND_GROUP_POLL_MS);
|
|
33357
34004
|
else
|
|
33358
34005
|
settleOnExit();
|
|
33359
34006
|
};
|
|
33360
34007
|
child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
|
|
33361
34008
|
stopExitWatch = watchForLostExit(child.pid, (exit) => {
|
|
33362
|
-
if (!settled
|
|
34009
|
+
if (!settled)
|
|
33363
34010
|
onCommandExit(exit);
|
|
33364
34011
|
});
|
|
33365
34012
|
if (timeoutMs > 0) {
|
|
@@ -33451,7 +34098,7 @@ var temporaryObjectDirectories = new Set;
|
|
|
33451
34098
|
process.once("exit", () => {
|
|
33452
34099
|
for (const directory of temporaryObjectDirectories) {
|
|
33453
34100
|
try {
|
|
33454
|
-
|
|
34101
|
+
rmSync2(directory, { recursive: true, force: true });
|
|
33455
34102
|
} catch {}
|
|
33456
34103
|
}
|
|
33457
34104
|
});
|
|
@@ -33708,8 +34355,8 @@ class WorkspaceChangeProbe {
|
|
|
33708
34355
|
return;
|
|
33709
34356
|
return {
|
|
33710
34357
|
root,
|
|
33711
|
-
indexPath:
|
|
33712
|
-
objectsPath:
|
|
34358
|
+
indexPath: isAbsolute3(index) ? index : resolve5(cwd, index),
|
|
34359
|
+
objectsPath: isAbsolute3(objects) ? objects : resolve5(cwd, objects)
|
|
33713
34360
|
};
|
|
33714
34361
|
}).catch(() => {
|
|
33715
34362
|
return;
|
|
@@ -33752,8 +34399,8 @@ class WorkspaceChangeProbe {
|
|
|
33752
34399
|
return;
|
|
33753
34400
|
const { root, indexPath } = repo.location;
|
|
33754
34401
|
const started = this.now();
|
|
33755
|
-
const tempIndex =
|
|
33756
|
-
const objectDirectory = await mkdtemp2(
|
|
34402
|
+
const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
|
|
34403
|
+
const objectDirectory = await mkdtemp2(join6(this.tempDir, "orkestrator-probe-objects-"));
|
|
33757
34404
|
temporaryObjectDirectories.add(objectDirectory);
|
|
33758
34405
|
let retained = false;
|
|
33759
34406
|
try {
|
|
@@ -33770,7 +34417,7 @@ class WorkspaceChangeProbe {
|
|
|
33770
34417
|
const included = [];
|
|
33771
34418
|
const skipped = new Map;
|
|
33772
34419
|
for (const path of untracked) {
|
|
33773
|
-
const stats = await
|
|
34420
|
+
const stats = await lstat2(join6(root, path)).catch(() => {
|
|
33774
34421
|
return;
|
|
33775
34422
|
});
|
|
33776
34423
|
if (!stats)
|
|
@@ -33917,7 +34564,7 @@ function parseNumstatZ(output) {
|
|
|
33917
34564
|
|
|
33918
34565
|
// ../../bridges/pi-bridge/src/change-evidence.ts
|
|
33919
34566
|
import { existsSync } from "node:fs";
|
|
33920
|
-
import { isAbsolute as
|
|
34567
|
+
import { isAbsolute as isAbsolute4, relative as relative2 } from "node:path";
|
|
33921
34568
|
|
|
33922
34569
|
// ../protocol/src/field-validation.ts
|
|
33923
34570
|
function isPlainRecord(value) {
|
|
@@ -34320,10 +34967,10 @@ function workspaceObservationReportIssues(value) {
|
|
|
34320
34967
|
}
|
|
34321
34968
|
|
|
34322
34969
|
// ../protocol/src/node/change-tracking/evidence-spool.ts
|
|
34323
|
-
import { createHash as
|
|
34970
|
+
import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
|
|
34324
34971
|
import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
|
|
34325
34972
|
import { appendFile as appendFile2, mkdir as mkdir3, rename as rename3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
|
|
34326
|
-
import { join as
|
|
34973
|
+
import { join as join7 } from "node:path";
|
|
34327
34974
|
var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
|
|
34328
34975
|
maxEntries: 2048,
|
|
34329
34976
|
maxEntryBytes: 256 * 1024,
|
|
@@ -34336,10 +34983,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
|
|
|
34336
34983
|
var ENTRIES_FILE = "entries.jsonl";
|
|
34337
34984
|
var BODY_DIRECTORY = "bodies";
|
|
34338
34985
|
function evidenceBodyId(bytes) {
|
|
34339
|
-
return `sha256:${
|
|
34986
|
+
return `sha256:${createHash5("sha256").update(bytes).digest("hex")}`;
|
|
34340
34987
|
}
|
|
34341
34988
|
function stableEvidenceId(...parts) {
|
|
34342
|
-
const hash =
|
|
34989
|
+
const hash = createHash5("sha256");
|
|
34343
34990
|
for (const part of parts)
|
|
34344
34991
|
hash.update(`${part ?? ""}\x00`);
|
|
34345
34992
|
return hash.digest("hex").slice(0, 40);
|
|
@@ -34586,7 +35233,7 @@ class ChangeEvidenceSpool {
|
|
|
34586
35233
|
const lines = this.pendingLines.splice(0).join("");
|
|
34587
35234
|
this.enqueueIo(async () => {
|
|
34588
35235
|
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
34589
|
-
await appendFile2(
|
|
35236
|
+
await appendFile2(join7(directory, ENTRIES_FILE), lines, { mode: 384 });
|
|
34590
35237
|
});
|
|
34591
35238
|
}
|
|
34592
35239
|
persistBody(id, bytes) {
|
|
@@ -34594,9 +35241,9 @@ class ChangeEvidenceSpool {
|
|
|
34594
35241
|
if (!directory || this.restoring)
|
|
34595
35242
|
return;
|
|
34596
35243
|
this.enqueueIo(async () => {
|
|
34597
|
-
const bodies =
|
|
35244
|
+
const bodies = join7(directory, BODY_DIRECTORY);
|
|
34598
35245
|
await mkdir3(bodies, { recursive: true, mode: 448 });
|
|
34599
|
-
await writeFile3(
|
|
35246
|
+
await writeFile3(join7(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
|
|
34600
35247
|
if (error.code !== "EEXIST")
|
|
34601
35248
|
throw error;
|
|
34602
35249
|
});
|
|
@@ -34606,7 +35253,7 @@ class ChangeEvidenceSpool {
|
|
|
34606
35253
|
const directory = this.directory;
|
|
34607
35254
|
if (!directory)
|
|
34608
35255
|
return;
|
|
34609
|
-
this.enqueueIo(() => rm3(
|
|
35256
|
+
this.enqueueIo(() => rm3(join7(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
|
|
34610
35257
|
}
|
|
34611
35258
|
compactPersisted() {
|
|
34612
35259
|
const directory = this.directory;
|
|
@@ -34617,7 +35264,7 @@ class ChangeEvidenceSpool {
|
|
|
34617
35264
|
`);
|
|
34618
35265
|
this.enqueueIo(async () => {
|
|
34619
35266
|
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
34620
|
-
const file =
|
|
35267
|
+
const file = join7(directory, ENTRIES_FILE);
|
|
34621
35268
|
const temp = `${file}.${process.pid}.tmp`;
|
|
34622
35269
|
await writeFile3(temp, body ? `${body}
|
|
34623
35270
|
` : "", { mode: 384 });
|
|
@@ -34629,10 +35276,10 @@ class ChangeEvidenceSpool {
|
|
|
34629
35276
|
await this.io;
|
|
34630
35277
|
}
|
|
34631
35278
|
restore(directory) {
|
|
34632
|
-
const bodyDirectory =
|
|
35279
|
+
const bodyDirectory = join7(directory, BODY_DIRECTORY);
|
|
34633
35280
|
try {
|
|
34634
35281
|
for (const name of readdirSync2(bodyDirectory)) {
|
|
34635
|
-
const bytes = new Uint8Array(readFileSync2(
|
|
35282
|
+
const bytes = new Uint8Array(readFileSync2(join7(bodyDirectory, name)));
|
|
34636
35283
|
const id = evidenceBodyId(bytes);
|
|
34637
35284
|
if (bodyFileName(id) !== name)
|
|
34638
35285
|
continue;
|
|
@@ -34644,7 +35291,7 @@ class ChangeEvidenceSpool {
|
|
|
34644
35291
|
} catch {}
|
|
34645
35292
|
let text = "";
|
|
34646
35293
|
try {
|
|
34647
|
-
text = readFileSync2(
|
|
35294
|
+
text = readFileSync2(join7(directory, ENTRIES_FILE), "utf8");
|
|
34648
35295
|
} catch {
|
|
34649
35296
|
return;
|
|
34650
35297
|
}
|
|
@@ -35062,10 +35709,10 @@ function stringField(value, key) {
|
|
|
35062
35709
|
function evidencePath(path) {
|
|
35063
35710
|
if (!path)
|
|
35064
35711
|
return;
|
|
35065
|
-
if (!
|
|
35712
|
+
if (!isAbsolute4(path))
|
|
35066
35713
|
return path;
|
|
35067
|
-
const inside =
|
|
35068
|
-
return inside && !inside.startsWith("..") && !
|
|
35714
|
+
const inside = relative2(workingDirectory, path);
|
|
35715
|
+
return inside && !inside.startsWith("..") && !isAbsolute4(inside) ? inside : path;
|
|
35069
35716
|
}
|
|
35070
35717
|
function writeReplacement(input, claim) {
|
|
35071
35718
|
const path = evidencePath(stringField(input, "path"));
|
|
@@ -35333,9 +35980,9 @@ async function overlayCommandChanges(state, options = {}) {
|
|
|
35333
35980
|
}
|
|
35334
35981
|
|
|
35335
35982
|
// ../../bridges/pi-bridge/src/session-list-cache.ts
|
|
35336
|
-
import { createHash as
|
|
35983
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
35337
35984
|
import { readdir, stat as stat2 } from "node:fs/promises";
|
|
35338
|
-
import { join as
|
|
35985
|
+
import { join as join8 } from "node:path";
|
|
35339
35986
|
var SESSION_LIST_CACHE_TTL_MS = 30000;
|
|
35340
35987
|
var MAX_CACHED_SESSION_LIST_BYTES = 2 * 1024 * 1024;
|
|
35341
35988
|
var cached2;
|
|
@@ -35346,10 +35993,10 @@ async function sessionFilesStamp(directory) {
|
|
|
35346
35993
|
} catch {
|
|
35347
35994
|
return;
|
|
35348
35995
|
}
|
|
35349
|
-
const stats = await Promise.all(names.map((name) => stat2(
|
|
35996
|
+
const stats = await Promise.all(names.map((name) => stat2(join8(directory, name)).catch(() => {
|
|
35350
35997
|
return;
|
|
35351
35998
|
})));
|
|
35352
|
-
const hash =
|
|
35999
|
+
const hash = createHash6("sha256");
|
|
35353
36000
|
for (const [index, name] of names.entries()) {
|
|
35354
36001
|
const file = stats[index];
|
|
35355
36002
|
hash.update(file ? `${name}\x00${file.size}\x00${file.mtimeMs}\x00${file.ctimeMs}\x00${file.ino}
|
|
@@ -35368,6 +36015,71 @@ function rememberSessionList(directory, stamp, entries) {
|
|
|
35368
36015
|
cached2 = stamp !== undefined && encodedJsonBytes(entries) <= MAX_CACHED_SESSION_LIST_BYTES ? { directory, stamp, entries, expiresAt: performance.now() + SESSION_LIST_CACHE_TTL_MS } : undefined;
|
|
35369
36016
|
}
|
|
35370
36017
|
|
|
36018
|
+
// ../../bridges/pi-bridge/src/compaction-controls.ts
|
|
36019
|
+
var AUTO_COMPACTION_PARAMETER_ID = "autoCompaction";
|
|
36020
|
+
var PI_AUTO_COMPACTION_DEFAULT = true;
|
|
36021
|
+
var COMPACTION_CANCELLED_MESSAGE = "Compaction was stopped before it finished; the conversation was not compacted.";
|
|
36022
|
+
function autoCompactionEnabled(state) {
|
|
36023
|
+
return state.autoCompaction ?? state.autoCompactionSetting ?? PI_AUTO_COMPACTION_DEFAULT;
|
|
36024
|
+
}
|
|
36025
|
+
function publicComposer(state) {
|
|
36026
|
+
const composer = state.composer;
|
|
36027
|
+
const parameter = {
|
|
36028
|
+
id: AUTO_COMPACTION_PARAMETER_ID,
|
|
36029
|
+
label: "Auto-compact",
|
|
36030
|
+
kind: "toggle",
|
|
36031
|
+
defaultValue: state.autoCompactionSetting ?? PI_AUTO_COMPACTION_DEFAULT,
|
|
36032
|
+
scope: "session"
|
|
36033
|
+
};
|
|
36034
|
+
return {
|
|
36035
|
+
...composer,
|
|
36036
|
+
models: composer.models.map((model) => ({
|
|
36037
|
+
...model,
|
|
36038
|
+
parameters: [
|
|
36039
|
+
...(model.parameters ?? []).filter((entry) => entry.id !== AUTO_COMPACTION_PARAMETER_ID),
|
|
36040
|
+
parameter
|
|
36041
|
+
]
|
|
36042
|
+
})),
|
|
36043
|
+
parameterValues: {
|
|
36044
|
+
...composer.parameterValues,
|
|
36045
|
+
[AUTO_COMPACTION_PARAMETER_ID]: autoCompactionEnabled(state)
|
|
36046
|
+
}
|
|
36047
|
+
};
|
|
36048
|
+
}
|
|
36049
|
+
function parseAutoCompaction(parameterValues) {
|
|
36050
|
+
if (!parameterValues || typeof parameterValues !== "object" || Array.isArray(parameterValues)) {
|
|
36051
|
+
return;
|
|
36052
|
+
}
|
|
36053
|
+
const value = parameterValues[AUTO_COMPACTION_PARAMETER_ID];
|
|
36054
|
+
return typeof value === "boolean" ? value : undefined;
|
|
36055
|
+
}
|
|
36056
|
+
function installAutoCompactionOverride(settingsManager, choice) {
|
|
36057
|
+
const own = settingsManager.getCompactionEnabled.bind(settingsManager);
|
|
36058
|
+
const setting = own();
|
|
36059
|
+
settingsManager.getCompactionEnabled = () => choice() ?? own();
|
|
36060
|
+
return setting;
|
|
36061
|
+
}
|
|
36062
|
+
function readAutoCompactionSetting(read) {
|
|
36063
|
+
try {
|
|
36064
|
+
return read().getCompactionEnabled();
|
|
36065
|
+
} catch {
|
|
36066
|
+
return;
|
|
36067
|
+
}
|
|
36068
|
+
}
|
|
36069
|
+
function requestCompactionCancellation(state) {
|
|
36070
|
+
const compaction = state.manualCompaction;
|
|
36071
|
+
if (!compaction)
|
|
36072
|
+
return;
|
|
36073
|
+
compaction.cancelRequested = true;
|
|
36074
|
+
state.session?.abortCompaction();
|
|
36075
|
+
return compaction.settled;
|
|
36076
|
+
}
|
|
36077
|
+
function abortCancelledCompactionOnStart(state, event, session) {
|
|
36078
|
+
if (event.type === "compaction_start" && state.manualCompaction?.cancelRequested) {
|
|
36079
|
+
session.abortCompaction();
|
|
36080
|
+
}
|
|
36081
|
+
}
|
|
36082
|
+
|
|
35371
36083
|
// ../../bridges/pi-bridge/src/agent-session.ts
|
|
35372
36084
|
var log4 = createLogger("bridge.pi");
|
|
35373
36085
|
var closingSessions = new WeakSet;
|
|
@@ -35423,6 +36135,15 @@ function defaultModelIds(state, cwd = workingDirectory, agentDir = agentDirector
|
|
|
35423
36135
|
ids.push(fallback);
|
|
35424
36136
|
return ids;
|
|
35425
36137
|
}
|
|
36138
|
+
function refreshAutoCompactionSetting(state) {
|
|
36139
|
+
const setting = readAutoCompactionSetting(() => SettingsManager.create(workingDirectory, agentDirectory() ?? getAgentDir(), {
|
|
36140
|
+
projectTrusted: piResourceLoaderPolicy(state).projectTrusted
|
|
36141
|
+
}));
|
|
36142
|
+
if (setting !== undefined && setting !== state.autoCompactionSetting) {
|
|
36143
|
+
state.autoCompactionSetting = setting;
|
|
36144
|
+
state.revision += 1;
|
|
36145
|
+
}
|
|
36146
|
+
}
|
|
35426
36147
|
function adoptHydratedComposer(state, hydrated) {
|
|
35427
36148
|
const current = state.composer;
|
|
35428
36149
|
const selectedModelId = current.selectedModelId ?? hydrated.selectedModelId;
|
|
@@ -35450,6 +36171,7 @@ async function hydrateSessionComposer(state, options = {}) {
|
|
|
35450
36171
|
const operation = (async () => {
|
|
35451
36172
|
if (settled)
|
|
35452
36173
|
await settled;
|
|
36174
|
+
refreshAutoCompactionSetting(state);
|
|
35453
36175
|
const hydrated = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
|
|
35454
36176
|
if (hydrated.models.length === 0) {
|
|
35455
36177
|
composerHydrationRetryAfter.set(state, Date.now() + CATALOG_TIMEOUT_MS);
|
|
@@ -35518,6 +36240,7 @@ async function createSession(clientSessionKey, patch, policy) {
|
|
|
35518
36240
|
if (resolved.id === "coordinator-read-only")
|
|
35519
36241
|
state.readOnly = true;
|
|
35520
36242
|
applyComposerPatch(state, patch);
|
|
36243
|
+
refreshAutoCompactionSetting(state);
|
|
35521
36244
|
state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
|
|
35522
36245
|
sessions.set(state.id, state);
|
|
35523
36246
|
if (clientSessionKey)
|
|
@@ -35610,7 +36333,10 @@ async function createPiAgentSession(state) {
|
|
|
35610
36333
|
sessionManager,
|
|
35611
36334
|
sessionStartEvent
|
|
35612
36335
|
}) => {
|
|
35613
|
-
const settingsManager = SettingsManager.create(cwd, runtimeAgentDir
|
|
36336
|
+
const settingsManager = SettingsManager.create(cwd, runtimeAgentDir, {
|
|
36337
|
+
projectTrusted: piResourceLoaderPolicy(state, cwd).projectTrusted
|
|
36338
|
+
});
|
|
36339
|
+
state.autoCompactionSetting = installAutoCompactionOverride(settingsManager, () => state.autoCompaction);
|
|
35614
36340
|
const services = await createPiSessionServices(state, {
|
|
35615
36341
|
cwd,
|
|
35616
36342
|
agentDir: runtimeAgentDir,
|
|
@@ -35705,6 +36431,7 @@ function publishAttachedSession(state, session) {
|
|
|
35705
36431
|
state.sessionFile = session.sessionFile;
|
|
35706
36432
|
state.unsubscribe = session.subscribe((event) => {
|
|
35707
36433
|
applySessionEvent(state, event);
|
|
36434
|
+
abortCancelledCompactionOnStart(state, event, session);
|
|
35708
36435
|
if (event.type === "tool_execution_end") {
|
|
35709
36436
|
discardToolCall(state, event.toolCallId, event.result);
|
|
35710
36437
|
}
|
|
@@ -35804,9 +36531,9 @@ function projectResourceDiscoveryOptions(enabled = false, readOnly = false) {
|
|
|
35804
36531
|
}
|
|
35805
36532
|
function coordinatorProjectSkillPaths(cwd = workingDirectory) {
|
|
35806
36533
|
return [
|
|
35807
|
-
|
|
35808
|
-
|
|
35809
|
-
|
|
36534
|
+
join9(cwd, ".pi", "skills"),
|
|
36535
|
+
join9(cwd, ".agents", "skills"),
|
|
36536
|
+
join9(cwd, ".claude", "skills")
|
|
35810
36537
|
].filter((path) => existsSync2(path));
|
|
35811
36538
|
}
|
|
35812
36539
|
function piResourceLoaderPolicy(state, cwd = workingDirectory) {
|
|
@@ -35970,6 +36697,9 @@ function parseComposerPatch(body) {
|
|
|
35970
36697
|
patch.reasoningId ??= body.effort.trim();
|
|
35971
36698
|
if (typeof body.persistDefaults === "boolean")
|
|
35972
36699
|
patch.persistDefaults = body.persistDefaults;
|
|
36700
|
+
const autoCompaction = parseAutoCompaction(body.parameterValues);
|
|
36701
|
+
if (autoCompaction !== undefined)
|
|
36702
|
+
patch.autoCompaction = autoCompaction;
|
|
35973
36703
|
return Object.keys(patch).length > 0 ? patch : undefined;
|
|
35974
36704
|
}
|
|
35975
36705
|
function applyComposerPatch(state, patch) {
|
|
@@ -35989,6 +36719,10 @@ function applyComposerPatch(state, patch) {
|
|
|
35989
36719
|
state.composer = { ...state.composer, selectedReasoningId: patch.reasoningId };
|
|
35990
36720
|
changed = true;
|
|
35991
36721
|
}
|
|
36722
|
+
if (patch.autoCompaction !== undefined && patch.autoCompaction !== state.autoCompaction) {
|
|
36723
|
+
state.autoCompaction = patch.autoCompaction;
|
|
36724
|
+
changed = true;
|
|
36725
|
+
}
|
|
35992
36726
|
if (changed)
|
|
35993
36727
|
state.revision += 1;
|
|
35994
36728
|
return changed;
|
|
@@ -36065,20 +36799,20 @@ async function readResumableSessions(signal) {
|
|
|
36065
36799
|
return entries;
|
|
36066
36800
|
}
|
|
36067
36801
|
function resumableSessionRoot() {
|
|
36068
|
-
return sessionDirectory() ??
|
|
36802
|
+
return sessionDirectory() ?? join9(agentDirectory() ?? getAgentDir(), "sessions");
|
|
36069
36803
|
}
|
|
36070
36804
|
async function assertResumableSessionFile(sessionFile) {
|
|
36071
36805
|
const root = resumableSessionRoot();
|
|
36072
|
-
const requested =
|
|
36806
|
+
const requested = resolve6(root, sessionFile);
|
|
36073
36807
|
let real;
|
|
36074
36808
|
let rootReal;
|
|
36075
36809
|
try {
|
|
36076
|
-
rootReal = await
|
|
36077
|
-
real = await
|
|
36810
|
+
rootReal = await realpath2(root);
|
|
36811
|
+
real = await realpath2(requested);
|
|
36078
36812
|
} catch {
|
|
36079
36813
|
throw new Error("That Pi session file does not exist");
|
|
36080
36814
|
}
|
|
36081
|
-
if (real !== rootReal && !real.startsWith(rootReal.endsWith(
|
|
36815
|
+
if (real !== rootReal && !real.startsWith(rootReal.endsWith(sep3) ? rootReal : rootReal + sep3)) {
|
|
36082
36816
|
throw new Error("That Pi session file is outside this environment's session directory");
|
|
36083
36817
|
}
|
|
36084
36818
|
const info = await stat3(real).catch(() => {
|
|
@@ -36094,7 +36828,7 @@ async function resumeSession(sessionFile, patch, policy) {
|
|
|
36094
36828
|
const ownedFile = existing.sessionFile;
|
|
36095
36829
|
if (!ownedFile)
|
|
36096
36830
|
continue;
|
|
36097
|
-
const sameFile = ownedFile === resolved || ownedFile === sessionFile || await
|
|
36831
|
+
const sameFile = ownedFile === resolved || ownedFile === sessionFile || await realpath2(ownedFile).catch(() => {
|
|
36098
36832
|
return;
|
|
36099
36833
|
}) === resolved;
|
|
36100
36834
|
if (sameFile) {
|
|
@@ -36123,6 +36857,7 @@ async function resumeSession(sessionFile, patch, policy) {
|
|
|
36123
36857
|
state.policyPending = !policy;
|
|
36124
36858
|
state.sessionFile = resolved;
|
|
36125
36859
|
applyComposerPatch(state, patch);
|
|
36860
|
+
refreshAutoCompactionSetting(state);
|
|
36126
36861
|
state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
|
|
36127
36862
|
hydrateHistory(state);
|
|
36128
36863
|
await overlayCommandChanges(state);
|
|
@@ -36250,7 +36985,7 @@ function hydrateHistory(state) {
|
|
|
36250
36985
|
state.revision += 1;
|
|
36251
36986
|
}
|
|
36252
36987
|
function appendHistoricNotice(state, entry, part) {
|
|
36253
|
-
const messageId =
|
|
36988
|
+
const messageId = randomBytes8(12).toString("hex");
|
|
36254
36989
|
pushMessage(state, "assistant", part.content, [{ ...part, sourcePartId: `${messageId}:0`, sourceMessageId: messageId }], entryCreatedAt(entry), messageId);
|
|
36255
36990
|
}
|
|
36256
36991
|
function entryCreatedAt(entry) {
|
|
@@ -36402,7 +37137,7 @@ function readContentText(content) {
|
|
|
36402
37137
|
return chunks.join(`
|
|
36403
37138
|
`);
|
|
36404
37139
|
}
|
|
36405
|
-
function pushMessage(state, role, content, parts, createdAt, messageId =
|
|
37140
|
+
function pushMessage(state, role, content, parts, createdAt, messageId = randomBytes8(12).toString("hex")) {
|
|
36406
37141
|
const message = {
|
|
36407
37142
|
id: messageId,
|
|
36408
37143
|
role,
|
|
@@ -36421,7 +37156,7 @@ function pushMessage(state, role, content, parts, createdAt, messageId = randomB
|
|
|
36421
37156
|
chargeTranscript(state, Buffer.byteLength(JSON.stringify(message)));
|
|
36422
37157
|
}
|
|
36423
37158
|
// ../protocol/src/node/bridge-diagnostics.ts
|
|
36424
|
-
import { createHash as
|
|
37159
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
36425
37160
|
|
|
36426
37161
|
// ../protocol/src/event-loop-stall-monitor.ts
|
|
36427
37162
|
var log5 = createLogger("event-loop");
|
|
@@ -36520,7 +37255,7 @@ function sameSet(a, b) {
|
|
|
36520
37255
|
function identity(value) {
|
|
36521
37256
|
if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
|
|
36522
37257
|
return;
|
|
36523
|
-
return
|
|
37258
|
+
return createHash7("sha256").update(value).digest("hex").slice(0, 16);
|
|
36524
37259
|
}
|
|
36525
37260
|
function readBridgeDebugFlag(value) {
|
|
36526
37261
|
return value?.trim() === "1";
|
|
@@ -37677,250 +38412,6 @@ function errorText(error) {
|
|
|
37677
38412
|
function toImageContent(image) {
|
|
37678
38413
|
return { type: "image", data: image.data, mimeType: image.mimeType };
|
|
37679
38414
|
}
|
|
37680
|
-
// ../../bridges/pi-bridge/src/prompt-attachments.ts
|
|
37681
|
-
import { constants } from "node:fs";
|
|
37682
|
-
import { lstat as lstat2, open as open2, realpath as realpath2 } from "node:fs/promises";
|
|
37683
|
-
import { isAbsolute as isAbsolute3, join as join8, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
|
|
37684
|
-
class PromptAttachmentError extends Error {
|
|
37685
|
-
code;
|
|
37686
|
-
name = "PromptAttachmentError";
|
|
37687
|
-
constructor(code, message) {
|
|
37688
|
-
super(message);
|
|
37689
|
-
this.code = code;
|
|
37690
|
-
}
|
|
37691
|
-
}
|
|
37692
|
-
var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
|
|
37693
|
-
var MAX_PROMPT_ATTACHMENTS = 20;
|
|
37694
|
-
var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
|
|
37695
|
-
var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
|
|
37696
|
-
var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
|
|
37697
|
-
var READ_CHUNK_BYTES = 64 * 1024;
|
|
37698
|
-
function parsePromptAttachments(value) {
|
|
37699
|
-
if (value === undefined || value === null)
|
|
37700
|
-
return [];
|
|
37701
|
-
if (!Array.isArray(value)) {
|
|
37702
|
-
throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
|
|
37703
|
-
}
|
|
37704
|
-
if (value.length > MAX_PROMPT_ATTACHMENTS) {
|
|
37705
|
-
throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
|
|
37706
|
-
}
|
|
37707
|
-
return value.map((candidate) => {
|
|
37708
|
-
if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
|
|
37709
|
-
throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
|
|
37710
|
-
}
|
|
37711
|
-
const record = candidate;
|
|
37712
|
-
if (record.type !== "image" && record.type !== "file") {
|
|
37713
|
-
throw new PromptAttachmentError("attachment_invalid", "An attachment must be an image or a file");
|
|
37714
|
-
}
|
|
37715
|
-
const path = typeof record.path === "string" ? record.path.trim() : "";
|
|
37716
|
-
if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
|
|
37717
|
-
throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
|
|
37718
|
-
}
|
|
37719
|
-
if (path.includes("\x00")) {
|
|
37720
|
-
throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
|
|
37721
|
-
}
|
|
37722
|
-
const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
|
|
37723
|
-
return { type: record.type, path, ...filename ? { filename } : {} };
|
|
37724
|
-
});
|
|
37725
|
-
}
|
|
37726
|
-
async function readPromptImages(attachments, workspaceRoot, modelResize) {
|
|
37727
|
-
const images = [];
|
|
37728
|
-
let totalBytes = 0;
|
|
37729
|
-
for (const attachment of attachments) {
|
|
37730
|
-
if (attachment.type !== "image")
|
|
37731
|
-
continue;
|
|
37732
|
-
const { bytes, absolutePath, mimeType } = await readWorkspaceImage(attachment.path, workspaceRoot);
|
|
37733
|
-
totalBytes += bytes.length;
|
|
37734
|
-
if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
|
|
37735
|
-
throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
|
|
37736
|
-
}
|
|
37737
|
-
const normalized = await normalizeImageForPi(bytes, mimeType, modelResize);
|
|
37738
|
-
images.push({
|
|
37739
|
-
data: normalized.data,
|
|
37740
|
-
mimeType: normalized.mimeType,
|
|
37741
|
-
path: attachment.path,
|
|
37742
|
-
absolutePath,
|
|
37743
|
-
...attachment.filename ? { filename: attachment.filename } : {}
|
|
37744
|
-
});
|
|
37745
|
-
}
|
|
37746
|
-
return images;
|
|
37747
|
-
}
|
|
37748
|
-
async function normalizeImageForPi(bytes, mimeType, modelResize) {
|
|
37749
|
-
const resized = await resizeImage(bytes, mimeType, {
|
|
37750
|
-
...modelResize,
|
|
37751
|
-
maxBytes: Math.min(modelResize?.maxBytes ?? Infinity, MAX_IMAGE_ATTACHMENT_BYTES)
|
|
37752
|
-
}).catch(() => null);
|
|
37753
|
-
let normalized = resized ?? { data: bytes.toString("base64"), mimeType };
|
|
37754
|
-
if (normalized.mimeType === "image/gif" || normalized.mimeType === "image/webp") {
|
|
37755
|
-
normalized = await convertToPng(normalized.data, normalized.mimeType).catch(() => null) ?? normalized;
|
|
37756
|
-
}
|
|
37757
|
-
return { data: normalized.data, mimeType: normalized.mimeType };
|
|
37758
|
-
}
|
|
37759
|
-
function attachmentErrorForFsFailure(error) {
|
|
37760
|
-
const code = error?.code;
|
|
37761
|
-
if (code === "ELOOP") {
|
|
37762
|
-
return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
37763
|
-
}
|
|
37764
|
-
return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
|
|
37765
|
-
}
|
|
37766
|
-
var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
|
|
37767
|
-
function configuredAttachmentRoot(env = process.env) {
|
|
37768
|
-
const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
|
|
37769
|
-
return value && isAbsolute3(value) ? resolve4(value) : undefined;
|
|
37770
|
-
}
|
|
37771
|
-
function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
|
|
37772
|
-
if (extraRoot && isAbsolute3(filePath) && isPathWithin(extraRoot, resolve4(filePath))) {
|
|
37773
|
-
return extraRoot;
|
|
37774
|
-
}
|
|
37775
|
-
return resolve4(workspaceRoot);
|
|
37776
|
-
}
|
|
37777
|
-
function isPathWithin(root, candidate) {
|
|
37778
|
-
if (candidate === root)
|
|
37779
|
-
return true;
|
|
37780
|
-
const childPath = relative2(root, candidate);
|
|
37781
|
-
return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute3(childPath);
|
|
37782
|
-
}
|
|
37783
|
-
async function assertNoSymlinkComponents(root, targetPath) {
|
|
37784
|
-
let currentPath = root;
|
|
37785
|
-
for (const segment of relative2(root, targetPath).split(sep2).filter(Boolean)) {
|
|
37786
|
-
currentPath = join8(currentPath, segment);
|
|
37787
|
-
const stats = await lstat2(currentPath).catch((error) => {
|
|
37788
|
-
throw attachmentErrorForFsFailure(error);
|
|
37789
|
-
});
|
|
37790
|
-
if (stats.isSymbolicLink()) {
|
|
37791
|
-
throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
37792
|
-
}
|
|
37793
|
-
}
|
|
37794
|
-
}
|
|
37795
|
-
async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
|
|
37796
|
-
const [pathStats, canonicalTarget] = await Promise.all([
|
|
37797
|
-
lstat2(targetPath),
|
|
37798
|
-
realpath2(targetPath)
|
|
37799
|
-
]).catch((error) => {
|
|
37800
|
-
throw attachmentErrorForFsFailure(error);
|
|
37801
|
-
});
|
|
37802
|
-
if (pathStats.isSymbolicLink()) {
|
|
37803
|
-
throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
|
|
37804
|
-
}
|
|
37805
|
-
if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
|
|
37806
|
-
throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
|
|
37807
|
-
}
|
|
37808
|
-
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
37809
|
-
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
37810
|
-
}
|
|
37811
|
-
}
|
|
37812
|
-
function assertStableRead(initial, final, bytesRead) {
|
|
37813
|
-
if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
|
|
37814
|
-
throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
|
|
37815
|
-
}
|
|
37816
|
-
}
|
|
37817
|
-
async function readWorkspaceImage(filePath, workspaceRoot) {
|
|
37818
|
-
const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
|
|
37819
|
-
const targetPath = isAbsolute3(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
|
|
37820
|
-
if (!isPathWithin(lexicalRoot, targetPath)) {
|
|
37821
|
-
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
37822
|
-
}
|
|
37823
|
-
const canonicalRoot = await realpath2(lexicalRoot).catch((error) => {
|
|
37824
|
-
throw attachmentErrorForFsFailure(error);
|
|
37825
|
-
});
|
|
37826
|
-
await assertNoSymlinkComponents(lexicalRoot, targetPath);
|
|
37827
|
-
const canonicalTarget = await realpath2(targetPath).catch((error) => {
|
|
37828
|
-
throw attachmentErrorForFsFailure(error);
|
|
37829
|
-
});
|
|
37830
|
-
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
37831
|
-
throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
|
|
37832
|
-
}
|
|
37833
|
-
const noFollow = constants.O_NOFOLLOW ?? 0;
|
|
37834
|
-
const handle = await open2(targetPath, constants.O_RDONLY | noFollow).catch((error) => {
|
|
37835
|
-
throw attachmentErrorForFsFailure(error);
|
|
37836
|
-
});
|
|
37837
|
-
try {
|
|
37838
|
-
const initialStats = await handle.stat();
|
|
37839
|
-
await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
|
|
37840
|
-
if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
37841
|
-
throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
|
|
37842
|
-
}
|
|
37843
|
-
const mimeType = await detectSupportedImageMimeTypeFromFile(targetPath).catch(() => null);
|
|
37844
|
-
if (!mimeType) {
|
|
37845
|
-
throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
|
|
37846
|
-
}
|
|
37847
|
-
const chunks = [];
|
|
37848
|
-
let totalBytes = 0;
|
|
37849
|
-
while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
37850
|
-
const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
|
|
37851
|
-
const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
|
37852
|
-
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
37853
|
-
if (bytesRead === 0)
|
|
37854
|
-
break;
|
|
37855
|
-
chunks.push(chunk.subarray(0, bytesRead));
|
|
37856
|
-
totalBytes += bytesRead;
|
|
37857
|
-
}
|
|
37858
|
-
if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
|
|
37859
|
-
throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
|
|
37860
|
-
}
|
|
37861
|
-
if (totalBytes === 0) {
|
|
37862
|
-
throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
|
|
37863
|
-
}
|
|
37864
|
-
const finalStats = await handle.stat();
|
|
37865
|
-
await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
|
|
37866
|
-
assertStableRead(initialStats, finalStats, totalBytes);
|
|
37867
|
-
return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath, mimeType };
|
|
37868
|
-
} catch (error) {
|
|
37869
|
-
if (error instanceof PromptAttachmentError)
|
|
37870
|
-
throw error;
|
|
37871
|
-
throw attachmentErrorForFsFailure(error);
|
|
37872
|
-
} finally {
|
|
37873
|
-
await handle.close();
|
|
37874
|
-
}
|
|
37875
|
-
}
|
|
37876
|
-
async function resolvePromptFiles(attachments, workspaceRoot) {
|
|
37877
|
-
const files = [];
|
|
37878
|
-
for (const attachment of attachments) {
|
|
37879
|
-
if (attachment.type !== "file")
|
|
37880
|
-
continue;
|
|
37881
|
-
const absolutePath = await resolveWorkspaceFile(attachment.path, workspaceRoot);
|
|
37882
|
-
files.push({
|
|
37883
|
-
path: attachment.path,
|
|
37884
|
-
absolutePath,
|
|
37885
|
-
...attachment.filename ? { filename: attachment.filename } : {}
|
|
37886
|
-
});
|
|
37887
|
-
}
|
|
37888
|
-
return files;
|
|
37889
|
-
}
|
|
37890
|
-
async function resolveWorkspaceFile(filePath, workspaceRoot) {
|
|
37891
|
-
const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
|
|
37892
|
-
const targetPath = isAbsolute3(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
|
|
37893
|
-
if (!isPathWithin(lexicalRoot, targetPath)) {
|
|
37894
|
-
throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
|
|
37895
|
-
}
|
|
37896
|
-
const canonicalRoot = await realpath2(lexicalRoot).catch((error) => {
|
|
37897
|
-
throw attachmentErrorForFsFailure(error);
|
|
37898
|
-
});
|
|
37899
|
-
await assertNoSymlinkComponents(lexicalRoot, targetPath);
|
|
37900
|
-
const canonicalTarget = await realpath2(targetPath).catch((error) => {
|
|
37901
|
-
throw attachmentErrorForFsFailure(error);
|
|
37902
|
-
});
|
|
37903
|
-
if (!isPathWithin(canonicalRoot, canonicalTarget)) {
|
|
37904
|
-
throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
|
|
37905
|
-
}
|
|
37906
|
-
const stats = await lstat2(targetPath).catch((error) => {
|
|
37907
|
-
throw attachmentErrorForFsFailure(error);
|
|
37908
|
-
});
|
|
37909
|
-
if (!stats.isFile()) {
|
|
37910
|
-
throw new PromptAttachmentError("attachment_not_regular_file", "A file attachment must name a regular workspace file");
|
|
37911
|
-
}
|
|
37912
|
-
return targetPath;
|
|
37913
|
-
}
|
|
37914
|
-
function promptFileReferences(files) {
|
|
37915
|
-
if (files.length === 0)
|
|
37916
|
-
return "";
|
|
37917
|
-
const lines = files.map((file) => file.filename && file.filename !== file.path ? `- ${file.absolutePath} (${file.filename})` : `- ${file.absolutePath}`);
|
|
37918
|
-
return `
|
|
37919
|
-
|
|
37920
|
-
Attached files:
|
|
37921
|
-
${lines.join(`
|
|
37922
|
-
`)}`;
|
|
37923
|
-
}
|
|
37924
38415
|
// ../protocol/src/node/transcript-window.ts
|
|
37925
38416
|
import { Buffer as Buffer4 } from "node:buffer";
|
|
37926
38417
|
var DEFAULT_ENVELOPE_RESERVE_BYTES = 256;
|
|
@@ -38029,7 +38520,8 @@ function publicSession(state) {
|
|
|
38029
38520
|
revision: state.revision,
|
|
38030
38521
|
...publicCommandRevision(state),
|
|
38031
38522
|
sessionId: state.id,
|
|
38032
|
-
composer: state
|
|
38523
|
+
composer: publicComposer(state),
|
|
38524
|
+
...publicTurnActivity(state),
|
|
38033
38525
|
...state.policy ? { policy: piReportedPolicy(state.policy, state.readOnly) } : {},
|
|
38034
38526
|
...contextUsage ? { contextUsage } : {},
|
|
38035
38527
|
runtime: publicRuntime(state)
|
|
@@ -38054,7 +38546,8 @@ function publicStatus(state, readiness) {
|
|
|
38054
38546
|
...publicCommandRevision(state),
|
|
38055
38547
|
...state.sessionFile ? { resumableSessionId: state.sessionFile } : {},
|
|
38056
38548
|
...state.title ? { title: state.title } : {},
|
|
38057
|
-
composer: state
|
|
38549
|
+
composer: publicComposer(state),
|
|
38550
|
+
...publicTurnActivity(state),
|
|
38058
38551
|
...state.policy ? { policy: piReportedPolicy(state.policy, state.readOnly) } : {},
|
|
38059
38552
|
...contextUsage ? { contextUsage } : {},
|
|
38060
38553
|
runtime: publicRuntime(state),
|
|
@@ -38081,7 +38574,10 @@ function messageWindow(state, fromIndex, tailMessages = null) {
|
|
|
38081
38574
|
};
|
|
38082
38575
|
}
|
|
38083
38576
|
function publicTurnError(state) {
|
|
38084
|
-
return state.promptClaim !== undefined ? undefined : state.error;
|
|
38577
|
+
return state.promptClaim !== undefined || state.compacting ? undefined : state.error;
|
|
38578
|
+
}
|
|
38579
|
+
function publicTurnActivity(state) {
|
|
38580
|
+
return state.compacting ? { activity: "compacting" } : {};
|
|
38085
38581
|
}
|
|
38086
38582
|
function publicActivity(state) {
|
|
38087
38583
|
if (sessionIsBlocked(state))
|
|
@@ -38381,7 +38877,7 @@ function humanPromptObservation(messages, tasks) {
|
|
|
38381
38877
|
}
|
|
38382
38878
|
|
|
38383
38879
|
// ../../bridges/pi-bridge/src/http.ts
|
|
38384
|
-
import { createHash as
|
|
38880
|
+
import { createHash as createHash9, randomBytes as randomBytes9 } from "node:crypto";
|
|
38385
38881
|
import { pathToFileURL } from "node:url";
|
|
38386
38882
|
import { gzip } from "node:zlib";
|
|
38387
38883
|
|
|
@@ -38438,7 +38934,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
|
|
|
38438
38934
|
|
|
38439
38935
|
// ../protocol/src/node/bridge-transcript-summary.ts
|
|
38440
38936
|
import { Buffer as Buffer5 } from "node:buffer";
|
|
38441
|
-
import { createHash as
|
|
38937
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
38442
38938
|
|
|
38443
38939
|
// ../protocol/src/node/progressive-transcript.ts
|
|
38444
38940
|
var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
|
|
@@ -38604,7 +39100,7 @@ function digestPayload(payload) {
|
|
|
38604
39100
|
const serialized = JSON.stringify(payload);
|
|
38605
39101
|
return {
|
|
38606
39102
|
bytes: Buffer5.byteLength(serialized),
|
|
38607
|
-
digest:
|
|
39103
|
+
digest: createHash8("sha256").update(serialized).digest("base64url").slice(0, 32)
|
|
38608
39104
|
};
|
|
38609
39105
|
}
|
|
38610
39106
|
function topLevelKey(part, index) {
|
|
@@ -39356,7 +39852,7 @@ function assertSessionOpen(state) {
|
|
|
39356
39852
|
var GLOBAL_REFRESH_CONCURRENCY = 4;
|
|
39357
39853
|
var DEFAULT_DELETE_CANCEL_TIMEOUT_MS = 5000;
|
|
39358
39854
|
var DEFAULT_CANCEL_ACK_TIMEOUT_MS = 5000;
|
|
39359
|
-
var TRANSCRIPT_GENERATION =
|
|
39855
|
+
var TRANSCRIPT_GENERATION = randomBytes9(16).toString("hex");
|
|
39360
39856
|
var deleteCancelTimeoutMs = DEFAULT_DELETE_CANCEL_TIMEOUT_MS;
|
|
39361
39857
|
var cancelAckTimeoutMs = DEFAULT_CANCEL_ACK_TIMEOUT_MS;
|
|
39362
39858
|
function setDeleteCancelTimeoutForTests(timeoutMs) {
|
|
@@ -39379,6 +39875,9 @@ async function route(request, response, clientSignal) {
|
|
|
39379
39875
|
})) {
|
|
39380
39876
|
return json(response, 401, { error: "Unauthorized" });
|
|
39381
39877
|
}
|
|
39878
|
+
const refused = await admitNodeBridgeRequest(bridgeAuthority, request, MAX_BODY_BYTES);
|
|
39879
|
+
if (refused)
|
|
39880
|
+
return json(response, refused.status, refused.body);
|
|
39382
39881
|
try {
|
|
39383
39882
|
if (url.pathname === SESSION_ACTIVITY_BATCH_PATH && request.method === "POST") {
|
|
39384
39883
|
const answer = await answerSessionActivityBatch(request, sessionActivityObservation, {
|
|
@@ -39640,7 +40139,7 @@ async function routeSession(request, response, url, clientSignal) {
|
|
|
39640
40139
|
return json(response, 200, { servers: publicPiMcpServers(state) });
|
|
39641
40140
|
}
|
|
39642
40141
|
if (action === "config" && request.method === "GET") {
|
|
39643
|
-
return json(response, 200, { ...state
|
|
40142
|
+
return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
|
|
39644
40143
|
}
|
|
39645
40144
|
if (action === "config" && request.method === "POST") {
|
|
39646
40145
|
return await handleConfig(request, response, state);
|
|
@@ -39749,7 +40248,7 @@ async function handleConfig(request, response, state) {
|
|
|
39749
40248
|
}
|
|
39750
40249
|
const patch = parseComposerPatch(body);
|
|
39751
40250
|
if (!patch)
|
|
39752
|
-
return json(response, 200, { ...state
|
|
40251
|
+
return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
|
|
39753
40252
|
state.dispatching = true;
|
|
39754
40253
|
try {
|
|
39755
40254
|
if (applyComposerPatch(state, patch)) {
|
|
@@ -39759,7 +40258,7 @@ async function handleConfig(request, response, state) {
|
|
|
39759
40258
|
} finally {
|
|
39760
40259
|
state.dispatching = false;
|
|
39761
40260
|
}
|
|
39762
|
-
return json(response, 200, { ...state
|
|
40261
|
+
return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
|
|
39763
40262
|
}
|
|
39764
40263
|
async function handleCancel(response, state) {
|
|
39765
40264
|
const { claim, cancel } = requestTurnCancellation(state, "The turn was cancelled before this tool call was approved.");
|
|
@@ -39770,6 +40269,13 @@ async function handleCancel(response, state) {
|
|
|
39770
40269
|
if (claim !== undefined) {
|
|
39771
40270
|
return json(response, 202, { cancelled: false, pending: true });
|
|
39772
40271
|
}
|
|
40272
|
+
const compaction = requestCompactionCancellation(state);
|
|
40273
|
+
if (compaction) {
|
|
40274
|
+
const outcome = await withTimeout(compaction.then((stopped) => stopped ? "stopped" : "finished"), cancelAckTimeoutMs, "Pi compaction cancellation is still in flight").catch(() => "pending");
|
|
40275
|
+
if (outcome === "pending")
|
|
40276
|
+
return json(response, 202, { cancelled: false, pending: true });
|
|
40277
|
+
return json(response, 200, { cancelled: outcome === "stopped" });
|
|
40278
|
+
}
|
|
39773
40279
|
return json(response, 200, { cancelled: false });
|
|
39774
40280
|
}
|
|
39775
40281
|
async function handleCompact(request, response, state) {
|
|
@@ -39780,6 +40286,17 @@ async function handleCompact(request, response, state) {
|
|
|
39780
40286
|
state.dispatching = true;
|
|
39781
40287
|
state.compacting = true;
|
|
39782
40288
|
state.revision += 1;
|
|
40289
|
+
let settle = () => {
|
|
40290
|
+
return;
|
|
40291
|
+
};
|
|
40292
|
+
const compaction = {
|
|
40293
|
+
cancelRequested: false,
|
|
40294
|
+
settled: new Promise((resolve) => {
|
|
40295
|
+
settle = resolve;
|
|
40296
|
+
})
|
|
40297
|
+
};
|
|
40298
|
+
state.manualCompaction = compaction;
|
|
40299
|
+
let stopped = false;
|
|
39783
40300
|
let instructions;
|
|
39784
40301
|
try {
|
|
39785
40302
|
const parsed = parseCompactInstructionsBody(await readJsonValue(request));
|
|
@@ -39787,8 +40304,21 @@ async function handleCompact(request, response, state) {
|
|
|
39787
40304
|
throw new HttpError(400, parsed.error);
|
|
39788
40305
|
instructions = parsed.instructions;
|
|
39789
40306
|
const session = await ensureSession(state);
|
|
39790
|
-
|
|
40307
|
+
if (compaction.cancelRequested)
|
|
40308
|
+
stopped = true;
|
|
40309
|
+
else {
|
|
40310
|
+
try {
|
|
40311
|
+
await session.compact(instructions);
|
|
40312
|
+
} catch (error) {
|
|
40313
|
+
if (!compaction.cancelRequested)
|
|
40314
|
+
throw error;
|
|
40315
|
+
stopped = true;
|
|
40316
|
+
}
|
|
40317
|
+
}
|
|
39791
40318
|
} finally {
|
|
40319
|
+
if (state.manualCompaction === compaction)
|
|
40320
|
+
state.manualCompaction = undefined;
|
|
40321
|
+
settle(stopped);
|
|
39792
40322
|
state.compacting = false;
|
|
39793
40323
|
state.dispatching = false;
|
|
39794
40324
|
state.revision += 1;
|
|
@@ -39797,6 +40327,9 @@ async function handleCompact(request, response, state) {
|
|
|
39797
40327
|
return;
|
|
39798
40328
|
});
|
|
39799
40329
|
}
|
|
40330
|
+
if (stopped) {
|
|
40331
|
+
return json(response, 409, { error: COMPACTION_CANCELLED_MESSAGE, cancelled: true });
|
|
40332
|
+
}
|
|
39800
40333
|
return json(response, 200, instructions ? { compacted: true, instructions: "applied" } : { compacted: true });
|
|
39801
40334
|
}
|
|
39802
40335
|
async function handleSteer(request, response, state) {
|
|
@@ -39816,7 +40349,7 @@ async function handleSteer(request, response, state) {
|
|
|
39816
40349
|
throw new HttpError(400, "requestId is required");
|
|
39817
40350
|
if (!expectedRunId)
|
|
39818
40351
|
throw new HttpError(400, "expectedRunId is required");
|
|
39819
|
-
const inputDigest =
|
|
40352
|
+
const inputDigest = createHash9("sha256").update(text).digest("hex");
|
|
39820
40353
|
const previous = state.steerJournal.get(requestId);
|
|
39821
40354
|
if (previous) {
|
|
39822
40355
|
if (previous.inputDigest !== inputDigest || previous.expectedRunId !== expectedRunId) {
|
|
@@ -40249,7 +40782,7 @@ function appendLocalExchange(state, prompt, reply, requestId, kind) {
|
|
|
40249
40782
|
if (userId && state.messages.some((message) => message.id === userId))
|
|
40250
40783
|
return;
|
|
40251
40784
|
appendUserMessage(state, prompt, [], [], userId);
|
|
40252
|
-
const messageId = requestId ? `${kind}-reply:${requestId}` :
|
|
40785
|
+
const messageId = requestId ? `${kind}-reply:${requestId}` : randomBytes9(12).toString("hex");
|
|
40253
40786
|
state.messages.push({
|
|
40254
40787
|
id: messageId,
|
|
40255
40788
|
role: "assistant",
|
|
@@ -40266,7 +40799,7 @@ function appendLocalExchange(state, prompt, reply, requestId, kind) {
|
|
|
40266
40799
|
});
|
|
40267
40800
|
chargeTranscript(state, Buffer.byteLength(reply));
|
|
40268
40801
|
}
|
|
40269
|
-
function appendUserMessage(state, prompt, images, files, messageId =
|
|
40802
|
+
function appendUserMessage(state, prompt, images, files, messageId = randomBytes9(12).toString("hex")) {
|
|
40270
40803
|
const attachments = [...images, ...files];
|
|
40271
40804
|
state.messages.push({
|
|
40272
40805
|
id: messageId,
|
|
@@ -40322,9 +40855,10 @@ async function readJson(request) {
|
|
|
40322
40855
|
return isObject(parsed) ? parsed : {};
|
|
40323
40856
|
}
|
|
40324
40857
|
async function readJsonValue(request) {
|
|
40325
|
-
const
|
|
40326
|
-
|
|
40327
|
-
|
|
40858
|
+
const admitted = takeAdmittedBody(request);
|
|
40859
|
+
const chunks = admitted ? [admitted] : [];
|
|
40860
|
+
let total = admitted?.length ?? 0;
|
|
40861
|
+
for await (const chunk of admitted ? [] : request) {
|
|
40328
40862
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
40329
40863
|
total += buffer.length;
|
|
40330
40864
|
if (total > MAX_BODY_BYTES)
|
|
@@ -40868,6 +41402,7 @@ export {
|
|
|
40868
41402
|
boundTranscript,
|
|
40869
41403
|
boundTranscriptDuringStreaming,
|
|
40870
41404
|
boundTranscriptForRead,
|
|
41405
|
+
bridgeAuthority,
|
|
40871
41406
|
bridgeGeneration,
|
|
40872
41407
|
cancelRequestedFor,
|
|
40873
41408
|
catalogReadFailed,
|