repoburg 1.3.295 → 1.3.296
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 +666 -320
- package/agent-pane/backend/dist/server.js +666 -320
- 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");
|
|
@@ -43630,6 +43634,7 @@ import { readFileSync } from "node:fs";
|
|
|
43630
43634
|
import { spawn } from "node:child_process";
|
|
43631
43635
|
import { EventEmitter } from "node:events";
|
|
43632
43636
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
43637
|
+
var CLOSE_GRACE_MS = 2e3;
|
|
43633
43638
|
var AppServerClient = class {
|
|
43634
43639
|
proc;
|
|
43635
43640
|
nextId = 1;
|
|
@@ -43638,6 +43643,8 @@ var AppServerClient = class {
|
|
|
43638
43643
|
requestHandlers = /* @__PURE__ */ new Map();
|
|
43639
43644
|
buffer = "";
|
|
43640
43645
|
closed = false;
|
|
43646
|
+
/** The process is gone (exit), or never started (spawn error). */
|
|
43647
|
+
gone = false;
|
|
43641
43648
|
clientInfo;
|
|
43642
43649
|
/** Bound stdout listener — removed in close() so stale data is not processed. */
|
|
43643
43650
|
stdoutListener = (chunk) => this.onStdoutData(chunk);
|
|
@@ -43651,6 +43658,8 @@ var AppServerClient = class {
|
|
|
43651
43658
|
stdio: ["pipe", "pipe", "pipe"]
|
|
43652
43659
|
});
|
|
43653
43660
|
this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
|
|
43661
|
+
this.proc.stdin?.on("error", () => {
|
|
43662
|
+
});
|
|
43654
43663
|
this.proc.stdout?.setEncoding("utf-8");
|
|
43655
43664
|
this.proc.stdout?.on("data", this.stdoutListener);
|
|
43656
43665
|
this.proc.stderr?.on("data", (chunk) => {
|
|
@@ -43658,6 +43667,7 @@ var AppServerClient = class {
|
|
|
43658
43667
|
if (text2) console.error("[app-server] stderr:", text2);
|
|
43659
43668
|
});
|
|
43660
43669
|
this.proc.on("exit", (code, signal) => {
|
|
43670
|
+
this.gone = true;
|
|
43661
43671
|
this.onProcessExit(code, signal);
|
|
43662
43672
|
});
|
|
43663
43673
|
this.proc.on("error", (err) => {
|
|
@@ -43717,7 +43727,17 @@ var AppServerClient = class {
|
|
|
43717
43727
|
isClosed() {
|
|
43718
43728
|
return this.closed;
|
|
43719
43729
|
}
|
|
43720
|
-
/**
|
|
43730
|
+
/** Pid of the app-server process (the codex launcher), undefined when it never started. */
|
|
43731
|
+
get pid() {
|
|
43732
|
+
return this.proc.pid;
|
|
43733
|
+
}
|
|
43734
|
+
/**
|
|
43735
|
+
* Close the client and end the app-server. Its stdin is closed first: on end
|
|
43736
|
+
* of input the app-server shuts down and ends the commands it runs, while a
|
|
43737
|
+
* SIGTERM makes it exit at once and leaves them running. SIGTERM follows
|
|
43738
|
+
* only when it has not exited CLOSE_GRACE_MS later, SIGKILL after another
|
|
43739
|
+
* CLOSE_GRACE_MS. Resolves once it exited (or got SIGKILL).
|
|
43740
|
+
*/
|
|
43721
43741
|
async close() {
|
|
43722
43742
|
if (this.closed) return;
|
|
43723
43743
|
this.closed = true;
|
|
@@ -43727,7 +43747,27 @@ var AppServerClient = class {
|
|
|
43727
43747
|
entry.reject(new Error("AppServerClient closed"));
|
|
43728
43748
|
this.pending.delete(id);
|
|
43729
43749
|
}
|
|
43750
|
+
this.proc.stdin?.end();
|
|
43751
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43730
43752
|
this.proc.kill("SIGTERM");
|
|
43753
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43754
|
+
this.proc.kill("SIGKILL");
|
|
43755
|
+
}
|
|
43756
|
+
/** True once the process exited, false when it is still running after `ms`. */
|
|
43757
|
+
exitWithin(ms) {
|
|
43758
|
+
if (this.gone) return Promise.resolve(true);
|
|
43759
|
+
return new Promise((resolve) => {
|
|
43760
|
+
const onExit = () => {
|
|
43761
|
+
clearTimeout(timer2);
|
|
43762
|
+
resolve(true);
|
|
43763
|
+
};
|
|
43764
|
+
const timer2 = setTimeout(() => {
|
|
43765
|
+
this.proc.removeListener("exit", onExit);
|
|
43766
|
+
resolve(false);
|
|
43767
|
+
}, ms);
|
|
43768
|
+
timer2.unref?.();
|
|
43769
|
+
this.proc.once("exit", onExit);
|
|
43770
|
+
});
|
|
43731
43771
|
}
|
|
43732
43772
|
// --- Internal methods ---
|
|
43733
43773
|
write(message) {
|
|
@@ -43803,6 +43843,7 @@ var AppServerClient = class {
|
|
|
43803
43843
|
onProcessExit(code, signal) {
|
|
43804
43844
|
if (this.closed) return;
|
|
43805
43845
|
this.closed = true;
|
|
43846
|
+
this.proc.stdin?.end();
|
|
43806
43847
|
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
43807
43848
|
const error51 = new Error(`App-server process exited (${reason})`);
|
|
43808
43849
|
for (const [, entry] of this.pending) {
|
|
@@ -43816,6 +43857,7 @@ var AppServerClient = class {
|
|
|
43816
43857
|
* binary is missing). Rejects pending requests and emits 'closed' so callers
|
|
43817
43858
|
* can fail gracefully instead of crashing the whole process. */
|
|
43818
43859
|
onProcessError(err) {
|
|
43860
|
+
if (this.proc.pid === void 0) this.gone = true;
|
|
43819
43861
|
if (this.closed) return;
|
|
43820
43862
|
this.closed = true;
|
|
43821
43863
|
for (const [, entry] of this.pending) {
|
|
@@ -116665,8 +116707,111 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
|
|
|
116665
116707
|
];
|
|
116666
116708
|
}
|
|
116667
116709
|
|
|
116710
|
+
// src/claude/cli-orphans.ts
|
|
116711
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
116712
|
+
var TERM_GRACE_MS = 2e3;
|
|
116713
|
+
var POLL_MS = 100;
|
|
116714
|
+
function inspectProcess(pid) {
|
|
116715
|
+
return new Promise((resolve) => {
|
|
116716
|
+
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
116717
|
+
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
116718
|
+
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
116719
|
+
});
|
|
116720
|
+
});
|
|
116721
|
+
}
|
|
116722
|
+
function listDescendants(pid) {
|
|
116723
|
+
return new Promise((resolve) => {
|
|
116724
|
+
execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
|
|
116725
|
+
if (err) {
|
|
116726
|
+
resolve([]);
|
|
116727
|
+
return;
|
|
116728
|
+
}
|
|
116729
|
+
const children = /* @__PURE__ */ new Map();
|
|
116730
|
+
for (const line of stdout.split("\n")) {
|
|
116731
|
+
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
116732
|
+
if (!match) continue;
|
|
116733
|
+
const parent = Number(match[2]);
|
|
116734
|
+
children.set(parent, [...children.get(parent) ?? [], Number(match[1])]);
|
|
116735
|
+
}
|
|
116736
|
+
const found = [];
|
|
116737
|
+
const queue = [...children.get(pid) ?? []];
|
|
116738
|
+
while (queue.length > 0) {
|
|
116739
|
+
const next = queue.shift();
|
|
116740
|
+
found.push(next);
|
|
116741
|
+
queue.push(...children.get(next) ?? []);
|
|
116742
|
+
}
|
|
116743
|
+
resolve(found);
|
|
116744
|
+
});
|
|
116745
|
+
});
|
|
116746
|
+
}
|
|
116747
|
+
var defaultDeps = {
|
|
116748
|
+
inspect: inspectProcess,
|
|
116749
|
+
descendants: listDescendants,
|
|
116750
|
+
kill: (pid, signal) => {
|
|
116751
|
+
try {
|
|
116752
|
+
process.kill(pid, signal);
|
|
116753
|
+
} catch {
|
|
116754
|
+
}
|
|
116755
|
+
},
|
|
116756
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
116757
|
+
};
|
|
116758
|
+
var isOrphan = {
|
|
116759
|
+
claude: (info) => info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json"),
|
|
116760
|
+
// The codex launcher (`node …/codex app-server …`) or the binary itself.
|
|
116761
|
+
codex: (info) => info.ppid === 1 && /\bcodex\b/.test(info.command) && /\bapp-server\b/.test(info.command)
|
|
116762
|
+
};
|
|
116763
|
+
async function endProcesses(pids, deps) {
|
|
116764
|
+
for (const pid of pids) deps.kill(pid, "SIGTERM");
|
|
116765
|
+
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
116766
|
+
await deps.sleep(POLL_MS);
|
|
116767
|
+
const alive = await Promise.all(pids.map((pid) => deps.inspect(pid)));
|
|
116768
|
+
if (alive.every((info) => !info)) return;
|
|
116769
|
+
}
|
|
116770
|
+
for (const pid of pids) {
|
|
116771
|
+
if (await deps.inspect(pid)) deps.kill(pid, "SIGKILL");
|
|
116772
|
+
}
|
|
116773
|
+
}
|
|
116774
|
+
function recordCliProcess(db2, pid, sessionId, runtime = "claude") {
|
|
116775
|
+
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, runtime, created_at) VALUES (?, ?, ?, ?)").run(
|
|
116776
|
+
pid,
|
|
116777
|
+
sessionId,
|
|
116778
|
+
runtime,
|
|
116779
|
+
(/* @__PURE__ */ new Date()).toISOString()
|
|
116780
|
+
);
|
|
116781
|
+
}
|
|
116782
|
+
function forgetCliProcess(db2, pid) {
|
|
116783
|
+
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
116784
|
+
}
|
|
116785
|
+
async function reapOrphanProcesses(db2, runtime, deps = defaultDeps) {
|
|
116786
|
+
const rows = db2.prepare("SELECT pid FROM cli_processes WHERE runtime = ?").all(runtime);
|
|
116787
|
+
const ended = await Promise.all(
|
|
116788
|
+
rows.map(async ({ pid }) => {
|
|
116789
|
+
const info = await deps.inspect(pid);
|
|
116790
|
+
if (info?.ppid === process.pid) return false;
|
|
116791
|
+
const orphan = info !== null && isOrphan[runtime](info);
|
|
116792
|
+
if (orphan) {
|
|
116793
|
+
const tree = runtime === "codex" ? await deps.descendants(pid) : [];
|
|
116794
|
+
await endProcesses([...tree, pid], deps);
|
|
116795
|
+
}
|
|
116796
|
+
forgetCliProcess(db2, pid);
|
|
116797
|
+
return orphan;
|
|
116798
|
+
})
|
|
116799
|
+
);
|
|
116800
|
+
return ended.filter(Boolean).length;
|
|
116801
|
+
}
|
|
116802
|
+
function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
116803
|
+
return reapOrphanProcesses(db2, "claude", deps);
|
|
116804
|
+
}
|
|
116805
|
+
|
|
116668
116806
|
// src/codex/codex-provider.ts
|
|
116669
116807
|
var sessionMap = /* @__PURE__ */ new Map();
|
|
116808
|
+
var startingThreads = /* @__PURE__ */ new Map();
|
|
116809
|
+
var ENDED_TURNS_KEPT = 20;
|
|
116810
|
+
function interruptWaitMs() {
|
|
116811
|
+
const ms = Number(process.env.AGENT_PANE_CODEX_INTERRUPT_WAIT_MS);
|
|
116812
|
+
return Number.isFinite(ms) && ms > 0 ? ms : 1e4;
|
|
116813
|
+
}
|
|
116814
|
+
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
116815
|
function setSessionStatus(db2, sessionId, isRunning, status, now, hasUnreviewed = false) {
|
|
116671
116816
|
if (hasUnreviewed) {
|
|
116672
116817
|
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
@@ -116745,50 +116890,290 @@ function autoApproveToolUserInput(client) {
|
|
|
116745
116890
|
return { answers };
|
|
116746
116891
|
});
|
|
116747
116892
|
}
|
|
116748
|
-
|
|
116893
|
+
function trackProcess(pid, sessionId) {
|
|
116894
|
+
if (pid === void 0) return;
|
|
116895
|
+
try {
|
|
116896
|
+
recordCliProcess(getDb(), pid, sessionId, "codex");
|
|
116897
|
+
} catch {
|
|
116898
|
+
}
|
|
116899
|
+
}
|
|
116900
|
+
function untrackProcess(pid) {
|
|
116901
|
+
if (pid === void 0) return;
|
|
116902
|
+
try {
|
|
116903
|
+
forgetCliProcess(getDb(), pid);
|
|
116904
|
+
} catch {
|
|
116905
|
+
}
|
|
116906
|
+
}
|
|
116907
|
+
function getOrCreateThread(session) {
|
|
116749
116908
|
const existing = sessionMap.get(session.id);
|
|
116750
|
-
if (existing) return existing;
|
|
116909
|
+
if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
|
|
116910
|
+
const pending = startingThreads.get(session.id);
|
|
116911
|
+
if (pending) return pending;
|
|
116912
|
+
const started = startThread(session).finally(() => startingThreads.delete(session.id));
|
|
116913
|
+
startingThreads.set(session.id, started);
|
|
116914
|
+
return started;
|
|
116915
|
+
}
|
|
116916
|
+
async function startThread(session) {
|
|
116751
116917
|
const cwd = session.cwd ?? process.cwd();
|
|
116752
116918
|
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
|
-
|
|
116919
|
+
const entry = {
|
|
116920
|
+
sessionId: session.id,
|
|
116921
|
+
client,
|
|
116922
|
+
pid: client.pid,
|
|
116923
|
+
threadId: "",
|
|
116924
|
+
turns: [],
|
|
116925
|
+
ended: /* @__PURE__ */ new Map(),
|
|
116926
|
+
resumedTurnIds: null,
|
|
116927
|
+
closing: null
|
|
116928
|
+
};
|
|
116929
|
+
trackProcess(entry.pid, session.id);
|
|
116930
|
+
listen(entry);
|
|
116931
|
+
try {
|
|
116932
|
+
await client.initialize();
|
|
116933
|
+
if (session.origin_app_id) {
|
|
116934
|
+
autoApproveToolUserInput(client);
|
|
116935
|
+
}
|
|
116936
|
+
const config3 = parseRuntimeConfig(session);
|
|
116937
|
+
const sandbox = sandboxType(config3);
|
|
116938
|
+
const instructions = threadInstructionParams(cwd);
|
|
116939
|
+
if (session.external_thread_id) {
|
|
116940
|
+
const result = await client.request("thread/resume", {
|
|
116941
|
+
threadId: session.external_thread_id,
|
|
116942
|
+
cwd,
|
|
116943
|
+
approvalPolicy: "never",
|
|
116944
|
+
sandbox,
|
|
116945
|
+
model: session.model ?? void 0,
|
|
116946
|
+
...instructions
|
|
116947
|
+
});
|
|
116948
|
+
entry.threadId = result.thread.id;
|
|
116949
|
+
entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
|
|
116950
|
+
} else {
|
|
116951
|
+
const result = await client.request("thread/start", {
|
|
116952
|
+
cwd,
|
|
116953
|
+
approvalPolicy: "never",
|
|
116954
|
+
sandbox,
|
|
116955
|
+
model: session.model ?? void 0,
|
|
116956
|
+
...instructions
|
|
116957
|
+
});
|
|
116958
|
+
entry.threadId = result.thread.id;
|
|
116959
|
+
const db2 = getDb();
|
|
116960
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116961
|
+
db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
|
|
116962
|
+
entry.threadId,
|
|
116963
|
+
now,
|
|
116964
|
+
session.id
|
|
116965
|
+
);
|
|
116966
|
+
}
|
|
116967
|
+
} catch (err) {
|
|
116968
|
+
void retireEntry(entry, "keep");
|
|
116969
|
+
throw err;
|
|
116787
116970
|
}
|
|
116788
|
-
const entry = { client, threadId, turnId: null };
|
|
116789
116971
|
sessionMap.set(session.id, entry);
|
|
116790
116972
|
return entry;
|
|
116791
116973
|
}
|
|
116974
|
+
function retireEntry(entry, left, error51 = "App-server closed") {
|
|
116975
|
+
if (entry.closing) return entry.closing;
|
|
116976
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116977
|
+
if (left !== "keep") {
|
|
116978
|
+
for (const active of [...entry.turns]) {
|
|
116979
|
+
endTurn(entry, active);
|
|
116980
|
+
try {
|
|
116981
|
+
const db2 = getDb();
|
|
116982
|
+
if (left === "cancel") abortTurn(db2, entry.sessionId, active.id);
|
|
116983
|
+
else failTurn(db2, entry.sessionId, active.id, error51);
|
|
116984
|
+
} catch (err) {
|
|
116985
|
+
console.error(`[codex] could not settle turn ${active.id}:`, err.message);
|
|
116986
|
+
}
|
|
116987
|
+
}
|
|
116988
|
+
}
|
|
116989
|
+
entry.closing = entry.client.close().catch(() => {
|
|
116990
|
+
}).finally(() => untrackProcess(entry.pid));
|
|
116991
|
+
return entry.closing;
|
|
116992
|
+
}
|
|
116993
|
+
function onClientClosed(entry, reason) {
|
|
116994
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116995
|
+
untrackProcess(entry.pid);
|
|
116996
|
+
if (entry.closing || entry.turns.length === 0) return;
|
|
116997
|
+
let db2;
|
|
116998
|
+
try {
|
|
116999
|
+
db2 = getDb();
|
|
117000
|
+
} catch {
|
|
117001
|
+
return;
|
|
117002
|
+
}
|
|
117003
|
+
const detail = `App-server process exited (${reason})`;
|
|
117004
|
+
for (const active of [...entry.turns]) {
|
|
117005
|
+
endTurn(entry, active);
|
|
117006
|
+
failOpenItems(db2, entry.sessionId, active.id);
|
|
117007
|
+
if (active.discussionThreadId) {
|
|
117008
|
+
failTurn(db2, entry.sessionId, active.id, "App-server process closed unexpectedly");
|
|
117009
|
+
} else {
|
|
117010
|
+
markTurnInterrupted(db2, active.id, "process_exit", { detail });
|
|
117011
|
+
}
|
|
117012
|
+
}
|
|
117013
|
+
}
|
|
117014
|
+
function isTurnLive(db2, turnId) {
|
|
117015
|
+
const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
|
|
117016
|
+
return row?.status === "pending" || row?.status === "running";
|
|
117017
|
+
}
|
|
117018
|
+
function endTurn(entry, active) {
|
|
117019
|
+
active.done = true;
|
|
117020
|
+
entry.turns = entry.turns.filter((t) => t !== active);
|
|
117021
|
+
rememberEnded(entry, active);
|
|
117022
|
+
}
|
|
117023
|
+
function rememberEnded(entry, active) {
|
|
117024
|
+
if (!active.codexId) return;
|
|
117025
|
+
entry.ended.set(active.codexId, active.id);
|
|
117026
|
+
if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
|
|
117027
|
+
}
|
|
117028
|
+
function liveTurnsOf(entry, codexId) {
|
|
117029
|
+
if (!codexId) return entry.turns.slice(-1);
|
|
117030
|
+
const known = entry.turns.filter((t) => t.codexId === codexId);
|
|
117031
|
+
if (known.length > 0 || entry.ended.has(codexId)) return known;
|
|
117032
|
+
const waiting = entry.turns.find((t) => t.codexId === null);
|
|
117033
|
+
if (!waiting) return [];
|
|
117034
|
+
waiting.codexId = codexId;
|
|
117035
|
+
return [waiting];
|
|
117036
|
+
}
|
|
117037
|
+
function noteContinued(active) {
|
|
117038
|
+
if (!active.resuming) return;
|
|
117039
|
+
active.resuming = false;
|
|
117040
|
+
markTurnResumed(getDb(), active.id);
|
|
117041
|
+
}
|
|
117042
|
+
function completeTurn(db2, sessionId, turnId, usage) {
|
|
117043
|
+
markTurnResumed(db2, turnId, { settle: true });
|
|
117044
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117045
|
+
const response = turnResponse(db2, turnId);
|
|
117046
|
+
const result = usage !== void 0 ? db2.prepare(
|
|
117047
|
+
"UPDATE turns SET status = 'completed', token_usage = ?, updated_at = ? WHERE id = ? AND status IN ('pending', 'running')"
|
|
117048
|
+
).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);
|
|
117049
|
+
if (result.changes === 0) return;
|
|
117050
|
+
broadcast("turn:completed", {
|
|
117051
|
+
sessionId,
|
|
117052
|
+
turnId,
|
|
117053
|
+
...usage !== void 0 ? { usage } : {},
|
|
117054
|
+
hasUnreviewed: true,
|
|
117055
|
+
response
|
|
117056
|
+
});
|
|
117057
|
+
recomputeSessionRunning(db2, sessionId, "active", true);
|
|
117058
|
+
syncThreadTitle(sessionId);
|
|
117059
|
+
}
|
|
117060
|
+
function failTurn(db2, sessionId, turnId, error51) {
|
|
117061
|
+
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117062
|
+
if (!row || row.status !== "pending" && row.status !== "running") return;
|
|
117063
|
+
if (row.resume_state === "waiting" || row.resume_state === "resuming") {
|
|
117064
|
+
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
117065
|
+
}
|
|
117066
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117067
|
+
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run("failed", error51, now, turnId);
|
|
117068
|
+
recomputeSessionRunning(db2, sessionId, "failed");
|
|
117069
|
+
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
117070
|
+
}
|
|
117071
|
+
function abortTurn(db2, sessionId, turnId) {
|
|
117072
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117073
|
+
const result = db2.prepare("UPDATE turns SET status = 'aborted', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(now, turnId);
|
|
117074
|
+
if (result.changes === 0) return false;
|
|
117075
|
+
markResumeCancelled(db2, turnId);
|
|
117076
|
+
recomputeSessionRunning(db2, sessionId);
|
|
117077
|
+
broadcast("turn:cancelled", { sessionId, turnId });
|
|
117078
|
+
return true;
|
|
117079
|
+
}
|
|
117080
|
+
function cancelTurn(entry, active) {
|
|
117081
|
+
if (active.done) return;
|
|
117082
|
+
endTurn(entry, active);
|
|
117083
|
+
abortTurn(getDb(), entry.sessionId, active.id);
|
|
117084
|
+
}
|
|
117085
|
+
function failOpenItems(db2, sessionId, turnId) {
|
|
117086
|
+
const rows = db2.prepare(
|
|
117087
|
+
"SELECT id, external_item_id, type, data, created_at FROM items WHERE turn_id = ? AND status = 'in_progress'"
|
|
117088
|
+
).all(turnId);
|
|
117089
|
+
if (rows.length === 0) return;
|
|
117090
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117091
|
+
db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE turn_id = ? AND status = 'in_progress'").run(
|
|
117092
|
+
now,
|
|
117093
|
+
turnId
|
|
117094
|
+
);
|
|
117095
|
+
for (const row of rows) {
|
|
117096
|
+
const item = {
|
|
117097
|
+
id: row.id,
|
|
117098
|
+
turn_id: turnId,
|
|
117099
|
+
external_item_id: row.external_item_id,
|
|
117100
|
+
type: row.type,
|
|
117101
|
+
data: row.data ? JSON.parse(row.data) : {},
|
|
117102
|
+
status: "failed",
|
|
117103
|
+
created_at: row.created_at,
|
|
117104
|
+
updated_at: now
|
|
117105
|
+
};
|
|
117106
|
+
broadcast("item:completed", { sessionId, turnId, item });
|
|
117107
|
+
}
|
|
117108
|
+
}
|
|
117109
|
+
function listen(entry) {
|
|
117110
|
+
const on = (method, handle) => {
|
|
117111
|
+
entry.client.onNotification(method, (params) => {
|
|
117112
|
+
const p = params;
|
|
117113
|
+
if (!p || p.threadId !== entry.threadId) return;
|
|
117114
|
+
handle(p);
|
|
117115
|
+
});
|
|
117116
|
+
};
|
|
117117
|
+
on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
|
|
117118
|
+
on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
|
|
117119
|
+
on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
|
|
117120
|
+
on("item/agentMessage/delta", (p) => onAgentMessageDelta(entry, p));
|
|
117121
|
+
on("turn/completed", (p) => onTurnCompleted(entry, p));
|
|
117122
|
+
on("turn/failed", (p) => onTurnFailed(entry, p));
|
|
117123
|
+
on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
|
|
117124
|
+
entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
|
|
117125
|
+
}
|
|
117126
|
+
function onItem(entry, p, status, event) {
|
|
117127
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117128
|
+
if (live) {
|
|
117129
|
+
if (!shouldSkipItem(p.item.type)) noteContinued(live);
|
|
117130
|
+
handleItemEvent(p, entry.sessionId, live.id, status, event);
|
|
117131
|
+
return;
|
|
117132
|
+
}
|
|
117133
|
+
const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
|
|
117134
|
+
if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
|
|
117135
|
+
}
|
|
117136
|
+
function onAgentMessageDelta(entry, p) {
|
|
117137
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117138
|
+
if (!live) return;
|
|
117139
|
+
noteContinued(live);
|
|
117140
|
+
broadcast("item:delta", {
|
|
117141
|
+
sessionId: entry.sessionId,
|
|
117142
|
+
turnId: live.id,
|
|
117143
|
+
itemId: p.itemId,
|
|
117144
|
+
delta: p.delta
|
|
117145
|
+
});
|
|
117146
|
+
}
|
|
117147
|
+
function onTurnCompleted(entry, p) {
|
|
117148
|
+
const db2 = getDb();
|
|
117149
|
+
for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
|
|
117150
|
+
if (p.turn?.status === "interrupted") {
|
|
117151
|
+
cancelTurn(entry, live);
|
|
117152
|
+
} else if (p.turn?.status === "failed") {
|
|
117153
|
+
endTurn(entry, live);
|
|
117154
|
+
failTurn(db2, entry.sessionId, live.id, p.turn.error?.message ?? "Codex turn failed");
|
|
117155
|
+
} else {
|
|
117156
|
+
endTurn(entry, live);
|
|
117157
|
+
completeTurn(db2, entry.sessionId, live.id, p.usage);
|
|
117158
|
+
}
|
|
117159
|
+
}
|
|
117160
|
+
}
|
|
117161
|
+
function onTurnFailed(entry, p) {
|
|
117162
|
+
const db2 = getDb();
|
|
117163
|
+
for (const live of liveTurnsOf(entry, p.turnId)) {
|
|
117164
|
+
endTurn(entry, live);
|
|
117165
|
+
failTurn(db2, entry.sessionId, live.id, p.error.message);
|
|
117166
|
+
}
|
|
117167
|
+
}
|
|
117168
|
+
function onTokenUsage(entry, p) {
|
|
117169
|
+
const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
|
|
117170
|
+
if (!turnId) return;
|
|
117171
|
+
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
117172
|
+
const db2 = getDb();
|
|
117173
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117174
|
+
db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
|
|
117175
|
+
broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
|
|
117176
|
+
}
|
|
116792
117177
|
function turnAttachments2(turn) {
|
|
116793
117178
|
const raw = turn.attachments;
|
|
116794
117179
|
if (!raw) return [];
|
|
@@ -116822,175 +117207,63 @@ ${decoded}
|
|
|
116822
117207
|
}
|
|
116823
117208
|
return input;
|
|
116824
117209
|
}
|
|
117210
|
+
async function runTurn(session, turn, entry, input, resume) {
|
|
117211
|
+
const db2 = getDb();
|
|
117212
|
+
const sandbox = sandboxType(parseRuntimeConfig(session));
|
|
117213
|
+
let resolveStarted;
|
|
117214
|
+
const active = {
|
|
117215
|
+
id: turn.id,
|
|
117216
|
+
discussionThreadId: turn.thread_id ?? null,
|
|
117217
|
+
codexId: null,
|
|
117218
|
+
started: new Promise((resolve) => {
|
|
117219
|
+
resolveStarted = resolve;
|
|
117220
|
+
}),
|
|
117221
|
+
done: false,
|
|
117222
|
+
resuming: resume
|
|
117223
|
+
};
|
|
117224
|
+
entry.turns.push(active);
|
|
117225
|
+
try {
|
|
117226
|
+
const result = await entry.client.request("turn/start", {
|
|
117227
|
+
threadId: entry.threadId,
|
|
117228
|
+
input,
|
|
117229
|
+
approvalPolicy: "never",
|
|
117230
|
+
sandbox: { type: sandbox },
|
|
117231
|
+
model: session.model ?? void 0,
|
|
117232
|
+
effort: session.model_reasoning_effort ?? void 0
|
|
117233
|
+
});
|
|
117234
|
+
active.codexId = result.turn.id;
|
|
117235
|
+
if (active.done) rememberEnded(entry, active);
|
|
117236
|
+
db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
|
|
117237
|
+
result.turn.id,
|
|
117238
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
117239
|
+
turn.id
|
|
117240
|
+
);
|
|
117241
|
+
resolveStarted(result.turn.id);
|
|
117242
|
+
} catch (err) {
|
|
117243
|
+
const message = err.message;
|
|
117244
|
+
const settled = active.done;
|
|
117245
|
+
endTurn(entry, active);
|
|
117246
|
+
if (!message.startsWith("JSON-RPC error")) void retireEntry(entry, "fail", message);
|
|
117247
|
+
if (!settled && !resume) failTurn(db2, session.id, turn.id, message);
|
|
117248
|
+
resolveStarted(null);
|
|
117249
|
+
if (!settled && resume) throw err;
|
|
117250
|
+
}
|
|
117251
|
+
}
|
|
116825
117252
|
async function startTurn2(session, turn) {
|
|
116826
117253
|
const db2 = getDb();
|
|
116827
117254
|
let entry;
|
|
116828
117255
|
try {
|
|
116829
117256
|
entry = await getOrCreateThread(session);
|
|
116830
117257
|
} 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 });
|
|
117258
|
+
failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
|
|
116841
117259
|
return;
|
|
116842
117260
|
}
|
|
116843
|
-
|
|
117261
|
+
if (!isTurnLive(db2, turn.id)) return;
|
|
116844
117262
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116845
117263
|
db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
|
|
116846
117264
|
setSessionStatus(db2, session.id, 1, "running", now);
|
|
116847
117265
|
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
|
-
}
|
|
117266
|
+
await runTurn(session, turn, entry, buildCodexInput(turn), false);
|
|
116994
117267
|
}
|
|
116995
117268
|
function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
116996
117269
|
const db2 = getDb();
|
|
@@ -117038,39 +117311,99 @@ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
|
117038
117311
|
};
|
|
117039
117312
|
broadcast(broadcastEvent, { sessionId, turnId, item: wsItem });
|
|
117040
117313
|
}
|
|
117041
|
-
|
|
117042
|
-
|
|
117043
|
-
|
|
117314
|
+
function within(promise2, ms) {
|
|
117315
|
+
return new Promise((resolve) => {
|
|
117316
|
+
const timer2 = setTimeout(() => resolve(null), ms);
|
|
117317
|
+
timer2.unref?.();
|
|
117318
|
+
promise2.then(
|
|
117319
|
+
(value) => {
|
|
117320
|
+
clearTimeout(timer2);
|
|
117321
|
+
resolve(value);
|
|
117322
|
+
},
|
|
117323
|
+
() => {
|
|
117324
|
+
clearTimeout(timer2);
|
|
117325
|
+
resolve(null);
|
|
117326
|
+
}
|
|
117327
|
+
);
|
|
117328
|
+
});
|
|
117329
|
+
}
|
|
117330
|
+
function turnToStop(entry, threadId) {
|
|
117331
|
+
if (threadId) return entry.turns.find((t) => t.discussionThreadId === threadId);
|
|
117332
|
+
return entry.turns.find((t) => !t.discussionThreadId) ?? entry.turns[0];
|
|
117333
|
+
}
|
|
117334
|
+
function abortOrphanTurn(sessionId, threadId) {
|
|
117044
117335
|
try {
|
|
117045
|
-
await entry.client.request("turn/interrupt", {
|
|
117046
|
-
threadId: entry.threadId,
|
|
117047
|
-
turnId: entry.turnId
|
|
117048
|
-
});
|
|
117049
117336
|
const db2 = getDb();
|
|
117050
|
-
const
|
|
117051
|
-
|
|
117052
|
-
|
|
117053
|
-
|
|
117054
|
-
entry.turnId = null;
|
|
117055
|
-
return true;
|
|
117337
|
+
const orphan = db2.prepare(
|
|
117338
|
+
`SELECT id FROM turns WHERE session_id = ? ${threadId ? "AND thread_id = ?" : ""} AND status IN ('pending', 'running') ORDER BY created_at DESC LIMIT 1`
|
|
117339
|
+
).get(...threadId ? [sessionId, threadId] : [sessionId]);
|
|
117340
|
+
return orphan ? abortTurn(db2, sessionId, orphan.id) : false;
|
|
117056
117341
|
} catch {
|
|
117057
117342
|
return false;
|
|
117058
117343
|
}
|
|
117059
117344
|
}
|
|
117060
|
-
|
|
117345
|
+
var END_COMMANDS_WAIT_MS = 5e3;
|
|
117346
|
+
async function endTurnCommands(entry, turnId) {
|
|
117347
|
+
try {
|
|
117348
|
+
const rows = getDb().prepare(
|
|
117349
|
+
"SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
|
|
117350
|
+
).all(turnId);
|
|
117351
|
+
const started = new Set(rows.map((row) => row.id));
|
|
117352
|
+
if (started.size === 0) return;
|
|
117353
|
+
let cursor = null;
|
|
117354
|
+
do {
|
|
117355
|
+
const page = await entry.client.request("thread/backgroundTerminals/list", {
|
|
117356
|
+
threadId: entry.threadId,
|
|
117357
|
+
cursor
|
|
117358
|
+
});
|
|
117359
|
+
for (const terminal of page.data) {
|
|
117360
|
+
if (!started.has(terminal.itemId)) continue;
|
|
117361
|
+
await entry.client.request("thread/backgroundTerminals/terminate", {
|
|
117362
|
+
threadId: entry.threadId,
|
|
117363
|
+
processId: terminal.processId
|
|
117364
|
+
});
|
|
117365
|
+
}
|
|
117366
|
+
cursor = page.nextCursor;
|
|
117367
|
+
} while (cursor);
|
|
117368
|
+
} catch (err) {
|
|
117369
|
+
console.warn(`[codex] could not end the commands of stopped turn ${turnId}: ${err.message}`);
|
|
117370
|
+
}
|
|
117371
|
+
}
|
|
117372
|
+
async function interruptTurn(sessionId, threadId) {
|
|
117061
117373
|
const entry = sessionMap.get(sessionId);
|
|
117062
|
-
|
|
117063
|
-
|
|
117064
|
-
|
|
117065
|
-
|
|
117374
|
+
const target = entry ? turnToStop(entry, threadId) : void 0;
|
|
117375
|
+
if (entry && target) {
|
|
117376
|
+
const codexId = target.codexId ?? await within(target.started, interruptWaitMs());
|
|
117377
|
+
let stopped = false;
|
|
117378
|
+
if (codexId && !target.done) {
|
|
117379
|
+
try {
|
|
117380
|
+
await entry.client.request("turn/interrupt", {
|
|
117381
|
+
threadId: entry.threadId,
|
|
117382
|
+
turnId: codexId
|
|
117383
|
+
});
|
|
117384
|
+
stopped = true;
|
|
117385
|
+
} catch (err) {
|
|
117386
|
+
console.warn(`[codex] turn/interrupt failed for turn ${target.id}: ${err.message}`);
|
|
117387
|
+
}
|
|
117388
|
+
}
|
|
117389
|
+
const live = !target.done;
|
|
117390
|
+
if (live) {
|
|
117391
|
+
cancelTurn(entry, target);
|
|
117392
|
+
if (!stopped) void retireEntry(entry, "fail");
|
|
117393
|
+
}
|
|
117394
|
+
if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
|
|
117395
|
+
if (live || stopped) return true;
|
|
117066
117396
|
}
|
|
117397
|
+
return abortOrphanTurn(sessionId, threadId);
|
|
117398
|
+
}
|
|
117399
|
+
function clearThread(sessionId) {
|
|
117400
|
+
const entry = sessionMap.get(sessionId);
|
|
117401
|
+
if (entry) void retireEntry(entry, "cancel");
|
|
117067
117402
|
}
|
|
117068
117403
|
function clearAllThreads() {
|
|
117069
|
-
for (const
|
|
117070
|
-
entry.client.close().catch(() => {
|
|
117071
|
-
});
|
|
117072
|
-
}
|
|
117404
|
+
for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
|
|
117073
117405
|
sessionMap.clear();
|
|
117406
|
+
startingThreads.clear();
|
|
117074
117407
|
titleGenerating.clear();
|
|
117075
117408
|
}
|
|
117076
117409
|
var titleGenerating = /* @__PURE__ */ new Set();
|
|
@@ -117250,8 +117583,42 @@ async function getModels() {
|
|
|
117250
117583
|
}
|
|
117251
117584
|
}
|
|
117252
117585
|
async function shutdown() {
|
|
117253
|
-
|
|
117254
|
-
|
|
117586
|
+
let db2 = null;
|
|
117587
|
+
try {
|
|
117588
|
+
db2 = getDb();
|
|
117589
|
+
} catch {
|
|
117590
|
+
db2 = null;
|
|
117591
|
+
}
|
|
117592
|
+
const closing = [closeSharedAppServer()];
|
|
117593
|
+
for (const entry of [...sessionMap.values()]) {
|
|
117594
|
+
for (const active of [...entry.turns]) {
|
|
117595
|
+
if (active.discussionThreadId) continue;
|
|
117596
|
+
endTurn(entry, active);
|
|
117597
|
+
if (!db2) continue;
|
|
117598
|
+
try {
|
|
117599
|
+
markTurnInterrupted(db2, active.id, "host_shutdown", { notify: false });
|
|
117600
|
+
} catch (err) {
|
|
117601
|
+
console.error("[codex] could not park turn for resume:", err.message);
|
|
117602
|
+
}
|
|
117603
|
+
}
|
|
117604
|
+
closing.push(retireEntry(entry, "keep"));
|
|
117605
|
+
}
|
|
117606
|
+
await Promise.all(closing);
|
|
117607
|
+
titleGenerating.clear();
|
|
117608
|
+
}
|
|
117609
|
+
async function reapOrphans() {
|
|
117610
|
+
const ended = await reapOrphanProcesses(getDb(), "codex");
|
|
117611
|
+
if (ended > 0) console.log(`[codex] ended ${ended} app-server(s) left by the previous host`);
|
|
117612
|
+
}
|
|
117613
|
+
async function resumeInterruptedTurn(session, turn, _opts) {
|
|
117614
|
+
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
117615
|
+
const entry = await getOrCreateThread(session);
|
|
117616
|
+
if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
|
|
117617
|
+
if (!isTurnLive(getDb(), turn.id)) return;
|
|
117618
|
+
const codexId = turn.external_turn_id;
|
|
117619
|
+
const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
|
|
117620
|
+
const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
|
|
117621
|
+
await runTurn(session, turn, entry, input, true);
|
|
117255
117622
|
}
|
|
117256
117623
|
var codexProvider = {
|
|
117257
117624
|
startTurn: startTurn2,
|
|
@@ -117260,6 +117627,8 @@ var codexProvider = {
|
|
|
117260
117627
|
clearAllThreads,
|
|
117261
117628
|
getModels,
|
|
117262
117629
|
summarizeThread: summarizeCodexThread,
|
|
117630
|
+
resumeInterruptedTurn,
|
|
117631
|
+
reapOrphans,
|
|
117263
117632
|
shutdown
|
|
117264
117633
|
};
|
|
117265
117634
|
|
|
@@ -117591,64 +117960,6 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
|
|
|
117591
117960
|
return "fatal";
|
|
117592
117961
|
}
|
|
117593
117962
|
|
|
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
117963
|
// src/claude/claude-provider.ts
|
|
117653
117964
|
var PromptQueue = class {
|
|
117654
117965
|
buffer = [];
|
|
@@ -117865,7 +118176,7 @@ function trackResumeFrame(entry, message, db2) {
|
|
|
117865
118176
|
}
|
|
117866
118177
|
return true;
|
|
117867
118178
|
}
|
|
117868
|
-
function
|
|
118179
|
+
function failTurn2(db2, sessionId, turnId, error51) {
|
|
117869
118180
|
const row = db2.prepare("SELECT resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117870
118181
|
if (row?.resume_state === "waiting" || row?.resume_state === "resuming") {
|
|
117871
118182
|
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
@@ -117888,7 +118199,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
|
|
|
117888
118199
|
if (!entry.threadId && !entry.closeReason && isSignalExit(errMsg)) {
|
|
117889
118200
|
markTurnInterrupted(db2, turnId, "process_exit", { detail: errMsg });
|
|
117890
118201
|
} else {
|
|
117891
|
-
|
|
118202
|
+
failTurn2(db2, sessionId, turnId, errMsg);
|
|
117892
118203
|
}
|
|
117893
118204
|
}
|
|
117894
118205
|
if (staleItems.changes > 0) {
|
|
@@ -117987,7 +118298,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
117987
118298
|
const currentTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
117988
118299
|
if (currentTurn && currentTurn.status === "running") {
|
|
117989
118300
|
const usage = currentTurn.token_usage ? JSON.parse(currentTurn.token_usage) : null;
|
|
117990
|
-
|
|
118301
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
117991
118302
|
}
|
|
117992
118303
|
syncThreadTitle2(session.id);
|
|
117993
118304
|
}
|
|
@@ -118053,7 +118364,7 @@ async function startTurn3(session, turn) {
|
|
|
118053
118364
|
const prevTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
118054
118365
|
if (prevTurn && prevTurn.status === "running") {
|
|
118055
118366
|
const usage = prevTurn.token_usage ? JSON.parse(prevTurn.token_usage) : null;
|
|
118056
|
-
|
|
118367
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
118057
118368
|
}
|
|
118058
118369
|
syncThreadTitle2(session.id);
|
|
118059
118370
|
streamingMessageIds.delete(entry.turnId);
|
|
@@ -118542,18 +118853,18 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118542
118853
|
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
|
|
118543
118854
|
return;
|
|
118544
118855
|
}
|
|
118545
|
-
|
|
118856
|
+
failTurn2(db2, sessionId, turnId, text2);
|
|
118546
118857
|
return;
|
|
118547
118858
|
}
|
|
118548
118859
|
await refreshContext(entry, sessionId, db2);
|
|
118549
|
-
|
|
118860
|
+
completeTurn2(db2, sessionId, turnId, usage);
|
|
118550
118861
|
} else {
|
|
118551
118862
|
entry.lastApiError = null;
|
|
118552
118863
|
const errorMsg = message.errors?.join("; ") || "Claude turn failed";
|
|
118553
|
-
|
|
118864
|
+
failTurn2(db2, sessionId, turnId, errorMsg);
|
|
118554
118865
|
}
|
|
118555
118866
|
}
|
|
118556
|
-
function
|
|
118867
|
+
function completeTurn2(db2, sessionId, turnId, usage) {
|
|
118557
118868
|
markTurnResumed(db2, turnId, { settle: true });
|
|
118558
118869
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
118559
118870
|
const response = turnResponse(db2, turnId);
|
|
@@ -118836,7 +119147,7 @@ async function shutdown2() {
|
|
|
118836
119147
|
}
|
|
118837
119148
|
clearAllThreads2();
|
|
118838
119149
|
}
|
|
118839
|
-
async function
|
|
119150
|
+
async function reapOrphans2() {
|
|
118840
119151
|
const ended = await reapOrphanCliProcesses(getDb());
|
|
118841
119152
|
if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
|
|
118842
119153
|
}
|
|
@@ -118849,7 +119160,7 @@ function retireCli(sessionId, entry) {
|
|
|
118849
119160
|
entry.query.close();
|
|
118850
119161
|
sessionMap2.delete(sessionId);
|
|
118851
119162
|
}
|
|
118852
|
-
async function
|
|
119163
|
+
async function resumeInterruptedTurn2(session, turn, opts) {
|
|
118853
119164
|
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
118854
119165
|
let live = sessionMap2.get(session.id);
|
|
118855
119166
|
if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
|
|
@@ -119011,8 +119322,8 @@ var claudeProvider = {
|
|
|
119011
119322
|
setModel,
|
|
119012
119323
|
stopTask,
|
|
119013
119324
|
listBackgroundTasks,
|
|
119014
|
-
resumeInterruptedTurn,
|
|
119015
|
-
reapOrphans,
|
|
119325
|
+
resumeInterruptedTurn: resumeInterruptedTurn2,
|
|
119326
|
+
reapOrphans: reapOrphans2,
|
|
119016
119327
|
shutdown: shutdown2
|
|
119017
119328
|
};
|
|
119018
119329
|
|
|
@@ -119501,11 +119812,13 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119501
119812
|
if (opts.signal?.aborted || err.name === "AbortError") {
|
|
119502
119813
|
return "aborted";
|
|
119503
119814
|
}
|
|
119815
|
+
opts.onDisconnect?.();
|
|
119504
119816
|
await reconnectDelay(delayMs, opts.signal);
|
|
119505
119817
|
continue;
|
|
119506
119818
|
}
|
|
119507
119819
|
if (response.status === 404) return "session-not-found";
|
|
119508
119820
|
if (!response.ok || !response.body) {
|
|
119821
|
+
opts.onDisconnect?.();
|
|
119509
119822
|
await reconnectDelay(delayMs, opts.signal);
|
|
119510
119823
|
continue;
|
|
119511
119824
|
}
|
|
@@ -119519,6 +119832,7 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119519
119832
|
});
|
|
119520
119833
|
return reason;
|
|
119521
119834
|
}
|
|
119835
|
+
opts.onDisconnect?.();
|
|
119522
119836
|
await reconnectDelay(delayMs, opts.signal);
|
|
119523
119837
|
}
|
|
119524
119838
|
}
|
|
@@ -120187,6 +120501,9 @@ function mapReasoningEffort(modelId, effort) {
|
|
|
120187
120501
|
}
|
|
120188
120502
|
var sessionMap3 = /* @__PURE__ */ new Map();
|
|
120189
120503
|
var STALLED_STREAM_MS = 6e4;
|
|
120504
|
+
var BACKEND_LOST_MS = 3e4;
|
|
120505
|
+
var BACKEND_RESTARTED_ERROR = "The Repoburg backend restarted while this turn ran, so the turn was lost. Send the prompt again.";
|
|
120506
|
+
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
120507
|
function isConnectionError(err) {
|
|
120191
120508
|
const message = String(err?.message ?? "");
|
|
120192
120509
|
return /fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|socket hang up/i.test(
|
|
@@ -120310,7 +120627,7 @@ function failTurnBeforeStart(db2, sessionId, turnId, error51) {
|
|
|
120310
120627
|
recomputeSessionRunning(db2, sessionId, "failed");
|
|
120311
120628
|
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
120312
120629
|
}
|
|
120313
|
-
function
|
|
120630
|
+
function failTurn3(entry, error51) {
|
|
120314
120631
|
const active = entry.activeTurn;
|
|
120315
120632
|
if (!active) return;
|
|
120316
120633
|
entry.activeTurn = null;
|
|
@@ -120334,32 +120651,61 @@ function failTurn2(entry, error51) {
|
|
|
120334
120651
|
broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
|
|
120335
120652
|
}
|
|
120336
120653
|
async function runStreamLoop(entry, projector) {
|
|
120337
|
-
|
|
120338
|
-
|
|
120339
|
-
|
|
120340
|
-
|
|
120341
|
-
|
|
120342
|
-
|
|
120654
|
+
const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
|
|
120655
|
+
const lose = (error51) => {
|
|
120656
|
+
if (isCurrent()) failTurn3(entry, error51);
|
|
120657
|
+
};
|
|
120658
|
+
let lostTimer = null;
|
|
120659
|
+
const clearLostTimer = () => {
|
|
120660
|
+
if (lostTimer) clearTimeout(lostTimer);
|
|
120661
|
+
lostTimer = null;
|
|
120662
|
+
};
|
|
120663
|
+
try {
|
|
120664
|
+
while (isCurrent()) {
|
|
120665
|
+
const active = entry.activeTurn;
|
|
120666
|
+
const controller = new AbortController();
|
|
120667
|
+
active.sseAbort = controller;
|
|
120668
|
+
let stallTimer = null;
|
|
120669
|
+
const resetStall = () => {
|
|
120670
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
120671
|
+
stallTimer = setTimeout(() => controller.abort(), STALLED_STREAM_MS);
|
|
120672
|
+
};
|
|
120673
|
+
resetStall();
|
|
120674
|
+
const onMessage = (message) => {
|
|
120675
|
+
if (message.type === "system") {
|
|
120676
|
+
clearLostTimer();
|
|
120677
|
+
const bootId = message.bootId ?? null;
|
|
120678
|
+
if (active.bootId === void 0) active.bootId = bootId;
|
|
120679
|
+
else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
|
|
120680
|
+
}
|
|
120681
|
+
projector.handle(message);
|
|
120682
|
+
};
|
|
120683
|
+
const onDisconnect = () => {
|
|
120684
|
+
if (typeof active.bootId !== "string" || lostTimer) return;
|
|
120685
|
+
lostTimer = setTimeout(() => {
|
|
120686
|
+
lostTimer = null;
|
|
120687
|
+
invalidateBackend(entry.baseUrl);
|
|
120688
|
+
lose(BACKEND_UNREACHABLE_ERROR);
|
|
120689
|
+
}, BACKEND_LOST_MS);
|
|
120690
|
+
};
|
|
120691
|
+
const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
|
|
120692
|
+
signal: controller.signal,
|
|
120693
|
+
onActivity: resetStall,
|
|
120694
|
+
onDisconnect
|
|
120695
|
+
});
|
|
120343
120696
|
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;
|
|
120697
|
+
if (!isCurrent()) return;
|
|
120698
|
+
if (reason === "session-not-found") {
|
|
120699
|
+
failTurn3(entry, "Repoburg session no longer exists on the backend.");
|
|
120700
|
+
return;
|
|
120701
|
+
}
|
|
120702
|
+
if (reason === "aborted") {
|
|
120703
|
+
if (active.cancelled) return;
|
|
120704
|
+
continue;
|
|
120705
|
+
}
|
|
120362
120706
|
}
|
|
120707
|
+
} finally {
|
|
120708
|
+
clearLostTimer();
|
|
120363
120709
|
}
|
|
120364
120710
|
}
|
|
120365
120711
|
function turnImageDataUrls(turn) {
|
|
@@ -120445,7 +120791,7 @@ async function startTurn4(session, turn) {
|
|
|
120445
120791
|
void ensureContextWindow(entry);
|
|
120446
120792
|
runStreamLoop(entry, projector).catch((err) => {
|
|
120447
120793
|
console.error("[repoburg] stream loop crashed:", err);
|
|
120448
|
-
|
|
120794
|
+
failTurn3(entry, `Stream loop failed: ${err.message}`);
|
|
120449
120795
|
});
|
|
120450
120796
|
try {
|
|
120451
120797
|
const images = turnImageDataUrls(turn);
|
|
@@ -120456,7 +120802,7 @@ async function startTurn4(session, turn) {
|
|
|
120456
120802
|
});
|
|
120457
120803
|
} catch (err) {
|
|
120458
120804
|
if (isConnectionError(err)) invalidateBackend(entry.baseUrl);
|
|
120459
|
-
|
|
120805
|
+
failTurn3(entry, err.message);
|
|
120460
120806
|
}
|
|
120461
120807
|
}
|
|
120462
120808
|
async function interruptTurn3(sessionId, threadId) {
|