repoburg 1.3.295 → 1.3.297
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/agent-pane/backend/dist/index.js +685 -323
- package/agent-pane/backend/dist/server.js +685 -323
- package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.d.ts +7 -1
- package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js +19 -0
- package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js.map +1 -1
- package/backend/dist/src/agent-runtime/agent-runtime.controller.d.ts +2 -0
- package/backend/dist/src/agent-runtime/agent-runtime.controller.js +22 -0
- package/backend/dist/src/agent-runtime/agent-runtime.controller.js.map +1 -1
- package/backend/dist/src/agent-runtime/agent-runtime.types.d.ts +7 -0
- package/backend/dist/src/interactive-chat/chat.service.js +1 -0
- package/backend/dist/src/interactive-chat/chat.service.js.map +1 -1
- package/backend/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/tabtape/extension/dist/build-info.json +3 -3
- package/tabtape/extension/dist/manifest.json +1 -1
- package/tabtape/ui/dist/build-info.json +3 -3
|
@@ -2698,7 +2698,7 @@ var require_server = __commonJS({
|
|
|
2698
2698
|
}
|
|
2699
2699
|
function createServer(options, httpHandler) {
|
|
2700
2700
|
const server = getServerInstance(options, httpHandler);
|
|
2701
|
-
function
|
|
2701
|
+
function listen2(listenOptions = { port: 0, host: "localhost" }, cb = void 0) {
|
|
2702
2702
|
if (typeof cb === "function") {
|
|
2703
2703
|
if (cb.constructor.name === "AsyncFunction") {
|
|
2704
2704
|
FSTWRN003("listen method");
|
|
@@ -2783,7 +2783,7 @@ var require_server = __commonJS({
|
|
|
2783
2783
|
const keepAliveConnections = !serverHasCloseAllConnections && forceCloseConnections === true ? /* @__PURE__ */ new Set() : noopSet();
|
|
2784
2784
|
return {
|
|
2785
2785
|
server,
|
|
2786
|
-
listen,
|
|
2786
|
+
listen: listen2,
|
|
2787
2787
|
forceCloseConnections,
|
|
2788
2788
|
serverHasCloseAllConnections,
|
|
2789
2789
|
serverHasCloseHttp2Sessions,
|
|
@@ -36169,7 +36169,7 @@ var require_fastify = __commonJS({
|
|
|
36169
36169
|
const httpHandler = wrapRouting(router, options);
|
|
36170
36170
|
const {
|
|
36171
36171
|
server,
|
|
36172
|
-
listen,
|
|
36172
|
+
listen: listen2,
|
|
36173
36173
|
forceCloseConnections,
|
|
36174
36174
|
serverHasCloseAllConnections,
|
|
36175
36175
|
serverHasCloseHttp2Sessions,
|
|
@@ -36313,7 +36313,7 @@ var require_fastify = __commonJS({
|
|
|
36313
36313
|
return this[pluginUtils.kRegisteredPlugins].includes(name) || this[kPluginNameChain].includes(name);
|
|
36314
36314
|
},
|
|
36315
36315
|
// http server
|
|
36316
|
-
listen,
|
|
36316
|
+
listen: listen2,
|
|
36317
36317
|
server,
|
|
36318
36318
|
addresses: function() {
|
|
36319
36319
|
const binded = this[kServerBindings].map((b) => b.address());
|
|
@@ -41197,6 +41197,10 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
|
|
|
41197
41197
|
if (!turnColumns.some((c) => c.name === "resume_at")) {
|
|
41198
41198
|
database.exec("ALTER TABLE turns ADD COLUMN resume_at TEXT");
|
|
41199
41199
|
}
|
|
41200
|
+
const processColumns = database.prepare("PRAGMA table_info(cli_processes)").all();
|
|
41201
|
+
if (!processColumns.some((c) => c.name === "runtime")) {
|
|
41202
|
+
database.exec("ALTER TABLE cli_processes ADD COLUMN runtime TEXT NOT NULL DEFAULT 'claude'");
|
|
41203
|
+
}
|
|
41200
41204
|
const threadColumns = database.prepare("PRAGMA table_info(discussion_threads)").all();
|
|
41201
41205
|
if (!threadColumns.some((c) => c.name === "external_thread_id")) {
|
|
41202
41206
|
database.exec("ALTER TABLE discussion_threads ADD COLUMN external_thread_id TEXT");
|
|
@@ -42367,9 +42371,20 @@ function resumeMadeProgress(db2, turn) {
|
|
|
42367
42371
|
AND created_at >= ? LIMIT 1`
|
|
42368
42372
|
).get(turn.id, resumedAt);
|
|
42369
42373
|
}
|
|
42374
|
+
function isReopenable(db2, turn) {
|
|
42375
|
+
if (turn.status !== "completed" || turn.thread_id) return false;
|
|
42376
|
+
const latest = db2.prepare(
|
|
42377
|
+
"SELECT id FROM turns WHERE session_id = ? AND thread_id IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1"
|
|
42378
|
+
).get(turn.session_id);
|
|
42379
|
+
if (latest?.id !== turn.id) return false;
|
|
42380
|
+
return !db2.prepare(
|
|
42381
|
+
"SELECT 1 FROM turns WHERE session_id = ? AND thread_id IS NULL AND status IN ('pending', 'running') LIMIT 1"
|
|
42382
|
+
).get(turn.session_id);
|
|
42383
|
+
}
|
|
42370
42384
|
function markTurnInterrupted(db2, turnId, reason, opts = {}) {
|
|
42371
42385
|
const turn = getTurn(db2, turnId);
|
|
42372
|
-
if (!turn
|
|
42386
|
+
if (!turn) return false;
|
|
42387
|
+
if (!isLive(turn.status) && !(opts.reopen && isReopenable(db2, turn))) return false;
|
|
42373
42388
|
if (turn.status === "pending" && turn.resume_state === "waiting") return false;
|
|
42374
42389
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42375
42390
|
const detail = opts.detail ?? null;
|
|
@@ -43630,6 +43645,7 @@ import { readFileSync } from "node:fs";
|
|
|
43630
43645
|
import { spawn } from "node:child_process";
|
|
43631
43646
|
import { EventEmitter } from "node:events";
|
|
43632
43647
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
43648
|
+
var CLOSE_GRACE_MS = 2e3;
|
|
43633
43649
|
var AppServerClient = class {
|
|
43634
43650
|
proc;
|
|
43635
43651
|
nextId = 1;
|
|
@@ -43638,6 +43654,8 @@ var AppServerClient = class {
|
|
|
43638
43654
|
requestHandlers = /* @__PURE__ */ new Map();
|
|
43639
43655
|
buffer = "";
|
|
43640
43656
|
closed = false;
|
|
43657
|
+
/** The process is gone (exit), or never started (spawn error). */
|
|
43658
|
+
gone = false;
|
|
43641
43659
|
clientInfo;
|
|
43642
43660
|
/** Bound stdout listener — removed in close() so stale data is not processed. */
|
|
43643
43661
|
stdoutListener = (chunk) => this.onStdoutData(chunk);
|
|
@@ -43651,6 +43669,8 @@ var AppServerClient = class {
|
|
|
43651
43669
|
stdio: ["pipe", "pipe", "pipe"]
|
|
43652
43670
|
});
|
|
43653
43671
|
this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
|
|
43672
|
+
this.proc.stdin?.on("error", () => {
|
|
43673
|
+
});
|
|
43654
43674
|
this.proc.stdout?.setEncoding("utf-8");
|
|
43655
43675
|
this.proc.stdout?.on("data", this.stdoutListener);
|
|
43656
43676
|
this.proc.stderr?.on("data", (chunk) => {
|
|
@@ -43658,6 +43678,7 @@ var AppServerClient = class {
|
|
|
43658
43678
|
if (text2) console.error("[app-server] stderr:", text2);
|
|
43659
43679
|
});
|
|
43660
43680
|
this.proc.on("exit", (code, signal) => {
|
|
43681
|
+
this.gone = true;
|
|
43661
43682
|
this.onProcessExit(code, signal);
|
|
43662
43683
|
});
|
|
43663
43684
|
this.proc.on("error", (err) => {
|
|
@@ -43717,7 +43738,17 @@ var AppServerClient = class {
|
|
|
43717
43738
|
isClosed() {
|
|
43718
43739
|
return this.closed;
|
|
43719
43740
|
}
|
|
43720
|
-
/**
|
|
43741
|
+
/** Pid of the app-server process (the codex launcher), undefined when it never started. */
|
|
43742
|
+
get pid() {
|
|
43743
|
+
return this.proc.pid;
|
|
43744
|
+
}
|
|
43745
|
+
/**
|
|
43746
|
+
* Close the client and end the app-server. Its stdin is closed first: on end
|
|
43747
|
+
* of input the app-server shuts down and ends the commands it runs, while a
|
|
43748
|
+
* SIGTERM makes it exit at once and leaves them running. SIGTERM follows
|
|
43749
|
+
* only when it has not exited CLOSE_GRACE_MS later, SIGKILL after another
|
|
43750
|
+
* CLOSE_GRACE_MS. Resolves once it exited (or got SIGKILL).
|
|
43751
|
+
*/
|
|
43721
43752
|
async close() {
|
|
43722
43753
|
if (this.closed) return;
|
|
43723
43754
|
this.closed = true;
|
|
@@ -43727,7 +43758,27 @@ var AppServerClient = class {
|
|
|
43727
43758
|
entry.reject(new Error("AppServerClient closed"));
|
|
43728
43759
|
this.pending.delete(id);
|
|
43729
43760
|
}
|
|
43761
|
+
this.proc.stdin?.end();
|
|
43762
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43730
43763
|
this.proc.kill("SIGTERM");
|
|
43764
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43765
|
+
this.proc.kill("SIGKILL");
|
|
43766
|
+
}
|
|
43767
|
+
/** True once the process exited, false when it is still running after `ms`. */
|
|
43768
|
+
exitWithin(ms) {
|
|
43769
|
+
if (this.gone) return Promise.resolve(true);
|
|
43770
|
+
return new Promise((resolve) => {
|
|
43771
|
+
const onExit = () => {
|
|
43772
|
+
clearTimeout(timer2);
|
|
43773
|
+
resolve(true);
|
|
43774
|
+
};
|
|
43775
|
+
const timer2 = setTimeout(() => {
|
|
43776
|
+
this.proc.removeListener("exit", onExit);
|
|
43777
|
+
resolve(false);
|
|
43778
|
+
}, ms);
|
|
43779
|
+
timer2.unref?.();
|
|
43780
|
+
this.proc.once("exit", onExit);
|
|
43781
|
+
});
|
|
43731
43782
|
}
|
|
43732
43783
|
// --- Internal methods ---
|
|
43733
43784
|
write(message) {
|
|
@@ -43803,6 +43854,7 @@ var AppServerClient = class {
|
|
|
43803
43854
|
onProcessExit(code, signal) {
|
|
43804
43855
|
if (this.closed) return;
|
|
43805
43856
|
this.closed = true;
|
|
43857
|
+
this.proc.stdin?.end();
|
|
43806
43858
|
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
43807
43859
|
const error51 = new Error(`App-server process exited (${reason})`);
|
|
43808
43860
|
for (const [, entry] of this.pending) {
|
|
@@ -43816,6 +43868,7 @@ var AppServerClient = class {
|
|
|
43816
43868
|
* binary is missing). Rejects pending requests and emits 'closed' so callers
|
|
43817
43869
|
* can fail gracefully instead of crashing the whole process. */
|
|
43818
43870
|
onProcessError(err) {
|
|
43871
|
+
if (this.proc.pid === void 0) this.gone = true;
|
|
43819
43872
|
if (this.closed) return;
|
|
43820
43873
|
this.closed = true;
|
|
43821
43874
|
for (const [, entry] of this.pending) {
|
|
@@ -116665,8 +116718,111 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
|
|
|
116665
116718
|
];
|
|
116666
116719
|
}
|
|
116667
116720
|
|
|
116721
|
+
// src/claude/cli-orphans.ts
|
|
116722
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
116723
|
+
var TERM_GRACE_MS = 2e3;
|
|
116724
|
+
var POLL_MS = 100;
|
|
116725
|
+
function inspectProcess(pid) {
|
|
116726
|
+
return new Promise((resolve) => {
|
|
116727
|
+
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
116728
|
+
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
116729
|
+
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
116730
|
+
});
|
|
116731
|
+
});
|
|
116732
|
+
}
|
|
116733
|
+
function listDescendants(pid) {
|
|
116734
|
+
return new Promise((resolve) => {
|
|
116735
|
+
execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
|
|
116736
|
+
if (err) {
|
|
116737
|
+
resolve([]);
|
|
116738
|
+
return;
|
|
116739
|
+
}
|
|
116740
|
+
const children = /* @__PURE__ */ new Map();
|
|
116741
|
+
for (const line of stdout.split("\n")) {
|
|
116742
|
+
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
116743
|
+
if (!match) continue;
|
|
116744
|
+
const parent = Number(match[2]);
|
|
116745
|
+
children.set(parent, [...children.get(parent) ?? [], Number(match[1])]);
|
|
116746
|
+
}
|
|
116747
|
+
const found = [];
|
|
116748
|
+
const queue = [...children.get(pid) ?? []];
|
|
116749
|
+
while (queue.length > 0) {
|
|
116750
|
+
const next = queue.shift();
|
|
116751
|
+
found.push(next);
|
|
116752
|
+
queue.push(...children.get(next) ?? []);
|
|
116753
|
+
}
|
|
116754
|
+
resolve(found);
|
|
116755
|
+
});
|
|
116756
|
+
});
|
|
116757
|
+
}
|
|
116758
|
+
var defaultDeps = {
|
|
116759
|
+
inspect: inspectProcess,
|
|
116760
|
+
descendants: listDescendants,
|
|
116761
|
+
kill: (pid, signal) => {
|
|
116762
|
+
try {
|
|
116763
|
+
process.kill(pid, signal);
|
|
116764
|
+
} catch {
|
|
116765
|
+
}
|
|
116766
|
+
},
|
|
116767
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
116768
|
+
};
|
|
116769
|
+
var isOrphan = {
|
|
116770
|
+
claude: (info) => info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json"),
|
|
116771
|
+
// The codex launcher (`node …/codex app-server …`) or the binary itself.
|
|
116772
|
+
codex: (info) => info.ppid === 1 && /\bcodex\b/.test(info.command) && /\bapp-server\b/.test(info.command)
|
|
116773
|
+
};
|
|
116774
|
+
async function endProcesses(pids, deps) {
|
|
116775
|
+
for (const pid of pids) deps.kill(pid, "SIGTERM");
|
|
116776
|
+
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
116777
|
+
await deps.sleep(POLL_MS);
|
|
116778
|
+
const alive = await Promise.all(pids.map((pid) => deps.inspect(pid)));
|
|
116779
|
+
if (alive.every((info) => !info)) return;
|
|
116780
|
+
}
|
|
116781
|
+
for (const pid of pids) {
|
|
116782
|
+
if (await deps.inspect(pid)) deps.kill(pid, "SIGKILL");
|
|
116783
|
+
}
|
|
116784
|
+
}
|
|
116785
|
+
function recordCliProcess(db2, pid, sessionId, runtime = "claude") {
|
|
116786
|
+
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, runtime, created_at) VALUES (?, ?, ?, ?)").run(
|
|
116787
|
+
pid,
|
|
116788
|
+
sessionId,
|
|
116789
|
+
runtime,
|
|
116790
|
+
(/* @__PURE__ */ new Date()).toISOString()
|
|
116791
|
+
);
|
|
116792
|
+
}
|
|
116793
|
+
function forgetCliProcess(db2, pid) {
|
|
116794
|
+
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
116795
|
+
}
|
|
116796
|
+
async function reapOrphanProcesses(db2, runtime, deps = defaultDeps) {
|
|
116797
|
+
const rows = db2.prepare("SELECT pid FROM cli_processes WHERE runtime = ?").all(runtime);
|
|
116798
|
+
const ended = await Promise.all(
|
|
116799
|
+
rows.map(async ({ pid }) => {
|
|
116800
|
+
const info = await deps.inspect(pid);
|
|
116801
|
+
if (info?.ppid === process.pid) return false;
|
|
116802
|
+
const orphan = info !== null && isOrphan[runtime](info);
|
|
116803
|
+
if (orphan) {
|
|
116804
|
+
const tree = runtime === "codex" ? await deps.descendants(pid) : [];
|
|
116805
|
+
await endProcesses([...tree, pid], deps);
|
|
116806
|
+
}
|
|
116807
|
+
forgetCliProcess(db2, pid);
|
|
116808
|
+
return orphan;
|
|
116809
|
+
})
|
|
116810
|
+
);
|
|
116811
|
+
return ended.filter(Boolean).length;
|
|
116812
|
+
}
|
|
116813
|
+
function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
116814
|
+
return reapOrphanProcesses(db2, "claude", deps);
|
|
116815
|
+
}
|
|
116816
|
+
|
|
116668
116817
|
// src/codex/codex-provider.ts
|
|
116669
116818
|
var sessionMap = /* @__PURE__ */ new Map();
|
|
116819
|
+
var startingThreads = /* @__PURE__ */ new Map();
|
|
116820
|
+
var ENDED_TURNS_KEPT = 20;
|
|
116821
|
+
function interruptWaitMs() {
|
|
116822
|
+
const ms = Number(process.env.AGENT_PANE_CODEX_INTERRUPT_WAIT_MS);
|
|
116823
|
+
return Number.isFinite(ms) && ms > 0 ? ms : 1e4;
|
|
116824
|
+
}
|
|
116825
|
+
var CODEX_CONTINUE_PROMPT = "Continue from where you left off. Your session was restarted while you were working: a command you started before the restart may have been stopped, or may still be running, so check its outcome before you run it again.";
|
|
116670
116826
|
function setSessionStatus(db2, sessionId, isRunning, status, now, hasUnreviewed = false) {
|
|
116671
116827
|
if (hasUnreviewed) {
|
|
116672
116828
|
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
@@ -116745,50 +116901,290 @@ function autoApproveToolUserInput(client) {
|
|
|
116745
116901
|
return { answers };
|
|
116746
116902
|
});
|
|
116747
116903
|
}
|
|
116748
|
-
|
|
116904
|
+
function trackProcess(pid, sessionId) {
|
|
116905
|
+
if (pid === void 0) return;
|
|
116906
|
+
try {
|
|
116907
|
+
recordCliProcess(getDb(), pid, sessionId, "codex");
|
|
116908
|
+
} catch {
|
|
116909
|
+
}
|
|
116910
|
+
}
|
|
116911
|
+
function untrackProcess(pid) {
|
|
116912
|
+
if (pid === void 0) return;
|
|
116913
|
+
try {
|
|
116914
|
+
forgetCliProcess(getDb(), pid);
|
|
116915
|
+
} catch {
|
|
116916
|
+
}
|
|
116917
|
+
}
|
|
116918
|
+
function getOrCreateThread(session) {
|
|
116749
116919
|
const existing = sessionMap.get(session.id);
|
|
116750
|
-
if (existing) return existing;
|
|
116920
|
+
if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
|
|
116921
|
+
const pending = startingThreads.get(session.id);
|
|
116922
|
+
if (pending) return pending;
|
|
116923
|
+
const started = startThread(session).finally(() => startingThreads.delete(session.id));
|
|
116924
|
+
startingThreads.set(session.id, started);
|
|
116925
|
+
return started;
|
|
116926
|
+
}
|
|
116927
|
+
async function startThread(session) {
|
|
116751
116928
|
const cwd = session.cwd ?? process.cwd();
|
|
116752
116929
|
const client = new AppServerClient(appServerClientOptions(session, cwd));
|
|
116753
|
-
|
|
116754
|
-
|
|
116755
|
-
|
|
116756
|
-
|
|
116757
|
-
|
|
116758
|
-
|
|
116759
|
-
|
|
116760
|
-
|
|
116761
|
-
|
|
116762
|
-
|
|
116763
|
-
|
|
116764
|
-
|
|
116765
|
-
|
|
116766
|
-
|
|
116767
|
-
|
|
116768
|
-
|
|
116769
|
-
}
|
|
116770
|
-
|
|
116771
|
-
|
|
116772
|
-
const
|
|
116773
|
-
|
|
116774
|
-
|
|
116775
|
-
|
|
116776
|
-
|
|
116777
|
-
|
|
116778
|
-
|
|
116779
|
-
|
|
116780
|
-
|
|
116781
|
-
|
|
116782
|
-
|
|
116783
|
-
|
|
116784
|
-
|
|
116785
|
-
|
|
116786
|
-
|
|
116930
|
+
const entry = {
|
|
116931
|
+
sessionId: session.id,
|
|
116932
|
+
client,
|
|
116933
|
+
pid: client.pid,
|
|
116934
|
+
threadId: "",
|
|
116935
|
+
turns: [],
|
|
116936
|
+
ended: /* @__PURE__ */ new Map(),
|
|
116937
|
+
resumedTurnIds: null,
|
|
116938
|
+
closing: null
|
|
116939
|
+
};
|
|
116940
|
+
trackProcess(entry.pid, session.id);
|
|
116941
|
+
listen(entry);
|
|
116942
|
+
try {
|
|
116943
|
+
await client.initialize();
|
|
116944
|
+
if (session.origin_app_id) {
|
|
116945
|
+
autoApproveToolUserInput(client);
|
|
116946
|
+
}
|
|
116947
|
+
const config3 = parseRuntimeConfig(session);
|
|
116948
|
+
const sandbox = sandboxType(config3);
|
|
116949
|
+
const instructions = threadInstructionParams(cwd);
|
|
116950
|
+
if (session.external_thread_id) {
|
|
116951
|
+
const result = await client.request("thread/resume", {
|
|
116952
|
+
threadId: session.external_thread_id,
|
|
116953
|
+
cwd,
|
|
116954
|
+
approvalPolicy: "never",
|
|
116955
|
+
sandbox,
|
|
116956
|
+
model: session.model ?? void 0,
|
|
116957
|
+
...instructions
|
|
116958
|
+
});
|
|
116959
|
+
entry.threadId = result.thread.id;
|
|
116960
|
+
entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
|
|
116961
|
+
} else {
|
|
116962
|
+
const result = await client.request("thread/start", {
|
|
116963
|
+
cwd,
|
|
116964
|
+
approvalPolicy: "never",
|
|
116965
|
+
sandbox,
|
|
116966
|
+
model: session.model ?? void 0,
|
|
116967
|
+
...instructions
|
|
116968
|
+
});
|
|
116969
|
+
entry.threadId = result.thread.id;
|
|
116970
|
+
const db2 = getDb();
|
|
116971
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116972
|
+
db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
|
|
116973
|
+
entry.threadId,
|
|
116974
|
+
now,
|
|
116975
|
+
session.id
|
|
116976
|
+
);
|
|
116977
|
+
}
|
|
116978
|
+
} catch (err) {
|
|
116979
|
+
void retireEntry(entry, "keep");
|
|
116980
|
+
throw err;
|
|
116787
116981
|
}
|
|
116788
|
-
const entry = { client, threadId, turnId: null };
|
|
116789
116982
|
sessionMap.set(session.id, entry);
|
|
116790
116983
|
return entry;
|
|
116791
116984
|
}
|
|
116985
|
+
function retireEntry(entry, left, error51 = "App-server closed") {
|
|
116986
|
+
if (entry.closing) return entry.closing;
|
|
116987
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116988
|
+
if (left !== "keep") {
|
|
116989
|
+
for (const active of [...entry.turns]) {
|
|
116990
|
+
endTurn(entry, active);
|
|
116991
|
+
try {
|
|
116992
|
+
const db2 = getDb();
|
|
116993
|
+
if (left === "cancel") abortTurn(db2, entry.sessionId, active.id);
|
|
116994
|
+
else failTurn(db2, entry.sessionId, active.id, error51);
|
|
116995
|
+
} catch (err) {
|
|
116996
|
+
console.error(`[codex] could not settle turn ${active.id}:`, err.message);
|
|
116997
|
+
}
|
|
116998
|
+
}
|
|
116999
|
+
}
|
|
117000
|
+
entry.closing = entry.client.close().catch(() => {
|
|
117001
|
+
}).finally(() => untrackProcess(entry.pid));
|
|
117002
|
+
return entry.closing;
|
|
117003
|
+
}
|
|
117004
|
+
function onClientClosed(entry, reason) {
|
|
117005
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
117006
|
+
untrackProcess(entry.pid);
|
|
117007
|
+
if (entry.closing || entry.turns.length === 0) return;
|
|
117008
|
+
let db2;
|
|
117009
|
+
try {
|
|
117010
|
+
db2 = getDb();
|
|
117011
|
+
} catch {
|
|
117012
|
+
return;
|
|
117013
|
+
}
|
|
117014
|
+
const detail = `App-server process exited (${reason})`;
|
|
117015
|
+
for (const active of [...entry.turns]) {
|
|
117016
|
+
endTurn(entry, active);
|
|
117017
|
+
failOpenItems(db2, entry.sessionId, active.id);
|
|
117018
|
+
if (active.discussionThreadId) {
|
|
117019
|
+
failTurn(db2, entry.sessionId, active.id, "App-server process closed unexpectedly");
|
|
117020
|
+
} else {
|
|
117021
|
+
markTurnInterrupted(db2, active.id, "process_exit", { detail });
|
|
117022
|
+
}
|
|
117023
|
+
}
|
|
117024
|
+
}
|
|
117025
|
+
function isTurnLive(db2, turnId) {
|
|
117026
|
+
const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
|
|
117027
|
+
return row?.status === "pending" || row?.status === "running";
|
|
117028
|
+
}
|
|
117029
|
+
function endTurn(entry, active) {
|
|
117030
|
+
active.done = true;
|
|
117031
|
+
entry.turns = entry.turns.filter((t) => t !== active);
|
|
117032
|
+
rememberEnded(entry, active);
|
|
117033
|
+
}
|
|
117034
|
+
function rememberEnded(entry, active) {
|
|
117035
|
+
if (!active.codexId) return;
|
|
117036
|
+
entry.ended.set(active.codexId, active.id);
|
|
117037
|
+
if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
|
|
117038
|
+
}
|
|
117039
|
+
function liveTurnsOf(entry, codexId) {
|
|
117040
|
+
if (!codexId) return entry.turns.slice(-1);
|
|
117041
|
+
const known = entry.turns.filter((t) => t.codexId === codexId);
|
|
117042
|
+
if (known.length > 0 || entry.ended.has(codexId)) return known;
|
|
117043
|
+
const waiting = entry.turns.find((t) => t.codexId === null);
|
|
117044
|
+
if (!waiting) return [];
|
|
117045
|
+
waiting.codexId = codexId;
|
|
117046
|
+
return [waiting];
|
|
117047
|
+
}
|
|
117048
|
+
function noteContinued(active) {
|
|
117049
|
+
if (!active.resuming) return;
|
|
117050
|
+
active.resuming = false;
|
|
117051
|
+
markTurnResumed(getDb(), active.id);
|
|
117052
|
+
}
|
|
117053
|
+
function completeTurn(db2, sessionId, turnId, usage) {
|
|
117054
|
+
markTurnResumed(db2, turnId, { settle: true });
|
|
117055
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117056
|
+
const response = turnResponse(db2, turnId);
|
|
117057
|
+
const result = usage !== void 0 ? db2.prepare(
|
|
117058
|
+
"UPDATE turns SET status = 'completed', token_usage = ?, updated_at = ? WHERE id = ? AND status IN ('pending', 'running')"
|
|
117059
|
+
).run(JSON.stringify(usage), now, turnId) : db2.prepare("UPDATE turns SET status = 'completed', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(now, turnId);
|
|
117060
|
+
if (result.changes === 0) return;
|
|
117061
|
+
broadcast("turn:completed", {
|
|
117062
|
+
sessionId,
|
|
117063
|
+
turnId,
|
|
117064
|
+
...usage !== void 0 ? { usage } : {},
|
|
117065
|
+
hasUnreviewed: true,
|
|
117066
|
+
response
|
|
117067
|
+
});
|
|
117068
|
+
recomputeSessionRunning(db2, sessionId, "active", true);
|
|
117069
|
+
syncThreadTitle(sessionId);
|
|
117070
|
+
}
|
|
117071
|
+
function failTurn(db2, sessionId, turnId, error51) {
|
|
117072
|
+
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117073
|
+
if (!row || row.status !== "pending" && row.status !== "running") return;
|
|
117074
|
+
if (row.resume_state === "waiting" || row.resume_state === "resuming") {
|
|
117075
|
+
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
117076
|
+
}
|
|
117077
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117078
|
+
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run("failed", error51, now, turnId);
|
|
117079
|
+
recomputeSessionRunning(db2, sessionId, "failed");
|
|
117080
|
+
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
117081
|
+
}
|
|
117082
|
+
function abortTurn(db2, sessionId, turnId) {
|
|
117083
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117084
|
+
const result = db2.prepare("UPDATE turns SET status = 'aborted', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(now, turnId);
|
|
117085
|
+
if (result.changes === 0) return false;
|
|
117086
|
+
markResumeCancelled(db2, turnId);
|
|
117087
|
+
recomputeSessionRunning(db2, sessionId);
|
|
117088
|
+
broadcast("turn:cancelled", { sessionId, turnId });
|
|
117089
|
+
return true;
|
|
117090
|
+
}
|
|
117091
|
+
function cancelTurn(entry, active) {
|
|
117092
|
+
if (active.done) return;
|
|
117093
|
+
endTurn(entry, active);
|
|
117094
|
+
abortTurn(getDb(), entry.sessionId, active.id);
|
|
117095
|
+
}
|
|
117096
|
+
function failOpenItems(db2, sessionId, turnId) {
|
|
117097
|
+
const rows = db2.prepare(
|
|
117098
|
+
"SELECT id, external_item_id, type, data, created_at FROM items WHERE turn_id = ? AND status = 'in_progress'"
|
|
117099
|
+
).all(turnId);
|
|
117100
|
+
if (rows.length === 0) return;
|
|
117101
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117102
|
+
db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE turn_id = ? AND status = 'in_progress'").run(
|
|
117103
|
+
now,
|
|
117104
|
+
turnId
|
|
117105
|
+
);
|
|
117106
|
+
for (const row of rows) {
|
|
117107
|
+
const item = {
|
|
117108
|
+
id: row.id,
|
|
117109
|
+
turn_id: turnId,
|
|
117110
|
+
external_item_id: row.external_item_id,
|
|
117111
|
+
type: row.type,
|
|
117112
|
+
data: row.data ? JSON.parse(row.data) : {},
|
|
117113
|
+
status: "failed",
|
|
117114
|
+
created_at: row.created_at,
|
|
117115
|
+
updated_at: now
|
|
117116
|
+
};
|
|
117117
|
+
broadcast("item:completed", { sessionId, turnId, item });
|
|
117118
|
+
}
|
|
117119
|
+
}
|
|
117120
|
+
function listen(entry) {
|
|
117121
|
+
const on = (method, handle) => {
|
|
117122
|
+
entry.client.onNotification(method, (params) => {
|
|
117123
|
+
const p = params;
|
|
117124
|
+
if (!p || p.threadId !== entry.threadId) return;
|
|
117125
|
+
handle(p);
|
|
117126
|
+
});
|
|
117127
|
+
};
|
|
117128
|
+
on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
|
|
117129
|
+
on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
|
|
117130
|
+
on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
|
|
117131
|
+
on("item/agentMessage/delta", (p) => onAgentMessageDelta(entry, p));
|
|
117132
|
+
on("turn/completed", (p) => onTurnCompleted(entry, p));
|
|
117133
|
+
on("turn/failed", (p) => onTurnFailed(entry, p));
|
|
117134
|
+
on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
|
|
117135
|
+
entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
|
|
117136
|
+
}
|
|
117137
|
+
function onItem(entry, p, status, event) {
|
|
117138
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117139
|
+
if (live) {
|
|
117140
|
+
if (!shouldSkipItem(p.item.type)) noteContinued(live);
|
|
117141
|
+
handleItemEvent(p, entry.sessionId, live.id, status, event);
|
|
117142
|
+
return;
|
|
117143
|
+
}
|
|
117144
|
+
const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
|
|
117145
|
+
if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
|
|
117146
|
+
}
|
|
117147
|
+
function onAgentMessageDelta(entry, p) {
|
|
117148
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117149
|
+
if (!live) return;
|
|
117150
|
+
noteContinued(live);
|
|
117151
|
+
broadcast("item:delta", {
|
|
117152
|
+
sessionId: entry.sessionId,
|
|
117153
|
+
turnId: live.id,
|
|
117154
|
+
itemId: p.itemId,
|
|
117155
|
+
delta: p.delta
|
|
117156
|
+
});
|
|
117157
|
+
}
|
|
117158
|
+
function onTurnCompleted(entry, p) {
|
|
117159
|
+
const db2 = getDb();
|
|
117160
|
+
for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
|
|
117161
|
+
if (p.turn?.status === "interrupted") {
|
|
117162
|
+
cancelTurn(entry, live);
|
|
117163
|
+
} else if (p.turn?.status === "failed") {
|
|
117164
|
+
endTurn(entry, live);
|
|
117165
|
+
failTurn(db2, entry.sessionId, live.id, p.turn.error?.message ?? "Codex turn failed");
|
|
117166
|
+
} else {
|
|
117167
|
+
endTurn(entry, live);
|
|
117168
|
+
completeTurn(db2, entry.sessionId, live.id, p.usage);
|
|
117169
|
+
}
|
|
117170
|
+
}
|
|
117171
|
+
}
|
|
117172
|
+
function onTurnFailed(entry, p) {
|
|
117173
|
+
const db2 = getDb();
|
|
117174
|
+
for (const live of liveTurnsOf(entry, p.turnId)) {
|
|
117175
|
+
endTurn(entry, live);
|
|
117176
|
+
failTurn(db2, entry.sessionId, live.id, p.error.message);
|
|
117177
|
+
}
|
|
117178
|
+
}
|
|
117179
|
+
function onTokenUsage(entry, p) {
|
|
117180
|
+
const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
|
|
117181
|
+
if (!turnId) return;
|
|
117182
|
+
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
117183
|
+
const db2 = getDb();
|
|
117184
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117185
|
+
db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
|
|
117186
|
+
broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
|
|
117187
|
+
}
|
|
116792
117188
|
function turnAttachments2(turn) {
|
|
116793
117189
|
const raw = turn.attachments;
|
|
116794
117190
|
if (!raw) return [];
|
|
@@ -116822,175 +117218,63 @@ ${decoded}
|
|
|
116822
117218
|
}
|
|
116823
117219
|
return input;
|
|
116824
117220
|
}
|
|
117221
|
+
async function runTurn(session, turn, entry, input, resume) {
|
|
117222
|
+
const db2 = getDb();
|
|
117223
|
+
const sandbox = sandboxType(parseRuntimeConfig(session));
|
|
117224
|
+
let resolveStarted;
|
|
117225
|
+
const active = {
|
|
117226
|
+
id: turn.id,
|
|
117227
|
+
discussionThreadId: turn.thread_id ?? null,
|
|
117228
|
+
codexId: null,
|
|
117229
|
+
started: new Promise((resolve) => {
|
|
117230
|
+
resolveStarted = resolve;
|
|
117231
|
+
}),
|
|
117232
|
+
done: false,
|
|
117233
|
+
resuming: resume
|
|
117234
|
+
};
|
|
117235
|
+
entry.turns.push(active);
|
|
117236
|
+
try {
|
|
117237
|
+
const result = await entry.client.request("turn/start", {
|
|
117238
|
+
threadId: entry.threadId,
|
|
117239
|
+
input,
|
|
117240
|
+
approvalPolicy: "never",
|
|
117241
|
+
sandbox: { type: sandbox },
|
|
117242
|
+
model: session.model ?? void 0,
|
|
117243
|
+
effort: session.model_reasoning_effort ?? void 0
|
|
117244
|
+
});
|
|
117245
|
+
active.codexId = result.turn.id;
|
|
117246
|
+
if (active.done) rememberEnded(entry, active);
|
|
117247
|
+
db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
|
|
117248
|
+
result.turn.id,
|
|
117249
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
117250
|
+
turn.id
|
|
117251
|
+
);
|
|
117252
|
+
resolveStarted(result.turn.id);
|
|
117253
|
+
} catch (err) {
|
|
117254
|
+
const message = err.message;
|
|
117255
|
+
const settled = active.done;
|
|
117256
|
+
endTurn(entry, active);
|
|
117257
|
+
if (!message.startsWith("JSON-RPC error")) void retireEntry(entry, "fail", message);
|
|
117258
|
+
if (!settled && !resume) failTurn(db2, session.id, turn.id, message);
|
|
117259
|
+
resolveStarted(null);
|
|
117260
|
+
if (!settled && resume) throw err;
|
|
117261
|
+
}
|
|
117262
|
+
}
|
|
116825
117263
|
async function startTurn2(session, turn) {
|
|
116826
117264
|
const db2 = getDb();
|
|
116827
117265
|
let entry;
|
|
116828
117266
|
try {
|
|
116829
117267
|
entry = await getOrCreateThread(session);
|
|
116830
117268
|
} catch (err) {
|
|
116831
|
-
|
|
116832
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116833
|
-
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116834
|
-
"failed",
|
|
116835
|
-
errMsg,
|
|
116836
|
-
now2,
|
|
116837
|
-
turn.id
|
|
116838
|
-
);
|
|
116839
|
-
recomputeSessionRunning(db2, session.id, "failed");
|
|
116840
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
117269
|
+
failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
|
|
116841
117270
|
return;
|
|
116842
117271
|
}
|
|
116843
|
-
|
|
117272
|
+
if (!isTurnLive(db2, turn.id)) return;
|
|
116844
117273
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116845
117274
|
db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
|
|
116846
117275
|
setSessionStatus(db2, session.id, 1, "running", now);
|
|
116847
117276
|
broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
|
|
116848
|
-
|
|
116849
|
-
const config3 = parseRuntimeConfig(session);
|
|
116850
|
-
const sandbox = sandboxType(config3);
|
|
116851
|
-
let turnDone = false;
|
|
116852
|
-
const handleItemStarted = (params) => {
|
|
116853
|
-
if (turnDone) return;
|
|
116854
|
-
const p = params;
|
|
116855
|
-
if (p.threadId !== threadId) return;
|
|
116856
|
-
handleItemEvent(p, session.id, turn.id, "in_progress", "item:started");
|
|
116857
|
-
};
|
|
116858
|
-
const handleItemUpdated = (params) => {
|
|
116859
|
-
if (turnDone) return;
|
|
116860
|
-
const p = params;
|
|
116861
|
-
if (p.threadId !== threadId) return;
|
|
116862
|
-
handleItemEvent(p, session.id, turn.id, "in_progress", "item:updated");
|
|
116863
|
-
};
|
|
116864
|
-
const handleItemCompleted = (params) => {
|
|
116865
|
-
if (turnDone) return;
|
|
116866
|
-
const p = params;
|
|
116867
|
-
if (p.threadId !== threadId) return;
|
|
116868
|
-
const status = getItemStatus(p.item);
|
|
116869
|
-
handleItemEvent(p, session.id, turn.id, status, "item:completed");
|
|
116870
|
-
};
|
|
116871
|
-
const handleTurnCompleted = (params) => {
|
|
116872
|
-
if (turnDone) return;
|
|
116873
|
-
const p = params;
|
|
116874
|
-
if (p.threadId !== threadId) return;
|
|
116875
|
-
turnDone = true;
|
|
116876
|
-
const db3 = getDb();
|
|
116877
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116878
|
-
if (p.turn?.status === "failed") {
|
|
116879
|
-
const errMsg = p.turn.error?.message ?? "Codex turn failed";
|
|
116880
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116881
|
-
"failed",
|
|
116882
|
-
errMsg,
|
|
116883
|
-
now2,
|
|
116884
|
-
turn.id
|
|
116885
|
-
);
|
|
116886
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116887
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
116888
|
-
return;
|
|
116889
|
-
}
|
|
116890
|
-
const response = turnResponse(db3, turn.id);
|
|
116891
|
-
if (p.usage !== void 0) {
|
|
116892
|
-
db3.prepare("UPDATE turns SET status = ?, token_usage = ?, updated_at = ? WHERE id = ?").run(
|
|
116893
|
-
"completed",
|
|
116894
|
-
JSON.stringify(p.usage),
|
|
116895
|
-
now2,
|
|
116896
|
-
turn.id
|
|
116897
|
-
);
|
|
116898
|
-
broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, usage: p.usage, hasUnreviewed: true, response });
|
|
116899
|
-
} else {
|
|
116900
|
-
db3.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("completed", now2, turn.id);
|
|
116901
|
-
broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, hasUnreviewed: true, response });
|
|
116902
|
-
}
|
|
116903
|
-
recomputeSessionRunning(db3, session.id, "active", true);
|
|
116904
|
-
syncThreadTitle(session.id);
|
|
116905
|
-
};
|
|
116906
|
-
const handleTurnFailed = (params) => {
|
|
116907
|
-
if (turnDone) return;
|
|
116908
|
-
const p = params;
|
|
116909
|
-
if (p.threadId !== threadId) return;
|
|
116910
|
-
turnDone = true;
|
|
116911
|
-
const db3 = getDb();
|
|
116912
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116913
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116914
|
-
"failed",
|
|
116915
|
-
p.error.message,
|
|
116916
|
-
now2,
|
|
116917
|
-
turn.id
|
|
116918
|
-
);
|
|
116919
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116920
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: p.error.message });
|
|
116921
|
-
};
|
|
116922
|
-
const handleAgentMessageDelta = (params) => {
|
|
116923
|
-
if (turnDone) return;
|
|
116924
|
-
const p = params;
|
|
116925
|
-
if (p.threadId !== threadId) return;
|
|
116926
|
-
broadcast("item:delta", {
|
|
116927
|
-
sessionId: session.id,
|
|
116928
|
-
turnId: turn.id,
|
|
116929
|
-
itemId: p.itemId,
|
|
116930
|
-
delta: p.delta
|
|
116931
|
-
});
|
|
116932
|
-
};
|
|
116933
|
-
const handleTokenUsageUpdated = (params) => {
|
|
116934
|
-
const p = params;
|
|
116935
|
-
if (p.threadId !== threadId) return;
|
|
116936
|
-
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
116937
|
-
const db3 = getDb();
|
|
116938
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116939
|
-
db3.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(
|
|
116940
|
-
JSON.stringify(usage),
|
|
116941
|
-
now2,
|
|
116942
|
-
turn.id
|
|
116943
|
-
);
|
|
116944
|
-
broadcast("turn:tokenUsage", { sessionId: session.id, turnId: turn.id, usage });
|
|
116945
|
-
};
|
|
116946
|
-
client.onNotification("item/started", handleItemStarted);
|
|
116947
|
-
client.onNotification("item/updated", handleItemUpdated);
|
|
116948
|
-
client.onNotification("item/completed", handleItemCompleted);
|
|
116949
|
-
client.onNotification("item/agentMessage/delta", handleAgentMessageDelta);
|
|
116950
|
-
client.onNotification("turn/completed", handleTurnCompleted);
|
|
116951
|
-
client.onNotification("turn/failed", handleTurnFailed);
|
|
116952
|
-
client.onNotification("thread/tokenUsage/updated", handleTokenUsageUpdated);
|
|
116953
|
-
try {
|
|
116954
|
-
await client.request("turn/start", {
|
|
116955
|
-
threadId,
|
|
116956
|
-
input: buildCodexInput(turn),
|
|
116957
|
-
approvalPolicy: "never",
|
|
116958
|
-
sandbox: { type: sandbox },
|
|
116959
|
-
model: session.model ?? void 0,
|
|
116960
|
-
effort: session.model_reasoning_effort ?? void 0
|
|
116961
|
-
});
|
|
116962
|
-
client.events.once("closed", () => {
|
|
116963
|
-
const db3 = getDb();
|
|
116964
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116965
|
-
const currentTurn = db3.prepare("SELECT status FROM turns WHERE id = ?").get(turn.id);
|
|
116966
|
-
if (currentTurn && currentTurn.status === "running") {
|
|
116967
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116968
|
-
"failed",
|
|
116969
|
-
"App-server process closed unexpectedly",
|
|
116970
|
-
now2,
|
|
116971
|
-
turn.id
|
|
116972
|
-
);
|
|
116973
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116974
|
-
broadcast("turn:failed", {
|
|
116975
|
-
sessionId: session.id,
|
|
116976
|
-
turnId: turn.id,
|
|
116977
|
-
error: "App-server process closed unexpectedly"
|
|
116978
|
-
});
|
|
116979
|
-
}
|
|
116980
|
-
});
|
|
116981
|
-
} catch (err) {
|
|
116982
|
-
const errMsg = err.message;
|
|
116983
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116984
|
-
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116985
|
-
"failed",
|
|
116986
|
-
errMsg,
|
|
116987
|
-
now2,
|
|
116988
|
-
turn.id
|
|
116989
|
-
);
|
|
116990
|
-
recomputeSessionRunning(db2, session.id, "failed");
|
|
116991
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
116992
|
-
turnDone = true;
|
|
116993
|
-
}
|
|
117277
|
+
await runTurn(session, turn, entry, buildCodexInput(turn), false);
|
|
116994
117278
|
}
|
|
116995
117279
|
function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
116996
117280
|
const db2 = getDb();
|
|
@@ -117038,39 +117322,99 @@ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
|
117038
117322
|
};
|
|
117039
117323
|
broadcast(broadcastEvent, { sessionId, turnId, item: wsItem });
|
|
117040
117324
|
}
|
|
117041
|
-
|
|
117042
|
-
|
|
117043
|
-
|
|
117325
|
+
function within(promise2, ms) {
|
|
117326
|
+
return new Promise((resolve) => {
|
|
117327
|
+
const timer2 = setTimeout(() => resolve(null), ms);
|
|
117328
|
+
timer2.unref?.();
|
|
117329
|
+
promise2.then(
|
|
117330
|
+
(value) => {
|
|
117331
|
+
clearTimeout(timer2);
|
|
117332
|
+
resolve(value);
|
|
117333
|
+
},
|
|
117334
|
+
() => {
|
|
117335
|
+
clearTimeout(timer2);
|
|
117336
|
+
resolve(null);
|
|
117337
|
+
}
|
|
117338
|
+
);
|
|
117339
|
+
});
|
|
117340
|
+
}
|
|
117341
|
+
function turnToStop(entry, threadId) {
|
|
117342
|
+
if (threadId) return entry.turns.find((t) => t.discussionThreadId === threadId);
|
|
117343
|
+
return entry.turns.find((t) => !t.discussionThreadId) ?? entry.turns[0];
|
|
117344
|
+
}
|
|
117345
|
+
function abortOrphanTurn(sessionId, threadId) {
|
|
117044
117346
|
try {
|
|
117045
|
-
await entry.client.request("turn/interrupt", {
|
|
117046
|
-
threadId: entry.threadId,
|
|
117047
|
-
turnId: entry.turnId
|
|
117048
|
-
});
|
|
117049
117347
|
const db2 = getDb();
|
|
117050
|
-
const
|
|
117051
|
-
|
|
117052
|
-
|
|
117053
|
-
|
|
117054
|
-
entry.turnId = null;
|
|
117055
|
-
return true;
|
|
117348
|
+
const orphan = db2.prepare(
|
|
117349
|
+
`SELECT id FROM turns WHERE session_id = ? ${threadId ? "AND thread_id = ?" : ""} AND status IN ('pending', 'running') ORDER BY created_at DESC LIMIT 1`
|
|
117350
|
+
).get(...threadId ? [sessionId, threadId] : [sessionId]);
|
|
117351
|
+
return orphan ? abortTurn(db2, sessionId, orphan.id) : false;
|
|
117056
117352
|
} catch {
|
|
117057
117353
|
return false;
|
|
117058
117354
|
}
|
|
117059
117355
|
}
|
|
117060
|
-
|
|
117356
|
+
var END_COMMANDS_WAIT_MS = 5e3;
|
|
117357
|
+
async function endTurnCommands(entry, turnId) {
|
|
117358
|
+
try {
|
|
117359
|
+
const rows = getDb().prepare(
|
|
117360
|
+
"SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
|
|
117361
|
+
).all(turnId);
|
|
117362
|
+
const started = new Set(rows.map((row) => row.id));
|
|
117363
|
+
if (started.size === 0) return;
|
|
117364
|
+
let cursor = null;
|
|
117365
|
+
do {
|
|
117366
|
+
const page = await entry.client.request("thread/backgroundTerminals/list", {
|
|
117367
|
+
threadId: entry.threadId,
|
|
117368
|
+
cursor
|
|
117369
|
+
});
|
|
117370
|
+
for (const terminal of page.data) {
|
|
117371
|
+
if (!started.has(terminal.itemId)) continue;
|
|
117372
|
+
await entry.client.request("thread/backgroundTerminals/terminate", {
|
|
117373
|
+
threadId: entry.threadId,
|
|
117374
|
+
processId: terminal.processId
|
|
117375
|
+
});
|
|
117376
|
+
}
|
|
117377
|
+
cursor = page.nextCursor;
|
|
117378
|
+
} while (cursor);
|
|
117379
|
+
} catch (err) {
|
|
117380
|
+
console.warn(`[codex] could not end the commands of stopped turn ${turnId}: ${err.message}`);
|
|
117381
|
+
}
|
|
117382
|
+
}
|
|
117383
|
+
async function interruptTurn(sessionId, threadId) {
|
|
117061
117384
|
const entry = sessionMap.get(sessionId);
|
|
117062
|
-
|
|
117063
|
-
|
|
117064
|
-
|
|
117065
|
-
|
|
117385
|
+
const target = entry ? turnToStop(entry, threadId) : void 0;
|
|
117386
|
+
if (entry && target) {
|
|
117387
|
+
const codexId = target.codexId ?? await within(target.started, interruptWaitMs());
|
|
117388
|
+
let stopped = false;
|
|
117389
|
+
if (codexId && !target.done) {
|
|
117390
|
+
try {
|
|
117391
|
+
await entry.client.request("turn/interrupt", {
|
|
117392
|
+
threadId: entry.threadId,
|
|
117393
|
+
turnId: codexId
|
|
117394
|
+
});
|
|
117395
|
+
stopped = true;
|
|
117396
|
+
} catch (err) {
|
|
117397
|
+
console.warn(`[codex] turn/interrupt failed for turn ${target.id}: ${err.message}`);
|
|
117398
|
+
}
|
|
117399
|
+
}
|
|
117400
|
+
const live = !target.done;
|
|
117401
|
+
if (live) {
|
|
117402
|
+
cancelTurn(entry, target);
|
|
117403
|
+
if (!stopped) void retireEntry(entry, "fail");
|
|
117404
|
+
}
|
|
117405
|
+
if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
|
|
117406
|
+
if (live || stopped) return true;
|
|
117066
117407
|
}
|
|
117408
|
+
return abortOrphanTurn(sessionId, threadId);
|
|
117409
|
+
}
|
|
117410
|
+
function clearThread(sessionId) {
|
|
117411
|
+
const entry = sessionMap.get(sessionId);
|
|
117412
|
+
if (entry) void retireEntry(entry, "cancel");
|
|
117067
117413
|
}
|
|
117068
117414
|
function clearAllThreads() {
|
|
117069
|
-
for (const
|
|
117070
|
-
entry.client.close().catch(() => {
|
|
117071
|
-
});
|
|
117072
|
-
}
|
|
117415
|
+
for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
|
|
117073
117416
|
sessionMap.clear();
|
|
117417
|
+
startingThreads.clear();
|
|
117074
117418
|
titleGenerating.clear();
|
|
117075
117419
|
}
|
|
117076
117420
|
var titleGenerating = /* @__PURE__ */ new Set();
|
|
@@ -117250,8 +117594,42 @@ async function getModels() {
|
|
|
117250
117594
|
}
|
|
117251
117595
|
}
|
|
117252
117596
|
async function shutdown() {
|
|
117253
|
-
|
|
117254
|
-
|
|
117597
|
+
let db2 = null;
|
|
117598
|
+
try {
|
|
117599
|
+
db2 = getDb();
|
|
117600
|
+
} catch {
|
|
117601
|
+
db2 = null;
|
|
117602
|
+
}
|
|
117603
|
+
const closing = [closeSharedAppServer()];
|
|
117604
|
+
for (const entry of [...sessionMap.values()]) {
|
|
117605
|
+
for (const active of [...entry.turns]) {
|
|
117606
|
+
if (active.discussionThreadId) continue;
|
|
117607
|
+
endTurn(entry, active);
|
|
117608
|
+
if (!db2) continue;
|
|
117609
|
+
try {
|
|
117610
|
+
markTurnInterrupted(db2, active.id, "host_shutdown", { notify: false });
|
|
117611
|
+
} catch (err) {
|
|
117612
|
+
console.error("[codex] could not park turn for resume:", err.message);
|
|
117613
|
+
}
|
|
117614
|
+
}
|
|
117615
|
+
closing.push(retireEntry(entry, "keep"));
|
|
117616
|
+
}
|
|
117617
|
+
await Promise.all(closing);
|
|
117618
|
+
titleGenerating.clear();
|
|
117619
|
+
}
|
|
117620
|
+
async function reapOrphans() {
|
|
117621
|
+
const ended = await reapOrphanProcesses(getDb(), "codex");
|
|
117622
|
+
if (ended > 0) console.log(`[codex] ended ${ended} app-server(s) left by the previous host`);
|
|
117623
|
+
}
|
|
117624
|
+
async function resumeInterruptedTurn(session, turn, _opts) {
|
|
117625
|
+
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
117626
|
+
const entry = await getOrCreateThread(session);
|
|
117627
|
+
if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
|
|
117628
|
+
if (!isTurnLive(getDb(), turn.id)) return;
|
|
117629
|
+
const codexId = turn.external_turn_id;
|
|
117630
|
+
const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
|
|
117631
|
+
const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
|
|
117632
|
+
await runTurn(session, turn, entry, input, true);
|
|
117255
117633
|
}
|
|
117256
117634
|
var codexProvider = {
|
|
117257
117635
|
startTurn: startTurn2,
|
|
@@ -117260,6 +117638,8 @@ var codexProvider = {
|
|
|
117260
117638
|
clearAllThreads,
|
|
117261
117639
|
getModels,
|
|
117262
117640
|
summarizeThread: summarizeCodexThread,
|
|
117641
|
+
resumeInterruptedTurn,
|
|
117642
|
+
reapOrphans,
|
|
117263
117643
|
shutdown
|
|
117264
117644
|
};
|
|
117265
117645
|
|
|
@@ -117591,64 +117971,6 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
|
|
|
117591
117971
|
return "fatal";
|
|
117592
117972
|
}
|
|
117593
117973
|
|
|
117594
|
-
// src/claude/cli-orphans.ts
|
|
117595
|
-
import { execFile as execFile3 } from "node:child_process";
|
|
117596
|
-
var TERM_GRACE_MS = 2e3;
|
|
117597
|
-
var POLL_MS = 100;
|
|
117598
|
-
function inspectProcess(pid) {
|
|
117599
|
-
return new Promise((resolve) => {
|
|
117600
|
-
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
117601
|
-
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
117602
|
-
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
117603
|
-
});
|
|
117604
|
-
});
|
|
117605
|
-
}
|
|
117606
|
-
var defaultDeps = {
|
|
117607
|
-
inspect: inspectProcess,
|
|
117608
|
-
kill: (pid, signal) => {
|
|
117609
|
-
try {
|
|
117610
|
-
process.kill(pid, signal);
|
|
117611
|
-
} catch {
|
|
117612
|
-
}
|
|
117613
|
-
},
|
|
117614
|
-
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
117615
|
-
};
|
|
117616
|
-
function isOrphanCli(info) {
|
|
117617
|
-
return info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json");
|
|
117618
|
-
}
|
|
117619
|
-
async function endProcess(pid, deps) {
|
|
117620
|
-
deps.kill(pid, "SIGTERM");
|
|
117621
|
-
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
117622
|
-
await deps.sleep(POLL_MS);
|
|
117623
|
-
if (!await deps.inspect(pid)) return;
|
|
117624
|
-
}
|
|
117625
|
-
deps.kill(pid, "SIGKILL");
|
|
117626
|
-
}
|
|
117627
|
-
function recordCliProcess(db2, pid, sessionId) {
|
|
117628
|
-
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, created_at) VALUES (?, ?, ?)").run(
|
|
117629
|
-
pid,
|
|
117630
|
-
sessionId,
|
|
117631
|
-
(/* @__PURE__ */ new Date()).toISOString()
|
|
117632
|
-
);
|
|
117633
|
-
}
|
|
117634
|
-
function forgetCliProcess(db2, pid) {
|
|
117635
|
-
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
117636
|
-
}
|
|
117637
|
-
async function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
117638
|
-
const rows = db2.prepare("SELECT pid FROM cli_processes").all();
|
|
117639
|
-
const ended = await Promise.all(
|
|
117640
|
-
rows.map(async ({ pid }) => {
|
|
117641
|
-
const info = await deps.inspect(pid);
|
|
117642
|
-
if (info?.ppid === process.pid) return false;
|
|
117643
|
-
const orphan = info !== null && isOrphanCli(info);
|
|
117644
|
-
if (orphan) await endProcess(pid, deps);
|
|
117645
|
-
forgetCliProcess(db2, pid);
|
|
117646
|
-
return orphan;
|
|
117647
|
-
})
|
|
117648
|
-
);
|
|
117649
|
-
return ended.filter(Boolean).length;
|
|
117650
|
-
}
|
|
117651
|
-
|
|
117652
117974
|
// src/claude/claude-provider.ts
|
|
117653
117975
|
var PromptQueue = class {
|
|
117654
117976
|
buffer = [];
|
|
@@ -117865,7 +118187,7 @@ function trackResumeFrame(entry, message, db2) {
|
|
|
117865
118187
|
}
|
|
117866
118188
|
return true;
|
|
117867
118189
|
}
|
|
117868
|
-
function
|
|
118190
|
+
function failTurn2(db2, sessionId, turnId, error51) {
|
|
117869
118191
|
const row = db2.prepare("SELECT resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117870
118192
|
if (row?.resume_state === "waiting" || row?.resume_state === "resuming") {
|
|
117871
118193
|
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
@@ -117888,7 +118210,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
|
|
|
117888
118210
|
if (!entry.threadId && !entry.closeReason && isSignalExit(errMsg)) {
|
|
117889
118211
|
markTurnInterrupted(db2, turnId, "process_exit", { detail: errMsg });
|
|
117890
118212
|
} else {
|
|
117891
|
-
|
|
118213
|
+
failTurn2(db2, sessionId, turnId, errMsg);
|
|
117892
118214
|
}
|
|
117893
118215
|
}
|
|
117894
118216
|
if (staleItems.changes > 0) {
|
|
@@ -117987,7 +118309,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
117987
118309
|
const currentTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
117988
118310
|
if (currentTurn && currentTurn.status === "running") {
|
|
117989
118311
|
const usage = currentTurn.token_usage ? JSON.parse(currentTurn.token_usage) : null;
|
|
117990
|
-
|
|
118312
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
117991
118313
|
}
|
|
117992
118314
|
syncThreadTitle2(session.id);
|
|
117993
118315
|
}
|
|
@@ -118053,7 +118375,7 @@ async function startTurn3(session, turn) {
|
|
|
118053
118375
|
const prevTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
118054
118376
|
if (prevTurn && prevTurn.status === "running") {
|
|
118055
118377
|
const usage = prevTurn.token_usage ? JSON.parse(prevTurn.token_usage) : null;
|
|
118056
|
-
|
|
118378
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
118057
118379
|
}
|
|
118058
118380
|
syncThreadTitle2(session.id);
|
|
118059
118381
|
streamingMessageIds.delete(entry.turnId);
|
|
@@ -118529,8 +118851,7 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118529
118851
|
entry.lastApiError = null;
|
|
118530
118852
|
if (message.is_error) {
|
|
118531
118853
|
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
118532
|
-
if (row
|
|
118533
|
-
if (row.status === "pending" && row.resume_state === "waiting") return;
|
|
118854
|
+
if (!row || row.status === "pending" && row.resume_state === "waiting") return;
|
|
118534
118855
|
const text2 = (message.result || apiError?.text || "Claude API error").trim();
|
|
118535
118856
|
const kind = classifyApiError({
|
|
118536
118857
|
error: apiError?.error,
|
|
@@ -118539,21 +118860,27 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118539
118860
|
limitRejected: entry.rateLimit?.status === "rejected"
|
|
118540
118861
|
});
|
|
118541
118862
|
const resumeAt = kind === "usage_limit" ? usageLimitResumeAt(entry.rateLimit?.resetsAt) : null;
|
|
118863
|
+
if (row.status !== "pending" && row.status !== "running") {
|
|
118864
|
+
if (kind === "usage_limit" && resumeAt && !entry.threadId) {
|
|
118865
|
+
markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt, reopen: true });
|
|
118866
|
+
}
|
|
118867
|
+
return;
|
|
118868
|
+
}
|
|
118542
118869
|
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
|
|
118543
118870
|
return;
|
|
118544
118871
|
}
|
|
118545
|
-
|
|
118872
|
+
failTurn2(db2, sessionId, turnId, text2);
|
|
118546
118873
|
return;
|
|
118547
118874
|
}
|
|
118548
118875
|
await refreshContext(entry, sessionId, db2);
|
|
118549
|
-
|
|
118876
|
+
completeTurn2(db2, sessionId, turnId, usage);
|
|
118550
118877
|
} else {
|
|
118551
118878
|
entry.lastApiError = null;
|
|
118552
118879
|
const errorMsg = message.errors?.join("; ") || "Claude turn failed";
|
|
118553
|
-
|
|
118880
|
+
failTurn2(db2, sessionId, turnId, errorMsg);
|
|
118554
118881
|
}
|
|
118555
118882
|
}
|
|
118556
|
-
function
|
|
118883
|
+
function completeTurn2(db2, sessionId, turnId, usage) {
|
|
118557
118884
|
markTurnResumed(db2, turnId, { settle: true });
|
|
118558
118885
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
118559
118886
|
const response = turnResponse(db2, turnId);
|
|
@@ -118836,7 +119163,7 @@ async function shutdown2() {
|
|
|
118836
119163
|
}
|
|
118837
119164
|
clearAllThreads2();
|
|
118838
119165
|
}
|
|
118839
|
-
async function
|
|
119166
|
+
async function reapOrphans2() {
|
|
118840
119167
|
const ended = await reapOrphanCliProcesses(getDb());
|
|
118841
119168
|
if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
|
|
118842
119169
|
}
|
|
@@ -118849,7 +119176,7 @@ function retireCli(sessionId, entry) {
|
|
|
118849
119176
|
entry.query.close();
|
|
118850
119177
|
sessionMap2.delete(sessionId);
|
|
118851
119178
|
}
|
|
118852
|
-
async function
|
|
119179
|
+
async function resumeInterruptedTurn2(session, turn, opts) {
|
|
118853
119180
|
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
118854
119181
|
let live = sessionMap2.get(session.id);
|
|
118855
119182
|
if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
|
|
@@ -119011,8 +119338,8 @@ var claudeProvider = {
|
|
|
119011
119338
|
setModel,
|
|
119012
119339
|
stopTask,
|
|
119013
119340
|
listBackgroundTasks,
|
|
119014
|
-
resumeInterruptedTurn,
|
|
119015
|
-
reapOrphans,
|
|
119341
|
+
resumeInterruptedTurn: resumeInterruptedTurn2,
|
|
119342
|
+
reapOrphans: reapOrphans2,
|
|
119016
119343
|
shutdown: shutdown2
|
|
119017
119344
|
};
|
|
119018
119345
|
|
|
@@ -119501,11 +119828,13 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119501
119828
|
if (opts.signal?.aborted || err.name === "AbortError") {
|
|
119502
119829
|
return "aborted";
|
|
119503
119830
|
}
|
|
119831
|
+
opts.onDisconnect?.();
|
|
119504
119832
|
await reconnectDelay(delayMs, opts.signal);
|
|
119505
119833
|
continue;
|
|
119506
119834
|
}
|
|
119507
119835
|
if (response.status === 404) return "session-not-found";
|
|
119508
119836
|
if (!response.ok || !response.body) {
|
|
119837
|
+
opts.onDisconnect?.();
|
|
119509
119838
|
await reconnectDelay(delayMs, opts.signal);
|
|
119510
119839
|
continue;
|
|
119511
119840
|
}
|
|
@@ -119519,6 +119848,7 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119519
119848
|
});
|
|
119520
119849
|
return reason;
|
|
119521
119850
|
}
|
|
119851
|
+
opts.onDisconnect?.();
|
|
119522
119852
|
await reconnectDelay(delayMs, opts.signal);
|
|
119523
119853
|
}
|
|
119524
119854
|
}
|
|
@@ -120187,6 +120517,9 @@ function mapReasoningEffort(modelId, effort) {
|
|
|
120187
120517
|
}
|
|
120188
120518
|
var sessionMap3 = /* @__PURE__ */ new Map();
|
|
120189
120519
|
var STALLED_STREAM_MS = 6e4;
|
|
120520
|
+
var BACKEND_LOST_MS = 3e4;
|
|
120521
|
+
var BACKEND_RESTARTED_ERROR = "The Repoburg backend restarted while this turn ran, so the turn was lost. Send the prompt again.";
|
|
120522
|
+
var BACKEND_UNREACHABLE_ERROR = `The Repoburg backend was unreachable for ${BACKEND_LOST_MS / 1e3} s while this turn ran, so the turn was lost. Send the prompt again.`;
|
|
120190
120523
|
function isConnectionError(err) {
|
|
120191
120524
|
const message = String(err?.message ?? "");
|
|
120192
120525
|
return /fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|socket hang up/i.test(
|
|
@@ -120310,7 +120643,7 @@ function failTurnBeforeStart(db2, sessionId, turnId, error51) {
|
|
|
120310
120643
|
recomputeSessionRunning(db2, sessionId, "failed");
|
|
120311
120644
|
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
120312
120645
|
}
|
|
120313
|
-
function
|
|
120646
|
+
function failTurn3(entry, error51) {
|
|
120314
120647
|
const active = entry.activeTurn;
|
|
120315
120648
|
if (!active) return;
|
|
120316
120649
|
entry.activeTurn = null;
|
|
@@ -120334,32 +120667,61 @@ function failTurn2(entry, error51) {
|
|
|
120334
120667
|
broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
|
|
120335
120668
|
}
|
|
120336
120669
|
async function runStreamLoop(entry, projector) {
|
|
120337
|
-
|
|
120338
|
-
|
|
120339
|
-
|
|
120340
|
-
|
|
120341
|
-
|
|
120342
|
-
|
|
120670
|
+
const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
|
|
120671
|
+
const lose = (error51) => {
|
|
120672
|
+
if (isCurrent()) failTurn3(entry, error51);
|
|
120673
|
+
};
|
|
120674
|
+
let lostTimer = null;
|
|
120675
|
+
const clearLostTimer = () => {
|
|
120676
|
+
if (lostTimer) clearTimeout(lostTimer);
|
|
120677
|
+
lostTimer = null;
|
|
120678
|
+
};
|
|
120679
|
+
try {
|
|
120680
|
+
while (isCurrent()) {
|
|
120681
|
+
const active = entry.activeTurn;
|
|
120682
|
+
const controller = new AbortController();
|
|
120683
|
+
active.sseAbort = controller;
|
|
120684
|
+
let stallTimer = null;
|
|
120685
|
+
const resetStall = () => {
|
|
120686
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
120687
|
+
stallTimer = setTimeout(() => controller.abort(), STALLED_STREAM_MS);
|
|
120688
|
+
};
|
|
120689
|
+
resetStall();
|
|
120690
|
+
const onMessage = (message) => {
|
|
120691
|
+
if (message.type === "system") {
|
|
120692
|
+
clearLostTimer();
|
|
120693
|
+
const bootId = message.bootId ?? null;
|
|
120694
|
+
if (active.bootId === void 0) active.bootId = bootId;
|
|
120695
|
+
else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
|
|
120696
|
+
}
|
|
120697
|
+
projector.handle(message);
|
|
120698
|
+
};
|
|
120699
|
+
const onDisconnect = () => {
|
|
120700
|
+
if (typeof active.bootId !== "string" || lostTimer) return;
|
|
120701
|
+
lostTimer = setTimeout(() => {
|
|
120702
|
+
lostTimer = null;
|
|
120703
|
+
invalidateBackend(entry.baseUrl);
|
|
120704
|
+
lose(BACKEND_UNREACHABLE_ERROR);
|
|
120705
|
+
}, BACKEND_LOST_MS);
|
|
120706
|
+
};
|
|
120707
|
+
const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
|
|
120708
|
+
signal: controller.signal,
|
|
120709
|
+
onActivity: resetStall,
|
|
120710
|
+
onDisconnect
|
|
120711
|
+
});
|
|
120343
120712
|
if (stallTimer) clearTimeout(stallTimer);
|
|
120344
|
-
|
|
120345
|
-
|
|
120346
|
-
|
|
120347
|
-
|
|
120348
|
-
|
|
120349
|
-
|
|
120350
|
-
|
|
120351
|
-
|
|
120352
|
-
|
|
120353
|
-
if (stallTimer) clearTimeout(stallTimer);
|
|
120354
|
-
if (projector.isDone || entry.activeTurn?.projector !== projector) return;
|
|
120355
|
-
if (reason === "session-not-found") {
|
|
120356
|
-
failTurn2(entry, "Repoburg session no longer exists on the backend.");
|
|
120357
|
-
return;
|
|
120358
|
-
}
|
|
120359
|
-
if (reason === "aborted") {
|
|
120360
|
-
if (active.cancelled) return;
|
|
120361
|
-
continue;
|
|
120713
|
+
if (!isCurrent()) return;
|
|
120714
|
+
if (reason === "session-not-found") {
|
|
120715
|
+
failTurn3(entry, "Repoburg session no longer exists on the backend.");
|
|
120716
|
+
return;
|
|
120717
|
+
}
|
|
120718
|
+
if (reason === "aborted") {
|
|
120719
|
+
if (active.cancelled) return;
|
|
120720
|
+
continue;
|
|
120721
|
+
}
|
|
120362
120722
|
}
|
|
120723
|
+
} finally {
|
|
120724
|
+
clearLostTimer();
|
|
120363
120725
|
}
|
|
120364
120726
|
}
|
|
120365
120727
|
function turnImageDataUrls(turn) {
|
|
@@ -120445,7 +120807,7 @@ async function startTurn4(session, turn) {
|
|
|
120445
120807
|
void ensureContextWindow(entry);
|
|
120446
120808
|
runStreamLoop(entry, projector).catch((err) => {
|
|
120447
120809
|
console.error("[repoburg] stream loop crashed:", err);
|
|
120448
|
-
|
|
120810
|
+
failTurn3(entry, `Stream loop failed: ${err.message}`);
|
|
120449
120811
|
});
|
|
120450
120812
|
try {
|
|
120451
120813
|
const images = turnImageDataUrls(turn);
|
|
@@ -120456,7 +120818,7 @@ async function startTurn4(session, turn) {
|
|
|
120456
120818
|
});
|
|
120457
120819
|
} catch (err) {
|
|
120458
120820
|
if (isConnectionError(err)) invalidateBackend(entry.baseUrl);
|
|
120459
|
-
|
|
120821
|
+
failTurn3(entry, err.message);
|
|
120460
120822
|
}
|
|
120461
120823
|
}
|
|
120462
120824
|
async function interruptTurn3(sessionId, threadId) {
|