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");
|
|
@@ -42350,9 +42354,20 @@ function resumeMadeProgress(db2, turn) {
|
|
|
42350
42354
|
AND created_at >= ? LIMIT 1`
|
|
42351
42355
|
).get(turn.id, resumedAt);
|
|
42352
42356
|
}
|
|
42357
|
+
function isReopenable(db2, turn) {
|
|
42358
|
+
if (turn.status !== "completed" || turn.thread_id) return false;
|
|
42359
|
+
const latest = db2.prepare(
|
|
42360
|
+
"SELECT id FROM turns WHERE session_id = ? AND thread_id IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1"
|
|
42361
|
+
).get(turn.session_id);
|
|
42362
|
+
if (latest?.id !== turn.id) return false;
|
|
42363
|
+
return !db2.prepare(
|
|
42364
|
+
"SELECT 1 FROM turns WHERE session_id = ? AND thread_id IS NULL AND status IN ('pending', 'running') LIMIT 1"
|
|
42365
|
+
).get(turn.session_id);
|
|
42366
|
+
}
|
|
42353
42367
|
function markTurnInterrupted(db2, turnId, reason, opts = {}) {
|
|
42354
42368
|
const turn = getTurn(db2, turnId);
|
|
42355
|
-
if (!turn
|
|
42369
|
+
if (!turn) return false;
|
|
42370
|
+
if (!isLive(turn.status) && !(opts.reopen && isReopenable(db2, turn))) return false;
|
|
42356
42371
|
if (turn.status === "pending" && turn.resume_state === "waiting") return false;
|
|
42357
42372
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42358
42373
|
const detail = opts.detail ?? null;
|
|
@@ -43613,6 +43628,7 @@ import { readFileSync } from "node:fs";
|
|
|
43613
43628
|
import { spawn } from "node:child_process";
|
|
43614
43629
|
import { EventEmitter } from "node:events";
|
|
43615
43630
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
43631
|
+
var CLOSE_GRACE_MS = 2e3;
|
|
43616
43632
|
var AppServerClient = class {
|
|
43617
43633
|
proc;
|
|
43618
43634
|
nextId = 1;
|
|
@@ -43621,6 +43637,8 @@ var AppServerClient = class {
|
|
|
43621
43637
|
requestHandlers = /* @__PURE__ */ new Map();
|
|
43622
43638
|
buffer = "";
|
|
43623
43639
|
closed = false;
|
|
43640
|
+
/** The process is gone (exit), or never started (spawn error). */
|
|
43641
|
+
gone = false;
|
|
43624
43642
|
clientInfo;
|
|
43625
43643
|
/** Bound stdout listener — removed in close() so stale data is not processed. */
|
|
43626
43644
|
stdoutListener = (chunk) => this.onStdoutData(chunk);
|
|
@@ -43634,6 +43652,8 @@ var AppServerClient = class {
|
|
|
43634
43652
|
stdio: ["pipe", "pipe", "pipe"]
|
|
43635
43653
|
});
|
|
43636
43654
|
this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
|
|
43655
|
+
this.proc.stdin?.on("error", () => {
|
|
43656
|
+
});
|
|
43637
43657
|
this.proc.stdout?.setEncoding("utf-8");
|
|
43638
43658
|
this.proc.stdout?.on("data", this.stdoutListener);
|
|
43639
43659
|
this.proc.stderr?.on("data", (chunk) => {
|
|
@@ -43641,6 +43661,7 @@ var AppServerClient = class {
|
|
|
43641
43661
|
if (text2) console.error("[app-server] stderr:", text2);
|
|
43642
43662
|
});
|
|
43643
43663
|
this.proc.on("exit", (code, signal) => {
|
|
43664
|
+
this.gone = true;
|
|
43644
43665
|
this.onProcessExit(code, signal);
|
|
43645
43666
|
});
|
|
43646
43667
|
this.proc.on("error", (err) => {
|
|
@@ -43700,7 +43721,17 @@ var AppServerClient = class {
|
|
|
43700
43721
|
isClosed() {
|
|
43701
43722
|
return this.closed;
|
|
43702
43723
|
}
|
|
43703
|
-
/**
|
|
43724
|
+
/** Pid of the app-server process (the codex launcher), undefined when it never started. */
|
|
43725
|
+
get pid() {
|
|
43726
|
+
return this.proc.pid;
|
|
43727
|
+
}
|
|
43728
|
+
/**
|
|
43729
|
+
* Close the client and end the app-server. Its stdin is closed first: on end
|
|
43730
|
+
* of input the app-server shuts down and ends the commands it runs, while a
|
|
43731
|
+
* SIGTERM makes it exit at once and leaves them running. SIGTERM follows
|
|
43732
|
+
* only when it has not exited CLOSE_GRACE_MS later, SIGKILL after another
|
|
43733
|
+
* CLOSE_GRACE_MS. Resolves once it exited (or got SIGKILL).
|
|
43734
|
+
*/
|
|
43704
43735
|
async close() {
|
|
43705
43736
|
if (this.closed) return;
|
|
43706
43737
|
this.closed = true;
|
|
@@ -43710,7 +43741,27 @@ var AppServerClient = class {
|
|
|
43710
43741
|
entry.reject(new Error("AppServerClient closed"));
|
|
43711
43742
|
this.pending.delete(id);
|
|
43712
43743
|
}
|
|
43744
|
+
this.proc.stdin?.end();
|
|
43745
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43713
43746
|
this.proc.kill("SIGTERM");
|
|
43747
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43748
|
+
this.proc.kill("SIGKILL");
|
|
43749
|
+
}
|
|
43750
|
+
/** True once the process exited, false when it is still running after `ms`. */
|
|
43751
|
+
exitWithin(ms) {
|
|
43752
|
+
if (this.gone) return Promise.resolve(true);
|
|
43753
|
+
return new Promise((resolve) => {
|
|
43754
|
+
const onExit = () => {
|
|
43755
|
+
clearTimeout(timer2);
|
|
43756
|
+
resolve(true);
|
|
43757
|
+
};
|
|
43758
|
+
const timer2 = setTimeout(() => {
|
|
43759
|
+
this.proc.removeListener("exit", onExit);
|
|
43760
|
+
resolve(false);
|
|
43761
|
+
}, ms);
|
|
43762
|
+
timer2.unref?.();
|
|
43763
|
+
this.proc.once("exit", onExit);
|
|
43764
|
+
});
|
|
43714
43765
|
}
|
|
43715
43766
|
// --- Internal methods ---
|
|
43716
43767
|
write(message) {
|
|
@@ -43786,6 +43837,7 @@ var AppServerClient = class {
|
|
|
43786
43837
|
onProcessExit(code, signal) {
|
|
43787
43838
|
if (this.closed) return;
|
|
43788
43839
|
this.closed = true;
|
|
43840
|
+
this.proc.stdin?.end();
|
|
43789
43841
|
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
43790
43842
|
const error51 = new Error(`App-server process exited (${reason})`);
|
|
43791
43843
|
for (const [, entry] of this.pending) {
|
|
@@ -43799,6 +43851,7 @@ var AppServerClient = class {
|
|
|
43799
43851
|
* binary is missing). Rejects pending requests and emits 'closed' so callers
|
|
43800
43852
|
* can fail gracefully instead of crashing the whole process. */
|
|
43801
43853
|
onProcessError(err) {
|
|
43854
|
+
if (this.proc.pid === void 0) this.gone = true;
|
|
43802
43855
|
if (this.closed) return;
|
|
43803
43856
|
this.closed = true;
|
|
43804
43857
|
for (const [, entry] of this.pending) {
|
|
@@ -116648,8 +116701,111 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
|
|
|
116648
116701
|
];
|
|
116649
116702
|
}
|
|
116650
116703
|
|
|
116704
|
+
// src/claude/cli-orphans.ts
|
|
116705
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
116706
|
+
var TERM_GRACE_MS = 2e3;
|
|
116707
|
+
var POLL_MS = 100;
|
|
116708
|
+
function inspectProcess(pid) {
|
|
116709
|
+
return new Promise((resolve) => {
|
|
116710
|
+
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
116711
|
+
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
116712
|
+
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
116713
|
+
});
|
|
116714
|
+
});
|
|
116715
|
+
}
|
|
116716
|
+
function listDescendants(pid) {
|
|
116717
|
+
return new Promise((resolve) => {
|
|
116718
|
+
execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
|
|
116719
|
+
if (err) {
|
|
116720
|
+
resolve([]);
|
|
116721
|
+
return;
|
|
116722
|
+
}
|
|
116723
|
+
const children = /* @__PURE__ */ new Map();
|
|
116724
|
+
for (const line of stdout.split("\n")) {
|
|
116725
|
+
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
116726
|
+
if (!match) continue;
|
|
116727
|
+
const parent = Number(match[2]);
|
|
116728
|
+
children.set(parent, [...children.get(parent) ?? [], Number(match[1])]);
|
|
116729
|
+
}
|
|
116730
|
+
const found = [];
|
|
116731
|
+
const queue = [...children.get(pid) ?? []];
|
|
116732
|
+
while (queue.length > 0) {
|
|
116733
|
+
const next = queue.shift();
|
|
116734
|
+
found.push(next);
|
|
116735
|
+
queue.push(...children.get(next) ?? []);
|
|
116736
|
+
}
|
|
116737
|
+
resolve(found);
|
|
116738
|
+
});
|
|
116739
|
+
});
|
|
116740
|
+
}
|
|
116741
|
+
var defaultDeps = {
|
|
116742
|
+
inspect: inspectProcess,
|
|
116743
|
+
descendants: listDescendants,
|
|
116744
|
+
kill: (pid, signal) => {
|
|
116745
|
+
try {
|
|
116746
|
+
process.kill(pid, signal);
|
|
116747
|
+
} catch {
|
|
116748
|
+
}
|
|
116749
|
+
},
|
|
116750
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
116751
|
+
};
|
|
116752
|
+
var isOrphan = {
|
|
116753
|
+
claude: (info) => info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json"),
|
|
116754
|
+
// The codex launcher (`node …/codex app-server …`) or the binary itself.
|
|
116755
|
+
codex: (info) => info.ppid === 1 && /\bcodex\b/.test(info.command) && /\bapp-server\b/.test(info.command)
|
|
116756
|
+
};
|
|
116757
|
+
async function endProcesses(pids, deps) {
|
|
116758
|
+
for (const pid of pids) deps.kill(pid, "SIGTERM");
|
|
116759
|
+
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
116760
|
+
await deps.sleep(POLL_MS);
|
|
116761
|
+
const alive = await Promise.all(pids.map((pid) => deps.inspect(pid)));
|
|
116762
|
+
if (alive.every((info) => !info)) return;
|
|
116763
|
+
}
|
|
116764
|
+
for (const pid of pids) {
|
|
116765
|
+
if (await deps.inspect(pid)) deps.kill(pid, "SIGKILL");
|
|
116766
|
+
}
|
|
116767
|
+
}
|
|
116768
|
+
function recordCliProcess(db2, pid, sessionId, runtime = "claude") {
|
|
116769
|
+
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, runtime, created_at) VALUES (?, ?, ?, ?)").run(
|
|
116770
|
+
pid,
|
|
116771
|
+
sessionId,
|
|
116772
|
+
runtime,
|
|
116773
|
+
(/* @__PURE__ */ new Date()).toISOString()
|
|
116774
|
+
);
|
|
116775
|
+
}
|
|
116776
|
+
function forgetCliProcess(db2, pid) {
|
|
116777
|
+
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
116778
|
+
}
|
|
116779
|
+
async function reapOrphanProcesses(db2, runtime, deps = defaultDeps) {
|
|
116780
|
+
const rows = db2.prepare("SELECT pid FROM cli_processes WHERE runtime = ?").all(runtime);
|
|
116781
|
+
const ended = await Promise.all(
|
|
116782
|
+
rows.map(async ({ pid }) => {
|
|
116783
|
+
const info = await deps.inspect(pid);
|
|
116784
|
+
if (info?.ppid === process.pid) return false;
|
|
116785
|
+
const orphan = info !== null && isOrphan[runtime](info);
|
|
116786
|
+
if (orphan) {
|
|
116787
|
+
const tree = runtime === "codex" ? await deps.descendants(pid) : [];
|
|
116788
|
+
await endProcesses([...tree, pid], deps);
|
|
116789
|
+
}
|
|
116790
|
+
forgetCliProcess(db2, pid);
|
|
116791
|
+
return orphan;
|
|
116792
|
+
})
|
|
116793
|
+
);
|
|
116794
|
+
return ended.filter(Boolean).length;
|
|
116795
|
+
}
|
|
116796
|
+
function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
116797
|
+
return reapOrphanProcesses(db2, "claude", deps);
|
|
116798
|
+
}
|
|
116799
|
+
|
|
116651
116800
|
// src/codex/codex-provider.ts
|
|
116652
116801
|
var sessionMap = /* @__PURE__ */ new Map();
|
|
116802
|
+
var startingThreads = /* @__PURE__ */ new Map();
|
|
116803
|
+
var ENDED_TURNS_KEPT = 20;
|
|
116804
|
+
function interruptWaitMs() {
|
|
116805
|
+
const ms = Number(process.env.AGENT_PANE_CODEX_INTERRUPT_WAIT_MS);
|
|
116806
|
+
return Number.isFinite(ms) && ms > 0 ? ms : 1e4;
|
|
116807
|
+
}
|
|
116808
|
+
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.";
|
|
116653
116809
|
function setSessionStatus(db2, sessionId, isRunning, status, now, hasUnreviewed = false) {
|
|
116654
116810
|
if (hasUnreviewed) {
|
|
116655
116811
|
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
@@ -116728,50 +116884,290 @@ function autoApproveToolUserInput(client) {
|
|
|
116728
116884
|
return { answers };
|
|
116729
116885
|
});
|
|
116730
116886
|
}
|
|
116731
|
-
|
|
116887
|
+
function trackProcess(pid, sessionId) {
|
|
116888
|
+
if (pid === void 0) return;
|
|
116889
|
+
try {
|
|
116890
|
+
recordCliProcess(getDb(), pid, sessionId, "codex");
|
|
116891
|
+
} catch {
|
|
116892
|
+
}
|
|
116893
|
+
}
|
|
116894
|
+
function untrackProcess(pid) {
|
|
116895
|
+
if (pid === void 0) return;
|
|
116896
|
+
try {
|
|
116897
|
+
forgetCliProcess(getDb(), pid);
|
|
116898
|
+
} catch {
|
|
116899
|
+
}
|
|
116900
|
+
}
|
|
116901
|
+
function getOrCreateThread(session) {
|
|
116732
116902
|
const existing = sessionMap.get(session.id);
|
|
116733
|
-
if (existing) return existing;
|
|
116903
|
+
if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
|
|
116904
|
+
const pending = startingThreads.get(session.id);
|
|
116905
|
+
if (pending) return pending;
|
|
116906
|
+
const started = startThread(session).finally(() => startingThreads.delete(session.id));
|
|
116907
|
+
startingThreads.set(session.id, started);
|
|
116908
|
+
return started;
|
|
116909
|
+
}
|
|
116910
|
+
async function startThread(session) {
|
|
116734
116911
|
const cwd = session.cwd ?? process.cwd();
|
|
116735
116912
|
const client = new AppServerClient(appServerClientOptions(session, cwd));
|
|
116736
|
-
|
|
116737
|
-
|
|
116738
|
-
|
|
116739
|
-
|
|
116740
|
-
|
|
116741
|
-
|
|
116742
|
-
|
|
116743
|
-
|
|
116744
|
-
|
|
116745
|
-
|
|
116746
|
-
|
|
116747
|
-
|
|
116748
|
-
|
|
116749
|
-
|
|
116750
|
-
|
|
116751
|
-
|
|
116752
|
-
}
|
|
116753
|
-
|
|
116754
|
-
|
|
116755
|
-
const
|
|
116756
|
-
|
|
116757
|
-
|
|
116758
|
-
|
|
116759
|
-
|
|
116760
|
-
|
|
116761
|
-
|
|
116762
|
-
|
|
116763
|
-
|
|
116764
|
-
|
|
116765
|
-
|
|
116766
|
-
|
|
116767
|
-
|
|
116768
|
-
|
|
116769
|
-
|
|
116913
|
+
const entry = {
|
|
116914
|
+
sessionId: session.id,
|
|
116915
|
+
client,
|
|
116916
|
+
pid: client.pid,
|
|
116917
|
+
threadId: "",
|
|
116918
|
+
turns: [],
|
|
116919
|
+
ended: /* @__PURE__ */ new Map(),
|
|
116920
|
+
resumedTurnIds: null,
|
|
116921
|
+
closing: null
|
|
116922
|
+
};
|
|
116923
|
+
trackProcess(entry.pid, session.id);
|
|
116924
|
+
listen(entry);
|
|
116925
|
+
try {
|
|
116926
|
+
await client.initialize();
|
|
116927
|
+
if (session.origin_app_id) {
|
|
116928
|
+
autoApproveToolUserInput(client);
|
|
116929
|
+
}
|
|
116930
|
+
const config3 = parseRuntimeConfig(session);
|
|
116931
|
+
const sandbox = sandboxType(config3);
|
|
116932
|
+
const instructions = threadInstructionParams(cwd);
|
|
116933
|
+
if (session.external_thread_id) {
|
|
116934
|
+
const result = await client.request("thread/resume", {
|
|
116935
|
+
threadId: session.external_thread_id,
|
|
116936
|
+
cwd,
|
|
116937
|
+
approvalPolicy: "never",
|
|
116938
|
+
sandbox,
|
|
116939
|
+
model: session.model ?? void 0,
|
|
116940
|
+
...instructions
|
|
116941
|
+
});
|
|
116942
|
+
entry.threadId = result.thread.id;
|
|
116943
|
+
entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
|
|
116944
|
+
} else {
|
|
116945
|
+
const result = await client.request("thread/start", {
|
|
116946
|
+
cwd,
|
|
116947
|
+
approvalPolicy: "never",
|
|
116948
|
+
sandbox,
|
|
116949
|
+
model: session.model ?? void 0,
|
|
116950
|
+
...instructions
|
|
116951
|
+
});
|
|
116952
|
+
entry.threadId = result.thread.id;
|
|
116953
|
+
const db2 = getDb();
|
|
116954
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116955
|
+
db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
|
|
116956
|
+
entry.threadId,
|
|
116957
|
+
now,
|
|
116958
|
+
session.id
|
|
116959
|
+
);
|
|
116960
|
+
}
|
|
116961
|
+
} catch (err) {
|
|
116962
|
+
void retireEntry(entry, "keep");
|
|
116963
|
+
throw err;
|
|
116770
116964
|
}
|
|
116771
|
-
const entry = { client, threadId, turnId: null };
|
|
116772
116965
|
sessionMap.set(session.id, entry);
|
|
116773
116966
|
return entry;
|
|
116774
116967
|
}
|
|
116968
|
+
function retireEntry(entry, left, error51 = "App-server closed") {
|
|
116969
|
+
if (entry.closing) return entry.closing;
|
|
116970
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116971
|
+
if (left !== "keep") {
|
|
116972
|
+
for (const active of [...entry.turns]) {
|
|
116973
|
+
endTurn(entry, active);
|
|
116974
|
+
try {
|
|
116975
|
+
const db2 = getDb();
|
|
116976
|
+
if (left === "cancel") abortTurn(db2, entry.sessionId, active.id);
|
|
116977
|
+
else failTurn(db2, entry.sessionId, active.id, error51);
|
|
116978
|
+
} catch (err) {
|
|
116979
|
+
console.error(`[codex] could not settle turn ${active.id}:`, err.message);
|
|
116980
|
+
}
|
|
116981
|
+
}
|
|
116982
|
+
}
|
|
116983
|
+
entry.closing = entry.client.close().catch(() => {
|
|
116984
|
+
}).finally(() => untrackProcess(entry.pid));
|
|
116985
|
+
return entry.closing;
|
|
116986
|
+
}
|
|
116987
|
+
function onClientClosed(entry, reason) {
|
|
116988
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116989
|
+
untrackProcess(entry.pid);
|
|
116990
|
+
if (entry.closing || entry.turns.length === 0) return;
|
|
116991
|
+
let db2;
|
|
116992
|
+
try {
|
|
116993
|
+
db2 = getDb();
|
|
116994
|
+
} catch {
|
|
116995
|
+
return;
|
|
116996
|
+
}
|
|
116997
|
+
const detail = `App-server process exited (${reason})`;
|
|
116998
|
+
for (const active of [...entry.turns]) {
|
|
116999
|
+
endTurn(entry, active);
|
|
117000
|
+
failOpenItems(db2, entry.sessionId, active.id);
|
|
117001
|
+
if (active.discussionThreadId) {
|
|
117002
|
+
failTurn(db2, entry.sessionId, active.id, "App-server process closed unexpectedly");
|
|
117003
|
+
} else {
|
|
117004
|
+
markTurnInterrupted(db2, active.id, "process_exit", { detail });
|
|
117005
|
+
}
|
|
117006
|
+
}
|
|
117007
|
+
}
|
|
117008
|
+
function isTurnLive(db2, turnId) {
|
|
117009
|
+
const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
|
|
117010
|
+
return row?.status === "pending" || row?.status === "running";
|
|
117011
|
+
}
|
|
117012
|
+
function endTurn(entry, active) {
|
|
117013
|
+
active.done = true;
|
|
117014
|
+
entry.turns = entry.turns.filter((t) => t !== active);
|
|
117015
|
+
rememberEnded(entry, active);
|
|
117016
|
+
}
|
|
117017
|
+
function rememberEnded(entry, active) {
|
|
117018
|
+
if (!active.codexId) return;
|
|
117019
|
+
entry.ended.set(active.codexId, active.id);
|
|
117020
|
+
if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
|
|
117021
|
+
}
|
|
117022
|
+
function liveTurnsOf(entry, codexId) {
|
|
117023
|
+
if (!codexId) return entry.turns.slice(-1);
|
|
117024
|
+
const known = entry.turns.filter((t) => t.codexId === codexId);
|
|
117025
|
+
if (known.length > 0 || entry.ended.has(codexId)) return known;
|
|
117026
|
+
const waiting = entry.turns.find((t) => t.codexId === null);
|
|
117027
|
+
if (!waiting) return [];
|
|
117028
|
+
waiting.codexId = codexId;
|
|
117029
|
+
return [waiting];
|
|
117030
|
+
}
|
|
117031
|
+
function noteContinued(active) {
|
|
117032
|
+
if (!active.resuming) return;
|
|
117033
|
+
active.resuming = false;
|
|
117034
|
+
markTurnResumed(getDb(), active.id);
|
|
117035
|
+
}
|
|
117036
|
+
function completeTurn(db2, sessionId, turnId, usage) {
|
|
117037
|
+
markTurnResumed(db2, turnId, { settle: true });
|
|
117038
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117039
|
+
const response = turnResponse(db2, turnId);
|
|
117040
|
+
const result = usage !== void 0 ? db2.prepare(
|
|
117041
|
+
"UPDATE turns SET status = 'completed', token_usage = ?, updated_at = ? WHERE id = ? AND status IN ('pending', 'running')"
|
|
117042
|
+
).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);
|
|
117043
|
+
if (result.changes === 0) return;
|
|
117044
|
+
broadcast("turn:completed", {
|
|
117045
|
+
sessionId,
|
|
117046
|
+
turnId,
|
|
117047
|
+
...usage !== void 0 ? { usage } : {},
|
|
117048
|
+
hasUnreviewed: true,
|
|
117049
|
+
response
|
|
117050
|
+
});
|
|
117051
|
+
recomputeSessionRunning(db2, sessionId, "active", true);
|
|
117052
|
+
syncThreadTitle(sessionId);
|
|
117053
|
+
}
|
|
117054
|
+
function failTurn(db2, sessionId, turnId, error51) {
|
|
117055
|
+
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117056
|
+
if (!row || row.status !== "pending" && row.status !== "running") return;
|
|
117057
|
+
if (row.resume_state === "waiting" || row.resume_state === "resuming") {
|
|
117058
|
+
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
117059
|
+
}
|
|
117060
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117061
|
+
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run("failed", error51, now, turnId);
|
|
117062
|
+
recomputeSessionRunning(db2, sessionId, "failed");
|
|
117063
|
+
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
117064
|
+
}
|
|
117065
|
+
function abortTurn(db2, sessionId, turnId) {
|
|
117066
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117067
|
+
const result = db2.prepare("UPDATE turns SET status = 'aborted', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(now, turnId);
|
|
117068
|
+
if (result.changes === 0) return false;
|
|
117069
|
+
markResumeCancelled(db2, turnId);
|
|
117070
|
+
recomputeSessionRunning(db2, sessionId);
|
|
117071
|
+
broadcast("turn:cancelled", { sessionId, turnId });
|
|
117072
|
+
return true;
|
|
117073
|
+
}
|
|
117074
|
+
function cancelTurn(entry, active) {
|
|
117075
|
+
if (active.done) return;
|
|
117076
|
+
endTurn(entry, active);
|
|
117077
|
+
abortTurn(getDb(), entry.sessionId, active.id);
|
|
117078
|
+
}
|
|
117079
|
+
function failOpenItems(db2, sessionId, turnId) {
|
|
117080
|
+
const rows = db2.prepare(
|
|
117081
|
+
"SELECT id, external_item_id, type, data, created_at FROM items WHERE turn_id = ? AND status = 'in_progress'"
|
|
117082
|
+
).all(turnId);
|
|
117083
|
+
if (rows.length === 0) return;
|
|
117084
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117085
|
+
db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE turn_id = ? AND status = 'in_progress'").run(
|
|
117086
|
+
now,
|
|
117087
|
+
turnId
|
|
117088
|
+
);
|
|
117089
|
+
for (const row of rows) {
|
|
117090
|
+
const item = {
|
|
117091
|
+
id: row.id,
|
|
117092
|
+
turn_id: turnId,
|
|
117093
|
+
external_item_id: row.external_item_id,
|
|
117094
|
+
type: row.type,
|
|
117095
|
+
data: row.data ? JSON.parse(row.data) : {},
|
|
117096
|
+
status: "failed",
|
|
117097
|
+
created_at: row.created_at,
|
|
117098
|
+
updated_at: now
|
|
117099
|
+
};
|
|
117100
|
+
broadcast("item:completed", { sessionId, turnId, item });
|
|
117101
|
+
}
|
|
117102
|
+
}
|
|
117103
|
+
function listen(entry) {
|
|
117104
|
+
const on = (method, handle) => {
|
|
117105
|
+
entry.client.onNotification(method, (params) => {
|
|
117106
|
+
const p = params;
|
|
117107
|
+
if (!p || p.threadId !== entry.threadId) return;
|
|
117108
|
+
handle(p);
|
|
117109
|
+
});
|
|
117110
|
+
};
|
|
117111
|
+
on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
|
|
117112
|
+
on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
|
|
117113
|
+
on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
|
|
117114
|
+
on("item/agentMessage/delta", (p) => onAgentMessageDelta(entry, p));
|
|
117115
|
+
on("turn/completed", (p) => onTurnCompleted(entry, p));
|
|
117116
|
+
on("turn/failed", (p) => onTurnFailed(entry, p));
|
|
117117
|
+
on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
|
|
117118
|
+
entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
|
|
117119
|
+
}
|
|
117120
|
+
function onItem(entry, p, status, event) {
|
|
117121
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117122
|
+
if (live) {
|
|
117123
|
+
if (!shouldSkipItem(p.item.type)) noteContinued(live);
|
|
117124
|
+
handleItemEvent(p, entry.sessionId, live.id, status, event);
|
|
117125
|
+
return;
|
|
117126
|
+
}
|
|
117127
|
+
const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
|
|
117128
|
+
if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
|
|
117129
|
+
}
|
|
117130
|
+
function onAgentMessageDelta(entry, p) {
|
|
117131
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117132
|
+
if (!live) return;
|
|
117133
|
+
noteContinued(live);
|
|
117134
|
+
broadcast("item:delta", {
|
|
117135
|
+
sessionId: entry.sessionId,
|
|
117136
|
+
turnId: live.id,
|
|
117137
|
+
itemId: p.itemId,
|
|
117138
|
+
delta: p.delta
|
|
117139
|
+
});
|
|
117140
|
+
}
|
|
117141
|
+
function onTurnCompleted(entry, p) {
|
|
117142
|
+
const db2 = getDb();
|
|
117143
|
+
for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
|
|
117144
|
+
if (p.turn?.status === "interrupted") {
|
|
117145
|
+
cancelTurn(entry, live);
|
|
117146
|
+
} else if (p.turn?.status === "failed") {
|
|
117147
|
+
endTurn(entry, live);
|
|
117148
|
+
failTurn(db2, entry.sessionId, live.id, p.turn.error?.message ?? "Codex turn failed");
|
|
117149
|
+
} else {
|
|
117150
|
+
endTurn(entry, live);
|
|
117151
|
+
completeTurn(db2, entry.sessionId, live.id, p.usage);
|
|
117152
|
+
}
|
|
117153
|
+
}
|
|
117154
|
+
}
|
|
117155
|
+
function onTurnFailed(entry, p) {
|
|
117156
|
+
const db2 = getDb();
|
|
117157
|
+
for (const live of liveTurnsOf(entry, p.turnId)) {
|
|
117158
|
+
endTurn(entry, live);
|
|
117159
|
+
failTurn(db2, entry.sessionId, live.id, p.error.message);
|
|
117160
|
+
}
|
|
117161
|
+
}
|
|
117162
|
+
function onTokenUsage(entry, p) {
|
|
117163
|
+
const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
|
|
117164
|
+
if (!turnId) return;
|
|
117165
|
+
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
117166
|
+
const db2 = getDb();
|
|
117167
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117168
|
+
db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
|
|
117169
|
+
broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
|
|
117170
|
+
}
|
|
116775
117171
|
function turnAttachments2(turn) {
|
|
116776
117172
|
const raw = turn.attachments;
|
|
116777
117173
|
if (!raw) return [];
|
|
@@ -116805,175 +117201,63 @@ ${decoded}
|
|
|
116805
117201
|
}
|
|
116806
117202
|
return input;
|
|
116807
117203
|
}
|
|
117204
|
+
async function runTurn(session, turn, entry, input, resume) {
|
|
117205
|
+
const db2 = getDb();
|
|
117206
|
+
const sandbox = sandboxType(parseRuntimeConfig(session));
|
|
117207
|
+
let resolveStarted;
|
|
117208
|
+
const active = {
|
|
117209
|
+
id: turn.id,
|
|
117210
|
+
discussionThreadId: turn.thread_id ?? null,
|
|
117211
|
+
codexId: null,
|
|
117212
|
+
started: new Promise((resolve) => {
|
|
117213
|
+
resolveStarted = resolve;
|
|
117214
|
+
}),
|
|
117215
|
+
done: false,
|
|
117216
|
+
resuming: resume
|
|
117217
|
+
};
|
|
117218
|
+
entry.turns.push(active);
|
|
117219
|
+
try {
|
|
117220
|
+
const result = await entry.client.request("turn/start", {
|
|
117221
|
+
threadId: entry.threadId,
|
|
117222
|
+
input,
|
|
117223
|
+
approvalPolicy: "never",
|
|
117224
|
+
sandbox: { type: sandbox },
|
|
117225
|
+
model: session.model ?? void 0,
|
|
117226
|
+
effort: session.model_reasoning_effort ?? void 0
|
|
117227
|
+
});
|
|
117228
|
+
active.codexId = result.turn.id;
|
|
117229
|
+
if (active.done) rememberEnded(entry, active);
|
|
117230
|
+
db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
|
|
117231
|
+
result.turn.id,
|
|
117232
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
117233
|
+
turn.id
|
|
117234
|
+
);
|
|
117235
|
+
resolveStarted(result.turn.id);
|
|
117236
|
+
} catch (err) {
|
|
117237
|
+
const message = err.message;
|
|
117238
|
+
const settled = active.done;
|
|
117239
|
+
endTurn(entry, active);
|
|
117240
|
+
if (!message.startsWith("JSON-RPC error")) void retireEntry(entry, "fail", message);
|
|
117241
|
+
if (!settled && !resume) failTurn(db2, session.id, turn.id, message);
|
|
117242
|
+
resolveStarted(null);
|
|
117243
|
+
if (!settled && resume) throw err;
|
|
117244
|
+
}
|
|
117245
|
+
}
|
|
116808
117246
|
async function startTurn2(session, turn) {
|
|
116809
117247
|
const db2 = getDb();
|
|
116810
117248
|
let entry;
|
|
116811
117249
|
try {
|
|
116812
117250
|
entry = await getOrCreateThread(session);
|
|
116813
117251
|
} catch (err) {
|
|
116814
|
-
|
|
116815
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116816
|
-
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116817
|
-
"failed",
|
|
116818
|
-
errMsg,
|
|
116819
|
-
now2,
|
|
116820
|
-
turn.id
|
|
116821
|
-
);
|
|
116822
|
-
recomputeSessionRunning(db2, session.id, "failed");
|
|
116823
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
117252
|
+
failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
|
|
116824
117253
|
return;
|
|
116825
117254
|
}
|
|
116826
|
-
|
|
117255
|
+
if (!isTurnLive(db2, turn.id)) return;
|
|
116827
117256
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116828
117257
|
db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
|
|
116829
117258
|
setSessionStatus(db2, session.id, 1, "running", now);
|
|
116830
117259
|
broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
|
|
116831
|
-
|
|
116832
|
-
const config3 = parseRuntimeConfig(session);
|
|
116833
|
-
const sandbox = sandboxType(config3);
|
|
116834
|
-
let turnDone = false;
|
|
116835
|
-
const handleItemStarted = (params) => {
|
|
116836
|
-
if (turnDone) return;
|
|
116837
|
-
const p = params;
|
|
116838
|
-
if (p.threadId !== threadId) return;
|
|
116839
|
-
handleItemEvent(p, session.id, turn.id, "in_progress", "item:started");
|
|
116840
|
-
};
|
|
116841
|
-
const handleItemUpdated = (params) => {
|
|
116842
|
-
if (turnDone) return;
|
|
116843
|
-
const p = params;
|
|
116844
|
-
if (p.threadId !== threadId) return;
|
|
116845
|
-
handleItemEvent(p, session.id, turn.id, "in_progress", "item:updated");
|
|
116846
|
-
};
|
|
116847
|
-
const handleItemCompleted = (params) => {
|
|
116848
|
-
if (turnDone) return;
|
|
116849
|
-
const p = params;
|
|
116850
|
-
if (p.threadId !== threadId) return;
|
|
116851
|
-
const status = getItemStatus(p.item);
|
|
116852
|
-
handleItemEvent(p, session.id, turn.id, status, "item:completed");
|
|
116853
|
-
};
|
|
116854
|
-
const handleTurnCompleted = (params) => {
|
|
116855
|
-
if (turnDone) return;
|
|
116856
|
-
const p = params;
|
|
116857
|
-
if (p.threadId !== threadId) return;
|
|
116858
|
-
turnDone = true;
|
|
116859
|
-
const db3 = getDb();
|
|
116860
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116861
|
-
if (p.turn?.status === "failed") {
|
|
116862
|
-
const errMsg = p.turn.error?.message ?? "Codex turn failed";
|
|
116863
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116864
|
-
"failed",
|
|
116865
|
-
errMsg,
|
|
116866
|
-
now2,
|
|
116867
|
-
turn.id
|
|
116868
|
-
);
|
|
116869
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116870
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
116871
|
-
return;
|
|
116872
|
-
}
|
|
116873
|
-
const response = turnResponse(db3, turn.id);
|
|
116874
|
-
if (p.usage !== void 0) {
|
|
116875
|
-
db3.prepare("UPDATE turns SET status = ?, token_usage = ?, updated_at = ? WHERE id = ?").run(
|
|
116876
|
-
"completed",
|
|
116877
|
-
JSON.stringify(p.usage),
|
|
116878
|
-
now2,
|
|
116879
|
-
turn.id
|
|
116880
|
-
);
|
|
116881
|
-
broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, usage: p.usage, hasUnreviewed: true, response });
|
|
116882
|
-
} else {
|
|
116883
|
-
db3.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("completed", now2, turn.id);
|
|
116884
|
-
broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, hasUnreviewed: true, response });
|
|
116885
|
-
}
|
|
116886
|
-
recomputeSessionRunning(db3, session.id, "active", true);
|
|
116887
|
-
syncThreadTitle(session.id);
|
|
116888
|
-
};
|
|
116889
|
-
const handleTurnFailed = (params) => {
|
|
116890
|
-
if (turnDone) return;
|
|
116891
|
-
const p = params;
|
|
116892
|
-
if (p.threadId !== threadId) return;
|
|
116893
|
-
turnDone = true;
|
|
116894
|
-
const db3 = getDb();
|
|
116895
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116896
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116897
|
-
"failed",
|
|
116898
|
-
p.error.message,
|
|
116899
|
-
now2,
|
|
116900
|
-
turn.id
|
|
116901
|
-
);
|
|
116902
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116903
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: p.error.message });
|
|
116904
|
-
};
|
|
116905
|
-
const handleAgentMessageDelta = (params) => {
|
|
116906
|
-
if (turnDone) return;
|
|
116907
|
-
const p = params;
|
|
116908
|
-
if (p.threadId !== threadId) return;
|
|
116909
|
-
broadcast("item:delta", {
|
|
116910
|
-
sessionId: session.id,
|
|
116911
|
-
turnId: turn.id,
|
|
116912
|
-
itemId: p.itemId,
|
|
116913
|
-
delta: p.delta
|
|
116914
|
-
});
|
|
116915
|
-
};
|
|
116916
|
-
const handleTokenUsageUpdated = (params) => {
|
|
116917
|
-
const p = params;
|
|
116918
|
-
if (p.threadId !== threadId) return;
|
|
116919
|
-
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
116920
|
-
const db3 = getDb();
|
|
116921
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116922
|
-
db3.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(
|
|
116923
|
-
JSON.stringify(usage),
|
|
116924
|
-
now2,
|
|
116925
|
-
turn.id
|
|
116926
|
-
);
|
|
116927
|
-
broadcast("turn:tokenUsage", { sessionId: session.id, turnId: turn.id, usage });
|
|
116928
|
-
};
|
|
116929
|
-
client.onNotification("item/started", handleItemStarted);
|
|
116930
|
-
client.onNotification("item/updated", handleItemUpdated);
|
|
116931
|
-
client.onNotification("item/completed", handleItemCompleted);
|
|
116932
|
-
client.onNotification("item/agentMessage/delta", handleAgentMessageDelta);
|
|
116933
|
-
client.onNotification("turn/completed", handleTurnCompleted);
|
|
116934
|
-
client.onNotification("turn/failed", handleTurnFailed);
|
|
116935
|
-
client.onNotification("thread/tokenUsage/updated", handleTokenUsageUpdated);
|
|
116936
|
-
try {
|
|
116937
|
-
await client.request("turn/start", {
|
|
116938
|
-
threadId,
|
|
116939
|
-
input: buildCodexInput(turn),
|
|
116940
|
-
approvalPolicy: "never",
|
|
116941
|
-
sandbox: { type: sandbox },
|
|
116942
|
-
model: session.model ?? void 0,
|
|
116943
|
-
effort: session.model_reasoning_effort ?? void 0
|
|
116944
|
-
});
|
|
116945
|
-
client.events.once("closed", () => {
|
|
116946
|
-
const db3 = getDb();
|
|
116947
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116948
|
-
const currentTurn = db3.prepare("SELECT status FROM turns WHERE id = ?").get(turn.id);
|
|
116949
|
-
if (currentTurn && currentTurn.status === "running") {
|
|
116950
|
-
db3.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116951
|
-
"failed",
|
|
116952
|
-
"App-server process closed unexpectedly",
|
|
116953
|
-
now2,
|
|
116954
|
-
turn.id
|
|
116955
|
-
);
|
|
116956
|
-
recomputeSessionRunning(db3, session.id, "failed");
|
|
116957
|
-
broadcast("turn:failed", {
|
|
116958
|
-
sessionId: session.id,
|
|
116959
|
-
turnId: turn.id,
|
|
116960
|
-
error: "App-server process closed unexpectedly"
|
|
116961
|
-
});
|
|
116962
|
-
}
|
|
116963
|
-
});
|
|
116964
|
-
} catch (err) {
|
|
116965
|
-
const errMsg = err.message;
|
|
116966
|
-
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
116967
|
-
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(
|
|
116968
|
-
"failed",
|
|
116969
|
-
errMsg,
|
|
116970
|
-
now2,
|
|
116971
|
-
turn.id
|
|
116972
|
-
);
|
|
116973
|
-
recomputeSessionRunning(db2, session.id, "failed");
|
|
116974
|
-
broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
|
|
116975
|
-
turnDone = true;
|
|
116976
|
-
}
|
|
117260
|
+
await runTurn(session, turn, entry, buildCodexInput(turn), false);
|
|
116977
117261
|
}
|
|
116978
117262
|
function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
116979
117263
|
const db2 = getDb();
|
|
@@ -117021,39 +117305,99 @@ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
|
117021
117305
|
};
|
|
117022
117306
|
broadcast(broadcastEvent, { sessionId, turnId, item: wsItem });
|
|
117023
117307
|
}
|
|
117024
|
-
|
|
117025
|
-
|
|
117026
|
-
|
|
117308
|
+
function within(promise2, ms) {
|
|
117309
|
+
return new Promise((resolve) => {
|
|
117310
|
+
const timer2 = setTimeout(() => resolve(null), ms);
|
|
117311
|
+
timer2.unref?.();
|
|
117312
|
+
promise2.then(
|
|
117313
|
+
(value) => {
|
|
117314
|
+
clearTimeout(timer2);
|
|
117315
|
+
resolve(value);
|
|
117316
|
+
},
|
|
117317
|
+
() => {
|
|
117318
|
+
clearTimeout(timer2);
|
|
117319
|
+
resolve(null);
|
|
117320
|
+
}
|
|
117321
|
+
);
|
|
117322
|
+
});
|
|
117323
|
+
}
|
|
117324
|
+
function turnToStop(entry, threadId) {
|
|
117325
|
+
if (threadId) return entry.turns.find((t) => t.discussionThreadId === threadId);
|
|
117326
|
+
return entry.turns.find((t) => !t.discussionThreadId) ?? entry.turns[0];
|
|
117327
|
+
}
|
|
117328
|
+
function abortOrphanTurn(sessionId, threadId) {
|
|
117027
117329
|
try {
|
|
117028
|
-
await entry.client.request("turn/interrupt", {
|
|
117029
|
-
threadId: entry.threadId,
|
|
117030
|
-
turnId: entry.turnId
|
|
117031
|
-
});
|
|
117032
117330
|
const db2 = getDb();
|
|
117033
|
-
const
|
|
117034
|
-
|
|
117035
|
-
|
|
117036
|
-
|
|
117037
|
-
entry.turnId = null;
|
|
117038
|
-
return true;
|
|
117331
|
+
const orphan = db2.prepare(
|
|
117332
|
+
`SELECT id FROM turns WHERE session_id = ? ${threadId ? "AND thread_id = ?" : ""} AND status IN ('pending', 'running') ORDER BY created_at DESC LIMIT 1`
|
|
117333
|
+
).get(...threadId ? [sessionId, threadId] : [sessionId]);
|
|
117334
|
+
return orphan ? abortTurn(db2, sessionId, orphan.id) : false;
|
|
117039
117335
|
} catch {
|
|
117040
117336
|
return false;
|
|
117041
117337
|
}
|
|
117042
117338
|
}
|
|
117043
|
-
|
|
117339
|
+
var END_COMMANDS_WAIT_MS = 5e3;
|
|
117340
|
+
async function endTurnCommands(entry, turnId) {
|
|
117341
|
+
try {
|
|
117342
|
+
const rows = getDb().prepare(
|
|
117343
|
+
"SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
|
|
117344
|
+
).all(turnId);
|
|
117345
|
+
const started = new Set(rows.map((row) => row.id));
|
|
117346
|
+
if (started.size === 0) return;
|
|
117347
|
+
let cursor = null;
|
|
117348
|
+
do {
|
|
117349
|
+
const page = await entry.client.request("thread/backgroundTerminals/list", {
|
|
117350
|
+
threadId: entry.threadId,
|
|
117351
|
+
cursor
|
|
117352
|
+
});
|
|
117353
|
+
for (const terminal of page.data) {
|
|
117354
|
+
if (!started.has(terminal.itemId)) continue;
|
|
117355
|
+
await entry.client.request("thread/backgroundTerminals/terminate", {
|
|
117356
|
+
threadId: entry.threadId,
|
|
117357
|
+
processId: terminal.processId
|
|
117358
|
+
});
|
|
117359
|
+
}
|
|
117360
|
+
cursor = page.nextCursor;
|
|
117361
|
+
} while (cursor);
|
|
117362
|
+
} catch (err) {
|
|
117363
|
+
console.warn(`[codex] could not end the commands of stopped turn ${turnId}: ${err.message}`);
|
|
117364
|
+
}
|
|
117365
|
+
}
|
|
117366
|
+
async function interruptTurn(sessionId, threadId) {
|
|
117044
117367
|
const entry = sessionMap.get(sessionId);
|
|
117045
|
-
|
|
117046
|
-
|
|
117047
|
-
|
|
117048
|
-
|
|
117368
|
+
const target = entry ? turnToStop(entry, threadId) : void 0;
|
|
117369
|
+
if (entry && target) {
|
|
117370
|
+
const codexId = target.codexId ?? await within(target.started, interruptWaitMs());
|
|
117371
|
+
let stopped = false;
|
|
117372
|
+
if (codexId && !target.done) {
|
|
117373
|
+
try {
|
|
117374
|
+
await entry.client.request("turn/interrupt", {
|
|
117375
|
+
threadId: entry.threadId,
|
|
117376
|
+
turnId: codexId
|
|
117377
|
+
});
|
|
117378
|
+
stopped = true;
|
|
117379
|
+
} catch (err) {
|
|
117380
|
+
console.warn(`[codex] turn/interrupt failed for turn ${target.id}: ${err.message}`);
|
|
117381
|
+
}
|
|
117382
|
+
}
|
|
117383
|
+
const live = !target.done;
|
|
117384
|
+
if (live) {
|
|
117385
|
+
cancelTurn(entry, target);
|
|
117386
|
+
if (!stopped) void retireEntry(entry, "fail");
|
|
117387
|
+
}
|
|
117388
|
+
if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
|
|
117389
|
+
if (live || stopped) return true;
|
|
117049
117390
|
}
|
|
117391
|
+
return abortOrphanTurn(sessionId, threadId);
|
|
117392
|
+
}
|
|
117393
|
+
function clearThread(sessionId) {
|
|
117394
|
+
const entry = sessionMap.get(sessionId);
|
|
117395
|
+
if (entry) void retireEntry(entry, "cancel");
|
|
117050
117396
|
}
|
|
117051
117397
|
function clearAllThreads() {
|
|
117052
|
-
for (const
|
|
117053
|
-
entry.client.close().catch(() => {
|
|
117054
|
-
});
|
|
117055
|
-
}
|
|
117398
|
+
for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
|
|
117056
117399
|
sessionMap.clear();
|
|
117400
|
+
startingThreads.clear();
|
|
117057
117401
|
titleGenerating.clear();
|
|
117058
117402
|
}
|
|
117059
117403
|
var titleGenerating = /* @__PURE__ */ new Set();
|
|
@@ -117233,8 +117577,42 @@ async function getModels() {
|
|
|
117233
117577
|
}
|
|
117234
117578
|
}
|
|
117235
117579
|
async function shutdown() {
|
|
117236
|
-
|
|
117237
|
-
|
|
117580
|
+
let db2 = null;
|
|
117581
|
+
try {
|
|
117582
|
+
db2 = getDb();
|
|
117583
|
+
} catch {
|
|
117584
|
+
db2 = null;
|
|
117585
|
+
}
|
|
117586
|
+
const closing = [closeSharedAppServer()];
|
|
117587
|
+
for (const entry of [...sessionMap.values()]) {
|
|
117588
|
+
for (const active of [...entry.turns]) {
|
|
117589
|
+
if (active.discussionThreadId) continue;
|
|
117590
|
+
endTurn(entry, active);
|
|
117591
|
+
if (!db2) continue;
|
|
117592
|
+
try {
|
|
117593
|
+
markTurnInterrupted(db2, active.id, "host_shutdown", { notify: false });
|
|
117594
|
+
} catch (err) {
|
|
117595
|
+
console.error("[codex] could not park turn for resume:", err.message);
|
|
117596
|
+
}
|
|
117597
|
+
}
|
|
117598
|
+
closing.push(retireEntry(entry, "keep"));
|
|
117599
|
+
}
|
|
117600
|
+
await Promise.all(closing);
|
|
117601
|
+
titleGenerating.clear();
|
|
117602
|
+
}
|
|
117603
|
+
async function reapOrphans() {
|
|
117604
|
+
const ended = await reapOrphanProcesses(getDb(), "codex");
|
|
117605
|
+
if (ended > 0) console.log(`[codex] ended ${ended} app-server(s) left by the previous host`);
|
|
117606
|
+
}
|
|
117607
|
+
async function resumeInterruptedTurn(session, turn, _opts) {
|
|
117608
|
+
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
117609
|
+
const entry = await getOrCreateThread(session);
|
|
117610
|
+
if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
|
|
117611
|
+
if (!isTurnLive(getDb(), turn.id)) return;
|
|
117612
|
+
const codexId = turn.external_turn_id;
|
|
117613
|
+
const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
|
|
117614
|
+
const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
|
|
117615
|
+
await runTurn(session, turn, entry, input, true);
|
|
117238
117616
|
}
|
|
117239
117617
|
var codexProvider = {
|
|
117240
117618
|
startTurn: startTurn2,
|
|
@@ -117243,6 +117621,8 @@ var codexProvider = {
|
|
|
117243
117621
|
clearAllThreads,
|
|
117244
117622
|
getModels,
|
|
117245
117623
|
summarizeThread: summarizeCodexThread,
|
|
117624
|
+
resumeInterruptedTurn,
|
|
117625
|
+
reapOrphans,
|
|
117246
117626
|
shutdown
|
|
117247
117627
|
};
|
|
117248
117628
|
|
|
@@ -117574,64 +117954,6 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
|
|
|
117574
117954
|
return "fatal";
|
|
117575
117955
|
}
|
|
117576
117956
|
|
|
117577
|
-
// src/claude/cli-orphans.ts
|
|
117578
|
-
import { execFile as execFile3 } from "node:child_process";
|
|
117579
|
-
var TERM_GRACE_MS = 2e3;
|
|
117580
|
-
var POLL_MS = 100;
|
|
117581
|
-
function inspectProcess(pid) {
|
|
117582
|
-
return new Promise((resolve) => {
|
|
117583
|
-
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
117584
|
-
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
117585
|
-
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
117586
|
-
});
|
|
117587
|
-
});
|
|
117588
|
-
}
|
|
117589
|
-
var defaultDeps = {
|
|
117590
|
-
inspect: inspectProcess,
|
|
117591
|
-
kill: (pid, signal) => {
|
|
117592
|
-
try {
|
|
117593
|
-
process.kill(pid, signal);
|
|
117594
|
-
} catch {
|
|
117595
|
-
}
|
|
117596
|
-
},
|
|
117597
|
-
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
117598
|
-
};
|
|
117599
|
-
function isOrphanCli(info) {
|
|
117600
|
-
return info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json");
|
|
117601
|
-
}
|
|
117602
|
-
async function endProcess(pid, deps) {
|
|
117603
|
-
deps.kill(pid, "SIGTERM");
|
|
117604
|
-
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
117605
|
-
await deps.sleep(POLL_MS);
|
|
117606
|
-
if (!await deps.inspect(pid)) return;
|
|
117607
|
-
}
|
|
117608
|
-
deps.kill(pid, "SIGKILL");
|
|
117609
|
-
}
|
|
117610
|
-
function recordCliProcess(db2, pid, sessionId) {
|
|
117611
|
-
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, created_at) VALUES (?, ?, ?)").run(
|
|
117612
|
-
pid,
|
|
117613
|
-
sessionId,
|
|
117614
|
-
(/* @__PURE__ */ new Date()).toISOString()
|
|
117615
|
-
);
|
|
117616
|
-
}
|
|
117617
|
-
function forgetCliProcess(db2, pid) {
|
|
117618
|
-
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
117619
|
-
}
|
|
117620
|
-
async function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
117621
|
-
const rows = db2.prepare("SELECT pid FROM cli_processes").all();
|
|
117622
|
-
const ended = await Promise.all(
|
|
117623
|
-
rows.map(async ({ pid }) => {
|
|
117624
|
-
const info = await deps.inspect(pid);
|
|
117625
|
-
if (info?.ppid === process.pid) return false;
|
|
117626
|
-
const orphan = info !== null && isOrphanCli(info);
|
|
117627
|
-
if (orphan) await endProcess(pid, deps);
|
|
117628
|
-
forgetCliProcess(db2, pid);
|
|
117629
|
-
return orphan;
|
|
117630
|
-
})
|
|
117631
|
-
);
|
|
117632
|
-
return ended.filter(Boolean).length;
|
|
117633
|
-
}
|
|
117634
|
-
|
|
117635
117957
|
// src/claude/claude-provider.ts
|
|
117636
117958
|
var PromptQueue = class {
|
|
117637
117959
|
buffer = [];
|
|
@@ -117848,7 +118170,7 @@ function trackResumeFrame(entry, message, db2) {
|
|
|
117848
118170
|
}
|
|
117849
118171
|
return true;
|
|
117850
118172
|
}
|
|
117851
|
-
function
|
|
118173
|
+
function failTurn2(db2, sessionId, turnId, error51) {
|
|
117852
118174
|
const row = db2.prepare("SELECT resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117853
118175
|
if (row?.resume_state === "waiting" || row?.resume_state === "resuming") {
|
|
117854
118176
|
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
@@ -117871,7 +118193,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
|
|
|
117871
118193
|
if (!entry.threadId && !entry.closeReason && isSignalExit(errMsg)) {
|
|
117872
118194
|
markTurnInterrupted(db2, turnId, "process_exit", { detail: errMsg });
|
|
117873
118195
|
} else {
|
|
117874
|
-
|
|
118196
|
+
failTurn2(db2, sessionId, turnId, errMsg);
|
|
117875
118197
|
}
|
|
117876
118198
|
}
|
|
117877
118199
|
if (staleItems.changes > 0) {
|
|
@@ -117970,7 +118292,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
117970
118292
|
const currentTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
117971
118293
|
if (currentTurn && currentTurn.status === "running") {
|
|
117972
118294
|
const usage = currentTurn.token_usage ? JSON.parse(currentTurn.token_usage) : null;
|
|
117973
|
-
|
|
118295
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
117974
118296
|
}
|
|
117975
118297
|
syncThreadTitle2(session.id);
|
|
117976
118298
|
}
|
|
@@ -118036,7 +118358,7 @@ async function startTurn3(session, turn) {
|
|
|
118036
118358
|
const prevTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
118037
118359
|
if (prevTurn && prevTurn.status === "running") {
|
|
118038
118360
|
const usage = prevTurn.token_usage ? JSON.parse(prevTurn.token_usage) : null;
|
|
118039
|
-
|
|
118361
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
118040
118362
|
}
|
|
118041
118363
|
syncThreadTitle2(session.id);
|
|
118042
118364
|
streamingMessageIds.delete(entry.turnId);
|
|
@@ -118512,8 +118834,7 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118512
118834
|
entry.lastApiError = null;
|
|
118513
118835
|
if (message.is_error) {
|
|
118514
118836
|
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
118515
|
-
if (row
|
|
118516
|
-
if (row.status === "pending" && row.resume_state === "waiting") return;
|
|
118837
|
+
if (!row || row.status === "pending" && row.resume_state === "waiting") return;
|
|
118517
118838
|
const text2 = (message.result || apiError?.text || "Claude API error").trim();
|
|
118518
118839
|
const kind = classifyApiError({
|
|
118519
118840
|
error: apiError?.error,
|
|
@@ -118522,21 +118843,27 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118522
118843
|
limitRejected: entry.rateLimit?.status === "rejected"
|
|
118523
118844
|
});
|
|
118524
118845
|
const resumeAt = kind === "usage_limit" ? usageLimitResumeAt(entry.rateLimit?.resetsAt) : null;
|
|
118846
|
+
if (row.status !== "pending" && row.status !== "running") {
|
|
118847
|
+
if (kind === "usage_limit" && resumeAt && !entry.threadId) {
|
|
118848
|
+
markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt, reopen: true });
|
|
118849
|
+
}
|
|
118850
|
+
return;
|
|
118851
|
+
}
|
|
118525
118852
|
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
|
|
118526
118853
|
return;
|
|
118527
118854
|
}
|
|
118528
|
-
|
|
118855
|
+
failTurn2(db2, sessionId, turnId, text2);
|
|
118529
118856
|
return;
|
|
118530
118857
|
}
|
|
118531
118858
|
await refreshContext(entry, sessionId, db2);
|
|
118532
|
-
|
|
118859
|
+
completeTurn2(db2, sessionId, turnId, usage);
|
|
118533
118860
|
} else {
|
|
118534
118861
|
entry.lastApiError = null;
|
|
118535
118862
|
const errorMsg = message.errors?.join("; ") || "Claude turn failed";
|
|
118536
|
-
|
|
118863
|
+
failTurn2(db2, sessionId, turnId, errorMsg);
|
|
118537
118864
|
}
|
|
118538
118865
|
}
|
|
118539
|
-
function
|
|
118866
|
+
function completeTurn2(db2, sessionId, turnId, usage) {
|
|
118540
118867
|
markTurnResumed(db2, turnId, { settle: true });
|
|
118541
118868
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
118542
118869
|
const response = turnResponse(db2, turnId);
|
|
@@ -118819,7 +119146,7 @@ async function shutdown2() {
|
|
|
118819
119146
|
}
|
|
118820
119147
|
clearAllThreads2();
|
|
118821
119148
|
}
|
|
118822
|
-
async function
|
|
119149
|
+
async function reapOrphans2() {
|
|
118823
119150
|
const ended = await reapOrphanCliProcesses(getDb());
|
|
118824
119151
|
if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
|
|
118825
119152
|
}
|
|
@@ -118832,7 +119159,7 @@ function retireCli(sessionId, entry) {
|
|
|
118832
119159
|
entry.query.close();
|
|
118833
119160
|
sessionMap2.delete(sessionId);
|
|
118834
119161
|
}
|
|
118835
|
-
async function
|
|
119162
|
+
async function resumeInterruptedTurn2(session, turn, opts) {
|
|
118836
119163
|
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
118837
119164
|
let live = sessionMap2.get(session.id);
|
|
118838
119165
|
if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
|
|
@@ -118994,8 +119321,8 @@ var claudeProvider = {
|
|
|
118994
119321
|
setModel,
|
|
118995
119322
|
stopTask,
|
|
118996
119323
|
listBackgroundTasks,
|
|
118997
|
-
resumeInterruptedTurn,
|
|
118998
|
-
reapOrphans,
|
|
119324
|
+
resumeInterruptedTurn: resumeInterruptedTurn2,
|
|
119325
|
+
reapOrphans: reapOrphans2,
|
|
118999
119326
|
shutdown: shutdown2
|
|
119000
119327
|
};
|
|
119001
119328
|
|
|
@@ -119484,11 +119811,13 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119484
119811
|
if (opts.signal?.aborted || err.name === "AbortError") {
|
|
119485
119812
|
return "aborted";
|
|
119486
119813
|
}
|
|
119814
|
+
opts.onDisconnect?.();
|
|
119487
119815
|
await reconnectDelay(delayMs, opts.signal);
|
|
119488
119816
|
continue;
|
|
119489
119817
|
}
|
|
119490
119818
|
if (response.status === 404) return "session-not-found";
|
|
119491
119819
|
if (!response.ok || !response.body) {
|
|
119820
|
+
opts.onDisconnect?.();
|
|
119492
119821
|
await reconnectDelay(delayMs, opts.signal);
|
|
119493
119822
|
continue;
|
|
119494
119823
|
}
|
|
@@ -119502,6 +119831,7 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119502
119831
|
});
|
|
119503
119832
|
return reason;
|
|
119504
119833
|
}
|
|
119834
|
+
opts.onDisconnect?.();
|
|
119505
119835
|
await reconnectDelay(delayMs, opts.signal);
|
|
119506
119836
|
}
|
|
119507
119837
|
}
|
|
@@ -120170,6 +120500,9 @@ function mapReasoningEffort(modelId, effort) {
|
|
|
120170
120500
|
}
|
|
120171
120501
|
var sessionMap3 = /* @__PURE__ */ new Map();
|
|
120172
120502
|
var STALLED_STREAM_MS = 6e4;
|
|
120503
|
+
var BACKEND_LOST_MS = 3e4;
|
|
120504
|
+
var BACKEND_RESTARTED_ERROR = "The Repoburg backend restarted while this turn ran, so the turn was lost. Send the prompt again.";
|
|
120505
|
+
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.`;
|
|
120173
120506
|
function isConnectionError(err) {
|
|
120174
120507
|
const message = String(err?.message ?? "");
|
|
120175
120508
|
return /fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|socket hang up/i.test(
|
|
@@ -120293,7 +120626,7 @@ function failTurnBeforeStart(db2, sessionId, turnId, error51) {
|
|
|
120293
120626
|
recomputeSessionRunning(db2, sessionId, "failed");
|
|
120294
120627
|
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
120295
120628
|
}
|
|
120296
|
-
function
|
|
120629
|
+
function failTurn3(entry, error51) {
|
|
120297
120630
|
const active = entry.activeTurn;
|
|
120298
120631
|
if (!active) return;
|
|
120299
120632
|
entry.activeTurn = null;
|
|
@@ -120317,32 +120650,61 @@ function failTurn2(entry, error51) {
|
|
|
120317
120650
|
broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
|
|
120318
120651
|
}
|
|
120319
120652
|
async function runStreamLoop(entry, projector) {
|
|
120320
|
-
|
|
120321
|
-
|
|
120322
|
-
|
|
120323
|
-
|
|
120324
|
-
|
|
120325
|
-
|
|
120653
|
+
const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
|
|
120654
|
+
const lose = (error51) => {
|
|
120655
|
+
if (isCurrent()) failTurn3(entry, error51);
|
|
120656
|
+
};
|
|
120657
|
+
let lostTimer = null;
|
|
120658
|
+
const clearLostTimer = () => {
|
|
120659
|
+
if (lostTimer) clearTimeout(lostTimer);
|
|
120660
|
+
lostTimer = null;
|
|
120661
|
+
};
|
|
120662
|
+
try {
|
|
120663
|
+
while (isCurrent()) {
|
|
120664
|
+
const active = entry.activeTurn;
|
|
120665
|
+
const controller = new AbortController();
|
|
120666
|
+
active.sseAbort = controller;
|
|
120667
|
+
let stallTimer = null;
|
|
120668
|
+
const resetStall = () => {
|
|
120669
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
120670
|
+
stallTimer = setTimeout(() => controller.abort(), STALLED_STREAM_MS);
|
|
120671
|
+
};
|
|
120672
|
+
resetStall();
|
|
120673
|
+
const onMessage = (message) => {
|
|
120674
|
+
if (message.type === "system") {
|
|
120675
|
+
clearLostTimer();
|
|
120676
|
+
const bootId = message.bootId ?? null;
|
|
120677
|
+
if (active.bootId === void 0) active.bootId = bootId;
|
|
120678
|
+
else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
|
|
120679
|
+
}
|
|
120680
|
+
projector.handle(message);
|
|
120681
|
+
};
|
|
120682
|
+
const onDisconnect = () => {
|
|
120683
|
+
if (typeof active.bootId !== "string" || lostTimer) return;
|
|
120684
|
+
lostTimer = setTimeout(() => {
|
|
120685
|
+
lostTimer = null;
|
|
120686
|
+
invalidateBackend(entry.baseUrl);
|
|
120687
|
+
lose(BACKEND_UNREACHABLE_ERROR);
|
|
120688
|
+
}, BACKEND_LOST_MS);
|
|
120689
|
+
};
|
|
120690
|
+
const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
|
|
120691
|
+
signal: controller.signal,
|
|
120692
|
+
onActivity: resetStall,
|
|
120693
|
+
onDisconnect
|
|
120694
|
+
});
|
|
120326
120695
|
if (stallTimer) clearTimeout(stallTimer);
|
|
120327
|
-
|
|
120328
|
-
|
|
120329
|
-
|
|
120330
|
-
|
|
120331
|
-
|
|
120332
|
-
|
|
120333
|
-
|
|
120334
|
-
|
|
120335
|
-
|
|
120336
|
-
if (stallTimer) clearTimeout(stallTimer);
|
|
120337
|
-
if (projector.isDone || entry.activeTurn?.projector !== projector) return;
|
|
120338
|
-
if (reason === "session-not-found") {
|
|
120339
|
-
failTurn2(entry, "Repoburg session no longer exists on the backend.");
|
|
120340
|
-
return;
|
|
120341
|
-
}
|
|
120342
|
-
if (reason === "aborted") {
|
|
120343
|
-
if (active.cancelled) return;
|
|
120344
|
-
continue;
|
|
120696
|
+
if (!isCurrent()) return;
|
|
120697
|
+
if (reason === "session-not-found") {
|
|
120698
|
+
failTurn3(entry, "Repoburg session no longer exists on the backend.");
|
|
120699
|
+
return;
|
|
120700
|
+
}
|
|
120701
|
+
if (reason === "aborted") {
|
|
120702
|
+
if (active.cancelled) return;
|
|
120703
|
+
continue;
|
|
120704
|
+
}
|
|
120345
120705
|
}
|
|
120706
|
+
} finally {
|
|
120707
|
+
clearLostTimer();
|
|
120346
120708
|
}
|
|
120347
120709
|
}
|
|
120348
120710
|
function turnImageDataUrls(turn) {
|
|
@@ -120428,7 +120790,7 @@ async function startTurn4(session, turn) {
|
|
|
120428
120790
|
void ensureContextWindow(entry);
|
|
120429
120791
|
runStreamLoop(entry, projector).catch((err) => {
|
|
120430
120792
|
console.error("[repoburg] stream loop crashed:", err);
|
|
120431
|
-
|
|
120793
|
+
failTurn3(entry, `Stream loop failed: ${err.message}`);
|
|
120432
120794
|
});
|
|
120433
120795
|
try {
|
|
120434
120796
|
const images = turnImageDataUrls(turn);
|
|
@@ -120439,7 +120801,7 @@ async function startTurn4(session, turn) {
|
|
|
120439
120801
|
});
|
|
120440
120802
|
} catch (err) {
|
|
120441
120803
|
if (isConnectionError(err)) invalidateBackend(entry.baseUrl);
|
|
120442
|
-
|
|
120804
|
+
failTurn3(entry, err.message);
|
|
120443
120805
|
}
|
|
120444
120806
|
}
|
|
120445
120807
|
async function interruptTurn3(sessionId, threadId) {
|