@treestructuredplanning/gateway 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -11
- package/dist/cli.js +10 -6
- package/dist/gateway-schema.json +38 -8
- package/dist/{shared-M7CEELPK.js → shared-RM5C4AZN.js} +2077 -831
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
|
|
2
2
|
|
|
3
3
|
// ../tsp-shared/src/generated/constants.ts
|
|
4
|
-
var GATEWAY_PACKAGE_VERSION = "0.1.
|
|
4
|
+
var GATEWAY_PACKAGE_VERSION = "0.1.3";
|
|
5
5
|
var GATEWAY_PROTOCOL_VERSION = 1;
|
|
6
6
|
var SESSION_ACTIVITY_COUNT_MAX = 1e6;
|
|
7
7
|
var AGENT_SESSION_STATE = {
|
|
@@ -22,7 +22,8 @@ var GATEWAY_CLOSE_DISPOSITION = {
|
|
|
22
22
|
};
|
|
23
23
|
var HARNESS_KIND = {
|
|
24
24
|
CLAUDE_CODE: "claude_code",
|
|
25
|
-
CODEX: "codex"
|
|
25
|
+
CODEX: "codex",
|
|
26
|
+
CURSOR: "cursor"
|
|
26
27
|
};
|
|
27
28
|
var LAUNCH_REFUSAL_REASON = {
|
|
28
29
|
WORKSPACE_UNTRUSTED: "workspace_untrusted",
|
|
@@ -72,13 +73,44 @@ var GATEWAY_CLOSE_DISPOSITION_BY_CODE = {
|
|
|
72
73
|
"4501": "terminal",
|
|
73
74
|
"4502": "terminal",
|
|
74
75
|
"4503": "outdated",
|
|
75
|
-
"4504": "terminal",
|
|
76
76
|
"4505": "token",
|
|
77
77
|
"4506": "reconnectable",
|
|
78
78
|
"4507": "reconnectable",
|
|
79
79
|
"4508": "reconnectable"
|
|
80
80
|
};
|
|
81
81
|
|
|
82
|
+
// src/repository-files.ts
|
|
83
|
+
import { realpath } from "node:fs/promises";
|
|
84
|
+
import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
|
85
|
+
function contains(folder, path) {
|
|
86
|
+
const child = relative(folder, path);
|
|
87
|
+
return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
|
|
88
|
+
}
|
|
89
|
+
async function realLocation(path) {
|
|
90
|
+
let current = parse(path).root;
|
|
91
|
+
const parts = path.slice(current.length).split(sep);
|
|
92
|
+
for (let index = 0; index < parts.length; index++) {
|
|
93
|
+
const part = parts[index];
|
|
94
|
+
if (part === "" || part === ".") continue;
|
|
95
|
+
if (part === "..") {
|
|
96
|
+
current = dirname(current);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const next = join(current, part);
|
|
100
|
+
try {
|
|
101
|
+
current = await realpath(next);
|
|
102
|
+
} catch {
|
|
103
|
+
return resolve(next, ...parts.slice(index + 1));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return current;
|
|
107
|
+
}
|
|
108
|
+
async function inRepository(root, path) {
|
|
109
|
+
const base = resolve(root);
|
|
110
|
+
const absolute = isAbsolute(path) ? path : `${base}${sep}${path}`;
|
|
111
|
+
return contains(await realLocation(base), await realLocation(absolute));
|
|
112
|
+
}
|
|
113
|
+
|
|
82
114
|
// src/session-activity.ts
|
|
83
115
|
var REPORTING_LEVELS = ["activity", "off"];
|
|
84
116
|
var DEFAULT_REPORTING = "activity";
|
|
@@ -101,6 +133,9 @@ function toWire(snapshot, working, nowMs) {
|
|
|
101
133
|
var PENDING_LIMIT = 256;
|
|
102
134
|
var ActivityTally = class {
|
|
103
135
|
files = /* @__PURE__ */ new Set();
|
|
136
|
+
candidates = /* @__PURE__ */ new Set();
|
|
137
|
+
judged = /* @__PURE__ */ new Set();
|
|
138
|
+
judgedFor = null;
|
|
104
139
|
pending = /* @__PURE__ */ new Map();
|
|
105
140
|
commands = 0;
|
|
106
141
|
settled = null;
|
|
@@ -127,13 +162,31 @@ var ActivityTally = class {
|
|
|
127
162
|
this.pending.delete(id);
|
|
128
163
|
this.settled = SESSION_ACTIVITY_KIND.THINKING;
|
|
129
164
|
}
|
|
165
|
+
/** A turn is over or beginning: no tool of an earlier one is still current. Counts stay. */
|
|
166
|
+
clearPending() {
|
|
167
|
+
this.pending.clear();
|
|
168
|
+
}
|
|
130
169
|
ranCommand() {
|
|
131
170
|
this.commands = Math.min(this.commands + 1, SESSION_ACTIVITY_COUNT_MAX);
|
|
132
171
|
}
|
|
172
|
+
/** An edit not yet known to be inside the repository; `snapshot` judges it. */
|
|
133
173
|
editedFile(path) {
|
|
134
|
-
if (this.
|
|
135
|
-
|
|
136
|
-
|
|
174
|
+
if (this.candidates.size + this.judged.size < SESSION_ACTIVITY_COUNT_MAX)
|
|
175
|
+
this.candidates.add(path);
|
|
176
|
+
}
|
|
177
|
+
async snapshot(root) {
|
|
178
|
+
if (this.judgedFor !== null && this.judgedFor !== root) {
|
|
179
|
+
for (const path of this.judged) this.candidates.add(path);
|
|
180
|
+
this.judged.clear();
|
|
181
|
+
this.files.clear();
|
|
182
|
+
}
|
|
183
|
+
this.judgedFor = root;
|
|
184
|
+
const unjudged = [...this.candidates];
|
|
185
|
+
this.candidates.clear();
|
|
186
|
+
for (const path of unjudged) {
|
|
187
|
+
this.judged.add(path);
|
|
188
|
+
if (await inRepository(root, path)) this.files.add(path);
|
|
189
|
+
}
|
|
137
190
|
if (this.lastActiveMs === null) return null;
|
|
138
191
|
return {
|
|
139
192
|
kind: [...this.pending.values()].at(-1) ?? this.settled,
|
|
@@ -333,7 +386,7 @@ function decodeHubText(data) {
|
|
|
333
386
|
|
|
334
387
|
// src/claude-transcript.ts
|
|
335
388
|
import { open, readdir, stat } from "node:fs/promises";
|
|
336
|
-
import { join } from "node:path";
|
|
389
|
+
import { join as join2 } from "node:path";
|
|
337
390
|
var TRANSCRIPT_READ_BYTES = 1 << 20;
|
|
338
391
|
var LINE_LIMIT_BYTES = 8 << 20;
|
|
339
392
|
var SEARCH_INTERVAL_MS = 3e4;
|
|
@@ -362,9 +415,9 @@ var ClaudeTranscripts = class {
|
|
|
362
415
|
}
|
|
363
416
|
cursors = /* @__PURE__ */ new Map();
|
|
364
417
|
edits = /* @__PURE__ */ new Map();
|
|
365
|
-
async activity(conversationId, cwd, configDir) {
|
|
418
|
+
async activity(conversationId, cwd, configDir, root) {
|
|
366
419
|
try {
|
|
367
|
-
return await this.read(conversationId, cwd, configDir);
|
|
420
|
+
return await this.read(conversationId, cwd, configDir, root);
|
|
368
421
|
} catch {
|
|
369
422
|
return null;
|
|
370
423
|
}
|
|
@@ -377,7 +430,7 @@ var ClaudeTranscripts = class {
|
|
|
377
430
|
this.edits.delete(id);
|
|
378
431
|
}
|
|
379
432
|
}
|
|
380
|
-
async read(conversationId, cwd, configDir) {
|
|
433
|
+
async read(conversationId, cwd, configDir, root) {
|
|
381
434
|
this.prune();
|
|
382
435
|
let cursor = this.cursors.get(conversationId);
|
|
383
436
|
if (!cursor) {
|
|
@@ -400,7 +453,7 @@ var ClaudeTranscripts = class {
|
|
|
400
453
|
this.edits.delete(conversationId);
|
|
401
454
|
}
|
|
402
455
|
if (size > cursor.offset) await this.advance(conversationId, cursor, size);
|
|
403
|
-
return cursor.caughtUp ? cursor.tally.snapshot() : null;
|
|
456
|
+
return cursor.caughtUp ? await cursor.tally.snapshot(root) : null;
|
|
404
457
|
}
|
|
405
458
|
fresh(path) {
|
|
406
459
|
return {
|
|
@@ -414,15 +467,15 @@ var ClaudeTranscripts = class {
|
|
|
414
467
|
};
|
|
415
468
|
}
|
|
416
469
|
async locate(cursor, conversationId, cwd, configDir) {
|
|
417
|
-
const projects =
|
|
470
|
+
const projects = join2(configDir, "projects");
|
|
418
471
|
const file = `${conversationId}.jsonl`;
|
|
419
|
-
const expected =
|
|
472
|
+
const expected = join2(projects, claudeProjectFolder(cwd), file);
|
|
420
473
|
if (await exists(expected)) return expected;
|
|
421
474
|
if (this.now() - cursor.searchedAt < SEARCH_INTERVAL_MS) return null;
|
|
422
475
|
cursor.searchedAt = this.now();
|
|
423
476
|
for (const entry of await readdir(projects, { withFileTypes: true })) {
|
|
424
477
|
if (!entry.isDirectory()) continue;
|
|
425
|
-
const candidate =
|
|
478
|
+
const candidate = join2(projects, entry.name, file);
|
|
426
479
|
if (await exists(candidate)) return candidate;
|
|
427
480
|
}
|
|
428
481
|
return null;
|
|
@@ -533,7 +586,7 @@ async function exists(path) {
|
|
|
533
586
|
// src/claude-trust.ts
|
|
534
587
|
import { open as open2 } from "node:fs/promises";
|
|
535
588
|
import { homedir } from "node:os";
|
|
536
|
-
import { join as
|
|
589
|
+
import { join as join3 } from "node:path";
|
|
537
590
|
var MAX_CONFIG_BYTES = 4 * 1024 * 1024;
|
|
538
591
|
var ClaudeTrust = class {
|
|
539
592
|
constructor(environment = process.env, home = homedir()) {
|
|
@@ -548,7 +601,7 @@ var ClaudeTrust = class {
|
|
|
548
601
|
async projects(folder) {
|
|
549
602
|
try {
|
|
550
603
|
const env = typeof this.environment === "function" ? await this.environment(folder) : this.environment;
|
|
551
|
-
const path =
|
|
604
|
+
const path = join3(env["CLAUDE_CONFIG_DIR"] ?? env["HOME"] ?? this.home, ".claude.json");
|
|
552
605
|
const previous = this.paths.get(folder);
|
|
553
606
|
if (previous !== void 0 && path !== previous) this.observed.delete(folder);
|
|
554
607
|
this.paths.set(folder, path);
|
|
@@ -600,6 +653,11 @@ function isTerminalSessionState(state) {
|
|
|
600
653
|
function wantsActivity(query, id) {
|
|
601
654
|
return query !== void 0 && "refs" in query && query.activity === true && query.refs.includes(id);
|
|
602
655
|
}
|
|
656
|
+
function promptCheck(requireLive) {
|
|
657
|
+
const { prompt, signal } = requireLive;
|
|
658
|
+
if (!prompt) return requireLive;
|
|
659
|
+
return signal ? Object.assign(() => prompt(), { signal }) : () => prompt();
|
|
660
|
+
}
|
|
603
661
|
var HarnessRefusal = class extends Error {
|
|
604
662
|
constructor(reason) {
|
|
605
663
|
super(reason);
|
|
@@ -609,7 +667,7 @@ var HarnessRefusal = class extends Error {
|
|
|
609
667
|
var RESUME_CONTINUATION = "Continue where you left off.";
|
|
610
668
|
|
|
611
669
|
// src/launch-config.ts
|
|
612
|
-
import { isAbsolute } from "node:path";
|
|
670
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
613
671
|
function defaultLaunchConfig() {
|
|
614
672
|
return { mode: "login-shell", wrapper: [], env: {} };
|
|
615
673
|
}
|
|
@@ -624,7 +682,7 @@ function decodeLaunchConfig(value) {
|
|
|
624
682
|
const wrapper = Object.hasOwn(value, "wrapper") ? field(value, "wrapper") : [];
|
|
625
683
|
const env = Object.hasOwn(value, "env") ? field(value, "env") : {};
|
|
626
684
|
if (mode !== "login-shell" && mode !== "direct") throw new Error("Invalid launch.mode");
|
|
627
|
-
if (shell !== void 0 && (!text2(shell) || !
|
|
685
|
+
if (shell !== void 0 && (!text2(shell) || !isAbsolute2(shell)))
|
|
628
686
|
throw new Error("launch.shell must be an absolute executable path");
|
|
629
687
|
return {
|
|
630
688
|
mode,
|
|
@@ -637,7 +695,7 @@ function decodeWrapper(wrapper) {
|
|
|
637
695
|
if (!Array.isArray(wrapper) || !wrapper.every(text2) || wrapper.length > 0 && !wrapper[0])
|
|
638
696
|
throw new Error("launch.wrapper must be an argv array with a nonempty executable");
|
|
639
697
|
const executable2 = wrapper[0];
|
|
640
|
-
if (executable2 !== void 0 && !
|
|
698
|
+
if (executable2 !== void 0 && !isAbsolute2(executable2) && !/^[A-Za-z0-9_][A-Za-z0-9_.+-]*$/.test(executable2))
|
|
641
699
|
throw new Error(
|
|
642
700
|
"launch.wrapper executable must be an absolute path or a bare command name"
|
|
643
701
|
);
|
|
@@ -658,7 +716,7 @@ function decodeVariables(env) {
|
|
|
658
716
|
// src/process.ts
|
|
659
717
|
import { spawn } from "node:child_process";
|
|
660
718
|
function execute(file, args, env, cwd) {
|
|
661
|
-
return new Promise((
|
|
719
|
+
return new Promise((resolve7, reject) => {
|
|
662
720
|
const child = spawn(file, args, {
|
|
663
721
|
env,
|
|
664
722
|
...cwd ? { cwd } : {},
|
|
@@ -686,7 +744,7 @@ function execute(file, args, env, cwd) {
|
|
|
686
744
|
});
|
|
687
745
|
child.once("close", (code) => {
|
|
688
746
|
clearTimeout(timer);
|
|
689
|
-
|
|
747
|
+
resolve7({ code: code ?? 1, stdout, stderr });
|
|
690
748
|
});
|
|
691
749
|
});
|
|
692
750
|
}
|
|
@@ -703,7 +761,7 @@ function pidAlive(pid) {
|
|
|
703
761
|
import { constants } from "node:fs";
|
|
704
762
|
import { access, stat as stat2 } from "node:fs/promises";
|
|
705
763
|
import { userInfo } from "node:os";
|
|
706
|
-
import { basename, isAbsolute as
|
|
764
|
+
import { basename, isAbsolute as isAbsolute3 } from "node:path";
|
|
707
765
|
var posix = {
|
|
708
766
|
flags: ["-l", "-i", "-c"],
|
|
709
767
|
command: 'cd /; cd -- "$5" || { "$1" -e "$6" "$3" "$5"; exit 125; }; "$1" -e "$2" "$3" "$4" || exit; cd /; cd -- "$5" || { "$1" -e "$6" "" "$5"; exit 125; }; shift 6; exec "$@"',
|
|
@@ -733,7 +791,7 @@ var strategies = /* @__PURE__ */ new Map([
|
|
|
733
791
|
["xonsh", null]
|
|
734
792
|
]);
|
|
735
793
|
async function executable(path) {
|
|
736
|
-
if (!
|
|
794
|
+
if (!isAbsolute3(path)) return false;
|
|
737
795
|
try {
|
|
738
796
|
await access(path, constants.X_OK);
|
|
739
797
|
return (await stat2(path)).isFile();
|
|
@@ -788,7 +846,7 @@ function shellArguments(path, capture, argv) {
|
|
|
788
846
|
// src/harness-executor.ts
|
|
789
847
|
import { spawn as spawn3 } from "node:child_process";
|
|
790
848
|
import { homedir as homedir2 } from "node:os";
|
|
791
|
-
import { resolve } from "node:path";
|
|
849
|
+
import { resolve as resolve2 } from "node:path";
|
|
792
850
|
|
|
793
851
|
// src/shell-process.ts
|
|
794
852
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -867,7 +925,7 @@ var CAPTURE_ENVIRONMENT = 'const fs=require("node:fs"),s=process.argv[1];if(!fs.
|
|
|
867
925
|
import { closeSync, constants as constants2, openSync, writeSync } from "node:fs";
|
|
868
926
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
869
927
|
import { tmpdir } from "node:os";
|
|
870
|
-
import { join as
|
|
928
|
+
import { join as join4 } from "node:path";
|
|
871
929
|
var ShellRelease = class _ShellRelease {
|
|
872
930
|
constructor(path, directory, fd) {
|
|
873
931
|
this.path = path;
|
|
@@ -875,8 +933,8 @@ var ShellRelease = class _ShellRelease {
|
|
|
875
933
|
this.fd = fd;
|
|
876
934
|
}
|
|
877
935
|
static async create() {
|
|
878
|
-
const directory = await mkdtemp(
|
|
879
|
-
const path =
|
|
936
|
+
const directory = await mkdtemp(join4(tmpdir(), "tsp-shell-"));
|
|
937
|
+
const path = join4(directory, "release");
|
|
880
938
|
try {
|
|
881
939
|
const result = await execute("/usr/bin/mkfifo", ["-m", "600", path], {});
|
|
882
940
|
if (result.code !== 0) throw new Error("Could not create login-shell release FIFO");
|
|
@@ -917,7 +975,7 @@ async function executeShell(path, argv, env, options) {
|
|
|
917
975
|
}
|
|
918
976
|
function runShell(path, argv, env, options) {
|
|
919
977
|
const { cwd, startupMs, requireLive, release } = options;
|
|
920
|
-
return new Promise((
|
|
978
|
+
return new Promise((resolve7, reject) => {
|
|
921
979
|
const sentinel = `TSP_${randomUUID()}`;
|
|
922
980
|
const out = new ShellEnvironmentOutput(sentinel), err = new ShellOutput(sentinel);
|
|
923
981
|
const child = spawn2(
|
|
@@ -967,6 +1025,13 @@ function runShell(path, argv, env, options) {
|
|
|
967
1025
|
),
|
|
968
1026
|
startupMs
|
|
969
1027
|
);
|
|
1028
|
+
const signal = requireLive?.signal;
|
|
1029
|
+
const withdraw = () => {
|
|
1030
|
+
if (!started)
|
|
1031
|
+
fail(signal?.reason instanceof Error ? signal.reason : new Error("Withdrawn"));
|
|
1032
|
+
};
|
|
1033
|
+
signal?.addEventListener("abort", withdraw, { once: true });
|
|
1034
|
+
if (signal?.aborted) withdraw();
|
|
970
1035
|
const ready = () => {
|
|
971
1036
|
if (started || failure || !out.ready || !err.ready) return;
|
|
972
1037
|
try {
|
|
@@ -1000,6 +1065,7 @@ function runShell(path, argv, env, options) {
|
|
|
1000
1065
|
)
|
|
1001
1066
|
);
|
|
1002
1067
|
child.once("close", (code) => {
|
|
1068
|
+
signal?.removeEventListener("abort", withdraw);
|
|
1003
1069
|
if (settled) return;
|
|
1004
1070
|
clearTimeout(timer);
|
|
1005
1071
|
const exitError = shellExitError({ path, code, started, stderr, cwd });
|
|
@@ -1009,7 +1075,7 @@ function runShell(path, argv, env, options) {
|
|
|
1009
1075
|
reject(failure);
|
|
1010
1076
|
return;
|
|
1011
1077
|
}
|
|
1012
|
-
|
|
1078
|
+
resolve7({ code: code ?? 1, stdout, stderr, environment: out.environment });
|
|
1013
1079
|
});
|
|
1014
1080
|
});
|
|
1015
1081
|
}
|
|
@@ -1178,7 +1244,7 @@ var HarnessExecutor = class {
|
|
|
1178
1244
|
}
|
|
1179
1245
|
/** Read/control calls share a cold capture per cwd; repository-free calls use home. */
|
|
1180
1246
|
async execute(file, args, purpose = "read", cwd = this.home, requireLive) {
|
|
1181
|
-
cwd =
|
|
1247
|
+
cwd = resolve2(cwd);
|
|
1182
1248
|
const config = await this.configuration();
|
|
1183
1249
|
const capture = this.capture(cwd);
|
|
1184
1250
|
const path = await resolveLaunchPath(
|
|
@@ -1199,7 +1265,7 @@ var HarnessExecutor = class {
|
|
|
1199
1265
|
return execute(argv[0], argv.slice(1), environment, cwd);
|
|
1200
1266
|
}
|
|
1201
1267
|
async environment(fresh = false, cwd = this.home) {
|
|
1202
|
-
cwd =
|
|
1268
|
+
cwd = resolve2(cwd);
|
|
1203
1269
|
const config = await this.configuration();
|
|
1204
1270
|
const capture = this.capture(cwd);
|
|
1205
1271
|
if (fresh) {
|
|
@@ -1245,13 +1311,24 @@ var HarnessExecutor = class {
|
|
|
1245
1311
|
return this.environment(false, cwd);
|
|
1246
1312
|
return capture.environment ?? { ...this.env, ...config.env };
|
|
1247
1313
|
}
|
|
1248
|
-
/**
|
|
1249
|
-
|
|
1314
|
+
/**
|
|
1315
|
+
* A protocol child uses the same wrapper and captured environment as read/control calls. With
|
|
1316
|
+
* a `supervisor` (its program and leading arguments), that process leads the child's own process
|
|
1317
|
+
* group and holds a fourth pipe as the child's lifetime; the configured wrapper then wraps the
|
|
1318
|
+
* child, never the supervisor, so the supervisor keeps both.
|
|
1319
|
+
*/
|
|
1320
|
+
async spawn(file, args, cwd, requireLive, supervisor) {
|
|
1250
1321
|
const config = await this.configuration();
|
|
1251
1322
|
const env = await this.environment(false, cwd);
|
|
1252
|
-
const argv = [...config.wrapper, file, ...args];
|
|
1323
|
+
const argv = supervisor ? [...supervisor, ...config.wrapper, file, ...args] : [...config.wrapper, file, ...args];
|
|
1253
1324
|
requireLive?.();
|
|
1254
|
-
return spawn3(argv[0], argv.slice(1), {
|
|
1325
|
+
return spawn3(argv[0], argv.slice(1), {
|
|
1326
|
+
cwd,
|
|
1327
|
+
env,
|
|
1328
|
+
stdio: supervisor ? ["pipe", "pipe", "pipe", "pipe"] : "pipe",
|
|
1329
|
+
windowsHide: true,
|
|
1330
|
+
detached: supervisor !== void 0
|
|
1331
|
+
});
|
|
1255
1332
|
}
|
|
1256
1333
|
};
|
|
1257
1334
|
function slowShell(error) {
|
|
@@ -1260,7 +1337,7 @@ function slowShell(error) {
|
|
|
1260
1337
|
|
|
1261
1338
|
// src/claude-driver.ts
|
|
1262
1339
|
import { homedir as homedir3 } from "node:os";
|
|
1263
|
-
import { isAbsolute as
|
|
1340
|
+
import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
|
|
1264
1341
|
import { setTimeout as delay } from "node:timers/promises";
|
|
1265
1342
|
function opaque(value) {
|
|
1266
1343
|
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
|
|
@@ -1276,6 +1353,7 @@ function sanitizeWaiting(text3) {
|
|
|
1276
1353
|
].slice(0, 240).join("");
|
|
1277
1354
|
}
|
|
1278
1355
|
var STARTUP_GRACE_MS = 1e4;
|
|
1356
|
+
var START_PROMPT_LANDING_MS = 3e3;
|
|
1279
1357
|
function backgroundSession(row) {
|
|
1280
1358
|
if (!isObject(row) || field(row, "kind") !== "background") return null;
|
|
1281
1359
|
let id, conversationId;
|
|
@@ -1296,10 +1374,36 @@ function backgroundSession(row) {
|
|
|
1296
1374
|
state,
|
|
1297
1375
|
waiting,
|
|
1298
1376
|
idle: field(row, "status") === "idle",
|
|
1377
|
+
prompting: field(row, "status") === "waiting",
|
|
1299
1378
|
startedAt: typeof startedAt === "number" ? startedAt : null,
|
|
1300
|
-
cwd: typeof cwd === "string" &&
|
|
1379
|
+
cwd: typeof cwd === "string" && isAbsolute4(cwd) ? cwd : null
|
|
1301
1380
|
};
|
|
1302
1381
|
}
|
|
1382
|
+
async function observedState(session, signedIn) {
|
|
1383
|
+
const { state, waiting, idle, prompting, startedAt } = session;
|
|
1384
|
+
switch (state) {
|
|
1385
|
+
case "working":
|
|
1386
|
+
return {
|
|
1387
|
+
state: idle && startedAt !== null && Date.now() - startedAt > STARTUP_GRACE_MS ? "done" : "working",
|
|
1388
|
+
waitingFor: null
|
|
1389
|
+
};
|
|
1390
|
+
case "done":
|
|
1391
|
+
case "stopped":
|
|
1392
|
+
case "failed":
|
|
1393
|
+
return { state, waitingFor: null };
|
|
1394
|
+
case "blocked":
|
|
1395
|
+
if (typeof waiting === "string" && waiting.trim())
|
|
1396
|
+
return { state: "needs_input", waitingFor: sanitizeWaiting(waiting) };
|
|
1397
|
+
if (await signedIn() === false)
|
|
1398
|
+
return {
|
|
1399
|
+
state: "failed",
|
|
1400
|
+
waitingFor: "Claude Code is not signed in. Run claude auth login."
|
|
1401
|
+
};
|
|
1402
|
+
return { state: prompting ? "needs_input" : "done", waitingFor: null };
|
|
1403
|
+
default:
|
|
1404
|
+
return { state: "unknown", waitingFor: null };
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1303
1407
|
var ClaudeDriver = class {
|
|
1304
1408
|
constructor(env, executable2 = "claude", trust = void 0, executor = new HarnessExecutor(env), transcripts = new ClaudeTranscripts()) {
|
|
1305
1409
|
this.executable = executable2;
|
|
@@ -1318,7 +1422,8 @@ var ClaudeDriver = class {
|
|
|
1318
1422
|
stop: true,
|
|
1319
1423
|
resume: true,
|
|
1320
1424
|
attach_hint: true,
|
|
1321
|
-
answer_input: false
|
|
1425
|
+
answer_input: false,
|
|
1426
|
+
stop_starting: true
|
|
1322
1427
|
};
|
|
1323
1428
|
call(args, folder, purpose = "read", requireLive) {
|
|
1324
1429
|
return this.executor.execute(this.executable, args, purpose, folder, requireLive);
|
|
@@ -1358,12 +1463,13 @@ var ClaudeDriver = class {
|
|
|
1358
1463
|
}
|
|
1359
1464
|
}
|
|
1360
1465
|
async start(command, folder, requireLive) {
|
|
1361
|
-
requireLive
|
|
1466
|
+
const seeding = promptCheck(requireLive);
|
|
1467
|
+
seeding();
|
|
1362
1468
|
const result = await this.call(
|
|
1363
1469
|
["--bg", "--name", command.session_name, "--", command.seed],
|
|
1364
1470
|
folder,
|
|
1365
1471
|
"launch",
|
|
1366
|
-
|
|
1472
|
+
seeding
|
|
1367
1473
|
);
|
|
1368
1474
|
if (result.code !== 0) {
|
|
1369
1475
|
if (/Workspace not trusted/i.test(result.stdout + result.stderr)) {
|
|
@@ -1389,30 +1495,19 @@ var ClaudeDriver = class {
|
|
|
1389
1495
|
for (const row of rows) {
|
|
1390
1496
|
const session = backgroundSession(row);
|
|
1391
1497
|
if (!session) continue;
|
|
1392
|
-
const { id, conversationId, name, pid,
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
else if (state === "done") mapped = "done";
|
|
1398
|
-
else if (state === "stopped") mapped = "stopped";
|
|
1399
|
-
else if (state === "failed") mapped = "failed";
|
|
1400
|
-
else if (state === "blocked") {
|
|
1401
|
-
if (typeof waiting === "string" && waiting.trim()) {
|
|
1402
|
-
mapped = "needs_input";
|
|
1403
|
-
waitingFor = sanitizeWaiting(waiting);
|
|
1404
|
-
} else if (await (signedIn ??= this.signedIn(folder)) === false) {
|
|
1405
|
-
mapped = "failed";
|
|
1406
|
-
waitingFor = "Claude Code is not signed in. Run claude auth login.";
|
|
1407
|
-
} else mapped = "needs_input";
|
|
1408
|
-
}
|
|
1498
|
+
const { id, conversationId, name, pid, cwd, startedAt } = session;
|
|
1499
|
+
const { state, waitingFor } = await observedState(
|
|
1500
|
+
session,
|
|
1501
|
+
() => signedIn ??= this.signedIn(folder)
|
|
1502
|
+
);
|
|
1409
1503
|
sessions.push({
|
|
1410
1504
|
id,
|
|
1411
1505
|
conversationId,
|
|
1412
1506
|
name,
|
|
1413
1507
|
pid,
|
|
1414
|
-
state
|
|
1508
|
+
state,
|
|
1415
1509
|
waitingFor,
|
|
1510
|
+
...startedAt === null ? {} : { startPromptDueBy: startedAt + START_PROMPT_LANDING_MS },
|
|
1416
1511
|
...wantsActivity(query, id) ? { activity: await this.activity(conversationId, cwd, folder) } : {}
|
|
1417
1512
|
});
|
|
1418
1513
|
}
|
|
@@ -1423,8 +1518,8 @@ var ClaudeDriver = class {
|
|
|
1423
1518
|
if (!cwd) return null;
|
|
1424
1519
|
try {
|
|
1425
1520
|
const env = await this.executor.environment(false, folder);
|
|
1426
|
-
const configDir = env["CLAUDE_CONFIG_DIR"] ??
|
|
1427
|
-
return await this.transcripts.activity(conversationId, cwd, configDir);
|
|
1521
|
+
const configDir = env["CLAUDE_CONFIG_DIR"] ?? join5(env["HOME"] ?? homedir3(), ".claude");
|
|
1522
|
+
return await this.transcripts.activity(conversationId, cwd, configDir, folder);
|
|
1428
1523
|
} catch {
|
|
1429
1524
|
return null;
|
|
1430
1525
|
}
|
|
@@ -1454,7 +1549,8 @@ var ClaudeDriver = class {
|
|
|
1454
1549
|
await this.executor.environment(true, folder);
|
|
1455
1550
|
if (await this.signedIn(folder) === false) throw new HarnessRefusal("not_signed_in");
|
|
1456
1551
|
const prompt = text3 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
|
|
1457
|
-
requireLive
|
|
1552
|
+
const resuming = promptCheck(requireLive);
|
|
1553
|
+
resuming();
|
|
1458
1554
|
const result = await this.call(
|
|
1459
1555
|
[
|
|
1460
1556
|
"--resume",
|
|
@@ -1464,7 +1560,7 @@ var ClaudeDriver = class {
|
|
|
1464
1560
|
],
|
|
1465
1561
|
folder,
|
|
1466
1562
|
"launch",
|
|
1467
|
-
|
|
1563
|
+
resuming
|
|
1468
1564
|
);
|
|
1469
1565
|
if (result.code !== 0) throw new HarnessRefusal("harness_exited");
|
|
1470
1566
|
const copy = /started a copy as\s+([A-Za-z0-9_-]+)/.exec(result.stdout)?.[1];
|
|
@@ -1507,204 +1603,1176 @@ var ClaudeDriver = class {
|
|
|
1507
1603
|
}
|
|
1508
1604
|
};
|
|
1509
1605
|
|
|
1510
|
-
// src/
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1606
|
+
// src/acp-driver.ts
|
|
1607
|
+
import { homedir as homedir4 } from "node:os";
|
|
1608
|
+
|
|
1609
|
+
// src/acp-connection.ts
|
|
1610
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1611
|
+
|
|
1612
|
+
// src/acp-protocol.ts
|
|
1613
|
+
var ACP_PROTOCOL_VERSION = 1;
|
|
1614
|
+
var STOP_REASONS = [
|
|
1615
|
+
"end_turn",
|
|
1616
|
+
"max_tokens",
|
|
1617
|
+
"max_turn_requests",
|
|
1618
|
+
"refusal",
|
|
1619
|
+
"cancelled"
|
|
1620
|
+
];
|
|
1621
|
+
var ACP_PERMISSION_METHOD = "session/request_permission";
|
|
1622
|
+
var AcpRpcError = class extends Error {
|
|
1623
|
+
constructor(code, message) {
|
|
1624
|
+
super(message);
|
|
1625
|
+
this.code = code;
|
|
1626
|
+
}
|
|
1528
1627
|
};
|
|
1529
|
-
function
|
|
1530
|
-
if (
|
|
1531
|
-
throw new Error("
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
function member(value, choices, fallback) {
|
|
1535
|
-
return typeof value === "string" && choices.includes(value) ? value : fallback;
|
|
1536
|
-
}
|
|
1537
|
-
function codexThread(value) {
|
|
1538
|
-
if (!isObject(value)) throw new Error("Invalid Codex thread");
|
|
1539
|
-
const cwd = field(value, "cwd"), name = field(value, "name"), status = field(value, "status"), turns = field(value, "turns");
|
|
1540
|
-
if (typeof cwd !== "string" || !isObject(status))
|
|
1541
|
-
throw new Error("Invalid Codex thread metadata");
|
|
1542
|
-
const flags = field(status, "activeFlags");
|
|
1543
|
-
return {
|
|
1544
|
-
id: codexId(field(value, "id")),
|
|
1545
|
-
cwd,
|
|
1546
|
-
name: typeof name === "string" ? name : "",
|
|
1547
|
-
status: member(
|
|
1548
|
-
field(status, "type"),
|
|
1549
|
-
["active", "idle", "systemError", "notLoaded", "unknown"],
|
|
1550
|
-
"unknown"
|
|
1551
|
-
),
|
|
1552
|
-
activeFlags: Array.isArray(flags) ? flags.filter(
|
|
1553
|
-
(flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput"
|
|
1554
|
-
) : [],
|
|
1555
|
-
turns: Array.isArray(turns) ? turns.map(codexTurn) : []
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
function codexTurn(value) {
|
|
1559
|
-
if (!isObject(value)) throw new Error("Invalid Codex turn");
|
|
1628
|
+
function decodeInitialize(result) {
|
|
1629
|
+
if (!isObject(result) || field(result, "protocolVersion") !== ACP_PROTOCOL_VERSION)
|
|
1630
|
+
throw new Error("Unsupported ACP protocol version");
|
|
1631
|
+
const capabilities = field(result, "agentCapabilities");
|
|
1632
|
+
const sessions = isObject(capabilities) ? field(capabilities, "sessionCapabilities") : null;
|
|
1560
1633
|
return {
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
field(value, "status"),
|
|
1564
|
-
["completed", "interrupted", "failed", "inProgress", "unknown"],
|
|
1565
|
-
"unknown"
|
|
1566
|
-
)
|
|
1634
|
+
loadSession: isObject(capabilities) && field(capabilities, "loadSession") === true,
|
|
1635
|
+
listSessions: isObject(sessions) && isObject(field(sessions, "list"))
|
|
1567
1636
|
};
|
|
1568
1637
|
}
|
|
1569
|
-
function
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
return
|
|
1574
|
-
}
|
|
1575
|
-
function
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1638
|
+
function decodeSessionId(result) {
|
|
1639
|
+
const id = isObject(result) ? field(result, "sessionId") : null;
|
|
1640
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 128)
|
|
1641
|
+
throw new Error("Invalid ACP session id");
|
|
1642
|
+
return id;
|
|
1643
|
+
}
|
|
1644
|
+
function decodeStopReason(result) {
|
|
1645
|
+
const reason = isObject(result) ? field(result, "stopReason") : null;
|
|
1646
|
+
if (typeof reason !== "string" || !STOP_REASONS.includes(reason))
|
|
1647
|
+
throw new Error("Invalid ACP stop reason");
|
|
1648
|
+
return reason;
|
|
1649
|
+
}
|
|
1650
|
+
function decodeStoredSessions(result) {
|
|
1651
|
+
const rows = isObject(result) ? field(result, "sessions") : null;
|
|
1652
|
+
if (!Array.isArray(rows)) throw new Error("Invalid ACP session list");
|
|
1653
|
+
const sessions = [];
|
|
1654
|
+
for (const row of rows) {
|
|
1655
|
+
if (!isObject(row)) continue;
|
|
1656
|
+
const sessionId = field(row, "sessionId");
|
|
1657
|
+
const cwd = field(row, "cwd");
|
|
1658
|
+
const title = field(row, "title");
|
|
1659
|
+
if (typeof sessionId === "string" && typeof cwd === "string")
|
|
1660
|
+
sessions.push({ sessionId, cwd, title: typeof title === "string" ? title : null });
|
|
1661
|
+
}
|
|
1662
|
+
const next = isObject(result) ? field(result, "nextCursor") : null;
|
|
1663
|
+
return { sessions, next: typeof next === "string" && next ? next : null };
|
|
1664
|
+
}
|
|
1665
|
+
function heldRequestText(params) {
|
|
1666
|
+
if (!isObject(params)) return null;
|
|
1667
|
+
const toolCall = field(params, "toolCall");
|
|
1668
|
+
for (const source of [isObject(toolCall) ? toolCall : null, params]) {
|
|
1669
|
+
if (!source) continue;
|
|
1670
|
+
for (const key of ["title", "question", "name"]) {
|
|
1671
|
+
const text3 = field(source, key);
|
|
1672
|
+
if (typeof text3 === "string" && text3.trim()) return text3.trim();
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
return null;
|
|
1590
1676
|
}
|
|
1591
|
-
function
|
|
1592
|
-
const
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
conversationId: thread.id,
|
|
1596
|
-
name: thread.name,
|
|
1597
|
-
pid: null,
|
|
1598
|
-
...STATES[key]
|
|
1599
|
-
};
|
|
1677
|
+
function decodeUpdate(params) {
|
|
1678
|
+
const update = isObject(params) ? field(params, "update") : null;
|
|
1679
|
+
const kind = isObject(update) ? field(update, "sessionUpdate") : null;
|
|
1680
|
+
return isObject(update) && typeof kind === "string" ? { kind, body: update } : null;
|
|
1600
1681
|
}
|
|
1601
1682
|
|
|
1602
|
-
// src/
|
|
1603
|
-
var
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
}
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1683
|
+
// src/acp-supervisor.ts
|
|
1684
|
+
var ACP_SUPERVISOR_SOURCE = `
|
|
1685
|
+
const { spawn } = require("node:child_process");
|
|
1686
|
+
const net = require("node:net");
|
|
1687
|
+
const [, , file, ...args] = process.argv;
|
|
1688
|
+
const group = -process.pid;
|
|
1689
|
+
process.on("SIGTERM", () => {});
|
|
1690
|
+
process.on("SIGHUP", () => {});
|
|
1691
|
+
let ending = false;
|
|
1692
|
+
function end(graceMs) {
|
|
1693
|
+
if (ending) return;
|
|
1694
|
+
ending = true;
|
|
1695
|
+
try { process.kill(group, "SIGTERM"); } catch {}
|
|
1696
|
+
setTimeout(() => {
|
|
1697
|
+
try { process.kill(group, "SIGKILL"); } catch {}
|
|
1698
|
+
process.exit(0);
|
|
1699
|
+
}, graceMs);
|
|
1700
|
+
}
|
|
1701
|
+
const child = spawn(file, args, { stdio: ["inherit", "inherit", "inherit"] });
|
|
1702
|
+
child.on("error", () => end(0));
|
|
1703
|
+
child.on("exit", () => end(300));
|
|
1704
|
+
const lifetime = new net.Socket({ fd: 3, readable: true });
|
|
1705
|
+
lifetime.on("error", () => end(2000));
|
|
1706
|
+
lifetime.on("close", () => end(2000));
|
|
1707
|
+
lifetime.resume();
|
|
1708
|
+
`.replace(/\s*\n\s*/g, " ").trim();
|
|
1709
|
+
|
|
1710
|
+
// src/acp-connection.ts
|
|
1711
|
+
var MAX_LINE_BYTES = 4 * 1024 * 1024;
|
|
1712
|
+
var METHOD_NOT_FOUND = -32601;
|
|
1713
|
+
var CLOSE_WAIT_MS = 3e3;
|
|
1714
|
+
var AcpConnection = class _AcpConnection {
|
|
1715
|
+
constructor(child, holdMethods, timeouts) {
|
|
1716
|
+
this.child = child;
|
|
1717
|
+
this.holdMethods = holdMethods;
|
|
1718
|
+
this.timeouts = timeouts;
|
|
1719
|
+
this.exited = new Promise((resolve7) => child.once("close", resolve7));
|
|
1720
|
+
child.stderr.resume();
|
|
1721
|
+
child.stdout.setEncoding("utf8");
|
|
1722
|
+
child.stdout.on("data", (chunk) => this.receive(chunk));
|
|
1723
|
+
child.stdin.on("error", () => this.fail(new Error("ACP write failed")));
|
|
1724
|
+
child.stdout.on("error", () => this.fail(new Error("ACP read failed")));
|
|
1725
|
+
child.once("error", () => this.fail(new Error("ACP process failed")));
|
|
1726
|
+
child.once("close", () => this.fail(new Error("ACP process closed")));
|
|
1623
1727
|
}
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
if (typeof id !== "string" || !id) return null;
|
|
1635
|
-
const status = field(item, "status");
|
|
1636
|
-
const finite = (time) => typeof time === "number" && Number.isFinite(time);
|
|
1637
|
-
const completedAt = field(value, "completedAtMs");
|
|
1638
|
-
const times = [field(value, "startedAtMs"), completedAt].filter(finite);
|
|
1639
|
-
return {
|
|
1640
|
-
id,
|
|
1641
|
-
item,
|
|
1642
|
-
status: typeof status === "string" ? status : null,
|
|
1643
|
-
at: times.length ? Math.max(...times) : null,
|
|
1644
|
-
completed: finite(completedAt)
|
|
1728
|
+
pending = /* @__PURE__ */ new Map();
|
|
1729
|
+
heldRequests = /* @__PURE__ */ new Map();
|
|
1730
|
+
exited;
|
|
1731
|
+
nextId = 1;
|
|
1732
|
+
buffer = "";
|
|
1733
|
+
closed = false;
|
|
1734
|
+
recorded;
|
|
1735
|
+
failure;
|
|
1736
|
+
/** Called for each `session/update` notification's params. */
|
|
1737
|
+
onUpdate = () => {
|
|
1645
1738
|
};
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1739
|
+
/** Called when a request starts or stops being held. */
|
|
1740
|
+
onHeldChange = () => {
|
|
1741
|
+
};
|
|
1742
|
+
capabilities = { loadSession: false, listSessions: false };
|
|
1743
|
+
/** Spawns the agent through the executor, so it runs under the user's own login environment. */
|
|
1744
|
+
static async open(executor, agent, requireLive) {
|
|
1745
|
+
const { executable: executable2, args, folder, holdMethods, timeouts, groups } = agent;
|
|
1746
|
+
const supervised = process.platform !== "win32";
|
|
1747
|
+
const token = `tsp-acp-${randomUUID2()}`;
|
|
1748
|
+
const child = supervised ? await executor.spawn(executable2, [...args], folder, requireLive, [
|
|
1749
|
+
process.execPath,
|
|
1750
|
+
"-e",
|
|
1751
|
+
ACP_SUPERVISOR_SOURCE,
|
|
1752
|
+
token
|
|
1753
|
+
]) : await executor.spawn(executable2, [...args], folder, requireLive);
|
|
1754
|
+
const connection = new _AcpConnection(child, holdMethods, timeouts);
|
|
1755
|
+
if (supervised && child.pid !== void 0 && groups) {
|
|
1756
|
+
connection.recorded = { groups, token };
|
|
1757
|
+
await groups.add(token, child.pid).catch(() => void 0);
|
|
1758
|
+
}
|
|
1759
|
+
const abort = () => void connection.close();
|
|
1760
|
+
requireLive?.signal?.addEventListener("abort", abort, { once: true });
|
|
1653
1761
|
try {
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1762
|
+
requireLive?.();
|
|
1763
|
+
connection.capabilities = decodeInitialize(
|
|
1764
|
+
await connection.request(
|
|
1765
|
+
"initialize",
|
|
1766
|
+
{
|
|
1767
|
+
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
1768
|
+
clientCapabilities: {},
|
|
1769
|
+
clientInfo: { name: "tsp_gateway", version: GATEWAY_PACKAGE_VERSION }
|
|
1770
|
+
},
|
|
1771
|
+
{ timeoutMs: timeouts.startupMs }
|
|
1772
|
+
)
|
|
1773
|
+
);
|
|
1774
|
+
return connection;
|
|
1775
|
+
} catch (error) {
|
|
1776
|
+
await connection.close();
|
|
1777
|
+
throw error;
|
|
1778
|
+
} finally {
|
|
1779
|
+
requireLive?.signal?.removeEventListener("abort", abort);
|
|
1657
1780
|
}
|
|
1658
1781
|
}
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
};
|
|
1671
|
-
this.threads.set(threadId, thread);
|
|
1782
|
+
get usable() {
|
|
1783
|
+
return !this.closed && !this.failure;
|
|
1784
|
+
}
|
|
1785
|
+
get held() {
|
|
1786
|
+
return [...this.heldRequests.values()];
|
|
1787
|
+
}
|
|
1788
|
+
fail(error) {
|
|
1789
|
+
this.failure ??= error;
|
|
1790
|
+
for (const request of this.pending.values()) {
|
|
1791
|
+
clearTimeout(request.timer);
|
|
1792
|
+
request.reject(error);
|
|
1672
1793
|
}
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
if (thread.settled.has(entry.id)) {
|
|
1691
|
-
reachedSettled = true;
|
|
1692
|
-
continue;
|
|
1794
|
+
this.pending.clear();
|
|
1795
|
+
if (this.heldRequests.size > 0) {
|
|
1796
|
+
this.heldRequests.clear();
|
|
1797
|
+
this.onHeldChange();
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
write(message) {
|
|
1801
|
+
return new Promise((resolve7, reject) => {
|
|
1802
|
+
if (!this.usable) return reject(this.failure ?? new Error("ACP connection closed"));
|
|
1803
|
+
this.child.stdin.write(
|
|
1804
|
+
`${JSON.stringify({ jsonrpc: "2.0", ...message })}
|
|
1805
|
+
`,
|
|
1806
|
+
(error) => {
|
|
1807
|
+
if (error) {
|
|
1808
|
+
this.fail(new Error("ACP write failed"));
|
|
1809
|
+
reject(error);
|
|
1810
|
+
} else resolve7();
|
|
1693
1811
|
}
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1812
|
+
);
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
receive(chunk) {
|
|
1816
|
+
this.buffer += chunk;
|
|
1817
|
+
for (let end = this.buffer.indexOf("\n"); end >= 0; end = this.buffer.indexOf("\n")) {
|
|
1818
|
+
const line = this.buffer.slice(0, end);
|
|
1819
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
1820
|
+
if (line.trim()) this.dispatch(line);
|
|
1700
1821
|
}
|
|
1701
|
-
|
|
1822
|
+
if (this.buffer.length > MAX_LINE_BYTES) this.fail(new Error("ACP message too large"));
|
|
1823
|
+
}
|
|
1824
|
+
dispatch(line) {
|
|
1825
|
+
let message;
|
|
1826
|
+
try {
|
|
1827
|
+
message = parseJson(line);
|
|
1828
|
+
} catch {
|
|
1829
|
+
return this.fail(new Error("Invalid ACP message"));
|
|
1830
|
+
}
|
|
1831
|
+
if (!isObject(message)) return;
|
|
1832
|
+
const id = field(message, "id");
|
|
1833
|
+
const method = field(message, "method");
|
|
1834
|
+
if (typeof method === "string") {
|
|
1835
|
+
if (typeof id === "number" || typeof id === "string")
|
|
1836
|
+
return this.incomingRequest(id, method, field(message, "params"));
|
|
1837
|
+
if (method === "session/update") this.onUpdate(field(message, "params"));
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
const request = typeof id === "number" ? this.pending.get(id) : void 0;
|
|
1841
|
+
if (!request) return;
|
|
1842
|
+
this.pending.delete(id);
|
|
1843
|
+
clearTimeout(request.timer);
|
|
1844
|
+
const error = field(message, "error");
|
|
1845
|
+
if (isObject(error)) {
|
|
1846
|
+
const code = field(error, "code");
|
|
1847
|
+
const text3 = field(error, "message");
|
|
1848
|
+
request.reject(
|
|
1849
|
+
new AcpRpcError(
|
|
1850
|
+
typeof code === "number" ? code : -32603,
|
|
1851
|
+
typeof text3 === "string" ? text3 : "ACP request failed"
|
|
1852
|
+
)
|
|
1853
|
+
);
|
|
1854
|
+
} else request.resolve(field(message, "result"));
|
|
1855
|
+
}
|
|
1856
|
+
incomingRequest(id, method, params) {
|
|
1857
|
+
if (this.holdMethods.has(method)) {
|
|
1858
|
+
this.heldRequests.set(id, { id, method, text: heldRequestText(params) });
|
|
1859
|
+
this.onHeldChange();
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
void this.write({
|
|
1863
|
+
id,
|
|
1864
|
+
error: { code: METHOD_NOT_FOUND, message: "Method not found" }
|
|
1865
|
+
}).catch(() => void 0);
|
|
1866
|
+
}
|
|
1867
|
+
request(method, params, options = {}) {
|
|
1868
|
+
const { requireLive, timeoutMs = this.timeouts.requestMs } = options;
|
|
1869
|
+
if (!this.usable) return Promise.reject(this.failure ?? new Error("ACP connection closed"));
|
|
1870
|
+
requireLive?.();
|
|
1871
|
+
const id = this.nextId++;
|
|
1872
|
+
return new Promise((resolve7, reject) => {
|
|
1873
|
+
const timer = timeoutMs === null ? void 0 : setTimeout(() => this.fail(new Error(`ACP ${method} timed out`)), timeoutMs);
|
|
1874
|
+
this.pending.set(id, { resolve: resolve7, reject, timer });
|
|
1875
|
+
this.write({ id, method, params }).catch(() => void 0);
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
notify(method, params) {
|
|
1879
|
+
return this.write({ method, params });
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* Answers the held permission requests `cancelled`, which ACP requires once a turn is
|
|
1883
|
+
* cancelled, and drops the other held requests with the turn. It never selects an option.
|
|
1884
|
+
*/
|
|
1885
|
+
async cancelHeld() {
|
|
1886
|
+
const held = this.held;
|
|
1887
|
+
this.heldRequests.clear();
|
|
1888
|
+
if (held.length > 0) this.onHeldChange();
|
|
1889
|
+
for (const request of held)
|
|
1890
|
+
if (request.method === ACP_PERMISSION_METHOD)
|
|
1891
|
+
await this.write({
|
|
1892
|
+
id: request.id,
|
|
1893
|
+
result: { outcome: { outcome: "cancelled" } }
|
|
1894
|
+
}).catch(() => void 0);
|
|
1895
|
+
}
|
|
1896
|
+
async close() {
|
|
1897
|
+
if (this.closed) return this.exited;
|
|
1898
|
+
this.closed = true;
|
|
1899
|
+
this.fail(new Error("ACP connection closed"));
|
|
1900
|
+
this.child.stdin.end();
|
|
1901
|
+
const signal = (name) => this.endProcessGroup(name);
|
|
1902
|
+
const terminate = setTimeout(() => signal("SIGTERM"), 250);
|
|
1903
|
+
const kill = setTimeout(() => signal("SIGKILL"), 1e3);
|
|
1904
|
+
const abandon = new Promise((resolve7) => setTimeout(resolve7, CLOSE_WAIT_MS).unref());
|
|
1905
|
+
try {
|
|
1906
|
+
await Promise.race([this.exited, abandon]);
|
|
1907
|
+
} finally {
|
|
1908
|
+
clearTimeout(terminate);
|
|
1909
|
+
clearTimeout(kill);
|
|
1910
|
+
signal("SIGKILL");
|
|
1911
|
+
this.child.stdout.destroy();
|
|
1912
|
+
this.child.stderr.destroy();
|
|
1913
|
+
await this.recorded?.groups.remove(this.recorded.token).catch(() => void 0);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
/** Signals the agent and anything it started, since a tool it left running holds the pipes open. */
|
|
1917
|
+
endProcessGroup(name) {
|
|
1918
|
+
const pid = this.child.pid;
|
|
1919
|
+
try {
|
|
1920
|
+
if (pid !== void 0 && process.platform !== "win32") process.kill(-pid, name);
|
|
1921
|
+
else this.child.kill(name);
|
|
1922
|
+
} catch {
|
|
1923
|
+
this.child.kill(name);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
};
|
|
1927
|
+
|
|
1928
|
+
// src/acp-session.ts
|
|
1929
|
+
var WAITING_FALLBACK = "The agent is waiting for you.";
|
|
1930
|
+
var TOOL_KINDS = {
|
|
1931
|
+
read: SESSION_ACTIVITY_KIND.READING,
|
|
1932
|
+
search: SESSION_ACTIVITY_KIND.READING,
|
|
1933
|
+
edit: SESSION_ACTIVITY_KIND.EDITING,
|
|
1934
|
+
delete: SESSION_ACTIVITY_KIND.EDITING,
|
|
1935
|
+
move: SESSION_ACTIVITY_KIND.EDITING,
|
|
1936
|
+
execute: SESSION_ACTIVITY_KIND.RUNNING_COMMAND,
|
|
1937
|
+
think: SESSION_ACTIVITY_KIND.THINKING,
|
|
1938
|
+
switch_mode: SESSION_ACTIVITY_KIND.THINKING
|
|
1939
|
+
};
|
|
1940
|
+
var BETWEEN_UPDATES = /* @__PURE__ */ new Set([
|
|
1941
|
+
"agent_message_chunk",
|
|
1942
|
+
"agent_thought_chunk",
|
|
1943
|
+
"user_message_chunk",
|
|
1944
|
+
"plan"
|
|
1945
|
+
]);
|
|
1946
|
+
function messageText(update) {
|
|
1947
|
+
const content = field(update, "content");
|
|
1948
|
+
const text3 = isObject(content) && field(content, "type") === "text" ? field(content, "text") : null;
|
|
1949
|
+
return typeof text3 === "string" ? text3 : "";
|
|
1950
|
+
}
|
|
1951
|
+
var AcpSession = class {
|
|
1952
|
+
constructor(id, name, folder) {
|
|
1953
|
+
this.id = id;
|
|
1954
|
+
this.name = name;
|
|
1955
|
+
this.folder = folder;
|
|
1956
|
+
}
|
|
1957
|
+
state = "starting";
|
|
1958
|
+
waitingFor = null;
|
|
1959
|
+
/** The process running the current turn; null between turns, when nothing runs. */
|
|
1960
|
+
connection = null;
|
|
1961
|
+
/** Set by the owner's Stop, so a turn that ends any other way afterwards still reads stopped. */
|
|
1962
|
+
stopRequested = false;
|
|
1963
|
+
/** Whether a prompt was sent in this process; a reconciled launch sends its seed at most once. */
|
|
1964
|
+
seeded = false;
|
|
1965
|
+
/** Whether the last `session/load` replayed a user message, which proves the seed was sent. */
|
|
1966
|
+
replayed = false;
|
|
1967
|
+
tally = new ActivityTally();
|
|
1968
|
+
said = "";
|
|
1969
|
+
ended = Promise.resolve(true);
|
|
1970
|
+
endTurn = () => {
|
|
1971
|
+
};
|
|
1972
|
+
beginTurn(connection) {
|
|
1973
|
+
this.connection = connection;
|
|
1974
|
+
this.state = "working";
|
|
1975
|
+
this.waitingFor = null;
|
|
1976
|
+
this.seeded = true;
|
|
1977
|
+
this.said = "";
|
|
1978
|
+
this.tally.clearPending();
|
|
1979
|
+
this.stopRequested = false;
|
|
1980
|
+
this.ended = new Promise((resolve7) => {
|
|
1981
|
+
this.endTurn = () => resolve7(true);
|
|
1982
|
+
});
|
|
1983
|
+
}
|
|
1984
|
+
beginReplay() {
|
|
1985
|
+
this.replayed = false;
|
|
1986
|
+
}
|
|
1987
|
+
turnEnded() {
|
|
1988
|
+
return this.ended;
|
|
1989
|
+
}
|
|
1990
|
+
/** A held request is the one thing that makes a working session need the owner. */
|
|
1991
|
+
holding(held) {
|
|
1992
|
+
if (!this.connection) return;
|
|
1993
|
+
const first = held[0];
|
|
1994
|
+
this.state = first ? "needs_input" : "working";
|
|
1995
|
+
this.waitingFor = first ? sanitizeWaiting(first.text ?? WAITING_FALLBACK) : null;
|
|
1996
|
+
}
|
|
1997
|
+
/** The turn is over. A Stop's cancellation outranks every outcome but a completed turn. */
|
|
1998
|
+
finish(state, waitingFor = null) {
|
|
1999
|
+
this.state = this.stopRequested && state !== "done" ? "stopped" : state;
|
|
2000
|
+
this.waitingFor = this.state === "failed" ? waitingFor : null;
|
|
2001
|
+
this.connection = null;
|
|
2002
|
+
this.endTurn();
|
|
2003
|
+
}
|
|
2004
|
+
/** The process that ran this session is gone: it ended with the gateway, and Resume reopens the chat. */
|
|
2005
|
+
endedWithGateway() {
|
|
2006
|
+
this.connection = null;
|
|
2007
|
+
this.state = "stopped";
|
|
2008
|
+
this.waitingFor = null;
|
|
2009
|
+
}
|
|
2010
|
+
replay(params) {
|
|
2011
|
+
if (decodeUpdate(params)?.kind === "user_message_chunk") this.replayed = true;
|
|
2012
|
+
}
|
|
2013
|
+
observe(params) {
|
|
2014
|
+
const update = decodeUpdate(params);
|
|
2015
|
+
if (!update) return;
|
|
2016
|
+
this.tally.stepped(Date.now());
|
|
2017
|
+
const id = field(update.body, "toolCallId");
|
|
2018
|
+
if (update.kind === "tool_call") this.said = "";
|
|
2019
|
+
if (update.kind === "tool_call" && typeof id === "string") {
|
|
2020
|
+
const kind = field(update.body, "kind");
|
|
2021
|
+
this.tally.started(id, TOOL_KINDS[String(kind)] ?? SESSION_ACTIVITY_KIND.USING_TOOL);
|
|
2022
|
+
if (kind === "execute") this.tally.ranCommand();
|
|
2023
|
+
const opening = field(update.body, "status");
|
|
2024
|
+
if (opening === "completed" || opening === "failed") this.tally.finished(id);
|
|
2025
|
+
this.edited(update.body);
|
|
2026
|
+
} else if (update.kind === "tool_call_update" && typeof id === "string") {
|
|
2027
|
+
this.edited(update.body);
|
|
2028
|
+
const status = field(update.body, "status");
|
|
2029
|
+
if (status === "completed" || status === "failed") this.tally.finished(id);
|
|
2030
|
+
} else if (BETWEEN_UPDATES.has(update.kind)) this.tally.between();
|
|
2031
|
+
if (update.kind === "agent_message_chunk") this.said += messageText(update.body);
|
|
2032
|
+
}
|
|
2033
|
+
edited(body) {
|
|
2034
|
+
const content = field(body, "content");
|
|
2035
|
+
if (!Array.isArray(content)) return;
|
|
2036
|
+
for (const part of content)
|
|
2037
|
+
if (isObject(part) && field(part, "type") === "diff") {
|
|
2038
|
+
const path = field(part, "path");
|
|
2039
|
+
if (typeof path === "string") this.tally.editedFile(path);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
/** The turn's last words, only for a finished turn, as the owner's canvas shows them. */
|
|
2043
|
+
lastMessage() {
|
|
2044
|
+
const text3 = sanitizeWaiting(this.said.replace(/\s+/g, " ").trim());
|
|
2045
|
+
return this.state === "done" && text3 ? text3 : void 0;
|
|
2046
|
+
}
|
|
2047
|
+
async snapshot(activityRoot) {
|
|
2048
|
+
return {
|
|
2049
|
+
id: this.id,
|
|
2050
|
+
conversationId: this.id,
|
|
2051
|
+
name: this.name,
|
|
2052
|
+
pid: null,
|
|
2053
|
+
state: this.state,
|
|
2054
|
+
waitingFor: this.waitingFor,
|
|
2055
|
+
...activityRoot === void 0 ? {} : {
|
|
2056
|
+
activity: await this.tally.snapshot(activityRoot),
|
|
2057
|
+
...this.lastMessage() === void 0 ? {} : { lastMessage: this.lastMessage() }
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
};
|
|
2062
|
+
|
|
2063
|
+
// src/acp-driver.ts
|
|
2064
|
+
var ACP_TIMEOUTS = { startupMs: 1e4, requestMs: 3e4 };
|
|
2065
|
+
var CANCEL_GRACE_MS = 2e3;
|
|
2066
|
+
var STORED_TTL_MS = 6e4;
|
|
2067
|
+
var FAILURE_TEXT = {
|
|
2068
|
+
refusal: "The agent refused to continue.",
|
|
2069
|
+
max_tokens: "The agent stopped at its token limit.",
|
|
2070
|
+
max_turn_requests: "The agent stopped at its request limit."
|
|
2071
|
+
};
|
|
2072
|
+
var AcpDriver = class {
|
|
2073
|
+
constructor(agent, executor, timeouts = ACP_TIMEOUTS, groups) {
|
|
2074
|
+
this.agent = agent;
|
|
2075
|
+
this.executor = executor;
|
|
2076
|
+
this.timeouts = timeouts;
|
|
2077
|
+
this.groups = groups;
|
|
2078
|
+
this.displayName = agent.displayName;
|
|
2079
|
+
this.signInInstruction = agent.signInInstruction;
|
|
2080
|
+
this.installInstruction = agent.installInstruction;
|
|
2081
|
+
this.repositorySetupInstruction = agent.repositorySetupInstruction;
|
|
2082
|
+
this.unknownTrustAdmits = agent.unknownTrustAdmits;
|
|
2083
|
+
this.hold = /* @__PURE__ */ new Set([ACP_PERMISSION_METHOD, ...agent.holdMethods]);
|
|
2084
|
+
}
|
|
2085
|
+
displayName;
|
|
2086
|
+
signInInstruction;
|
|
2087
|
+
installInstruction;
|
|
2088
|
+
repositorySetupInstruction;
|
|
2089
|
+
unknownTrustAdmits;
|
|
2090
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2091
|
+
stored = /* @__PURE__ */ new Map();
|
|
2092
|
+
hold;
|
|
2093
|
+
loadSession = false;
|
|
2094
|
+
probedVersion = null;
|
|
2095
|
+
/**
|
|
2096
|
+
* Derived from what the agent advertised at its last probe: Resume needs `session/load`. No
|
|
2097
|
+
* terminal can join a live ACP session, so `attach_hint` is never advertised: the canvas
|
|
2098
|
+
* offers no command that would start a second process on a running chat.
|
|
2099
|
+
*/
|
|
2100
|
+
get capabilities() {
|
|
2101
|
+
return {
|
|
2102
|
+
start: true,
|
|
2103
|
+
stop: true,
|
|
2104
|
+
resume: this.loadSession,
|
|
2105
|
+
attach_hint: false,
|
|
2106
|
+
answer_input: false,
|
|
2107
|
+
stop_starting: true
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
connect(folder, requireLive) {
|
|
2111
|
+
return AcpConnection.open(
|
|
2112
|
+
this.executor,
|
|
2113
|
+
{
|
|
2114
|
+
executable: this.agent.executable,
|
|
2115
|
+
args: this.agent.args,
|
|
2116
|
+
folder,
|
|
2117
|
+
holdMethods: this.hold,
|
|
2118
|
+
timeouts: this.timeouts,
|
|
2119
|
+
groups: this.groups
|
|
2120
|
+
},
|
|
2121
|
+
requireLive
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
async detect(folder) {
|
|
2125
|
+
if (folder) await this.executor.environment(true, folder);
|
|
2126
|
+
return this.probe(folder);
|
|
2127
|
+
}
|
|
2128
|
+
async probe(folder) {
|
|
2129
|
+
const found = await this.agent.probe(this.executor, folder).catch(() => ({ available: false, version: null, signedIn: null }));
|
|
2130
|
+
if (found.available && found.version !== this.probedVersion)
|
|
2131
|
+
await this.readCapabilities(found.version, folder ?? homedir4()).catch(() => void 0);
|
|
2132
|
+
return {
|
|
2133
|
+
harness: this.agent.harness,
|
|
2134
|
+
available: found.available,
|
|
2135
|
+
harness_version: found.version,
|
|
2136
|
+
signed_in: found.signedIn,
|
|
2137
|
+
operations: this.capabilities
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
async readCapabilities(version, folder) {
|
|
2141
|
+
const connection = await this.connect(folder);
|
|
2142
|
+
try {
|
|
2143
|
+
this.loadSession = connection.capabilities.loadSession;
|
|
2144
|
+
this.probedVersion = version;
|
|
2145
|
+
} finally {
|
|
2146
|
+
await connection.close();
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
async requireTrusted(folder) {
|
|
2150
|
+
if (await this.agent.trust(this.executor, folder) !== "trusted")
|
|
2151
|
+
throw new HarnessRefusal("workspace_untrusted");
|
|
2152
|
+
}
|
|
2153
|
+
register(id, name, folder) {
|
|
2154
|
+
const known = this.sessions.get(id);
|
|
2155
|
+
if (known) return known;
|
|
2156
|
+
const session = new AcpSession(id, name, folder);
|
|
2157
|
+
this.sessions.set(id, session);
|
|
2158
|
+
return session;
|
|
2159
|
+
}
|
|
2160
|
+
/** Sends one prompt without waiting for its turn, which ends through `settle`. */
|
|
2161
|
+
beginTurn(session, connection, text3, check) {
|
|
2162
|
+
check();
|
|
2163
|
+
session.beginTurn(connection);
|
|
2164
|
+
connection.onUpdate = (params) => session.observe(params);
|
|
2165
|
+
connection.onHeldChange = () => session.holding(connection.held);
|
|
2166
|
+
void connection.request(
|
|
2167
|
+
"session/prompt",
|
|
2168
|
+
{ sessionId: session.id, prompt: [{ type: "text", text: text3 }] },
|
|
2169
|
+
{ timeoutMs: null }
|
|
2170
|
+
).then((result) => decodeStopReason(result)).then(
|
|
2171
|
+
(reason) => this.settle(session, connection, reason),
|
|
2172
|
+
(error) => this.settle(
|
|
2173
|
+
session,
|
|
2174
|
+
connection,
|
|
2175
|
+
error instanceof Error ? error : new Error("ACP failed")
|
|
2176
|
+
)
|
|
2177
|
+
);
|
|
2178
|
+
}
|
|
2179
|
+
async settle(session, connection, outcome) {
|
|
2180
|
+
if (session.connection !== connection) return;
|
|
2181
|
+
if (typeof outcome === "string") {
|
|
2182
|
+
if (outcome === "end_turn") session.finish("done");
|
|
2183
|
+
else if (outcome === "cancelled") session.finish("stopped");
|
|
2184
|
+
else session.finish("failed", FAILURE_TEXT[outcome]);
|
|
2185
|
+
} else
|
|
2186
|
+
session.finish(
|
|
2187
|
+
"failed",
|
|
2188
|
+
outcome instanceof AcpRpcError ? "The agent reported an error." : "The agent process ended unexpectedly."
|
|
2189
|
+
);
|
|
2190
|
+
await connection.close();
|
|
2191
|
+
}
|
|
2192
|
+
async start(command, folder, requireLive, checkpoint) {
|
|
2193
|
+
await this.requireTrusted(folder);
|
|
2194
|
+
const connection = await this.connect(folder, requireLive);
|
|
2195
|
+
try {
|
|
2196
|
+
const id = decodeSessionId(
|
|
2197
|
+
await connection.request(
|
|
2198
|
+
"session/new",
|
|
2199
|
+
{ cwd: folder, mcpServers: [] },
|
|
2200
|
+
{ requireLive }
|
|
2201
|
+
)
|
|
2202
|
+
);
|
|
2203
|
+
await checkpoint?.(id);
|
|
2204
|
+
const session = this.register(id, command.session_name, folder);
|
|
2205
|
+
this.beginTurn(session, connection, command.seed, promptCheck(requireLive));
|
|
2206
|
+
return id;
|
|
2207
|
+
} catch (error) {
|
|
2208
|
+
await connection.close();
|
|
2209
|
+
throw error;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
async reconcileLaunch(ref, command, folder, requireLive) {
|
|
2213
|
+
const known = this.sessions.get(ref);
|
|
2214
|
+
if (known?.seeded) return known.snapshot();
|
|
2215
|
+
const connection = await this.connect(folder, requireLive);
|
|
2216
|
+
try {
|
|
2217
|
+
if (!connection.capabilities.loadSession) throw new HarnessRefusal("start_uncertain");
|
|
2218
|
+
const session = known ?? this.register(ref, command.session_name, folder);
|
|
2219
|
+
const seeded = await this.load(session, connection, folder, requireLive);
|
|
2220
|
+
if (seeded === void 0) {
|
|
2221
|
+
this.sessions.delete(ref);
|
|
2222
|
+
await connection.close();
|
|
2223
|
+
return void 0;
|
|
2224
|
+
}
|
|
2225
|
+
if (seeded) {
|
|
2226
|
+
session.endedWithGateway();
|
|
2227
|
+
await connection.close();
|
|
2228
|
+
return session.snapshot();
|
|
2229
|
+
}
|
|
2230
|
+
await this.requireTrusted(folder);
|
|
2231
|
+
this.beginTurn(session, connection, command.seed, promptCheck(requireLive));
|
|
2232
|
+
return session.snapshot();
|
|
2233
|
+
} catch (error) {
|
|
2234
|
+
await connection.close();
|
|
2235
|
+
throw error;
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
/**
|
|
2239
|
+
* Reopens a stored session. Returns whether it already holds a user message (the seed was
|
|
2240
|
+
* sent), or undefined when the agent has no such session.
|
|
2241
|
+
*/
|
|
2242
|
+
async load(session, connection, folder, requireLive) {
|
|
2243
|
+
session.beginReplay();
|
|
2244
|
+
connection.onUpdate = (params) => session.replay(params);
|
|
2245
|
+
try {
|
|
2246
|
+
await connection.request(
|
|
2247
|
+
"session/load",
|
|
2248
|
+
{ sessionId: session.id, cwd: folder, mcpServers: [] },
|
|
2249
|
+
{ requireLive }
|
|
2250
|
+
);
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
if (error instanceof AcpRpcError && /not found/i.test(error.message)) return void 0;
|
|
2253
|
+
throw error;
|
|
2254
|
+
}
|
|
2255
|
+
return session.replayed;
|
|
2256
|
+
}
|
|
2257
|
+
async list(folder, _requireLive, query) {
|
|
2258
|
+
const rows = [];
|
|
2259
|
+
const wanted = query && "refs" in query ? new Set(query.refs) : null;
|
|
2260
|
+
const missing = new Set(wanted);
|
|
2261
|
+
for (const session of this.sessions.values()) {
|
|
2262
|
+
if (session.folder !== folder) continue;
|
|
2263
|
+
if (wanted && !wanted.has(session.id)) continue;
|
|
2264
|
+
if (query && "name" in query && session.name !== query.name) continue;
|
|
2265
|
+
missing.delete(session.id);
|
|
2266
|
+
rows.push(
|
|
2267
|
+
await session.snapshot(wantsActivity(query, session.id) ? folder : void 0)
|
|
2268
|
+
);
|
|
2269
|
+
}
|
|
2270
|
+
if (missing.size > 0) {
|
|
2271
|
+
const stored = await this.storedSessions(folder);
|
|
2272
|
+
for (const id of missing) {
|
|
2273
|
+
if (!stored.has(id)) continue;
|
|
2274
|
+
const session = this.register(id, stored.get(id) ?? "", folder);
|
|
2275
|
+
session.endedWithGateway();
|
|
2276
|
+
rows.push(await session.snapshot());
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
return rows;
|
|
2280
|
+
}
|
|
2281
|
+
/** Sessions the agent stored for the folder, found through `session/list` and reused briefly. */
|
|
2282
|
+
async storedSessions(folder) {
|
|
2283
|
+
const cached = this.stored.get(folder);
|
|
2284
|
+
if (cached && Date.now() - cached.at < STORED_TTL_MS) return cached.sessions;
|
|
2285
|
+
const connection = await this.connect(folder);
|
|
2286
|
+
try {
|
|
2287
|
+
if (!connection.capabilities.listSessions)
|
|
2288
|
+
throw new Error("ACP session list unavailable");
|
|
2289
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
2290
|
+
let cursor = null;
|
|
2291
|
+
for (let page2 = 0; page2 < 20; page2++) {
|
|
2292
|
+
const result = decodeStoredSessions(
|
|
2293
|
+
await connection.request(
|
|
2294
|
+
"session/list",
|
|
2295
|
+
cursor ? { cwd: folder, cursor } : { cwd: folder }
|
|
2296
|
+
)
|
|
2297
|
+
);
|
|
2298
|
+
for (const row of result.sessions) sessions.set(row.sessionId, row.title);
|
|
2299
|
+
cursor = result.next;
|
|
2300
|
+
if (!cursor) break;
|
|
2301
|
+
}
|
|
2302
|
+
this.stored.set(folder, { at: Date.now(), sessions });
|
|
2303
|
+
return sessions;
|
|
2304
|
+
} finally {
|
|
2305
|
+
await connection.close();
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
async stop(session, _folder, requireLive) {
|
|
2309
|
+
const running3 = this.sessions.get(session.id);
|
|
2310
|
+
const connection = running3?.connection;
|
|
2311
|
+
if (!running3 || !connection) return;
|
|
2312
|
+
requireLive();
|
|
2313
|
+
running3.stopRequested = true;
|
|
2314
|
+
await connection.notify("session/cancel", { sessionId: running3.id }).catch(() => void 0);
|
|
2315
|
+
await connection.cancelHeld();
|
|
2316
|
+
const ended = await Promise.race([
|
|
2317
|
+
running3.turnEnded(),
|
|
2318
|
+
new Promise((resolve7) => setTimeout(() => resolve7(false), CANCEL_GRACE_MS))
|
|
2319
|
+
]);
|
|
2320
|
+
if (ended === false && running3.connection === connection) running3.finish("stopped");
|
|
2321
|
+
await connection.close();
|
|
2322
|
+
}
|
|
2323
|
+
async resume(session, text3, folder, requireLive) {
|
|
2324
|
+
if (session.state === "working" || session.state === "needs_input")
|
|
2325
|
+
throw new HarnessRefusal("unsupported_command");
|
|
2326
|
+
const detected = await this.detect(folder);
|
|
2327
|
+
if (!detected.available) throw new HarnessRefusal("harness_unavailable");
|
|
2328
|
+
if (detected.signed_in === false) throw new HarnessRefusal("not_signed_in");
|
|
2329
|
+
await this.requireTrusted(folder);
|
|
2330
|
+
if (!this.loadSession) throw new HarnessRefusal("unsupported_command");
|
|
2331
|
+
const record = this.register(session.id, session.name, folder);
|
|
2332
|
+
if (record.connection) throw new HarnessRefusal("unsupported_command");
|
|
2333
|
+
const prompt = text3 ?? (session.state === "stopped" ? RESUME_CONTINUATION : null);
|
|
2334
|
+
const connection = await this.connect(folder, requireLive);
|
|
2335
|
+
try {
|
|
2336
|
+
if (await this.load(record, connection, folder, requireLive) === void 0)
|
|
2337
|
+
throw new HarnessRefusal("session_not_found");
|
|
2338
|
+
if (prompt === null) {
|
|
2339
|
+
record.finish(session.state === "failed" ? "failed" : "done");
|
|
2340
|
+
await connection.close();
|
|
2341
|
+
} else this.beginTurn(record, connection, prompt, promptCheck(requireLive));
|
|
2342
|
+
return session.id;
|
|
2343
|
+
} catch (error) {
|
|
2344
|
+
await connection.close();
|
|
2345
|
+
throw error;
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
attachHint(id) {
|
|
2349
|
+
return { harness: this.agent.harness, session_ref: id };
|
|
2350
|
+
}
|
|
2351
|
+
async repositories(folders) {
|
|
2352
|
+
return Promise.all(
|
|
2353
|
+
Object.entries(folders).sort(([a], [b]) => a.localeCompare(b)).map(async ([slug, folder]) => {
|
|
2354
|
+
const detection = await this.probe(folder);
|
|
2355
|
+
return {
|
|
2356
|
+
harness: this.agent.harness,
|
|
2357
|
+
slug,
|
|
2358
|
+
trust: await this.agent.trust(this.executor, folder),
|
|
2359
|
+
available: detection.available,
|
|
2360
|
+
signed_in: detection.signed_in ?? null
|
|
2361
|
+
};
|
|
2362
|
+
})
|
|
2363
|
+
);
|
|
2364
|
+
}
|
|
2365
|
+
/** Ends agent process groups a gateway killed outright left behind, once at startup. */
|
|
2366
|
+
async reap() {
|
|
2367
|
+
await this.groups?.reap();
|
|
2368
|
+
}
|
|
2369
|
+
/** Ends every agent process this driver owns, as the gateway shuts down. */
|
|
2370
|
+
async dispose() {
|
|
2371
|
+
await Promise.all(
|
|
2372
|
+
[...this.sessions.values()].map((session) => session.connection?.close())
|
|
2373
|
+
);
|
|
2374
|
+
}
|
|
2375
|
+
};
|
|
2376
|
+
|
|
2377
|
+
// src/local-store.ts
|
|
2378
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
2379
|
+
import { chmod, mkdir, open as open3, readFile, realpath as realpath2, rename } from "node:fs/promises";
|
|
2380
|
+
import { homedir as homedir5 } from "node:os";
|
|
2381
|
+
import { dirname as dirname2, isAbsolute as isAbsolute5, join as join6, resolve as resolve3 } from "node:path";
|
|
2382
|
+
function locations(env = process.env, platform = process.platform, home = homedir5()) {
|
|
2383
|
+
const configRoot = platform === "win32" ? env["APPDATA"] ?? join6(home, "AppData", "Roaming") : env["XDG_CONFIG_HOME"] ?? join6(home, ".config");
|
|
2384
|
+
const stateRoot = platform === "win32" ? env["LOCALAPPDATA"] ?? join6(home, "AppData", "Local") : env["XDG_STATE_HOME"] ?? join6(home, ".local", "state");
|
|
2385
|
+
return {
|
|
2386
|
+
config: resolve3(configRoot, "tsp-gateway", "config.json"),
|
|
2387
|
+
state: resolve3(stateRoot, "tsp-gateway")
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
async function privateDirectory(path) {
|
|
2391
|
+
await mkdir(path, { recursive: true, mode: 448 });
|
|
2392
|
+
await chmod(path, 448);
|
|
2393
|
+
}
|
|
2394
|
+
async function privateWrite(path, value) {
|
|
2395
|
+
await privateDirectory(dirname2(path));
|
|
2396
|
+
const temporary = `${path}.${randomUUID3()}.tmp`;
|
|
2397
|
+
const handle = await open3(temporary, "wx", 384);
|
|
2398
|
+
try {
|
|
2399
|
+
await handle.writeFile(value);
|
|
2400
|
+
await handle.sync();
|
|
2401
|
+
} finally {
|
|
2402
|
+
await handle.close();
|
|
2403
|
+
}
|
|
2404
|
+
await rename(temporary, path);
|
|
2405
|
+
}
|
|
2406
|
+
async function readConfig(path) {
|
|
2407
|
+
let text3;
|
|
2408
|
+
try {
|
|
2409
|
+
text3 = await readFile(path, "utf8");
|
|
2410
|
+
} catch (error) {
|
|
2411
|
+
if (isObject(error) && field(error, "code") === "ENOENT")
|
|
2412
|
+
return {
|
|
2413
|
+
repositories: {},
|
|
2414
|
+
pairing: null,
|
|
2415
|
+
loginPath: null,
|
|
2416
|
+
launch: defaultLaunchConfig(),
|
|
2417
|
+
reporting: DEFAULT_REPORTING
|
|
2418
|
+
};
|
|
2419
|
+
throw error;
|
|
2420
|
+
}
|
|
2421
|
+
const value = parseJson(text3);
|
|
2422
|
+
if (!isObject(value) || Object.keys(value).some(
|
|
2423
|
+
(key) => !["repositories", "pairing", "loginPath", "launch", "reporting"].includes(key)
|
|
2424
|
+
))
|
|
2425
|
+
throw new Error("Invalid gateway config");
|
|
2426
|
+
const launch = Object.hasOwn(value, "launch") ? decodeLaunchConfig(field(value, "launch")) : defaultLaunchConfig();
|
|
2427
|
+
const reporting = Object.hasOwn(value, "reporting") ? decodeReporting(field(value, "reporting")) : DEFAULT_REPORTING;
|
|
2428
|
+
const repositories = field(value, "repositories"), pairing = field(value, "pairing"), loginPath = field(value, "loginPath");
|
|
2429
|
+
if (!isObject(repositories) || !(loginPath === null || typeof loginPath === "string"))
|
|
2430
|
+
throw new Error("Invalid gateway config");
|
|
2431
|
+
const map = {};
|
|
2432
|
+
for (const slug of Object.keys(repositories)) {
|
|
2433
|
+
const folder = field(repositories, slug);
|
|
2434
|
+
if (!validSlug(slug) || typeof folder !== "string" || !isAbsolute5(folder))
|
|
2435
|
+
throw new Error("Invalid repository registry");
|
|
2436
|
+
map[slug] = folder;
|
|
2437
|
+
}
|
|
2438
|
+
let paired = null;
|
|
2439
|
+
if (pairing !== null) {
|
|
2440
|
+
if (!isObject(pairing)) throw new Error("Invalid pairing");
|
|
2441
|
+
const origin = field(pairing, "origin"), clientId = field(pairing, "clientId");
|
|
2442
|
+
if (typeof origin !== "string" || typeof clientId !== "string")
|
|
2443
|
+
throw new Error("Invalid pairing");
|
|
2444
|
+
validateOrigin(origin);
|
|
2445
|
+
paired = {
|
|
2446
|
+
...decodeRegistration({
|
|
2447
|
+
machine_id: field(pairing, "machine_id"),
|
|
2448
|
+
hub_path: field(pairing, "hub_path")
|
|
2449
|
+
}),
|
|
2450
|
+
origin,
|
|
2451
|
+
clientId
|
|
2452
|
+
};
|
|
2453
|
+
}
|
|
2454
|
+
return { repositories: map, pairing: paired, loginPath, launch, reporting };
|
|
2455
|
+
}
|
|
2456
|
+
function saveConfig(path, config) {
|
|
2457
|
+
return privateWrite(path, JSON.stringify(config, null, 2) + "\n");
|
|
2458
|
+
}
|
|
2459
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
2460
|
+
function validateOrigin(input) {
|
|
2461
|
+
const url = new URL(input);
|
|
2462
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)))
|
|
2463
|
+
throw new Error(
|
|
2464
|
+
"TSP requires HTTPS (HTTP is allowed only on a loopback host for local tests)"
|
|
2465
|
+
);
|
|
2466
|
+
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash)
|
|
2467
|
+
throw new Error("Use the TSP API origin without a path");
|
|
2468
|
+
return url.origin;
|
|
2469
|
+
}
|
|
2470
|
+
function validSlug(slug) {
|
|
2471
|
+
return slug.length >= 3 && slug.length <= 201 && /^[a-z0-9][a-z0-9_-]*\/[a-z0-9][a-z0-9_.-]*$/.test(slug);
|
|
2472
|
+
}
|
|
2473
|
+
function githubSlug(remote) {
|
|
2474
|
+
const match = /^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([^\s?#]+?)\/?$/.exec(
|
|
2475
|
+
remote.trim()
|
|
2476
|
+
);
|
|
2477
|
+
const slug = match?.[1]?.replace(/\.git$/, "").toLowerCase();
|
|
2478
|
+
return slug && validSlug(slug) ? slug : null;
|
|
2479
|
+
}
|
|
2480
|
+
async function registerFolder(folder, env = process.env) {
|
|
2481
|
+
const absolute = await realpath2(folder);
|
|
2482
|
+
const remotes = await execute("git", ["remote"], env, absolute);
|
|
2483
|
+
if (remotes.code !== 0) throw new Error("Folder is not a Git repository");
|
|
2484
|
+
const names = remotes.stdout.trim().split(/\r?\n/).filter(Boolean).sort((a, b) => Number(b === "origin") - Number(a === "origin"));
|
|
2485
|
+
for (const name of names) {
|
|
2486
|
+
const remote = await execute("git", ["remote", "get-url", name], env, absolute);
|
|
2487
|
+
const slug = remote.code === 0 ? githubSlug(remote.stdout) : null;
|
|
2488
|
+
if (slug) return { slug, folder: absolute };
|
|
2489
|
+
}
|
|
2490
|
+
throw new Error("Folder has no GitHub remote");
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
// src/acp-groups.ts
|
|
2494
|
+
import { execFile } from "node:child_process";
|
|
2495
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
2496
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
2497
|
+
import { promisify } from "node:util";
|
|
2498
|
+
var run = promisify(execFile);
|
|
2499
|
+
var REAP_GRACE_MS = 1e3;
|
|
2500
|
+
async function listProcesses() {
|
|
2501
|
+
try {
|
|
2502
|
+
const { stdout } = await run("ps", ["-axo", "pid=,pgid=,command="]);
|
|
2503
|
+
return stdout.split("\n").flatMap((line) => {
|
|
2504
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
2505
|
+
return match?.[1] && match[2] && match[3] ? [{ pid: Number(match[1]), pgid: Number(match[2]), command: match[3] }] : [];
|
|
2506
|
+
});
|
|
2507
|
+
} catch {
|
|
2508
|
+
return [];
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
var AcpGroupLedger = class {
|
|
2512
|
+
constructor(path) {
|
|
2513
|
+
this.path = path;
|
|
2514
|
+
}
|
|
2515
|
+
queue = Promise.resolve();
|
|
2516
|
+
async read() {
|
|
2517
|
+
try {
|
|
2518
|
+
const value = parseJson(await readFile2(this.path, "utf8"));
|
|
2519
|
+
const groups = isObject(value) ? field(value, "groups") : null;
|
|
2520
|
+
if (!Array.isArray(groups)) return [];
|
|
2521
|
+
return groups.flatMap((row) => {
|
|
2522
|
+
const token = isObject(row) ? field(row, "token") : null;
|
|
2523
|
+
const pgid = isObject(row) ? field(row, "pgid") : null;
|
|
2524
|
+
return typeof token === "string" && typeof pgid === "number" ? [{ token, pgid }] : [];
|
|
2525
|
+
});
|
|
2526
|
+
} catch {
|
|
2527
|
+
return [];
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
change(update) {
|
|
2531
|
+
const next = this.queue.then(async () => {
|
|
2532
|
+
await privateWrite(this.path, JSON.stringify({ groups: update(await this.read()) }));
|
|
2533
|
+
});
|
|
2534
|
+
this.queue = next.catch(() => void 0);
|
|
2535
|
+
return next;
|
|
2536
|
+
}
|
|
2537
|
+
add(token, pgid) {
|
|
2538
|
+
return this.change((groups) => [
|
|
2539
|
+
...groups.filter((row) => row.token !== token),
|
|
2540
|
+
{ token, pgid }
|
|
2541
|
+
]);
|
|
2542
|
+
}
|
|
2543
|
+
remove(token) {
|
|
2544
|
+
return this.change((groups) => groups.filter((row) => row.token !== token));
|
|
2545
|
+
}
|
|
2546
|
+
/** Ends every recorded group that still exists and matches, then forgets them all. */
|
|
2547
|
+
async reap() {
|
|
2548
|
+
const recorded = await this.read();
|
|
2549
|
+
if (recorded.length === 0) return 0;
|
|
2550
|
+
const processes = await listProcesses();
|
|
2551
|
+
let reaped = 0;
|
|
2552
|
+
for (const { token, pgid } of recorded) {
|
|
2553
|
+
const leader = processes.find((row) => row.pid === pgid);
|
|
2554
|
+
const matches2 = leader ? leader.command.includes(token) : processes.some((row) => row.pgid === pgid);
|
|
2555
|
+
if (!matches2) continue;
|
|
2556
|
+
reaped++;
|
|
2557
|
+
this.signal(pgid, "SIGTERM");
|
|
2558
|
+
await delay2(REAP_GRACE_MS);
|
|
2559
|
+
this.signal(pgid, "SIGKILL");
|
|
2560
|
+
}
|
|
2561
|
+
await this.change(() => []);
|
|
2562
|
+
return reaped;
|
|
2563
|
+
}
|
|
2564
|
+
signal(pgid, name) {
|
|
2565
|
+
try {
|
|
2566
|
+
process.kill(-pgid, name);
|
|
2567
|
+
} catch {
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
};
|
|
2572
|
+
|
|
2573
|
+
// src/codex-activity.ts
|
|
2574
|
+
import { isAbsolute as isAbsolute6, sep as sep2 } from "node:path";
|
|
2575
|
+
|
|
2576
|
+
// src/codex-protocol.ts
|
|
2577
|
+
var STATES = {
|
|
2578
|
+
active: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
|
|
2579
|
+
waitingOnApproval: {
|
|
2580
|
+
state: AGENT_SESSION_STATE.NEEDS_INPUT,
|
|
2581
|
+
waitingFor: "Codex needs approval. Open the session locally."
|
|
2582
|
+
},
|
|
2583
|
+
waitingOnUserInput: {
|
|
2584
|
+
state: AGENT_SESSION_STATE.NEEDS_INPUT,
|
|
2585
|
+
waitingFor: "Codex needs your input. Open the session locally."
|
|
2586
|
+
},
|
|
2587
|
+
idle: { state: AGENT_SESSION_STATE.DONE, waitingFor: null },
|
|
2588
|
+
completed: { state: AGENT_SESSION_STATE.DONE, waitingFor: null },
|
|
2589
|
+
interrupted: { state: AGENT_SESSION_STATE.STOPPED, waitingFor: null },
|
|
2590
|
+
failed: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
|
|
2591
|
+
inProgress: { state: AGENT_SESSION_STATE.WORKING, waitingFor: null },
|
|
2592
|
+
systemError: { state: AGENT_SESSION_STATE.FAILED, waitingFor: null },
|
|
2593
|
+
unknown: { state: AGENT_SESSION_STATE.UNKNOWN, waitingFor: null }
|
|
2594
|
+
};
|
|
2595
|
+
function codexId(value) {
|
|
2596
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
|
|
2597
|
+
throw new Error("Invalid Codex session identity");
|
|
2598
|
+
return value;
|
|
2599
|
+
}
|
|
2600
|
+
function member(value, choices, fallback) {
|
|
2601
|
+
return typeof value === "string" && choices.includes(value) ? value : fallback;
|
|
2602
|
+
}
|
|
2603
|
+
function codexThread(value) {
|
|
2604
|
+
if (!isObject(value)) throw new Error("Invalid Codex thread");
|
|
2605
|
+
const cwd = field(value, "cwd"), name = field(value, "name"), status = field(value, "status"), turns = field(value, "turns");
|
|
2606
|
+
if (typeof cwd !== "string" || !isObject(status))
|
|
2607
|
+
throw new Error("Invalid Codex thread metadata");
|
|
2608
|
+
const flags = field(status, "activeFlags");
|
|
2609
|
+
return {
|
|
2610
|
+
id: codexId(field(value, "id")),
|
|
2611
|
+
cwd,
|
|
2612
|
+
name: typeof name === "string" ? name : "",
|
|
2613
|
+
status: member(
|
|
2614
|
+
field(status, "type"),
|
|
2615
|
+
["active", "idle", "systemError", "notLoaded", "unknown"],
|
|
2616
|
+
"unknown"
|
|
2617
|
+
),
|
|
2618
|
+
activeFlags: Array.isArray(flags) ? flags.filter(
|
|
2619
|
+
(flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput"
|
|
2620
|
+
) : [],
|
|
2621
|
+
turns: Array.isArray(turns) ? turns.map(codexTurn) : []
|
|
2622
|
+
};
|
|
2623
|
+
}
|
|
2624
|
+
function codexTurn(value) {
|
|
2625
|
+
if (!isObject(value)) throw new Error("Invalid Codex turn");
|
|
2626
|
+
return {
|
|
2627
|
+
id: codexId(field(value, "id")),
|
|
2628
|
+
status: member(
|
|
2629
|
+
field(value, "status"),
|
|
2630
|
+
["completed", "interrupted", "failed", "inProgress", "unknown"],
|
|
2631
|
+
"unknown"
|
|
2632
|
+
)
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
function latestTurn(value) {
|
|
2636
|
+
if (!isObject(value)) throw new Error("Invalid Codex turn page");
|
|
2637
|
+
const data = field(value, "data");
|
|
2638
|
+
if (!Array.isArray(data) || data.length > 1) throw new Error("Invalid Codex turn page");
|
|
2639
|
+
return data.length ? codexTurn(data[0]) : null;
|
|
2640
|
+
}
|
|
2641
|
+
function threadResult(value) {
|
|
2642
|
+
return codexThread(isObject(value) ? field(value, "thread") : null);
|
|
2643
|
+
}
|
|
2644
|
+
function page(value, decode) {
|
|
2645
|
+
if (!isObject(value)) throw new Error("Invalid Codex thread list");
|
|
2646
|
+
const data = field(value, "data"), cursor = field(value, "nextCursor");
|
|
2647
|
+
if (!Array.isArray(data) || !(cursor === null || typeof cursor === "string"))
|
|
2648
|
+
throw new Error("Invalid Codex thread page");
|
|
2649
|
+
return { threads: data.map(decode), cursor };
|
|
2650
|
+
}
|
|
2651
|
+
function threadPage(value) {
|
|
2652
|
+
return page(value, codexThread);
|
|
2653
|
+
}
|
|
2654
|
+
function loadedThreadPage(value) {
|
|
2655
|
+
return page(value, codexId);
|
|
2656
|
+
}
|
|
2657
|
+
function sessionFromThread(thread) {
|
|
2658
|
+
const key = thread.status === "active" ? thread.activeFlags.find((flag) => flag === "waitingOnApproval") ?? thread.activeFlags[0] ?? "active" : thread.status === "idle" || thread.status === "notLoaded" ? thread.turns.at(-1)?.status ?? "idle" : thread.status;
|
|
2659
|
+
return {
|
|
2660
|
+
id: thread.id,
|
|
2661
|
+
conversationId: thread.id,
|
|
2662
|
+
name: thread.name,
|
|
2663
|
+
pid: null,
|
|
2664
|
+
...STATES[key]
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
// src/codex-activity.ts
|
|
2669
|
+
var PAGE_SIZE = 20;
|
|
2670
|
+
var PAGE_LIMIT = 5;
|
|
2671
|
+
var IDLE_FORGET_MS2 = 60 * 6e4;
|
|
2672
|
+
var SETTLED_MEMORY = 200;
|
|
2673
|
+
var READ_ACTIONS = /* @__PURE__ */ new Set(["read", "listFiles", "search"]);
|
|
2674
|
+
var BETWEEN = /* @__PURE__ */ new Set(["reasoning", "agentMessage", "plan", "userMessage", "hookPrompt"]);
|
|
2675
|
+
function readOnly(item) {
|
|
2676
|
+
const actions = field(item, "commandActions");
|
|
2677
|
+
return Array.isArray(actions) && actions.length > 0 && actions.every(
|
|
2678
|
+
(action) => isObject(action) && READ_ACTIONS.has(String(field(action, "type")))
|
|
2679
|
+
);
|
|
2680
|
+
}
|
|
2681
|
+
function codexItemKind(item) {
|
|
2682
|
+
const type = field(item, "type");
|
|
2683
|
+
if (type === "commandExecution")
|
|
2684
|
+
return readOnly(item) ? SESSION_ACTIVITY_KIND.READING : SESSION_ACTIVITY_KIND.RUNNING_COMMAND;
|
|
2685
|
+
if (type === "fileChange") return SESSION_ACTIVITY_KIND.EDITING;
|
|
2686
|
+
if (type === "mcpToolCall") {
|
|
2687
|
+
const tool = field(item, "tool");
|
|
2688
|
+
return typeof tool === "string" && /^tsp[._]/.test(tool) ? SESSION_ACTIVITY_KIND.USING_PLAN : SESSION_ACTIVITY_KIND.USING_TOOL;
|
|
2689
|
+
}
|
|
2690
|
+
if (type === "collabAgentToolCall" || type === "subAgentActivity")
|
|
2691
|
+
return SESSION_ACTIVITY_KIND.DELEGATING;
|
|
2692
|
+
if (typeof type === "string" && BETWEEN.has(type)) return SESSION_ACTIVITY_KIND.THINKING;
|
|
2693
|
+
return SESSION_ACTIVITY_KIND.USING_TOOL;
|
|
2694
|
+
}
|
|
2695
|
+
function entryOf(value) {
|
|
2696
|
+
if (!isObject(value)) return null;
|
|
2697
|
+
const item = field(value, "item");
|
|
2698
|
+
if (!isObject(item)) return null;
|
|
2699
|
+
const id = field(item, "id");
|
|
2700
|
+
if (typeof id !== "string" || !id) return null;
|
|
2701
|
+
const status = field(item, "status");
|
|
2702
|
+
const finite = (time) => typeof time === "number" && Number.isFinite(time);
|
|
2703
|
+
const completedAt = field(value, "completedAtMs");
|
|
2704
|
+
const times = [field(value, "startedAtMs"), completedAt].filter(finite);
|
|
2705
|
+
return {
|
|
2706
|
+
id,
|
|
2707
|
+
item,
|
|
2708
|
+
status: typeof status === "string" ? status : null,
|
|
2709
|
+
at: times.length ? Math.max(...times) : null,
|
|
2710
|
+
completed: finite(completedAt)
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
var CodexActivity = class {
|
|
2714
|
+
constructor(now = Date.now) {
|
|
2715
|
+
this.now = now;
|
|
2716
|
+
}
|
|
2717
|
+
threads = /* @__PURE__ */ new Map();
|
|
2718
|
+
async activity(server, threadId, root, cwd = root) {
|
|
2719
|
+
try {
|
|
2720
|
+
return await this.read(server, threadId, root, cwd);
|
|
2721
|
+
} catch {
|
|
2722
|
+
return null;
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
async read(server, threadId, root, cwd) {
|
|
2726
|
+
for (const [id, thread2] of this.threads)
|
|
2727
|
+
if (this.now() - thread2.readAt > IDLE_FORGET_MS2) this.threads.delete(id);
|
|
2728
|
+
let thread = this.threads.get(threadId);
|
|
2729
|
+
if (!thread) {
|
|
2730
|
+
thread = {
|
|
2731
|
+
tally: new ActivityTally(),
|
|
2732
|
+
settled: /* @__PURE__ */ new Set(),
|
|
2733
|
+
running: /* @__PURE__ */ new Set(),
|
|
2734
|
+
commands: /* @__PURE__ */ new Set(),
|
|
2735
|
+
cwd,
|
|
2736
|
+
readAt: this.now()
|
|
2737
|
+
};
|
|
2738
|
+
this.threads.set(threadId, thread);
|
|
2739
|
+
}
|
|
2740
|
+
thread.readAt = this.now();
|
|
2741
|
+
thread.cwd = cwd;
|
|
2742
|
+
const entries = [];
|
|
2743
|
+
const unseen = new Set(thread.running);
|
|
2744
|
+
let cursor = null;
|
|
2745
|
+
for (let page2 = 0; page2 < PAGE_LIMIT; page2++) {
|
|
2746
|
+
const response = await server.request("thread/items/list", {
|
|
2747
|
+
threadId: codexId(threadId),
|
|
2748
|
+
limit: PAGE_SIZE,
|
|
2749
|
+
sortDirection: "desc",
|
|
2750
|
+
...cursor ? { cursor } : {}
|
|
2751
|
+
});
|
|
2752
|
+
if (!isObject(response) || !Array.isArray(field(response, "data")))
|
|
2753
|
+
throw new Error("Unrecognised Codex item page");
|
|
2754
|
+
let reachedSettled = false;
|
|
2755
|
+
for (const raw of field(response, "data")) {
|
|
2756
|
+
const entry = entryOf(raw);
|
|
2757
|
+
if (!entry) continue;
|
|
2758
|
+
if (thread.settled.has(entry.id)) {
|
|
2759
|
+
reachedSettled = true;
|
|
2760
|
+
continue;
|
|
2761
|
+
}
|
|
2762
|
+
unseen.delete(entry.id);
|
|
2763
|
+
entries.push(entry);
|
|
2764
|
+
}
|
|
2765
|
+
const next = field(response, "nextCursor");
|
|
2766
|
+
cursor = typeof next === "string" && next ? next : null;
|
|
2767
|
+
if (!cursor || reachedSettled && unseen.size === 0) break;
|
|
2768
|
+
}
|
|
2769
|
+
for (const id of unseen) {
|
|
1702
2770
|
thread.running.delete(id);
|
|
1703
2771
|
thread.commands.delete(id);
|
|
1704
2772
|
thread.tally.finished(id);
|
|
1705
2773
|
}
|
|
1706
2774
|
for (const entry of entries.reverse()) this.apply(thread, entry);
|
|
1707
|
-
return thread.tally.snapshot();
|
|
2775
|
+
return thread.tally.snapshot(root);
|
|
1708
2776
|
}
|
|
1709
2777
|
apply(thread, { id, item, status, at, completed }) {
|
|
1710
2778
|
const kind = codexItemKind(item);
|
|
@@ -1713,8 +2781,8 @@ var CodexActivity = class {
|
|
|
1713
2781
|
thread.commands.add(id);
|
|
1714
2782
|
thread.tally.ranCommand();
|
|
1715
2783
|
}
|
|
1716
|
-
const
|
|
1717
|
-
if (status === "inProgress" ||
|
|
2784
|
+
const open7 = status === null && !completed && kind !== SESSION_ACTIVITY_KIND.THINKING;
|
|
2785
|
+
if (status === "inProgress" || open7) {
|
|
1718
2786
|
thread.running.add(id);
|
|
1719
2787
|
thread.tally.started(id, kind);
|
|
1720
2788
|
return;
|
|
@@ -1727,7 +2795,10 @@ var CodexActivity = class {
|
|
|
1727
2795
|
if (Array.isArray(changes))
|
|
1728
2796
|
for (const change of changes) {
|
|
1729
2797
|
const path = isObject(change) ? field(change, "path") : null;
|
|
1730
|
-
if (typeof path === "string")
|
|
2798
|
+
if (typeof path === "string")
|
|
2799
|
+
thread.tally.editedFile(
|
|
2800
|
+
isAbsolute6(path) ? path : `${thread.cwd}${sep2}${path}`
|
|
2801
|
+
);
|
|
1731
2802
|
}
|
|
1732
2803
|
}
|
|
1733
2804
|
if (status === null && !completed) return;
|
|
@@ -1739,9 +2810,9 @@ var CodexActivity = class {
|
|
|
1739
2810
|
};
|
|
1740
2811
|
|
|
1741
2812
|
// src/codex-trust.ts
|
|
1742
|
-
import { open as
|
|
1743
|
-
import { homedir as
|
|
1744
|
-
import { basename as basename3, dirname, join as
|
|
2813
|
+
import { open as open4, realpath as realpath3 } from "node:fs/promises";
|
|
2814
|
+
import { homedir as homedir6 } from "node:os";
|
|
2815
|
+
import { basename as basename3, dirname as dirname3, join as join7, resolve as resolve4 } from "node:path";
|
|
1745
2816
|
import { parseToml } from "./vendor.js";
|
|
1746
2817
|
var MAX_CONFIG_BYTES2 = 4 * 1024 * 1024;
|
|
1747
2818
|
var CodexTrust = class {
|
|
@@ -1770,18 +2841,18 @@ var CodexTrust = class {
|
|
|
1770
2841
|
folder
|
|
1771
2842
|
);
|
|
1772
2843
|
if (root.code !== 0 || prefix.code !== 0) return "unknown";
|
|
1773
|
-
const canonical2 = await
|
|
2844
|
+
const canonical2 = await realpath3(root.stdout.trim());
|
|
1774
2845
|
const commonDir = common.code === 0 ? common.stdout.trim() : "";
|
|
1775
|
-
const main = basename3(commonDir) === ".git" ? await
|
|
1776
|
-
let given =
|
|
2846
|
+
const main = basename3(commonDir) === ".git" ? await realpath3(dirname3(commonDir)) : canonical2;
|
|
2847
|
+
let given = resolve4(folder);
|
|
1777
2848
|
for (const part of prefix.stdout.trim().split("/").filter(Boolean)) {
|
|
1778
|
-
if (part) given =
|
|
2849
|
+
if (part) given = dirname3(given);
|
|
1779
2850
|
}
|
|
1780
|
-
const path =
|
|
1781
|
-
env["CODEX_HOME"] ??
|
|
2851
|
+
const path = join7(
|
|
2852
|
+
env["CODEX_HOME"] ?? join7(env["HOME"] ?? homedir6(), ".codex"),
|
|
1782
2853
|
"config.toml"
|
|
1783
2854
|
);
|
|
1784
|
-
const file = await
|
|
2855
|
+
const file = await open4(path, "r");
|
|
1785
2856
|
let contents;
|
|
1786
2857
|
try {
|
|
1787
2858
|
if (!(await file.stat()).isFile()) return "unknown";
|
|
@@ -1817,7 +2888,7 @@ var CodexTrust = class {
|
|
|
1817
2888
|
};
|
|
1818
2889
|
|
|
1819
2890
|
// src/codex-driver.ts
|
|
1820
|
-
import { realpath as
|
|
2891
|
+
import { realpath as realpath5 } from "node:fs/promises";
|
|
1821
2892
|
|
|
1822
2893
|
// src/codex-app-server.ts
|
|
1823
2894
|
import { Duplex } from "node:stream";
|
|
@@ -1828,7 +2899,7 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1828
2899
|
constructor(child, timeouts) {
|
|
1829
2900
|
this.child = child;
|
|
1830
2901
|
this.timeouts = timeouts;
|
|
1831
|
-
this.exited = new Promise((
|
|
2902
|
+
this.exited = new Promise((resolve7) => child.once("close", resolve7));
|
|
1832
2903
|
this.stream = new Duplex({
|
|
1833
2904
|
read() {
|
|
1834
2905
|
},
|
|
@@ -1896,7 +2967,7 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1896
2967
|
static async connect(executor, executable2, folder, timeouts, requireLive) {
|
|
1897
2968
|
const timeout = new Error("Codex connection timed out");
|
|
1898
2969
|
let expired = false;
|
|
1899
|
-
let
|
|
2970
|
+
let connection;
|
|
1900
2971
|
let timer;
|
|
1901
2972
|
const deadline = new Promise((_resolve, reject) => {
|
|
1902
2973
|
timer = setTimeout(() => {
|
|
@@ -1910,19 +2981,19 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1910
2981
|
requireLive?.();
|
|
1911
2982
|
});
|
|
1912
2983
|
const server = new _CodexAppServer(child, timeouts);
|
|
1913
|
-
|
|
2984
|
+
connection = server;
|
|
1914
2985
|
if (expired) {
|
|
1915
2986
|
await server.close();
|
|
1916
2987
|
throw timeout;
|
|
1917
2988
|
}
|
|
1918
|
-
await new Promise((
|
|
2989
|
+
await new Promise((resolve7, reject) => {
|
|
1919
2990
|
const opened = () => finish();
|
|
1920
2991
|
const failed = () => finish(new Error("Cannot connect to Codex"));
|
|
1921
2992
|
function finish(error) {
|
|
1922
2993
|
server.socket.off("open", opened).off("error", failed).off("close", failed);
|
|
1923
2994
|
child.off("error", failed).off("close", failed);
|
|
1924
2995
|
if (error) reject(error);
|
|
1925
|
-
else
|
|
2996
|
+
else resolve7();
|
|
1926
2997
|
}
|
|
1927
2998
|
server.socket.once("open", opened).once("error", failed).once("close", failed);
|
|
1928
2999
|
child.once("error", failed).once("close", failed);
|
|
@@ -1942,7 +3013,7 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1942
3013
|
try {
|
|
1943
3014
|
return await Promise.race([startup(), deadline]);
|
|
1944
3015
|
} catch (error) {
|
|
1945
|
-
await
|
|
3016
|
+
await connection?.close();
|
|
1946
3017
|
throw error;
|
|
1947
3018
|
} finally {
|
|
1948
3019
|
clearTimeout(timer);
|
|
@@ -1961,12 +3032,12 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1961
3032
|
return Promise.reject(this.failure ?? new Error("Codex connection closed"));
|
|
1962
3033
|
requireLive?.();
|
|
1963
3034
|
const id = this.nextId++;
|
|
1964
|
-
return new Promise((
|
|
3035
|
+
return new Promise((resolve7, reject) => {
|
|
1965
3036
|
const timer = setTimeout(() => {
|
|
1966
3037
|
this.fail(new Error(`Codex ${method} timed out`));
|
|
1967
3038
|
}, timeoutMs);
|
|
1968
3039
|
this.pending.set(id, {
|
|
1969
|
-
resolve:
|
|
3040
|
+
resolve: resolve7,
|
|
1970
3041
|
reject,
|
|
1971
3042
|
timer,
|
|
1972
3043
|
method,
|
|
@@ -1985,10 +3056,10 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
1985
3056
|
let timer;
|
|
1986
3057
|
let onClose = () => {
|
|
1987
3058
|
};
|
|
1988
|
-
const closed = new Promise((
|
|
1989
|
-
onClose =
|
|
3059
|
+
const closed = new Promise((resolve7) => {
|
|
3060
|
+
onClose = resolve7;
|
|
1990
3061
|
this.socket.once("close", onClose);
|
|
1991
|
-
timer = setTimeout(
|
|
3062
|
+
timer = setTimeout(resolve7, 250);
|
|
1992
3063
|
});
|
|
1993
3064
|
this.socket.close(1e3);
|
|
1994
3065
|
try {
|
|
@@ -2013,13 +3084,12 @@ var CodexAppServer = class _CodexAppServer {
|
|
|
2013
3084
|
};
|
|
2014
3085
|
|
|
2015
3086
|
// src/codex-sessions.ts
|
|
2016
|
-
import { realpath as
|
|
2017
|
-
import { isAbsolute as
|
|
3087
|
+
import { realpath as realpath4 } from "node:fs/promises";
|
|
3088
|
+
import { isAbsolute as isAbsolute7, resolve as resolve5 } from "node:path";
|
|
2018
3089
|
async function inside(folder, cwd) {
|
|
2019
|
-
if (!
|
|
2020
|
-
const path = await
|
|
2021
|
-
|
|
2022
|
-
return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute4(child);
|
|
3090
|
+
if (!isAbsolute7(cwd)) return false;
|
|
3091
|
+
const path = await realpath4(cwd).catch(() => resolve5(cwd));
|
|
3092
|
+
return contains(folder, path);
|
|
2023
3093
|
}
|
|
2024
3094
|
async function lastTurn(server, id) {
|
|
2025
3095
|
return latestTurn(
|
|
@@ -2089,7 +3159,7 @@ async function* threads(server, folder, query) {
|
|
|
2089
3159
|
}
|
|
2090
3160
|
}
|
|
2091
3161
|
async function listCodexSessions(server, folder, query, activity) {
|
|
2092
|
-
const root = await
|
|
3162
|
+
const root = await realpath4(folder);
|
|
2093
3163
|
const sessions = [];
|
|
2094
3164
|
for await (let thread of threads(server, folder, query)) {
|
|
2095
3165
|
if (!await inside(root, thread.cwd)) continue;
|
|
@@ -2104,7 +3174,7 @@ async function listCodexSessions(server, folder, query, activity) {
|
|
|
2104
3174
|
}
|
|
2105
3175
|
const session = sessionFromThread(thread);
|
|
2106
3176
|
if (activity && wantsActivity(query, session.id))
|
|
2107
|
-
session.activity = await activity.activity(server, session.id);
|
|
3177
|
+
session.activity = await activity.activity(server, session.id, root, thread.cwd);
|
|
2108
3178
|
sessions.push(session);
|
|
2109
3179
|
}
|
|
2110
3180
|
return sessions;
|
|
@@ -2134,6 +3204,22 @@ async function discardThread(server, threadId) {
|
|
|
2134
3204
|
} catch {
|
|
2135
3205
|
}
|
|
2136
3206
|
}
|
|
3207
|
+
async function seedThread(server, thread, command, requireLive) {
|
|
3208
|
+
if (thread.name !== command.session_name)
|
|
3209
|
+
await server.request(
|
|
3210
|
+
"thread/name/set",
|
|
3211
|
+
{ threadId: thread.id, name: command.session_name },
|
|
3212
|
+
requireLive
|
|
3213
|
+
);
|
|
3214
|
+
await server.request(
|
|
3215
|
+
"turn/start",
|
|
3216
|
+
{
|
|
3217
|
+
threadId: thread.id,
|
|
3218
|
+
input: [{ type: "text", text: command.seed, text_elements: [] }]
|
|
3219
|
+
},
|
|
3220
|
+
promptCheck(requireLive)
|
|
3221
|
+
);
|
|
3222
|
+
}
|
|
2137
3223
|
var CodexDriver = class {
|
|
2138
3224
|
constructor(env, executable2 = "codex", executor = new HarnessExecutor(env), timeouts = {}) {
|
|
2139
3225
|
this.executable = executable2;
|
|
@@ -2152,7 +3238,8 @@ var CodexDriver = class {
|
|
|
2152
3238
|
stop: true,
|
|
2153
3239
|
resume: true,
|
|
2154
3240
|
attach_hint: true,
|
|
2155
|
-
answer_input: false
|
|
3241
|
+
answer_input: false,
|
|
3242
|
+
stop_starting: true
|
|
2156
3243
|
};
|
|
2157
3244
|
trust;
|
|
2158
3245
|
activity = new CodexActivity();
|
|
@@ -2252,19 +3339,7 @@ var CodexDriver = class {
|
|
|
2252
3339
|
);
|
|
2253
3340
|
await checkpoint?.(thread.id);
|
|
2254
3341
|
try {
|
|
2255
|
-
await server
|
|
2256
|
-
"thread/name/set",
|
|
2257
|
-
{ threadId: thread.id, name: command.session_name },
|
|
2258
|
-
requireLive
|
|
2259
|
-
);
|
|
2260
|
-
await server.request(
|
|
2261
|
-
"turn/start",
|
|
2262
|
-
{
|
|
2263
|
-
threadId: thread.id,
|
|
2264
|
-
input: [{ type: "text", text: command.seed, text_elements: [] }]
|
|
2265
|
-
},
|
|
2266
|
-
requireLive
|
|
2267
|
-
);
|
|
3342
|
+
await seedThread(server, thread, command, requireLive);
|
|
2268
3343
|
} catch (error) {
|
|
2269
3344
|
if (error instanceof HarnessRefusal) await discardThread(server, thread.id);
|
|
2270
3345
|
throw error;
|
|
@@ -2290,7 +3365,7 @@ var CodexDriver = class {
|
|
|
2290
3365
|
if (error instanceof CodexThreadMissing) return void 0;
|
|
2291
3366
|
throw error;
|
|
2292
3367
|
}
|
|
2293
|
-
if (!await inside(await
|
|
3368
|
+
if (!await inside(await realpath5(folder), thread.cwd))
|
|
2294
3369
|
throw new HarnessRefusal("start_uncertain");
|
|
2295
3370
|
const turn = await lastTurn(server, thread.id);
|
|
2296
3371
|
if (turn) return sessionFromThread({ ...thread, turns: [turn] });
|
|
@@ -2304,20 +3379,7 @@ var CodexDriver = class {
|
|
|
2304
3379
|
const loadedTurn = await lastTurn(server, thread.id);
|
|
2305
3380
|
if (loadedTurn) return sessionFromThread({ ...thread, turns: [loadedTurn] });
|
|
2306
3381
|
}
|
|
2307
|
-
|
|
2308
|
-
await server.request(
|
|
2309
|
-
"thread/name/set",
|
|
2310
|
-
{ threadId: thread.id, name: command.session_name },
|
|
2311
|
-
requireLive
|
|
2312
|
-
);
|
|
2313
|
-
await server.request(
|
|
2314
|
-
"turn/start",
|
|
2315
|
-
{
|
|
2316
|
-
threadId: thread.id,
|
|
2317
|
-
input: [{ type: "text", text: command.seed, text_elements: [] }]
|
|
2318
|
-
},
|
|
2319
|
-
requireLive
|
|
2320
|
-
);
|
|
3382
|
+
await seedThread(server, thread, command, requireLive);
|
|
2321
3383
|
return { ...sessionFromThread(thread), state: "starting", waitingFor: null };
|
|
2322
3384
|
},
|
|
2323
3385
|
requireLive
|
|
@@ -2381,7 +3443,7 @@ var CodexDriver = class {
|
|
|
2381
3443
|
threadId: id,
|
|
2382
3444
|
input: [{ type: "text", text: prompt, text_elements: [] }]
|
|
2383
3445
|
},
|
|
2384
|
-
requireLive
|
|
3446
|
+
promptCheck(requireLive)
|
|
2385
3447
|
);
|
|
2386
3448
|
return id;
|
|
2387
3449
|
},
|
|
@@ -2407,6 +3469,81 @@ var CodexDriver = class {
|
|
|
2407
3469
|
}
|
|
2408
3470
|
};
|
|
2409
3471
|
|
|
3472
|
+
// src/cursor-agent.ts
|
|
3473
|
+
import { open as open5, realpath as realpath6 } from "node:fs/promises";
|
|
3474
|
+
import { homedir as homedir7 } from "node:os";
|
|
3475
|
+
import { join as join8 } from "node:path";
|
|
3476
|
+
var MINIMUM_CURSOR_VERSION = "2026.10.19";
|
|
3477
|
+
var MAX_RECORD_BYTES = 64 * 1024;
|
|
3478
|
+
function supportedVersion(version) {
|
|
3479
|
+
const parts = (text3) => (text3.split(/[-+]/)[0] ?? "").split(".").map(Number);
|
|
3480
|
+
if (!version) return true;
|
|
3481
|
+
const found = parts(version), minimum = parts(MINIMUM_CURSOR_VERSION);
|
|
3482
|
+
for (const [index, part] of minimum.entries()) {
|
|
3483
|
+
const value = found[index] ?? 0;
|
|
3484
|
+
if (value !== part) return value > part;
|
|
3485
|
+
}
|
|
3486
|
+
return true;
|
|
3487
|
+
}
|
|
3488
|
+
function cursorProjectKey(folder) {
|
|
3489
|
+
return folder.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
3490
|
+
}
|
|
3491
|
+
var CursorAgent = class {
|
|
3492
|
+
harness = HARNESS_KIND.CURSOR;
|
|
3493
|
+
displayName = "Cursor";
|
|
3494
|
+
executable = "agent";
|
|
3495
|
+
args = ["acp"];
|
|
3496
|
+
holdMethods = ["cursor/ask_question", "cursor/create_plan"];
|
|
3497
|
+
repositorySetupInstruction = "Run agent in that folder once and trust the workspace when it asks.";
|
|
3498
|
+
signInInstruction = "Run agent login and sign in.";
|
|
3499
|
+
installInstruction = `Install the Cursor CLI ${MINIMUM_CURSOR_VERSION} or newer with curl https://cursor.com/install -fsS | bash, then run connect again.`;
|
|
3500
|
+
/** ACP has no trust gate of its own, so an undecided folder is a step to take, not a launch to admit. */
|
|
3501
|
+
unknownTrustAdmits = false;
|
|
3502
|
+
async probe(executor, folder) {
|
|
3503
|
+
const probe = { available: false, version: null, signedIn: null };
|
|
3504
|
+
const version = await executor.execute(this.executable, ["--version"], "read", folder);
|
|
3505
|
+
probe.version = version.stdout.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-[A-Za-z0-9.]+)?/)?.[0]?.slice(0, 80) ?? null;
|
|
3506
|
+
probe.available = version.code === 0 && probe.version !== null && supportedVersion(probe.version);
|
|
3507
|
+
if (!probe.available) return probe;
|
|
3508
|
+
const status = await executor.execute(this.executable, ["status"], "read", folder);
|
|
3509
|
+
const text3 = status.stdout + status.stderr;
|
|
3510
|
+
probe.signedIn = /not logged in|not authenticated|login required/i.test(text3) ? false : status.code === 0 && /logged in/i.test(text3) ? true : null;
|
|
3511
|
+
return probe;
|
|
3512
|
+
}
|
|
3513
|
+
async trust(executor, folder) {
|
|
3514
|
+
try {
|
|
3515
|
+
const env = await executor.environment(false, folder);
|
|
3516
|
+
const root = env["CURSOR_CONFIG_DIR"] ?? join8(env["HOME"] ?? homedir7(), ".cursor");
|
|
3517
|
+
const canonical2 = await realpath6(folder);
|
|
3518
|
+
for (const spelling of /* @__PURE__ */ new Set([canonical2, folder])) {
|
|
3519
|
+
const record = await readRecord(
|
|
3520
|
+
join8(root, "projects", cursorProjectKey(spelling), ".workspace-trusted")
|
|
3521
|
+
);
|
|
3522
|
+
if (isObject(record) && field(record, "workspacePath") === spelling)
|
|
3523
|
+
return "trusted";
|
|
3524
|
+
}
|
|
3525
|
+
return "unknown";
|
|
3526
|
+
} catch {
|
|
3527
|
+
return "unknown";
|
|
3528
|
+
}
|
|
3529
|
+
}
|
|
3530
|
+
};
|
|
3531
|
+
async function readRecord(path) {
|
|
3532
|
+
try {
|
|
3533
|
+
const file = await open5(path, "r");
|
|
3534
|
+
try {
|
|
3535
|
+
if (!(await file.stat()).isFile()) return null;
|
|
3536
|
+
const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);
|
|
3537
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
|
|
3538
|
+
return bytesRead > MAX_RECORD_BYTES ? null : parseJson(buffer.subarray(0, bytesRead).toString("utf8"));
|
|
3539
|
+
} finally {
|
|
3540
|
+
await file.close();
|
|
3541
|
+
}
|
|
3542
|
+
} catch {
|
|
3543
|
+
return null;
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
|
|
2410
3547
|
// src/harness-registry.ts
|
|
2411
3548
|
var HarnessRegistry = class {
|
|
2412
3549
|
constructor(drivers) {
|
|
@@ -2435,6 +3572,12 @@ var HarnessRegistry = class {
|
|
|
2435
3572
|
async detect() {
|
|
2436
3573
|
return Promise.all(Object.values(this.drivers).map((driver) => driver.detect()));
|
|
2437
3574
|
}
|
|
3575
|
+
async reap() {
|
|
3576
|
+
await Promise.all(Object.values(this.drivers).map((driver) => driver.reap?.()));
|
|
3577
|
+
}
|
|
3578
|
+
async dispose() {
|
|
3579
|
+
await Promise.all(Object.values(this.drivers).map((driver) => driver.dispose?.()));
|
|
3580
|
+
}
|
|
2438
3581
|
async repositories(folders) {
|
|
2439
3582
|
return (await Promise.all(
|
|
2440
3583
|
Object.values(this.drivers).map((driver) => driver.repositories(folders))
|
|
@@ -2443,14 +3586,23 @@ var HarnessRegistry = class {
|
|
|
2443
3586
|
};
|
|
2444
3587
|
|
|
2445
3588
|
// src/builtin-harnesses.ts
|
|
2446
|
-
function builtinHarnesses(environment, executor = new HarnessExecutor(environment)) {
|
|
3589
|
+
function builtinHarnesses(environment, executor = new HarnessExecutor(environment), acpGroupsFile) {
|
|
2447
3590
|
return new HarnessRegistry({
|
|
2448
3591
|
[HARNESS_KIND.CLAUDE_CODE]: new ClaudeDriver(environment, "claude", void 0, executor),
|
|
2449
|
-
[HARNESS_KIND.CODEX]: new CodexDriver(environment, "codex", executor)
|
|
3592
|
+
[HARNESS_KIND.CODEX]: new CodexDriver(environment, "codex", executor),
|
|
3593
|
+
[HARNESS_KIND.CURSOR]: new AcpDriver(
|
|
3594
|
+
new CursorAgent(),
|
|
3595
|
+
executor,
|
|
3596
|
+
void 0,
|
|
3597
|
+
acpGroupsFile ? new AcpGroupLedger(acpGroupsFile) : void 0
|
|
3598
|
+
)
|
|
2450
3599
|
});
|
|
2451
3600
|
}
|
|
2452
3601
|
|
|
2453
3602
|
// src/command-lifetime.ts
|
|
3603
|
+
function withdrawnReason(command) {
|
|
3604
|
+
return command.kind === "launch" ? "launch_withdrawn" : "control_withdrawn";
|
|
3605
|
+
}
|
|
2454
3606
|
var lifetimeClock = {
|
|
2455
3607
|
monotonic: () => performance.now(),
|
|
2456
3608
|
wall: () => Date.now()
|
|
@@ -2463,140 +3615,131 @@ var CommandLifetime = class {
|
|
|
2463
3615
|
this.deadline = clock.monotonic() + remaining;
|
|
2464
3616
|
}
|
|
2465
3617
|
deadline;
|
|
3618
|
+
withdrawal = new AbortController();
|
|
3619
|
+
uncertain = false;
|
|
3620
|
+
held = false;
|
|
2466
3621
|
remaining() {
|
|
2467
3622
|
return Math.max(0, this.deadline - this.clock.monotonic());
|
|
2468
3623
|
}
|
|
2469
3624
|
checkpoint() {
|
|
2470
3625
|
return { remainingMs: this.remaining(), savedAtMs: this.clock.wall() };
|
|
2471
3626
|
}
|
|
3627
|
+
/**
|
|
3628
|
+
* Marks a start an earlier attempt journaled without an outcome. A withdrawal it already
|
|
3629
|
+
* received becomes a hold, so the retry can still find what that attempt started.
|
|
3630
|
+
*/
|
|
3631
|
+
uncertainStart() {
|
|
3632
|
+
this.uncertain = true;
|
|
3633
|
+
if (!this.withdrawal.signal.aborted) return;
|
|
3634
|
+
this.held = true;
|
|
3635
|
+
this.withdrawal = new AbortController();
|
|
3636
|
+
}
|
|
3637
|
+
/**
|
|
3638
|
+
* Aborts `signal` and fails every later check of this launch or resume, or only holds an
|
|
3639
|
+
* uncertain one. Repeating it changes nothing.
|
|
3640
|
+
*/
|
|
3641
|
+
withdraw(command) {
|
|
3642
|
+
if (command.kind === "stop" || this.held || this.withdrawal.signal.aborted) return;
|
|
3643
|
+
if (this.uncertain) {
|
|
3644
|
+
this.held = true;
|
|
3645
|
+
return;
|
|
3646
|
+
}
|
|
3647
|
+
this.withdrawal.abort(new HarnessRefusal(withdrawnReason(command)));
|
|
3648
|
+
}
|
|
2472
3649
|
requireLive(command) {
|
|
3650
|
+
if (this.withdrawal.signal.aborted) throw this.withdrawal.signal.reason;
|
|
2473
3651
|
if (this.remaining() <= 0)
|
|
2474
3652
|
throw new HarnessRefusal(
|
|
2475
3653
|
command.kind === "launch" ? "launch_expired" : "control_expired"
|
|
2476
3654
|
);
|
|
2477
3655
|
}
|
|
3656
|
+
/** The checks a command's harness effects run, carrying the withdrawal signal with them. */
|
|
3657
|
+
check(command) {
|
|
3658
|
+
return Object.assign(() => this.requireLive(command), {
|
|
3659
|
+
signal: this.withdrawal.signal,
|
|
3660
|
+
prompt: () => {
|
|
3661
|
+
this.requireLive(command);
|
|
3662
|
+
if (this.held) throw new HarnessRefusal(withdrawnReason(command));
|
|
3663
|
+
}
|
|
3664
|
+
});
|
|
3665
|
+
}
|
|
3666
|
+
/**
|
|
3667
|
+
* Waits for read-only preparation, ending the wait at a withdrawal. The abandoned work
|
|
3668
|
+
* finishes on its own and its result is dropped; it sends no prompt.
|
|
3669
|
+
*/
|
|
3670
|
+
async unlessWithdrawn(work) {
|
|
3671
|
+
const { signal } = this.withdrawal;
|
|
3672
|
+
work.catch(() => void 0);
|
|
3673
|
+
if (signal.aborted) throw signal.reason;
|
|
3674
|
+
let detach = () => {
|
|
3675
|
+
};
|
|
3676
|
+
const withdrawn = new Promise((_resolve, reject) => {
|
|
3677
|
+
const abort = () => reject(signal.reason);
|
|
3678
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
3679
|
+
detach = () => signal.removeEventListener("abort", abort);
|
|
3680
|
+
});
|
|
3681
|
+
try {
|
|
3682
|
+
return await Promise.race([work, withdrawn]);
|
|
3683
|
+
} finally {
|
|
3684
|
+
detach();
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
2478
3687
|
};
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
state: resolve4(stateRoot, "tsp-gateway")
|
|
2491
|
-
};
|
|
2492
|
-
}
|
|
2493
|
-
async function privateDirectory(path) {
|
|
2494
|
-
await mkdir(path, { recursive: true, mode: 448 });
|
|
2495
|
-
await chmod(path, 448);
|
|
2496
|
-
}
|
|
2497
|
-
async function privateWrite(path, value) {
|
|
2498
|
-
await privateDirectory(dirname2(path));
|
|
2499
|
-
const temporary = `${path}.${randomUUID2()}.tmp`;
|
|
2500
|
-
const handle = await open4(temporary, "wx", 384);
|
|
2501
|
-
try {
|
|
2502
|
-
await handle.writeFile(value);
|
|
2503
|
-
await handle.sync();
|
|
2504
|
-
} finally {
|
|
2505
|
-
await handle.close();
|
|
3688
|
+
var CommandLifetimes = class {
|
|
3689
|
+
constructor(journal, clock) {
|
|
3690
|
+
this.journal = journal;
|
|
3691
|
+
this.clock = clock;
|
|
3692
|
+
for (const entry of journal.entries.values()) {
|
|
3693
|
+
const { command } = entry;
|
|
3694
|
+
const lifetime = new CommandLifetime(command.ttl_ms, clock, entry.lifetime);
|
|
3695
|
+
this.lifetimes.set(command.command_id, lifetime);
|
|
3696
|
+
if (entry.receipt === null && command.kind !== "stop") lifetime.uncertainStart();
|
|
3697
|
+
if (command.kind === "stop") this.withdrawStarts(command);
|
|
3698
|
+
}
|
|
2506
3699
|
}
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
};
|
|
2522
|
-
throw error;
|
|
3700
|
+
lifetimes = /* @__PURE__ */ new Map();
|
|
3701
|
+
/** Commands received but not journaled yet, so a Stop can withdraw a start still queued. */
|
|
3702
|
+
queued = /* @__PURE__ */ new Map();
|
|
3703
|
+
receive(command) {
|
|
3704
|
+
let lifetime = this.lifetimes.get(command.command_id);
|
|
3705
|
+
if (!lifetime) {
|
|
3706
|
+
lifetime = new CommandLifetime(command.ttl_ms, this.clock);
|
|
3707
|
+
this.lifetimes.set(command.command_id, lifetime);
|
|
3708
|
+
if (!this.journal.entries.has(command.command_id))
|
|
3709
|
+
this.queued.set(command.command_id, command);
|
|
3710
|
+
}
|
|
3711
|
+
if (command.kind === "stop" && !this.journal.entries.get(command.command_id)?.receipt)
|
|
3712
|
+
this.withdrawStarts(command);
|
|
3713
|
+
return lifetime;
|
|
2523
3714
|
}
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
))
|
|
2528
|
-
throw new Error("Invalid gateway config");
|
|
2529
|
-
const launch = Object.hasOwn(value, "launch") ? decodeLaunchConfig(field(value, "launch")) : defaultLaunchConfig();
|
|
2530
|
-
const reporting = Object.hasOwn(value, "reporting") ? decodeReporting(field(value, "reporting")) : DEFAULT_REPORTING;
|
|
2531
|
-
const repositories = field(value, "repositories"), pairing = field(value, "pairing"), loginPath = field(value, "loginPath");
|
|
2532
|
-
if (!isObject(repositories) || !(loginPath === null || typeof loginPath === "string"))
|
|
2533
|
-
throw new Error("Invalid gateway config");
|
|
2534
|
-
const map = {};
|
|
2535
|
-
for (const slug of Object.keys(repositories)) {
|
|
2536
|
-
const folder = field(repositories, slug);
|
|
2537
|
-
if (!validSlug(slug) || typeof folder !== "string" || !isAbsolute5(folder))
|
|
2538
|
-
throw new Error("Invalid repository registry");
|
|
2539
|
-
map[slug] = folder;
|
|
3715
|
+
/** The command left the queue; the journal holds it from here on. */
|
|
3716
|
+
dequeued(commandId) {
|
|
3717
|
+
this.queued.delete(commandId);
|
|
2540
3718
|
}
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
...decodeRegistration({
|
|
2550
|
-
machine_id: field(pairing, "machine_id"),
|
|
2551
|
-
hub_path: field(pairing, "hub_path")
|
|
2552
|
-
}),
|
|
2553
|
-
origin,
|
|
2554
|
-
clientId
|
|
2555
|
-
};
|
|
3719
|
+
retire(actionId) {
|
|
3720
|
+
for (const { command } of this.journal.entries.values())
|
|
3721
|
+
if (command.action_id === actionId) this.lifetimes.delete(command.command_id);
|
|
3722
|
+
for (const [id, command] of this.queued)
|
|
3723
|
+
if (command.action_id === actionId) {
|
|
3724
|
+
this.queued.delete(id);
|
|
3725
|
+
this.lifetimes.delete(id);
|
|
3726
|
+
}
|
|
2556
3727
|
}
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)))
|
|
2566
|
-
throw new Error(
|
|
2567
|
-
"TSP requires HTTPS (HTTP is allowed only on a loopback host for local tests)"
|
|
2568
|
-
);
|
|
2569
|
-
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash)
|
|
2570
|
-
throw new Error("Use the TSP API origin without a path");
|
|
2571
|
-
return url.origin;
|
|
2572
|
-
}
|
|
2573
|
-
function validSlug(slug) {
|
|
2574
|
-
return slug.length >= 3 && slug.length <= 201 && /^[a-z0-9][a-z0-9_-]*\/[a-z0-9][a-z0-9_.-]*$/.test(slug);
|
|
2575
|
-
}
|
|
2576
|
-
function githubSlug(remote) {
|
|
2577
|
-
const match = /^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([^\s?#]+?)\/?$/.exec(
|
|
2578
|
-
remote.trim()
|
|
2579
|
-
);
|
|
2580
|
-
const slug = match?.[1]?.replace(/\.git$/, "").toLowerCase();
|
|
2581
|
-
return slug && validSlug(slug) ? slug : null;
|
|
2582
|
-
}
|
|
2583
|
-
async function registerFolder(folder, env = process.env) {
|
|
2584
|
-
const absolute = await realpath4(folder);
|
|
2585
|
-
const remotes = await execute("git", ["remote"], env, absolute);
|
|
2586
|
-
if (remotes.code !== 0) throw new Error("Folder is not a Git repository");
|
|
2587
|
-
const names = remotes.stdout.trim().split(/\r?\n/).filter(Boolean).sort((a, b) => Number(b === "origin") - Number(a === "origin"));
|
|
2588
|
-
for (const name of names) {
|
|
2589
|
-
const remote = await execute("git", ["remote", "get-url", name], env, absolute);
|
|
2590
|
-
const slug = remote.code === 0 ? githubSlug(remote.stdout) : null;
|
|
2591
|
-
if (slug) return { slug, folder: absolute };
|
|
3728
|
+
/** Withdraws every unfinished launch or resume of the Stop's action received before it. */
|
|
3729
|
+
withdrawStarts(stop) {
|
|
3730
|
+
for (const [id, lifetime] of this.lifetimes) {
|
|
3731
|
+
const entry = this.journal.entries.get(id);
|
|
3732
|
+
const command = entry?.command ?? this.queued.get(id);
|
|
3733
|
+
if (command && command.kind !== "stop" && command.action_id === stop.action_id && !entry?.receipt)
|
|
3734
|
+
lifetime.withdraw(command);
|
|
3735
|
+
}
|
|
2592
3736
|
}
|
|
2593
|
-
|
|
2594
|
-
}
|
|
3737
|
+
};
|
|
2595
3738
|
|
|
2596
3739
|
// src/journal.ts
|
|
2597
3740
|
import { createHash } from "node:crypto";
|
|
2598
|
-
import { open as
|
|
2599
|
-
import { dirname as
|
|
3741
|
+
import { open as open6, readFile as readFile3, truncate } from "node:fs/promises";
|
|
3742
|
+
import { dirname as dirname4 } from "node:path";
|
|
2600
3743
|
|
|
2601
3744
|
// src/journal-codec.ts
|
|
2602
3745
|
function object(value) {
|
|
@@ -2643,7 +3786,7 @@ function readCommand(value) {
|
|
|
2643
3786
|
};
|
|
2644
3787
|
}
|
|
2645
3788
|
case "stop":
|
|
2646
|
-
return { ...identity2, kind: "stop", session_ref:
|
|
3789
|
+
return { ...identity2, kind: "stop", session_ref: nullable(field(row, "session_ref")) };
|
|
2647
3790
|
case "resume":
|
|
2648
3791
|
return {
|
|
2649
3792
|
...identity2,
|
|
@@ -2694,6 +3837,7 @@ function readObservation(value, command) {
|
|
|
2694
3837
|
session_ref: string(field(row, "session_ref")),
|
|
2695
3838
|
state: member2(field(row, "state"), Object.values(AGENT_SESSION_STATE)),
|
|
2696
3839
|
waiting_for: nullable(field(row, "waiting_for")),
|
|
3840
|
+
last_message: nullable(field(row, "last_message")),
|
|
2697
3841
|
attach_hint: readAttachHint(field(row, "attach_hint")),
|
|
2698
3842
|
resumed_as: nullable(field(row, "resumed_as"))
|
|
2699
3843
|
};
|
|
@@ -2741,6 +3885,7 @@ function storeJournalEntry(entry) {
|
|
|
2741
3885
|
session_ref: update.session_ref,
|
|
2742
3886
|
state: update.state,
|
|
2743
3887
|
waiting_for: update.waiting_for ?? null,
|
|
3888
|
+
last_message: update.last_message ?? null,
|
|
2744
3889
|
attach_hint: update.attach_hint ?? null,
|
|
2745
3890
|
resumed_as: update.resumed_as ?? null
|
|
2746
3891
|
},
|
|
@@ -2773,10 +3918,10 @@ var Journal = class {
|
|
|
2773
3918
|
unreadableCommandIds = /* @__PURE__ */ new Set();
|
|
2774
3919
|
unreadableRows = [];
|
|
2775
3920
|
async load() {
|
|
2776
|
-
await privateDirectory(
|
|
3921
|
+
await privateDirectory(dirname4(this.path));
|
|
2777
3922
|
let bytes;
|
|
2778
3923
|
try {
|
|
2779
|
-
bytes = await
|
|
3924
|
+
bytes = await readFile3(this.path);
|
|
2780
3925
|
} catch (error) {
|
|
2781
3926
|
if (isObject(error) && field(error, "code") === "ENOENT") return;
|
|
2782
3927
|
throw error;
|
|
@@ -2817,7 +3962,7 @@ var Journal = class {
|
|
|
2817
3962
|
}
|
|
2818
3963
|
}
|
|
2819
3964
|
async append(entry) {
|
|
2820
|
-
const handle = await
|
|
3965
|
+
const handle = await open6(this.path, "a", 384);
|
|
2821
3966
|
try {
|
|
2822
3967
|
await handle.chmod(384);
|
|
2823
3968
|
await handle.writeFile(JSON.stringify(storeJournalEntry(entry)) + "\n");
|
|
@@ -2830,18 +3975,50 @@ var Journal = class {
|
|
|
2830
3975
|
};
|
|
2831
3976
|
|
|
2832
3977
|
// src/session-control.ts
|
|
2833
|
-
import { setTimeout as
|
|
2834
|
-
|
|
3978
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
3979
|
+
var STOP_POLL_MS = 200;
|
|
3980
|
+
var STOP_REISSUE_MS = 1e3;
|
|
3981
|
+
function running(state) {
|
|
3982
|
+
return state === "working" || state === "needs_input";
|
|
3983
|
+
}
|
|
3984
|
+
async function stopUntilSettled(driver, session, folder, requireLive, settleMs) {
|
|
2835
3985
|
const deadline = performance.now() + settleMs;
|
|
3986
|
+
const promptDueBy = session.startPromptDueBy ?? 0;
|
|
3987
|
+
let reissueAt = performance.now() + STOP_REISSUE_MS;
|
|
3988
|
+
if (session.state !== "stopped") {
|
|
3989
|
+
requireLive();
|
|
3990
|
+
await driver.stop(session, folder, requireLive);
|
|
3991
|
+
}
|
|
2836
3992
|
for (; ; ) {
|
|
2837
|
-
const row = (await driver.list(folder, void 0, { refs: [id] })).find(
|
|
2838
|
-
(candidate) => candidate.id === id
|
|
3993
|
+
const row = (await driver.list(folder, void 0, { refs: [session.id] })).find(
|
|
3994
|
+
(candidate) => candidate.id === session.id
|
|
2839
3995
|
);
|
|
2840
|
-
if (row && row.state
|
|
2841
|
-
|
|
2842
|
-
|
|
3996
|
+
if (row && !running(row.state)) {
|
|
3997
|
+
if (Date.now() >= promptDueBy || performance.now() >= deadline) return row.state;
|
|
3998
|
+
await delay3(STOP_POLL_MS);
|
|
3999
|
+
continue;
|
|
4000
|
+
}
|
|
4001
|
+
if (performance.now() >= deadline) {
|
|
4002
|
+
if (row) throw new HarnessRefusal("stop_failed");
|
|
4003
|
+
return "unknown";
|
|
4004
|
+
}
|
|
4005
|
+
if (row && performance.now() >= reissueAt) {
|
|
4006
|
+
reissueAt = performance.now() + STOP_REISSUE_MS;
|
|
4007
|
+
requireLive();
|
|
4008
|
+
await driver.stop(row, folder, requireLive).catch(() => void 0);
|
|
4009
|
+
}
|
|
4010
|
+
await delay3(STOP_POLL_MS);
|
|
2843
4011
|
}
|
|
2844
4012
|
}
|
|
4013
|
+
function stopUnstarted(journal, command) {
|
|
4014
|
+
const launches = [...journal.entries.values()].filter(
|
|
4015
|
+
(entry) => entry.command.action_id === command.action_id && entry.command.kind === "launch"
|
|
4016
|
+
);
|
|
4017
|
+
if (launches.length === 0) throw new HarnessRefusal("session_not_found");
|
|
4018
|
+
if (launches.some((entry) => entry.receipt === null))
|
|
4019
|
+
throw new Error("The launch this Stop withdrew is still settling");
|
|
4020
|
+
return { update: null, conversationId: null };
|
|
4021
|
+
}
|
|
2845
4022
|
async function findSession(driver, ref, folder, requireLive) {
|
|
2846
4023
|
const session = (await driver.list(folder, requireLive, { refs: [ref] })).find(
|
|
2847
4024
|
(row) => row.id === ref
|
|
@@ -2887,7 +4064,7 @@ async function launchSession(journal, request) {
|
|
|
2887
4064
|
}
|
|
2888
4065
|
if (session) return { ref: session.id, session };
|
|
2889
4066
|
if (retry && !driver.reconcileLaunch) throw new HarnessRefusal("start_uncertain");
|
|
2890
|
-
requireLive();
|
|
4067
|
+
promptCheck(requireLive)();
|
|
2891
4068
|
const ref = await driver.start(command, folder, requireLive, checkpoint);
|
|
2892
4069
|
return { ref };
|
|
2893
4070
|
}
|
|
@@ -2907,7 +4084,7 @@ async function resumeSession(journal, request) {
|
|
|
2907
4084
|
intent.observedRefs = await driver.resumeRecovery.observe(session, folder);
|
|
2908
4085
|
intent.conversationId = session.conversationId;
|
|
2909
4086
|
await journal.append(intent);
|
|
2910
|
-
requireLive();
|
|
4087
|
+
promptCheck(requireLive)();
|
|
2911
4088
|
return driver.resume(session, command.text ?? null, folder, requireLive);
|
|
2912
4089
|
}
|
|
2913
4090
|
const sessions = await driver.list(folder);
|
|
@@ -2921,7 +4098,7 @@ async function resumeSession(journal, request) {
|
|
|
2921
4098
|
}
|
|
2922
4099
|
intent.observedRefs = sessions.filter((row) => row.conversationId === session.conversationId).map((row) => row.id);
|
|
2923
4100
|
await journal.append({ ...intent, conversationId: session.conversationId });
|
|
2924
|
-
requireLive();
|
|
4101
|
+
promptCheck(requireLive)();
|
|
2925
4102
|
return await driver.resume(session, command.text ?? null, folder, requireLive);
|
|
2926
4103
|
}
|
|
2927
4104
|
async function observeSessions(drivers, contexts, activity = false) {
|
|
@@ -2981,32 +4158,20 @@ var Commands = class {
|
|
|
2981
4158
|
constructor(journal, drivers, repositories, options = {}) {
|
|
2982
4159
|
this.journal = journal;
|
|
2983
4160
|
this.drivers = drivers;
|
|
2984
|
-
this.repositories = repositories;
|
|
2985
|
-
this.stopSettleMs = options.stopSettleMs ??
|
|
2986
|
-
this.
|
|
2987
|
-
this.
|
|
2988
|
-
for (const entry of journal.entries.values())
|
|
2989
|
-
this.remember(entry);
|
|
2990
|
-
this.lifetimes.set(
|
|
2991
|
-
entry.command.command_id,
|
|
2992
|
-
new CommandLifetime(entry.command.ttl_ms, this.clock, entry.lifetime)
|
|
2993
|
-
);
|
|
2994
|
-
}
|
|
4161
|
+
this.repositories = repositories;
|
|
4162
|
+
this.stopSettleMs = options.stopSettleMs ?? 1e4;
|
|
4163
|
+
this.activity = options.activity ?? new ActivityReporter();
|
|
4164
|
+
this.lifetimes = new CommandLifetimes(journal, options.clock ?? lifetimeClock);
|
|
4165
|
+
for (const entry of journal.entries.values()) this.remember(entry);
|
|
2995
4166
|
}
|
|
2996
4167
|
stopSettleMs;
|
|
2997
|
-
clock;
|
|
2998
4168
|
activity;
|
|
2999
4169
|
bindings = /* @__PURE__ */ new Map();
|
|
3000
|
-
lifetimes
|
|
4170
|
+
lifetimes;
|
|
3001
4171
|
resolutions = /* @__PURE__ */ new Map();
|
|
3002
|
-
/** Called at socket receipt, before joining the serial work queue. */
|
|
4172
|
+
/** Called at socket receipt, before joining the serial work queue. A Stop withdraws its action's start at once. */
|
|
3003
4173
|
receive(command) {
|
|
3004
|
-
|
|
3005
|
-
if (!lifetime) {
|
|
3006
|
-
lifetime = new CommandLifetime(command.ttl_ms, this.clock);
|
|
3007
|
-
this.lifetimes.set(command.command_id, lifetime);
|
|
3008
|
-
}
|
|
3009
|
-
return lifetime;
|
|
4174
|
+
return this.lifetimes.receive(command);
|
|
3010
4175
|
}
|
|
3011
4176
|
remember(entry) {
|
|
3012
4177
|
const { command, update } = entry;
|
|
@@ -3030,6 +4195,7 @@ var Commands = class {
|
|
|
3030
4195
|
session_ref: ref,
|
|
3031
4196
|
state,
|
|
3032
4197
|
waiting_for: null,
|
|
4198
|
+
last_message: null,
|
|
3033
4199
|
attach_hint: this.drivers.get(harness).attachHint(resumedAs ?? ref),
|
|
3034
4200
|
resumed_as: resumedAs ?? null
|
|
3035
4201
|
};
|
|
@@ -3063,19 +4229,14 @@ var Commands = class {
|
|
|
3063
4229
|
await this.journal.append(intent);
|
|
3064
4230
|
let update = null, conversationId = intent.conversationId;
|
|
3065
4231
|
let receipt;
|
|
4232
|
+
this.lifetimes.dequeued(command.command_id);
|
|
3066
4233
|
try {
|
|
3067
|
-
|
|
4234
|
+
const retry = Boolean(previous) || this.hasUncertainLaunch(command);
|
|
4235
|
+
if (retry) lifetime.uncertainStart();
|
|
4236
|
+
else lifetime.requireLive(command);
|
|
3068
4237
|
if (this.journal.unreadableCommandIds.has(command.command_id))
|
|
3069
4238
|
throw unreadableCommandRefusal(command);
|
|
3070
|
-
const result = command.kind === "launch" ? await this.launch(
|
|
3071
|
-
intent,
|
|
3072
|
-
Boolean(previous),
|
|
3073
|
-
() => lifetime.requireLive(command)
|
|
3074
|
-
) : await this.control(
|
|
3075
|
-
intent,
|
|
3076
|
-
Boolean(previous),
|
|
3077
|
-
() => lifetime.requireLive(command)
|
|
3078
|
-
);
|
|
4239
|
+
const result = command.kind === "launch" ? await this.launch(intent, retry, lifetime) : await this.control(intent, retry, lifetime);
|
|
3079
4240
|
update = result.update;
|
|
3080
4241
|
conversationId = result.conversationId;
|
|
3081
4242
|
receipt = {
|
|
@@ -3146,6 +4307,7 @@ var Commands = class {
|
|
|
3146
4307
|
return this.emit(entry.receipt, update);
|
|
3147
4308
|
}
|
|
3148
4309
|
hasUncertainLaunch(command) {
|
|
4310
|
+
if (command.kind !== "launch") return false;
|
|
3149
4311
|
const earlier = [...this.journal.entries.values()].filter(
|
|
3150
4312
|
(entry) => entry.command.action_id === command.action_id && entry.command.command_id !== command.command_id && entry.command.kind === "launch"
|
|
3151
4313
|
);
|
|
@@ -3155,13 +4317,13 @@ var Commands = class {
|
|
|
3155
4317
|
}
|
|
3156
4318
|
return earlier.some((entry) => entry.receipt === null);
|
|
3157
4319
|
}
|
|
3158
|
-
async launch(intent, retry,
|
|
4320
|
+
async launch(intent, retry, lifetime) {
|
|
3159
4321
|
const command = intent.command;
|
|
3160
4322
|
if (command.kind !== "launch") throw new HarnessRefusal("unsupported_command");
|
|
4323
|
+
const requireLive = lifetime.check(command);
|
|
3161
4324
|
const folder = (await this.repositories())[command.repository.toLowerCase()];
|
|
3162
4325
|
if (!folder) throw new HarnessRefusal("repository_not_registered");
|
|
3163
|
-
const driver = await this.drivers.ready(command.harness, folder);
|
|
3164
|
-
retry ||= this.hasUncertainLaunch(command);
|
|
4326
|
+
const driver = await lifetime.unlessWithdrawn(this.drivers.ready(command.harness, folder));
|
|
3165
4327
|
const known = this.bindings.get(command.action_id);
|
|
3166
4328
|
if (known && (known.repository !== command.repository.toLowerCase() || known.harness !== command.harness))
|
|
3167
4329
|
throw new Error("Action identity conflict");
|
|
@@ -3182,32 +4344,30 @@ var Commands = class {
|
|
|
3182
4344
|
update.waiting_for = session?.waitingFor ?? null;
|
|
3183
4345
|
return { update, conversationId: session?.conversationId ?? null };
|
|
3184
4346
|
}
|
|
3185
|
-
async control(intent, retry,
|
|
4347
|
+
async control(intent, retry, lifetime) {
|
|
3186
4348
|
const command = intent.command;
|
|
3187
4349
|
if (command.kind !== "stop" && command.kind !== "resume")
|
|
3188
4350
|
throw new HarnessRefusal("unsupported_command");
|
|
4351
|
+
const requireLive = lifetime.check(command);
|
|
3189
4352
|
const binding = this.bindings.get(command.action_id);
|
|
3190
|
-
if (
|
|
4353
|
+
if (command.kind === "stop" && !command.session_ref && !binding)
|
|
4354
|
+
return stopUnstarted(this.journal, command);
|
|
4355
|
+
if (!binding || (command.session_ref ?? binding.ref) !== binding.ref)
|
|
3191
4356
|
throw new HarnessRefusal("session_not_found");
|
|
3192
4357
|
const folder = (await this.repositories())[binding.repository];
|
|
3193
4358
|
if (!folder) throw new HarnessRefusal("repository_not_registered");
|
|
3194
4359
|
const driver = this.drivers.get(binding.harness);
|
|
3195
4360
|
const session = await findSession(driver, binding.ref, folder, requireLive);
|
|
3196
|
-
if (command.kind === "stop")
|
|
3197
|
-
if (session.state !== "stopped") {
|
|
3198
|
-
requireLive();
|
|
3199
|
-
await driver.stop(session, folder, requireLive);
|
|
3200
|
-
}
|
|
4361
|
+
if (command.kind === "stop")
|
|
3201
4362
|
return {
|
|
3202
4363
|
update: this.update(
|
|
3203
4364
|
binding.harness,
|
|
3204
4365
|
command.action_id,
|
|
3205
4366
|
session.id,
|
|
3206
|
-
await
|
|
4367
|
+
await stopUntilSettled(driver, session, folder, requireLive, this.stopSettleMs)
|
|
3207
4368
|
),
|
|
3208
4369
|
conversationId: session.conversationId
|
|
3209
4370
|
};
|
|
3210
|
-
}
|
|
3211
4371
|
const ref = await resumeSession(this.journal, {
|
|
3212
4372
|
driver,
|
|
3213
4373
|
intent,
|
|
@@ -3239,10 +4399,9 @@ var Commands = class {
|
|
|
3239
4399
|
}
|
|
3240
4400
|
async retire(actionId) {
|
|
3241
4401
|
for (const entry of this.journal.entries.values())
|
|
3242
|
-
if (entry.command.action_id === actionId)
|
|
3243
|
-
this.lifetimes.delete(entry.command.command_id);
|
|
4402
|
+
if (entry.command.action_id === actionId)
|
|
3244
4403
|
this.resolutions.delete(entry.command.command_id);
|
|
3245
|
-
|
|
4404
|
+
this.lifetimes.retire(actionId);
|
|
3246
4405
|
await this.journal.retire(actionId);
|
|
3247
4406
|
this.bindings.delete(actionId);
|
|
3248
4407
|
this.activity.release(actionId);
|
|
@@ -3297,6 +4456,7 @@ var Commands = class {
|
|
|
3297
4456
|
if (state === null) continue;
|
|
3298
4457
|
const update = this.update(binding.harness, action, binding.ref, state);
|
|
3299
4458
|
update.waiting_for = row?.waitingFor ?? null;
|
|
4459
|
+
update.last_message = row?.lastMessage ?? null;
|
|
3300
4460
|
binding.state = update.state;
|
|
3301
4461
|
const frame = this.activity.frame(update, row?.activity ?? null, activity);
|
|
3302
4462
|
if (frame) updates.push(frame);
|
|
@@ -3307,7 +4467,7 @@ var Commands = class {
|
|
|
3307
4467
|
|
|
3308
4468
|
// src/config-watch.ts
|
|
3309
4469
|
import { statSync, watch } from "node:fs";
|
|
3310
|
-
import { basename as basename4, dirname as
|
|
4470
|
+
import { basename as basename4, dirname as dirname5 } from "node:path";
|
|
3311
4471
|
var watchDirectory = (directory, listener) => watch(directory, (_, filename) => listener(filename));
|
|
3312
4472
|
function watchConfig(path, changed, options = {}) {
|
|
3313
4473
|
let reported = identity(path);
|
|
@@ -3328,7 +4488,7 @@ function watchConfig(path, changed, options = {}) {
|
|
|
3328
4488
|
if (pending === void 0 && identity(path) !== reported) settle();
|
|
3329
4489
|
}, options.pollMs ?? 1e3);
|
|
3330
4490
|
try {
|
|
3331
|
-
watcher = (options.watchDirectory ?? watchDirectory)(
|
|
4491
|
+
watcher = (options.watchDirectory ?? watchDirectory)(dirname5(path), (filename) => {
|
|
3332
4492
|
if (filename === null || filename === basename4(path)) settle();
|
|
3333
4493
|
});
|
|
3334
4494
|
watcher.on("error", () => watcher?.close());
|
|
@@ -3355,9 +4515,9 @@ var LaunchPermits = class {
|
|
|
3355
4515
|
}
|
|
3356
4516
|
pending = null;
|
|
3357
4517
|
accept(command, remainingMs) {
|
|
3358
|
-
return new Promise((
|
|
4518
|
+
return new Promise((resolve7) => {
|
|
3359
4519
|
if (!this.active() || remainingMs <= 0) {
|
|
3360
|
-
|
|
4520
|
+
resolve7(false);
|
|
3361
4521
|
return;
|
|
3362
4522
|
}
|
|
3363
4523
|
const timer = setTimeout(
|
|
@@ -3373,7 +4533,7 @@ var LaunchPermits = class {
|
|
|
3373
4533
|
resolve: (decision) => {
|
|
3374
4534
|
clearTimeout(timer);
|
|
3375
4535
|
this.pending = null;
|
|
3376
|
-
|
|
4536
|
+
resolve7(decision === true ? this.active() : decision);
|
|
3377
4537
|
}
|
|
3378
4538
|
};
|
|
3379
4539
|
this.send({
|
|
@@ -3395,6 +4555,268 @@ var LaunchPermits = class {
|
|
|
3395
4555
|
}
|
|
3396
4556
|
};
|
|
3397
4557
|
|
|
4558
|
+
// src/hub-connection.ts
|
|
4559
|
+
var STABLE_CONNECTION_MS = 3e4;
|
|
4560
|
+
var HANDOVER_MS = 2e3;
|
|
4561
|
+
var REFRESH_LEAD_MS = 15e3;
|
|
4562
|
+
function authenticatedSocket(pairing, token) {
|
|
4563
|
+
const url = new URL(pairing.hub_path, pairing.origin);
|
|
4564
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4565
|
+
const NodeWebSocket = WebSocket;
|
|
4566
|
+
return new NodeWebSocket(url, { headers: { Authorization: `Bearer ${token}` } });
|
|
4567
|
+
}
|
|
4568
|
+
function sessionPolling(options, enqueue, send, isReady, pending) {
|
|
4569
|
+
let polling = false;
|
|
4570
|
+
let pollTimer;
|
|
4571
|
+
const schedulePoll = () => {
|
|
4572
|
+
if (!isReady()) return;
|
|
4573
|
+
pollTimer = setTimeout(
|
|
4574
|
+
() => {
|
|
4575
|
+
pollTimer = void 0;
|
|
4576
|
+
enqueue(async () => {
|
|
4577
|
+
if (pollTimer === void 0) await poll();
|
|
4578
|
+
});
|
|
4579
|
+
},
|
|
4580
|
+
options.commands.hasLiveBindings || pending.exists() ? options.pollMs ?? 2e3 : options.idlePollMs ?? 3e4
|
|
4581
|
+
);
|
|
4582
|
+
};
|
|
4583
|
+
const poll = async () => {
|
|
4584
|
+
if (!isReady() || polling) return;
|
|
4585
|
+
clearTimeout(pollTimer);
|
|
4586
|
+
pollTimer = void 0;
|
|
4587
|
+
polling = true;
|
|
4588
|
+
try {
|
|
4589
|
+
await pending.retry();
|
|
4590
|
+
for (const update of await options.commands.poll()) send(update);
|
|
4591
|
+
} finally {
|
|
4592
|
+
polling = false;
|
|
4593
|
+
schedulePoll();
|
|
4594
|
+
}
|
|
4595
|
+
};
|
|
4596
|
+
return { poll, stop: () => clearTimeout(pollTimer) };
|
|
4597
|
+
}
|
|
4598
|
+
function transportSender(socket, isActive) {
|
|
4599
|
+
return (message) => {
|
|
4600
|
+
if (!isActive() || socket.readyState !== WebSocket.OPEN) return;
|
|
4601
|
+
try {
|
|
4602
|
+
socket.send(JSON.stringify(message));
|
|
4603
|
+
} catch {
|
|
4604
|
+
socket.close(4001, "Transport send failed");
|
|
4605
|
+
}
|
|
4606
|
+
};
|
|
4607
|
+
}
|
|
4608
|
+
function commandProcessor(commands, permits, retries, send) {
|
|
4609
|
+
return async (command) => {
|
|
4610
|
+
if (!retries.ready(command.command_id)) return;
|
|
4611
|
+
let results;
|
|
4612
|
+
try {
|
|
4613
|
+
results = await commands.process(
|
|
4614
|
+
command,
|
|
4615
|
+
(operation, remainingMs) => permits.accept(operation, remainingMs)
|
|
4616
|
+
);
|
|
4617
|
+
} catch {
|
|
4618
|
+
console.error(
|
|
4619
|
+
`TSP gateway command pending: kind=${command.kind} command_id=${command.command_id} action_id=${command.action_id}`
|
|
4620
|
+
);
|
|
4621
|
+
return;
|
|
4622
|
+
} finally {
|
|
4623
|
+
retries.defer(command);
|
|
4624
|
+
}
|
|
4625
|
+
for (const result of results) send(result);
|
|
4626
|
+
};
|
|
4627
|
+
}
|
|
4628
|
+
function machineFacts(options, send, enqueue, state) {
|
|
4629
|
+
let lastAdvertisement;
|
|
4630
|
+
const advertise = async (kind) => {
|
|
4631
|
+
const advertisement = {
|
|
4632
|
+
protocol_version: GATEWAY_PROTOCOL_VERSION,
|
|
4633
|
+
gateway_version: options.version,
|
|
4634
|
+
harnesses: await options.drivers.detect(),
|
|
4635
|
+
repositories: await options.repositories()
|
|
4636
|
+
};
|
|
4637
|
+
const encoded = JSON.stringify(advertisement);
|
|
4638
|
+
if (kind === "hello" || encoded !== lastAdvertisement) {
|
|
4639
|
+
send({ ...advertisement, protocol_version: GATEWAY_PROTOCOL_VERSION, kind });
|
|
4640
|
+
lastAdvertisement = encoded;
|
|
4641
|
+
}
|
|
4642
|
+
};
|
|
4643
|
+
let refreshing = false;
|
|
4644
|
+
let refreshPending = false;
|
|
4645
|
+
const refresh = () => {
|
|
4646
|
+
if (!state.ready()) return;
|
|
4647
|
+
refreshPending = true;
|
|
4648
|
+
if (refreshing) return;
|
|
4649
|
+
refreshing = true;
|
|
4650
|
+
enqueue(async () => {
|
|
4651
|
+
try {
|
|
4652
|
+
refreshPending = false;
|
|
4653
|
+
await advertise("advertise");
|
|
4654
|
+
} finally {
|
|
4655
|
+
refreshing = false;
|
|
4656
|
+
if (refreshPending && state.live()) refresh();
|
|
4657
|
+
}
|
|
4658
|
+
});
|
|
4659
|
+
};
|
|
4660
|
+
return { advertise, refresh };
|
|
4661
|
+
}
|
|
4662
|
+
function openConnection(options, setup) {
|
|
4663
|
+
const socket = authenticatedSocket(options.pairing, setup.credential.token);
|
|
4664
|
+
let isOpen = true;
|
|
4665
|
+
let markRefreshDue = () => {
|
|
4666
|
+
};
|
|
4667
|
+
const refreshDue = new Promise((resolve7) => {
|
|
4668
|
+
markRefreshDue = resolve7;
|
|
4669
|
+
});
|
|
4670
|
+
const closed = serve(options, socket, setup, markRefreshDue);
|
|
4671
|
+
void closed.finally(() => {
|
|
4672
|
+
isOpen = false;
|
|
4673
|
+
});
|
|
4674
|
+
return {
|
|
4675
|
+
closed,
|
|
4676
|
+
refreshDue,
|
|
4677
|
+
open: () => isOpen,
|
|
4678
|
+
handOver: async () => {
|
|
4679
|
+
const handover = setTimeout(
|
|
4680
|
+
() => socket.close(4e3, "Refresh access token"),
|
|
4681
|
+
HANDOVER_MS
|
|
4682
|
+
);
|
|
4683
|
+
try {
|
|
4684
|
+
await closed;
|
|
4685
|
+
} finally {
|
|
4686
|
+
clearTimeout(handover);
|
|
4687
|
+
}
|
|
4688
|
+
},
|
|
4689
|
+
retire: async () => {
|
|
4690
|
+
socket.close(4e3, "Refresh access token");
|
|
4691
|
+
await closed;
|
|
4692
|
+
}
|
|
4693
|
+
};
|
|
4694
|
+
}
|
|
4695
|
+
async function serve(options, socket, setup, refreshDue) {
|
|
4696
|
+
const { retries, status, predecessor } = setup;
|
|
4697
|
+
let active = true, ready = false;
|
|
4698
|
+
const now = options.now ?? (() => performance.now());
|
|
4699
|
+
let readyAt = null;
|
|
4700
|
+
let stable = false;
|
|
4701
|
+
let receivedFrame = false;
|
|
4702
|
+
let queue = Promise.resolve();
|
|
4703
|
+
const send = transportSender(socket, () => active);
|
|
4704
|
+
const permits = new LaunchPermits(
|
|
4705
|
+
send,
|
|
4706
|
+
() => active && !options.signal.aborted,
|
|
4707
|
+
() => socket.close(4001, "Acceptance timeout")
|
|
4708
|
+
);
|
|
4709
|
+
const enqueue = (task) => {
|
|
4710
|
+
queue = queue.then(async () => {
|
|
4711
|
+
if (active && !options.signal.aborted) await task();
|
|
4712
|
+
}).catch(() => {
|
|
4713
|
+
console.error("TSP gateway local queue task failed.");
|
|
4714
|
+
});
|
|
4715
|
+
};
|
|
4716
|
+
const processCommand = commandProcessor(options.commands, permits, retries, send);
|
|
4717
|
+
const { advertise, refresh } = machineFacts(options, send, enqueue, {
|
|
4718
|
+
ready: () => ready,
|
|
4719
|
+
live: () => active && !options.signal.aborted
|
|
4720
|
+
});
|
|
4721
|
+
const factsInterval = setInterval(refresh, options.advertiseMs ?? 3e4);
|
|
4722
|
+
const unwatch = options.watchFacts?.(refresh);
|
|
4723
|
+
const polling = sessionPolling(
|
|
4724
|
+
options,
|
|
4725
|
+
enqueue,
|
|
4726
|
+
send,
|
|
4727
|
+
() => ready && active && !options.signal.aborted,
|
|
4728
|
+
{
|
|
4729
|
+
retry: () => retries.retryPending(processCommand, () => active && !options.signal.aborted),
|
|
4730
|
+
exists: () => retries.hasPending
|
|
4731
|
+
}
|
|
4732
|
+
);
|
|
4733
|
+
const expiry = setTimeout(
|
|
4734
|
+
refreshDue,
|
|
4735
|
+
Math.max(100, setup.credential.expiresAt - Date.now() - REFRESH_LEAD_MS)
|
|
4736
|
+
);
|
|
4737
|
+
const timeout = setTimeout(() => socket.close(4001, "Connection timeout"), 2e4);
|
|
4738
|
+
const abort = () => {
|
|
4739
|
+
active = false;
|
|
4740
|
+
permits.cancel();
|
|
4741
|
+
socket.close(1e3, "Gateway stopped");
|
|
4742
|
+
};
|
|
4743
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
4744
|
+
if (options.signal.aborted) abort();
|
|
4745
|
+
socket.addEventListener("open", () => {
|
|
4746
|
+
enqueue(async () => {
|
|
4747
|
+
await advertise("hello");
|
|
4748
|
+
clearTimeout(timeout);
|
|
4749
|
+
for (const receipt of options.commands.durableReceipts()) send(receipt);
|
|
4750
|
+
await predecessor?.handOver();
|
|
4751
|
+
options.commands.resetObservations();
|
|
4752
|
+
ready = true;
|
|
4753
|
+
readyAt = now();
|
|
4754
|
+
await polling.poll();
|
|
4755
|
+
await status(true, "Connected");
|
|
4756
|
+
});
|
|
4757
|
+
});
|
|
4758
|
+
socket.addEventListener("message", (event) => {
|
|
4759
|
+
if (!active || options.signal.aborted) return;
|
|
4760
|
+
let message;
|
|
4761
|
+
try {
|
|
4762
|
+
message = decodeHubText(event.data);
|
|
4763
|
+
} catch {
|
|
4764
|
+
socket.close(4002, "Invalid frame");
|
|
4765
|
+
return;
|
|
4766
|
+
}
|
|
4767
|
+
receivedFrame = true;
|
|
4768
|
+
if (message.kind === "ping") {
|
|
4769
|
+
send({
|
|
4770
|
+
kind: "pong",
|
|
4771
|
+
protocol_version: GATEWAY_PROTOCOL_VERSION,
|
|
4772
|
+
nonce: message.nonce
|
|
4773
|
+
});
|
|
4774
|
+
return;
|
|
4775
|
+
}
|
|
4776
|
+
if (message.kind === "permit" || message.kind === "retire") {
|
|
4777
|
+
permits.receive(message);
|
|
4778
|
+
if (message.kind === "permit") {
|
|
4779
|
+
const receipt = message.receipt;
|
|
4780
|
+
if (receipt)
|
|
4781
|
+
enqueue(async () => {
|
|
4782
|
+
await options.commands.reconcile(receipt);
|
|
4783
|
+
});
|
|
4784
|
+
return;
|
|
4785
|
+
}
|
|
4786
|
+
}
|
|
4787
|
+
if (message.kind !== "retire") options.commands.receive(message);
|
|
4788
|
+
enqueue(async () => {
|
|
4789
|
+
if (message.kind === "retire") {
|
|
4790
|
+
retries.retire(message.action_id);
|
|
4791
|
+
await options.commands.retire(message.action_id);
|
|
4792
|
+
} else await processCommand(message);
|
|
4793
|
+
await polling.poll();
|
|
4794
|
+
await advertise("advertise");
|
|
4795
|
+
});
|
|
4796
|
+
});
|
|
4797
|
+
socket.addEventListener("error", () => void 0);
|
|
4798
|
+
const code = await new Promise(
|
|
4799
|
+
(resolve7) => socket.addEventListener(
|
|
4800
|
+
"close",
|
|
4801
|
+
(event) => {
|
|
4802
|
+
stable = readyAt !== null && now() - readyAt >= STABLE_CONNECTION_MS;
|
|
4803
|
+
active = false;
|
|
4804
|
+
permits.cancel();
|
|
4805
|
+
resolve7(event.code);
|
|
4806
|
+
},
|
|
4807
|
+
{ once: true }
|
|
4808
|
+
)
|
|
4809
|
+
);
|
|
4810
|
+
polling.stop();
|
|
4811
|
+
clearInterval(factsInterval);
|
|
4812
|
+
unwatch?.();
|
|
4813
|
+
clearTimeout(expiry);
|
|
4814
|
+
clearTimeout(timeout);
|
|
4815
|
+
options.signal.removeEventListener("abort", abort);
|
|
4816
|
+
await queue;
|
|
4817
|
+
return { code, stable, receivedFrame };
|
|
4818
|
+
}
|
|
4819
|
+
|
|
3398
4820
|
// src/oauth.ts
|
|
3399
4821
|
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
3400
4822
|
import { createServer } from "node:http";
|
|
@@ -3485,8 +4907,8 @@ async function pair(origin, store, openBrowser, report = () => {
|
|
|
3485
4907
|
};
|
|
3486
4908
|
let rejectCode = () => {
|
|
3487
4909
|
};
|
|
3488
|
-
const code = new Promise((
|
|
3489
|
-
acceptCode =
|
|
4910
|
+
const code = new Promise((resolve7, reject) => {
|
|
4911
|
+
acceptCode = resolve7;
|
|
3490
4912
|
rejectCode = reject;
|
|
3491
4913
|
});
|
|
3492
4914
|
void code.catch(() => {
|
|
@@ -3506,9 +4928,9 @@ async function pair(origin, store, openBrowser, report = () => {
|
|
|
3506
4928
|
response.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }).end("TSP gateway authorized. You can close this tab.");
|
|
3507
4929
|
acceptCode(authorizationCode);
|
|
3508
4930
|
});
|
|
3509
|
-
await new Promise((
|
|
4931
|
+
await new Promise((resolve7, reject) => {
|
|
3510
4932
|
server.once("error", reject);
|
|
3511
|
-
server.listen(0, "127.0.0.1",
|
|
4933
|
+
server.listen(0, "127.0.0.1", resolve7);
|
|
3512
4934
|
});
|
|
3513
4935
|
const timer = setTimeout(() => rejectCode(new Error("Pairing timed out")), 18e4);
|
|
3514
4936
|
try {
|
|
@@ -3575,7 +4997,7 @@ ${url.href}`);
|
|
|
3575
4997
|
} finally {
|
|
3576
4998
|
clearTimeout(timer);
|
|
3577
4999
|
server.closeAllConnections();
|
|
3578
|
-
await new Promise((
|
|
5000
|
+
await new Promise((resolve7) => server.close(() => resolve7()));
|
|
3579
5001
|
}
|
|
3580
5002
|
}
|
|
3581
5003
|
async function unpair(pairing, store) {
|
|
@@ -3620,7 +5042,7 @@ async function unpair(pairing, store) {
|
|
|
3620
5042
|
}
|
|
3621
5043
|
|
|
3622
5044
|
// src/daemon.ts
|
|
3623
|
-
import { setTimeout as
|
|
5045
|
+
import { setTimeout as delay4 } from "node:timers/promises";
|
|
3624
5046
|
|
|
3625
5047
|
// src/intent-retries.ts
|
|
3626
5048
|
var BASE_INTENT_RETRY_MS = 2e3;
|
|
@@ -3636,11 +5058,11 @@ var IntentRetries = class {
|
|
|
3636
5058
|
retryAt = /* @__PURE__ */ new Map();
|
|
3637
5059
|
unjournaled = /* @__PURE__ */ new Map();
|
|
3638
5060
|
schedule(commandId, attempts) {
|
|
3639
|
-
const
|
|
5061
|
+
const delay5 = Math.min(
|
|
3640
5062
|
MAX_INTENT_RETRY_MS,
|
|
3641
5063
|
BASE_INTENT_RETRY_MS * 2 ** Math.max(0, attempts - 1)
|
|
3642
5064
|
);
|
|
3643
|
-
this.retryAt.set(commandId, this.now() + Math.floor(
|
|
5065
|
+
this.retryAt.set(commandId, this.now() + Math.floor(delay5 * (0.5 + this.random() * 0.5)));
|
|
3644
5066
|
}
|
|
3645
5067
|
get hasPending() {
|
|
3646
5068
|
return this.unjournaled.size > 0 || this.commands.pendingIntents.length > 0;
|
|
@@ -3684,17 +5106,10 @@ var IntentRetries = class {
|
|
|
3684
5106
|
for (const id of this.retryAt.keys()) if (!ids.has(id)) this.retryAt.delete(id);
|
|
3685
5107
|
return commands;
|
|
3686
5108
|
}
|
|
3687
|
-
};
|
|
3688
|
-
|
|
3689
|
-
// src/daemon.ts
|
|
3690
|
-
var
|
|
3691
|
-
var OUTDATED_RETRY_MS = 60 * 60 * 1e3;
|
|
3692
|
-
function authenticatedSocket(pairing, token) {
|
|
3693
|
-
const url = new URL(pairing.hub_path, pairing.origin);
|
|
3694
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3695
|
-
const NodeWebSocket = WebSocket;
|
|
3696
|
-
return new NodeWebSocket(url, { headers: { Authorization: `Bearer ${token}` } });
|
|
3697
|
-
}
|
|
5109
|
+
};
|
|
5110
|
+
|
|
5111
|
+
// src/daemon.ts
|
|
5112
|
+
var OUTDATED_RETRY_MS = 60 * 60 * 1e3;
|
|
3698
5113
|
function reconnectDelay(attempt, random = Math.random) {
|
|
3699
5114
|
return Math.floor(Math.min(3e4, 500 * 2 ** Math.min(attempt, 6)) * (0.5 + random() * 0.5));
|
|
3700
5115
|
}
|
|
@@ -3703,23 +5118,9 @@ function disposition(code) {
|
|
|
3703
5118
|
if (Number(key) === code) return value;
|
|
3704
5119
|
return "reconnectable";
|
|
3705
5120
|
}
|
|
3706
|
-
|
|
3707
|
-
const retries = new IntentRetries(
|
|
3708
|
-
options.commands,
|
|
3709
|
-
options.now ?? (() => performance.now()),
|
|
3710
|
-
options.random ?? Math.random
|
|
3711
|
-
);
|
|
3712
|
-
let attempt = 0, force = false, rejectedToken = false;
|
|
3713
|
-
let closeCode = null;
|
|
3714
|
-
let closeDisposition = null;
|
|
3715
|
-
const status = (connected, message) => options.status({
|
|
3716
|
-
connected,
|
|
3717
|
-
message,
|
|
3718
|
-
close_code: closeCode,
|
|
3719
|
-
close_disposition: closeDisposition
|
|
3720
|
-
});
|
|
5121
|
+
function reconnectState(options) {
|
|
3721
5122
|
const wait = options.wait ?? (async (ms, signal) => {
|
|
3722
|
-
await
|
|
5123
|
+
await delay4(ms, void 0, { signal });
|
|
3723
5124
|
});
|
|
3724
5125
|
const pause = async (ms) => {
|
|
3725
5126
|
try {
|
|
@@ -3728,312 +5129,151 @@ async function runDaemon(options) {
|
|
|
3728
5129
|
if (!options.signal.aborted) throw new Error("Reconnect wait failed");
|
|
3729
5130
|
}
|
|
3730
5131
|
};
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
closeCode = result.code;
|
|
3751
|
-
closeDisposition = recovery;
|
|
3752
|
-
const reconnect = !options.signal.aborted && recovery !== "terminal" && !(recovery === "token" && rejectedToken);
|
|
3753
|
-
console.error(
|
|
3754
|
-
`TSP gateway socket closed: code=${result.code} disposition=${recovery} reconnect=${reconnect}`
|
|
3755
|
-
);
|
|
3756
|
-
if (options.signal.aborted) break;
|
|
3757
|
-
if (recovery === "outdated") {
|
|
3758
|
-
await status(
|
|
3759
|
-
false,
|
|
3760
|
-
"This gateway is outdated. Run npm install --global @treestructuredplanning/gateway@latest, then tsp-gateway install."
|
|
3761
|
-
);
|
|
3762
|
-
await pause(OUTDATED_RETRY_MS);
|
|
3763
|
-
continue;
|
|
3764
|
-
}
|
|
3765
|
-
if (recovery === "terminal") {
|
|
3766
|
-
await status(
|
|
3767
|
-
false,
|
|
3768
|
-
result.code === 4504 ? "Agent work is disabled. Restart manually after it is enabled." : "Machine access ended. Run tsp-gateway pair again."
|
|
3769
|
-
);
|
|
3770
|
-
return;
|
|
3771
|
-
}
|
|
3772
|
-
if (recovery === "token") {
|
|
3773
|
-
if (rejectedToken) {
|
|
3774
|
-
await status(false, "Token rejected after refresh. Run tsp-gateway pair again.");
|
|
3775
|
-
return;
|
|
3776
|
-
}
|
|
3777
|
-
rejectedToken = true;
|
|
3778
|
-
force = true;
|
|
3779
|
-
}
|
|
3780
|
-
if (result.code === 4e3) force = true;
|
|
3781
|
-
await status(false, "Reconnecting");
|
|
3782
|
-
await pause(reconnectDelay(attempt++, options.random));
|
|
3783
|
-
}
|
|
3784
|
-
await status(false, "Stopped");
|
|
3785
|
-
}
|
|
3786
|
-
function sessionPolling(options, enqueue, send, isReady, pending) {
|
|
3787
|
-
let polling = false;
|
|
3788
|
-
let pollTimer;
|
|
3789
|
-
const schedulePoll = () => {
|
|
3790
|
-
if (!isReady()) return;
|
|
3791
|
-
pollTimer = setTimeout(
|
|
3792
|
-
() => {
|
|
3793
|
-
pollTimer = void 0;
|
|
3794
|
-
enqueue(async () => {
|
|
3795
|
-
if (pollTimer === void 0) await poll();
|
|
3796
|
-
});
|
|
3797
|
-
},
|
|
3798
|
-
options.commands.hasLiveBindings || pending.exists() ? options.pollMs ?? 2e3 : options.idlePollMs ?? 3e4
|
|
3799
|
-
);
|
|
3800
|
-
};
|
|
3801
|
-
const poll = async () => {
|
|
3802
|
-
if (!isReady() || polling) return;
|
|
3803
|
-
clearTimeout(pollTimer);
|
|
3804
|
-
pollTimer = void 0;
|
|
3805
|
-
polling = true;
|
|
3806
|
-
try {
|
|
3807
|
-
await pending.retry();
|
|
3808
|
-
for (const update of await options.commands.poll()) send(update);
|
|
3809
|
-
} finally {
|
|
3810
|
-
polling = false;
|
|
3811
|
-
schedulePoll();
|
|
3812
|
-
}
|
|
3813
|
-
};
|
|
3814
|
-
return { poll, stop: () => clearTimeout(pollTimer) };
|
|
3815
|
-
}
|
|
3816
|
-
function transportSender(socket, isActive) {
|
|
3817
|
-
return (message) => {
|
|
3818
|
-
if (!isActive() || socket.readyState !== WebSocket.OPEN) return;
|
|
3819
|
-
try {
|
|
3820
|
-
socket.send(JSON.stringify(message));
|
|
3821
|
-
} catch {
|
|
3822
|
-
socket.close(4001, "Transport send failed");
|
|
3823
|
-
}
|
|
5132
|
+
const state = {
|
|
5133
|
+
attempt: 0,
|
|
5134
|
+
force: false,
|
|
5135
|
+
rejectedToken: false,
|
|
5136
|
+
closeCode: null,
|
|
5137
|
+
closeDisposition: null,
|
|
5138
|
+
retries: new IntentRetries(
|
|
5139
|
+
options.commands,
|
|
5140
|
+
options.now ?? (() => performance.now()),
|
|
5141
|
+
options.random ?? Math.random
|
|
5142
|
+
),
|
|
5143
|
+
status: (connected, message) => options.status({
|
|
5144
|
+
connected,
|
|
5145
|
+
message,
|
|
5146
|
+
close_code: state.closeCode,
|
|
5147
|
+
close_disposition: state.closeDisposition
|
|
5148
|
+
}),
|
|
5149
|
+
backoff: () => pause(reconnectDelay(state.attempt++, options.random)),
|
|
5150
|
+
pause
|
|
3824
5151
|
};
|
|
5152
|
+
return state;
|
|
3825
5153
|
}
|
|
3826
|
-
function
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
(operation, remainingMs) => permits.accept(operation, remainingMs)
|
|
3834
|
-
);
|
|
3835
|
-
} catch {
|
|
3836
|
-
console.error(
|
|
3837
|
-
`TSP gateway command pending: kind=${command.kind} command_id=${command.command_id} action_id=${command.action_id}`
|
|
3838
|
-
);
|
|
3839
|
-
return;
|
|
3840
|
-
} finally {
|
|
3841
|
-
retries.defer(command);
|
|
3842
|
-
}
|
|
3843
|
-
for (const result of results) send(result);
|
|
3844
|
-
};
|
|
5154
|
+
async function runDaemon(options) {
|
|
5155
|
+
const handover = { predecessor: null };
|
|
5156
|
+
try {
|
|
5157
|
+
await reconnectLoop(options, handover);
|
|
5158
|
+
} finally {
|
|
5159
|
+
await handover.predecessor?.retire();
|
|
5160
|
+
}
|
|
3845
5161
|
}
|
|
3846
|
-
function
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
const
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
};
|
|
3861
|
-
let refreshing = false;
|
|
3862
|
-
let refreshPending = false;
|
|
3863
|
-
const refresh = () => {
|
|
3864
|
-
if (!state.ready()) return;
|
|
3865
|
-
refreshPending = true;
|
|
3866
|
-
if (refreshing) return;
|
|
3867
|
-
refreshing = true;
|
|
3868
|
-
enqueue(async () => {
|
|
3869
|
-
try {
|
|
3870
|
-
refreshPending = false;
|
|
3871
|
-
await advertise("advertise");
|
|
3872
|
-
} finally {
|
|
3873
|
-
refreshing = false;
|
|
3874
|
-
if (refreshPending && state.live()) refresh();
|
|
3875
|
-
}
|
|
5162
|
+
async function reconnectLoop(options, handover) {
|
|
5163
|
+
const state = reconnectState(options);
|
|
5164
|
+
while (!options.signal.aborted) {
|
|
5165
|
+
if (handover.predecessor && !handover.predecessor.open()) handover.predecessor = null;
|
|
5166
|
+
const credential = await accessToken(options, state, handover);
|
|
5167
|
+
if (credential === "halt") return;
|
|
5168
|
+
if (credential === "exit") break;
|
|
5169
|
+
if (credential === "retry") continue;
|
|
5170
|
+
state.force = false;
|
|
5171
|
+
const current = openConnection(options, {
|
|
5172
|
+
credential,
|
|
5173
|
+
status: state.status,
|
|
5174
|
+
retries: state.retries,
|
|
5175
|
+
predecessor: handover.predecessor
|
|
3876
5176
|
});
|
|
3877
|
-
|
|
3878
|
-
|
|
5177
|
+
const outcome = await Promise.race([
|
|
5178
|
+
current.closed,
|
|
5179
|
+
current.refreshDue.then(() => "refresh")
|
|
5180
|
+
]);
|
|
5181
|
+
if (outcome === "refresh") {
|
|
5182
|
+
handover.predecessor = current;
|
|
5183
|
+
state.force = true;
|
|
5184
|
+
state.attempt = 0;
|
|
5185
|
+
continue;
|
|
5186
|
+
}
|
|
5187
|
+
const step = await afterClose(options, state, outcome, handover);
|
|
5188
|
+
if (step === "halt") return;
|
|
5189
|
+
if (step === "exit") break;
|
|
5190
|
+
}
|
|
5191
|
+
await state.status(false, "Stopped");
|
|
3879
5192
|
}
|
|
3880
|
-
async function
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
const permits = new LaunchPermits(
|
|
3890
|
-
send,
|
|
3891
|
-
() => active && !options.signal.aborted,
|
|
3892
|
-
() => socket.close(4001, "Acceptance timeout")
|
|
3893
|
-
);
|
|
3894
|
-
const enqueue = (task) => {
|
|
3895
|
-
queue = queue.then(async () => {
|
|
3896
|
-
if (active && !options.signal.aborted) await task();
|
|
3897
|
-
}).catch(() => {
|
|
3898
|
-
console.error("TSP gateway local queue task failed.");
|
|
3899
|
-
});
|
|
3900
|
-
};
|
|
3901
|
-
const processCommand = commandProcessor(options.commands, permits, retries, send);
|
|
3902
|
-
const { advertise, refresh } = machineFacts(options, send, enqueue, {
|
|
3903
|
-
ready: () => ready,
|
|
3904
|
-
live: () => active && !options.signal.aborted
|
|
3905
|
-
});
|
|
3906
|
-
const factsInterval = setInterval(refresh, options.advertiseMs ?? 3e4);
|
|
3907
|
-
const unwatch = options.watchFacts?.(refresh);
|
|
3908
|
-
const polling = sessionPolling(
|
|
3909
|
-
options,
|
|
3910
|
-
enqueue,
|
|
3911
|
-
send,
|
|
3912
|
-
() => ready && active && !options.signal.aborted,
|
|
3913
|
-
{
|
|
3914
|
-
retry: () => retries.retryPending(processCommand, () => active && !options.signal.aborted),
|
|
3915
|
-
exists: () => retries.hasPending
|
|
5193
|
+
async function accessToken(options, state, handover) {
|
|
5194
|
+
try {
|
|
5195
|
+
return await options.tokens.access(state.force);
|
|
5196
|
+
} catch (error) {
|
|
5197
|
+
if (options.signal.aborted) return "exit";
|
|
5198
|
+
if (error instanceof TokenAccessDenied) {
|
|
5199
|
+
await handover.predecessor?.retire();
|
|
5200
|
+
await state.status(false, "Token refresh failed. Run tsp-gateway pair again.");
|
|
5201
|
+
return "halt";
|
|
3916
5202
|
}
|
|
5203
|
+
if (!handover.predecessor)
|
|
5204
|
+
await state.status(false, "Waiting for the network or TSP. Retrying\u2026");
|
|
5205
|
+
await state.backoff();
|
|
5206
|
+
return "retry";
|
|
5207
|
+
}
|
|
5208
|
+
}
|
|
5209
|
+
async function afterClose(options, state, result, handover) {
|
|
5210
|
+
if (result.stable) state.attempt = 0;
|
|
5211
|
+
if (result.receivedFrame) state.rejectedToken = false;
|
|
5212
|
+
const recovery = disposition(result.code);
|
|
5213
|
+
state.closeCode = result.code;
|
|
5214
|
+
state.closeDisposition = recovery;
|
|
5215
|
+
const reconnect = !options.signal.aborted && recovery !== "terminal" && !(recovery === "token" && state.rejectedToken);
|
|
5216
|
+
console.error(
|
|
5217
|
+
`TSP gateway socket closed: code=${result.code} disposition=${recovery} reconnect=${reconnect}`
|
|
3917
5218
|
);
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
options.commands.resetObservations();
|
|
3936
|
-
ready = true;
|
|
3937
|
-
readyAt = now();
|
|
3938
|
-
await polling.poll();
|
|
3939
|
-
await status(true, "Connected");
|
|
3940
|
-
});
|
|
3941
|
-
});
|
|
3942
|
-
socket.addEventListener("message", (event) => {
|
|
3943
|
-
if (!active || options.signal.aborted) return;
|
|
3944
|
-
let message;
|
|
3945
|
-
try {
|
|
3946
|
-
message = decodeHubText(event.data);
|
|
3947
|
-
} catch {
|
|
3948
|
-
socket.close(4002, "Invalid frame");
|
|
3949
|
-
return;
|
|
3950
|
-
}
|
|
3951
|
-
receivedFrame = true;
|
|
3952
|
-
if (message.kind === "ping") {
|
|
3953
|
-
send({
|
|
3954
|
-
kind: "pong",
|
|
3955
|
-
protocol_version: GATEWAY_PROTOCOL_VERSION,
|
|
3956
|
-
nonce: message.nonce
|
|
3957
|
-
});
|
|
3958
|
-
return;
|
|
3959
|
-
}
|
|
3960
|
-
if (message.kind === "permit" || message.kind === "retire") {
|
|
3961
|
-
permits.receive(message);
|
|
3962
|
-
if (message.kind === "permit") {
|
|
3963
|
-
const receipt = message.receipt;
|
|
3964
|
-
if (receipt)
|
|
3965
|
-
enqueue(async () => {
|
|
3966
|
-
await options.commands.reconcile(receipt);
|
|
3967
|
-
});
|
|
3968
|
-
return;
|
|
3969
|
-
}
|
|
5219
|
+
if (options.signal.aborted) return "exit";
|
|
5220
|
+
if (recovery === "outdated") {
|
|
5221
|
+
await state.status(
|
|
5222
|
+
false,
|
|
5223
|
+
"This gateway is outdated. Run npm install --global @treestructuredplanning/gateway@latest, then tsp-gateway install."
|
|
5224
|
+
);
|
|
5225
|
+
await state.pause(OUTDATED_RETRY_MS);
|
|
5226
|
+
return "retry";
|
|
5227
|
+
}
|
|
5228
|
+
if (recovery === "terminal") {
|
|
5229
|
+
await state.status(false, "Machine access ended. Run tsp-gateway pair again.");
|
|
5230
|
+
return "halt";
|
|
5231
|
+
}
|
|
5232
|
+
if (recovery === "token") {
|
|
5233
|
+
if (state.rejectedToken) {
|
|
5234
|
+
await state.status(false, "Token rejected after refresh. Run tsp-gateway pair again.");
|
|
5235
|
+
return "halt";
|
|
3970
5236
|
}
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
3974
|
-
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
await polling.poll();
|
|
3978
|
-
await advertise("advertise");
|
|
3979
|
-
});
|
|
3980
|
-
});
|
|
3981
|
-
socket.addEventListener("error", () => {
|
|
3982
|
-
});
|
|
3983
|
-
const code = await new Promise(
|
|
3984
|
-
(resolve6) => socket.addEventListener(
|
|
3985
|
-
"close",
|
|
3986
|
-
(event) => {
|
|
3987
|
-
stable = readyAt !== null && now() - readyAt >= STABLE_CONNECTION_MS;
|
|
3988
|
-
active = false;
|
|
3989
|
-
permits.cancel();
|
|
3990
|
-
resolve6(event.code);
|
|
3991
|
-
},
|
|
3992
|
-
{ once: true }
|
|
3993
|
-
)
|
|
3994
|
-
);
|
|
3995
|
-
polling.stop();
|
|
3996
|
-
clearInterval(factsInterval);
|
|
3997
|
-
unwatch?.();
|
|
3998
|
-
clearTimeout(expiry);
|
|
3999
|
-
clearTimeout(timeout);
|
|
4000
|
-
options.signal.removeEventListener("abort", abort);
|
|
4001
|
-
await queue;
|
|
4002
|
-
return { code, stable, receivedFrame };
|
|
5237
|
+
state.rejectedToken = true;
|
|
5238
|
+
state.force = true;
|
|
5239
|
+
}
|
|
5240
|
+
if (!handover.predecessor?.open()) await state.status(false, "Reconnecting");
|
|
5241
|
+
await state.backoff();
|
|
5242
|
+
return "retry";
|
|
4003
5243
|
}
|
|
4004
5244
|
|
|
4005
5245
|
// src/daemon-lock.ts
|
|
4006
5246
|
import { createHash as createHash3 } from "node:crypto";
|
|
4007
5247
|
import { lstatSync, unlinkSync } from "node:fs";
|
|
4008
|
-
import { realpath as
|
|
5248
|
+
import { realpath as realpath7 } from "node:fs/promises";
|
|
4009
5249
|
import { createConnection, createServer as createServer2 } from "node:net";
|
|
4010
5250
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
4011
|
-
import { join as
|
|
5251
|
+
import { join as join9, resolve as resolve6 } from "node:path";
|
|
4012
5252
|
function hasCode(error, code) {
|
|
4013
5253
|
return isObject(error) && field(error, "code") === code;
|
|
4014
5254
|
}
|
|
4015
5255
|
async function lockEndpoint(state) {
|
|
4016
|
-
await privateDirectory(
|
|
4017
|
-
const absolute = await
|
|
5256
|
+
await privateDirectory(resolve6(state));
|
|
5257
|
+
const absolute = await realpath7(state);
|
|
4018
5258
|
const hash = createHash3("sha256").update(absolute).digest("hex");
|
|
4019
5259
|
if (process.platform === "win32") return `\\\\.\\pipe\\tsp-gateway-${hash}`;
|
|
4020
|
-
const local =
|
|
5260
|
+
const local = join9(absolute, "daemon.sock");
|
|
4021
5261
|
if (Buffer.byteLength(local) <= 103) return local;
|
|
4022
5262
|
const name = `tsp-gateway-${hash.slice(0, 24)}`;
|
|
4023
|
-
let directory =
|
|
4024
|
-
if (Buffer.byteLength(
|
|
5263
|
+
let directory = join9(tmpdir2(), name);
|
|
5264
|
+
if (Buffer.byteLength(join9(directory, "lock.sock")) > 103) directory = join9("/tmp", name);
|
|
4025
5265
|
await privateDirectory(directory);
|
|
4026
|
-
return
|
|
5266
|
+
return join9(directory, "lock.sock");
|
|
4027
5267
|
}
|
|
4028
5268
|
function listen(server, path) {
|
|
4029
|
-
return new Promise((
|
|
5269
|
+
return new Promise((resolve7, reject) => {
|
|
4030
5270
|
const failed = (error) => {
|
|
4031
5271
|
server.removeListener("listening", ready);
|
|
4032
5272
|
reject(error);
|
|
4033
5273
|
};
|
|
4034
5274
|
const ready = () => {
|
|
4035
5275
|
server.removeListener("error", failed);
|
|
4036
|
-
|
|
5276
|
+
resolve7();
|
|
4037
5277
|
};
|
|
4038
5278
|
server.once("error", failed);
|
|
4039
5279
|
server.once("listening", ready);
|
|
@@ -4041,15 +5281,15 @@ function listen(server, path) {
|
|
|
4041
5281
|
});
|
|
4042
5282
|
}
|
|
4043
5283
|
function owned(path) {
|
|
4044
|
-
return new Promise((
|
|
5284
|
+
return new Promise((resolve7, reject) => {
|
|
4045
5285
|
const socket = createConnection(path);
|
|
4046
5286
|
socket.once("connect", () => {
|
|
4047
5287
|
socket.destroy();
|
|
4048
|
-
|
|
5288
|
+
resolve7(true);
|
|
4049
5289
|
});
|
|
4050
5290
|
socket.once("error", (error) => {
|
|
4051
5291
|
socket.destroy();
|
|
4052
|
-
if (hasCode(error, "ECONNREFUSED") || hasCode(error, "ENOENT"))
|
|
5292
|
+
if (hasCode(error, "ECONNREFUSED") || hasCode(error, "ENOENT")) resolve7(false);
|
|
4053
5293
|
else reject(error);
|
|
4054
5294
|
});
|
|
4055
5295
|
socket.setTimeout(2e3, () => {
|
|
@@ -4087,15 +5327,15 @@ async function daemonLock(state) {
|
|
|
4087
5327
|
}
|
|
4088
5328
|
let releasing;
|
|
4089
5329
|
return () => {
|
|
4090
|
-
releasing ??= new Promise((
|
|
4091
|
-
server.close((error) => error ? reject(error) :
|
|
5330
|
+
releasing ??= new Promise((resolve7, reject) => {
|
|
5331
|
+
server.close((error) => error ? reject(error) : resolve7());
|
|
4092
5332
|
});
|
|
4093
5333
|
return releasing;
|
|
4094
5334
|
};
|
|
4095
5335
|
}
|
|
4096
5336
|
|
|
4097
5337
|
// src/gateway-status.ts
|
|
4098
|
-
import { readFile as
|
|
5338
|
+
import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
|
|
4099
5339
|
var GatewayStatus = class {
|
|
4100
5340
|
constructor(path, executor) {
|
|
4101
5341
|
this.path = path;
|
|
@@ -4125,7 +5365,7 @@ var GatewayStatus = class {
|
|
|
4125
5365
|
};
|
|
4126
5366
|
async function daemonConnection(statusPath, since = 0) {
|
|
4127
5367
|
try {
|
|
4128
|
-
const [text3, info] = await Promise.all([
|
|
5368
|
+
const [text3, info] = await Promise.all([readFile4(statusPath, "utf8"), stat3(statusPath)]);
|
|
4129
5369
|
if (info.mtimeMs < since) return null;
|
|
4130
5370
|
const status = parseJson(text3);
|
|
4131
5371
|
if (!isObject(status)) return null;
|
|
@@ -4140,7 +5380,7 @@ async function awaitDaemonConnection(statusPath, since, timeoutMs = 8e3, interva
|
|
|
4140
5380
|
for (; ; ) {
|
|
4141
5381
|
const message = await daemonConnection(statusPath, since);
|
|
4142
5382
|
if (message !== null || Date.now() >= deadline) return message;
|
|
4143
|
-
await new Promise((
|
|
5383
|
+
await new Promise((resolve7) => setTimeout(resolve7, intervalMs));
|
|
4144
5384
|
}
|
|
4145
5385
|
}
|
|
4146
5386
|
function readLaunchObservation(value) {
|
|
@@ -4168,9 +5408,9 @@ function keychain(account) {
|
|
|
4168
5408
|
}
|
|
4169
5409
|
|
|
4170
5410
|
// src/installer.ts
|
|
4171
|
-
import { readFile as
|
|
4172
|
-
import { homedir as
|
|
4173
|
-
import { dirname as
|
|
5411
|
+
import { readFile as readFile5, rm as rm2 } from "node:fs/promises";
|
|
5412
|
+
import { homedir as homedir8, userInfo as userInfo2 } from "node:os";
|
|
5413
|
+
import { dirname as dirname6, isAbsolute as isAbsolute8, join as join10, win32 } from "node:path";
|
|
4174
5414
|
var label = "com.treestructuredplanning.tsp-gateway";
|
|
4175
5415
|
function xml(value) {
|
|
4176
5416
|
return value.replace(
|
|
@@ -4187,7 +5427,7 @@ function quoted(value) {
|
|
|
4187
5427
|
}
|
|
4188
5428
|
function installDefinition(platform, spec) {
|
|
4189
5429
|
if (![spec.node, spec.entry, spec.config, spec.state].every(
|
|
4190
|
-
platform === "win32" ? (value) => win32.isAbsolute(value) ||
|
|
5430
|
+
platform === "win32" ? (value) => win32.isAbsolute(value) || isAbsolute8(value) : isAbsolute8
|
|
4191
5431
|
) || /[\r\n\0]/.test(Object.values(spec).join("")))
|
|
4192
5432
|
throw new Error("Installer requires absolute paths and single-line values");
|
|
4193
5433
|
const args = [
|
|
@@ -4210,8 +5450,8 @@ function installDefinition(platform, spec) {
|
|
|
4210
5450
|
<key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
|
|
4211
5451
|
<key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
4212
5452
|
<key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(spec.path)}</string></dict>
|
|
4213
|
-
<key>StandardOutPath</key><string>${xml(
|
|
4214
|
-
<key>StandardErrorPath</key><string>${xml(
|
|
5453
|
+
<key>StandardOutPath</key><string>${xml(join10(spec.state, "stdout.log"))}</string>
|
|
5454
|
+
<key>StandardErrorPath</key><string>${xml(join10(spec.state, "stderr.log"))}</string>
|
|
4215
5455
|
</dict></plist>
|
|
4216
5456
|
`;
|
|
4217
5457
|
if (platform === "linux")
|
|
@@ -4224,14 +5464,14 @@ Environment=${systemd(`PATH=${spec.path}`, false)}
|
|
|
4224
5464
|
Restart=on-failure
|
|
4225
5465
|
RestartSec=5
|
|
4226
5466
|
UMask=0077
|
|
4227
|
-
StandardOutput=append:${
|
|
4228
|
-
StandardError=append:${
|
|
5467
|
+
StandardOutput=append:${join10(spec.state, "stdout.log").replace(/%/g, "%%")}
|
|
5468
|
+
StandardError=append:${join10(spec.state, "stderr.log").replace(/%/g, "%%")}
|
|
4229
5469
|
[Install]
|
|
4230
5470
|
WantedBy=default.target
|
|
4231
5471
|
`;
|
|
4232
5472
|
if (platform === "win32")
|
|
4233
5473
|
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
4234
|
-
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Description>TSP gateway ${xml(spec.version)}</Description></RegistrationInfo><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(spec.user ?? userInfo2().username)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(spec.user ?? userInfo2().username)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>${xml(spec.node)}</Command><Arguments>${xml(args.slice(1).map(quoted).join(" "))}</Arguments><WorkingDirectory>${xml(win32.isAbsolute(spec.entry) ? win32.dirname(spec.entry) :
|
|
5474
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Description>TSP gateway ${xml(spec.version)}</Description></RegistrationInfo><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(spec.user ?? userInfo2().username)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(spec.user ?? userInfo2().username)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>${xml(spec.node)}</Command><Arguments>${xml(args.slice(1).map(quoted).join(" "))}</Arguments><WorkingDirectory>${xml(win32.isAbsolute(spec.entry) ? win32.dirname(spec.entry) : dirname6(spec.entry))}</WorkingDirectory></Exec></Actions></Task>
|
|
4235
5475
|
`;
|
|
4236
5476
|
throw new Error("Login items support macOS, Linux and Windows");
|
|
4237
5477
|
}
|
|
@@ -4251,11 +5491,11 @@ async function captureLoginPath(env = process.env, platform = process.platform,
|
|
|
4251
5491
|
if (!path || /[\r\n\0]/.test(path)) throw new Error("Could not capture login-shell PATH");
|
|
4252
5492
|
return path;
|
|
4253
5493
|
}
|
|
4254
|
-
function installPath(platform, state, home =
|
|
4255
|
-
if (platform === "darwin") return
|
|
5494
|
+
function installPath(platform, state, home = homedir8()) {
|
|
5495
|
+
if (platform === "darwin") return join10(home, "Library", "LaunchAgents", `${label}.plist`);
|
|
4256
5496
|
if (platform === "linux")
|
|
4257
|
-
return
|
|
4258
|
-
if (platform === "win32") return
|
|
5497
|
+
return join10(home, ".config", "systemd", "user", "tsp-gateway.service");
|
|
5498
|
+
if (platform === "win32") return join10(state, "tsp-gateway.xml");
|
|
4259
5499
|
throw new Error("Unsupported platform");
|
|
4260
5500
|
}
|
|
4261
5501
|
function launchdDomain() {
|
|
@@ -4268,7 +5508,7 @@ async function registered(platform) {
|
|
|
4268
5508
|
const [file, args] = platform === "darwin" ? ["launchctl", ["print", launchdService()]] : platform === "linux" ? ["systemctl", ["--user", "is-active", "--quiet", "tsp-gateway.service"]] : ["schtasks.exe", ["/Query", "/TN", label]];
|
|
4269
5509
|
return (await execute(file, args, process.env)).code === 0;
|
|
4270
5510
|
}
|
|
4271
|
-
async function
|
|
5511
|
+
async function running2(platform) {
|
|
4272
5512
|
if (platform === "linux") return registered(platform);
|
|
4273
5513
|
const [file, args, pattern] = platform === "darwin" ? ["launchctl", ["print", launchdService()], /^\s*state = running$/m] : ["schtasks.exe", ["/Query", "/TN", label, "/FO", "LIST"], /^Status:\s+Running\s*$/m];
|
|
4274
5514
|
const result = await execute(file, args, process.env);
|
|
@@ -4280,7 +5520,7 @@ async function bootout(timeoutMs = 1e4, intervalMs = 100) {
|
|
|
4280
5520
|
while (await registered("darwin")) {
|
|
4281
5521
|
if (Date.now() >= deadline)
|
|
4282
5522
|
throw new Error("Could not update login item (launchd still lists the old one)");
|
|
4283
|
-
await new Promise((
|
|
5523
|
+
await new Promise((resolve7) => setTimeout(resolve7, intervalMs));
|
|
4284
5524
|
}
|
|
4285
5525
|
}
|
|
4286
5526
|
async function systemCommand(file, args) {
|
|
@@ -4288,11 +5528,11 @@ async function systemCommand(file, args) {
|
|
|
4288
5528
|
if (result.code !== 0)
|
|
4289
5529
|
throw new Error(`Could not update login item (${file}, exit ${result.code})`);
|
|
4290
5530
|
}
|
|
4291
|
-
async function install(spec, platform = process.platform, home =
|
|
5531
|
+
async function install(spec, platform = process.platform, home = homedir8()) {
|
|
4292
5532
|
const destination = installPath(platform, spec.state, home);
|
|
4293
5533
|
await privateDirectory(spec.state);
|
|
4294
5534
|
await import("node:fs/promises").then(
|
|
4295
|
-
(fs) => fs.mkdir(
|
|
5535
|
+
(fs) => fs.mkdir(dirname6(destination), { recursive: true })
|
|
4296
5536
|
);
|
|
4297
5537
|
const definition = installDefinition(platform, spec);
|
|
4298
5538
|
if (platform === "win32") {
|
|
@@ -4315,12 +5555,12 @@ async function install(spec, platform = process.platform, home = homedir6()) {
|
|
|
4315
5555
|
await systemCommand("systemctl", ["--user", "restart", "tsp-gateway.service"]);
|
|
4316
5556
|
}
|
|
4317
5557
|
}
|
|
4318
|
-
await privateWrite(
|
|
5558
|
+
await privateWrite(join10(spec.state, "installation.json"), JSON.stringify(spec));
|
|
4319
5559
|
}
|
|
4320
|
-
async function uninstall(state, platform = process.platform, home =
|
|
5560
|
+
async function uninstall(state, platform = process.platform, home = homedir8()) {
|
|
4321
5561
|
const destination = installPath(platform, state, home);
|
|
4322
5562
|
try {
|
|
4323
|
-
await
|
|
5563
|
+
await readFile5(destination);
|
|
4324
5564
|
} catch {
|
|
4325
5565
|
return false;
|
|
4326
5566
|
}
|
|
@@ -4334,20 +5574,20 @@ async function uninstall(state, platform = process.platform, home = homedir6())
|
|
|
4334
5574
|
}
|
|
4335
5575
|
await rm2(destination, { force: true });
|
|
4336
5576
|
if (platform === "linux") await systemCommand("systemctl", ["--user", "daemon-reload"]);
|
|
4337
|
-
await rm2(
|
|
5577
|
+
await rm2(join10(state, "installation.json"), { force: true });
|
|
4338
5578
|
return true;
|
|
4339
5579
|
}
|
|
4340
|
-
async function loginItemCurrent(spec, platform = process.platform, home =
|
|
5580
|
+
async function loginItemCurrent(spec, platform = process.platform, home = homedir8()) {
|
|
4341
5581
|
try {
|
|
4342
|
-
const recorded = parseJson(await
|
|
4343
|
-
await
|
|
5582
|
+
const recorded = parseJson(await readFile5(join10(spec.state, "installation.json"), "utf8"));
|
|
5583
|
+
await readFile5(installPath(platform, spec.state, home));
|
|
4344
5584
|
const keys = Object.keys(spec);
|
|
4345
5585
|
if (!isObject(recorded) || Object.keys(recorded).length !== keys.length || keys.some((key) => field(recorded, key) !== spec[key]))
|
|
4346
5586
|
return false;
|
|
4347
5587
|
} catch {
|
|
4348
5588
|
return false;
|
|
4349
5589
|
}
|
|
4350
|
-
return
|
|
5590
|
+
return running2(platform);
|
|
4351
5591
|
}
|
|
4352
5592
|
|
|
4353
5593
|
// src/setup.ts
|
|
@@ -4558,12 +5798,7 @@ export {
|
|
|
4558
5798
|
HarnessExecutor,
|
|
4559
5799
|
sanitizeWaiting,
|
|
4560
5800
|
ClaudeDriver,
|
|
4561
|
-
|
|
4562
|
-
CodexTrust,
|
|
4563
|
-
CodexDriver,
|
|
4564
|
-
HarnessRegistry,
|
|
4565
|
-
builtinHarnesses,
|
|
4566
|
-
CommandLifetime,
|
|
5801
|
+
AcpDriver,
|
|
4567
5802
|
locations,
|
|
4568
5803
|
privateDirectory,
|
|
4569
5804
|
readConfig,
|
|
@@ -4572,12 +5807,23 @@ export {
|
|
|
4572
5807
|
validSlug,
|
|
4573
5808
|
githubSlug,
|
|
4574
5809
|
registerFolder,
|
|
5810
|
+
AcpGroupLedger,
|
|
5811
|
+
CodexActivity,
|
|
5812
|
+
CodexTrust,
|
|
5813
|
+
CodexDriver,
|
|
5814
|
+
cursorProjectKey,
|
|
5815
|
+
CursorAgent,
|
|
5816
|
+
HarnessRegistry,
|
|
5817
|
+
builtinHarnesses,
|
|
5818
|
+
CommandLifetime,
|
|
4575
5819
|
Journal,
|
|
4576
5820
|
MISSING_SESSION_POLLS,
|
|
4577
5821
|
UNREADABLE_SESSION_POLLS,
|
|
4578
5822
|
Commands,
|
|
4579
5823
|
watchConfig,
|
|
4580
5824
|
LaunchPermits,
|
|
5825
|
+
HANDOVER_MS,
|
|
5826
|
+
REFRESH_LEAD_MS,
|
|
4581
5827
|
OAuthTokens,
|
|
4582
5828
|
pair,
|
|
4583
5829
|
unpair,
|
|
@@ -4608,4 +5854,4 @@ export {
|
|
|
4608
5854
|
connectLines,
|
|
4609
5855
|
statusLines
|
|
4610
5856
|
};
|
|
4611
|
-
//# sourceMappingURL=shared-
|
|
5857
|
+
//# sourceMappingURL=shared-RM5C4AZN.js.map
|