@parall/daemon 1.59.0 → 1.60.0
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/bundle/manifest.json +11 -11
- package/bundle/parall-browser-pod.js +59 -5
- package/bundle/parall-claude-agent.js +2276 -819
- package/bundle/parall-codex-agent.js +1889 -812
- package/bundle/parall-daemon.js +596 -361
- package/dist/daemon-main.d.ts.map +1 -1
- package/dist/daemon-main.js +9 -2
- package/dist/runtimes.d.ts.map +1 -1
- package/dist/runtimes.js +5 -1
- package/package.json +6 -6
|
@@ -17719,9 +17719,9 @@ var require_getMachineId_linux = __commonJS({
|
|
|
17719
17719
|
var api_1 = (init_esm(), __toCommonJS(esm_exports));
|
|
17720
17720
|
async function getMachineId() {
|
|
17721
17721
|
const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
|
|
17722
|
-
for (const
|
|
17722
|
+
for (const path14 of paths) {
|
|
17723
17723
|
try {
|
|
17724
|
-
const result = await fs_1.promises.readFile(
|
|
17724
|
+
const result = await fs_1.promises.readFile(path14, { encoding: "utf8" });
|
|
17725
17725
|
return result.trim();
|
|
17726
17726
|
} catch (e) {
|
|
17727
17727
|
api_1.diag.debug(`error reading machine id: ${e}`);
|
|
@@ -21124,7 +21124,7 @@ function appendRootPathToUrlIfNeeded(url) {
|
|
|
21124
21124
|
return void 0;
|
|
21125
21125
|
}
|
|
21126
21126
|
}
|
|
21127
|
-
function appendResourcePathToUrl(url,
|
|
21127
|
+
function appendResourcePathToUrl(url, path14) {
|
|
21128
21128
|
try {
|
|
21129
21129
|
new URL(url);
|
|
21130
21130
|
} catch (_a) {
|
|
@@ -21134,11 +21134,11 @@ function appendResourcePathToUrl(url, path13) {
|
|
|
21134
21134
|
if (!url.endsWith("/")) {
|
|
21135
21135
|
url = url + "/";
|
|
21136
21136
|
}
|
|
21137
|
-
url +=
|
|
21137
|
+
url += path14;
|
|
21138
21138
|
try {
|
|
21139
21139
|
new URL(url);
|
|
21140
21140
|
} catch (_b) {
|
|
21141
|
-
diag2.warn("Configuration: Provided URL appended with '" +
|
|
21141
|
+
diag2.warn("Configuration: Provided URL appended with '" + path14 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
|
|
21142
21142
|
return void 0;
|
|
21143
21143
|
}
|
|
21144
21144
|
return url;
|
|
@@ -27549,14 +27549,14 @@ var require_util2 = __commonJS({
|
|
|
27549
27549
|
}
|
|
27550
27550
|
const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
|
|
27551
27551
|
let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
|
|
27552
|
-
let
|
|
27552
|
+
let path14 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
|
|
27553
27553
|
if (origin[origin.length - 1] === "/") {
|
|
27554
27554
|
origin = origin.slice(0, origin.length - 1);
|
|
27555
27555
|
}
|
|
27556
|
-
if (
|
|
27557
|
-
|
|
27556
|
+
if (path14 && path14[0] !== "/") {
|
|
27557
|
+
path14 = `/${path14}`;
|
|
27558
27558
|
}
|
|
27559
|
-
return new URL(`${origin}${
|
|
27559
|
+
return new URL(`${origin}${path14}`);
|
|
27560
27560
|
}
|
|
27561
27561
|
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
|
|
27562
27562
|
throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
|
|
@@ -28377,9 +28377,9 @@ var require_diagnostics = __commonJS({
|
|
|
28377
28377
|
"undici:client:sendHeaders",
|
|
28378
28378
|
(evt) => {
|
|
28379
28379
|
const {
|
|
28380
|
-
request: { method, path:
|
|
28380
|
+
request: { method, path: path14, origin }
|
|
28381
28381
|
} = evt;
|
|
28382
|
-
debugLog("sending request to %s %s%s", method, origin,
|
|
28382
|
+
debugLog("sending request to %s %s%s", method, origin, path14);
|
|
28383
28383
|
}
|
|
28384
28384
|
);
|
|
28385
28385
|
}
|
|
@@ -28397,14 +28397,14 @@ var require_diagnostics = __commonJS({
|
|
|
28397
28397
|
"undici:request:headers",
|
|
28398
28398
|
(evt) => {
|
|
28399
28399
|
const {
|
|
28400
|
-
request: { method, path:
|
|
28400
|
+
request: { method, path: path14, origin },
|
|
28401
28401
|
response: { statusCode }
|
|
28402
28402
|
} = evt;
|
|
28403
28403
|
debugLog(
|
|
28404
28404
|
"received response to %s %s%s - HTTP %d",
|
|
28405
28405
|
method,
|
|
28406
28406
|
origin,
|
|
28407
|
-
|
|
28407
|
+
path14,
|
|
28408
28408
|
statusCode
|
|
28409
28409
|
);
|
|
28410
28410
|
}
|
|
@@ -28413,23 +28413,23 @@ var require_diagnostics = __commonJS({
|
|
|
28413
28413
|
"undici:request:trailers",
|
|
28414
28414
|
(evt) => {
|
|
28415
28415
|
const {
|
|
28416
|
-
request: { method, path:
|
|
28416
|
+
request: { method, path: path14, origin }
|
|
28417
28417
|
} = evt;
|
|
28418
|
-
debugLog("trailers received from %s %s%s", method, origin,
|
|
28418
|
+
debugLog("trailers received from %s %s%s", method, origin, path14);
|
|
28419
28419
|
}
|
|
28420
28420
|
);
|
|
28421
28421
|
diagnosticsChannel.subscribe(
|
|
28422
28422
|
"undici:request:error",
|
|
28423
28423
|
(evt) => {
|
|
28424
28424
|
const {
|
|
28425
|
-
request: { method, path:
|
|
28425
|
+
request: { method, path: path14, origin },
|
|
28426
28426
|
error
|
|
28427
28427
|
} = evt;
|
|
28428
28428
|
debugLog(
|
|
28429
28429
|
"request to %s %s%s errored - %s",
|
|
28430
28430
|
method,
|
|
28431
28431
|
origin,
|
|
28432
|
-
|
|
28432
|
+
path14,
|
|
28433
28433
|
error.message
|
|
28434
28434
|
);
|
|
28435
28435
|
}
|
|
@@ -28532,7 +28532,7 @@ var require_request = __commonJS({
|
|
|
28532
28532
|
var kHandler = Symbol("handler");
|
|
28533
28533
|
var Request = class {
|
|
28534
28534
|
constructor(origin, {
|
|
28535
|
-
path:
|
|
28535
|
+
path: path14,
|
|
28536
28536
|
method,
|
|
28537
28537
|
body,
|
|
28538
28538
|
headers,
|
|
@@ -28549,11 +28549,11 @@ var require_request = __commonJS({
|
|
|
28549
28549
|
maxRedirections,
|
|
28550
28550
|
typeOfService
|
|
28551
28551
|
}, handler) {
|
|
28552
|
-
if (typeof
|
|
28552
|
+
if (typeof path14 !== "string") {
|
|
28553
28553
|
throw new InvalidArgumentError("path must be a string");
|
|
28554
|
-
} else if (
|
|
28554
|
+
} else if (path14[0] !== "/" && !(path14.startsWith("http://") || path14.startsWith("https://")) && method !== "CONNECT") {
|
|
28555
28555
|
throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
|
|
28556
|
-
} else if (invalidPathRegex.test(
|
|
28556
|
+
} else if (invalidPathRegex.test(path14)) {
|
|
28557
28557
|
throw new InvalidArgumentError("invalid request path");
|
|
28558
28558
|
}
|
|
28559
28559
|
if (typeof method !== "string") {
|
|
@@ -28628,7 +28628,7 @@ var require_request = __commonJS({
|
|
|
28628
28628
|
this.completed = false;
|
|
28629
28629
|
this.aborted = false;
|
|
28630
28630
|
this.upgrade = upgrade || null;
|
|
28631
|
-
this.path = query ? serializePathWithQuery(
|
|
28631
|
+
this.path = query ? serializePathWithQuery(path14, query) : path14;
|
|
28632
28632
|
this.origin = origin;
|
|
28633
28633
|
this.protocol = getProtocolFromUrlString(origin);
|
|
28634
28634
|
this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
|
|
@@ -33667,7 +33667,7 @@ var require_client_h1 = __commonJS({
|
|
|
33667
33667
|
return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
|
|
33668
33668
|
}
|
|
33669
33669
|
function writeH1(client, request3) {
|
|
33670
|
-
const { method, path:
|
|
33670
|
+
const { method, path: path14, host, upgrade, blocking, reset } = request3;
|
|
33671
33671
|
let { body, headers, contentLength } = request3;
|
|
33672
33672
|
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
|
|
33673
33673
|
if (util.isFormDataLike(body)) {
|
|
@@ -33736,7 +33736,7 @@ var require_client_h1 = __commonJS({
|
|
|
33736
33736
|
if (socket.setTypeOfService) {
|
|
33737
33737
|
socket.setTypeOfService(request3.typeOfService);
|
|
33738
33738
|
}
|
|
33739
|
-
let header = `${method} ${
|
|
33739
|
+
let header = `${method} ${path14} HTTP/1.1\r
|
|
33740
33740
|
`;
|
|
33741
33741
|
if (typeof host === "string") {
|
|
33742
33742
|
header += `host: ${host}\r
|
|
@@ -34389,7 +34389,7 @@ var require_client_h2 = __commonJS({
|
|
|
34389
34389
|
function writeH2(client, request3) {
|
|
34390
34390
|
const requestTimeout = request3.bodyTimeout ?? client[kBodyTimeout];
|
|
34391
34391
|
const session = client[kHTTP2Session];
|
|
34392
|
-
const { method, path:
|
|
34392
|
+
const { method, path: path14, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request3;
|
|
34393
34393
|
let { body } = request3;
|
|
34394
34394
|
if (upgrade != null && upgrade !== "websocket") {
|
|
34395
34395
|
util.errorRequest(client, request3, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
|
|
@@ -34457,7 +34457,7 @@ var require_client_h2 = __commonJS({
|
|
|
34457
34457
|
}
|
|
34458
34458
|
headers[HTTP2_HEADER_METHOD] = "CONNECT";
|
|
34459
34459
|
headers[HTTP2_HEADER_PROTOCOL] = "websocket";
|
|
34460
|
-
headers[HTTP2_HEADER_PATH] =
|
|
34460
|
+
headers[HTTP2_HEADER_PATH] = path14;
|
|
34461
34461
|
if (protocol === "ws:" || protocol === "wss:") {
|
|
34462
34462
|
headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
|
|
34463
34463
|
} else {
|
|
@@ -34498,7 +34498,7 @@ var require_client_h2 = __commonJS({
|
|
|
34498
34498
|
stream.setTimeout(requestTimeout);
|
|
34499
34499
|
return true;
|
|
34500
34500
|
}
|
|
34501
|
-
headers[HTTP2_HEADER_PATH] =
|
|
34501
|
+
headers[HTTP2_HEADER_PATH] = path14;
|
|
34502
34502
|
headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
|
|
34503
34503
|
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
|
|
34504
34504
|
if (body && typeof body.read === "function") {
|
|
@@ -36800,10 +36800,10 @@ var require_proxy_agent = __commonJS({
|
|
|
36800
36800
|
};
|
|
36801
36801
|
const {
|
|
36802
36802
|
origin,
|
|
36803
|
-
path:
|
|
36803
|
+
path: path14 = "/",
|
|
36804
36804
|
headers = {}
|
|
36805
36805
|
} = opts;
|
|
36806
|
-
opts.path = origin +
|
|
36806
|
+
opts.path = origin + path14;
|
|
36807
36807
|
if (!("host" in headers) && !("Host" in headers)) {
|
|
36808
36808
|
const { host } = new URL(origin);
|
|
36809
36809
|
headers.host = host;
|
|
@@ -38866,20 +38866,20 @@ var require_mock_utils = __commonJS({
|
|
|
38866
38866
|
}
|
|
38867
38867
|
return normalizedQp;
|
|
38868
38868
|
}
|
|
38869
|
-
function safeUrl(
|
|
38870
|
-
if (typeof
|
|
38871
|
-
return
|
|
38869
|
+
function safeUrl(path14) {
|
|
38870
|
+
if (typeof path14 !== "string") {
|
|
38871
|
+
return path14;
|
|
38872
38872
|
}
|
|
38873
|
-
const pathSegments =
|
|
38873
|
+
const pathSegments = path14.split("?", 3);
|
|
38874
38874
|
if (pathSegments.length !== 2) {
|
|
38875
|
-
return
|
|
38875
|
+
return path14;
|
|
38876
38876
|
}
|
|
38877
38877
|
const qp = new URLSearchParams(pathSegments.pop());
|
|
38878
38878
|
qp.sort();
|
|
38879
38879
|
return [...pathSegments, qp.toString()].join("?");
|
|
38880
38880
|
}
|
|
38881
|
-
function matchKey(mockDispatch2, { path:
|
|
38882
|
-
const pathMatch = matchValue(mockDispatch2.path,
|
|
38881
|
+
function matchKey(mockDispatch2, { path: path14, method, body, headers }) {
|
|
38882
|
+
const pathMatch = matchValue(mockDispatch2.path, path14);
|
|
38883
38883
|
const methodMatch = matchValue(mockDispatch2.method, method);
|
|
38884
38884
|
const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
|
|
38885
38885
|
const headersMatch = matchHeaders(mockDispatch2, headers);
|
|
@@ -38904,8 +38904,8 @@ var require_mock_utils = __commonJS({
|
|
|
38904
38904
|
const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
|
|
38905
38905
|
const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
|
|
38906
38906
|
const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
|
|
38907
|
-
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path:
|
|
38908
|
-
return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(
|
|
38907
|
+
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path14, ignoreTrailingSlash }) => {
|
|
38908
|
+
return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path14)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path14), resolvedPath);
|
|
38909
38909
|
});
|
|
38910
38910
|
if (matchedMockDispatches.length === 0) {
|
|
38911
38911
|
throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
|
|
@@ -38944,19 +38944,19 @@ var require_mock_utils = __commonJS({
|
|
|
38944
38944
|
mockDispatches.splice(index, 1);
|
|
38945
38945
|
}
|
|
38946
38946
|
}
|
|
38947
|
-
function removeTrailingSlash(
|
|
38948
|
-
while (
|
|
38949
|
-
|
|
38947
|
+
function removeTrailingSlash(path14) {
|
|
38948
|
+
while (path14.endsWith("/")) {
|
|
38949
|
+
path14 = path14.slice(0, -1);
|
|
38950
38950
|
}
|
|
38951
|
-
if (
|
|
38952
|
-
|
|
38951
|
+
if (path14.length === 0) {
|
|
38952
|
+
path14 = "/";
|
|
38953
38953
|
}
|
|
38954
|
-
return
|
|
38954
|
+
return path14;
|
|
38955
38955
|
}
|
|
38956
38956
|
function buildKey(opts) {
|
|
38957
|
-
const { path:
|
|
38957
|
+
const { path: path14, method, body, headers, query } = opts;
|
|
38958
38958
|
return {
|
|
38959
|
-
path:
|
|
38959
|
+
path: path14,
|
|
38960
38960
|
method,
|
|
38961
38961
|
body,
|
|
38962
38962
|
headers,
|
|
@@ -39646,10 +39646,10 @@ var require_pending_interceptors_formatter = __commonJS({
|
|
|
39646
39646
|
}
|
|
39647
39647
|
format(pendingInterceptors) {
|
|
39648
39648
|
const withPrettyHeaders = pendingInterceptors.map(
|
|
39649
|
-
({ method, path:
|
|
39649
|
+
({ method, path: path14, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
|
|
39650
39650
|
Method: method,
|
|
39651
39651
|
Origin: origin,
|
|
39652
|
-
Path:
|
|
39652
|
+
Path: path14,
|
|
39653
39653
|
"Status code": statusCode,
|
|
39654
39654
|
Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
|
|
39655
39655
|
Invocations: timesInvoked,
|
|
@@ -39731,9 +39731,9 @@ var require_mock_agent = __commonJS({
|
|
|
39731
39731
|
const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
|
|
39732
39732
|
const dispatchOpts = { ...opts };
|
|
39733
39733
|
if (acceptNonStandardSearchParameters && dispatchOpts.path) {
|
|
39734
|
-
const [
|
|
39734
|
+
const [path14, searchParams] = dispatchOpts.path.split("?");
|
|
39735
39735
|
const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
|
|
39736
|
-
dispatchOpts.path = `${
|
|
39736
|
+
dispatchOpts.path = `${path14}?${normalizedSearchParams}`;
|
|
39737
39737
|
}
|
|
39738
39738
|
return this[kAgent].dispatch(dispatchOpts, handler);
|
|
39739
39739
|
}
|
|
@@ -39938,7 +39938,7 @@ var require_snapshot_recorder = __commonJS({
|
|
|
39938
39938
|
"ts/node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
|
|
39939
39939
|
"use strict";
|
|
39940
39940
|
var { writeFile, readFile, mkdir: mkdir2 } = __require("node:fs/promises");
|
|
39941
|
-
var { dirname:
|
|
39941
|
+
var { dirname: dirname9, resolve: resolve4 } = __require("node:path");
|
|
39942
39942
|
var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("node:timers");
|
|
39943
39943
|
var { InvalidArgumentError, UndiciError } = require_errors();
|
|
39944
39944
|
var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
|
|
@@ -40134,12 +40134,12 @@ var require_snapshot_recorder = __commonJS({
|
|
|
40134
40134
|
* @return {Promise<void>} - Resolves when snapshots are loaded
|
|
40135
40135
|
*/
|
|
40136
40136
|
async loadSnapshots(filePath) {
|
|
40137
|
-
const
|
|
40138
|
-
if (!
|
|
40137
|
+
const path14 = filePath || this.#snapshotPath;
|
|
40138
|
+
if (!path14) {
|
|
40139
40139
|
throw new InvalidArgumentError("Snapshot path is required");
|
|
40140
40140
|
}
|
|
40141
40141
|
try {
|
|
40142
|
-
const data = await readFile(resolve4(
|
|
40142
|
+
const data = await readFile(resolve4(path14), "utf8");
|
|
40143
40143
|
const parsed = JSON.parse(data);
|
|
40144
40144
|
if (Array.isArray(parsed)) {
|
|
40145
40145
|
this.#snapshots.clear();
|
|
@@ -40153,7 +40153,7 @@ var require_snapshot_recorder = __commonJS({
|
|
|
40153
40153
|
if (error.code === "ENOENT") {
|
|
40154
40154
|
this.#snapshots.clear();
|
|
40155
40155
|
} else {
|
|
40156
|
-
throw new UndiciError(`Failed to load snapshots from ${
|
|
40156
|
+
throw new UndiciError(`Failed to load snapshots from ${path14}`, { cause: error });
|
|
40157
40157
|
}
|
|
40158
40158
|
}
|
|
40159
40159
|
}
|
|
@@ -40164,12 +40164,12 @@ var require_snapshot_recorder = __commonJS({
|
|
|
40164
40164
|
* @returns {Promise<void>} - Resolves when snapshots are saved
|
|
40165
40165
|
*/
|
|
40166
40166
|
async saveSnapshots(filePath) {
|
|
40167
|
-
const
|
|
40168
|
-
if (!
|
|
40167
|
+
const path14 = filePath || this.#snapshotPath;
|
|
40168
|
+
if (!path14) {
|
|
40169
40169
|
throw new InvalidArgumentError("Snapshot path is required");
|
|
40170
40170
|
}
|
|
40171
|
-
const resolvedPath = resolve4(
|
|
40172
|
-
await mkdir2(
|
|
40171
|
+
const resolvedPath = resolve4(path14);
|
|
40172
|
+
await mkdir2(dirname9(resolvedPath), { recursive: true });
|
|
40173
40173
|
const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
|
|
40174
40174
|
hash,
|
|
40175
40175
|
snapshot
|
|
@@ -40793,15 +40793,15 @@ var require_redirect_handler = __commonJS({
|
|
|
40793
40793
|
return;
|
|
40794
40794
|
}
|
|
40795
40795
|
const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
|
|
40796
|
-
const
|
|
40797
|
-
const redirectUrlString = `${origin}${
|
|
40796
|
+
const path14 = search ? `${pathname}${search}` : pathname;
|
|
40797
|
+
const redirectUrlString = `${origin}${path14}`;
|
|
40798
40798
|
for (const historyUrl of this.history) {
|
|
40799
40799
|
if (historyUrl.toString() === redirectUrlString) {
|
|
40800
40800
|
throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
|
|
40801
40801
|
}
|
|
40802
40802
|
}
|
|
40803
40803
|
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
|
|
40804
|
-
this.opts.path =
|
|
40804
|
+
this.opts.path = path14;
|
|
40805
40805
|
this.opts.origin = origin;
|
|
40806
40806
|
this.opts.query = null;
|
|
40807
40807
|
}
|
|
@@ -47008,11 +47008,11 @@ var require_fetch = __commonJS({
|
|
|
47008
47008
|
function dispatch({ body }) {
|
|
47009
47009
|
const url = requestCurrentURL(request3);
|
|
47010
47010
|
const agent = fetchParams.controller.dispatcher;
|
|
47011
|
-
const
|
|
47011
|
+
const path14 = url.pathname + url.search;
|
|
47012
47012
|
const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
|
|
47013
47013
|
return new Promise((resolve4, reject) => agent.dispatch(
|
|
47014
47014
|
{
|
|
47015
|
-
path: hasTrailingQuestionMark ? `${
|
|
47015
|
+
path: hasTrailingQuestionMark ? `${path14}?` : path14,
|
|
47016
47016
|
origin: url.origin,
|
|
47017
47017
|
method: request3.method,
|
|
47018
47018
|
body: agent.isMockActive ? request3.body && (request3.body.source || request3.body.stream) : body,
|
|
@@ -47959,9 +47959,9 @@ var require_util5 = __commonJS({
|
|
|
47959
47959
|
}
|
|
47960
47960
|
}
|
|
47961
47961
|
}
|
|
47962
|
-
function validateCookiePath(
|
|
47963
|
-
for (let i = 0; i <
|
|
47964
|
-
const code =
|
|
47962
|
+
function validateCookiePath(path14) {
|
|
47963
|
+
for (let i = 0; i < path14.length; ++i) {
|
|
47964
|
+
const code = path14.charCodeAt(i);
|
|
47965
47965
|
if (code < 32 || // exclude CTLs (0-31)
|
|
47966
47966
|
code === 127 || // DEL
|
|
47967
47967
|
code === 59) {
|
|
@@ -51131,11 +51131,11 @@ var require_undici = __commonJS({
|
|
|
51131
51131
|
if (typeof opts.path !== "string") {
|
|
51132
51132
|
throw new InvalidArgumentError("invalid opts.path");
|
|
51133
51133
|
}
|
|
51134
|
-
let
|
|
51134
|
+
let path14 = opts.path;
|
|
51135
51135
|
if (!opts.path.startsWith("/")) {
|
|
51136
|
-
|
|
51136
|
+
path14 = `/${path14}`;
|
|
51137
51137
|
}
|
|
51138
|
-
url = new URL(util.parseOrigin(url).origin +
|
|
51138
|
+
url = new URL(util.parseOrigin(url).origin + path14);
|
|
51139
51139
|
} else {
|
|
51140
51140
|
if (!opts) {
|
|
51141
51141
|
opts = typeof url === "object" ? url : {};
|
|
@@ -51251,7 +51251,7 @@ import * as os3 from "node:os";
|
|
|
51251
51251
|
var PLATFORM_IDENTITY_BASE = "## You on Parall\n\nParall is a shared workspace where humans and agents work side by side as equals.\nYou are a participant here, not a service. You hold tasks, own decisions, and are\naccountable for the work you take on \u2014 the same way a human teammate is.\n\nThe people and agents around you are collaborators, not users to serve. Be honest,\nbe direct, and care about the outcome of the work \u2014 not just the request in front\nof you.\n\nYour organization's private instructions below define who you are and what you\nowe. They can widen your duties; they do not cancel the platform rules that\nfollow \u2014 those are how this workspace runs for everyone.";
|
|
51252
51252
|
var IDENTITY_PROFILE_SUFFIX = "### Your Parall Identity\n\nYou are **{{DISPLAY_NAME}}** (`prll://{{USER_ID}}`).{{PUBLIC_PROFILE}}{{MANAGER_LINE}}{{INSTRUCTIONS_SECTION}}\n\nWhen you see `{{USER_ID}}` or `prll://{{USER_ID}}` in messages, mentions, or events \u2014 that's you.";
|
|
51253
51253
|
var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nEvery wake-up arrives as one frame rendered by the platform. Its first line is `[From <target> | <what this is> | \u2026 | TZ: <zone>]` \u2014 the target\'s `prll://` URI is what you address when you act on it \u2014 and its last line is a `[Reminder to Reply: \u2026]` (a person is waiting for your answer) or a `[Reminder: \u2026]` (nobody is; it names the situation and where to look, e.g. `parall tasks -h`). Between them: a line explaining why you receive this and how to change that, then the messages, task, comment, run or decision itself.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively, and don\'t retry or work around a denial. An `INVALID_TARGET` error is different: you addressed the wrong kind of thing (e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use `dm` for a user).\n';
|
|
51254
|
-
var BEHAVIOR_TEMPLATE = "## How to work here\n\n### When to speak\nIn a multi-person chat/task/wiki, whether to speak is not \"is this relevant to me\" \u2014\nit is \"is this turn mine\". Three doors open it; everything else stays silent.\n\n**Invited \u2192 respond.** Invited means: mentioned, DM'd by a person, assigned,\nor someone is asking you back \u2014 answering your question, taking up your\noffer. A frame whose last line is `Reminder to Reply` is always an\ninvitation. A reaction is acknowledgement, not an invitation. An ordinary DM\nfrom another agent is not an invitation \u2014 reply only if it moves the work\nforward (a mention inside that DM still is one). A reply in a thread you\nstarted or joined is an invitation only when it is directed at you \u2014\notherwise it is ordinary discussion and the doors below apply. An invitation\ncovers the thing you were asked \u2014 it is not standing permission to keep\nparticipating. When invited and unsure what is being asked, ask one specific\nquestion \u2014 here, silence is the failure.\n\n**Your declared duty covers it and nobody has claimed it \u2192 respond.** Duties\ncome only from your title, profile, and instructions, or an explicit\narrangement in the chat \u2014 you have no implicit duties. Answer once per discussion, not once per\nmessage: batch what you owe into one reply. If ownership is genuinely\nunclear, claim in one line (\"taking this unless someone else has it\")\nbefore starting.\n\n**Otherwise you are uninvited \u2014 post only facts you hold.** A fact you hold\nis something you yourself did, directly observed, or the current state of a\nsystem you operate \u2014 not what you believe, recall, or could look up. Two\nshapes: it directly contradicts what was just said, or someone asked the\nroom for it and you have it ready. Anything generative \u2014 ideas, plans,\nimprovements, analyses \u2014 is never posted uninvited; its only form is a\none-line offer (\"I have context on this \u2014 ask me if useful\"), at most once\nper discussion. Either way say it once, then you're done \u2014 no follow-up if\ncontradicted or ignored.\n\nUninvited, this rules out: answering a message addressed to someone else,\neven when you know the answer; adding to a question a human already\nanswered; replying message-by-message in a live discussion, or summarizing\nit \u2014 conclusions belong to the participants; responding to FYI or chatter\n(react if acknowledgement helps).\n\nThe asymmetry lives at the door: missing an uninvited chance costs nothing\n\u2014 people will mention you when they need you. Skipping an invited reply is\na real failure. And this door governs only speaking in a room \u2014 the\ninitiative expected of you (below) applies to work you own, never to other\npeople's conversations.\n\nWhat you receive from each channel and thread is yours to set \u2014 the frame's\nsecond line names the exact command. `parall watch list` shows what is in\nforce; `parall watch set <prll://target> all|mentions [until <time>]` sets it\n(`mentions until 2h` is a temporary mute that goes back to all; `all until\ntomorrow` is the reverse); `parall watch <thread> [--until <time>]` and\n`parall unwatch <thread|task>` follow and leave threads and tasks. A personal\n@, @all / @allagent, a person's DM, an assignment and a reaction on your own\nmessage always reach you.\n\n### How to speak\nSpeak like a real human. Match the conversation \u2014 concise in chat, thorough\nin docs, plain language over jargon. Make the point once and stop: don't\nrestate what others just said, don't narrate your internal process or every\ntool call, don't pad replies to seem thorough, and don't close with\napproval-seeking questions.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in channels, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Stay in scope\nYour title, profile, and private instructions define what you are for \u2014\nthey are your scope, and the source of the declared duties above. Work\ninside it. Out-of-scope work is not yours to pick up, however capable you\nare. If something outside your scope looks important, take it to your\nmanager (or an org admin if you have none) and get agreement before acting\n\u2014 a short message making the case beats quietly doing it. When your scope\nitself is unclear, or two duties conflict, ask your manager to settle it\nrather than guessing.\n\n### Move your work forward\nInitiative applies to the work you own \u2014 your tasks, your duties, what you\nwere asked to do. There, don't wait for instructions: if you see the next\nstep, take it; if something is ambiguous, ask the requester once and\nproceed; if you're blocked, say what's blocking you \u2014 don't go silent.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Remember what you learn\nYour workspace memory file \u2014 the file at your workspace root that this\nruntime natively loads into every session (create it if it doesn't exist\nyet) \u2014 is where corrections, org-specific facts, and hard-won know-how go\nthe moment you learn them; don't wait to be told to remember. Keep that\nfile small: long notes go in their own files, linked from it with a\none-line hook saying when to read them. What the organization needs to see\nstill goes to tasks and wiki \u2014 memory is for what only you need next time\nyou wake up. One boundary: a root file that already belongs to a project or\noperator (content you didn't write) is not your memory \u2014 leave it to its\nowners. Keep yours in a file of your own where this runtime offers one\n(Claude Code also loads CLAUDE.local.md); where it doesn't, lean on tasks\nand wiki instead.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\nOther agents share this workspace too. Before starting work, check whether\nsomeone \u2014 human or agent \u2014 has already picked it up; the one-line claim above\nsettles ownership. Coordination beats racing.\n\n### When in doubt\nDoubt about your own work: ask the person who gave it to you rather than\nguess, and prefer \"I don't know\" over fabricating. Doubt about whether to\nspeak in a room: stay out \u2014 an invitation is what brings you back in. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
|
|
51254
|
+
var BEHAVIOR_TEMPLATE = "## How to work here\n\n### When to speak\nIn a multi-person chat/task/wiki, whether to speak is not \"is this relevant to me\" \u2014\nit is \"is this turn mine\". Three doors open it; everything else stays silent.\n\n**Invited \u2192 respond.** Invited means: mentioned, DM'd by a person, assigned,\nor someone is asking you back \u2014 answering your question, taking up your\noffer. A frame whose last line is `Reminder to Reply` is always an\ninvitation. A reaction is acknowledgement, not an invitation. An ordinary DM\nfrom another agent is not an invitation \u2014 reply only if it moves the work\nforward (a mention inside that DM still is one). A reply in a thread you\nstarted or joined is an invitation only when it is directed at you \u2014\notherwise it is ordinary discussion and the doors below apply. An invitation\ncovers the thing you were asked \u2014 it is not standing permission to keep\nparticipating. When invited and unsure what is being asked, ask one specific\nquestion \u2014 here, silence is the failure.\n\n**Your declared duty covers it and nobody has claimed it \u2192 respond.** Duties\ncome only from your title, profile, and instructions, or an explicit\narrangement in the chat \u2014 you have no implicit duties. Answer once per discussion, not once per\nmessage: batch what you owe into one reply. If ownership is genuinely\nunclear, claim in one line (\"taking this unless someone else has it\")\nbefore starting.\n\n**Otherwise you are uninvited \u2014 post only facts you hold.** A fact you hold\nis something you yourself did, directly observed, or the current state of a\nsystem you operate \u2014 not what you believe, recall, or could look up. Two\nshapes: it directly contradicts what was just said, or someone asked the\nroom for it and you have it ready. Anything generative \u2014 ideas, plans,\nimprovements, analyses \u2014 is never posted uninvited; its only form is a\none-line offer (\"I have context on this \u2014 ask me if useful\"), at most once\nper discussion. Either way say it once, then you're done \u2014 no follow-up if\ncontradicted or ignored.\n\nUninvited, this rules out: answering a message addressed to someone else,\neven when you know the answer; adding to a question a human already\nanswered; replying message-by-message in a live discussion, or summarizing\nit \u2014 conclusions belong to the participants; responding to FYI or chatter\n(react if acknowledgement helps).\n\nThe asymmetry lives at the door: missing an uninvited chance costs nothing\n\u2014 people will mention you when they need you. Skipping an invited reply is\na real failure. And this door governs only speaking in a room \u2014 the\ninitiative expected of you (below) applies to work you own, never to other\npeople's conversations.\n\nWhat you receive from each channel and thread is yours to set \u2014 the frame's\nsecond line names the exact command. `parall watch list` shows what is in\nforce; `parall watch set <prll://target> all|mentions [until <time>]` sets it\n(`mentions until 2h` is a temporary mute that goes back to all; `all until\ntomorrow` is the reverse); `parall watch <thread> [--until <time>]` and\n`parall unwatch <thread|task>` follow and leave threads and tasks. A personal\n@, @all / @allagent, a person's DM, an assignment and a reaction on your own\nmessage always reach you.\n\n### How to speak\nSpeak like a real human. Match the conversation \u2014 concise in chat, thorough\nin docs, plain language over jargon. Make the point once and stop: don't\nrestate what others just said, don't narrate your internal process or every\ntool call, don't pad replies to seem thorough, and don't close with\napproval-seeking questions.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in channels, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Stay in scope\nYour title, profile, and private instructions define what you are for \u2014\nthey are your scope, and the source of the declared duties above. Work\ninside it. Out-of-scope work is not yours to pick up, however capable you\nare. If something outside your scope looks important, take it to your\nmanager (or an org admin if you have none) and get agreement before acting\n\u2014 a short message making the case beats quietly doing it. When your scope\nitself is unclear, or two duties conflict, ask your manager to settle it\nrather than guessing.\n\n### Move your work forward\nInitiative applies to the work you own \u2014 your tasks, your duties, what you\nwere asked to do. There, don't wait for instructions: if you see the next\nstep, take it; if something is ambiguous, ask the requester once and\nproceed; if you're blocked, say what's blocking you \u2014 don't go silent.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Remember what you learn\nYour workspace memory file is the file at your workspace root that this\nruntime loads into every session \u2014 CLAUDE.md if you run as Claude Code,\nAGENTS.md under any other runtime (if a file under a legacy name already\nloads for you, keep using that one; if none exists, create it \u2014 unless the\nworkspace belongs to a project or operator, see the boundary below). A file\nunder a name your runtime doesn't load will not be read next time. A\ncorrection you accept, an org-specific fact, a hard-won lesson \u2014 it is not\nremembered until it is written there: your context will compact, your\nsession will start fresh, or you will wake on another machine, and what you\nonly acknowledged in chat is gone with it. Write it the moment you learn\nit; don't wait to be told. Keep that file small: long notes go in\ntheir own files, linked from it with a one-line hook saying when to read\nthem. What the organization needs to see still goes to tasks and wiki \u2014\nmemory is for what only you need next time you wake up. One boundary: a root file that already belongs to a project or\noperator (content you didn't write) is not your memory \u2014 leave it to its\nowners. Keep yours in a file of your own where this runtime offers one\n(Claude Code also loads CLAUDE.local.md); where it doesn't, lean on tasks\nand wiki instead.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\nOther agents share this workspace too. Before starting work, check whether\nsomeone \u2014 human or agent \u2014 has already picked it up; the one-line claim above\nsettles ownership. Coordination beats racing.\n\n### When in doubt\nDoubt about your own work: ask the person who gave it to you rather than\nguess, and prefer \"I don't know\" over fabricating. Doubt about whether to\nspeak in a room: stay out \u2014 an invitation is what brings you back in. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
|
|
51255
51255
|
var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\nA frame carries what is new to you since you last read the target (a mention\ninto a channel you don\'t otherwise receive brings at most 3 earlier messages,\nand says how many more are unread). If you\'re mentioned in a channel and lack\ncontext, pull what you need from the chat \u2014 don\'t guess:\n\n parall messages list cht_xxx --limit 20 --before msg_xxx\n parall messages get msg_xxx\n parall chats get cht_xxx\n\nRule of thumb: in a channel mention, the conversation that led up to you\nbeing called almost always matters \u2014 read it before replying. In a DM, your\nsession already has continuity, so skip the fetch unless something is unclear.\n\nSame pattern for any other entity referenced in the event: `tasks get`,\n`projects get`, `users get`, `chats get`. Follow the reflink, don\'t ask.\nWhen one entity isn\'t enough \u2014 you need what\'s *around* it \u2014 walk the\nreference graph instead of guessing (see "Walk the reference graph" below).\n\nWhen an event carries `[Hint: forwarded_message]`, its body is a set of message\nreferences rather than the forwarded text. Run `parall refs resolve --full`\nwith those references before responding, passing the `--from` message id the\nhint names \u2014 that forwarding message carries the cross-chat access, and when\nseveral forwards arrive in one turn the CLI\'s trigger default would point at\nthe wrong one. `--full` changes only the returned text length, not what you\nare allowed to read.\n\n### Find context with search first\n\nReach for unified semantic search before paging chat history:\n\n parall search "pricing decision june" --limit 10\n\nIt spans messages, tasks, wiki, and comments. Page `messages list` only for the\nverbatim recent flow of one chat, not for discovery.\n\n### Walk the reference graph\n\nReferences form a traversable graph, and you can query it \u2014 don\'t stop at\nfetching entities one by one:\n\n # entity metadata (title, status, preview)\n parall refs resolve prll://tsk_xxx prll://wik_xxx\n # who references this entity\n parall refs backlinks prll://tsk_xxx\n # connected sub-graph around it\n parall refs graph prll://tsk_xxx --depth 2\n\nUse `refs backlinks` when you need "where is this discussed / used"; use\n`refs graph` when you need the full picture around an entity (related tasks,\ndocs, conversations \u2014 edges carry the author\'s annotation for why they linked).\nThen `refs resolve` the interesting node URIs in one batch to get titles and\nstatus. `refs graph` takes entity-level URIs only (`prll://wik_xxx`, not\n`prll://wik_xxx/docs/a.md`). All results are filtered to what you can see.{{PLATFORM_SKILL_HINT}}\n\n### File attachments\n\nMessages may include attachments. They appear in events as:\n\n [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]\n\nTo download an attachment, use the CLI:\n\n parall files download att_xxx --output /tmp/screenshot.png\n\nTo send a file:\n\n parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"\n\nOr upload first and reuse across chats:\n\n parall files upload /tmp/report.pdf\n parall messages send prll://cht_aaa --attachment att_yyy --text "Report"\n parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"\n\nThe `--text` captions above are safe short literals; anything with `$`, backticks, or quotes goes via `--text-file` (see Shell-safety above).\n\n### When to reference\n\n- **Origin** \u2014 always link the message or task that triggered your work\n- **Design docs / wiki** \u2014 link specs and guides relevant to the work\n- **Related tasks** \u2014 link parent, sibling, or blocking tasks\n- **People** \u2014 link assignees or stakeholders when mentioning them\n- **Conversations** \u2014 link a chat or message range as context\n\n### Why this matters\n\nOther agents and humans read your output. References build a navigable context graph \u2014\nin multi-agent workflows, your references are the map that the next agent follows.';
|
|
51256
51256
|
var BRIDGE_SKILL_HINTS = {
|
|
51257
51257
|
SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
|
|
@@ -51458,6 +51458,30 @@ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
|
|
|
51458
51458
|
function buildErrorStepContent(message) {
|
|
51459
51459
|
return { text: message, suppressed: false, status: "error" };
|
|
51460
51460
|
}
|
|
51461
|
+
function isRuntimeBusy(state, now = Date.now()) {
|
|
51462
|
+
return state.activeTurns > 0 || (state.holdUntil ?? 0) > now;
|
|
51463
|
+
}
|
|
51464
|
+
function projectRuntimeEvent(event, groupKey) {
|
|
51465
|
+
switch (event.type) {
|
|
51466
|
+
case "text":
|
|
51467
|
+
return { ...event, project: false, groupKey };
|
|
51468
|
+
case "runtime_session":
|
|
51469
|
+
case "turn_outcome":
|
|
51470
|
+
return event;
|
|
51471
|
+
default:
|
|
51472
|
+
return { ...event, groupKey };
|
|
51473
|
+
}
|
|
51474
|
+
}
|
|
51475
|
+
function describeRuntimeTurnTrigger(trigger) {
|
|
51476
|
+
switch (trigger.kind) {
|
|
51477
|
+
case "background_task":
|
|
51478
|
+
return `background task ${trigger.taskId ?? "?"} ${trigger.status ?? "finished"}${trigger.description ? `: ${trigger.description}` : ""}`;
|
|
51479
|
+
case "subagent":
|
|
51480
|
+
return `subagent thread ${trigger.threadId}${trigger.nickname ? ` (${trigger.nickname})` : ""}`;
|
|
51481
|
+
default:
|
|
51482
|
+
return trigger.reason ? `runtime: ${trigger.reason}` : "runtime self-continuation";
|
|
51483
|
+
}
|
|
51484
|
+
}
|
|
51461
51485
|
|
|
51462
51486
|
// ts/agent-core/dist/fork-prefix.js
|
|
51463
51487
|
function sanitizeMeta(value) {
|
|
@@ -51520,7 +51544,7 @@ function splitChangeSource(sourceId) {
|
|
|
51520
51544
|
|
|
51521
51545
|
// ts/agent-core/dist/gateway-base.js
|
|
51522
51546
|
import * as fs3 from "node:fs";
|
|
51523
|
-
import * as
|
|
51547
|
+
import * as path4 from "node:path";
|
|
51524
51548
|
import { randomUUID } from "node:crypto";
|
|
51525
51549
|
|
|
51526
51550
|
// ts/sdk/dist/browser-viewer.js
|
|
@@ -51795,6 +51819,7 @@ var ENDPOINTS = {
|
|
|
51795
51819
|
CHANNEL_CONVERSATION: (orgId, conversationId) => `${API_BASE}/orgs/${orgId}/channel-conversations/${conversationId}`,
|
|
51796
51820
|
CHANNEL_CONVERSATION_MESSAGES: (orgId, conversationId) => `${API_BASE}/orgs/${orgId}/channel-conversations/${conversationId}/messages`,
|
|
51797
51821
|
CHANNEL_CONVERSATION_SESSION: (orgId, conversationId) => `${API_BASE}/orgs/${orgId}/channel-conversations/${conversationId}/session`,
|
|
51822
|
+
CHANNEL_CONVERSATION_ATTENTION: (orgId, conversationId) => `${API_BASE}/orgs/${orgId}/channel-conversations/${conversationId}/attention`,
|
|
51798
51823
|
CHANNEL_MESSAGE: (orgId, messageId) => `${API_BASE}/orgs/${orgId}/channel-messages/${messageId}`,
|
|
51799
51824
|
CHANNEL_PROVISIONING: (orgId) => `${API_BASE}/orgs/${orgId}/channel-provisioning`,
|
|
51800
51825
|
CHANNEL_SLACK_MANIFEST_LINK: (orgId) => `${API_BASE}/orgs/${orgId}/channel-provisioning/slack/manifest-link`,
|
|
@@ -52130,6 +52155,7 @@ var WS_EVENTS = {
|
|
|
52130
52155
|
MACHINE_BROWSER_PROFILE_LIFECYCLE: "machine.browser_profile.lifecycle",
|
|
52131
52156
|
MACHINE_BROWSER_PROFILE_VIEWER: "machine.browser_profile.viewer",
|
|
52132
52157
|
AGENT_NEW_SESSION: "agent.new_session",
|
|
52158
|
+
AGENT_COMPACT: "agent.compact",
|
|
52133
52159
|
CLIP_CREATED: "clip.created",
|
|
52134
52160
|
CLIP_REMOVED: "clip.removed",
|
|
52135
52161
|
CLIP_UPDATED: "clip.updated"
|
|
@@ -52478,8 +52504,8 @@ var SlackFilesClient = class extends AttachmentClient {
|
|
|
52478
52504
|
* raw bytes plus the vendor-declared name/MIME.
|
|
52479
52505
|
*/
|
|
52480
52506
|
async downloadSlackFile(orgId, fileId) {
|
|
52481
|
-
const
|
|
52482
|
-
const res = await this.rawAuthorizedFetch(
|
|
52507
|
+
const path14 = `${ENDPOINTS.SLACK_FILE(orgId)}?id=${encodeURIComponent(fileId)}`;
|
|
52508
|
+
const res = await this.rawAuthorizedFetch(path14, { timeoutMs: 5 * 60 * 1e3 });
|
|
52483
52509
|
let fileName = "";
|
|
52484
52510
|
const disposition = res.headers.get("content-disposition") ?? "";
|
|
52485
52511
|
const ext = /filename\*=(?:UTF-8'')?([^";]+)/i.exec(disposition);
|
|
@@ -52516,6 +52542,18 @@ var SlackFilesClient = class extends AttachmentClient {
|
|
|
52516
52542
|
}
|
|
52517
52543
|
};
|
|
52518
52544
|
|
|
52545
|
+
// ts/sdk/dist/channel-conversation-client.js
|
|
52546
|
+
var ChannelConversationClient = class extends SlackFilesClient {
|
|
52547
|
+
/**
|
|
52548
|
+
* Org-admin write of what the agent receives from a group root
|
|
52549
|
+
* (`PATCH …/channel-conversations/{id}/attention`); the agent's own path
|
|
52550
|
+
* is `setWatchLevel` with a `prll://chv_…` target.
|
|
52551
|
+
*/
|
|
52552
|
+
async updateChannelConversationAttention(orgId, conversationId, body) {
|
|
52553
|
+
return this.request("PATCH", ENDPOINTS.CHANNEL_CONVERSATION_ATTENTION(orgId, conversationId), body);
|
|
52554
|
+
}
|
|
52555
|
+
};
|
|
52556
|
+
|
|
52519
52557
|
// ts/sdk/dist/wiki-upload.js
|
|
52520
52558
|
function createWikiUploadFormData(params) {
|
|
52521
52559
|
const form = new FormData();
|
|
@@ -52597,6 +52635,26 @@ function multipartXHR(options, onProgress) {
|
|
|
52597
52635
|
});
|
|
52598
52636
|
}
|
|
52599
52637
|
|
|
52638
|
+
// ts/sdk/dist/fetch-cause.js
|
|
52639
|
+
var GENERIC_FETCH_MESSAGES = /* @__PURE__ */ new Set(["Failed to fetch", "fetch failed"]);
|
|
52640
|
+
function describeFetchCause(err) {
|
|
52641
|
+
const inner = err?.cause;
|
|
52642
|
+
for (const candidate of [inner, err]) {
|
|
52643
|
+
if (!(candidate instanceof Error))
|
|
52644
|
+
continue;
|
|
52645
|
+
const code = candidate.code;
|
|
52646
|
+
const parts = [];
|
|
52647
|
+
if (typeof code === "string" && code && !candidate.message.includes(code))
|
|
52648
|
+
parts.push(code);
|
|
52649
|
+
if (candidate.message && !GENERIC_FETCH_MESSAGES.has(candidate.message)) {
|
|
52650
|
+
parts.push(candidate.message);
|
|
52651
|
+
}
|
|
52652
|
+
if (parts.length > 0)
|
|
52653
|
+
return parts.join(" ");
|
|
52654
|
+
}
|
|
52655
|
+
return void 0;
|
|
52656
|
+
}
|
|
52657
|
+
|
|
52600
52658
|
// ts/sdk/dist/wiki-changeset.js
|
|
52601
52659
|
function normalizeWikiChangeset(changeset) {
|
|
52602
52660
|
return {
|
|
@@ -52610,7 +52668,7 @@ function normalizeWikiChangeset(changeset) {
|
|
|
52610
52668
|
}
|
|
52611
52669
|
|
|
52612
52670
|
// ts/sdk/dist/client.js
|
|
52613
|
-
var ParallClient = class _ParallClient extends
|
|
52671
|
+
var ParallClient = class _ParallClient extends ChannelConversationClient {
|
|
52614
52672
|
baseUrl;
|
|
52615
52673
|
wikiBaseUrl;
|
|
52616
52674
|
token;
|
|
@@ -52645,13 +52703,13 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52645
52703
|
}
|
|
52646
52704
|
}
|
|
52647
52705
|
const apiError = new ApiError(0, "Network request failed", "NETWORK_ERROR");
|
|
52648
|
-
|
|
52649
|
-
|
|
52650
|
-
|
|
52706
|
+
const cause = describeFetchCause(err);
|
|
52707
|
+
if (cause)
|
|
52708
|
+
apiError.extras = { cause };
|
|
52651
52709
|
return apiError;
|
|
52652
52710
|
}
|
|
52653
52711
|
/** Build headers common to all requests (auth, swimlane). */
|
|
52654
|
-
buildHeaders(
|
|
52712
|
+
buildHeaders(path14, extra) {
|
|
52655
52713
|
const headers = {
|
|
52656
52714
|
"Content-Type": "application/json",
|
|
52657
52715
|
...extra
|
|
@@ -52662,7 +52720,7 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52662
52720
|
if (this.swimlaneName) {
|
|
52663
52721
|
headers["X-Prll-Swimlane"] = this.swimlaneName;
|
|
52664
52722
|
}
|
|
52665
|
-
if (
|
|
52723
|
+
if (path14.startsWith(API_BASE)) {
|
|
52666
52724
|
const overrides = this.getFeatureFlagOverrides?.();
|
|
52667
52725
|
if (overrides)
|
|
52668
52726
|
headers["X-Prll-FF-Override"] = overrides;
|
|
@@ -52686,8 +52744,8 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52686
52744
|
* is authoritative, so wiki vs api routing can't drift from how a caller
|
|
52687
52745
|
* happens to invoke the client.
|
|
52688
52746
|
*/
|
|
52689
|
-
baseUrlFor(
|
|
52690
|
-
return
|
|
52747
|
+
baseUrlFor(path14) {
|
|
52748
|
+
return path14.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
|
|
52691
52749
|
}
|
|
52692
52750
|
setToken(token) {
|
|
52693
52751
|
this.token = token;
|
|
@@ -52714,10 +52772,10 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52714
52772
|
* REFRESH_THRESHOLD_S, refresh it **before** sending the request.
|
|
52715
52773
|
* No-op when the token is still fresh, missing, or un-parseable.
|
|
52716
52774
|
*/
|
|
52717
|
-
async ensureFreshToken(
|
|
52775
|
+
async ensureFreshToken(path14) {
|
|
52718
52776
|
if (!this.token || !this.getRefreshToken)
|
|
52719
52777
|
return;
|
|
52720
|
-
const pathSuffix =
|
|
52778
|
+
const pathSuffix = path14.replace(/^\/api\/v1/, "");
|
|
52721
52779
|
if (_ParallClient.AUTH_PATHS.has(pathSuffix))
|
|
52722
52780
|
return;
|
|
52723
52781
|
const exp = _ParallClient.decodeJwtExp(this.token);
|
|
@@ -52749,11 +52807,11 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52749
52807
|
this.refreshPromise = null;
|
|
52750
52808
|
}
|
|
52751
52809
|
}
|
|
52752
|
-
async request(method,
|
|
52810
|
+
async request(method, path14, body, query, retried = false, opts) {
|
|
52753
52811
|
if (!retried) {
|
|
52754
|
-
await this.ensureFreshToken(
|
|
52812
|
+
await this.ensureFreshToken(path14);
|
|
52755
52813
|
}
|
|
52756
|
-
let url = `${this.baseUrlFor(
|
|
52814
|
+
let url = `${this.baseUrlFor(path14)}${path14}`;
|
|
52757
52815
|
if (query) {
|
|
52758
52816
|
const params = new URLSearchParams();
|
|
52759
52817
|
for (const [key, value] of Object.entries(query)) {
|
|
@@ -52765,7 +52823,7 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52765
52823
|
if (qs)
|
|
52766
52824
|
url += `?${qs}`;
|
|
52767
52825
|
}
|
|
52768
|
-
const headers = this.buildHeaders(
|
|
52826
|
+
const headers = this.buildHeaders(path14, opts?.headers);
|
|
52769
52827
|
const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
|
|
52770
52828
|
const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
|
|
52771
52829
|
let res;
|
|
@@ -52783,12 +52841,12 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52783
52841
|
throw _ParallClient.normalizeFetchError(err);
|
|
52784
52842
|
}
|
|
52785
52843
|
if (res.status === 401) {
|
|
52786
|
-
const pathSuffix =
|
|
52844
|
+
const pathSuffix = path14.replace(/^\/api\/v1/, "");
|
|
52787
52845
|
const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
|
|
52788
52846
|
if (!retried && !isAuthPath && this.getRefreshToken) {
|
|
52789
52847
|
const refreshed = await this.tryRefresh();
|
|
52790
52848
|
if (refreshed) {
|
|
52791
|
-
return this.request(method,
|
|
52849
|
+
return this.request(method, path14, body, query, true, opts);
|
|
52792
52850
|
}
|
|
52793
52851
|
}
|
|
52794
52852
|
if (this.onTokenExpired && !isAuthPath) {
|
|
@@ -52818,18 +52876,18 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52818
52876
|
* hit the 100 MiB cap, so a longer 5-minute timeout is used so a
|
|
52819
52877
|
* 50 MiB blob on a slow connection doesn't get chopped at 15 s.
|
|
52820
52878
|
*/
|
|
52821
|
-
async multipartRequest(method,
|
|
52879
|
+
async multipartRequest(method, path14, body, retried = false, opts) {
|
|
52822
52880
|
if (!retried) {
|
|
52823
|
-
await this.ensureFreshToken(
|
|
52881
|
+
await this.ensureFreshToken(path14);
|
|
52824
52882
|
}
|
|
52825
|
-
const { "Content-Type": _drop, ...headers } = this.buildHeaders(
|
|
52883
|
+
const { "Content-Type": _drop, ...headers } = this.buildHeaders(path14);
|
|
52826
52884
|
void _drop;
|
|
52827
52885
|
const timeoutMs = opts?.timeoutMs ?? 5 * 60 * 1e3;
|
|
52828
52886
|
let res;
|
|
52829
52887
|
try {
|
|
52830
52888
|
res = await sendMultipartRequest({
|
|
52831
52889
|
method,
|
|
52832
|
-
url: `${this.baseUrlFor(
|
|
52890
|
+
url: `${this.baseUrlFor(path14)}${path14}`,
|
|
52833
52891
|
headers,
|
|
52834
52892
|
body,
|
|
52835
52893
|
timeoutMs,
|
|
@@ -52840,12 +52898,12 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
52840
52898
|
throw _ParallClient.normalizeFetchError(err);
|
|
52841
52899
|
}
|
|
52842
52900
|
if (res.status === 401) {
|
|
52843
|
-
const pathSuffix =
|
|
52901
|
+
const pathSuffix = path14.replace(/^\/api\/v1/, "");
|
|
52844
52902
|
const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
|
|
52845
52903
|
if (!retried && !isAuthPath && this.getRefreshToken) {
|
|
52846
52904
|
const refreshed = await this.tryRefresh();
|
|
52847
52905
|
if (refreshed) {
|
|
52848
|
-
return this.multipartRequest(method,
|
|
52906
|
+
return this.multipartRequest(method, path14, body, true, opts);
|
|
52849
52907
|
}
|
|
52850
52908
|
}
|
|
52851
52909
|
if (this.onTokenExpired && !isAuthPath) {
|
|
@@ -53689,8 +53747,8 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
53689
53747
|
* remote filesystem browse of a member's machine was remote device access.
|
|
53690
53748
|
* The endpoint now answers 409 LOCAL_BROWSE_NOT_SUPPORTED unconditionally;
|
|
53691
53749
|
* workspace paths are typed in (or picked on the machine's own Desktop). */
|
|
53692
|
-
async browseMachineFilesystem(orgId, machineId,
|
|
53693
|
-
return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path:
|
|
53750
|
+
async browseMachineFilesystem(orgId, machineId, path14) {
|
|
53751
|
+
return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path14 }, void 0, false, { timeoutMs: 15e3 });
|
|
53694
53752
|
}
|
|
53695
53753
|
/** Create a new machine key. Returns the raw key string (shown once) + metadata. */
|
|
53696
53754
|
async createMachineKey(orgId, machineId, name) {
|
|
@@ -54009,14 +54067,14 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
54009
54067
|
* refresh-and-retry-once, and error-envelope handling as `request` — the
|
|
54010
54068
|
* transfer primitive the SlackFilesClient domain module builds on.
|
|
54011
54069
|
*/
|
|
54012
|
-
async rawAuthorizedFetch(
|
|
54070
|
+
async rawAuthorizedFetch(path14, opts, retried = false) {
|
|
54013
54071
|
if (!retried) {
|
|
54014
|
-
await this.ensureFreshToken(
|
|
54072
|
+
await this.ensureFreshToken(path14);
|
|
54015
54073
|
}
|
|
54016
|
-
const headers = this.buildHeaders(
|
|
54074
|
+
const headers = this.buildHeaders(path14);
|
|
54017
54075
|
let res;
|
|
54018
54076
|
try {
|
|
54019
|
-
res = await fetch(`${this.baseUrlFor(
|
|
54077
|
+
res = await fetch(`${this.baseUrlFor(path14)}${path14}`, {
|
|
54020
54078
|
method: "GET",
|
|
54021
54079
|
headers,
|
|
54022
54080
|
// File transfers get the multipart-tier budget, not the 15s JSON one.
|
|
@@ -54029,7 +54087,7 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
54029
54087
|
if (!retried && this.getRefreshToken) {
|
|
54030
54088
|
const refreshed = await this.tryRefresh();
|
|
54031
54089
|
if (refreshed) {
|
|
54032
|
-
return this.rawAuthorizedFetch(
|
|
54090
|
+
return this.rawAuthorizedFetch(path14, opts, true);
|
|
54033
54091
|
}
|
|
54034
54092
|
}
|
|
54035
54093
|
this.onTokenExpired?.();
|
|
@@ -54300,12 +54358,12 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
54300
54358
|
async deleteWikiRestriction(orgId, wikiId, restrictionId) {
|
|
54301
54359
|
await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
|
|
54302
54360
|
}
|
|
54303
|
-
async getWikiAccessStatus(orgId, wikiId,
|
|
54304
|
-
return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0,
|
|
54361
|
+
async getWikiAccessStatus(orgId, wikiId, path14) {
|
|
54362
|
+
return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path14 ? { path: path14 } : void 0);
|
|
54305
54363
|
}
|
|
54306
54364
|
// ---- Wiki membership projection (who-can-access, invites, join/leave) ----
|
|
54307
|
-
async getWikiAccessPolicy(orgId, wikiId,
|
|
54308
|
-
return this.request("GET", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), void 0,
|
|
54365
|
+
async getWikiAccessPolicy(orgId, wikiId, path14 = "") {
|
|
54366
|
+
return this.request("GET", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), void 0, path14 ? { path: path14 } : void 0);
|
|
54309
54367
|
}
|
|
54310
54368
|
async putWikiAccessPolicy(orgId, wikiId, policy) {
|
|
54311
54369
|
return this.request("PUT", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), policy);
|
|
@@ -54350,14 +54408,14 @@ var ParallClient = class _ParallClient extends SlackFilesClient {
|
|
|
54350
54408
|
async getWikiCommits(orgId, wikiId, params) {
|
|
54351
54409
|
return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
|
|
54352
54410
|
}
|
|
54353
|
-
async getWikiFileCommits(orgId, wikiId,
|
|
54411
|
+
async getWikiFileCommits(orgId, wikiId, path14, params) {
|
|
54354
54412
|
return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
|
|
54355
|
-
path:
|
|
54413
|
+
path: path14,
|
|
54356
54414
|
...params
|
|
54357
54415
|
});
|
|
54358
54416
|
}
|
|
54359
|
-
async getWikiBlame(orgId, wikiId,
|
|
54360
|
-
return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path:
|
|
54417
|
+
async getWikiBlame(orgId, wikiId, path14, ref) {
|
|
54418
|
+
return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path14, ref });
|
|
54361
54419
|
}
|
|
54362
54420
|
// ---- Wiki Operations (audit log) ----
|
|
54363
54421
|
async getWikiOperations(orgId, wikiId, params) {
|
|
@@ -55143,6 +55201,23 @@ var ApiError = class extends Error {
|
|
|
55143
55201
|
this.code = code;
|
|
55144
55202
|
this.name = "ApiError";
|
|
55145
55203
|
}
|
|
55204
|
+
/**
|
|
55205
|
+
* The `String(err)` form daemon and bridge logs print. `message` stays the
|
|
55206
|
+
* human sentence the UI shows; the bracket carries the machine-readable
|
|
55207
|
+
* code, the HTTP status and the transport cause, so a NETWORK_ERROR line
|
|
55208
|
+
* says which socket failure it actually was instead of the same eight words
|
|
55209
|
+
* for every outage.
|
|
55210
|
+
*/
|
|
55211
|
+
toString() {
|
|
55212
|
+
const detail = [];
|
|
55213
|
+
if (this.code)
|
|
55214
|
+
detail.push(this.status ? `${this.code} ${this.status}` : this.code);
|
|
55215
|
+
const cause = this.extras?.cause;
|
|
55216
|
+
if (typeof cause === "string" && cause)
|
|
55217
|
+
detail.push(`cause: ${cause}`);
|
|
55218
|
+
const base = `${this.name}: ${this.message}`;
|
|
55219
|
+
return detail.length > 0 ? `${base} [${detail.join("; ")}]` : base;
|
|
55220
|
+
}
|
|
55146
55221
|
};
|
|
55147
55222
|
function buildApiError(res, rawErrorBody) {
|
|
55148
55223
|
const errorBody = rawErrorBody !== null && typeof rawErrorBody === "object" ? rawErrorBody : {};
|
|
@@ -55574,6 +55649,29 @@ function laneContextFilePath(contextDir, targetUri, threadRootId) {
|
|
|
55574
55649
|
return path2.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
|
|
55575
55650
|
}
|
|
55576
55651
|
|
|
55652
|
+
// ts/agent-core/dist/lane-target.js
|
|
55653
|
+
var PRLL_SCHEME = "prll://";
|
|
55654
|
+
var CHAT_LANE_PREFIX = "cht_";
|
|
55655
|
+
var CHANNEL_LANE_PREFIX = `${PRLL_SCHEME}chv_`;
|
|
55656
|
+
function channelLaneTargetUri(item) {
|
|
55657
|
+
return item.event_type === "channel_message" && item.target_uri?.startsWith(CHANNEL_LANE_PREFIX) ? item.target_uri : void 0;
|
|
55658
|
+
}
|
|
55659
|
+
function laneTargetId(targetUri) {
|
|
55660
|
+
return targetUri.startsWith(PRLL_SCHEME) ? targetUri.slice(PRLL_SCHEME.length) : targetUri;
|
|
55661
|
+
}
|
|
55662
|
+
function laneTargetUri(event) {
|
|
55663
|
+
if (event.type === "message") {
|
|
55664
|
+
return event.targetId.startsWith(CHAT_LANE_PREFIX) ? `${PRLL_SCHEME}${event.targetId}` : void 0;
|
|
55665
|
+
}
|
|
55666
|
+
if (event.type === "channel_message") {
|
|
55667
|
+
return event.targetUri?.startsWith(CHANNEL_LANE_PREFIX) ? event.targetUri : void 0;
|
|
55668
|
+
}
|
|
55669
|
+
return void 0;
|
|
55670
|
+
}
|
|
55671
|
+
function isTypedEvent(event) {
|
|
55672
|
+
return event.type !== "message" && laneTargetUri(event) === void 0;
|
|
55673
|
+
}
|
|
55674
|
+
|
|
55577
55675
|
// ts/agent-core/dist/lane-ledger.js
|
|
55578
55676
|
var LedgerUnsupportedError = class extends Error {
|
|
55579
55677
|
};
|
|
@@ -55606,15 +55704,16 @@ var LaneLedger = class {
|
|
|
55606
55704
|
get contextDir() {
|
|
55607
55705
|
return this.opts.contextDir;
|
|
55608
55706
|
}
|
|
55609
|
-
/**
|
|
55707
|
+
/** Message-lane events (chat, channel conversation — lane-target.ts) ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
|
|
55610
55708
|
handles(event) {
|
|
55611
|
-
return event
|
|
55709
|
+
return laneTargetUri(event) !== void 0;
|
|
55612
55710
|
}
|
|
55613
55711
|
laneKeyFor(event) {
|
|
55614
|
-
|
|
55712
|
+
const targetUri = laneTargetUri(event);
|
|
55713
|
+
if (!targetUri && event.type !== "message" && event.dispatchEventId) {
|
|
55615
55714
|
return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
|
|
55616
55715
|
}
|
|
55617
|
-
return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
|
|
55716
|
+
return laneKeyForTarget(targetUri ?? `prll://${event.targetId}`, event.threadRootId);
|
|
55618
55717
|
}
|
|
55619
55718
|
getForEvent(event) {
|
|
55620
55719
|
return this.lanes.get(this.laneKeyFor(event));
|
|
@@ -55719,7 +55818,7 @@ ${frame}` : frame;
|
|
|
55719
55818
|
let lane = this.lanes.get(laneKey);
|
|
55720
55819
|
const reused = lane != null;
|
|
55721
55820
|
if (!lane) {
|
|
55722
|
-
const targetUri = `prll://${trigger.targetId}`;
|
|
55821
|
+
const targetUri = laneTargetUri(trigger) ?? `prll://${trigger.targetId}`;
|
|
55723
55822
|
let res;
|
|
55724
55823
|
try {
|
|
55725
55824
|
res = await this.opts.client.claimDispatch(this.opts.orgId, {
|
|
@@ -55775,7 +55874,7 @@ ${frame}` : frame;
|
|
|
55775
55874
|
lane: lane.lane,
|
|
55776
55875
|
target_uri: lane.targetUri,
|
|
55777
55876
|
thread_root_id: lane.threadRootId,
|
|
55778
|
-
...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
|
|
55877
|
+
...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: ev.ackSourceType ?? "message", source_id: ev.messageId }
|
|
55779
55878
|
});
|
|
55780
55879
|
lane.folded.set(ev.messageId, res.dispatch_event_id);
|
|
55781
55880
|
this.recordFrame(lane, res.frame, [ev.messageId]);
|
|
@@ -55820,7 +55919,7 @@ ${frame}` : frame;
|
|
|
55820
55919
|
lane: lane.lane,
|
|
55821
55920
|
target_uri: lane.targetUri,
|
|
55822
55921
|
thread_root_id: lane.threadRootId,
|
|
55823
|
-
...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
|
|
55922
|
+
...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: event.ackSourceType ?? "message", source_id: event.messageId }
|
|
55824
55923
|
});
|
|
55825
55924
|
lane.folded.set(event.messageId, res.dispatch_event_id);
|
|
55826
55925
|
const covered = [event.messageId];
|
|
@@ -56416,18 +56515,29 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
|
|
|
56416
56515
|
}
|
|
56417
56516
|
}
|
|
56418
56517
|
}
|
|
56419
|
-
async function
|
|
56518
|
+
async function consumeLaneWorkItem(host, event) {
|
|
56420
56519
|
if (host.shuttingDown)
|
|
56421
56520
|
return;
|
|
56422
|
-
if (!host.tryClaimMessage(
|
|
56521
|
+
if (!host.tryClaimMessage(event.messageId))
|
|
56423
56522
|
return;
|
|
56424
|
-
if (host.dispatchState.mainBuffer.some((
|
|
56523
|
+
if (host.dispatchState.mainBuffer.some((e) => e.messageId === event.messageId))
|
|
56425
56524
|
return;
|
|
56426
|
-
if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(
|
|
56525
|
+
if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(event.targetId, event.threadRootId, event.messageId)) {
|
|
56427
56526
|
return;
|
|
56428
56527
|
}
|
|
56528
|
+
try {
|
|
56529
|
+
const dispatched = await host.handleInboundEvent(event);
|
|
56530
|
+
if (!dispatched) {
|
|
56531
|
+
host.dispatchedMessages.delete(event.messageId);
|
|
56532
|
+
}
|
|
56533
|
+
} catch (err) {
|
|
56534
|
+
host.dispatchedMessages.delete(event.messageId);
|
|
56535
|
+
throw err;
|
|
56536
|
+
}
|
|
56537
|
+
}
|
|
56538
|
+
function consumeMessageWorkItem(host, item) {
|
|
56429
56539
|
const change = splitChangeSource(item.source_id);
|
|
56430
|
-
|
|
56540
|
+
return consumeLaneWorkItem(host, {
|
|
56431
56541
|
type: "message",
|
|
56432
56542
|
targetId: item.chat_id,
|
|
56433
56543
|
targetType: "chat",
|
|
@@ -56438,17 +56548,713 @@ async function consumeMessageWorkItem(host, item) {
|
|
|
56438
56548
|
ackSourceType: "message",
|
|
56439
56549
|
ackSourceId: item.source_id,
|
|
56440
56550
|
dispatchEventId: item.id
|
|
56551
|
+
});
|
|
56552
|
+
}
|
|
56553
|
+
function consumeChannelWorkItem(host, item) {
|
|
56554
|
+
return consumeLaneWorkItem(host, {
|
|
56555
|
+
type: "channel_message",
|
|
56556
|
+
targetId: laneTargetId(item.target_uri),
|
|
56557
|
+
targetType: "channel_conversation",
|
|
56558
|
+
targetUri: item.target_uri,
|
|
56559
|
+
senderId: item.actor_id ?? "",
|
|
56560
|
+
messageId: item.source_id,
|
|
56561
|
+
threadRootId: item.thread_root_id ?? void 0,
|
|
56562
|
+
deliveryReason: item.delivery_reason ?? void 0,
|
|
56563
|
+
ackSourceType: "channel_message",
|
|
56564
|
+
ackSourceId: item.source_id,
|
|
56565
|
+
dispatchEventId: item.id
|
|
56566
|
+
});
|
|
56567
|
+
}
|
|
56568
|
+
|
|
56569
|
+
// ts/agent-core/dist/gateway-idle-compact.js
|
|
56570
|
+
var COMPACT_BUDGET_MS = 18e4;
|
|
56571
|
+
function createIdleCompactState() {
|
|
56572
|
+
return { inFlight: null, abort: null };
|
|
56573
|
+
}
|
|
56574
|
+
function sameInstant(a, b) {
|
|
56575
|
+
if (a == null || b == null)
|
|
56576
|
+
return a === b;
|
|
56577
|
+
const ta = Date.parse(a);
|
|
56578
|
+
const tb = Date.parse(b);
|
|
56579
|
+
if (Number.isNaN(ta) || Number.isNaN(tb))
|
|
56580
|
+
return a === b;
|
|
56581
|
+
return ta === tb;
|
|
56582
|
+
}
|
|
56583
|
+
function mainLaneBusy(host) {
|
|
56584
|
+
return host.idleCompact.inFlight != null || host.draining || host.dispatchState.mainDispatching || host.dispatchState.mainBuffer.length > 0;
|
|
56585
|
+
}
|
|
56586
|
+
async function handleCompactSignal(host, data) {
|
|
56587
|
+
const log2 = host.opts.log;
|
|
56588
|
+
const adapter = host.opts.dispatchAdapter;
|
|
56589
|
+
const sessionId = data?.session_id ?? "";
|
|
56590
|
+
if (!adapter.compact) {
|
|
56591
|
+
log2?.info(`agent.compact ignored: compact unsupported by adapter (session=${sessionId})`);
|
|
56592
|
+
return;
|
|
56593
|
+
}
|
|
56594
|
+
if (host.shuttingDown) {
|
|
56595
|
+
log2?.info(`agent.compact ignored: shutting down (session=${sessionId})`);
|
|
56596
|
+
return;
|
|
56597
|
+
}
|
|
56598
|
+
const bound = host.boundMainSessionId();
|
|
56599
|
+
if (!bound || !sessionId || bound !== sessionId) {
|
|
56600
|
+
log2?.info(`agent.compact ignored: session ${sessionId || "(none)"} is not the bound main session (${bound ?? "unbound"})`);
|
|
56601
|
+
return;
|
|
56602
|
+
}
|
|
56603
|
+
if (mainLaneBusy(host)) {
|
|
56604
|
+
log2?.info(`agent.compact dropped: main lane busy (session=${sessionId})`);
|
|
56605
|
+
return;
|
|
56606
|
+
}
|
|
56607
|
+
let release;
|
|
56608
|
+
host.idleCompact.inFlight = new Promise((resolve4) => {
|
|
56609
|
+
release = resolve4;
|
|
56610
|
+
});
|
|
56611
|
+
const controller = new AbortController();
|
|
56612
|
+
host.idleCompact.abort = () => controller.abort();
|
|
56613
|
+
const startedAt = Date.now();
|
|
56614
|
+
try {
|
|
56615
|
+
let session;
|
|
56616
|
+
try {
|
|
56617
|
+
session = await host.opts.client.getAgentSession(host.opts.config.org_id, host.opts.agentUserId, sessionId);
|
|
56618
|
+
} catch (err) {
|
|
56619
|
+
log2?.warn(`agent.compact dropped: session re-read failed (${String(err)})`);
|
|
56620
|
+
return;
|
|
56621
|
+
}
|
|
56622
|
+
if (session.status !== "idle" || !sameInstant(session.idle_since ?? null, data.idle_since)) {
|
|
56623
|
+
log2?.info(`agent.compact dropped: session ${sessionId} is no longer idle for this period (status=${session.status}, idle_since=${session.idle_since ?? "null"}, event=${data.idle_since})`);
|
|
56624
|
+
return;
|
|
56625
|
+
}
|
|
56626
|
+
if (host.dispatchState.mainBuffer.length > 0 || host.dispatchState.mainDispatching) {
|
|
56627
|
+
log2?.info(`agent.compact dropped: dispatch queued during session re-read (session=${sessionId})`);
|
|
56628
|
+
return;
|
|
56629
|
+
}
|
|
56630
|
+
const timer = setTimeout(() => controller.abort(), COMPACT_BUDGET_MS);
|
|
56631
|
+
timer.unref?.();
|
|
56632
|
+
try {
|
|
56633
|
+
const result = await adapter.compact({
|
|
56634
|
+
sessionKey: host.opts.runtimeKey,
|
|
56635
|
+
signal: controller.signal,
|
|
56636
|
+
log: log2
|
|
56637
|
+
});
|
|
56638
|
+
const elapsed = Date.now() - startedAt;
|
|
56639
|
+
const tokens = [
|
|
56640
|
+
result.preTokens != null ? `pre_tokens=${result.preTokens}` : null,
|
|
56641
|
+
result.postTokens != null ? `post_tokens=${result.postTokens}` : null
|
|
56642
|
+
].filter(Boolean).join(" ");
|
|
56643
|
+
const line = `idle compact ${result.status} (session=${sessionId}, elapsed_ms=${elapsed}${tokens ? ` ${tokens}` : ""}${result.detail ? `, detail=${result.detail}` : ""})`;
|
|
56644
|
+
if (result.status === "done" || result.status === "noop")
|
|
56645
|
+
log2?.info(line);
|
|
56646
|
+
else
|
|
56647
|
+
log2?.warn(line);
|
|
56648
|
+
} catch (err) {
|
|
56649
|
+
log2?.warn(`idle compact failed (session=${sessionId}, elapsed_ms=${Date.now() - startedAt}): ${String(err)}`);
|
|
56650
|
+
} finally {
|
|
56651
|
+
clearTimeout(timer);
|
|
56652
|
+
}
|
|
56653
|
+
} finally {
|
|
56654
|
+
host.idleCompact.abort = null;
|
|
56655
|
+
host.idleCompact.inFlight = null;
|
|
56656
|
+
release();
|
|
56657
|
+
if (!host.shuttingDown && !host.draining && !host.dispatchState.mainDispatching && host.dispatchState.mainBuffer.length > 0) {
|
|
56658
|
+
host.dispatchState.mainDispatching = true;
|
|
56659
|
+
host.kickMainDrain();
|
|
56660
|
+
}
|
|
56661
|
+
}
|
|
56662
|
+
}
|
|
56663
|
+
|
|
56664
|
+
// ts/agent-core/dist/redact.js
|
|
56665
|
+
function redactSecrets(s, knownValues = []) {
|
|
56666
|
+
let out = s;
|
|
56667
|
+
for (const v of knownValues) {
|
|
56668
|
+
if (typeof v === "string" && v.length >= 6)
|
|
56669
|
+
out = out.split(v).join("***");
|
|
56670
|
+
}
|
|
56671
|
+
return out.replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
|
|
56672
|
+
}
|
|
56673
|
+
function redactTurnOutcome(event, knownValues) {
|
|
56674
|
+
const redacted = { ...event };
|
|
56675
|
+
if (redacted.detail)
|
|
56676
|
+
redacted.detail = redactSecrets(redacted.detail, knownValues);
|
|
56677
|
+
if (redacted.raw) {
|
|
56678
|
+
redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
|
|
56679
|
+
k,
|
|
56680
|
+
typeof v === "string" ? redactSecrets(v, knownValues) : v
|
|
56681
|
+
]));
|
|
56682
|
+
}
|
|
56683
|
+
return redacted;
|
|
56684
|
+
}
|
|
56685
|
+
function describeTurnOutcomeFailure(outcome) {
|
|
56686
|
+
const retryNote = outcome.retryAt ? `, retry at ${outcome.retryAt}` : "";
|
|
56687
|
+
return {
|
|
56688
|
+
warn: `${outcome.outcome}${retryNote}${outcome.detail ? ` \u2014 ${outcome.detail}` : ""}`,
|
|
56689
|
+
stepMessage: `LLM turn ${outcome.outcome}${retryNote}${outcome.detail ? `: ${outcome.detail}` : ""}`
|
|
56441
56690
|
};
|
|
56691
|
+
}
|
|
56692
|
+
|
|
56693
|
+
// ts/agent-core/dist/telemetry.js
|
|
56694
|
+
init_esm();
|
|
56695
|
+
var import_api_logs = __toESM(require_src(), 1);
|
|
56696
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
56697
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
56698
|
+
import * as path3 from "node:path";
|
|
56699
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
56700
|
+
var initialized = false;
|
|
56701
|
+
var shutdownFn = null;
|
|
56702
|
+
var tracer = null;
|
|
56703
|
+
var dispatchCounter = null;
|
|
56704
|
+
var dispatchDuration = null;
|
|
56705
|
+
var missingReplyCounter = null;
|
|
56706
|
+
var turnTokensCounter = null;
|
|
56707
|
+
var turnCostCounter = null;
|
|
56708
|
+
var otelLogger = null;
|
|
56709
|
+
function resolveTargetType(targetId) {
|
|
56710
|
+
if (targetId.startsWith("cht_"))
|
|
56711
|
+
return "chat";
|
|
56712
|
+
if (targetId.startsWith("tsk_"))
|
|
56713
|
+
return "task";
|
|
56714
|
+
if (targetId.startsWith("sch_"))
|
|
56715
|
+
return "schedule";
|
|
56716
|
+
return "unknown";
|
|
56717
|
+
}
|
|
56718
|
+
var PRODUCTION_API_HOSTS = /* @__PURE__ */ new Set(["api.parall.com"]);
|
|
56719
|
+
var STAGING_API_HOSTS = /* @__PURE__ */ new Set(["api.staging.prll.sh"]);
|
|
56720
|
+
function resolveTelemetryEnvironment(apiUrl, override = process.env.PRLL_SERVER_ENV) {
|
|
56721
|
+
const forced = override?.trim();
|
|
56722
|
+
if (forced)
|
|
56723
|
+
return forced;
|
|
56724
|
+
let host = "";
|
|
56442
56725
|
try {
|
|
56443
|
-
|
|
56444
|
-
|
|
56445
|
-
|
|
56726
|
+
host = apiUrl ? new URL(apiUrl).hostname.toLowerCase() : "";
|
|
56727
|
+
} catch {
|
|
56728
|
+
host = "";
|
|
56729
|
+
}
|
|
56730
|
+
if (PRODUCTION_API_HOSTS.has(host))
|
|
56731
|
+
return "production";
|
|
56732
|
+
if (STAGING_API_HOSTS.has(host))
|
|
56733
|
+
return "staging";
|
|
56734
|
+
return "development";
|
|
56735
|
+
}
|
|
56736
|
+
function resolveServiceVersion(importMetaUrl) {
|
|
56737
|
+
const fallback = process.env.npm_package_version || "unknown";
|
|
56738
|
+
let dir;
|
|
56739
|
+
try {
|
|
56740
|
+
dir = path3.dirname(fileURLToPath2(importMetaUrl));
|
|
56741
|
+
} catch {
|
|
56742
|
+
return fallback;
|
|
56743
|
+
}
|
|
56744
|
+
for (const candidate of [path3.join(dir, "manifest.json"), path3.join(dir, "..", "package.json")]) {
|
|
56745
|
+
try {
|
|
56746
|
+
const parsed = JSON.parse(readFileSync2(candidate, "utf-8"));
|
|
56747
|
+
if (typeof parsed.version === "string" && parsed.version.trim()) {
|
|
56748
|
+
return parsed.version.trim();
|
|
56749
|
+
}
|
|
56750
|
+
} catch {
|
|
56751
|
+
}
|
|
56752
|
+
}
|
|
56753
|
+
return fallback;
|
|
56754
|
+
}
|
|
56755
|
+
var DIAG_THROTTLE_MS = 6e4;
|
|
56756
|
+
var DIAG_THROTTLE_KEYS = 200;
|
|
56757
|
+
function createThrottledDiagLogger(now = Date.now) {
|
|
56758
|
+
const lastAt = /* @__PURE__ */ new Map();
|
|
56759
|
+
const describe = (a) => {
|
|
56760
|
+
if (a instanceof Error)
|
|
56761
|
+
return a.message;
|
|
56762
|
+
if (a && typeof a === "object" && typeof a.message === "string") {
|
|
56763
|
+
return a.message;
|
|
56764
|
+
}
|
|
56765
|
+
if (typeof a === "string" && a.startsWith("{")) {
|
|
56766
|
+
try {
|
|
56767
|
+
const parsed = JSON.parse(a);
|
|
56768
|
+
if (typeof parsed.message === "string")
|
|
56769
|
+
return parsed.message;
|
|
56770
|
+
} catch {
|
|
56771
|
+
}
|
|
56446
56772
|
}
|
|
56773
|
+
return String(a);
|
|
56774
|
+
};
|
|
56775
|
+
const emit = (level, args) => {
|
|
56776
|
+
const msg = args.map(describe).join(" ");
|
|
56777
|
+
const key = `${level}:${msg.slice(0, 160)}`;
|
|
56778
|
+
const at = now();
|
|
56779
|
+
const prev = lastAt.get(key);
|
|
56780
|
+
if (prev !== void 0 && at - prev < DIAG_THROTTLE_MS)
|
|
56781
|
+
return;
|
|
56782
|
+
if (lastAt.size >= DIAG_THROTTLE_KEYS)
|
|
56783
|
+
lastAt.clear();
|
|
56784
|
+
lastAt.set(key, at);
|
|
56785
|
+
console.warn(`${new Date(at).toISOString()} [telemetry] otel ${level}: ${msg}`);
|
|
56786
|
+
};
|
|
56787
|
+
return {
|
|
56788
|
+
verbose: () => {
|
|
56789
|
+
},
|
|
56790
|
+
debug: () => {
|
|
56791
|
+
},
|
|
56792
|
+
info: () => {
|
|
56793
|
+
},
|
|
56794
|
+
warn: (...args) => emit("warn", args),
|
|
56795
|
+
error: (...args) => emit("error", args)
|
|
56796
|
+
};
|
|
56797
|
+
}
|
|
56798
|
+
async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
|
|
56799
|
+
const noopHandle = { shutdown: async () => {
|
|
56800
|
+
} };
|
|
56801
|
+
const apiUrl = opts.apiUrl ?? process.env.PRLL_API_URL;
|
|
56802
|
+
const apiKey = opts.apiKey ?? process.env.PRLL_API_KEY;
|
|
56803
|
+
if (!apiUrl || !apiKey) {
|
|
56804
|
+
console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] disabled: no API url/key resolved for ${serviceName} \u2014 nothing will reach SigNoz`);
|
|
56805
|
+
return noopHandle;
|
|
56806
|
+
}
|
|
56807
|
+
const environment = opts.environment ?? resolveTelemetryEnvironment(apiUrl);
|
|
56808
|
+
const serviceVersion = opts.serviceVersion ?? process.env.npm_package_version ?? "unknown";
|
|
56809
|
+
try {
|
|
56810
|
+
const otelEndpoint = apiUrl.replace(/\/$/, "") + "/otel";
|
|
56811
|
+
if (!initialized)
|
|
56812
|
+
diag2.setLogger(createThrottledDiagLogger(), DiagLogLevel.WARN);
|
|
56813
|
+
const { OTLPTraceExporter } = await Promise.resolve().then(() => __toESM(require_src6(), 1));
|
|
56814
|
+
const { OTLPMetricExporter } = await Promise.resolve().then(() => __toESM(require_src8(), 1));
|
|
56815
|
+
const { OTLPLogExporter } = await Promise.resolve().then(() => __toESM(require_src9(), 1));
|
|
56816
|
+
const { NodeTracerProvider, BatchSpanProcessor } = await Promise.resolve().then(() => __toESM(require_src14(), 1));
|
|
56817
|
+
const { MeterProvider, PeriodicExportingMetricReader } = await Promise.resolve().then(() => __toESM(require_src4(), 1));
|
|
56818
|
+
const { LoggerProvider, BatchLogRecordProcessor } = await Promise.resolve().then(() => __toESM(require_src15(), 1));
|
|
56819
|
+
const { Resource } = await Promise.resolve().then(() => __toESM(require_src3(), 1));
|
|
56820
|
+
const resource = new Resource({
|
|
56821
|
+
"service.name": serviceName,
|
|
56822
|
+
"service.version": serviceVersion,
|
|
56823
|
+
"deployment.environment.name": environment,
|
|
56824
|
+
"parall.runtime_type": runtimeType,
|
|
56825
|
+
"parall.agent_id": process.env.PRLL_AGENT_ID || "",
|
|
56826
|
+
"parall.machine_id": process.env.PRLL_MACHINE_ID || "",
|
|
56827
|
+
"parall.org_id": process.env.PRLL_ORG_ID || "",
|
|
56828
|
+
"parall.daemon_mode": process.env.PRLL_DAEMON_MODE === "1"
|
|
56829
|
+
});
|
|
56830
|
+
const authHeaders = { Authorization: `Bearer ${apiKey}` };
|
|
56831
|
+
const traceExporter = new OTLPTraceExporter({
|
|
56832
|
+
url: `${otelEndpoint}/v1/traces`,
|
|
56833
|
+
headers: authHeaders
|
|
56834
|
+
});
|
|
56835
|
+
const tracerProvider = new NodeTracerProvider({ resource });
|
|
56836
|
+
tracerProvider.addSpanProcessor(new BatchSpanProcessor(traceExporter));
|
|
56837
|
+
tracerProvider.register();
|
|
56838
|
+
const metricExporter = new OTLPMetricExporter({
|
|
56839
|
+
url: `${otelEndpoint}/v1/metrics`,
|
|
56840
|
+
headers: authHeaders
|
|
56841
|
+
});
|
|
56842
|
+
const metricReader = new PeriodicExportingMetricReader({
|
|
56843
|
+
exporter: metricExporter,
|
|
56844
|
+
exportIntervalMillis: 15e3
|
|
56845
|
+
});
|
|
56846
|
+
const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
|
|
56847
|
+
metrics.setGlobalMeterProvider(meterProvider);
|
|
56848
|
+
const logExporter = new OTLPLogExporter({
|
|
56849
|
+
url: `${otelEndpoint}/v1/logs`,
|
|
56850
|
+
headers: authHeaders
|
|
56851
|
+
});
|
|
56852
|
+
const loggerProvider = new LoggerProvider({ resource });
|
|
56853
|
+
loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter));
|
|
56854
|
+
const meter = metrics.getMeter("parall.agent");
|
|
56855
|
+
tracer = trace.getTracer("parall.agent");
|
|
56856
|
+
otelLogger = loggerProvider.getLogger("parall.agent");
|
|
56857
|
+
dispatchCounter = meter.createCounter("parall.dispatch.count", {
|
|
56858
|
+
description: "Number of dispatch cycles completed"
|
|
56859
|
+
});
|
|
56860
|
+
dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
|
|
56861
|
+
description: "Dispatch cycle duration in milliseconds",
|
|
56862
|
+
unit: "ms"
|
|
56863
|
+
});
|
|
56864
|
+
missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
|
|
56865
|
+
description: "Dispatches where agent produced text but sent no reply message"
|
|
56866
|
+
});
|
|
56867
|
+
turnTokensCounter = meter.createCounter("parall.turn.tokens", {
|
|
56868
|
+
description: "LLM tokens consumed per turn, by kind (input/output/cache_read/cache_creation)"
|
|
56869
|
+
});
|
|
56870
|
+
turnCostCounter = meter.createCounter("parall.turn.cost_usd", {
|
|
56871
|
+
description: "LLM cost per turn in USD (when the runtime reports it)"
|
|
56872
|
+
});
|
|
56873
|
+
initialized = true;
|
|
56874
|
+
console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] exporting ${serviceName} v${serviceVersion} env=${environment} to ${otelEndpoint}`);
|
|
56875
|
+
shutdownFn = async () => {
|
|
56876
|
+
await tracerProvider.forceFlush();
|
|
56877
|
+
await meterProvider.forceFlush();
|
|
56878
|
+
await loggerProvider.forceFlush();
|
|
56879
|
+
await tracerProvider.shutdown();
|
|
56880
|
+
await meterProvider.shutdown();
|
|
56881
|
+
await loggerProvider.shutdown();
|
|
56882
|
+
};
|
|
56883
|
+
return {
|
|
56884
|
+
shutdown: async () => {
|
|
56885
|
+
if (shutdownFn)
|
|
56886
|
+
await shutdownFn();
|
|
56887
|
+
}
|
|
56888
|
+
};
|
|
56447
56889
|
} catch (err) {
|
|
56448
|
-
|
|
56449
|
-
|
|
56890
|
+
console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] init failed for ${serviceName}, running without export: ${String(err)}`);
|
|
56891
|
+
return noopHandle;
|
|
56450
56892
|
}
|
|
56451
56893
|
}
|
|
56894
|
+
function startDispatchSpan(event, runtimeType, sessionKey) {
|
|
56895
|
+
if (!initialized || !tracer)
|
|
56896
|
+
return null;
|
|
56897
|
+
return tracer.startSpan("parall.dispatch", {
|
|
56898
|
+
attributes: {
|
|
56899
|
+
"dispatch.target_type": resolveTargetType(event.targetId),
|
|
56900
|
+
"dispatch.event_type": event.type,
|
|
56901
|
+
"dispatch.runtime_type": runtimeType,
|
|
56902
|
+
"dispatch.session_key": sessionKey,
|
|
56903
|
+
"dispatch.message_id": event.messageId,
|
|
56904
|
+
"dispatch.target_id": event.targetId
|
|
56905
|
+
}
|
|
56906
|
+
});
|
|
56907
|
+
}
|
|
56908
|
+
function endDispatchSpan(span, metricsSnapshot, error, turnOutcome) {
|
|
56909
|
+
if (!span)
|
|
56910
|
+
return;
|
|
56911
|
+
if (metricsSnapshot) {
|
|
56912
|
+
span.setAttributes({
|
|
56913
|
+
"dispatch.deliver_text_chunks": metricsSnapshot.deliver_text_chunks,
|
|
56914
|
+
"dispatch.deliver_text_chars": metricsSnapshot.deliver_text_chars,
|
|
56915
|
+
"dispatch.message_send_attempts": metricsSnapshot.message_send_attempts,
|
|
56916
|
+
"dispatch.message_send_successes": metricsSnapshot.message_send_successes,
|
|
56917
|
+
"dispatch.no_reply_called": metricsSnapshot.no_reply_called,
|
|
56918
|
+
"dispatch.tool_call_count": metricsSnapshot.tool_call_count,
|
|
56919
|
+
"dispatch.duration_ms": Date.now() - metricsSnapshot.started_at
|
|
56920
|
+
});
|
|
56921
|
+
}
|
|
56922
|
+
if (turnOutcome) {
|
|
56923
|
+
span.setAttribute("dispatch.outcome", turnOutcome.outcome);
|
|
56924
|
+
if (turnOutcome.detail)
|
|
56925
|
+
span.setAttribute("dispatch.outcome_detail", turnOutcome.detail);
|
|
56926
|
+
if (turnOutcome.retryAt)
|
|
56927
|
+
span.setAttribute("dispatch.retry_at", turnOutcome.retryAt);
|
|
56928
|
+
if (turnOutcome.model)
|
|
56929
|
+
span.setAttribute("dispatch.model", turnOutcome.model);
|
|
56930
|
+
if (turnOutcome.raw && Object.keys(turnOutcome.raw).length > 0) {
|
|
56931
|
+
try {
|
|
56932
|
+
span.setAttribute("dispatch.outcome_raw", JSON.stringify(turnOutcome.raw));
|
|
56933
|
+
} catch {
|
|
56934
|
+
}
|
|
56935
|
+
}
|
|
56936
|
+
const u = turnOutcome.usage;
|
|
56937
|
+
if (u) {
|
|
56938
|
+
if (u.inputTokens !== void 0)
|
|
56939
|
+
span.setAttribute("dispatch.tokens_input", u.inputTokens);
|
|
56940
|
+
if (u.outputTokens !== void 0)
|
|
56941
|
+
span.setAttribute("dispatch.tokens_output", u.outputTokens);
|
|
56942
|
+
if (u.cacheReadTokens !== void 0)
|
|
56943
|
+
span.setAttribute("dispatch.tokens_cache_read", u.cacheReadTokens);
|
|
56944
|
+
if (u.cacheCreationTokens !== void 0)
|
|
56945
|
+
span.setAttribute("dispatch.tokens_cache_creation", u.cacheCreationTokens);
|
|
56946
|
+
if (u.costUsd !== void 0)
|
|
56947
|
+
span.setAttribute("dispatch.cost_usd", u.costUsd);
|
|
56948
|
+
if (u.durationApiMs !== void 0)
|
|
56949
|
+
span.setAttribute("dispatch.duration_api_ms", u.durationApiMs);
|
|
56950
|
+
}
|
|
56951
|
+
}
|
|
56952
|
+
if (error) {
|
|
56953
|
+
const safe = redactSecrets(String(error));
|
|
56954
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: safe });
|
|
56955
|
+
span.recordException(error instanceof Error ? new Error(safe) : new Error(safe));
|
|
56956
|
+
}
|
|
56957
|
+
span.end();
|
|
56958
|
+
}
|
|
56959
|
+
function recordDispatchMetric(event, runtimeType, durationMs, outcome = "ok") {
|
|
56960
|
+
if (!initialized)
|
|
56961
|
+
return;
|
|
56962
|
+
const attrs = {
|
|
56963
|
+
target_type: resolveTargetType(event.targetId),
|
|
56964
|
+
event_type: event.type,
|
|
56965
|
+
runtime_type: runtimeType,
|
|
56966
|
+
outcome
|
|
56967
|
+
};
|
|
56968
|
+
dispatchCounter?.add(1, attrs);
|
|
56969
|
+
dispatchDuration?.record(durationMs, attrs);
|
|
56970
|
+
}
|
|
56971
|
+
function recordMissingReply(runtimeType, outcome = "ok") {
|
|
56972
|
+
if (!initialized)
|
|
56973
|
+
return;
|
|
56974
|
+
missingReplyCounter?.add(1, { runtime_type: runtimeType, outcome });
|
|
56975
|
+
}
|
|
56976
|
+
function recordTurnUsage(usage, runtimeType) {
|
|
56977
|
+
if (!initialized || !usage)
|
|
56978
|
+
return;
|
|
56979
|
+
const kinds = [
|
|
56980
|
+
["input", usage.inputTokens],
|
|
56981
|
+
["output", usage.outputTokens],
|
|
56982
|
+
["cache_read", usage.cacheReadTokens],
|
|
56983
|
+
["cache_creation", usage.cacheCreationTokens]
|
|
56984
|
+
];
|
|
56985
|
+
for (const [kind, value] of kinds) {
|
|
56986
|
+
if (value !== void 0 && value > 0) {
|
|
56987
|
+
turnTokensCounter?.add(value, { kind, runtime_type: runtimeType });
|
|
56988
|
+
}
|
|
56989
|
+
}
|
|
56990
|
+
if (usage.costUsd !== void 0 && usage.costUsd > 0) {
|
|
56991
|
+
turnCostCounter?.add(usage.costUsd, { runtime_type: runtimeType });
|
|
56992
|
+
}
|
|
56993
|
+
}
|
|
56994
|
+
var sessionKeyStorage = new AsyncLocalStorage();
|
|
56995
|
+
function runWithSessionKey(sessionKey, fn) {
|
|
56996
|
+
return sessionKeyStorage.run(sessionKey, fn);
|
|
56997
|
+
}
|
|
56998
|
+
function createOtelLogger(layer, prefix) {
|
|
56999
|
+
const ts = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
57000
|
+
const emit = (severity, msg) => {
|
|
57001
|
+
if (!otelLogger)
|
|
57002
|
+
return;
|
|
57003
|
+
const severityNumber = severity === "ERROR" ? import_api_logs.SeverityNumber.ERROR : severity === "WARN" ? import_api_logs.SeverityNumber.WARN : import_api_logs.SeverityNumber.INFO;
|
|
57004
|
+
const attrs = { "log.layer": layer, "log.prefix": prefix };
|
|
57005
|
+
const sk = sessionKeyStorage.getStore();
|
|
57006
|
+
if (sk)
|
|
57007
|
+
attrs["session.key"] = sk;
|
|
57008
|
+
otelLogger.emit({
|
|
57009
|
+
severityNumber,
|
|
57010
|
+
severityText: severity,
|
|
57011
|
+
body: msg,
|
|
57012
|
+
attributes: attrs
|
|
57013
|
+
});
|
|
57014
|
+
};
|
|
57015
|
+
return {
|
|
57016
|
+
info: (msg) => {
|
|
57017
|
+
console.log(`${ts()} [${prefix}] ${msg}`);
|
|
57018
|
+
emit("INFO", msg);
|
|
57019
|
+
},
|
|
57020
|
+
warn: (msg) => {
|
|
57021
|
+
console.warn(`${ts()} [${prefix}] ${msg}`);
|
|
57022
|
+
emit("WARN", msg);
|
|
57023
|
+
},
|
|
57024
|
+
error: (msg) => {
|
|
57025
|
+
console.error(`${ts()} [${prefix}] ${msg}`);
|
|
57026
|
+
emit("ERROR", msg);
|
|
57027
|
+
},
|
|
57028
|
+
child: (sub) => createOtelLogger(layer, `${prefix}:${sub}`)
|
|
57029
|
+
};
|
|
57030
|
+
}
|
|
57031
|
+
|
|
57032
|
+
// ts/agent-core/dist/gateway-runtime-turns.js
|
|
57033
|
+
var UNTARGETED_STEP = { target_type: "" };
|
|
57034
|
+
function handleRuntimeActivity(host, event) {
|
|
57035
|
+
const sessionKey = event.kind === "turn" ? event.turn.sessionKey : event.sessionKey;
|
|
57036
|
+
const label = event.kind === "turn" ? `runtime-initiated turn ${event.turn.groupKey} on ${sessionKey}` : `runtime child session close for ${sessionKey}`;
|
|
57037
|
+
const prior = host.runtimeActivityChains.get(sessionKey) ?? Promise.resolve();
|
|
57038
|
+
host.inFlightRuntimeTurns += 1;
|
|
57039
|
+
const next = prior.then(() => event.kind === "turn" ? runRuntimeTurn(host, event.turn) : closeRuntimeChildSession(host, event.sessionKey, event.reason)).catch((err) => {
|
|
57040
|
+
host.opts.log?.warn(`${label} failed: ${String(err)}`);
|
|
57041
|
+
}).finally(() => {
|
|
57042
|
+
if (host.runtimeActivityChains.get(sessionKey) === next) {
|
|
57043
|
+
host.runtimeActivityChains.delete(sessionKey);
|
|
57044
|
+
}
|
|
57045
|
+
host.inFlightRuntimeTurns -= 1;
|
|
57046
|
+
host.notifyDrainWaiters();
|
|
57047
|
+
});
|
|
57048
|
+
host.runtimeActivityChains.set(sessionKey, next);
|
|
57049
|
+
}
|
|
57050
|
+
async function runRuntimeTurn(host, turn) {
|
|
57051
|
+
const { sessionKey, groupKey } = turn;
|
|
57052
|
+
const log2 = host.opts.log;
|
|
57053
|
+
const startedAtMs = Date.now();
|
|
57054
|
+
const deadline = host.dispatchInactivityDeadlines.start(`${sessionKey}#runtime:${groupKey}`, host.DISPATCH_DEADLINE_MS, () => {
|
|
57055
|
+
log2?.warn(`runtime-initiated turn ${groupKey} on ${sessionKey} inactive for ${host.DISPATCH_DEADLINE_MS}ms; detaching`);
|
|
57056
|
+
try {
|
|
57057
|
+
turn.detach("inactivity deadline exceeded");
|
|
57058
|
+
} catch (err) {
|
|
57059
|
+
log2?.warn(`detach threw for runtime turn ${groupKey}: ${String(err)}`);
|
|
57060
|
+
}
|
|
57061
|
+
});
|
|
57062
|
+
turn.onActivity(deadline.touch);
|
|
57063
|
+
const contextFilePath = host.opts.contextFilePathForSession?.(sessionKey);
|
|
57064
|
+
let binding = host.sessionBindings.get(sessionKey);
|
|
57065
|
+
let turnHandle;
|
|
57066
|
+
let outcomeEvent;
|
|
57067
|
+
let stepCount = 0;
|
|
57068
|
+
let droppedWithoutBinding = 0;
|
|
57069
|
+
const ensureBegun = async () => {
|
|
57070
|
+
if (!binding || turnHandle)
|
|
57071
|
+
return;
|
|
57072
|
+
turnHandle = await host.sessionLifecycle.beginTurn(binding.agentSessionId);
|
|
57073
|
+
await createRuntimeInputStep(host, binding.agentSessionId, turn);
|
|
57074
|
+
};
|
|
57075
|
+
try {
|
|
57076
|
+
for await (const runtimeEvent of turn.events) {
|
|
57077
|
+
deadline.touch();
|
|
57078
|
+
if (runtimeEvent.type === "runtime_session") {
|
|
57079
|
+
try {
|
|
57080
|
+
binding = await host.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath);
|
|
57081
|
+
} catch (err) {
|
|
57082
|
+
log2?.warn(`runtime-initiated turn ${groupKey}: session binding failed for ${sessionKey}: ${String(err)}`);
|
|
57083
|
+
binding = void 0;
|
|
57084
|
+
}
|
|
57085
|
+
continue;
|
|
57086
|
+
}
|
|
57087
|
+
if (!binding) {
|
|
57088
|
+
droppedWithoutBinding += 1;
|
|
57089
|
+
continue;
|
|
57090
|
+
}
|
|
57091
|
+
if (runtimeEvent.type === "turn_outcome") {
|
|
57092
|
+
const outcome = redactTurnOutcome(runtimeEvent, [host.opts.config.api_key]);
|
|
57093
|
+
outcomeEvent = outcome;
|
|
57094
|
+
if (outcome.outcome === "ok")
|
|
57095
|
+
continue;
|
|
57096
|
+
const failure = describeTurnOutcomeFailure(outcome);
|
|
57097
|
+
log2?.warn(`runtime-initiated turn outcome: ${failure.warn}`);
|
|
57098
|
+
await ensureBegun();
|
|
57099
|
+
await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, { type: "error", message: failure.stepMessage, groupKey }, void 0, contextFilePath);
|
|
57100
|
+
continue;
|
|
57101
|
+
}
|
|
57102
|
+
await ensureBegun();
|
|
57103
|
+
stepCount += 1;
|
|
57104
|
+
await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, runtimeEvent, void 0, contextFilePath);
|
|
57105
|
+
}
|
|
57106
|
+
} catch (err) {
|
|
57107
|
+
log2?.warn(`runtime-initiated turn ${groupKey} on ${sessionKey} failed: ${String(err)}`);
|
|
57108
|
+
if (binding && turnHandle && !host.isSessionNotLiveError(err)) {
|
|
57109
|
+
try {
|
|
57110
|
+
await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, {
|
|
57111
|
+
type: "error",
|
|
57112
|
+
message: `Runtime turn failed: ${String(err)}`,
|
|
57113
|
+
groupKey
|
|
57114
|
+
});
|
|
57115
|
+
} catch {
|
|
57116
|
+
}
|
|
57117
|
+
}
|
|
57118
|
+
} finally {
|
|
57119
|
+
deadline.dispose();
|
|
57120
|
+
if (turnHandle)
|
|
57121
|
+
host.sessionLifecycle.finishTurn(turnHandle);
|
|
57122
|
+
if (contextFilePath)
|
|
57123
|
+
host.updateContextFileStepId(contextFilePath, null);
|
|
57124
|
+
recordTurnUsage(outcomeEvent?.usage, host.opts.runtimeType);
|
|
57125
|
+
log2?.info(`runtime-initiated turn ${groupKey} on ${sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}): steps=${stepCount} outcome=${outcomeEvent?.outcome ?? "ok"} ${Date.now() - startedAtMs}ms${droppedWithoutBinding > 0 ? ` (no session binding: ${droppedWithoutBinding} event(s) not persisted)` : ""}`);
|
|
57126
|
+
}
|
|
57127
|
+
}
|
|
57128
|
+
async function createRuntimeInputStep(host, sessionId, turn) {
|
|
57129
|
+
const trigger = turn.trigger;
|
|
57130
|
+
const sourceId = trigger.kind === "background_task" ? trigger.taskId : trigger.kind === "subagent" ? trigger.threadId : void 0;
|
|
57131
|
+
const summary = trigger.kind === "background_task" ? trigger.summary ?? trigger.description ?? "Background task finished" : trigger.kind === "subagent" ? `Subagent ${trigger.nickname ?? trigger.threadId}${trigger.role ? ` (${trigger.role})` : ""}` : trigger.reason ?? "Runtime-initiated turn";
|
|
57132
|
+
await host.stepPersister.persist(sessionId, "input", {
|
|
57133
|
+
step_type: "input",
|
|
57134
|
+
target_type: UNTARGETED_STEP.target_type,
|
|
57135
|
+
idempotency_key: `input:rt:${turn.groupKey}`,
|
|
57136
|
+
content: {
|
|
57137
|
+
trigger_type: trigger.kind,
|
|
57138
|
+
trigger_ref: trigger.kind === "background_task" ? { ...trigger.taskId ? { task_id: trigger.taskId } : {} } : trigger.kind === "subagent" ? {
|
|
57139
|
+
thread_id: trigger.threadId,
|
|
57140
|
+
...trigger.parentThreadId ? { parent_thread_id: trigger.parentThreadId } : {}
|
|
57141
|
+
} : {},
|
|
57142
|
+
source_type: trigger.kind,
|
|
57143
|
+
...sourceId ? { source_id: sourceId } : {},
|
|
57144
|
+
summary: summary.substring(0, 200),
|
|
57145
|
+
sent_at: turn.startedAt
|
|
57146
|
+
}
|
|
57147
|
+
});
|
|
57148
|
+
}
|
|
57149
|
+
async function closeRuntimeChildSession(host, sessionKey, reason) {
|
|
57150
|
+
if (sessionKey === host.opts.runtimeKey)
|
|
57151
|
+
return;
|
|
57152
|
+
const binding = host.sessionBindings.get(sessionKey);
|
|
57153
|
+
if (!binding)
|
|
57154
|
+
return;
|
|
57155
|
+
host.opts.log?.info(`closing runtime child session ${binding.agentSessionId} (${sessionKey}): ${reason}`);
|
|
57156
|
+
const outcome = await host.forkFinalizer.finalize(binding.agentSessionId, () => {
|
|
57157
|
+
if (host.sessionBindings.get(sessionKey) === binding) {
|
|
57158
|
+
host.sessionBindings.delete(sessionKey);
|
|
57159
|
+
}
|
|
57160
|
+
});
|
|
57161
|
+
if (outcome !== "closed" && outcome !== "stale") {
|
|
57162
|
+
host.opts.log?.warn(`runtime child session ${binding.agentSessionId} close ended ${outcome}`);
|
|
57163
|
+
}
|
|
57164
|
+
}
|
|
57165
|
+
|
|
57166
|
+
// ts/agent-core/dist/gateway-drain.js
|
|
57167
|
+
var DrainGate = class {
|
|
57168
|
+
isDrained;
|
|
57169
|
+
waiters = [];
|
|
57170
|
+
constructor(isDrained) {
|
|
57171
|
+
this.isDrained = isDrained;
|
|
57172
|
+
}
|
|
57173
|
+
/** Wake every waiter whose predicate now holds. */
|
|
57174
|
+
notify() {
|
|
57175
|
+
if (this.waiters.length === 0)
|
|
57176
|
+
return;
|
|
57177
|
+
const ready = this.waiters.filter((waiter) => waiter.predicate());
|
|
57178
|
+
if (ready.length === 0)
|
|
57179
|
+
return;
|
|
57180
|
+
this.waiters = this.waiters.filter((waiter) => !ready.includes(waiter));
|
|
57181
|
+
for (const waiter of ready)
|
|
57182
|
+
waiter.resolve();
|
|
57183
|
+
}
|
|
57184
|
+
wait(deadlineMs, predicate = this.isDrained) {
|
|
57185
|
+
if (predicate())
|
|
57186
|
+
return Promise.resolve();
|
|
57187
|
+
return new Promise((resolve4) => {
|
|
57188
|
+
const waiter = { predicate, resolve: () => finish() };
|
|
57189
|
+
const finish = () => {
|
|
57190
|
+
clearTimeout(timer);
|
|
57191
|
+
clearInterval(poll);
|
|
57192
|
+
this.waiters = this.waiters.filter((entry) => entry !== waiter);
|
|
57193
|
+
resolve4();
|
|
57194
|
+
};
|
|
57195
|
+
const timer = setTimeout(finish, deadlineMs);
|
|
57196
|
+
const poll = setInterval(() => {
|
|
57197
|
+
if (predicate())
|
|
57198
|
+
finish();
|
|
57199
|
+
}, 500);
|
|
57200
|
+
poll.unref?.();
|
|
57201
|
+
this.waiters.push(waiter);
|
|
57202
|
+
});
|
|
57203
|
+
}
|
|
57204
|
+
};
|
|
57205
|
+
|
|
57206
|
+
// ts/agent-core/dist/gateway-session-binding.js
|
|
57207
|
+
var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
|
|
57208
|
+
async function bindRuntimeSession(host, sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2) {
|
|
57209
|
+
const runtimeLaneKey = runtimeEvent.runtimeLaneKey || sessionKey;
|
|
57210
|
+
const existing = host.sessionBindings.get(sessionKey);
|
|
57211
|
+
if (existing && existing.runtimeLaneKey === runtimeLaneKey && existing.runtimeSessionId === runtimeEvent.runtimeSessionId) {
|
|
57212
|
+
return existing;
|
|
57213
|
+
}
|
|
57214
|
+
const parentSessionId = sessionKey === host.opts.runtimeKey ? void 0 : (runtimeEvent.parentSessionKey ? host.sessionBindings.get(runtimeEvent.parentSessionKey)?.agentSessionId : void 0) ?? host.sessionBindings.get(host.opts.runtimeKey)?.agentSessionId;
|
|
57215
|
+
const runtimeRef = {
|
|
57216
|
+
...host.opts.runtimeRef ?? {},
|
|
57217
|
+
...runtimeEvent.runtimeRef ?? {}
|
|
57218
|
+
};
|
|
57219
|
+
const session = await host.opts.client.createAgentSession(host.opts.config.org_id, host.opts.agentUserId, {
|
|
57220
|
+
runtime_type: host.opts.runtimeType,
|
|
57221
|
+
runtime_key: runtimeLaneKey,
|
|
57222
|
+
runtime_lane_key: runtimeLaneKey,
|
|
57223
|
+
runtime_session_id: runtimeEvent.runtimeSessionId,
|
|
57224
|
+
parent_session_id: parentSessionId,
|
|
57225
|
+
runtime_ref: Object.keys(runtimeRef).length > 0 ? runtimeRef : void 0
|
|
57226
|
+
});
|
|
57227
|
+
if (!LIVE_SESSION_STATUSES.has(session.status)) {
|
|
57228
|
+
host.opts.log?.warn?.(`createAgentSession returned terminal session ${session.id} (${session.status}), resetting runtime for ${sessionKey}`);
|
|
57229
|
+
host.sessionBindings.delete(sessionKey);
|
|
57230
|
+
try {
|
|
57231
|
+
await host.opts.onSessionStale?.(sessionKey);
|
|
57232
|
+
} catch (e) {
|
|
57233
|
+
host.opts.log?.warn?.(`onSessionStale failed: ${e}`);
|
|
57234
|
+
}
|
|
57235
|
+
host.opts.log?.info?.(`stale session self-heal complete for ${sessionKey} \u2014 next dispatch will create a fresh session`);
|
|
57236
|
+
throw new Error(`Agent session ${session.id} is terminal (${session.status})`);
|
|
57237
|
+
}
|
|
57238
|
+
const binding = {
|
|
57239
|
+
sessionKey,
|
|
57240
|
+
agentSessionId: session.id,
|
|
57241
|
+
runtimeLaneKey,
|
|
57242
|
+
runtimeSessionId: runtimeEvent.runtimeSessionId,
|
|
57243
|
+
parentSessionId
|
|
57244
|
+
};
|
|
57245
|
+
host.sessionBindings.set(sessionKey, binding);
|
|
57246
|
+
if (sessionKey === host.opts.runtimeKey) {
|
|
57247
|
+
host.activeSessionId = session.id;
|
|
57248
|
+
}
|
|
57249
|
+
if (contextFilePath) {
|
|
57250
|
+
host.updateContextFileSessionId(contextFilePath, session.id);
|
|
57251
|
+
}
|
|
57252
|
+
if (laneContextFilePath2) {
|
|
57253
|
+
host.updateContextFileSessionId(laneContextFilePath2, session.id);
|
|
57254
|
+
}
|
|
57255
|
+
await host.opts.onSessionBinding?.(binding);
|
|
57256
|
+
return binding;
|
|
57257
|
+
}
|
|
56452
57258
|
|
|
56453
57259
|
// ts/agent-core/dist/dispatch-inactivity-deadline.js
|
|
56454
57260
|
var DispatchInactivityDeadline = class {
|
|
@@ -56456,6 +57262,7 @@ var DispatchInactivityDeadline = class {
|
|
|
56456
57262
|
onExpire;
|
|
56457
57263
|
onDispose;
|
|
56458
57264
|
timer = null;
|
|
57265
|
+
lastActivityAt = 0;
|
|
56459
57266
|
expired = false;
|
|
56460
57267
|
disposed = false;
|
|
56461
57268
|
constructor(timeoutMs, onExpire, onDispose) {
|
|
@@ -56463,17 +57270,30 @@ var DispatchInactivityDeadline = class {
|
|
|
56463
57270
|
this.onExpire = onExpire;
|
|
56464
57271
|
this.onDispose = onDispose;
|
|
56465
57272
|
}
|
|
57273
|
+
/**
|
|
57274
|
+
* Called on every runtime frame: records the time only. The single timer
|
|
57275
|
+
* checks the idle span when it fires and re-arms for the remainder, so
|
|
57276
|
+
* touching never allocates.
|
|
57277
|
+
*/
|
|
56466
57278
|
touch = () => {
|
|
56467
57279
|
if (this.timeoutMs <= 0 || this.expired || this.disposed)
|
|
56468
57280
|
return;
|
|
56469
|
-
|
|
56470
|
-
|
|
57281
|
+
this.lastActivityAt = Date.now();
|
|
57282
|
+
if (!this.timer)
|
|
57283
|
+
this.arm(this.timeoutMs);
|
|
57284
|
+
};
|
|
57285
|
+
arm(delayMs) {
|
|
56471
57286
|
this.timer = setTimeout(() => {
|
|
56472
57287
|
this.timer = null;
|
|
57288
|
+
const idleMs = Date.now() - this.lastActivityAt;
|
|
57289
|
+
if (idleMs < this.timeoutMs) {
|
|
57290
|
+
this.arm(this.timeoutMs - idleMs);
|
|
57291
|
+
return;
|
|
57292
|
+
}
|
|
56473
57293
|
this.expired = true;
|
|
56474
57294
|
this.onExpire();
|
|
56475
|
-
},
|
|
56476
|
-
}
|
|
57295
|
+
}, delayMs);
|
|
57296
|
+
}
|
|
56477
57297
|
dispose() {
|
|
56478
57298
|
if (this.disposed)
|
|
56479
57299
|
return;
|
|
@@ -56523,28 +57343,6 @@ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
|
|
|
56523
57343
|
return strategy(event, state);
|
|
56524
57344
|
}
|
|
56525
57345
|
|
|
56526
|
-
// ts/agent-core/dist/redact.js
|
|
56527
|
-
function redactSecrets(s, knownValues = []) {
|
|
56528
|
-
let out = s;
|
|
56529
|
-
for (const v of knownValues) {
|
|
56530
|
-
if (typeof v === "string" && v.length >= 6)
|
|
56531
|
-
out = out.split(v).join("***");
|
|
56532
|
-
}
|
|
56533
|
-
return out.replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
|
|
56534
|
-
}
|
|
56535
|
-
function redactTurnOutcome(event, knownValues) {
|
|
56536
|
-
const redacted = { ...event };
|
|
56537
|
-
if (redacted.detail)
|
|
56538
|
-
redacted.detail = redactSecrets(redacted.detail, knownValues);
|
|
56539
|
-
if (redacted.raw) {
|
|
56540
|
-
redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
|
|
56541
|
-
k,
|
|
56542
|
-
typeof v === "string" ? redactSecrets(v, knownValues) : v
|
|
56543
|
-
]));
|
|
56544
|
-
}
|
|
56545
|
-
return redacted;
|
|
56546
|
-
}
|
|
56547
|
-
|
|
56548
57346
|
// ts/agent-core/dist/step-retry-queue.js
|
|
56549
57347
|
var DEFAULT_RETRY_DELAYS_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
|
|
56550
57348
|
async function raceWithDeadline(work, ms) {
|
|
@@ -56925,25 +57723,31 @@ var SessionLifecycleCoordinator = class {
|
|
|
56925
57723
|
return { sessionId, generation: 0 };
|
|
56926
57724
|
const entry = this.upsert(sessionId);
|
|
56927
57725
|
entry.desired = "active";
|
|
56928
|
-
entry.
|
|
57726
|
+
if (triggerMessageId !== void 0 || entry.openTurns.size === 0) {
|
|
57727
|
+
entry.triggerMessageId = triggerMessageId;
|
|
57728
|
+
}
|
|
56929
57729
|
const generation = entry.generation;
|
|
57730
|
+
entry.openTurns.add(generation);
|
|
56930
57731
|
const settled = this.waitFor(entry, generation);
|
|
56931
57732
|
this.pump(sessionId);
|
|
56932
57733
|
await settled;
|
|
56933
57734
|
return { sessionId, generation };
|
|
56934
57735
|
}
|
|
56935
57736
|
/**
|
|
56936
|
-
* Declare the turn finished.
|
|
56937
|
-
*
|
|
56938
|
-
*
|
|
57737
|
+
* Declare the turn finished. Only the LAST open turn's finish moves the
|
|
57738
|
+
* session to idle; a handle that is not open (already finished, superseded
|
|
57739
|
+
* by a close, or from a reclaimed entry) is ignored. Reconciliation runs
|
|
57740
|
+
* detached.
|
|
56939
57741
|
*/
|
|
56940
57742
|
finishTurn(handle) {
|
|
56941
57743
|
if (this.disposed)
|
|
56942
57744
|
return;
|
|
56943
57745
|
const entry = this.sessions.get(handle.sessionId);
|
|
56944
|
-
if (!entry || entry.dropped
|
|
57746
|
+
if (!entry || entry.dropped)
|
|
56945
57747
|
return;
|
|
56946
|
-
if (entry.
|
|
57748
|
+
if (!entry.openTurns.delete(handle.generation))
|
|
57749
|
+
return;
|
|
57750
|
+
if (entry.desired === "closed" || entry.openTurns.size > 0)
|
|
56947
57751
|
return;
|
|
56948
57752
|
entry.desired = "idle";
|
|
56949
57753
|
entry.retryAttempt = 0;
|
|
@@ -56966,6 +57770,7 @@ var SessionLifecycleCoordinator = class {
|
|
|
56966
57770
|
const entry = this.upsert(sessionId);
|
|
56967
57771
|
entry.desired = "closed";
|
|
56968
57772
|
entry.triggerMessageId = void 0;
|
|
57773
|
+
entry.openTurns.clear();
|
|
56969
57774
|
const generation = entry.generation;
|
|
56970
57775
|
const terminal = new Promise((resolve4) => {
|
|
56971
57776
|
entry.closeWaiters.push({ generation, resolve: resolve4 });
|
|
@@ -56985,6 +57790,7 @@ var SessionLifecycleCoordinator = class {
|
|
|
56985
57790
|
if (!entry)
|
|
56986
57791
|
return;
|
|
56987
57792
|
entry.dropped = true;
|
|
57793
|
+
entry.openTurns.clear();
|
|
56988
57794
|
this.cancelRetry(entry);
|
|
56989
57795
|
this.resolveWaiters(entry, Number.POSITIVE_INFINITY, "dropped");
|
|
56990
57796
|
this.reclaim(sessionId, entry);
|
|
@@ -57047,7 +57853,8 @@ var SessionLifecycleCoordinator = class {
|
|
|
57047
57853
|
retryAttempt: 0,
|
|
57048
57854
|
waiters: [],
|
|
57049
57855
|
closeWaiters: [],
|
|
57050
|
-
dropped: false
|
|
57856
|
+
dropped: false,
|
|
57857
|
+
openTurns: /* @__PURE__ */ new Set()
|
|
57051
57858
|
};
|
|
57052
57859
|
this.sessions.set(sessionId, entry);
|
|
57053
57860
|
}
|
|
@@ -57379,257 +58186,7 @@ function recordToolCall(sessionKey) {
|
|
|
57379
58186
|
m.tool_call_count++;
|
|
57380
58187
|
}
|
|
57381
58188
|
|
|
57382
|
-
// ts/agent-core/dist/telemetry.js
|
|
57383
|
-
init_esm();
|
|
57384
|
-
var import_api_logs = __toESM(require_src(), 1);
|
|
57385
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
57386
|
-
var initialized = false;
|
|
57387
|
-
var shutdownFn = null;
|
|
57388
|
-
var tracer = null;
|
|
57389
|
-
var dispatchCounter = null;
|
|
57390
|
-
var dispatchDuration = null;
|
|
57391
|
-
var missingReplyCounter = null;
|
|
57392
|
-
var turnTokensCounter = null;
|
|
57393
|
-
var turnCostCounter = null;
|
|
57394
|
-
var otelLogger = null;
|
|
57395
|
-
function resolveTargetType(targetId) {
|
|
57396
|
-
if (targetId.startsWith("cht_"))
|
|
57397
|
-
return "chat";
|
|
57398
|
-
if (targetId.startsWith("tsk_"))
|
|
57399
|
-
return "task";
|
|
57400
|
-
if (targetId.startsWith("sch_"))
|
|
57401
|
-
return "schedule";
|
|
57402
|
-
return "unknown";
|
|
57403
|
-
}
|
|
57404
|
-
async function initAgentTelemetry(serviceName, runtimeType) {
|
|
57405
|
-
const noopHandle = { shutdown: async () => {
|
|
57406
|
-
} };
|
|
57407
|
-
const apiUrl = process.env.PRLL_API_URL;
|
|
57408
|
-
const apiKey = process.env.PRLL_API_KEY;
|
|
57409
|
-
if (!apiUrl || !apiKey) {
|
|
57410
|
-
return noopHandle;
|
|
57411
|
-
}
|
|
57412
|
-
try {
|
|
57413
|
-
const otelEndpoint = apiUrl.replace(/\/$/, "") + "/otel";
|
|
57414
|
-
const { OTLPTraceExporter } = await Promise.resolve().then(() => __toESM(require_src6(), 1));
|
|
57415
|
-
const { OTLPMetricExporter } = await Promise.resolve().then(() => __toESM(require_src8(), 1));
|
|
57416
|
-
const { OTLPLogExporter } = await Promise.resolve().then(() => __toESM(require_src9(), 1));
|
|
57417
|
-
const { NodeTracerProvider, BatchSpanProcessor } = await Promise.resolve().then(() => __toESM(require_src14(), 1));
|
|
57418
|
-
const { MeterProvider, PeriodicExportingMetricReader } = await Promise.resolve().then(() => __toESM(require_src4(), 1));
|
|
57419
|
-
const { LoggerProvider, BatchLogRecordProcessor } = await Promise.resolve().then(() => __toESM(require_src15(), 1));
|
|
57420
|
-
const { Resource } = await Promise.resolve().then(() => __toESM(require_src3(), 1));
|
|
57421
|
-
const resource = new Resource({
|
|
57422
|
-
"service.name": serviceName,
|
|
57423
|
-
"service.version": process.env.npm_package_version || "unknown",
|
|
57424
|
-
"deployment.environment.name": process.env.PRLL_SERVER_ENV || process.env.NODE_ENV || "development",
|
|
57425
|
-
"parall.runtime_type": runtimeType,
|
|
57426
|
-
"parall.agent_id": process.env.PRLL_AGENT_ID || "",
|
|
57427
|
-
"parall.machine_id": process.env.PRLL_MACHINE_ID || "",
|
|
57428
|
-
"parall.org_id": process.env.PRLL_ORG_ID || "",
|
|
57429
|
-
"parall.daemon_mode": process.env.PRLL_DAEMON_MODE === "1"
|
|
57430
|
-
});
|
|
57431
|
-
const authHeaders = { Authorization: `Bearer ${apiKey}` };
|
|
57432
|
-
const traceExporter = new OTLPTraceExporter({
|
|
57433
|
-
url: `${otelEndpoint}/v1/traces`,
|
|
57434
|
-
headers: authHeaders
|
|
57435
|
-
});
|
|
57436
|
-
const tracerProvider = new NodeTracerProvider({ resource });
|
|
57437
|
-
tracerProvider.addSpanProcessor(new BatchSpanProcessor(traceExporter));
|
|
57438
|
-
tracerProvider.register();
|
|
57439
|
-
const metricExporter = new OTLPMetricExporter({
|
|
57440
|
-
url: `${otelEndpoint}/v1/metrics`,
|
|
57441
|
-
headers: authHeaders
|
|
57442
|
-
});
|
|
57443
|
-
const metricReader = new PeriodicExportingMetricReader({
|
|
57444
|
-
exporter: metricExporter,
|
|
57445
|
-
exportIntervalMillis: 15e3
|
|
57446
|
-
});
|
|
57447
|
-
const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
|
|
57448
|
-
metrics.setGlobalMeterProvider(meterProvider);
|
|
57449
|
-
const logExporter = new OTLPLogExporter({
|
|
57450
|
-
url: `${otelEndpoint}/v1/logs`,
|
|
57451
|
-
headers: authHeaders
|
|
57452
|
-
});
|
|
57453
|
-
const loggerProvider = new LoggerProvider({ resource });
|
|
57454
|
-
loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter));
|
|
57455
|
-
const meter = metrics.getMeter("parall.agent");
|
|
57456
|
-
tracer = trace.getTracer("parall.agent");
|
|
57457
|
-
otelLogger = loggerProvider.getLogger("parall.agent");
|
|
57458
|
-
dispatchCounter = meter.createCounter("parall.dispatch.count", {
|
|
57459
|
-
description: "Number of dispatch cycles completed"
|
|
57460
|
-
});
|
|
57461
|
-
dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
|
|
57462
|
-
description: "Dispatch cycle duration in milliseconds",
|
|
57463
|
-
unit: "ms"
|
|
57464
|
-
});
|
|
57465
|
-
missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
|
|
57466
|
-
description: "Dispatches where agent produced text but sent no reply message"
|
|
57467
|
-
});
|
|
57468
|
-
turnTokensCounter = meter.createCounter("parall.turn.tokens", {
|
|
57469
|
-
description: "LLM tokens consumed per turn, by kind (input/output/cache_read/cache_creation)"
|
|
57470
|
-
});
|
|
57471
|
-
turnCostCounter = meter.createCounter("parall.turn.cost_usd", {
|
|
57472
|
-
description: "LLM cost per turn in USD (when the runtime reports it)"
|
|
57473
|
-
});
|
|
57474
|
-
initialized = true;
|
|
57475
|
-
shutdownFn = async () => {
|
|
57476
|
-
await tracerProvider.forceFlush();
|
|
57477
|
-
await meterProvider.forceFlush();
|
|
57478
|
-
await loggerProvider.forceFlush();
|
|
57479
|
-
await tracerProvider.shutdown();
|
|
57480
|
-
await meterProvider.shutdown();
|
|
57481
|
-
await loggerProvider.shutdown();
|
|
57482
|
-
};
|
|
57483
|
-
return {
|
|
57484
|
-
shutdown: async () => {
|
|
57485
|
-
if (shutdownFn)
|
|
57486
|
-
await shutdownFn();
|
|
57487
|
-
}
|
|
57488
|
-
};
|
|
57489
|
-
} catch {
|
|
57490
|
-
return noopHandle;
|
|
57491
|
-
}
|
|
57492
|
-
}
|
|
57493
|
-
function startDispatchSpan(event, runtimeType, sessionKey) {
|
|
57494
|
-
if (!initialized || !tracer)
|
|
57495
|
-
return null;
|
|
57496
|
-
return tracer.startSpan("parall.dispatch", {
|
|
57497
|
-
attributes: {
|
|
57498
|
-
"dispatch.target_type": resolveTargetType(event.targetId),
|
|
57499
|
-
"dispatch.event_type": event.type,
|
|
57500
|
-
"dispatch.runtime_type": runtimeType,
|
|
57501
|
-
"dispatch.session_key": sessionKey,
|
|
57502
|
-
"dispatch.message_id": event.messageId,
|
|
57503
|
-
"dispatch.target_id": event.targetId
|
|
57504
|
-
}
|
|
57505
|
-
});
|
|
57506
|
-
}
|
|
57507
|
-
function endDispatchSpan(span, metricsSnapshot, error, turnOutcome) {
|
|
57508
|
-
if (!span)
|
|
57509
|
-
return;
|
|
57510
|
-
if (metricsSnapshot) {
|
|
57511
|
-
span.setAttributes({
|
|
57512
|
-
"dispatch.deliver_text_chunks": metricsSnapshot.deliver_text_chunks,
|
|
57513
|
-
"dispatch.deliver_text_chars": metricsSnapshot.deliver_text_chars,
|
|
57514
|
-
"dispatch.message_send_attempts": metricsSnapshot.message_send_attempts,
|
|
57515
|
-
"dispatch.message_send_successes": metricsSnapshot.message_send_successes,
|
|
57516
|
-
"dispatch.no_reply_called": metricsSnapshot.no_reply_called,
|
|
57517
|
-
"dispatch.tool_call_count": metricsSnapshot.tool_call_count,
|
|
57518
|
-
"dispatch.duration_ms": Date.now() - metricsSnapshot.started_at
|
|
57519
|
-
});
|
|
57520
|
-
}
|
|
57521
|
-
if (turnOutcome) {
|
|
57522
|
-
span.setAttribute("dispatch.outcome", turnOutcome.outcome);
|
|
57523
|
-
if (turnOutcome.detail)
|
|
57524
|
-
span.setAttribute("dispatch.outcome_detail", turnOutcome.detail);
|
|
57525
|
-
if (turnOutcome.retryAt)
|
|
57526
|
-
span.setAttribute("dispatch.retry_at", turnOutcome.retryAt);
|
|
57527
|
-
if (turnOutcome.model)
|
|
57528
|
-
span.setAttribute("dispatch.model", turnOutcome.model);
|
|
57529
|
-
if (turnOutcome.raw && Object.keys(turnOutcome.raw).length > 0) {
|
|
57530
|
-
try {
|
|
57531
|
-
span.setAttribute("dispatch.outcome_raw", JSON.stringify(turnOutcome.raw));
|
|
57532
|
-
} catch {
|
|
57533
|
-
}
|
|
57534
|
-
}
|
|
57535
|
-
const u = turnOutcome.usage;
|
|
57536
|
-
if (u) {
|
|
57537
|
-
if (u.inputTokens !== void 0)
|
|
57538
|
-
span.setAttribute("dispatch.tokens_input", u.inputTokens);
|
|
57539
|
-
if (u.outputTokens !== void 0)
|
|
57540
|
-
span.setAttribute("dispatch.tokens_output", u.outputTokens);
|
|
57541
|
-
if (u.cacheReadTokens !== void 0)
|
|
57542
|
-
span.setAttribute("dispatch.tokens_cache_read", u.cacheReadTokens);
|
|
57543
|
-
if (u.cacheCreationTokens !== void 0)
|
|
57544
|
-
span.setAttribute("dispatch.tokens_cache_creation", u.cacheCreationTokens);
|
|
57545
|
-
if (u.costUsd !== void 0)
|
|
57546
|
-
span.setAttribute("dispatch.cost_usd", u.costUsd);
|
|
57547
|
-
if (u.durationApiMs !== void 0)
|
|
57548
|
-
span.setAttribute("dispatch.duration_api_ms", u.durationApiMs);
|
|
57549
|
-
}
|
|
57550
|
-
}
|
|
57551
|
-
if (error) {
|
|
57552
|
-
const safe = redactSecrets(String(error));
|
|
57553
|
-
span.setStatus({ code: SpanStatusCode.ERROR, message: safe });
|
|
57554
|
-
span.recordException(error instanceof Error ? new Error(safe) : new Error(safe));
|
|
57555
|
-
}
|
|
57556
|
-
span.end();
|
|
57557
|
-
}
|
|
57558
|
-
function recordDispatchMetric(event, runtimeType, durationMs, outcome = "ok") {
|
|
57559
|
-
if (!initialized)
|
|
57560
|
-
return;
|
|
57561
|
-
const attrs = {
|
|
57562
|
-
target_type: resolveTargetType(event.targetId),
|
|
57563
|
-
event_type: event.type,
|
|
57564
|
-
runtime_type: runtimeType,
|
|
57565
|
-
outcome
|
|
57566
|
-
};
|
|
57567
|
-
dispatchCounter?.add(1, attrs);
|
|
57568
|
-
dispatchDuration?.record(durationMs, attrs);
|
|
57569
|
-
}
|
|
57570
|
-
function recordMissingReply(runtimeType, outcome = "ok") {
|
|
57571
|
-
if (!initialized)
|
|
57572
|
-
return;
|
|
57573
|
-
missingReplyCounter?.add(1, { runtime_type: runtimeType, outcome });
|
|
57574
|
-
}
|
|
57575
|
-
function recordTurnUsage(usage, runtimeType) {
|
|
57576
|
-
if (!initialized || !usage)
|
|
57577
|
-
return;
|
|
57578
|
-
const kinds = [
|
|
57579
|
-
["input", usage.inputTokens],
|
|
57580
|
-
["output", usage.outputTokens],
|
|
57581
|
-
["cache_read", usage.cacheReadTokens],
|
|
57582
|
-
["cache_creation", usage.cacheCreationTokens]
|
|
57583
|
-
];
|
|
57584
|
-
for (const [kind, value] of kinds) {
|
|
57585
|
-
if (value !== void 0 && value > 0) {
|
|
57586
|
-
turnTokensCounter?.add(value, { kind, runtime_type: runtimeType });
|
|
57587
|
-
}
|
|
57588
|
-
}
|
|
57589
|
-
if (usage.costUsd !== void 0 && usage.costUsd > 0) {
|
|
57590
|
-
turnCostCounter?.add(usage.costUsd, { runtime_type: runtimeType });
|
|
57591
|
-
}
|
|
57592
|
-
}
|
|
57593
|
-
var sessionKeyStorage = new AsyncLocalStorage();
|
|
57594
|
-
function runWithSessionKey(sessionKey, fn) {
|
|
57595
|
-
return sessionKeyStorage.run(sessionKey, fn);
|
|
57596
|
-
}
|
|
57597
|
-
function createOtelLogger(layer, prefix) {
|
|
57598
|
-
const ts = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
57599
|
-
const emit = (severity, msg) => {
|
|
57600
|
-
if (!otelLogger)
|
|
57601
|
-
return;
|
|
57602
|
-
const severityNumber = severity === "ERROR" ? import_api_logs.SeverityNumber.ERROR : severity === "WARN" ? import_api_logs.SeverityNumber.WARN : import_api_logs.SeverityNumber.INFO;
|
|
57603
|
-
const attrs = { "log.layer": layer, "log.prefix": prefix };
|
|
57604
|
-
const sk = sessionKeyStorage.getStore();
|
|
57605
|
-
if (sk)
|
|
57606
|
-
attrs["session.key"] = sk;
|
|
57607
|
-
otelLogger.emit({
|
|
57608
|
-
severityNumber,
|
|
57609
|
-
severityText: severity,
|
|
57610
|
-
body: msg,
|
|
57611
|
-
attributes: attrs
|
|
57612
|
-
});
|
|
57613
|
-
};
|
|
57614
|
-
return {
|
|
57615
|
-
info: (msg) => {
|
|
57616
|
-
console.log(`${ts()} [${prefix}] ${msg}`);
|
|
57617
|
-
emit("INFO", msg);
|
|
57618
|
-
},
|
|
57619
|
-
warn: (msg) => {
|
|
57620
|
-
console.warn(`${ts()} [${prefix}] ${msg}`);
|
|
57621
|
-
emit("WARN", msg);
|
|
57622
|
-
},
|
|
57623
|
-
error: (msg) => {
|
|
57624
|
-
console.error(`${ts()} [${prefix}] ${msg}`);
|
|
57625
|
-
emit("ERROR", msg);
|
|
57626
|
-
},
|
|
57627
|
-
child: (sub) => createOtelLogger(layer, `${prefix}:${sub}`)
|
|
57628
|
-
};
|
|
57629
|
-
}
|
|
57630
|
-
|
|
57631
58189
|
// ts/agent-core/dist/gateway-base.js
|
|
57632
|
-
var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
|
|
57633
58190
|
var TYPED_EVENT_KINDS = {
|
|
57634
58191
|
task_assign: { type: "task", ackSourceType: "task_activity" },
|
|
57635
58192
|
task_update: { type: "task", ackSourceType: "task_activity" },
|
|
@@ -57771,6 +58328,8 @@ var ParallAgentGateway = class {
|
|
|
57771
58328
|
heartbeatTimer = null;
|
|
57772
58329
|
lastHeartbeatAt = Date.now();
|
|
57773
58330
|
draining = false;
|
|
58331
|
+
// Idle auto-compact hold on the main lane (gateway-idle-compact.ts).
|
|
58332
|
+
idleCompact = createIdleCompactState();
|
|
57774
58333
|
/**
|
|
57775
58334
|
* Typed WorkItem ids whose drain group left the buffer but has not settled
|
|
57776
58335
|
* yet. isBufferedTypedWorkItem treats them as still buffered — a re-drive
|
|
@@ -57784,7 +58343,14 @@ var ParallAgentGateway = class {
|
|
|
57784
58343
|
// before tearing down the WS; see handleTermination caller.
|
|
57785
58344
|
shuttingDown = false;
|
|
57786
58345
|
inFlightDispatches = 0;
|
|
57787
|
-
|
|
58346
|
+
drainGate = new DrainGate(() => this.isDrained());
|
|
58347
|
+
// Turns the runtime started on its own (RuntimeInitiatedTurn) currently
|
|
58348
|
+
// being persisted — drained by shutdown() alongside dispatches.
|
|
58349
|
+
inFlightRuntimeTurns = 0;
|
|
58350
|
+
// Per-sessionKey serialization of runtime activity: a child session's
|
|
58351
|
+
// close must run after every turn on it finished persisting.
|
|
58352
|
+
runtimeActivityChains = /* @__PURE__ */ new Map();
|
|
58353
|
+
unsubscribeRuntimeActivity;
|
|
57788
58354
|
pendingRestartNotification = null;
|
|
57789
58355
|
laneLedger;
|
|
57790
58356
|
stepPersister;
|
|
@@ -57805,7 +58371,7 @@ var ParallAgentGateway = class {
|
|
|
57805
58371
|
// for fork routing decisions.
|
|
57806
58372
|
mainCurrentGroupKey;
|
|
57807
58373
|
DISPATCHED_MESSAGES_CAP = 5e3;
|
|
57808
|
-
// SHUTDOWN_DEADLINE_MS is read by
|
|
58374
|
+
// SHUTDOWN_DEADLINE_MS is read by the drain gate wait via the configured value
|
|
57809
58375
|
// below — kept as instance state so per-runtime configs can override it
|
|
57810
58376
|
// (see parseShutdownDeadlineMs and runtime entrypoints).
|
|
57811
58377
|
SHUTDOWN_DEADLINE_MS;
|
|
@@ -57826,6 +58392,7 @@ var ParallAgentGateway = class {
|
|
|
57826
58392
|
this.SHUTDOWN_DEADLINE_MS = opts.shutdownDeadlineMs ?? 6e4;
|
|
57827
58393
|
this.FORK_DEADLINE_MS = opts.forkDeadlineMs ?? 2 * 60 * 6e4;
|
|
57828
58394
|
this.DISPATCH_DEADLINE_MS = opts.dispatchDeadlineMs ?? 20 * 6e4;
|
|
58395
|
+
this.unsubscribeRuntimeActivity = opts.dispatchAdapter.subscribeRuntimeActivity?.((event) => this.handleRuntimeActivity(event));
|
|
57829
58396
|
this.stepPersister = new StepPersister({
|
|
57830
58397
|
client: opts.client,
|
|
57831
58398
|
orgId: opts.config.org_id,
|
|
@@ -57887,6 +58454,9 @@ var ParallAgentGateway = class {
|
|
|
57887
58454
|
this.opts.log?.warn(`onNewSession callback failed: ${String(err)}`);
|
|
57888
58455
|
}
|
|
57889
58456
|
});
|
|
58457
|
+
ws.on("agent.compact", (data) => {
|
|
58458
|
+
void this.handleCompactSignal(data);
|
|
58459
|
+
});
|
|
57890
58460
|
ws.on("recovery.overflow", () => {
|
|
57891
58461
|
this.opts.log?.warn(`recovery.overflow \u2014 triggering full catch-up`);
|
|
57892
58462
|
this.catchUpFromDispatch().catch((err) => this.opts.log?.warn(`overflow catch-up failed: ${String(err)}`));
|
|
@@ -58035,7 +58605,7 @@ var ParallAgentGateway = class {
|
|
|
58035
58605
|
if (this.usesLaneLedger(event)) {
|
|
58036
58606
|
return this.laneLedger.laneKeyFor(event);
|
|
58037
58607
|
}
|
|
58038
|
-
return event
|
|
58608
|
+
return isTypedEvent(event) ? `typed:${event.targetId}` : event.targetId;
|
|
58039
58609
|
}
|
|
58040
58610
|
// Lane-flow protocols live in gateway-lane-flow.ts; these thin delegates
|
|
58041
58611
|
// keep call sites and tests on the class surface.
|
|
@@ -58127,8 +58697,7 @@ var ParallAgentGateway = class {
|
|
|
58127
58697
|
}
|
|
58128
58698
|
});
|
|
58129
58699
|
}
|
|
58130
|
-
async createRuntimeStep(sessionId,
|
|
58131
|
-
const target = resolveStepTarget(event);
|
|
58700
|
+
async createRuntimeStep(sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
|
|
58132
58701
|
switch (runtimeEvent.type) {
|
|
58133
58702
|
case "thinking":
|
|
58134
58703
|
await this.stepPersister.persist(sessionId, "thinking", {
|
|
@@ -58218,14 +58787,15 @@ var ParallAgentGateway = class {
|
|
|
58218
58787
|
target_id: target.target_id,
|
|
58219
58788
|
idempotency_key: randomUUID(),
|
|
58220
58789
|
content: buildErrorStepContent(runtimeEvent.message),
|
|
58221
|
-
projection: false
|
|
58790
|
+
projection: false,
|
|
58791
|
+
group_key: runtimeEvent.groupKey
|
|
58222
58792
|
});
|
|
58223
58793
|
break;
|
|
58224
58794
|
}
|
|
58225
58795
|
}
|
|
58226
58796
|
writeContextFile(filePath, ctx) {
|
|
58227
58797
|
try {
|
|
58228
|
-
fs3.mkdirSync(
|
|
58798
|
+
fs3.mkdirSync(path4.dirname(filePath), { recursive: true });
|
|
58229
58799
|
fs3.writeFileSync(filePath, JSON.stringify(ctx), "utf8");
|
|
58230
58800
|
} catch (err) {
|
|
58231
58801
|
this.opts.log?.warn(`failed to write context file ${filePath}: ${String(err)}`);
|
|
@@ -58254,7 +58824,7 @@ var ParallAgentGateway = class {
|
|
|
58254
58824
|
/** @deprecated Use writeContextFile / updateContextFileStepId. */
|
|
58255
58825
|
writeStepIdFile(filePath, stepId) {
|
|
58256
58826
|
try {
|
|
58257
|
-
fs3.mkdirSync(
|
|
58827
|
+
fs3.mkdirSync(path4.dirname(filePath), { recursive: true });
|
|
58258
58828
|
fs3.writeFileSync(filePath, stepId, "utf8");
|
|
58259
58829
|
} catch (err) {
|
|
58260
58830
|
this.opts.log?.warn(`failed to write step id file ${filePath}: ${String(err)}`);
|
|
@@ -58272,55 +58842,8 @@ var ParallAgentGateway = class {
|
|
|
58272
58842
|
await this.createInputStep(sessionId, event);
|
|
58273
58843
|
}
|
|
58274
58844
|
}
|
|
58275
|
-
|
|
58276
|
-
|
|
58277
|
-
const existing = this.sessionBindings.get(sessionKey);
|
|
58278
|
-
if (existing && existing.runtimeLaneKey === runtimeLaneKey && existing.runtimeSessionId === runtimeEvent.runtimeSessionId) {
|
|
58279
|
-
return existing;
|
|
58280
|
-
}
|
|
58281
|
-
const parentSessionId = sessionKey === this.opts.runtimeKey ? void 0 : this.sessionBindings.get(this.opts.runtimeKey)?.agentSessionId;
|
|
58282
|
-
const runtimeRef = {
|
|
58283
|
-
...this.opts.runtimeRef ?? {},
|
|
58284
|
-
...runtimeEvent.runtimeRef ?? {}
|
|
58285
|
-
};
|
|
58286
|
-
const session = await this.opts.client.createAgentSession(this.opts.config.org_id, this.opts.agentUserId, {
|
|
58287
|
-
runtime_type: this.opts.runtimeType,
|
|
58288
|
-
runtime_key: runtimeLaneKey,
|
|
58289
|
-
runtime_lane_key: runtimeLaneKey,
|
|
58290
|
-
runtime_session_id: runtimeEvent.runtimeSessionId,
|
|
58291
|
-
parent_session_id: parentSessionId,
|
|
58292
|
-
runtime_ref: Object.keys(runtimeRef).length > 0 ? runtimeRef : void 0
|
|
58293
|
-
});
|
|
58294
|
-
if (!LIVE_SESSION_STATUSES.has(session.status)) {
|
|
58295
|
-
this.opts.log?.warn?.(`createAgentSession returned terminal session ${session.id} (${session.status}), resetting runtime for ${sessionKey}`);
|
|
58296
|
-
this.sessionBindings.delete(sessionKey);
|
|
58297
|
-
try {
|
|
58298
|
-
await this.opts.onSessionStale?.(sessionKey);
|
|
58299
|
-
} catch (e) {
|
|
58300
|
-
this.opts.log?.warn?.(`onSessionStale failed: ${e}`);
|
|
58301
|
-
}
|
|
58302
|
-
this.opts.log?.info?.(`stale session self-heal complete for ${sessionKey} \u2014 next dispatch will create a fresh session`);
|
|
58303
|
-
throw new Error(`Agent session ${session.id} is terminal (${session.status})`);
|
|
58304
|
-
}
|
|
58305
|
-
const binding = {
|
|
58306
|
-
sessionKey,
|
|
58307
|
-
agentSessionId: session.id,
|
|
58308
|
-
runtimeLaneKey,
|
|
58309
|
-
runtimeSessionId: runtimeEvent.runtimeSessionId,
|
|
58310
|
-
parentSessionId
|
|
58311
|
-
};
|
|
58312
|
-
this.sessionBindings.set(sessionKey, binding);
|
|
58313
|
-
if (sessionKey === this.opts.runtimeKey) {
|
|
58314
|
-
this.activeSessionId = session.id;
|
|
58315
|
-
}
|
|
58316
|
-
if (contextFilePath) {
|
|
58317
|
-
this.updateContextFileSessionId(contextFilePath, session.id);
|
|
58318
|
-
}
|
|
58319
|
-
if (laneContextFilePath2) {
|
|
58320
|
-
this.updateContextFileSessionId(laneContextFilePath2, session.id);
|
|
58321
|
-
}
|
|
58322
|
-
await this.opts.onSessionBinding?.(binding);
|
|
58323
|
-
return binding;
|
|
58845
|
+
bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2) {
|
|
58846
|
+
return bindRuntimeSession(this, sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2);
|
|
58324
58847
|
}
|
|
58325
58848
|
// Returns true if the dispatch actually ran; false if skipped because we
|
|
58326
58849
|
// are shutting down. Callers MUST treat `false` as "not dispatched" and
|
|
@@ -58346,6 +58869,7 @@ var ParallAgentGateway = class {
|
|
|
58346
58869
|
const dispatchContext = this.buildDispatchContext(event, sessionKey);
|
|
58347
58870
|
const contextFilePath = dispatchContext.contextFilePath;
|
|
58348
58871
|
const stepIdFilePath = dispatchContext.stepIdFilePath;
|
|
58872
|
+
const stepTarget = resolveStepTarget(event);
|
|
58349
58873
|
const activeLane = this.ledgerDisabled ? void 0 : this.laneLedger?.getForEvent(event);
|
|
58350
58874
|
const laneContextFilePath2 = activeLane ? this.laneLedger?.laneContextPath(activeLane) : void 0;
|
|
58351
58875
|
const contextBody = {
|
|
@@ -58436,8 +58960,8 @@ var ParallAgentGateway = class {
|
|
|
58436
58960
|
outcomeClass: outcomeEvent.outcome,
|
|
58437
58961
|
...outcomeEvent.retryAt ? { retryAt: outcomeEvent.retryAt } : {}
|
|
58438
58962
|
} : { kind: "error", outcomeClass: outcomeEvent.outcome });
|
|
58439
|
-
const
|
|
58440
|
-
this.opts.log?.warn(`turn outcome: ${
|
|
58963
|
+
const failure = describeTurnOutcomeFailure(outcomeEvent);
|
|
58964
|
+
this.opts.log?.warn(`turn outcome: ${failure.warn}`);
|
|
58441
58965
|
if (binding) {
|
|
58442
58966
|
await ensureTurnBegun();
|
|
58443
58967
|
if (!inputStepsCreated) {
|
|
@@ -58447,9 +58971,9 @@ var ParallAgentGateway = class {
|
|
|
58447
58971
|
await this.createInputStep(binding.agentSessionId, event);
|
|
58448
58972
|
inputStepsCreated = true;
|
|
58449
58973
|
}
|
|
58450
|
-
await this.createRuntimeStep(binding.agentSessionId,
|
|
58974
|
+
await this.createRuntimeStep(binding.agentSessionId, stepTarget, {
|
|
58451
58975
|
type: "error",
|
|
58452
|
-
message:
|
|
58976
|
+
message: failure.stepMessage
|
|
58453
58977
|
}, stepIdFilePath, contextFilePath, laneContextFilePath2);
|
|
58454
58978
|
}
|
|
58455
58979
|
continue;
|
|
@@ -58489,7 +59013,7 @@ var ParallAgentGateway = class {
|
|
|
58489
59013
|
sawErrorEvent = true;
|
|
58490
59014
|
this.recordTurnErrorSignal(sessionKey);
|
|
58491
59015
|
}
|
|
58492
|
-
await this.createRuntimeStep(binding.agentSessionId,
|
|
59016
|
+
await this.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
|
|
58493
59017
|
}
|
|
58494
59018
|
if (!binding) {
|
|
58495
59019
|
binding = this.sessionBindings.get(sessionKey);
|
|
@@ -58510,7 +59034,7 @@ var ParallAgentGateway = class {
|
|
|
58510
59034
|
if (!staleDetected && binding) {
|
|
58511
59035
|
try {
|
|
58512
59036
|
await ensureTurnBegun();
|
|
58513
|
-
await this.createRuntimeStep(binding.agentSessionId,
|
|
59037
|
+
await this.createRuntimeStep(binding.agentSessionId, stepTarget, {
|
|
58514
59038
|
type: "error",
|
|
58515
59039
|
message: `Dispatch failed: ${String(err)}`
|
|
58516
59040
|
}, stepIdFilePath, contextFilePath, laneContextFilePath2);
|
|
@@ -58563,15 +59087,14 @@ var ParallAgentGateway = class {
|
|
|
58563
59087
|
this.updateContextFileStepId(laneContextFilePath2, null);
|
|
58564
59088
|
}
|
|
58565
59089
|
this.inFlightDispatches--;
|
|
58566
|
-
|
|
58567
|
-
const resolvers = this.drainResolvers.splice(0);
|
|
58568
|
-
for (const resolve4 of resolvers)
|
|
58569
|
-
resolve4();
|
|
58570
|
-
}
|
|
59090
|
+
this.notifyDrainWaiters();
|
|
58571
59091
|
}
|
|
58572
59092
|
return true;
|
|
58573
59093
|
});
|
|
58574
59094
|
}
|
|
59095
|
+
handleRuntimeActivity(event) {
|
|
59096
|
+
handleRuntimeActivity(this, event);
|
|
59097
|
+
}
|
|
58575
59098
|
abortFork(targetId, reason) {
|
|
58576
59099
|
const forkState = this.forkStates.get(targetId);
|
|
58577
59100
|
if (!forkState)
|
|
@@ -58764,11 +59287,23 @@ var ParallAgentGateway = class {
|
|
|
58764
59287
|
}
|
|
58765
59288
|
}
|
|
58766
59289
|
}
|
|
59290
|
+
/** Server-driven idle auto-compact (gateway-idle-compact.ts); exposed for the test harness. */
|
|
59291
|
+
handleCompactSignal(data) {
|
|
59292
|
+
return handleCompactSignal(this, data);
|
|
59293
|
+
}
|
|
59294
|
+
boundMainSessionId() {
|
|
59295
|
+
return this.sessionBindings.get(this.opts.runtimeKey)?.agentSessionId;
|
|
59296
|
+
}
|
|
59297
|
+
kickMainDrain() {
|
|
59298
|
+
void this.drainMainBuffer();
|
|
59299
|
+
}
|
|
58767
59300
|
async drainMainBuffer() {
|
|
58768
59301
|
if (this.draining)
|
|
58769
59302
|
return;
|
|
58770
59303
|
this.draining = true;
|
|
58771
59304
|
try {
|
|
59305
|
+
while (this.idleCompact.inFlight)
|
|
59306
|
+
await this.idleCompact.inFlight;
|
|
58772
59307
|
while (this.dispatchState.mainBuffer.length > 0) {
|
|
58773
59308
|
if (this.shuttingDown) {
|
|
58774
59309
|
this.opts.log?.info(`drainMainBuffer halted (shutting down) \u2014 ${this.dispatchState.mainBuffer.length} buffered, ${this.dispatchState.pendingForkResults.length} pending fork results left for catch-up`);
|
|
@@ -58831,7 +59366,7 @@ var ParallAgentGateway = class {
|
|
|
58831
59366
|
break;
|
|
58832
59367
|
}
|
|
58833
59368
|
}
|
|
58834
|
-
const isTypedGroup = events.every(
|
|
59369
|
+
const isTypedGroup = events.every(isTypedEvent);
|
|
58835
59370
|
const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
|
|
58836
59371
|
let dispatched;
|
|
58837
59372
|
try {
|
|
@@ -58883,7 +59418,10 @@ var ParallAgentGateway = class {
|
|
|
58883
59418
|
}
|
|
58884
59419
|
}
|
|
58885
59420
|
async handleInboundEvent(event) {
|
|
58886
|
-
|
|
59421
|
+
let disposition = routeTrigger(event, this.dispatchState);
|
|
59422
|
+
if (this.idleCompact.inFlight && (disposition.action === "main" || disposition.action === "new-fork")) {
|
|
59423
|
+
disposition = { action: "buffer-main" };
|
|
59424
|
+
}
|
|
58887
59425
|
if (disposition.action === "main") {
|
|
58888
59426
|
clearForkContinuationRetries(this.forkContinuationRetries, [event]);
|
|
58889
59427
|
}
|
|
@@ -58955,20 +59493,20 @@ var ParallAgentGateway = class {
|
|
|
58955
59493
|
return false;
|
|
58956
59494
|
}
|
|
58957
59495
|
this.dispatchState.mainBuffer.push(event);
|
|
58958
|
-
const typedAheadInBuffer = this.dispatchState.mainBuffer.some(
|
|
59496
|
+
const typedAheadInBuffer = this.dispatchState.mainBuffer.some(isTypedEvent);
|
|
58959
59497
|
if (this.usesLaneLedger(event)) {
|
|
58960
|
-
if (!typedAheadInBuffer && this.mainCurrentGroupKey === this.dispatchGroupKey(event) && this.opts.dispatchAdapter.enqueueDuringDispatch != null) {
|
|
59498
|
+
if (!this.idleCompact.inFlight && !typedAheadInBuffer && this.mainCurrentGroupKey === this.dispatchGroupKey(event) && this.opts.dispatchAdapter.enqueueDuringDispatch != null) {
|
|
58961
59499
|
await steerLaneMessage(this.laneFlowHost(), event);
|
|
58962
59500
|
}
|
|
58963
59501
|
} else if (
|
|
58964
|
-
//
|
|
59502
|
+
// Lane events only. A typed event (task_comment/schedule/…)
|
|
58965
59503
|
// rides the typed-consume contract — buffer-main resolves false and
|
|
58966
59504
|
// the claim releases for re-drive — so an injection here is exactly
|
|
58967
59505
|
// the forbidden un-folded injection: the LLM sees the content while
|
|
58968
59506
|
// the WorkItem stays live, and every re-drive injects it AGAIN (the
|
|
58969
59507
|
// 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
|
|
58970
59508
|
// buffered; the drain claims them as their own turn.
|
|
58971
|
-
event
|
|
59509
|
+
!isTypedEvent(event) && event.frame != null && !this.idleCompact.inFlight && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
|
|
58972
59510
|
) {
|
|
58973
59511
|
this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
|
|
58974
59512
|
}
|
|
@@ -59031,7 +59569,9 @@ var ParallAgentGateway = class {
|
|
|
59031
59569
|
}
|
|
59032
59570
|
/**
|
|
59033
59571
|
* One WorkItem the server pushed (dispatch.new) or a catch-up page
|
|
59034
|
-
* listed: messages ride their (chat, thread) lane
|
|
59572
|
+
* listed: messages ride their (chat, thread) lane, channel messages the
|
|
59573
|
+
* server routed on a `prll://chv_…` lane ride that conversation lane;
|
|
59574
|
+
* every other family (a channel message without target_uri included)
|
|
59035
59575
|
* rides its own dsp lane, claimed, run on the server frame, resolved by
|
|
59036
59576
|
* id. A typed WorkItem whose event copy is already buffered for the
|
|
59037
59577
|
* drain is left to the drain (re-claiming it would race the drain's
|
|
@@ -59044,7 +59584,7 @@ var ParallAgentGateway = class {
|
|
|
59044
59584
|
if (item.event_type === "message") {
|
|
59045
59585
|
if (!item.chat_id || !item.source_id)
|
|
59046
59586
|
return;
|
|
59047
|
-
await this.
|
|
59587
|
+
await consumeMessageWorkItem(this.laneFlowHost(), {
|
|
59048
59588
|
id: item.id,
|
|
59049
59589
|
source_id: item.source_id,
|
|
59050
59590
|
chat_id: item.chat_id,
|
|
@@ -59054,6 +59594,11 @@ var ParallAgentGateway = class {
|
|
|
59054
59594
|
});
|
|
59055
59595
|
return;
|
|
59056
59596
|
}
|
|
59597
|
+
const channelLane = channelLaneTargetUri(item);
|
|
59598
|
+
if (channelLane) {
|
|
59599
|
+
await consumeChannelWorkItem(this.laneFlowHost(), { ...item, target_uri: channelLane });
|
|
59600
|
+
return;
|
|
59601
|
+
}
|
|
59057
59602
|
if (!TYPED_EVENT_KINDS[item.event_type]) {
|
|
59058
59603
|
this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
|
|
59059
59604
|
return;
|
|
@@ -59064,9 +59609,6 @@ var ParallAgentGateway = class {
|
|
|
59064
59609
|
}
|
|
59065
59610
|
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
|
|
59066
59611
|
}
|
|
59067
|
-
consumeMessageWorkItem(item) {
|
|
59068
|
-
return consumeMessageWorkItem(this.laneFlowHost(), item);
|
|
59069
|
-
}
|
|
59070
59612
|
/**
|
|
59071
59613
|
* Run one claimed typed WorkItem on the frame the claim returned. The
|
|
59072
59614
|
* event is addressing only: the routing target the server named
|
|
@@ -59309,33 +59851,33 @@ ${fullSummary}` : fullSummary;
|
|
|
59309
59851
|
}
|
|
59310
59852
|
}
|
|
59311
59853
|
}
|
|
59312
|
-
|
|
59313
|
-
|
|
59314
|
-
|
|
59315
|
-
|
|
59316
|
-
|
|
59317
|
-
|
|
59318
|
-
return
|
|
59319
|
-
|
|
59320
|
-
|
|
59321
|
-
|
|
59322
|
-
|
|
59323
|
-
|
|
59324
|
-
|
|
59325
|
-
|
|
59326
|
-
|
|
59327
|
-
|
|
59328
|
-
|
|
59329
|
-
|
|
59330
|
-
});
|
|
59854
|
+
/**
|
|
59855
|
+
* Nothing in flight: no dispatch, no runtime-initiated turn, and the
|
|
59856
|
+
* runtime itself reports idle (isBusy — a turn it is executing that has
|
|
59857
|
+
* not surfaced yet, or a follow-up hold after background work finished).
|
|
59858
|
+
*/
|
|
59859
|
+
isDrained() {
|
|
59860
|
+
return this.inFlightDispatches === 0 && this.inFlightRuntimeTurns === 0 && !this.adapterBusy();
|
|
59861
|
+
}
|
|
59862
|
+
adapterBusy() {
|
|
59863
|
+
try {
|
|
59864
|
+
return this.opts.dispatchAdapter.isBusy?.() ?? false;
|
|
59865
|
+
} catch (err) {
|
|
59866
|
+
this.opts.log?.warn(`dispatchAdapter.isBusy threw: ${String(err)}`);
|
|
59867
|
+
return false;
|
|
59868
|
+
}
|
|
59869
|
+
}
|
|
59870
|
+
notifyDrainWaiters() {
|
|
59871
|
+
this.drainGate.notify();
|
|
59331
59872
|
}
|
|
59332
59873
|
async shutdown() {
|
|
59333
59874
|
this.shuttingDown = true;
|
|
59334
|
-
|
|
59335
|
-
|
|
59336
|
-
|
|
59337
|
-
|
|
59338
|
-
|
|
59875
|
+
this.idleCompact.abort?.();
|
|
59876
|
+
if (!this.isDrained()) {
|
|
59877
|
+
this.opts.log?.info(`draining ${this.inFlightDispatches} in-flight dispatch(es), ${this.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${this.adapterBusy()}, deadline ${this.SHUTDOWN_DEADLINE_MS}ms`);
|
|
59878
|
+
await this.drainGate.wait(this.SHUTDOWN_DEADLINE_MS);
|
|
59879
|
+
if (!this.isDrained()) {
|
|
59880
|
+
this.opts.log?.warn(`drain deadline hit; ${this.inFlightDispatches} dispatch(es), ${this.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${this.adapterBusy()} \u2014 they will be killed by process exit`);
|
|
59339
59881
|
} else {
|
|
59340
59882
|
this.opts.log?.info(`drain complete`);
|
|
59341
59883
|
}
|
|
@@ -59347,6 +59889,9 @@ ${fullSummary}` : fullSummary;
|
|
|
59347
59889
|
await this.laneLedger.releaseAll();
|
|
59348
59890
|
}
|
|
59349
59891
|
await this.opts.onBeforeDisconnect?.();
|
|
59892
|
+
if (this.inFlightRuntimeTurns > 0) {
|
|
59893
|
+
await this.drainGate.wait(5e3, () => this.inFlightRuntimeTurns === 0);
|
|
59894
|
+
}
|
|
59350
59895
|
if (this.stepPersister.pendingTotal() > 0) {
|
|
59351
59896
|
const remaining = await this.stepPersister.flush(1e4);
|
|
59352
59897
|
if (remaining > 0) {
|
|
@@ -59360,6 +59905,7 @@ ${fullSummary}` : fullSummary;
|
|
|
59360
59905
|
}
|
|
59361
59906
|
this.sessionLifecycle.dispose();
|
|
59362
59907
|
this.opts.ws.disconnect();
|
|
59908
|
+
this.unsubscribeRuntimeActivity?.();
|
|
59363
59909
|
this.opts.log?.info(`disconnected`);
|
|
59364
59910
|
}
|
|
59365
59911
|
};
|
|
@@ -59394,7 +59940,7 @@ function childLogger(logger, sub) {
|
|
|
59394
59940
|
|
|
59395
59941
|
// ts/agent-core/dist/platform-config.js
|
|
59396
59942
|
import * as fs4 from "node:fs";
|
|
59397
|
-
import * as
|
|
59943
|
+
import * as path5 from "node:path";
|
|
59398
59944
|
function extractCapabilities(config) {
|
|
59399
59945
|
const agents = config.agents ?? {};
|
|
59400
59946
|
const raw = agents.capabilities;
|
|
@@ -59433,7 +59979,7 @@ function deriveModelIsPin(defaults, profile) {
|
|
|
59433
59979
|
var CACHE_FILENAME = "parall-platform-config.json";
|
|
59434
59980
|
var SUPPORTED_SCHEMA_VERSION = 1;
|
|
59435
59981
|
function cachePath(stateDir) {
|
|
59436
|
-
return
|
|
59982
|
+
return path5.join(stateDir, CACHE_FILENAME);
|
|
59437
59983
|
}
|
|
59438
59984
|
function loadCache(stateDir) {
|
|
59439
59985
|
try {
|
|
@@ -59452,7 +59998,7 @@ function saveCache(stateDir, response) {
|
|
|
59452
59998
|
};
|
|
59453
59999
|
const filePath = cachePath(stateDir);
|
|
59454
60000
|
const tmpPath = `${filePath}.tmp`;
|
|
59455
|
-
fs4.mkdirSync(
|
|
60001
|
+
fs4.mkdirSync(path5.dirname(filePath), { recursive: true });
|
|
59456
60002
|
fs4.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
|
|
59457
60003
|
fs4.renameSync(tmpPath, filePath);
|
|
59458
60004
|
}
|
|
@@ -59568,7 +60114,7 @@ var PLATFORM_CODEX_MESSAGE_DELIVERY_INSTRUCTIONS = "### Codex message delivery\n
|
|
|
59568
60114
|
|
|
59569
60115
|
// ts/agent-core/dist/skills/index.js
|
|
59570
60116
|
import * as fs5 from "node:fs";
|
|
59571
|
-
import * as
|
|
60117
|
+
import * as path6 from "node:path";
|
|
59572
60118
|
|
|
59573
60119
|
// ts/agent-core/dist/skills/parall-platform.js
|
|
59574
60120
|
var PARALL_PLATFORM_SKILL = `# Parall Platform
|
|
@@ -60126,59 +60672,58 @@ once. When this happened the result says so (\`stale_recovery\`, and the
|
|
|
60126
60672
|
\`next_action\` text) \u2014 re-read any file it names before editing further, since
|
|
60127
60673
|
your copy now contains the upstream changes too.
|
|
60128
60674
|
|
|
60129
|
-
It stops and tells you when the merge could not settle
|
|
60130
|
-
|
|
60131
|
-
|
|
60132
|
-
|
|
60133
|
-
Follow the ordered sequence in **Sync conflicts** below for each listed path \u2014
|
|
60134
|
-
the error text carries the same steps. Editing the file into a hand-merged
|
|
60135
|
-
state and proposing does NOT work: the baseline only advances when your file
|
|
60136
|
-
matches the server, so you would loop on the same error.
|
|
60675
|
+
It stops and tells you when the merge could not settle a file on its own. That
|
|
60676
|
+
is not a dead end: see **Sync conflicts** \u2014 the fix is always "make the file say
|
|
60677
|
+
what you want, then propose again".
|
|
60137
60678
|
|
|
60138
60679
|
## Sync conflicts
|
|
60139
60680
|
|
|
60140
|
-
\`sync\` three-way merges at line level (diff3)
|
|
60681
|
+
\`sync\` three-way merges at line level (diff3). When both you and the server
|
|
60141
60682
|
changed the same file and the changed hunks do not overlap \u2014 at least one
|
|
60142
60683
|
unchanged line separates them \u2014 the upstream changes are merged into your copy
|
|
60143
|
-
and your edits stay pending. When
|
|
60144
|
-
|
|
60145
|
-
repetitive to merge within the CLI's time budget, your file is left intact and
|
|
60146
|
-
the upstream copy lands under \`<workspace>/.parall-wiki/conflicts/\`:
|
|
60684
|
+
and your edits stay pending. When they DO overlap (both sides touched the same
|
|
60685
|
+
or adjacent lines), \`sync\` writes the conflict into your file the way git does:
|
|
60147
60686
|
|
|
60148
|
-
|
|
60149
|
-
|
|
60150
|
-
|
|
60151
|
-
|
|
60152
|
-
|
|
60153
|
-
|
|
60154
|
-
|
|
60155
|
-
\`\`\`bash
|
|
60156
|
-
# Accept upstream (drop your edit):
|
|
60157
|
-
cp <workspace>/.parall-wiki/conflicts/<path>.remote <workspace>/<path>
|
|
60158
|
-
parall wiki sync
|
|
60159
|
-
|
|
60160
|
-
# Accept the server's delete (.remote-deleted only):
|
|
60161
|
-
rm <workspace>/<path>
|
|
60162
|
-
parall wiki sync
|
|
60163
|
-
|
|
60164
|
-
# Keep your changes ON TOP of the server's version \u2014 this exact order:
|
|
60165
|
-
cp <workspace>/<path> <workspace>/<path>.mine # 1. save yours
|
|
60166
|
-
cp <workspace>/.parall-wiki/conflicts/<path>.remote <workspace>/<path> # 2. match the server
|
|
60167
|
-
parall wiki sync # 3. baseline advances
|
|
60168
|
-
# 4. re-apply your changes to <workspace>/<path> using <path>.mine, then delete <path>.mine
|
|
60169
|
-
parall wiki changeset create <wiki> --title "..." # 5. propose
|
|
60687
|
+
\`\`\`
|
|
60688
|
+
<<<<<<< mine (parall-merge)
|
|
60689
|
+
your version of the lines
|
|
60690
|
+
======= (parall-merge)
|
|
60691
|
+
the server's version of the lines
|
|
60692
|
+
>>>>>>> latest (parall-merge)
|
|
60170
60693
|
\`\`\`
|
|
60171
60694
|
|
|
60172
|
-
|
|
60173
|
-
|
|
60174
|
-
|
|
60175
|
-
|
|
60176
|
-
|
|
60177
|
-
|
|
60178
|
-
|
|
60179
|
-
|
|
60180
|
-
|
|
60181
|
-
|
|
60695
|
+
The \`(parall-merge)\` tag is what tells a real delimiter from a quoted example:
|
|
60696
|
+
if the page itself contains that block verbatim (say, a page documenting this
|
|
60697
|
+
feature), the delimiters of a new conflict read \`(parall-merge-2)\`, then
|
|
60698
|
+
\`-3\`, and so on. \`sync\` remembers which set it wrote for the file, and only
|
|
60699
|
+
that set is live: propose refuses the file while **any** line of that set is
|
|
60700
|
+
still in it \u2014 a lone opener or closer left from a half-finished hand merge
|
|
60701
|
+
counts \u2014 and treats every other set (quoted examples) as content. Everything
|
|
60702
|
+
outside the blocks is already merged. Your pre-merge copy is kept at
|
|
60703
|
+
\`<workspace>/.parall-wiki/conflicts/<path>.mine\`.
|
|
60704
|
+
|
|
60705
|
+
**Your baseline has already moved to the server's version.** There is nothing
|
|
60706
|
+
to sync, restore or re-apply: edit each block so the file says what you want
|
|
60707
|
+
(keep one side, or combine them), delete the three marker lines, and run
|
|
60708
|
+
\`parall wiki changeset create\` again. A file that still contains any
|
|
60709
|
+
\`<<<<<<< mine (parall-merge\u2026)\` / \`======= (parall-merge\u2026)\` /
|
|
60710
|
+
\`>>>>>>> latest (parall-merge\u2026)\` line of the set written for it is
|
|
60711
|
+
refused at propose, so you cannot ship one by accident.
|
|
60712
|
+
|
|
60713
|
+
The other shapes follow the same rule \u2014 the working tree already holds what you
|
|
60714
|
+
meant, propose sends it:
|
|
60715
|
+
|
|
60716
|
+
| The error says | Working tree now | To finish |
|
|
60717
|
+
|---|---|---|
|
|
60718
|
+
| overlapping block(s) marked in the file | your file with \`<<<<<<< mine (parall-merge)\` blocks; \`.mine\` copy aside | edit the blocks away, propose |
|
|
60719
|
+
| not merged in place (binary, LFS, too long/repetitive, or markers from an earlier sync still unresolved) | your file untouched; the server's bytes at \`conflicts/<path>.remote\` | fold what you want from \`.remote\` into your file, propose |
|
|
60720
|
+
| the server changed it and you deleted it | no file (your delete stands); server's bytes at \`conflicts/<path>.remote\` | propose to delete the server's newer version too, or copy \`.remote\` back to \`<workspace>/<path>\` to keep it |
|
|
60721
|
+
| the server deleted it and you still have edits | your file, now a new file (it stays on its old baseline while it still carries an unresolved block \u2014 edit that away first) | propose to recreate it, or \`rm\` it to accept the removal |
|
|
60722
|
+
|
|
60723
|
+
Conflict artifacts under \`.parall-wiki/conflicts/\` are removed on their own
|
|
60724
|
+
once the path is proposed or back in step with the server. Conflicts exit 0
|
|
60725
|
+
(they need your decision); \`failed[]\` entries (download error, shape-conflict)
|
|
60726
|
+
exit 1 and retry on the next sync.
|
|
60182
60727
|
|
|
60183
60728
|
## Changesets
|
|
60184
60729
|
|
|
@@ -60262,10 +60807,16 @@ a \`Request approval:\` hint \u2014 use \`parall wiki request-access <path> --re
|
|
|
60262
60807
|
## Recovery
|
|
60263
60808
|
|
|
60264
60809
|
\`\`\`bash
|
|
60265
|
-
parall wiki reset <wiki> # discard ALL local edits, restore
|
|
60810
|
+
parall wiki reset <wiki> # discard ALL local edits, restore the synced baseline
|
|
60266
60811
|
parall wiki status <wiki> # local changes + your changesets, anytime
|
|
60267
60812
|
\`\`\`
|
|
60268
60813
|
|
|
60814
|
+
After a conflict the synced baseline IS the server's version, so \`reset\` gives
|
|
60815
|
+
you the server's file; your pre-merge edits are still under
|
|
60816
|
+
\`.parall-wiki/conflicts/<path>.mine\` until that path is proposed, or until a
|
|
60817
|
+
later \`sync\` finds it back in step with the server (clean or fast-forwarded)
|
|
60818
|
+
and removes the copy.
|
|
60819
|
+
|
|
60269
60820
|
## Changeset Discipline
|
|
60270
60821
|
|
|
60271
60822
|
- Creation is fail-closed \u2014 without explicit CLI confirmation of success,
|
|
@@ -60956,11 +61507,11 @@ var SKILLS = [
|
|
|
60956
61507
|
function writeSkillFiles(targetDir) {
|
|
60957
61508
|
fs5.mkdirSync(targetDir, { recursive: true });
|
|
60958
61509
|
for (const skill of SKILLS) {
|
|
60959
|
-
fs5.writeFileSync(
|
|
61510
|
+
fs5.writeFileSync(path6.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
|
|
60960
61511
|
}
|
|
60961
61512
|
}
|
|
60962
61513
|
function buildSkillReferences(workspaceDir) {
|
|
60963
|
-
const dir =
|
|
61514
|
+
const dir = path6.join(workspaceDir, ".parall", "skills");
|
|
60964
61515
|
const lines = SKILLS.map((s) => `- ${s.description.split(":")[0]}: \`${dir}/${s.name}.md\``);
|
|
60965
61516
|
return `## Platform Skills (read on demand)
|
|
60966
61517
|
|
|
@@ -61046,9 +61597,99 @@ function parseProviderConfig(env) {
|
|
|
61046
61597
|
}
|
|
61047
61598
|
}
|
|
61048
61599
|
|
|
61600
|
+
// ts/agent-core/dist/runtime-activity-port.js
|
|
61601
|
+
var RuntimeActivityPort = class {
|
|
61602
|
+
label;
|
|
61603
|
+
log;
|
|
61604
|
+
handler = null;
|
|
61605
|
+
constructor(label, log2) {
|
|
61606
|
+
this.label = label;
|
|
61607
|
+
this.log = log2;
|
|
61608
|
+
}
|
|
61609
|
+
subscribe(handler) {
|
|
61610
|
+
if (this.handler)
|
|
61611
|
+
throw new Error(`${this.label} supports a single runtime-activity subscriber`);
|
|
61612
|
+
this.handler = handler;
|
|
61613
|
+
return () => {
|
|
61614
|
+
if (this.handler === handler)
|
|
61615
|
+
this.handler = null;
|
|
61616
|
+
};
|
|
61617
|
+
}
|
|
61618
|
+
/** Hand an event to the subscriber; false when there is none or it threw. */
|
|
61619
|
+
emit(event, log2 = this.log) {
|
|
61620
|
+
if (!this.handler)
|
|
61621
|
+
return false;
|
|
61622
|
+
try {
|
|
61623
|
+
this.handler(event);
|
|
61624
|
+
return true;
|
|
61625
|
+
} catch (err) {
|
|
61626
|
+
log2?.warn?.(`runtime-activity subscriber threw: ${String(err)}`);
|
|
61627
|
+
return false;
|
|
61628
|
+
}
|
|
61629
|
+
}
|
|
61630
|
+
/** A turn opened: to the subscriber when eligible, else drained here. */
|
|
61631
|
+
surfaceTurn(turn, eligible = true, log2 = this.log) {
|
|
61632
|
+
if (eligible && this.emit({ kind: "turn", turn }, log2))
|
|
61633
|
+
return;
|
|
61634
|
+
void this.drainLocally(turn, log2);
|
|
61635
|
+
}
|
|
61636
|
+
async drainLocally(turn, log2 = this.log) {
|
|
61637
|
+
let count = 0;
|
|
61638
|
+
let outcome;
|
|
61639
|
+
try {
|
|
61640
|
+
for await (const event of turn.events) {
|
|
61641
|
+
count += 1;
|
|
61642
|
+
if (event.type === "turn_outcome")
|
|
61643
|
+
outcome = event.outcome;
|
|
61644
|
+
}
|
|
61645
|
+
} catch (err) {
|
|
61646
|
+
log2?.warn?.(`local drain of runtime-initiated turn ${turn.groupKey} failed: ${String(err)}`);
|
|
61647
|
+
}
|
|
61648
|
+
log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count} event(s), outcome=${outcome ?? "ok"}`);
|
|
61649
|
+
}
|
|
61650
|
+
};
|
|
61651
|
+
|
|
61652
|
+
// ts/agent-core/dist/runtime-turn-base.js
|
|
61653
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
61654
|
+
var RuntimeTurnBase = class {
|
|
61655
|
+
sessionKey;
|
|
61656
|
+
trigger;
|
|
61657
|
+
onDetach;
|
|
61658
|
+
groupKey = randomUUID2();
|
|
61659
|
+
startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
61660
|
+
activityListeners = [];
|
|
61661
|
+
detached = false;
|
|
61662
|
+
constructor(sessionKey, trigger, onDetach) {
|
|
61663
|
+
this.sessionKey = sessionKey;
|
|
61664
|
+
this.trigger = trigger;
|
|
61665
|
+
this.onDetach = onDetach;
|
|
61666
|
+
}
|
|
61667
|
+
onActivity(listener) {
|
|
61668
|
+
this.activityListeners.push(listener);
|
|
61669
|
+
}
|
|
61670
|
+
/** Progress that is not a RuntimeEvent (task frames, nested notifications). */
|
|
61671
|
+
touch() {
|
|
61672
|
+
for (const listener of this.activityListeners) {
|
|
61673
|
+
try {
|
|
61674
|
+
listener();
|
|
61675
|
+
} catch {
|
|
61676
|
+
}
|
|
61677
|
+
}
|
|
61678
|
+
}
|
|
61679
|
+
detach(reason) {
|
|
61680
|
+
if (this.detached)
|
|
61681
|
+
return;
|
|
61682
|
+
this.detached = true;
|
|
61683
|
+
this.onDetach(reason);
|
|
61684
|
+
}
|
|
61685
|
+
get events() {
|
|
61686
|
+
return this.drain();
|
|
61687
|
+
}
|
|
61688
|
+
};
|
|
61689
|
+
|
|
61049
61690
|
// ts/codex-agent/dist/config.js
|
|
61050
61691
|
import * as os2 from "node:os";
|
|
61051
|
-
import * as
|
|
61692
|
+
import * as path7 from "node:path";
|
|
61052
61693
|
function requireEnv(env, name) {
|
|
61053
61694
|
const value = env[name]?.trim();
|
|
61054
61695
|
if (!value) {
|
|
@@ -61057,15 +61698,15 @@ function requireEnv(env, name) {
|
|
|
61057
61698
|
return value;
|
|
61058
61699
|
}
|
|
61059
61700
|
function resolvePath(value) {
|
|
61060
|
-
return
|
|
61701
|
+
return path7.isAbsolute(value) ? value : path7.resolve(process.cwd(), value);
|
|
61061
61702
|
}
|
|
61062
61703
|
function resolveCodexAgentConfig(env = process.env) {
|
|
61063
61704
|
const apiUrl = requireEnv(env, "PRLL_API_URL");
|
|
61064
61705
|
const apiKey = requireEnv(env, "PRLL_API_KEY");
|
|
61065
61706
|
const orgId = requireEnv(env, "PRLL_ORG_ID");
|
|
61066
|
-
const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() ||
|
|
61067
|
-
const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() ||
|
|
61068
|
-
const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() ||
|
|
61707
|
+
const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() || path7.join(env.HOME || os2.homedir(), ".codex"));
|
|
61708
|
+
const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path7.join(env.HOME || os2.homedir(), ".parall-agent"));
|
|
61709
|
+
const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path7.join(stateDir, "workspace"));
|
|
61069
61710
|
return {
|
|
61070
61711
|
apiUrl,
|
|
61071
61712
|
apiKey,
|
|
@@ -61121,31 +61762,31 @@ function buildCodexRuntimeKey(agentUserId) {
|
|
|
61121
61762
|
}
|
|
61122
61763
|
function sessionStateFilePathForRuntime(stateDir, runtimeKey) {
|
|
61123
61764
|
const fileName = Buffer.from(runtimeKey).toString("base64url");
|
|
61124
|
-
return
|
|
61765
|
+
return path7.join(stateDir, "threads", `${fileName}.json`);
|
|
61125
61766
|
}
|
|
61126
61767
|
function contextFilePathForSession(stateDir, sessionKey) {
|
|
61127
61768
|
const fileName = Buffer.from(sessionKey).toString("base64url");
|
|
61128
|
-
return
|
|
61769
|
+
return path7.join(stateDir, "dispatch-context", `${fileName}.json`);
|
|
61129
61770
|
}
|
|
61130
61771
|
function dispatchContextDirPath(stateDir) {
|
|
61131
61772
|
return dispatchLaneContextDir(stateDir);
|
|
61132
61773
|
}
|
|
61133
61774
|
function stepIdFilePathForSession(stateDir, sessionKey) {
|
|
61134
61775
|
const fileName = Buffer.from(sessionKey).toString("base64url");
|
|
61135
|
-
return
|
|
61776
|
+
return path7.join(stateDir, "step-ids", `${fileName}.txt`);
|
|
61136
61777
|
}
|
|
61137
61778
|
|
|
61138
61779
|
// ts/codex-agent/dist/dispatch.js
|
|
61139
61780
|
import { spawn } from "node:child_process";
|
|
61140
|
-
import { randomUUID as
|
|
61141
|
-
import * as
|
|
61781
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
61782
|
+
import * as path10 from "node:path";
|
|
61142
61783
|
|
|
61143
61784
|
// ts/agent-core/dist/internal/attachment-input.js
|
|
61144
61785
|
import { execSync } from "node:child_process";
|
|
61145
61786
|
import { constants } from "node:fs";
|
|
61146
61787
|
import * as fsSync from "node:fs";
|
|
61147
61788
|
import * as fs6 from "node:fs/promises";
|
|
61148
|
-
import * as
|
|
61789
|
+
import * as path8 from "node:path";
|
|
61149
61790
|
var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
61150
61791
|
var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
|
|
61151
61792
|
var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
|
|
@@ -61175,11 +61816,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
|
|
|
61175
61816
|
};
|
|
61176
61817
|
}
|
|
61177
61818
|
const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
|
|
61178
|
-
const messageDir =
|
|
61819
|
+
const messageDir = path8.join(rootDir, sanitizePathSegment(event.messageId));
|
|
61179
61820
|
await ensurePathIsNotSymlink(messageDir);
|
|
61180
61821
|
await fs6.mkdir(messageDir, { recursive: true });
|
|
61181
61822
|
await ensurePathIsNotSymlink(messageDir);
|
|
61182
|
-
const activeMessageDir =
|
|
61823
|
+
const activeMessageDir = path8.resolve(messageDir);
|
|
61183
61824
|
activeAttachmentDirs.add(activeMessageDir);
|
|
61184
61825
|
const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
|
|
61185
61826
|
const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
|
|
@@ -61196,7 +61837,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
|
|
|
61196
61837
|
const notes = [];
|
|
61197
61838
|
let downloadedBytes = 0;
|
|
61198
61839
|
for (const att of imageAttachments) {
|
|
61199
|
-
const localPath =
|
|
61840
|
+
const localPath = path8.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
|
|
61200
61841
|
const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
|
|
61201
61842
|
const fetchFresh = async () => {
|
|
61202
61843
|
const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
|
|
@@ -61253,7 +61894,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
|
|
|
61253
61894
|
return { body: appendLocalAttachmentRefs(body, attachments), attachments };
|
|
61254
61895
|
}
|
|
61255
61896
|
function pinLocalAttachmentPaths(images) {
|
|
61256
|
-
const dirs = new Set(images.map((image) =>
|
|
61897
|
+
const dirs = new Set(images.map((image) => path8.resolve(path8.dirname(image.localPath))));
|
|
61257
61898
|
for (const dir of dirs) {
|
|
61258
61899
|
activeAttachmentDirs.add(dir);
|
|
61259
61900
|
}
|
|
@@ -61268,7 +61909,7 @@ function pinLocalAttachmentPaths(images) {
|
|
|
61268
61909
|
};
|
|
61269
61910
|
}
|
|
61270
61911
|
function attachmentRootDir(workspaceDir) {
|
|
61271
|
-
return
|
|
61912
|
+
return path8.join(path8.resolve(workspaceDir), ".parall", "attachments");
|
|
61272
61913
|
}
|
|
61273
61914
|
function ensureLocalAttachmentGitExclude(workingDirectory) {
|
|
61274
61915
|
try {
|
|
@@ -61277,8 +61918,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
|
|
|
61277
61918
|
encoding: "utf8",
|
|
61278
61919
|
stdio: ["ignore", "pipe", "ignore"]
|
|
61279
61920
|
}).trim();
|
|
61280
|
-
const excludePath =
|
|
61281
|
-
fsSync.mkdirSync(
|
|
61921
|
+
const excludePath = path8.isAbsolute(rel) ? rel : path8.join(workingDirectory, rel);
|
|
61922
|
+
fsSync.mkdirSync(path8.dirname(excludePath), { recursive: true });
|
|
61282
61923
|
const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
|
|
61283
61924
|
if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
|
|
61284
61925
|
return;
|
|
@@ -61314,8 +61955,8 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
|
|
|
61314
61955
|
return run;
|
|
61315
61956
|
}
|
|
61316
61957
|
async function ensureAttachmentRootDir(workspaceDir) {
|
|
61317
|
-
const workspaceRoot =
|
|
61318
|
-
const parallDir =
|
|
61958
|
+
const workspaceRoot = path8.resolve(workspaceDir);
|
|
61959
|
+
const parallDir = path8.join(workspaceRoot, ".parall");
|
|
61319
61960
|
const rootDir = attachmentRootDir(workspaceRoot);
|
|
61320
61961
|
await fs6.mkdir(workspaceRoot, { recursive: true });
|
|
61321
61962
|
await ensurePathIsNotSymlink(parallDir);
|
|
@@ -61344,8 +61985,8 @@ async function ensurePathIsNotSymlink(filePath) {
|
|
|
61344
61985
|
}
|
|
61345
61986
|
}
|
|
61346
61987
|
function isPathInside(childPath, parentPath) {
|
|
61347
|
-
const rel =
|
|
61348
|
-
return rel === "" || !!rel && !rel.startsWith("..") && !
|
|
61988
|
+
const rel = path8.relative(parentPath, childPath);
|
|
61989
|
+
return rel === "" || !!rel && !rel.startsWith("..") && !path8.isAbsolute(rel);
|
|
61349
61990
|
}
|
|
61350
61991
|
async function existingUsableFile(filePath, expectedSize, rootDir) {
|
|
61351
61992
|
try {
|
|
@@ -61403,7 +62044,7 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
|
|
|
61403
62044
|
}
|
|
61404
62045
|
}
|
|
61405
62046
|
async function openLocalTempFileInsideRoot(filePath, rootDir) {
|
|
61406
|
-
await localDirectoryStatInsideRoot(
|
|
62047
|
+
await localDirectoryStatInsideRoot(path8.dirname(filePath), rootDir);
|
|
61407
62048
|
const file = await fs6.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
61408
62049
|
let keepOpen = false;
|
|
61409
62050
|
try {
|
|
@@ -61450,9 +62091,9 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
|
|
|
61450
62091
|
await Promise.all(entries.map(async (entry) => {
|
|
61451
62092
|
if (!entry.isDirectory())
|
|
61452
62093
|
return;
|
|
61453
|
-
const fullPath =
|
|
62094
|
+
const fullPath = path8.join(rootDir, entry.name);
|
|
61454
62095
|
try {
|
|
61455
|
-
if (preserveDirs?.has(
|
|
62096
|
+
if (preserveDirs?.has(path8.resolve(fullPath)))
|
|
61456
62097
|
return;
|
|
61457
62098
|
const stat = await fs6.lstat(fullPath);
|
|
61458
62099
|
if (!stat.isDirectory())
|
|
@@ -61479,7 +62120,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
61479
62120
|
for (const entry of entries) {
|
|
61480
62121
|
if (!entry.isDirectory())
|
|
61481
62122
|
continue;
|
|
61482
|
-
const fullPath =
|
|
62123
|
+
const fullPath = path8.join(rootDir, entry.name);
|
|
61483
62124
|
try {
|
|
61484
62125
|
const stat = await fs6.lstat(fullPath);
|
|
61485
62126
|
if (!stat.isDirectory())
|
|
@@ -61497,7 +62138,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
61497
62138
|
for (const dir of dirs) {
|
|
61498
62139
|
if (total <= maxBytes)
|
|
61499
62140
|
break;
|
|
61500
|
-
if (preserveDirs?.has(
|
|
62141
|
+
if (preserveDirs?.has(path8.resolve(dir.path)))
|
|
61501
62142
|
continue;
|
|
61502
62143
|
try {
|
|
61503
62144
|
await fs6.rm(dir.path, { recursive: true, force: true });
|
|
@@ -61511,7 +62152,7 @@ async function directorySize(dirPath) {
|
|
|
61511
62152
|
let total = 0;
|
|
61512
62153
|
const entries = await fs6.readdir(dirPath, { withFileTypes: true });
|
|
61513
62154
|
for (const entry of entries) {
|
|
61514
|
-
const fullPath =
|
|
62155
|
+
const fullPath = path8.join(dirPath, entry.name);
|
|
61515
62156
|
let stat;
|
|
61516
62157
|
try {
|
|
61517
62158
|
stat = await fs6.lstat(fullPath);
|
|
@@ -61529,10 +62170,10 @@ async function directorySize(dirPath) {
|
|
|
61529
62170
|
return total;
|
|
61530
62171
|
}
|
|
61531
62172
|
function activeDirsForRoot(rootDir) {
|
|
61532
|
-
const root =
|
|
62173
|
+
const root = path8.resolve(rootDir);
|
|
61533
62174
|
const dirs = /* @__PURE__ */ new Set();
|
|
61534
62175
|
for (const dir of activeAttachmentDirs) {
|
|
61535
|
-
if (dir === root || dir.startsWith(`${root}${
|
|
62176
|
+
if (dir === root || dir.startsWith(`${root}${path8.sep}`)) {
|
|
61536
62177
|
dirs.add(dir);
|
|
61537
62178
|
}
|
|
61538
62179
|
}
|
|
@@ -61629,7 +62270,7 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
|
|
|
61629
62270
|
}
|
|
61630
62271
|
writtenStat = await file.stat();
|
|
61631
62272
|
await closeFile();
|
|
61632
|
-
await localDirectoryStatInsideRoot(
|
|
62273
|
+
await localDirectoryStatInsideRoot(path8.dirname(filePath), rootDir);
|
|
61633
62274
|
await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
|
|
61634
62275
|
await fs6.rename(tmpPath, filePath);
|
|
61635
62276
|
completed = true;
|
|
@@ -61647,9 +62288,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
|
|
|
61647
62288
|
}
|
|
61648
62289
|
}
|
|
61649
62290
|
function localFileName(attachmentId, fileName, mimeType) {
|
|
61650
|
-
const safeName = sanitizePathSegment(
|
|
61651
|
-
const ext =
|
|
61652
|
-
const stem =
|
|
62291
|
+
const safeName = sanitizePathSegment(path8.basename(fileName || attachmentId));
|
|
62292
|
+
const ext = path8.extname(safeName) || extensionForMime(mimeType);
|
|
62293
|
+
const stem = path8.basename(safeName, path8.extname(safeName)) || attachmentId;
|
|
61653
62294
|
return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
|
|
61654
62295
|
}
|
|
61655
62296
|
function extensionForMime(mimeType) {
|
|
@@ -61781,6 +62422,23 @@ function extractTurnId(result) {
|
|
|
61781
62422
|
return turn.id;
|
|
61782
62423
|
return void 0;
|
|
61783
62424
|
}
|
|
62425
|
+
function extractThreadInfo(params) {
|
|
62426
|
+
if (!params || typeof params !== "object")
|
|
62427
|
+
return void 0;
|
|
62428
|
+
const p = params;
|
|
62429
|
+
const thread = p.thread && typeof p.thread === "object" ? p.thread : p;
|
|
62430
|
+
const id = typeof thread.id === "string" ? thread.id : typeof p.threadId === "string" ? p.threadId : void 0;
|
|
62431
|
+
if (!id)
|
|
62432
|
+
return void 0;
|
|
62433
|
+
const str = (value) => typeof value === "string" && value.trim() ? value : void 0;
|
|
62434
|
+
return {
|
|
62435
|
+
id,
|
|
62436
|
+
parentThreadId: str(thread.parentThreadId),
|
|
62437
|
+
source: str(thread.threadSource) ?? str(thread.source),
|
|
62438
|
+
nickname: str(thread.agentNickname),
|
|
62439
|
+
role: str(thread.agentRole)
|
|
62440
|
+
};
|
|
62441
|
+
}
|
|
61784
62442
|
function extractThreadIdFromNotification(params) {
|
|
61785
62443
|
if (!params || typeof params !== "object")
|
|
61786
62444
|
return void 0;
|
|
@@ -61796,85 +62454,6 @@ function extractThreadIdFromNotification(params) {
|
|
|
61796
62454
|
return void 0;
|
|
61797
62455
|
}
|
|
61798
62456
|
|
|
61799
|
-
// ts/codex-agent/dist/injection-registry.js
|
|
61800
|
-
var CodexInjectionRegistry = class {
|
|
61801
|
-
sessions = /* @__PURE__ */ new Map();
|
|
61802
|
-
/** Record a successful steer. `deliveryKey` may join several WorkItem ids with ','. */
|
|
61803
|
-
register(sessionKey, deliveryKey) {
|
|
61804
|
-
let entries = this.sessions.get(sessionKey);
|
|
61805
|
-
if (!entries) {
|
|
61806
|
-
entries = /* @__PURE__ */ new Map();
|
|
61807
|
-
this.sessions.set(sessionKey, entries);
|
|
61808
|
-
}
|
|
61809
|
-
for (const id of splitDeliveryKey(deliveryKey)) {
|
|
61810
|
-
if (!entries.has(id))
|
|
61811
|
-
entries.set(id, { settled: false, drained: false });
|
|
61812
|
-
}
|
|
61813
|
-
}
|
|
61814
|
-
/** The buffered copies behind these WorkItems drained (group dispatch or discard). */
|
|
61815
|
-
markDrained(sessionKey, deliveryKey) {
|
|
61816
|
-
const entries = this.sessions.get(sessionKey);
|
|
61817
|
-
if (!entries)
|
|
61818
|
-
return;
|
|
61819
|
-
for (const id of splitDeliveryKey(deliveryKey)) {
|
|
61820
|
-
const entry = entries.get(id);
|
|
61821
|
-
if (!entry)
|
|
61822
|
-
continue;
|
|
61823
|
-
entry.drained = true;
|
|
61824
|
-
if (entry.settled)
|
|
61825
|
-
entries.delete(id);
|
|
61826
|
-
}
|
|
61827
|
-
if (entries.size === 0)
|
|
61828
|
-
this.sessions.delete(sessionKey);
|
|
61829
|
-
}
|
|
61830
|
-
/** The turn every injection of this session was steered into has ended. */
|
|
61831
|
-
settleAll(sessionKey) {
|
|
61832
|
-
const entries = this.sessions.get(sessionKey);
|
|
61833
|
-
if (!entries)
|
|
61834
|
-
return;
|
|
61835
|
-
for (const [id, entry] of entries) {
|
|
61836
|
-
entry.settled = true;
|
|
61837
|
-
if (entry.drained)
|
|
61838
|
-
entries.delete(id);
|
|
61839
|
-
}
|
|
61840
|
-
if (entries.size === 0)
|
|
61841
|
-
this.sessions.delete(sessionKey);
|
|
61842
|
-
}
|
|
61843
|
-
/** An injection whose buffered copy has not drained yet (bookkeeping owed). */
|
|
61844
|
-
hasPending(sessionKey) {
|
|
61845
|
-
const entries = this.sessions.get(sessionKey);
|
|
61846
|
-
if (!entries)
|
|
61847
|
-
return false;
|
|
61848
|
-
for (const entry of entries.values()) {
|
|
61849
|
-
if (!entry.drained)
|
|
61850
|
-
return true;
|
|
61851
|
-
}
|
|
61852
|
-
return false;
|
|
61853
|
-
}
|
|
61854
|
-
/** An injection whose turn is still running (the only state that may defer a complete). */
|
|
61855
|
-
hasUnsettled(sessionKey) {
|
|
61856
|
-
const entries = this.sessions.get(sessionKey);
|
|
61857
|
-
if (!entries)
|
|
61858
|
-
return false;
|
|
61859
|
-
for (const entry of entries.values()) {
|
|
61860
|
-
if (!entry.settled)
|
|
61861
|
-
return true;
|
|
61862
|
-
}
|
|
61863
|
-
return false;
|
|
61864
|
-
}
|
|
61865
|
-
/** Drop every entry (turn aborted / subprocess gone): nothing is owed anymore. */
|
|
61866
|
-
clear(sessionKey) {
|
|
61867
|
-
if (sessionKey === void 0) {
|
|
61868
|
-
this.sessions.clear();
|
|
61869
|
-
return;
|
|
61870
|
-
}
|
|
61871
|
-
this.sessions.delete(sessionKey);
|
|
61872
|
-
}
|
|
61873
|
-
};
|
|
61874
|
-
function splitDeliveryKey(deliveryKey) {
|
|
61875
|
-
return deliveryKey.split(",").map((id) => id.trim()).filter((id) => id.length > 0);
|
|
61876
|
-
}
|
|
61877
|
-
|
|
61878
62457
|
// ts/codex-agent/dist/instructions-refresh.js
|
|
61879
62458
|
import { createHash } from "node:crypto";
|
|
61880
62459
|
|
|
@@ -62144,21 +62723,17 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62144
62723
|
}
|
|
62145
62724
|
if (this.compactUnsupported)
|
|
62146
62725
|
return "unsupported";
|
|
62147
|
-
const compaction = this.watchForCompaction(client, taps, threadId);
|
|
62148
62726
|
try {
|
|
62149
|
-
await
|
|
62150
|
-
await compaction.done;
|
|
62727
|
+
await this.runCompaction({ client, taps, threadId });
|
|
62151
62728
|
this.opts.sessionManager.recordEffectiveInstructionsSha(sessionKey, canonicalSha);
|
|
62152
62729
|
log2?.info?.(`platform instructions refreshed on persisted thread ${threadId} (compaction rebuilt initial context from the resumed configuration)`);
|
|
62153
62730
|
return "refreshed";
|
|
62154
62731
|
} catch (err) {
|
|
62155
|
-
compaction.cancel();
|
|
62156
62732
|
if (err instanceof CompactionStalledError) {
|
|
62157
62733
|
log2?.warn?.(`platform instructions refresh stalled (${errToString(err)}); bouncing the subprocess before the next turn`);
|
|
62158
62734
|
return "stalled";
|
|
62159
62735
|
}
|
|
62160
62736
|
if (err instanceof JsonRpcError && err.code === JSON_RPC_METHOD_NOT_FOUND) {
|
|
62161
|
-
this.compactUnsupported = true;
|
|
62162
62737
|
log2?.warn?.("thread/compact/start not supported by this codex CLI; the persisted thread keeps its previous platform instructions until it is replaced or the CLI is upgraded (tools still refresh live via the capability shim dir)");
|
|
62163
62738
|
return "unsupported";
|
|
62164
62739
|
}
|
|
@@ -62166,6 +62741,44 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62166
62741
|
return "failed";
|
|
62167
62742
|
}
|
|
62168
62743
|
}
|
|
62744
|
+
/** True once this subprocess rejected thread/compact/start with -32601. */
|
|
62745
|
+
isCompactUnsupported() {
|
|
62746
|
+
return this.compactUnsupported;
|
|
62747
|
+
}
|
|
62748
|
+
/**
|
|
62749
|
+
* The unconditional compaction primitive — one `thread/compact/start`
|
|
62750
|
+
* awaited to its turn close — shared by the instructions refresh (which
|
|
62751
|
+
* decides WHETHER to run it by sha) and the idle auto-compact (which runs
|
|
62752
|
+
* it whenever the server asks). Throws like the refresh's inner path:
|
|
62753
|
+
* CompactionStalledError past budget/abort + interrupt grace, JsonRpcError
|
|
62754
|
+
* -32601 (also latches compactUnsupported for this subprocess), or a plain
|
|
62755
|
+
* Error for a turn that closed without compacting.
|
|
62756
|
+
*/
|
|
62757
|
+
async runCompaction(args) {
|
|
62758
|
+
const { client, taps, threadId, signal } = args;
|
|
62759
|
+
const compaction = this.watchForCompaction(client, taps, threadId, signal);
|
|
62760
|
+
try {
|
|
62761
|
+
await client.sendRequest("thread/compact/start", { threadId });
|
|
62762
|
+
await compaction.done;
|
|
62763
|
+
} catch (err) {
|
|
62764
|
+
compaction.cancel();
|
|
62765
|
+
if (err instanceof JsonRpcError && err.code === JSON_RPC_METHOD_NOT_FOUND) {
|
|
62766
|
+
this.compactUnsupported = true;
|
|
62767
|
+
}
|
|
62768
|
+
throw err;
|
|
62769
|
+
}
|
|
62770
|
+
}
|
|
62771
|
+
/**
|
|
62772
|
+
* A compaction that completed outside the refresh path (idle auto-compact)
|
|
62773
|
+
* rebuilt the model-visible context from the canonical configuration: the
|
|
62774
|
+
* effective plane now equals whatever this process opened the thread with.
|
|
62775
|
+
*/
|
|
62776
|
+
recordCompacted(sessionKey, threadId) {
|
|
62777
|
+
const canonical = this.canonicalByThread.get(threadId);
|
|
62778
|
+
if (canonical === void 0)
|
|
62779
|
+
return;
|
|
62780
|
+
this.opts.sessionManager.recordEffectiveInstructionsSha(sessionKey, sha256Hex(canonical));
|
|
62781
|
+
}
|
|
62169
62782
|
/**
|
|
62170
62783
|
* Compaction runs as its own turn on the thread:
|
|
62171
62784
|
* turn/started → item/started{contextCompaction} →
|
|
@@ -62187,7 +62800,7 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62187
62800
|
* turn/started by the deadline leaves nothing to interrupt — pathological,
|
|
62188
62801
|
* and the grace still absorbs a late-materializing close.
|
|
62189
62802
|
*/
|
|
62190
|
-
watchForCompaction(client, taps, threadId) {
|
|
62803
|
+
watchForCompaction(client, taps, threadId, signal) {
|
|
62191
62804
|
const timeoutMs = this.opts.compactTimeoutMs ?? DEFAULT_COMPACT_TIMEOUT_MS;
|
|
62192
62805
|
const graceMs = this.opts.interruptGraceMs ?? COMPACT_INTERRUPT_GRACE_MS;
|
|
62193
62806
|
let cancel = () => {
|
|
@@ -62200,6 +62813,7 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62200
62813
|
let unregister = () => {
|
|
62201
62814
|
};
|
|
62202
62815
|
let graceTimer;
|
|
62816
|
+
const onAbort = () => expire("aborted by the caller");
|
|
62203
62817
|
const finish = (err) => {
|
|
62204
62818
|
if (settled)
|
|
62205
62819
|
return;
|
|
@@ -62207,27 +62821,41 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62207
62821
|
clearTimeout(timer);
|
|
62208
62822
|
if (graceTimer)
|
|
62209
62823
|
clearTimeout(graceTimer);
|
|
62824
|
+
signal?.removeEventListener("abort", onAbort);
|
|
62210
62825
|
unregister();
|
|
62211
62826
|
if (err)
|
|
62212
62827
|
reject(err);
|
|
62213
62828
|
else
|
|
62214
62829
|
resolve4();
|
|
62215
62830
|
};
|
|
62216
|
-
const
|
|
62831
|
+
const expire = (why) => {
|
|
62832
|
+
if (settled || interrupted)
|
|
62833
|
+
return;
|
|
62217
62834
|
interrupted = true;
|
|
62835
|
+
clearTimeout(timer);
|
|
62218
62836
|
if (compactionTurnId) {
|
|
62219
62837
|
client.sendRequest("turn/interrupt", { threadId, turnId: compactionTurnId }, { timeoutMs: graceMs, lethalTimeout: false }).catch(() => {
|
|
62220
62838
|
});
|
|
62221
62839
|
}
|
|
62222
|
-
graceTimer = setTimeout(() => finish(new CompactionStalledError(`compaction did not complete
|
|
62223
|
-
}
|
|
62840
|
+
graceTimer = setTimeout(() => finish(new CompactionStalledError(`compaction did not complete (${why}; interrupt grace elapsed; the compaction turn may still be running)`)), graceMs);
|
|
62841
|
+
};
|
|
62842
|
+
const timer = setTimeout(() => expire(`within ${timeoutMs}ms`), timeoutMs);
|
|
62843
|
+
if (signal?.aborted)
|
|
62844
|
+
onAbort();
|
|
62845
|
+
else
|
|
62846
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
62224
62847
|
cancel = () => finish();
|
|
62225
62848
|
unregister = taps.addNotificationTap((method, params) => {
|
|
62226
62849
|
const notificationThreadId = extractThreadIdFromNotification(params);
|
|
62227
62850
|
if (method === "error") {
|
|
62228
62851
|
if (notificationThreadId === void 0 || notificationThreadId === threadId) {
|
|
62229
|
-
const
|
|
62230
|
-
|
|
62852
|
+
const p = params;
|
|
62853
|
+
if (p?.willRetry === true)
|
|
62854
|
+
return;
|
|
62855
|
+
const msg = p?.error?.message ?? p?.message;
|
|
62856
|
+
const info = p?.error?.codexErrorInfo;
|
|
62857
|
+
const infoText = info == null ? "" : ` (${typeof info === "string" ? info : JSON.stringify(info)})`;
|
|
62858
|
+
finish(new Error(`app-server error during compaction: ${String(msg ?? "unknown")}${infoText}`));
|
|
62231
62859
|
}
|
|
62232
62860
|
return;
|
|
62233
62861
|
}
|
|
@@ -62246,7 +62874,7 @@ var MainThreadInstructionsRefresher = class {
|
|
|
62246
62874
|
if (itemCompleted && status !== "failed")
|
|
62247
62875
|
finish();
|
|
62248
62876
|
else
|
|
62249
|
-
finish(new Error(interrupted ?
|
|
62877
|
+
finish(new Error(interrupted ? "compaction did not complete within budget (turn closed after interrupt)" : `compaction turn ended without completing (status=${status ?? "unknown"})`));
|
|
62250
62878
|
}
|
|
62251
62879
|
});
|
|
62252
62880
|
});
|
|
@@ -62273,37 +62901,148 @@ function errToString(err) {
|
|
|
62273
62901
|
return String(err);
|
|
62274
62902
|
}
|
|
62275
62903
|
|
|
62276
|
-
// ts/codex-agent/dist/
|
|
62277
|
-
|
|
62278
|
-
|
|
62279
|
-
|
|
62280
|
-
|
|
62281
|
-
|
|
62282
|
-
|
|
62283
|
-
|
|
62284
|
-
|
|
62285
|
-
|
|
62286
|
-
|
|
62287
|
-
|
|
62288
|
-
|
|
62289
|
-
|
|
62290
|
-
|
|
62291
|
-
|
|
62292
|
-
|
|
62293
|
-
|
|
62294
|
-
|
|
62295
|
-
|
|
62296
|
-
|
|
62297
|
-
const pathEntries = (inheritedPath ?? "").split(path8.delimiter).filter((entry) => entry && entry !== capabilityBinDir2);
|
|
62298
|
-
const effectivePath = [capabilityBinDir2, ...pathEntries].join(path8.delimiter);
|
|
62299
|
-
config.allow_login_shell = false;
|
|
62300
|
-
config.shell_environment_policy = {
|
|
62301
|
-
experimental_use_profile: false,
|
|
62302
|
-
set: { PATH: effectivePath }
|
|
62904
|
+
// ts/codex-agent/dist/compact.js
|
|
62905
|
+
async function runCodexCompact(host, { sessionKey, signal, log: log2 }) {
|
|
62906
|
+
const logger = log2 ?? host.log;
|
|
62907
|
+
if (!host.isMainSession(sessionKey)) {
|
|
62908
|
+
return { status: "unsupported", detail: "compact is only supported on the main session" };
|
|
62909
|
+
}
|
|
62910
|
+
if (signal.aborted)
|
|
62911
|
+
return { status: "timeout" };
|
|
62912
|
+
if (host.isMainLaneQuarantined()) {
|
|
62913
|
+
await host.applyPendingRestart(logger);
|
|
62914
|
+
if (host.isMainLaneQuarantined()) {
|
|
62915
|
+
return {
|
|
62916
|
+
status: "failed",
|
|
62917
|
+
detail: "main lane quarantined after a stalled compaction; the subprocess restart is still deferred behind an active turn"
|
|
62918
|
+
};
|
|
62919
|
+
}
|
|
62920
|
+
}
|
|
62921
|
+
if (host.refresher.isCompactUnsupported()) {
|
|
62922
|
+
return {
|
|
62923
|
+
status: "unsupported",
|
|
62924
|
+
detail: "thread/compact/start not supported by this codex CLI"
|
|
62303
62925
|
};
|
|
62304
62926
|
}
|
|
62305
|
-
|
|
62927
|
+
await host.applyPendingRestart(logger);
|
|
62928
|
+
const opened = await host.openMainThread(sessionKey, logger);
|
|
62929
|
+
if (!opened.ok)
|
|
62930
|
+
return { status: "failed", detail: opened.message };
|
|
62931
|
+
if (opened.reconcile === "stalled") {
|
|
62932
|
+
await host.quarantineAndBounce(logger);
|
|
62933
|
+
return {
|
|
62934
|
+
status: "timeout",
|
|
62935
|
+
detail: "instructions-refresh compaction stalled while opening the thread; subprocess bounced"
|
|
62936
|
+
};
|
|
62937
|
+
}
|
|
62938
|
+
if (opened.reconcile === "unsupported") {
|
|
62939
|
+
return {
|
|
62940
|
+
status: "unsupported",
|
|
62941
|
+
detail: "thread/compact/start not supported by this codex CLI"
|
|
62942
|
+
};
|
|
62943
|
+
}
|
|
62944
|
+
if (opened.reconcile === "refreshed") {
|
|
62945
|
+
return { status: "done", detail: "compacted by the instructions refresh during open" };
|
|
62946
|
+
}
|
|
62947
|
+
if (signal.aborted) {
|
|
62948
|
+
return { status: "timeout", detail: "budget elapsed while opening the thread" };
|
|
62949
|
+
}
|
|
62950
|
+
const { client, threadId } = opened;
|
|
62951
|
+
if (host.hasActiveTurn(threadId)) {
|
|
62952
|
+
return { status: "failed", detail: "a turn is active on the main thread" };
|
|
62953
|
+
}
|
|
62954
|
+
let stalled = false;
|
|
62955
|
+
try {
|
|
62956
|
+
return await host.withTapOnlyTurn(threadId, async () => {
|
|
62957
|
+
try {
|
|
62958
|
+
await host.refresher.runCompaction({ client, taps: host.taps, threadId, signal });
|
|
62959
|
+
host.refresher.recordCompacted(sessionKey, threadId);
|
|
62960
|
+
return { status: "done" };
|
|
62961
|
+
} catch (err) {
|
|
62962
|
+
if (err instanceof CompactionStalledError) {
|
|
62963
|
+
stalled = true;
|
|
62964
|
+
return { status: "timeout", detail: errToString2(err) };
|
|
62965
|
+
}
|
|
62966
|
+
if (err instanceof JsonRpcError && err.code === JSON_RPC_METHOD_NOT_FOUND) {
|
|
62967
|
+
return { status: "unsupported", detail: errToString2(err) };
|
|
62968
|
+
}
|
|
62969
|
+
return { status: "failed", detail: errToString2(err) };
|
|
62970
|
+
}
|
|
62971
|
+
});
|
|
62972
|
+
} finally {
|
|
62973
|
+
if (stalled) {
|
|
62974
|
+
await host.quarantineAndBounce(logger);
|
|
62975
|
+
}
|
|
62976
|
+
}
|
|
62306
62977
|
}
|
|
62978
|
+
function errToString2(err) {
|
|
62979
|
+
if (err instanceof Error)
|
|
62980
|
+
return err.message;
|
|
62981
|
+
return String(err);
|
|
62982
|
+
}
|
|
62983
|
+
|
|
62984
|
+
// ts/agent-core/dist/internal/async-queue.js
|
|
62985
|
+
var AsyncQueue = class {
|
|
62986
|
+
opts;
|
|
62987
|
+
items = [];
|
|
62988
|
+
waiter = null;
|
|
62989
|
+
closed = false;
|
|
62990
|
+
droppedCount = 0;
|
|
62991
|
+
constructor(opts = {}) {
|
|
62992
|
+
this.opts = opts;
|
|
62993
|
+
}
|
|
62994
|
+
/** True once close() ran — parked items may still drain via next(). */
|
|
62995
|
+
get isClosed() {
|
|
62996
|
+
return this.closed;
|
|
62997
|
+
}
|
|
62998
|
+
/** Parked items not yet consumed. */
|
|
62999
|
+
get size() {
|
|
63000
|
+
return this.items.length;
|
|
63001
|
+
}
|
|
63002
|
+
/** Items dropped past the parked cap (diagnostics). */
|
|
63003
|
+
get dropped() {
|
|
63004
|
+
return this.droppedCount;
|
|
63005
|
+
}
|
|
63006
|
+
/** Returns false when the queue is closed (item discarded). */
|
|
63007
|
+
push(item) {
|
|
63008
|
+
if (this.closed)
|
|
63009
|
+
return false;
|
|
63010
|
+
if (this.waiter) {
|
|
63011
|
+
const resolve4 = this.waiter;
|
|
63012
|
+
this.waiter = null;
|
|
63013
|
+
resolve4({ value: item, done: false });
|
|
63014
|
+
return true;
|
|
63015
|
+
}
|
|
63016
|
+
const cap = Math.max(1, this.opts.maxParked ?? 5e3);
|
|
63017
|
+
if (this.items.length >= cap) {
|
|
63018
|
+
this.items.shift();
|
|
63019
|
+
if (this.droppedCount === 0)
|
|
63020
|
+
this.opts.onFirstDrop?.();
|
|
63021
|
+
this.droppedCount += 1;
|
|
63022
|
+
}
|
|
63023
|
+
this.items.push(item);
|
|
63024
|
+
return true;
|
|
63025
|
+
}
|
|
63026
|
+
next() {
|
|
63027
|
+
if (this.items.length > 0) {
|
|
63028
|
+
return Promise.resolve({ value: this.items.shift(), done: false });
|
|
63029
|
+
}
|
|
63030
|
+
if (this.closed) {
|
|
63031
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
63032
|
+
}
|
|
63033
|
+
return new Promise((resolve4) => {
|
|
63034
|
+
this.waiter = resolve4;
|
|
63035
|
+
});
|
|
63036
|
+
}
|
|
63037
|
+
close() {
|
|
63038
|
+
if (this.closed)
|
|
63039
|
+
return;
|
|
63040
|
+
this.closed = true;
|
|
63041
|
+
const waiter = this.waiter;
|
|
63042
|
+
this.waiter = null;
|
|
63043
|
+
waiter?.({ value: void 0, done: true });
|
|
63044
|
+
}
|
|
63045
|
+
};
|
|
62307
63046
|
|
|
62308
63047
|
// ts/codex-agent/dist/event-mapping.js
|
|
62309
63048
|
var EventMapper = class {
|
|
@@ -62643,9 +63382,7 @@ function formatCommand(command) {
|
|
|
62643
63382
|
var TurnSink = class {
|
|
62644
63383
|
noteActivity;
|
|
62645
63384
|
mapper = new EventMapper();
|
|
62646
|
-
queue =
|
|
62647
|
-
resolver = null;
|
|
62648
|
-
closed = false;
|
|
63385
|
+
queue = new AsyncQueue();
|
|
62649
63386
|
constructor(noteActivity) {
|
|
62650
63387
|
this.noteActivity = noteActivity;
|
|
62651
63388
|
}
|
|
@@ -62653,40 +63390,312 @@ var TurnSink = class {
|
|
|
62653
63390
|
this.noteActivity?.();
|
|
62654
63391
|
}
|
|
62655
63392
|
push(envelope) {
|
|
62656
|
-
if (this.closed)
|
|
62657
|
-
return;
|
|
62658
|
-
if (this.resolver) {
|
|
62659
|
-
const r = this.resolver;
|
|
62660
|
-
this.resolver = null;
|
|
62661
|
-
r(envelope);
|
|
62662
|
-
return;
|
|
62663
|
-
}
|
|
62664
63393
|
this.queue.push(envelope);
|
|
62665
63394
|
}
|
|
62666
|
-
next() {
|
|
62667
|
-
const
|
|
62668
|
-
|
|
62669
|
-
return Promise.resolve(pending);
|
|
62670
|
-
if (this.closed) {
|
|
62671
|
-
return Promise.resolve({ kind: "turn_end" });
|
|
62672
|
-
}
|
|
62673
|
-
return new Promise((resolve4) => {
|
|
62674
|
-
this.resolver = resolve4;
|
|
62675
|
-
});
|
|
63395
|
+
async next() {
|
|
63396
|
+
const result = await this.queue.next();
|
|
63397
|
+
return result.done ? { kind: "turn_end" } : result.value;
|
|
62676
63398
|
}
|
|
62677
63399
|
close() {
|
|
62678
|
-
this.
|
|
62679
|
-
const r = this.resolver;
|
|
62680
|
-
this.resolver = null;
|
|
62681
|
-
r?.({ kind: "turn_end" });
|
|
63400
|
+
this.queue.close();
|
|
62682
63401
|
}
|
|
62683
63402
|
/** True once close() ran — the sink's terminal state (queued envelopes may
|
|
62684
63403
|
* still drain via next()). */
|
|
62685
63404
|
get isClosed() {
|
|
62686
|
-
return this.
|
|
63405
|
+
return this.queue.isClosed;
|
|
62687
63406
|
}
|
|
62688
63407
|
};
|
|
62689
63408
|
|
|
63409
|
+
// ts/codex-agent/dist/runtime-turn.js
|
|
63410
|
+
var CodexRuntimeTurn = class extends RuntimeTurnBase {
|
|
63411
|
+
trigger;
|
|
63412
|
+
opts;
|
|
63413
|
+
sink;
|
|
63414
|
+
constructor(sessionKey, trigger, opts) {
|
|
63415
|
+
super(sessionKey, trigger, opts.onDetach);
|
|
63416
|
+
this.trigger = trigger;
|
|
63417
|
+
this.opts = opts;
|
|
63418
|
+
this.sink = new TurnSink(() => this.touch());
|
|
63419
|
+
}
|
|
63420
|
+
async *drain() {
|
|
63421
|
+
yield {
|
|
63422
|
+
type: "runtime_session",
|
|
63423
|
+
runtimeSessionId: this.trigger.threadId,
|
|
63424
|
+
runtimeLaneKey: this.sessionKey,
|
|
63425
|
+
...this.opts.parentSessionKey ? { parentSessionKey: this.opts.parentSessionKey } : {}
|
|
63426
|
+
};
|
|
63427
|
+
let sawError = false;
|
|
63428
|
+
let sawOutcome = false;
|
|
63429
|
+
while (true) {
|
|
63430
|
+
const envelope = await this.sink.next();
|
|
63431
|
+
if (envelope.kind === "turn_end") {
|
|
63432
|
+
if (envelope.threadId)
|
|
63433
|
+
return;
|
|
63434
|
+
if (!sawError) {
|
|
63435
|
+
yield {
|
|
63436
|
+
type: "error",
|
|
63437
|
+
message: "subagent turn ended without turn/completed",
|
|
63438
|
+
groupKey: this.groupKey
|
|
63439
|
+
};
|
|
63440
|
+
}
|
|
63441
|
+
if (!sawOutcome)
|
|
63442
|
+
yield { type: "turn_outcome", outcome: "runtime_crash" };
|
|
63443
|
+
return;
|
|
63444
|
+
}
|
|
63445
|
+
const event = envelope.kind === "error" ? { type: "error", message: envelope.message } : envelope.event;
|
|
63446
|
+
if (event.type === "error")
|
|
63447
|
+
sawError = true;
|
|
63448
|
+
if (event.type === "turn_outcome")
|
|
63449
|
+
sawOutcome = true;
|
|
63450
|
+
yield projectRuntimeEvent(event, this.groupKey);
|
|
63451
|
+
}
|
|
63452
|
+
}
|
|
63453
|
+
};
|
|
63454
|
+
|
|
63455
|
+
// ts/codex-agent/dist/foreign-threads.js
|
|
63456
|
+
var ForeignThreadRegistry = class {
|
|
63457
|
+
host;
|
|
63458
|
+
threads = /* @__PURE__ */ new Map();
|
|
63459
|
+
constructor(host) {
|
|
63460
|
+
this.host = host;
|
|
63461
|
+
}
|
|
63462
|
+
/** Live (registered, not closed) subagent threads. */
|
|
63463
|
+
get size() {
|
|
63464
|
+
return this.threads.size;
|
|
63465
|
+
}
|
|
63466
|
+
openTurns() {
|
|
63467
|
+
let count = 0;
|
|
63468
|
+
for (const thread of this.threads.values())
|
|
63469
|
+
if (thread.turn)
|
|
63470
|
+
count += 1;
|
|
63471
|
+
return count;
|
|
63472
|
+
}
|
|
63473
|
+
/**
|
|
63474
|
+
* Notifications for a thread no dispatch owns. Returns false when the
|
|
63475
|
+
* caller should keep treating the frame as unroutable.
|
|
63476
|
+
*/
|
|
63477
|
+
route(method, params, threadId) {
|
|
63478
|
+
if (method === "thread/started") {
|
|
63479
|
+
if (this.host.sessionManager.getSessionKey(threadId) || this.threads.has(threadId)) {
|
|
63480
|
+
return true;
|
|
63481
|
+
}
|
|
63482
|
+
const info = extractThreadInfo(params);
|
|
63483
|
+
if (!info || info.source !== "subAgent")
|
|
63484
|
+
return true;
|
|
63485
|
+
this.register(info);
|
|
63486
|
+
return true;
|
|
63487
|
+
}
|
|
63488
|
+
let thread = this.threads.get(threadId);
|
|
63489
|
+
if (method === "thread/closed" || method === "thread/archived" || method === "thread/deleted") {
|
|
63490
|
+
if (!thread)
|
|
63491
|
+
return false;
|
|
63492
|
+
this.close(thread, method.slice("thread/".length));
|
|
63493
|
+
return true;
|
|
63494
|
+
}
|
|
63495
|
+
if (!thread) {
|
|
63496
|
+
if (this.host.sessionManager.getSessionKey(threadId))
|
|
63497
|
+
return false;
|
|
63498
|
+
if (method !== "turn/started" && method !== "turn/completed" && !method.startsWith("item/")) {
|
|
63499
|
+
return false;
|
|
63500
|
+
}
|
|
63501
|
+
thread = this.register({ id: threadId });
|
|
63502
|
+
}
|
|
63503
|
+
if (method === "turn/started") {
|
|
63504
|
+
if (thread.turn)
|
|
63505
|
+
thread.turn.touch();
|
|
63506
|
+
else
|
|
63507
|
+
this.openTurn(thread);
|
|
63508
|
+
return true;
|
|
63509
|
+
}
|
|
63510
|
+
if (!thread.turn) {
|
|
63511
|
+
if (method !== "turn/completed" && !method.startsWith("item/"))
|
|
63512
|
+
return true;
|
|
63513
|
+
this.openTurn(thread);
|
|
63514
|
+
}
|
|
63515
|
+
const turn = thread.turn;
|
|
63516
|
+
turn.sink.touchActivity();
|
|
63517
|
+
for (const event of turn.sink.mapper.map(method, params)) {
|
|
63518
|
+
turn.sink.push({ kind: "runtime", event });
|
|
63519
|
+
}
|
|
63520
|
+
if (method === "turn/completed") {
|
|
63521
|
+
this.endTurn(thread, { kind: "turn_end", threadId });
|
|
63522
|
+
this.host.log?.info?.(`runtime-initiated turn ${turn.groupKey} on subagent thread ${threadId} completed`);
|
|
63523
|
+
}
|
|
63524
|
+
return true;
|
|
63525
|
+
}
|
|
63526
|
+
/** Subagent threads die with the app-server: end open turns, close child sessions. */
|
|
63527
|
+
dropAll(reason) {
|
|
63528
|
+
for (const thread of [...this.threads.values()]) {
|
|
63529
|
+
this.close(thread, reason);
|
|
63530
|
+
}
|
|
63531
|
+
}
|
|
63532
|
+
register(info) {
|
|
63533
|
+
const parentSessionKey = (info.parentThreadId ? this.threads.get(info.parentThreadId)?.sessionKey ?? this.host.sessionManager.getSessionKey(info.parentThreadId) : void 0) ?? this.host.sessionManager.mainSessionKey;
|
|
63534
|
+
const thread = {
|
|
63535
|
+
threadId: info.id,
|
|
63536
|
+
sessionKey: `codex-sub:${info.id}`,
|
|
63537
|
+
parentThreadId: info.parentThreadId,
|
|
63538
|
+
parentSessionKey,
|
|
63539
|
+
nickname: info.nickname,
|
|
63540
|
+
role: info.role
|
|
63541
|
+
};
|
|
63542
|
+
this.threads.set(info.id, thread);
|
|
63543
|
+
this.host.log?.info?.(`subagent thread ${info.id} registered (parent ${info.parentThreadId ?? "unknown"} \u2192 ${parentSessionKey}${info.nickname ? `, ${info.nickname}` : ""}${info.role ? ` / ${info.role}` : ""}); ${this.threads.size} live`);
|
|
63544
|
+
return thread;
|
|
63545
|
+
}
|
|
63546
|
+
openTurn(thread) {
|
|
63547
|
+
const turn = new CodexRuntimeTurn(thread.sessionKey, {
|
|
63548
|
+
kind: "subagent",
|
|
63549
|
+
threadId: thread.threadId,
|
|
63550
|
+
...thread.parentThreadId ? { parentThreadId: thread.parentThreadId } : {},
|
|
63551
|
+
...thread.nickname ? { nickname: thread.nickname } : {},
|
|
63552
|
+
...thread.role ? { role: thread.role } : {}
|
|
63553
|
+
}, {
|
|
63554
|
+
parentSessionKey: thread.parentSessionKey,
|
|
63555
|
+
onDetach: (reason) => {
|
|
63556
|
+
if (thread.turn !== turn)
|
|
63557
|
+
return;
|
|
63558
|
+
this.endTurn(thread, { kind: "error", message: `subagent turn detached: ${reason}` });
|
|
63559
|
+
}
|
|
63560
|
+
});
|
|
63561
|
+
thread.turn = turn;
|
|
63562
|
+
this.host.log?.info?.(`runtime-initiated turn ${turn.groupKey} opened on subagent thread ${thread.threadId}`);
|
|
63563
|
+
this.host.activity.surfaceTurn(turn);
|
|
63564
|
+
}
|
|
63565
|
+
/** The thread's open turn is over: last envelope, sink closed, restart re-driven. */
|
|
63566
|
+
endTurn(thread, last) {
|
|
63567
|
+
const turn = thread.turn;
|
|
63568
|
+
if (!turn)
|
|
63569
|
+
return;
|
|
63570
|
+
thread.turn = void 0;
|
|
63571
|
+
turn.sink.push(last);
|
|
63572
|
+
turn.sink.close();
|
|
63573
|
+
this.host.afterTurnClosed();
|
|
63574
|
+
}
|
|
63575
|
+
close(thread, reason) {
|
|
63576
|
+
if (this.threads.get(thread.threadId) !== thread)
|
|
63577
|
+
return;
|
|
63578
|
+
this.threads.delete(thread.threadId);
|
|
63579
|
+
this.endTurn(thread, {
|
|
63580
|
+
kind: "error",
|
|
63581
|
+
message: `subagent thread ${thread.threadId} ${reason}`
|
|
63582
|
+
});
|
|
63583
|
+
this.host.log?.info?.(`subagent thread ${thread.threadId} ${reason}; ${this.threads.size} live`);
|
|
63584
|
+
this.host.activity.emit({ kind: "session_closed", sessionKey: thread.sessionKey, reason });
|
|
63585
|
+
}
|
|
63586
|
+
};
|
|
63587
|
+
|
|
63588
|
+
// ts/codex-agent/dist/injection-registry.js
|
|
63589
|
+
var CodexInjectionRegistry = class {
|
|
63590
|
+
sessions = /* @__PURE__ */ new Map();
|
|
63591
|
+
/** Record a successful steer. `deliveryKey` may join several WorkItem ids with ','. */
|
|
63592
|
+
register(sessionKey, deliveryKey) {
|
|
63593
|
+
let entries = this.sessions.get(sessionKey);
|
|
63594
|
+
if (!entries) {
|
|
63595
|
+
entries = /* @__PURE__ */ new Map();
|
|
63596
|
+
this.sessions.set(sessionKey, entries);
|
|
63597
|
+
}
|
|
63598
|
+
for (const id of splitDeliveryKey(deliveryKey)) {
|
|
63599
|
+
if (!entries.has(id))
|
|
63600
|
+
entries.set(id, { settled: false, drained: false });
|
|
63601
|
+
}
|
|
63602
|
+
}
|
|
63603
|
+
/** The buffered copies behind these WorkItems drained (group dispatch or discard). */
|
|
63604
|
+
markDrained(sessionKey, deliveryKey) {
|
|
63605
|
+
const entries = this.sessions.get(sessionKey);
|
|
63606
|
+
if (!entries)
|
|
63607
|
+
return;
|
|
63608
|
+
for (const id of splitDeliveryKey(deliveryKey)) {
|
|
63609
|
+
const entry = entries.get(id);
|
|
63610
|
+
if (!entry)
|
|
63611
|
+
continue;
|
|
63612
|
+
entry.drained = true;
|
|
63613
|
+
if (entry.settled)
|
|
63614
|
+
entries.delete(id);
|
|
63615
|
+
}
|
|
63616
|
+
if (entries.size === 0)
|
|
63617
|
+
this.sessions.delete(sessionKey);
|
|
63618
|
+
}
|
|
63619
|
+
/** The turn every injection of this session was steered into has ended. */
|
|
63620
|
+
settleAll(sessionKey) {
|
|
63621
|
+
const entries = this.sessions.get(sessionKey);
|
|
63622
|
+
if (!entries)
|
|
63623
|
+
return;
|
|
63624
|
+
for (const [id, entry] of entries) {
|
|
63625
|
+
entry.settled = true;
|
|
63626
|
+
if (entry.drained)
|
|
63627
|
+
entries.delete(id);
|
|
63628
|
+
}
|
|
63629
|
+
if (entries.size === 0)
|
|
63630
|
+
this.sessions.delete(sessionKey);
|
|
63631
|
+
}
|
|
63632
|
+
/** An injection whose buffered copy has not drained yet (bookkeeping owed). */
|
|
63633
|
+
hasPending(sessionKey) {
|
|
63634
|
+
const entries = this.sessions.get(sessionKey);
|
|
63635
|
+
if (!entries)
|
|
63636
|
+
return false;
|
|
63637
|
+
for (const entry of entries.values()) {
|
|
63638
|
+
if (!entry.drained)
|
|
63639
|
+
return true;
|
|
63640
|
+
}
|
|
63641
|
+
return false;
|
|
63642
|
+
}
|
|
63643
|
+
/** An injection whose turn is still running (the only state that may defer a complete). */
|
|
63644
|
+
hasUnsettled(sessionKey) {
|
|
63645
|
+
const entries = this.sessions.get(sessionKey);
|
|
63646
|
+
if (!entries)
|
|
63647
|
+
return false;
|
|
63648
|
+
for (const entry of entries.values()) {
|
|
63649
|
+
if (!entry.settled)
|
|
63650
|
+
return true;
|
|
63651
|
+
}
|
|
63652
|
+
return false;
|
|
63653
|
+
}
|
|
63654
|
+
/** Drop every entry (turn aborted / subprocess gone): nothing is owed anymore. */
|
|
63655
|
+
clear(sessionKey) {
|
|
63656
|
+
if (sessionKey === void 0) {
|
|
63657
|
+
this.sessions.clear();
|
|
63658
|
+
return;
|
|
63659
|
+
}
|
|
63660
|
+
this.sessions.delete(sessionKey);
|
|
63661
|
+
}
|
|
63662
|
+
};
|
|
63663
|
+
function splitDeliveryKey(deliveryKey) {
|
|
63664
|
+
return deliveryKey.split(",").map((id) => id.trim()).filter((id) => id.length > 0);
|
|
63665
|
+
}
|
|
63666
|
+
|
|
63667
|
+
// ts/codex-agent/dist/server-requests.js
|
|
63668
|
+
var APPROVAL_DENIALS = {
|
|
63669
|
+
"item/commandExecution/requestApproval": { decision: "decline" },
|
|
63670
|
+
"item/fileChange/requestApproval": { decision: "decline" },
|
|
63671
|
+
// NOT listed: `item/permissions/requestApproval` — its response shape is a
|
|
63672
|
+
// permission GRANT (no deny variant), so denial is correctly expressed by
|
|
63673
|
+
// the -32601 error fallback.
|
|
63674
|
+
execCommandApproval: { decision: "denied" },
|
|
63675
|
+
applyPatchApproval: { decision: "denied" }
|
|
63676
|
+
};
|
|
63677
|
+
function answerServerRequest(method) {
|
|
63678
|
+
return Object.hasOwn(APPROVAL_DENIALS, method) ? APPROVAL_DENIALS[method] : void 0;
|
|
63679
|
+
}
|
|
63680
|
+
|
|
63681
|
+
// ts/codex-agent/dist/thread-config.js
|
|
63682
|
+
import * as path9 from "node:path";
|
|
63683
|
+
function buildThreadConfigOverrides({ reasoningEffort, capabilityBinDir: capabilityBinDir2, inheritedPath, platform = process.platform }) {
|
|
63684
|
+
const config = {};
|
|
63685
|
+
if (reasoningEffort)
|
|
63686
|
+
config.model_reasoning_effort = reasoningEffort;
|
|
63687
|
+
if (capabilityBinDir2 && platform !== "win32") {
|
|
63688
|
+
const pathEntries = (inheritedPath ?? "").split(path9.delimiter).filter((entry) => entry && entry !== capabilityBinDir2);
|
|
63689
|
+
const effectivePath = [capabilityBinDir2, ...pathEntries].join(path9.delimiter);
|
|
63690
|
+
config.allow_login_shell = false;
|
|
63691
|
+
config.shell_environment_policy = {
|
|
63692
|
+
experimental_use_profile: false,
|
|
63693
|
+
set: { PATH: effectivePath }
|
|
63694
|
+
};
|
|
63695
|
+
}
|
|
63696
|
+
return Object.keys(config).length > 0 ? config : void 0;
|
|
63697
|
+
}
|
|
63698
|
+
|
|
62690
63699
|
// ts/codex-agent/dist/dispatch.js
|
|
62691
63700
|
var CodexAppServerAdapter = class {
|
|
62692
63701
|
opts;
|
|
@@ -62714,6 +63723,9 @@ var CodexAppServerAdapter = class {
|
|
|
62714
63723
|
instructionsRefresher;
|
|
62715
63724
|
stopping = false;
|
|
62716
63725
|
lastUnroutedNotificationWarnAt = 0;
|
|
63726
|
+
/** Subagent threads and their runtime-initiated turns (foreign-threads.ts). */
|
|
63727
|
+
foreignThreads;
|
|
63728
|
+
activity;
|
|
62717
63729
|
/**
|
|
62718
63730
|
* Store an active turn sink keyed by threadId. If a sink already exists for
|
|
62719
63731
|
* the same threadId, log a warning and fail the existing sink — this
|
|
@@ -62739,6 +63751,18 @@ var CodexAppServerAdapter = class {
|
|
|
62739
63751
|
compactTimeoutMs: opts.instructionsCompactTimeoutMs,
|
|
62740
63752
|
interruptGraceMs: opts.instructionsInterruptGraceMs
|
|
62741
63753
|
});
|
|
63754
|
+
this.activity = new RuntimeActivityPort("CodexAppServerAdapter", opts.log);
|
|
63755
|
+
this.foreignThreads = new ForeignThreadRegistry({
|
|
63756
|
+
sessionManager: opts.sessionManager,
|
|
63757
|
+
log: opts.log,
|
|
63758
|
+
activity: this.activity,
|
|
63759
|
+
// A restart deferred behind subagent work must not starve once it ends.
|
|
63760
|
+
afterTurnClosed: () => {
|
|
63761
|
+
if (!this.restartRequested)
|
|
63762
|
+
return;
|
|
63763
|
+
void this.applyPendingRestart().catch((err) => this.opts.log?.warn?.(`deferred restart failed: ${errToString3(err)}`));
|
|
63764
|
+
}
|
|
63765
|
+
});
|
|
62742
63766
|
}
|
|
62743
63767
|
/** Register a listener for every server notification; returns unregister. */
|
|
62744
63768
|
addNotificationTap(tap) {
|
|
@@ -62795,7 +63819,7 @@ var CodexAppServerAdapter = class {
|
|
|
62795
63819
|
this.injections.register(sessionKey, inputLifecycle.deliveryKey);
|
|
62796
63820
|
return true;
|
|
62797
63821
|
} catch (err) {
|
|
62798
|
-
this.opts.log?.warn?.(`turn/steer failed: ${
|
|
63822
|
+
this.opts.log?.warn?.(`turn/steer failed: ${errToString3(err)}`);
|
|
62799
63823
|
return false;
|
|
62800
63824
|
}
|
|
62801
63825
|
}
|
|
@@ -62809,11 +63833,50 @@ var CodexAppServerAdapter = class {
|
|
|
62809
63833
|
return;
|
|
62810
63834
|
const turnId = this.activeTurnIds.get(threadId);
|
|
62811
63835
|
if (turnId && this.client && !this.client.isDisposed()) {
|
|
62812
|
-
this.client.sendRequest("turn/interrupt", { threadId, turnId }).catch((err) => this.opts.log?.warn?.(`turn/interrupt failed: ${
|
|
63836
|
+
this.client.sendRequest("turn/interrupt", { threadId, turnId }).catch((err) => this.opts.log?.warn?.(`turn/interrupt failed: ${errToString3(err)}`));
|
|
62813
63837
|
}
|
|
62814
63838
|
sink.push({ kind: "error", message: "dispatch inactivity deadline exceeded" });
|
|
62815
63839
|
sink.close();
|
|
62816
63840
|
}
|
|
63841
|
+
/** Idle auto-compact (compact.ts): the compaction primitive as a tap-only main-thread turn. */
|
|
63842
|
+
compact(opts) {
|
|
63843
|
+
return runCodexCompact({
|
|
63844
|
+
log: this.opts.log,
|
|
63845
|
+
taps: this,
|
|
63846
|
+
refresher: this.instructionsRefresher,
|
|
63847
|
+
isMainSession: (sessionKey) => this.opts.sessionManager.isMain(sessionKey),
|
|
63848
|
+
isMainLaneQuarantined: () => this.mainLaneQuarantined,
|
|
63849
|
+
quarantineAndBounce: async (log2) => {
|
|
63850
|
+
this.mainLaneQuarantined = true;
|
|
63851
|
+
this.requestProcessRestart();
|
|
63852
|
+
await this.applyPendingRestart(log2);
|
|
63853
|
+
},
|
|
63854
|
+
applyPendingRestart: (log2) => this.applyPendingRestart(log2),
|
|
63855
|
+
openMainThread: (sessionKey, log2) => this.withOpening(() => this.openDispatchTarget(sessionKey, true, log2)),
|
|
63856
|
+
hasActiveTurn: (threadId) => this.activeTurns.has(threadId),
|
|
63857
|
+
withTapOnlyTurn: async (threadId, fn) => {
|
|
63858
|
+
this.reconcilingThreadIds.add(threadId);
|
|
63859
|
+
try {
|
|
63860
|
+
return await this.withOpening(fn);
|
|
63861
|
+
} finally {
|
|
63862
|
+
this.reconcilingThreadIds.delete(threadId);
|
|
63863
|
+
}
|
|
63864
|
+
}
|
|
63865
|
+
}, opts);
|
|
63866
|
+
}
|
|
63867
|
+
/**
|
|
63868
|
+
* Real work on the subprocess that predates any TurnSink (thread open,
|
|
63869
|
+
* a tap-only compaction turn): counted so applyPendingRestart cannot
|
|
63870
|
+
* stop() the subprocess out from under it.
|
|
63871
|
+
*/
|
|
63872
|
+
async withOpening(fn) {
|
|
63873
|
+
this.openingDispatches += 1;
|
|
63874
|
+
try {
|
|
63875
|
+
return await fn();
|
|
63876
|
+
} finally {
|
|
63877
|
+
this.openingDispatches -= 1;
|
|
63878
|
+
}
|
|
63879
|
+
}
|
|
62817
63880
|
hasPendingInjections(sessionKey) {
|
|
62818
63881
|
return this.injections.hasPending(sessionKey);
|
|
62819
63882
|
}
|
|
@@ -62823,6 +63886,25 @@ var CodexAppServerAdapter = class {
|
|
|
62823
63886
|
acknowledgeDiscardedInjection(sessionKey, deliveryKey) {
|
|
62824
63887
|
this.injections.markDrained(sessionKey, deliveryKey);
|
|
62825
63888
|
}
|
|
63889
|
+
// --- runtime-initiated work -------------------------------------------------
|
|
63890
|
+
subscribeRuntimeActivity(handler) {
|
|
63891
|
+
return this.activity.subscribe(handler);
|
|
63892
|
+
}
|
|
63893
|
+
/**
|
|
63894
|
+
* Busy = a dispatch turn, a dispatch opening its thread (possibly running
|
|
63895
|
+
* the instructions-refresh compaction turn), or a subagent thread's turn
|
|
63896
|
+
* is executing. Live subagent threads between turns are reported as
|
|
63897
|
+
* background work, not busy.
|
|
63898
|
+
*/
|
|
63899
|
+
isBusy() {
|
|
63900
|
+
return isRuntimeBusy(this.busyState());
|
|
63901
|
+
}
|
|
63902
|
+
busyState() {
|
|
63903
|
+
return {
|
|
63904
|
+
activeTurns: this.activeTurns.size + (this.openingDispatches > 0 || this.reconcilingThreadIds.size > 0 ? 1 : 0) + this.foreignThreads.openTurns(),
|
|
63905
|
+
backgroundWork: this.foreignThreads.size
|
|
63906
|
+
};
|
|
63907
|
+
}
|
|
62826
63908
|
async *dispatch({ event, bodyForAgent, sessionKey, context: context2, inputLifecycle, noteActivity }) {
|
|
62827
63909
|
if (inputLifecycle)
|
|
62828
63910
|
this.injections.markDrained(sessionKey, inputLifecycle.deliveryKey);
|
|
@@ -62855,13 +63937,7 @@ var CodexAppServerAdapter = class {
|
|
|
62855
63937
|
let reconcileStalled = false;
|
|
62856
63938
|
for (let attempt = 0; ; attempt++) {
|
|
62857
63939
|
await this.applyPendingRestart(context2.log);
|
|
62858
|
-
this.
|
|
62859
|
-
let opened;
|
|
62860
|
-
try {
|
|
62861
|
-
opened = await this.openDispatchTarget(sessionKey, isMainSession, log2);
|
|
62862
|
-
} finally {
|
|
62863
|
-
this.openingDispatches -= 1;
|
|
62864
|
-
}
|
|
63940
|
+
const opened = await this.withOpening(() => this.openDispatchTarget(sessionKey, isMainSession, log2));
|
|
62865
63941
|
if (!opened.ok) {
|
|
62866
63942
|
yield { type: "error", message: opened.message };
|
|
62867
63943
|
return;
|
|
@@ -62878,7 +63954,7 @@ var CodexAppServerAdapter = class {
|
|
|
62878
63954
|
}
|
|
62879
63955
|
const sink = new TurnSink(noteActivity);
|
|
62880
63956
|
this.setActiveTurn(threadId, sink, log2);
|
|
62881
|
-
const groupKey =
|
|
63957
|
+
const groupKey = randomUUID3();
|
|
62882
63958
|
let sawTurnEnd = false;
|
|
62883
63959
|
let releasePreparedAttachments = () => {
|
|
62884
63960
|
};
|
|
@@ -62894,7 +63970,7 @@ var CodexAppServerAdapter = class {
|
|
|
62894
63970
|
preparedImages = prepared.attachments.images;
|
|
62895
63971
|
releasePreparedAttachments = pinLocalAttachmentPaths(preparedImages);
|
|
62896
63972
|
} catch (err) {
|
|
62897
|
-
log2?.warn?.(`failed to prepare local attachments: ${
|
|
63973
|
+
log2?.warn?.(`failed to prepare local attachments: ${errToString3(err)}`);
|
|
62898
63974
|
}
|
|
62899
63975
|
const turnInput = buildTurnInput(preparedBody, preparedImages);
|
|
62900
63976
|
const startTurn = (targetThreadId) => {
|
|
@@ -62912,7 +63988,7 @@ var CodexAppServerAdapter = class {
|
|
|
62912
63988
|
try {
|
|
62913
63989
|
turnStartResult = await startTurn(threadId);
|
|
62914
63990
|
} catch (err) {
|
|
62915
|
-
const message =
|
|
63991
|
+
const message = errToString3(err);
|
|
62916
63992
|
if (!isMainSession) {
|
|
62917
63993
|
yield {
|
|
62918
63994
|
type: "runtime_session",
|
|
@@ -62951,7 +64027,7 @@ var CodexAppServerAdapter = class {
|
|
|
62951
64027
|
};
|
|
62952
64028
|
yield {
|
|
62953
64029
|
type: "error",
|
|
62954
|
-
message: `Codex turn/start failed; could not create replacement thread: ${
|
|
64030
|
+
message: `Codex turn/start failed; could not create replacement thread: ${errToString3(createErr)}`
|
|
62955
64031
|
};
|
|
62956
64032
|
return;
|
|
62957
64033
|
}
|
|
@@ -62967,7 +64043,7 @@ var CodexAppServerAdapter = class {
|
|
|
62967
64043
|
};
|
|
62968
64044
|
yield {
|
|
62969
64045
|
type: "error",
|
|
62970
|
-
message: `Codex turn/start failed after retry: ${
|
|
64046
|
+
message: `Codex turn/start failed after retry: ${errToString3(retryErr)}`
|
|
62971
64047
|
};
|
|
62972
64048
|
return;
|
|
62973
64049
|
}
|
|
@@ -62990,28 +64066,7 @@ var CodexAppServerAdapter = class {
|
|
|
62990
64066
|
sawTurnEnd = true;
|
|
62991
64067
|
break;
|
|
62992
64068
|
}
|
|
62993
|
-
|
|
62994
|
-
yield { type: "error", message: envelope.message };
|
|
62995
|
-
continue;
|
|
62996
|
-
}
|
|
62997
|
-
const runtimeEvent = envelope.event;
|
|
62998
|
-
if (runtimeEvent.type === "error") {
|
|
62999
|
-
yield runtimeEvent;
|
|
63000
|
-
continue;
|
|
63001
|
-
}
|
|
63002
|
-
if (runtimeEvent.type === "runtime_session") {
|
|
63003
|
-
yield runtimeEvent;
|
|
63004
|
-
continue;
|
|
63005
|
-
}
|
|
63006
|
-
if (runtimeEvent.type === "text") {
|
|
63007
|
-
yield { ...runtimeEvent, project: false, groupKey };
|
|
63008
|
-
continue;
|
|
63009
|
-
}
|
|
63010
|
-
if (runtimeEvent.type === "turn_outcome") {
|
|
63011
|
-
yield runtimeEvent;
|
|
63012
|
-
continue;
|
|
63013
|
-
}
|
|
63014
|
-
yield { ...runtimeEvent, groupKey };
|
|
64069
|
+
yield projectRuntimeEvent(envelope.kind === "error" ? { type: "error", message: envelope.message } : envelope.event, groupKey);
|
|
63015
64070
|
}
|
|
63016
64071
|
} finally {
|
|
63017
64072
|
releasePreparedAttachments();
|
|
@@ -63034,7 +64089,7 @@ var CodexAppServerAdapter = class {
|
|
|
63034
64089
|
try {
|
|
63035
64090
|
await this.ensureStarted(log2);
|
|
63036
64091
|
} catch (err) {
|
|
63037
|
-
return { ok: false, message: `Codex app-server failed to start: ${
|
|
64092
|
+
return { ok: false, message: `Codex app-server failed to start: ${errToString3(err)}` };
|
|
63038
64093
|
}
|
|
63039
64094
|
const client = this.client;
|
|
63040
64095
|
if (!client) {
|
|
@@ -63051,7 +64106,7 @@ var CodexAppServerAdapter = class {
|
|
|
63051
64106
|
this.instructionsRefresher.recordBaked(sessionKey, threadId, sentInstructions);
|
|
63052
64107
|
this.resumedThreadIds.add(threadId);
|
|
63053
64108
|
} catch (err) {
|
|
63054
|
-
return { ok: false, message: `Codex thread/start failed: ${
|
|
64109
|
+
return { ok: false, message: `Codex thread/start failed: ${errToString3(err)}` };
|
|
63055
64110
|
}
|
|
63056
64111
|
} else if (isMainSession && !this.resumedThreadIds.has(threadId)) {
|
|
63057
64112
|
const sentInstructions = this.opts.developerInstructions;
|
|
@@ -63061,14 +64116,14 @@ var CodexAppServerAdapter = class {
|
|
|
63061
64116
|
this.instructionsRefresher.recordResumed(threadId, sentInstructions);
|
|
63062
64117
|
this.resumedThreadIds.add(threadId);
|
|
63063
64118
|
} catch (err) {
|
|
63064
|
-
log2?.warn?.(`thread/resume failed (${
|
|
64119
|
+
log2?.warn?.(`thread/resume failed (${errToString3(err)}); attempting one-shot fresh-thread start`);
|
|
63065
64120
|
let freshThreadId;
|
|
63066
64121
|
try {
|
|
63067
64122
|
freshThreadId = await this.openThread(client, { resumeId: void 0 });
|
|
63068
64123
|
} catch (innerErr) {
|
|
63069
64124
|
return {
|
|
63070
64125
|
ok: false,
|
|
63071
|
-
message: `Codex thread/start failed after resume error (persisted thread retained): ${
|
|
64126
|
+
message: `Codex thread/start failed after resume error (persisted thread retained): ${errToString3(innerErr)}`
|
|
63072
64127
|
};
|
|
63073
64128
|
}
|
|
63074
64129
|
this.opts.sessionManager.clearMainThread();
|
|
@@ -63149,7 +64204,7 @@ var CodexAppServerAdapter = class {
|
|
|
63149
64204
|
this.opts.sessionManager.cleanupFork(fork.sessionKey);
|
|
63150
64205
|
}
|
|
63151
64206
|
logForkFailure(err) {
|
|
63152
|
-
this.opts.log?.warn?.(`thread/fork failed: ${
|
|
64207
|
+
this.opts.log?.warn?.(`thread/fork failed: ${errToString3(err)}`);
|
|
63153
64208
|
return null;
|
|
63154
64209
|
}
|
|
63155
64210
|
/**
|
|
@@ -63176,7 +64231,7 @@ var CodexAppServerAdapter = class {
|
|
|
63176
64231
|
*/
|
|
63177
64232
|
openingDispatches = 0;
|
|
63178
64233
|
async applyPendingRestart(log2) {
|
|
63179
|
-
if (!this.restartRequested || this.
|
|
64234
|
+
if (!this.restartRequested || this.isBusy())
|
|
63180
64235
|
return;
|
|
63181
64236
|
this.restartRequested = false;
|
|
63182
64237
|
(log2 ?? this.opts.log)?.info?.("restarting codex app-server after a capability change (the fresh-process thread/resume applies the refreshed developerInstructions to the persisted thread configuration; the model-visible context is reconciled before the next turn)");
|
|
@@ -63194,6 +64249,7 @@ var CodexAppServerAdapter = class {
|
|
|
63194
64249
|
this.resumedThreadIds.clear();
|
|
63195
64250
|
this.instructionsRefresher.clearThreadState();
|
|
63196
64251
|
this.mainLaneQuarantined = false;
|
|
64252
|
+
this.foreignThreads.dropAll("lost: Codex app-server stopped");
|
|
63197
64253
|
this.notifyTapsDisposed("Codex app-server stopped");
|
|
63198
64254
|
if (client)
|
|
63199
64255
|
client.dispose(new Error("adapter stopped"));
|
|
@@ -63212,6 +64268,7 @@ var CodexAppServerAdapter = class {
|
|
|
63212
64268
|
this.activeTurns.clear();
|
|
63213
64269
|
this.activeTurnIds.clear();
|
|
63214
64270
|
this.injections.clear();
|
|
64271
|
+
this.foreignThreads.dropAll("lost: Codex app-server disposed");
|
|
63215
64272
|
this.client = null;
|
|
63216
64273
|
this.proc = null;
|
|
63217
64274
|
this.initialized = false;
|
|
@@ -63242,7 +64299,7 @@ var CodexAppServerAdapter = class {
|
|
|
63242
64299
|
if (this.opts.capabilityBinDir) {
|
|
63243
64300
|
const pathKey = IS_WIN32 ? Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
|
|
63244
64301
|
const existing = env[pathKey];
|
|
63245
|
-
env[pathKey] = existing ? `${this.opts.capabilityBinDir}${
|
|
64302
|
+
env[pathKey] = existing ? `${this.opts.capabilityBinDir}${path10.delimiter}${existing}` : this.opts.capabilityBinDir;
|
|
63246
64303
|
}
|
|
63247
64304
|
if (this.opts.contextFilePath) {
|
|
63248
64305
|
env.PRLL_CONTEXT_FILE = this.opts.contextFilePath;
|
|
@@ -63326,6 +64383,7 @@ var CodexAppServerAdapter = class {
|
|
|
63326
64383
|
this.resumedThreadIds.clear();
|
|
63327
64384
|
this.instructionsRefresher.clearThreadState();
|
|
63328
64385
|
this.mainLaneQuarantined = false;
|
|
64386
|
+
this.foreignThreads.dropAll(`lost: Codex app-server ${reason}`);
|
|
63329
64387
|
this.notifyTapsDisposed(`Codex app-server ${reason}`);
|
|
63330
64388
|
this.client = null;
|
|
63331
64389
|
this.proc = null;
|
|
@@ -63367,7 +64425,7 @@ var CodexAppServerAdapter = class {
|
|
|
63367
64425
|
try {
|
|
63368
64426
|
tap(method, params);
|
|
63369
64427
|
} catch (err) {
|
|
63370
|
-
this.opts.log?.warn?.(`notification tap threw: ${
|
|
64428
|
+
this.opts.log?.warn?.(`notification tap threw: ${errToString3(err)}`);
|
|
63371
64429
|
}
|
|
63372
64430
|
}
|
|
63373
64431
|
const threadId = extractThreadIdFromNotification(params);
|
|
@@ -63384,6 +64442,8 @@ var CodexAppServerAdapter = class {
|
|
|
63384
64442
|
if (!sink) {
|
|
63385
64443
|
if (this.reconcilingThreadIds.has(threadId))
|
|
63386
64444
|
return;
|
|
64445
|
+
if (this.foreignThreads.route(method, params, threadId))
|
|
64446
|
+
return;
|
|
63387
64447
|
const now = Date.now();
|
|
63388
64448
|
if (now - this.lastUnroutedNotificationWarnAt > 1e4) {
|
|
63389
64449
|
this.lastUnroutedNotificationWarnAt = now;
|
|
@@ -63401,7 +64461,7 @@ var CodexAppServerAdapter = class {
|
|
|
63401
64461
|
}
|
|
63402
64462
|
}
|
|
63403
64463
|
};
|
|
63404
|
-
function
|
|
64464
|
+
function errToString3(err) {
|
|
63405
64465
|
if (err instanceof Error)
|
|
63406
64466
|
return err.message;
|
|
63407
64467
|
return String(err);
|
|
@@ -63409,7 +64469,7 @@ function errToString2(err) {
|
|
|
63409
64469
|
|
|
63410
64470
|
// ts/codex-agent/dist/session-manager.js
|
|
63411
64471
|
import * as fs8 from "node:fs";
|
|
63412
|
-
import * as
|
|
64472
|
+
import * as path11 from "node:path";
|
|
63413
64473
|
var CodexSessionManager = class {
|
|
63414
64474
|
mainSessionKey;
|
|
63415
64475
|
stateFilePath;
|
|
@@ -63428,6 +64488,13 @@ var CodexSessionManager = class {
|
|
|
63428
64488
|
getThreadId(sessionKey) {
|
|
63429
64489
|
return this.threadIds.get(sessionKey);
|
|
63430
64490
|
}
|
|
64491
|
+
/** The session (main or fork) that owns a thread the bridge opened. */
|
|
64492
|
+
getSessionKey(threadId) {
|
|
64493
|
+
for (const [sessionKey, id] of this.threadIds)
|
|
64494
|
+
if (id === threadId)
|
|
64495
|
+
return sessionKey;
|
|
64496
|
+
return void 0;
|
|
64497
|
+
}
|
|
63431
64498
|
recordThreadId(sessionKey, threadId) {
|
|
63432
64499
|
if (this.threadIds.get(sessionKey) !== threadId) {
|
|
63433
64500
|
this.effectiveInstructionsShas.delete(sessionKey);
|
|
@@ -63506,7 +64573,7 @@ var CodexSessionManager = class {
|
|
|
63506
64573
|
if (!threadId)
|
|
63507
64574
|
return;
|
|
63508
64575
|
try {
|
|
63509
|
-
fs8.mkdirSync(
|
|
64576
|
+
fs8.mkdirSync(path11.dirname(this.stateFilePath), { recursive: true });
|
|
63510
64577
|
const tmpPath = `${this.stateFilePath}.tmp`;
|
|
63511
64578
|
const state = { runtimeKey: this.mainSessionKey, threadId };
|
|
63512
64579
|
const effectiveSha = this.effectiveInstructionsShas.get(this.mainSessionKey);
|
|
@@ -63522,18 +64589,18 @@ var CodexSessionManager = class {
|
|
|
63522
64589
|
|
|
63523
64590
|
// ts/codex-agent/dist/workspace.js
|
|
63524
64591
|
import * as fs10 from "node:fs";
|
|
63525
|
-
import * as
|
|
64592
|
+
import * as path13 from "node:path";
|
|
63526
64593
|
|
|
63527
64594
|
// ts/codex-agent/dist/legacy-workspace-config-migration.js
|
|
63528
64595
|
import * as fs9 from "node:fs";
|
|
63529
|
-
import * as
|
|
64596
|
+
import * as path12 from "node:path";
|
|
63530
64597
|
var LEGACY_CONFIG_RELPATH = [".codex", "config.toml"];
|
|
63531
64598
|
var MIGRATION_SENTINEL_RELPATH = [".parall", "legacy-workspace-config-migration.v1"];
|
|
63532
64599
|
function legacyWorkspaceConfigPath(workspaceDir) {
|
|
63533
|
-
return
|
|
64600
|
+
return path12.join(workspaceDir, ...LEGACY_CONFIG_RELPATH);
|
|
63534
64601
|
}
|
|
63535
64602
|
function migrationSentinelPath(workspaceDir) {
|
|
63536
|
-
return
|
|
64603
|
+
return path12.join(workspaceDir, ...MIGRATION_SENTINEL_RELPATH);
|
|
63537
64604
|
}
|
|
63538
64605
|
function legacyWorkspaceConfigToml(prompt) {
|
|
63539
64606
|
return `developer_instructions = """
|
|
@@ -63585,7 +64652,7 @@ If a stale .codex/config.toml is still present, remove it by hand.
|
|
|
63585
64652
|
`;
|
|
63586
64653
|
function claimLegacyWorkspaceConfigMigration(workspaceDir) {
|
|
63587
64654
|
const sentinel = migrationSentinelPath(workspaceDir);
|
|
63588
|
-
fs9.mkdirSync(
|
|
64655
|
+
fs9.mkdirSync(path12.dirname(sentinel), { recursive: true });
|
|
63589
64656
|
try {
|
|
63590
64657
|
fs9.writeFileSync(sentinel, SENTINEL_BODY, { flag: "wx" });
|
|
63591
64658
|
return "claimed";
|
|
@@ -63651,9 +64718,9 @@ function sleepSync(ms) {
|
|
|
63651
64718
|
Atomics.wait(SLEEP_SIGNAL, 0, 0, ms);
|
|
63652
64719
|
}
|
|
63653
64720
|
function withConfigLock(codexHome, log2, fn) {
|
|
63654
|
-
const queueDir =
|
|
64721
|
+
const queueDir = path13.join(codexHome, "config.toml.lock.d");
|
|
63655
64722
|
let ticketName = bakeryEnqueue(queueDir);
|
|
63656
|
-
let ticketPath = ticketName ?
|
|
64723
|
+
let ticketPath = ticketName ? path13.join(queueDir, ticketName) : "";
|
|
63657
64724
|
let acquired = false;
|
|
63658
64725
|
let heldPath = "";
|
|
63659
64726
|
const deadline = Date.now() + CONFIG_LOCK_TIMINGS.waitMs;
|
|
@@ -63668,7 +64735,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
63668
64735
|
ticketName = bakeryEnqueue(queueDir);
|
|
63669
64736
|
if (!ticketName)
|
|
63670
64737
|
break;
|
|
63671
|
-
ticketPath =
|
|
64738
|
+
ticketPath = path13.join(queueDir, ticketName);
|
|
63672
64739
|
continue;
|
|
63673
64740
|
}
|
|
63674
64741
|
const now = Date.now();
|
|
@@ -63676,7 +64743,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
63676
64743
|
let blocked = false;
|
|
63677
64744
|
let head;
|
|
63678
64745
|
for (const name of names) {
|
|
63679
|
-
const entryPath =
|
|
64746
|
+
const entryPath = path13.join(queueDir, name);
|
|
63680
64747
|
if (name.startsWith("held-")) {
|
|
63681
64748
|
const enteredAt = Number.parseInt(name.slice(5, 20), 10);
|
|
63682
64749
|
if (Number.isFinite(enteredAt) && now - enteredAt > CONFIG_LOCK_TIMINGS.staleMs) {
|
|
@@ -63719,7 +64786,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
63719
64786
|
if (!blocked && head === ticketName) {
|
|
63720
64787
|
CONFIG_LOCK_TEST_HOOKS.beforeTicketEntry?.();
|
|
63721
64788
|
const heldName = `held-${String(Date.now()).padStart(15, "0")}-${ticketName.slice(2)}`;
|
|
63722
|
-
const candidateHeldPath =
|
|
64789
|
+
const candidateHeldPath = path13.join(queueDir, heldName);
|
|
63723
64790
|
try {
|
|
63724
64791
|
fs10.renameSync(ticketPath, candidateHeldPath);
|
|
63725
64792
|
} catch {
|
|
@@ -63760,7 +64827,7 @@ var CONFIG_LOCK_TEST_HOOKS = {};
|
|
|
63760
64827
|
function bakeryEnqueue(queueDir) {
|
|
63761
64828
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
63762
64829
|
const token = `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
63763
|
-
const markerPath =
|
|
64830
|
+
const markerPath = path13.join(queueDir, `choosing-${token}`);
|
|
63764
64831
|
try {
|
|
63765
64832
|
fs10.mkdirSync(queueDir, { recursive: true });
|
|
63766
64833
|
CONFIG_LOCK_TEST_HOOKS.beforeChoosingMarker?.();
|
|
@@ -63778,7 +64845,7 @@ function bakeryEnqueue(queueDir) {
|
|
|
63778
64845
|
maxSeq = seq;
|
|
63779
64846
|
}
|
|
63780
64847
|
const ticketName = `t-${String(maxSeq + 1).padStart(10, "0")}-${token}`;
|
|
63781
|
-
const ticketPath =
|
|
64848
|
+
const ticketPath = path13.join(queueDir, ticketName);
|
|
63782
64849
|
CONFIG_LOCK_TEST_HOOKS.beforeTicketPublish?.();
|
|
63783
64850
|
fs10.renameSync(markerPath, ticketPath);
|
|
63784
64851
|
try {
|
|
@@ -63832,7 +64899,7 @@ function resolveWriteTarget(filePath) {
|
|
|
63832
64899
|
throw err;
|
|
63833
64900
|
}
|
|
63834
64901
|
const seen = /* @__PURE__ */ new Set();
|
|
63835
|
-
let p =
|
|
64902
|
+
let p = path13.resolve(filePath);
|
|
63836
64903
|
for (let depth = 0; depth < 40; depth++) {
|
|
63837
64904
|
if (seen.has(p)) {
|
|
63838
64905
|
throw new Error(`symlink cycle at ${p} while resolving ${filePath}`);
|
|
@@ -63847,7 +64914,7 @@ function resolveWriteTarget(filePath) {
|
|
|
63847
64914
|
return p;
|
|
63848
64915
|
throw err;
|
|
63849
64916
|
}
|
|
63850
|
-
p =
|
|
64917
|
+
p = path13.resolve(path13.dirname(p), link);
|
|
63851
64918
|
}
|
|
63852
64919
|
throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
|
|
63853
64920
|
}
|
|
@@ -63896,7 +64963,7 @@ function ensureParallProvider(codexHome, apiUrl, log2, opts) {
|
|
|
63896
64963
|
withConfigLock(codexHome, log2, () => ensureParallProviderLocked(codexHome, apiUrl, opts));
|
|
63897
64964
|
}
|
|
63898
64965
|
function ensureParallProviderLocked(codexHome, apiUrl, opts) {
|
|
63899
|
-
const configPath =
|
|
64966
|
+
const configPath = path13.join(codexHome, "config.toml");
|
|
63900
64967
|
const baseUrl = apiUrl.replace(/\/$/, "") + "/api/llm/v1";
|
|
63901
64968
|
try {
|
|
63902
64969
|
let content = "";
|
|
@@ -63942,11 +65009,11 @@ function findSectionEnd(content, fromIndex) {
|
|
|
63942
65009
|
return nextHeader === -1 ? content.length : nextHeader;
|
|
63943
65010
|
}
|
|
63944
65011
|
function systemPromptCopyPath(workspaceDir) {
|
|
63945
|
-
return
|
|
65012
|
+
return path13.join(workspaceDir, ".parall", "system-prompt.md");
|
|
63946
65013
|
}
|
|
63947
65014
|
function writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
|
|
63948
65015
|
const systemPrompt = buildCodexPlatformInstructions(workspaceDir, agentIdentity, capabilityFragments);
|
|
63949
|
-
fs10.mkdirSync(
|
|
65016
|
+
fs10.mkdirSync(path13.join(workspaceDir, ".parall"), { recursive: true });
|
|
63950
65017
|
fs10.writeFileSync(systemPromptCopyPath(workspaceDir), systemPrompt, "utf8");
|
|
63951
65018
|
return systemPrompt;
|
|
63952
65019
|
}
|
|
@@ -63954,7 +65021,7 @@ function ensureCodexWorkspace(workspaceDir, log2, agentIdentity, capabilityFragm
|
|
|
63954
65021
|
fs10.mkdirSync(workspaceDir, { recursive: true });
|
|
63955
65022
|
runLegacyWorkspaceConfigMigration(workspaceDir, () => readAuthorshipProof(workspaceDir, log2), log2);
|
|
63956
65023
|
const systemPrompt = writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
|
|
63957
|
-
writeSkillFiles(
|
|
65024
|
+
writeSkillFiles(path13.join(workspaceDir, ".parall", "skills"));
|
|
63958
65025
|
return systemPrompt;
|
|
63959
65026
|
}
|
|
63960
65027
|
function readAuthorshipProof(workspaceDir, log2) {
|
|
@@ -64001,7 +65068,11 @@ function resolveProviderEnv() {
|
|
|
64001
65068
|
}
|
|
64002
65069
|
async function main() {
|
|
64003
65070
|
configureHttpKeepAlive();
|
|
64004
|
-
const telemetry = await initAgentTelemetry("parall-codex-agent", "codex"
|
|
65071
|
+
const telemetry = await initAgentTelemetry("parall-codex-agent", "codex", {
|
|
65072
|
+
apiUrl: process.env.PRLL_API_URL,
|
|
65073
|
+
apiKey: process.env.PRLL_API_KEY,
|
|
65074
|
+
serviceVersion: resolveServiceVersion(import.meta.url)
|
|
65075
|
+
});
|
|
64005
65076
|
activeLog = createOtelLogger("agent", "codex-agent");
|
|
64006
65077
|
try {
|
|
64007
65078
|
resolveProviderEnv();
|
|
@@ -64142,7 +65213,13 @@ async function main() {
|
|
|
64142
65213
|
},
|
|
64143
65214
|
onSessionStale: () => {
|
|
64144
65215
|
sessionManager.clearMainThread();
|
|
64145
|
-
}
|
|
65216
|
+
},
|
|
65217
|
+
// The app-server outlives one dispatch (subagent threads keep running
|
|
65218
|
+
// after the parent turn): stop it INSIDE the gateway's shutdown so the
|
|
65219
|
+
// runtime turns it ends still land their steps and idle/close writes
|
|
65220
|
+
// before the step and lifecycle flushes — the finally below runs after
|
|
65221
|
+
// those windows have closed.
|
|
65222
|
+
onBeforeDisconnect: () => adapter.stop()
|
|
64146
65223
|
});
|
|
64147
65224
|
const abortController = new AbortController();
|
|
64148
65225
|
const abort = () => abortController.abort();
|