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");
|
|
@@ -43613,6 +43617,7 @@ import { readFileSync } from "node:fs";
|
|
|
43613
43617
|
import { spawn } from "node:child_process";
|
|
43614
43618
|
import { EventEmitter } from "node:events";
|
|
43615
43619
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
43620
|
+
var CLOSE_GRACE_MS = 2e3;
|
|
43616
43621
|
var AppServerClient = class {
|
|
43617
43622
|
proc;
|
|
43618
43623
|
nextId = 1;
|
|
@@ -43621,6 +43626,8 @@ var AppServerClient = class {
|
|
|
43621
43626
|
requestHandlers = /* @__PURE__ */ new Map();
|
|
43622
43627
|
buffer = "";
|
|
43623
43628
|
closed = false;
|
|
43629
|
+
/** The process is gone (exit), or never started (spawn error). */
|
|
43630
|
+
gone = false;
|
|
43624
43631
|
clientInfo;
|
|
43625
43632
|
/** Bound stdout listener — removed in close() so stale data is not processed. */
|
|
43626
43633
|
stdoutListener = (chunk) => this.onStdoutData(chunk);
|
|
@@ -43634,6 +43641,8 @@ var AppServerClient = class {
|
|
|
43634
43641
|
stdio: ["pipe", "pipe", "pipe"]
|
|
43635
43642
|
});
|
|
43636
43643
|
this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
|
|
43644
|
+
this.proc.stdin?.on("error", () => {
|
|
43645
|
+
});
|
|
43637
43646
|
this.proc.stdout?.setEncoding("utf-8");
|
|
43638
43647
|
this.proc.stdout?.on("data", this.stdoutListener);
|
|
43639
43648
|
this.proc.stderr?.on("data", (chunk) => {
|
|
@@ -43641,6 +43650,7 @@ var AppServerClient = class {
|
|
|
43641
43650
|
if (text2) console.error("[app-server] stderr:", text2);
|
|
43642
43651
|
});
|
|
43643
43652
|
this.proc.on("exit", (code, signal) => {
|
|
43653
|
+
this.gone = true;
|
|
43644
43654
|
this.onProcessExit(code, signal);
|
|
43645
43655
|
});
|
|
43646
43656
|
this.proc.on("error", (err) => {
|
|
@@ -43700,7 +43710,17 @@ var AppServerClient = class {
|
|
|
43700
43710
|
isClosed() {
|
|
43701
43711
|
return this.closed;
|
|
43702
43712
|
}
|
|
43703
|
-
/**
|
|
43713
|
+
/** Pid of the app-server process (the codex launcher), undefined when it never started. */
|
|
43714
|
+
get pid() {
|
|
43715
|
+
return this.proc.pid;
|
|
43716
|
+
}
|
|
43717
|
+
/**
|
|
43718
|
+
* Close the client and end the app-server. Its stdin is closed first: on end
|
|
43719
|
+
* of input the app-server shuts down and ends the commands it runs, while a
|
|
43720
|
+
* SIGTERM makes it exit at once and leaves them running. SIGTERM follows
|
|
43721
|
+
* only when it has not exited CLOSE_GRACE_MS later, SIGKILL after another
|
|
43722
|
+
* CLOSE_GRACE_MS. Resolves once it exited (or got SIGKILL).
|
|
43723
|
+
*/
|
|
43704
43724
|
async close() {
|
|
43705
43725
|
if (this.closed) return;
|
|
43706
43726
|
this.closed = true;
|
|
@@ -43710,7 +43730,27 @@ var AppServerClient = class {
|
|
|
43710
43730
|
entry.reject(new Error("AppServerClient closed"));
|
|
43711
43731
|
this.pending.delete(id);
|
|
43712
43732
|
}
|
|
43733
|
+
this.proc.stdin?.end();
|
|
43734
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43713
43735
|
this.proc.kill("SIGTERM");
|
|
43736
|
+
if (await this.exitWithin(CLOSE_GRACE_MS)) return;
|
|
43737
|
+
this.proc.kill("SIGKILL");
|
|
43738
|
+
}
|
|
43739
|
+
/** True once the process exited, false when it is still running after `ms`. */
|
|
43740
|
+
exitWithin(ms) {
|
|
43741
|
+
if (this.gone) return Promise.resolve(true);
|
|
43742
|
+
return new Promise((resolve) => {
|
|
43743
|
+
const onExit = () => {
|
|
43744
|
+
clearTimeout(timer2);
|
|
43745
|
+
resolve(true);
|
|
43746
|
+
};
|
|
43747
|
+
const timer2 = setTimeout(() => {
|
|
43748
|
+
this.proc.removeListener("exit", onExit);
|
|
43749
|
+
resolve(false);
|
|
43750
|
+
}, ms);
|
|
43751
|
+
timer2.unref?.();
|
|
43752
|
+
this.proc.once("exit", onExit);
|
|
43753
|
+
});
|
|
43714
43754
|
}
|
|
43715
43755
|
// --- Internal methods ---
|
|
43716
43756
|
write(message) {
|
|
@@ -43786,6 +43826,7 @@ var AppServerClient = class {
|
|
|
43786
43826
|
onProcessExit(code, signal) {
|
|
43787
43827
|
if (this.closed) return;
|
|
43788
43828
|
this.closed = true;
|
|
43829
|
+
this.proc.stdin?.end();
|
|
43789
43830
|
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
43790
43831
|
const error51 = new Error(`App-server process exited (${reason})`);
|
|
43791
43832
|
for (const [, entry] of this.pending) {
|
|
@@ -43799,6 +43840,7 @@ var AppServerClient = class {
|
|
|
43799
43840
|
* binary is missing). Rejects pending requests and emits 'closed' so callers
|
|
43800
43841
|
* can fail gracefully instead of crashing the whole process. */
|
|
43801
43842
|
onProcessError(err) {
|
|
43843
|
+
if (this.proc.pid === void 0) this.gone = true;
|
|
43802
43844
|
if (this.closed) return;
|
|
43803
43845
|
this.closed = true;
|
|
43804
43846
|
for (const [, entry] of this.pending) {
|
|
@@ -116648,8 +116690,111 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
|
|
|
116648
116690
|
];
|
|
116649
116691
|
}
|
|
116650
116692
|
|
|
116693
|
+
// src/claude/cli-orphans.ts
|
|
116694
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
116695
|
+
var TERM_GRACE_MS = 2e3;
|
|
116696
|
+
var POLL_MS = 100;
|
|
116697
|
+
function inspectProcess(pid) {
|
|
116698
|
+
return new Promise((resolve) => {
|
|
116699
|
+
execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
|
|
116700
|
+
const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
|
|
116701
|
+
resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
|
|
116702
|
+
});
|
|
116703
|
+
});
|
|
116704
|
+
}
|
|
116705
|
+
function listDescendants(pid) {
|
|
116706
|
+
return new Promise((resolve) => {
|
|
116707
|
+
execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
|
|
116708
|
+
if (err) {
|
|
116709
|
+
resolve([]);
|
|
116710
|
+
return;
|
|
116711
|
+
}
|
|
116712
|
+
const children = /* @__PURE__ */ new Map();
|
|
116713
|
+
for (const line of stdout.split("\n")) {
|
|
116714
|
+
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
116715
|
+
if (!match) continue;
|
|
116716
|
+
const parent = Number(match[2]);
|
|
116717
|
+
children.set(parent, [...children.get(parent) ?? [], Number(match[1])]);
|
|
116718
|
+
}
|
|
116719
|
+
const found = [];
|
|
116720
|
+
const queue = [...children.get(pid) ?? []];
|
|
116721
|
+
while (queue.length > 0) {
|
|
116722
|
+
const next = queue.shift();
|
|
116723
|
+
found.push(next);
|
|
116724
|
+
queue.push(...children.get(next) ?? []);
|
|
116725
|
+
}
|
|
116726
|
+
resolve(found);
|
|
116727
|
+
});
|
|
116728
|
+
});
|
|
116729
|
+
}
|
|
116730
|
+
var defaultDeps = {
|
|
116731
|
+
inspect: inspectProcess,
|
|
116732
|
+
descendants: listDescendants,
|
|
116733
|
+
kill: (pid, signal) => {
|
|
116734
|
+
try {
|
|
116735
|
+
process.kill(pid, signal);
|
|
116736
|
+
} catch {
|
|
116737
|
+
}
|
|
116738
|
+
},
|
|
116739
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
116740
|
+
};
|
|
116741
|
+
var isOrphan = {
|
|
116742
|
+
claude: (info) => info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json"),
|
|
116743
|
+
// The codex launcher (`node …/codex app-server …`) or the binary itself.
|
|
116744
|
+
codex: (info) => info.ppid === 1 && /\bcodex\b/.test(info.command) && /\bapp-server\b/.test(info.command)
|
|
116745
|
+
};
|
|
116746
|
+
async function endProcesses(pids, deps) {
|
|
116747
|
+
for (const pid of pids) deps.kill(pid, "SIGTERM");
|
|
116748
|
+
for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
|
|
116749
|
+
await deps.sleep(POLL_MS);
|
|
116750
|
+
const alive = await Promise.all(pids.map((pid) => deps.inspect(pid)));
|
|
116751
|
+
if (alive.every((info) => !info)) return;
|
|
116752
|
+
}
|
|
116753
|
+
for (const pid of pids) {
|
|
116754
|
+
if (await deps.inspect(pid)) deps.kill(pid, "SIGKILL");
|
|
116755
|
+
}
|
|
116756
|
+
}
|
|
116757
|
+
function recordCliProcess(db2, pid, sessionId, runtime = "claude") {
|
|
116758
|
+
db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, runtime, created_at) VALUES (?, ?, ?, ?)").run(
|
|
116759
|
+
pid,
|
|
116760
|
+
sessionId,
|
|
116761
|
+
runtime,
|
|
116762
|
+
(/* @__PURE__ */ new Date()).toISOString()
|
|
116763
|
+
);
|
|
116764
|
+
}
|
|
116765
|
+
function forgetCliProcess(db2, pid) {
|
|
116766
|
+
db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
|
|
116767
|
+
}
|
|
116768
|
+
async function reapOrphanProcesses(db2, runtime, deps = defaultDeps) {
|
|
116769
|
+
const rows = db2.prepare("SELECT pid FROM cli_processes WHERE runtime = ?").all(runtime);
|
|
116770
|
+
const ended = await Promise.all(
|
|
116771
|
+
rows.map(async ({ pid }) => {
|
|
116772
|
+
const info = await deps.inspect(pid);
|
|
116773
|
+
if (info?.ppid === process.pid) return false;
|
|
116774
|
+
const orphan = info !== null && isOrphan[runtime](info);
|
|
116775
|
+
if (orphan) {
|
|
116776
|
+
const tree = runtime === "codex" ? await deps.descendants(pid) : [];
|
|
116777
|
+
await endProcesses([...tree, pid], deps);
|
|
116778
|
+
}
|
|
116779
|
+
forgetCliProcess(db2, pid);
|
|
116780
|
+
return orphan;
|
|
116781
|
+
})
|
|
116782
|
+
);
|
|
116783
|
+
return ended.filter(Boolean).length;
|
|
116784
|
+
}
|
|
116785
|
+
function reapOrphanCliProcesses(db2, deps = defaultDeps) {
|
|
116786
|
+
return reapOrphanProcesses(db2, "claude", deps);
|
|
116787
|
+
}
|
|
116788
|
+
|
|
116651
116789
|
// src/codex/codex-provider.ts
|
|
116652
116790
|
var sessionMap = /* @__PURE__ */ new Map();
|
|
116791
|
+
var startingThreads = /* @__PURE__ */ new Map();
|
|
116792
|
+
var ENDED_TURNS_KEPT = 20;
|
|
116793
|
+
function interruptWaitMs() {
|
|
116794
|
+
const ms = Number(process.env.AGENT_PANE_CODEX_INTERRUPT_WAIT_MS);
|
|
116795
|
+
return Number.isFinite(ms) && ms > 0 ? ms : 1e4;
|
|
116796
|
+
}
|
|
116797
|
+
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
116798
|
function setSessionStatus(db2, sessionId, isRunning, status, now, hasUnreviewed = false) {
|
|
116654
116799
|
if (hasUnreviewed) {
|
|
116655
116800
|
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
@@ -116728,50 +116873,290 @@ function autoApproveToolUserInput(client) {
|
|
|
116728
116873
|
return { answers };
|
|
116729
116874
|
});
|
|
116730
116875
|
}
|
|
116731
|
-
|
|
116876
|
+
function trackProcess(pid, sessionId) {
|
|
116877
|
+
if (pid === void 0) return;
|
|
116878
|
+
try {
|
|
116879
|
+
recordCliProcess(getDb(), pid, sessionId, "codex");
|
|
116880
|
+
} catch {
|
|
116881
|
+
}
|
|
116882
|
+
}
|
|
116883
|
+
function untrackProcess(pid) {
|
|
116884
|
+
if (pid === void 0) return;
|
|
116885
|
+
try {
|
|
116886
|
+
forgetCliProcess(getDb(), pid);
|
|
116887
|
+
} catch {
|
|
116888
|
+
}
|
|
116889
|
+
}
|
|
116890
|
+
function getOrCreateThread(session) {
|
|
116732
116891
|
const existing = sessionMap.get(session.id);
|
|
116733
|
-
if (existing) return existing;
|
|
116892
|
+
if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
|
|
116893
|
+
const pending = startingThreads.get(session.id);
|
|
116894
|
+
if (pending) return pending;
|
|
116895
|
+
const started = startThread(session).finally(() => startingThreads.delete(session.id));
|
|
116896
|
+
startingThreads.set(session.id, started);
|
|
116897
|
+
return started;
|
|
116898
|
+
}
|
|
116899
|
+
async function startThread(session) {
|
|
116734
116900
|
const cwd = session.cwd ?? process.cwd();
|
|
116735
116901
|
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
|
-
|
|
116902
|
+
const entry = {
|
|
116903
|
+
sessionId: session.id,
|
|
116904
|
+
client,
|
|
116905
|
+
pid: client.pid,
|
|
116906
|
+
threadId: "",
|
|
116907
|
+
turns: [],
|
|
116908
|
+
ended: /* @__PURE__ */ new Map(),
|
|
116909
|
+
resumedTurnIds: null,
|
|
116910
|
+
closing: null
|
|
116911
|
+
};
|
|
116912
|
+
trackProcess(entry.pid, session.id);
|
|
116913
|
+
listen(entry);
|
|
116914
|
+
try {
|
|
116915
|
+
await client.initialize();
|
|
116916
|
+
if (session.origin_app_id) {
|
|
116917
|
+
autoApproveToolUserInput(client);
|
|
116918
|
+
}
|
|
116919
|
+
const config3 = parseRuntimeConfig(session);
|
|
116920
|
+
const sandbox = sandboxType(config3);
|
|
116921
|
+
const instructions = threadInstructionParams(cwd);
|
|
116922
|
+
if (session.external_thread_id) {
|
|
116923
|
+
const result = await client.request("thread/resume", {
|
|
116924
|
+
threadId: session.external_thread_id,
|
|
116925
|
+
cwd,
|
|
116926
|
+
approvalPolicy: "never",
|
|
116927
|
+
sandbox,
|
|
116928
|
+
model: session.model ?? void 0,
|
|
116929
|
+
...instructions
|
|
116930
|
+
});
|
|
116931
|
+
entry.threadId = result.thread.id;
|
|
116932
|
+
entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
|
|
116933
|
+
} else {
|
|
116934
|
+
const result = await client.request("thread/start", {
|
|
116935
|
+
cwd,
|
|
116936
|
+
approvalPolicy: "never",
|
|
116937
|
+
sandbox,
|
|
116938
|
+
model: session.model ?? void 0,
|
|
116939
|
+
...instructions
|
|
116940
|
+
});
|
|
116941
|
+
entry.threadId = result.thread.id;
|
|
116942
|
+
const db2 = getDb();
|
|
116943
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116944
|
+
db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
|
|
116945
|
+
entry.threadId,
|
|
116946
|
+
now,
|
|
116947
|
+
session.id
|
|
116948
|
+
);
|
|
116949
|
+
}
|
|
116950
|
+
} catch (err) {
|
|
116951
|
+
void retireEntry(entry, "keep");
|
|
116952
|
+
throw err;
|
|
116770
116953
|
}
|
|
116771
|
-
const entry = { client, threadId, turnId: null };
|
|
116772
116954
|
sessionMap.set(session.id, entry);
|
|
116773
116955
|
return entry;
|
|
116774
116956
|
}
|
|
116957
|
+
function retireEntry(entry, left, error51 = "App-server closed") {
|
|
116958
|
+
if (entry.closing) return entry.closing;
|
|
116959
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116960
|
+
if (left !== "keep") {
|
|
116961
|
+
for (const active of [...entry.turns]) {
|
|
116962
|
+
endTurn(entry, active);
|
|
116963
|
+
try {
|
|
116964
|
+
const db2 = getDb();
|
|
116965
|
+
if (left === "cancel") abortTurn(db2, entry.sessionId, active.id);
|
|
116966
|
+
else failTurn(db2, entry.sessionId, active.id, error51);
|
|
116967
|
+
} catch (err) {
|
|
116968
|
+
console.error(`[codex] could not settle turn ${active.id}:`, err.message);
|
|
116969
|
+
}
|
|
116970
|
+
}
|
|
116971
|
+
}
|
|
116972
|
+
entry.closing = entry.client.close().catch(() => {
|
|
116973
|
+
}).finally(() => untrackProcess(entry.pid));
|
|
116974
|
+
return entry.closing;
|
|
116975
|
+
}
|
|
116976
|
+
function onClientClosed(entry, reason) {
|
|
116977
|
+
if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
|
|
116978
|
+
untrackProcess(entry.pid);
|
|
116979
|
+
if (entry.closing || entry.turns.length === 0) return;
|
|
116980
|
+
let db2;
|
|
116981
|
+
try {
|
|
116982
|
+
db2 = getDb();
|
|
116983
|
+
} catch {
|
|
116984
|
+
return;
|
|
116985
|
+
}
|
|
116986
|
+
const detail = `App-server process exited (${reason})`;
|
|
116987
|
+
for (const active of [...entry.turns]) {
|
|
116988
|
+
endTurn(entry, active);
|
|
116989
|
+
failOpenItems(db2, entry.sessionId, active.id);
|
|
116990
|
+
if (active.discussionThreadId) {
|
|
116991
|
+
failTurn(db2, entry.sessionId, active.id, "App-server process closed unexpectedly");
|
|
116992
|
+
} else {
|
|
116993
|
+
markTurnInterrupted(db2, active.id, "process_exit", { detail });
|
|
116994
|
+
}
|
|
116995
|
+
}
|
|
116996
|
+
}
|
|
116997
|
+
function isTurnLive(db2, turnId) {
|
|
116998
|
+
const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
|
|
116999
|
+
return row?.status === "pending" || row?.status === "running";
|
|
117000
|
+
}
|
|
117001
|
+
function endTurn(entry, active) {
|
|
117002
|
+
active.done = true;
|
|
117003
|
+
entry.turns = entry.turns.filter((t) => t !== active);
|
|
117004
|
+
rememberEnded(entry, active);
|
|
117005
|
+
}
|
|
117006
|
+
function rememberEnded(entry, active) {
|
|
117007
|
+
if (!active.codexId) return;
|
|
117008
|
+
entry.ended.set(active.codexId, active.id);
|
|
117009
|
+
if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
|
|
117010
|
+
}
|
|
117011
|
+
function liveTurnsOf(entry, codexId) {
|
|
117012
|
+
if (!codexId) return entry.turns.slice(-1);
|
|
117013
|
+
const known = entry.turns.filter((t) => t.codexId === codexId);
|
|
117014
|
+
if (known.length > 0 || entry.ended.has(codexId)) return known;
|
|
117015
|
+
const waiting = entry.turns.find((t) => t.codexId === null);
|
|
117016
|
+
if (!waiting) return [];
|
|
117017
|
+
waiting.codexId = codexId;
|
|
117018
|
+
return [waiting];
|
|
117019
|
+
}
|
|
117020
|
+
function noteContinued(active) {
|
|
117021
|
+
if (!active.resuming) return;
|
|
117022
|
+
active.resuming = false;
|
|
117023
|
+
markTurnResumed(getDb(), active.id);
|
|
117024
|
+
}
|
|
117025
|
+
function completeTurn(db2, sessionId, turnId, usage) {
|
|
117026
|
+
markTurnResumed(db2, turnId, { settle: true });
|
|
117027
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117028
|
+
const response = turnResponse(db2, turnId);
|
|
117029
|
+
const result = usage !== void 0 ? db2.prepare(
|
|
117030
|
+
"UPDATE turns SET status = 'completed', token_usage = ?, updated_at = ? WHERE id = ? AND status IN ('pending', 'running')"
|
|
117031
|
+
).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);
|
|
117032
|
+
if (result.changes === 0) return;
|
|
117033
|
+
broadcast("turn:completed", {
|
|
117034
|
+
sessionId,
|
|
117035
|
+
turnId,
|
|
117036
|
+
...usage !== void 0 ? { usage } : {},
|
|
117037
|
+
hasUnreviewed: true,
|
|
117038
|
+
response
|
|
117039
|
+
});
|
|
117040
|
+
recomputeSessionRunning(db2, sessionId, "active", true);
|
|
117041
|
+
syncThreadTitle(sessionId);
|
|
117042
|
+
}
|
|
117043
|
+
function failTurn(db2, sessionId, turnId, error51) {
|
|
117044
|
+
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117045
|
+
if (!row || row.status !== "pending" && row.status !== "running") return;
|
|
117046
|
+
if (row.resume_state === "waiting" || row.resume_state === "resuming") {
|
|
117047
|
+
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
117048
|
+
}
|
|
117049
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117050
|
+
db2.prepare("UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?").run("failed", error51, now, turnId);
|
|
117051
|
+
recomputeSessionRunning(db2, sessionId, "failed");
|
|
117052
|
+
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
117053
|
+
}
|
|
117054
|
+
function abortTurn(db2, sessionId, turnId) {
|
|
117055
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117056
|
+
const result = db2.prepare("UPDATE turns SET status = 'aborted', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(now, turnId);
|
|
117057
|
+
if (result.changes === 0) return false;
|
|
117058
|
+
markResumeCancelled(db2, turnId);
|
|
117059
|
+
recomputeSessionRunning(db2, sessionId);
|
|
117060
|
+
broadcast("turn:cancelled", { sessionId, turnId });
|
|
117061
|
+
return true;
|
|
117062
|
+
}
|
|
117063
|
+
function cancelTurn(entry, active) {
|
|
117064
|
+
if (active.done) return;
|
|
117065
|
+
endTurn(entry, active);
|
|
117066
|
+
abortTurn(getDb(), entry.sessionId, active.id);
|
|
117067
|
+
}
|
|
117068
|
+
function failOpenItems(db2, sessionId, turnId) {
|
|
117069
|
+
const rows = db2.prepare(
|
|
117070
|
+
"SELECT id, external_item_id, type, data, created_at FROM items WHERE turn_id = ? AND status = 'in_progress'"
|
|
117071
|
+
).all(turnId);
|
|
117072
|
+
if (rows.length === 0) return;
|
|
117073
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117074
|
+
db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE turn_id = ? AND status = 'in_progress'").run(
|
|
117075
|
+
now,
|
|
117076
|
+
turnId
|
|
117077
|
+
);
|
|
117078
|
+
for (const row of rows) {
|
|
117079
|
+
const item = {
|
|
117080
|
+
id: row.id,
|
|
117081
|
+
turn_id: turnId,
|
|
117082
|
+
external_item_id: row.external_item_id,
|
|
117083
|
+
type: row.type,
|
|
117084
|
+
data: row.data ? JSON.parse(row.data) : {},
|
|
117085
|
+
status: "failed",
|
|
117086
|
+
created_at: row.created_at,
|
|
117087
|
+
updated_at: now
|
|
117088
|
+
};
|
|
117089
|
+
broadcast("item:completed", { sessionId, turnId, item });
|
|
117090
|
+
}
|
|
117091
|
+
}
|
|
117092
|
+
function listen(entry) {
|
|
117093
|
+
const on = (method, handle) => {
|
|
117094
|
+
entry.client.onNotification(method, (params) => {
|
|
117095
|
+
const p = params;
|
|
117096
|
+
if (!p || p.threadId !== entry.threadId) return;
|
|
117097
|
+
handle(p);
|
|
117098
|
+
});
|
|
117099
|
+
};
|
|
117100
|
+
on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
|
|
117101
|
+
on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
|
|
117102
|
+
on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
|
|
117103
|
+
on("item/agentMessage/delta", (p) => onAgentMessageDelta(entry, p));
|
|
117104
|
+
on("turn/completed", (p) => onTurnCompleted(entry, p));
|
|
117105
|
+
on("turn/failed", (p) => onTurnFailed(entry, p));
|
|
117106
|
+
on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
|
|
117107
|
+
entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
|
|
117108
|
+
}
|
|
117109
|
+
function onItem(entry, p, status, event) {
|
|
117110
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117111
|
+
if (live) {
|
|
117112
|
+
if (!shouldSkipItem(p.item.type)) noteContinued(live);
|
|
117113
|
+
handleItemEvent(p, entry.sessionId, live.id, status, event);
|
|
117114
|
+
return;
|
|
117115
|
+
}
|
|
117116
|
+
const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
|
|
117117
|
+
if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
|
|
117118
|
+
}
|
|
117119
|
+
function onAgentMessageDelta(entry, p) {
|
|
117120
|
+
const [live] = liveTurnsOf(entry, p.turnId);
|
|
117121
|
+
if (!live) return;
|
|
117122
|
+
noteContinued(live);
|
|
117123
|
+
broadcast("item:delta", {
|
|
117124
|
+
sessionId: entry.sessionId,
|
|
117125
|
+
turnId: live.id,
|
|
117126
|
+
itemId: p.itemId,
|
|
117127
|
+
delta: p.delta
|
|
117128
|
+
});
|
|
117129
|
+
}
|
|
117130
|
+
function onTurnCompleted(entry, p) {
|
|
117131
|
+
const db2 = getDb();
|
|
117132
|
+
for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
|
|
117133
|
+
if (p.turn?.status === "interrupted") {
|
|
117134
|
+
cancelTurn(entry, live);
|
|
117135
|
+
} else if (p.turn?.status === "failed") {
|
|
117136
|
+
endTurn(entry, live);
|
|
117137
|
+
failTurn(db2, entry.sessionId, live.id, p.turn.error?.message ?? "Codex turn failed");
|
|
117138
|
+
} else {
|
|
117139
|
+
endTurn(entry, live);
|
|
117140
|
+
completeTurn(db2, entry.sessionId, live.id, p.usage);
|
|
117141
|
+
}
|
|
117142
|
+
}
|
|
117143
|
+
}
|
|
117144
|
+
function onTurnFailed(entry, p) {
|
|
117145
|
+
const db2 = getDb();
|
|
117146
|
+
for (const live of liveTurnsOf(entry, p.turnId)) {
|
|
117147
|
+
endTurn(entry, live);
|
|
117148
|
+
failTurn(db2, entry.sessionId, live.id, p.error.message);
|
|
117149
|
+
}
|
|
117150
|
+
}
|
|
117151
|
+
function onTokenUsage(entry, p) {
|
|
117152
|
+
const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
|
|
117153
|
+
if (!turnId) return;
|
|
117154
|
+
const usage = mapTokenUsage(p.tokenUsage.total);
|
|
117155
|
+
const db2 = getDb();
|
|
117156
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
117157
|
+
db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
|
|
117158
|
+
broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
|
|
117159
|
+
}
|
|
116775
117160
|
function turnAttachments2(turn) {
|
|
116776
117161
|
const raw = turn.attachments;
|
|
116777
117162
|
if (!raw) return [];
|
|
@@ -116805,175 +117190,63 @@ ${decoded}
|
|
|
116805
117190
|
}
|
|
116806
117191
|
return input;
|
|
116807
117192
|
}
|
|
117193
|
+
async function runTurn(session, turn, entry, input, resume) {
|
|
117194
|
+
const db2 = getDb();
|
|
117195
|
+
const sandbox = sandboxType(parseRuntimeConfig(session));
|
|
117196
|
+
let resolveStarted;
|
|
117197
|
+
const active = {
|
|
117198
|
+
id: turn.id,
|
|
117199
|
+
discussionThreadId: turn.thread_id ?? null,
|
|
117200
|
+
codexId: null,
|
|
117201
|
+
started: new Promise((resolve) => {
|
|
117202
|
+
resolveStarted = resolve;
|
|
117203
|
+
}),
|
|
117204
|
+
done: false,
|
|
117205
|
+
resuming: resume
|
|
117206
|
+
};
|
|
117207
|
+
entry.turns.push(active);
|
|
117208
|
+
try {
|
|
117209
|
+
const result = await entry.client.request("turn/start", {
|
|
117210
|
+
threadId: entry.threadId,
|
|
117211
|
+
input,
|
|
117212
|
+
approvalPolicy: "never",
|
|
117213
|
+
sandbox: { type: sandbox },
|
|
117214
|
+
model: session.model ?? void 0,
|
|
117215
|
+
effort: session.model_reasoning_effort ?? void 0
|
|
117216
|
+
});
|
|
117217
|
+
active.codexId = result.turn.id;
|
|
117218
|
+
if (active.done) rememberEnded(entry, active);
|
|
117219
|
+
db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
|
|
117220
|
+
result.turn.id,
|
|
117221
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
117222
|
+
turn.id
|
|
117223
|
+
);
|
|
117224
|
+
resolveStarted(result.turn.id);
|
|
117225
|
+
} catch (err) {
|
|
117226
|
+
const message = err.message;
|
|
117227
|
+
const settled = active.done;
|
|
117228
|
+
endTurn(entry, active);
|
|
117229
|
+
if (!message.startsWith("JSON-RPC error")) void retireEntry(entry, "fail", message);
|
|
117230
|
+
if (!settled && !resume) failTurn(db2, session.id, turn.id, message);
|
|
117231
|
+
resolveStarted(null);
|
|
117232
|
+
if (!settled && resume) throw err;
|
|
117233
|
+
}
|
|
117234
|
+
}
|
|
116808
117235
|
async function startTurn2(session, turn) {
|
|
116809
117236
|
const db2 = getDb();
|
|
116810
117237
|
let entry;
|
|
116811
117238
|
try {
|
|
116812
117239
|
entry = await getOrCreateThread(session);
|
|
116813
117240
|
} 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 });
|
|
117241
|
+
failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
|
|
116824
117242
|
return;
|
|
116825
117243
|
}
|
|
116826
|
-
|
|
117244
|
+
if (!isTurnLive(db2, turn.id)) return;
|
|
116827
117245
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
116828
117246
|
db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
|
|
116829
117247
|
setSessionStatus(db2, session.id, 1, "running", now);
|
|
116830
117248
|
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
|
-
}
|
|
117249
|
+
await runTurn(session, turn, entry, buildCodexInput(turn), false);
|
|
116977
117250
|
}
|
|
116978
117251
|
function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
116979
117252
|
const db2 = getDb();
|
|
@@ -117021,39 +117294,99 @@ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
|
|
|
117021
117294
|
};
|
|
117022
117295
|
broadcast(broadcastEvent, { sessionId, turnId, item: wsItem });
|
|
117023
117296
|
}
|
|
117024
|
-
|
|
117025
|
-
|
|
117026
|
-
|
|
117297
|
+
function within(promise2, ms) {
|
|
117298
|
+
return new Promise((resolve) => {
|
|
117299
|
+
const timer2 = setTimeout(() => resolve(null), ms);
|
|
117300
|
+
timer2.unref?.();
|
|
117301
|
+
promise2.then(
|
|
117302
|
+
(value) => {
|
|
117303
|
+
clearTimeout(timer2);
|
|
117304
|
+
resolve(value);
|
|
117305
|
+
},
|
|
117306
|
+
() => {
|
|
117307
|
+
clearTimeout(timer2);
|
|
117308
|
+
resolve(null);
|
|
117309
|
+
}
|
|
117310
|
+
);
|
|
117311
|
+
});
|
|
117312
|
+
}
|
|
117313
|
+
function turnToStop(entry, threadId) {
|
|
117314
|
+
if (threadId) return entry.turns.find((t) => t.discussionThreadId === threadId);
|
|
117315
|
+
return entry.turns.find((t) => !t.discussionThreadId) ?? entry.turns[0];
|
|
117316
|
+
}
|
|
117317
|
+
function abortOrphanTurn(sessionId, threadId) {
|
|
117027
117318
|
try {
|
|
117028
|
-
await entry.client.request("turn/interrupt", {
|
|
117029
|
-
threadId: entry.threadId,
|
|
117030
|
-
turnId: entry.turnId
|
|
117031
|
-
});
|
|
117032
117319
|
const db2 = getDb();
|
|
117033
|
-
const
|
|
117034
|
-
|
|
117035
|
-
|
|
117036
|
-
|
|
117037
|
-
entry.turnId = null;
|
|
117038
|
-
return true;
|
|
117320
|
+
const orphan = db2.prepare(
|
|
117321
|
+
`SELECT id FROM turns WHERE session_id = ? ${threadId ? "AND thread_id = ?" : ""} AND status IN ('pending', 'running') ORDER BY created_at DESC LIMIT 1`
|
|
117322
|
+
).get(...threadId ? [sessionId, threadId] : [sessionId]);
|
|
117323
|
+
return orphan ? abortTurn(db2, sessionId, orphan.id) : false;
|
|
117039
117324
|
} catch {
|
|
117040
117325
|
return false;
|
|
117041
117326
|
}
|
|
117042
117327
|
}
|
|
117043
|
-
|
|
117328
|
+
var END_COMMANDS_WAIT_MS = 5e3;
|
|
117329
|
+
async function endTurnCommands(entry, turnId) {
|
|
117330
|
+
try {
|
|
117331
|
+
const rows = getDb().prepare(
|
|
117332
|
+
"SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
|
|
117333
|
+
).all(turnId);
|
|
117334
|
+
const started = new Set(rows.map((row) => row.id));
|
|
117335
|
+
if (started.size === 0) return;
|
|
117336
|
+
let cursor = null;
|
|
117337
|
+
do {
|
|
117338
|
+
const page = await entry.client.request("thread/backgroundTerminals/list", {
|
|
117339
|
+
threadId: entry.threadId,
|
|
117340
|
+
cursor
|
|
117341
|
+
});
|
|
117342
|
+
for (const terminal of page.data) {
|
|
117343
|
+
if (!started.has(terminal.itemId)) continue;
|
|
117344
|
+
await entry.client.request("thread/backgroundTerminals/terminate", {
|
|
117345
|
+
threadId: entry.threadId,
|
|
117346
|
+
processId: terminal.processId
|
|
117347
|
+
});
|
|
117348
|
+
}
|
|
117349
|
+
cursor = page.nextCursor;
|
|
117350
|
+
} while (cursor);
|
|
117351
|
+
} catch (err) {
|
|
117352
|
+
console.warn(`[codex] could not end the commands of stopped turn ${turnId}: ${err.message}`);
|
|
117353
|
+
}
|
|
117354
|
+
}
|
|
117355
|
+
async function interruptTurn(sessionId, threadId) {
|
|
117044
117356
|
const entry = sessionMap.get(sessionId);
|
|
117045
|
-
|
|
117046
|
-
|
|
117047
|
-
|
|
117048
|
-
|
|
117357
|
+
const target = entry ? turnToStop(entry, threadId) : void 0;
|
|
117358
|
+
if (entry && target) {
|
|
117359
|
+
const codexId = target.codexId ?? await within(target.started, interruptWaitMs());
|
|
117360
|
+
let stopped = false;
|
|
117361
|
+
if (codexId && !target.done) {
|
|
117362
|
+
try {
|
|
117363
|
+
await entry.client.request("turn/interrupt", {
|
|
117364
|
+
threadId: entry.threadId,
|
|
117365
|
+
turnId: codexId
|
|
117366
|
+
});
|
|
117367
|
+
stopped = true;
|
|
117368
|
+
} catch (err) {
|
|
117369
|
+
console.warn(`[codex] turn/interrupt failed for turn ${target.id}: ${err.message}`);
|
|
117370
|
+
}
|
|
117371
|
+
}
|
|
117372
|
+
const live = !target.done;
|
|
117373
|
+
if (live) {
|
|
117374
|
+
cancelTurn(entry, target);
|
|
117375
|
+
if (!stopped) void retireEntry(entry, "fail");
|
|
117376
|
+
}
|
|
117377
|
+
if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
|
|
117378
|
+
if (live || stopped) return true;
|
|
117049
117379
|
}
|
|
117380
|
+
return abortOrphanTurn(sessionId, threadId);
|
|
117381
|
+
}
|
|
117382
|
+
function clearThread(sessionId) {
|
|
117383
|
+
const entry = sessionMap.get(sessionId);
|
|
117384
|
+
if (entry) void retireEntry(entry, "cancel");
|
|
117050
117385
|
}
|
|
117051
117386
|
function clearAllThreads() {
|
|
117052
|
-
for (const
|
|
117053
|
-
entry.client.close().catch(() => {
|
|
117054
|
-
});
|
|
117055
|
-
}
|
|
117387
|
+
for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
|
|
117056
117388
|
sessionMap.clear();
|
|
117389
|
+
startingThreads.clear();
|
|
117057
117390
|
titleGenerating.clear();
|
|
117058
117391
|
}
|
|
117059
117392
|
var titleGenerating = /* @__PURE__ */ new Set();
|
|
@@ -117233,8 +117566,42 @@ async function getModels() {
|
|
|
117233
117566
|
}
|
|
117234
117567
|
}
|
|
117235
117568
|
async function shutdown() {
|
|
117236
|
-
|
|
117237
|
-
|
|
117569
|
+
let db2 = null;
|
|
117570
|
+
try {
|
|
117571
|
+
db2 = getDb();
|
|
117572
|
+
} catch {
|
|
117573
|
+
db2 = null;
|
|
117574
|
+
}
|
|
117575
|
+
const closing = [closeSharedAppServer()];
|
|
117576
|
+
for (const entry of [...sessionMap.values()]) {
|
|
117577
|
+
for (const active of [...entry.turns]) {
|
|
117578
|
+
if (active.discussionThreadId) continue;
|
|
117579
|
+
endTurn(entry, active);
|
|
117580
|
+
if (!db2) continue;
|
|
117581
|
+
try {
|
|
117582
|
+
markTurnInterrupted(db2, active.id, "host_shutdown", { notify: false });
|
|
117583
|
+
} catch (err) {
|
|
117584
|
+
console.error("[codex] could not park turn for resume:", err.message);
|
|
117585
|
+
}
|
|
117586
|
+
}
|
|
117587
|
+
closing.push(retireEntry(entry, "keep"));
|
|
117588
|
+
}
|
|
117589
|
+
await Promise.all(closing);
|
|
117590
|
+
titleGenerating.clear();
|
|
117591
|
+
}
|
|
117592
|
+
async function reapOrphans() {
|
|
117593
|
+
const ended = await reapOrphanProcesses(getDb(), "codex");
|
|
117594
|
+
if (ended > 0) console.log(`[codex] ended ${ended} app-server(s) left by the previous host`);
|
|
117595
|
+
}
|
|
117596
|
+
async function resumeInterruptedTurn(session, turn, _opts) {
|
|
117597
|
+
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
117598
|
+
const entry = await getOrCreateThread(session);
|
|
117599
|
+
if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
|
|
117600
|
+
if (!isTurnLive(getDb(), turn.id)) return;
|
|
117601
|
+
const codexId = turn.external_turn_id;
|
|
117602
|
+
const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
|
|
117603
|
+
const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
|
|
117604
|
+
await runTurn(session, turn, entry, input, true);
|
|
117238
117605
|
}
|
|
117239
117606
|
var codexProvider = {
|
|
117240
117607
|
startTurn: startTurn2,
|
|
@@ -117243,6 +117610,8 @@ var codexProvider = {
|
|
|
117243
117610
|
clearAllThreads,
|
|
117244
117611
|
getModels,
|
|
117245
117612
|
summarizeThread: summarizeCodexThread,
|
|
117613
|
+
resumeInterruptedTurn,
|
|
117614
|
+
reapOrphans,
|
|
117246
117615
|
shutdown
|
|
117247
117616
|
};
|
|
117248
117617
|
|
|
@@ -117574,64 +117943,6 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
|
|
|
117574
117943
|
return "fatal";
|
|
117575
117944
|
}
|
|
117576
117945
|
|
|
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
117946
|
// src/claude/claude-provider.ts
|
|
117636
117947
|
var PromptQueue = class {
|
|
117637
117948
|
buffer = [];
|
|
@@ -117848,7 +118159,7 @@ function trackResumeFrame(entry, message, db2) {
|
|
|
117848
118159
|
}
|
|
117849
118160
|
return true;
|
|
117850
118161
|
}
|
|
117851
|
-
function
|
|
118162
|
+
function failTurn2(db2, sessionId, turnId, error51) {
|
|
117852
118163
|
const row = db2.prepare("SELECT resume_state FROM turns WHERE id = ?").get(turnId);
|
|
117853
118164
|
if (row?.resume_state === "waiting" || row?.resume_state === "resuming") {
|
|
117854
118165
|
if (finalizeInterruptedTurn(db2, turnId, "gave_up", error51)) return;
|
|
@@ -117871,7 +118182,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
|
|
|
117871
118182
|
if (!entry.threadId && !entry.closeReason && isSignalExit(errMsg)) {
|
|
117872
118183
|
markTurnInterrupted(db2, turnId, "process_exit", { detail: errMsg });
|
|
117873
118184
|
} else {
|
|
117874
|
-
|
|
118185
|
+
failTurn2(db2, sessionId, turnId, errMsg);
|
|
117875
118186
|
}
|
|
117876
118187
|
}
|
|
117877
118188
|
if (staleItems.changes > 0) {
|
|
@@ -117970,7 +118281,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
117970
118281
|
const currentTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
117971
118282
|
if (currentTurn && currentTurn.status === "running") {
|
|
117972
118283
|
const usage = currentTurn.token_usage ? JSON.parse(currentTurn.token_usage) : null;
|
|
117973
|
-
|
|
118284
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
117974
118285
|
}
|
|
117975
118286
|
syncThreadTitle2(session.id);
|
|
117976
118287
|
}
|
|
@@ -118036,7 +118347,7 @@ async function startTurn3(session, turn) {
|
|
|
118036
118347
|
const prevTurn = db2.prepare("SELECT status, token_usage FROM turns WHERE id = ?").get(entry.turnId);
|
|
118037
118348
|
if (prevTurn && prevTurn.status === "running") {
|
|
118038
118349
|
const usage = prevTurn.token_usage ? JSON.parse(prevTurn.token_usage) : null;
|
|
118039
|
-
|
|
118350
|
+
completeTurn2(db2, session.id, entry.turnId, usage);
|
|
118040
118351
|
}
|
|
118041
118352
|
syncThreadTitle2(session.id);
|
|
118042
118353
|
streamingMessageIds.delete(entry.turnId);
|
|
@@ -118525,18 +118836,18 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
118525
118836
|
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
|
|
118526
118837
|
return;
|
|
118527
118838
|
}
|
|
118528
|
-
|
|
118839
|
+
failTurn2(db2, sessionId, turnId, text2);
|
|
118529
118840
|
return;
|
|
118530
118841
|
}
|
|
118531
118842
|
await refreshContext(entry, sessionId, db2);
|
|
118532
|
-
|
|
118843
|
+
completeTurn2(db2, sessionId, turnId, usage);
|
|
118533
118844
|
} else {
|
|
118534
118845
|
entry.lastApiError = null;
|
|
118535
118846
|
const errorMsg = message.errors?.join("; ") || "Claude turn failed";
|
|
118536
|
-
|
|
118847
|
+
failTurn2(db2, sessionId, turnId, errorMsg);
|
|
118537
118848
|
}
|
|
118538
118849
|
}
|
|
118539
|
-
function
|
|
118850
|
+
function completeTurn2(db2, sessionId, turnId, usage) {
|
|
118540
118851
|
markTurnResumed(db2, turnId, { settle: true });
|
|
118541
118852
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
118542
118853
|
const response = turnResponse(db2, turnId);
|
|
@@ -118819,7 +119130,7 @@ async function shutdown2() {
|
|
|
118819
119130
|
}
|
|
118820
119131
|
clearAllThreads2();
|
|
118821
119132
|
}
|
|
118822
|
-
async function
|
|
119133
|
+
async function reapOrphans2() {
|
|
118823
119134
|
const ended = await reapOrphanCliProcesses(getDb());
|
|
118824
119135
|
if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
|
|
118825
119136
|
}
|
|
@@ -118832,7 +119143,7 @@ function retireCli(sessionId, entry) {
|
|
|
118832
119143
|
entry.query.close();
|
|
118833
119144
|
sessionMap2.delete(sessionId);
|
|
118834
119145
|
}
|
|
118835
|
-
async function
|
|
119146
|
+
async function resumeInterruptedTurn2(session, turn, opts) {
|
|
118836
119147
|
if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
|
|
118837
119148
|
let live = sessionMap2.get(session.id);
|
|
118838
119149
|
if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
|
|
@@ -118994,8 +119305,8 @@ var claudeProvider = {
|
|
|
118994
119305
|
setModel,
|
|
118995
119306
|
stopTask,
|
|
118996
119307
|
listBackgroundTasks,
|
|
118997
|
-
resumeInterruptedTurn,
|
|
118998
|
-
reapOrphans,
|
|
119308
|
+
resumeInterruptedTurn: resumeInterruptedTurn2,
|
|
119309
|
+
reapOrphans: reapOrphans2,
|
|
118999
119310
|
shutdown: shutdown2
|
|
119000
119311
|
};
|
|
119001
119312
|
|
|
@@ -119484,11 +119795,13 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119484
119795
|
if (opts.signal?.aborted || err.name === "AbortError") {
|
|
119485
119796
|
return "aborted";
|
|
119486
119797
|
}
|
|
119798
|
+
opts.onDisconnect?.();
|
|
119487
119799
|
await reconnectDelay(delayMs, opts.signal);
|
|
119488
119800
|
continue;
|
|
119489
119801
|
}
|
|
119490
119802
|
if (response.status === 404) return "session-not-found";
|
|
119491
119803
|
if (!response.ok || !response.body) {
|
|
119804
|
+
opts.onDisconnect?.();
|
|
119492
119805
|
await reconnectDelay(delayMs, opts.signal);
|
|
119493
119806
|
continue;
|
|
119494
119807
|
}
|
|
@@ -119502,6 +119815,7 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
|
|
|
119502
119815
|
});
|
|
119503
119816
|
return reason;
|
|
119504
119817
|
}
|
|
119818
|
+
opts.onDisconnect?.();
|
|
119505
119819
|
await reconnectDelay(delayMs, opts.signal);
|
|
119506
119820
|
}
|
|
119507
119821
|
}
|
|
@@ -120170,6 +120484,9 @@ function mapReasoningEffort(modelId, effort) {
|
|
|
120170
120484
|
}
|
|
120171
120485
|
var sessionMap3 = /* @__PURE__ */ new Map();
|
|
120172
120486
|
var STALLED_STREAM_MS = 6e4;
|
|
120487
|
+
var BACKEND_LOST_MS = 3e4;
|
|
120488
|
+
var BACKEND_RESTARTED_ERROR = "The Repoburg backend restarted while this turn ran, so the turn was lost. Send the prompt again.";
|
|
120489
|
+
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
120490
|
function isConnectionError(err) {
|
|
120174
120491
|
const message = String(err?.message ?? "");
|
|
120175
120492
|
return /fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|socket hang up/i.test(
|
|
@@ -120293,7 +120610,7 @@ function failTurnBeforeStart(db2, sessionId, turnId, error51) {
|
|
|
120293
120610
|
recomputeSessionRunning(db2, sessionId, "failed");
|
|
120294
120611
|
broadcast("turn:failed", { sessionId, turnId, error: error51 });
|
|
120295
120612
|
}
|
|
120296
|
-
function
|
|
120613
|
+
function failTurn3(entry, error51) {
|
|
120297
120614
|
const active = entry.activeTurn;
|
|
120298
120615
|
if (!active) return;
|
|
120299
120616
|
entry.activeTurn = null;
|
|
@@ -120317,32 +120634,61 @@ function failTurn2(entry, error51) {
|
|
|
120317
120634
|
broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
|
|
120318
120635
|
}
|
|
120319
120636
|
async function runStreamLoop(entry, projector) {
|
|
120320
|
-
|
|
120321
|
-
|
|
120322
|
-
|
|
120323
|
-
|
|
120324
|
-
|
|
120325
|
-
|
|
120637
|
+
const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
|
|
120638
|
+
const lose = (error51) => {
|
|
120639
|
+
if (isCurrent()) failTurn3(entry, error51);
|
|
120640
|
+
};
|
|
120641
|
+
let lostTimer = null;
|
|
120642
|
+
const clearLostTimer = () => {
|
|
120643
|
+
if (lostTimer) clearTimeout(lostTimer);
|
|
120644
|
+
lostTimer = null;
|
|
120645
|
+
};
|
|
120646
|
+
try {
|
|
120647
|
+
while (isCurrent()) {
|
|
120648
|
+
const active = entry.activeTurn;
|
|
120649
|
+
const controller = new AbortController();
|
|
120650
|
+
active.sseAbort = controller;
|
|
120651
|
+
let stallTimer = null;
|
|
120652
|
+
const resetStall = () => {
|
|
120653
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
120654
|
+
stallTimer = setTimeout(() => controller.abort(), STALLED_STREAM_MS);
|
|
120655
|
+
};
|
|
120656
|
+
resetStall();
|
|
120657
|
+
const onMessage = (message) => {
|
|
120658
|
+
if (message.type === "system") {
|
|
120659
|
+
clearLostTimer();
|
|
120660
|
+
const bootId = message.bootId ?? null;
|
|
120661
|
+
if (active.bootId === void 0) active.bootId = bootId;
|
|
120662
|
+
else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
|
|
120663
|
+
}
|
|
120664
|
+
projector.handle(message);
|
|
120665
|
+
};
|
|
120666
|
+
const onDisconnect = () => {
|
|
120667
|
+
if (typeof active.bootId !== "string" || lostTimer) return;
|
|
120668
|
+
lostTimer = setTimeout(() => {
|
|
120669
|
+
lostTimer = null;
|
|
120670
|
+
invalidateBackend(entry.baseUrl);
|
|
120671
|
+
lose(BACKEND_UNREACHABLE_ERROR);
|
|
120672
|
+
}, BACKEND_LOST_MS);
|
|
120673
|
+
};
|
|
120674
|
+
const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
|
|
120675
|
+
signal: controller.signal,
|
|
120676
|
+
onActivity: resetStall,
|
|
120677
|
+
onDisconnect
|
|
120678
|
+
});
|
|
120326
120679
|
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;
|
|
120680
|
+
if (!isCurrent()) return;
|
|
120681
|
+
if (reason === "session-not-found") {
|
|
120682
|
+
failTurn3(entry, "Repoburg session no longer exists on the backend.");
|
|
120683
|
+
return;
|
|
120684
|
+
}
|
|
120685
|
+
if (reason === "aborted") {
|
|
120686
|
+
if (active.cancelled) return;
|
|
120687
|
+
continue;
|
|
120688
|
+
}
|
|
120345
120689
|
}
|
|
120690
|
+
} finally {
|
|
120691
|
+
clearLostTimer();
|
|
120346
120692
|
}
|
|
120347
120693
|
}
|
|
120348
120694
|
function turnImageDataUrls(turn) {
|
|
@@ -120428,7 +120774,7 @@ async function startTurn4(session, turn) {
|
|
|
120428
120774
|
void ensureContextWindow(entry);
|
|
120429
120775
|
runStreamLoop(entry, projector).catch((err) => {
|
|
120430
120776
|
console.error("[repoburg] stream loop crashed:", err);
|
|
120431
|
-
|
|
120777
|
+
failTurn3(entry, `Stream loop failed: ${err.message}`);
|
|
120432
120778
|
});
|
|
120433
120779
|
try {
|
|
120434
120780
|
const images = turnImageDataUrls(turn);
|
|
@@ -120439,7 +120785,7 @@ async function startTurn4(session, turn) {
|
|
|
120439
120785
|
});
|
|
120440
120786
|
} catch (err) {
|
|
120441
120787
|
if (isConnectionError(err)) invalidateBackend(entry.baseUrl);
|
|
120442
|
-
|
|
120788
|
+
failTurn3(entry, err.message);
|
|
120443
120789
|
}
|
|
120444
120790
|
}
|
|
120445
120791
|
async function interruptTurn3(sessionId, threadId) {
|