repoburg 1.3.286 → 1.3.288
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 +882 -440
- package/agent-pane/backend/dist/server.js +882 -440
- package/agent-pane/frontend/dist/assets/{TerminalView-BFw1zt_D.js → TerminalView-BIN1AVRE.js} +1 -1
- package/agent-pane/frontend/dist/assets/{index-8ltC2W3q.js → index-DumuprBy.js} +132 -125
- package/agent-pane/frontend/dist/index.html +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
|
@@ -13456,13 +13456,13 @@ var require_context = __commonJS({
|
|
|
13456
13456
|
this.server = server;
|
|
13457
13457
|
}
|
|
13458
13458
|
function defaultSchemaErrorFormatter(errors, dataVar) {
|
|
13459
|
-
let
|
|
13459
|
+
let text2 = "";
|
|
13460
13460
|
const separator = ", ";
|
|
13461
13461
|
for (let i = 0; i !== errors.length; ++i) {
|
|
13462
13462
|
const e = errors[i];
|
|
13463
|
-
|
|
13463
|
+
text2 += dataVar + (e.instancePath || "") + " " + e.message + separator;
|
|
13464
13464
|
}
|
|
13465
|
-
return new Error(
|
|
13465
|
+
return new Error(text2.slice(0, -separator.length));
|
|
13466
13466
|
}
|
|
13467
13467
|
module.exports = Context;
|
|
13468
13468
|
}
|
|
@@ -13475,20 +13475,20 @@ var require_secure_json_parse = __commonJS({
|
|
|
13475
13475
|
var hasBuffer = typeof Buffer !== "undefined";
|
|
13476
13476
|
var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
13477
13477
|
var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
13478
|
-
function _parse(
|
|
13478
|
+
function _parse(text2, reviver, options) {
|
|
13479
13479
|
if (options == null) {
|
|
13480
13480
|
if (reviver !== null && typeof reviver === "object") {
|
|
13481
13481
|
options = reviver;
|
|
13482
13482
|
reviver = void 0;
|
|
13483
13483
|
}
|
|
13484
13484
|
}
|
|
13485
|
-
if (hasBuffer && Buffer.isBuffer(
|
|
13486
|
-
|
|
13485
|
+
if (hasBuffer && Buffer.isBuffer(text2)) {
|
|
13486
|
+
text2 = text2.toString();
|
|
13487
13487
|
}
|
|
13488
|
-
if (
|
|
13489
|
-
|
|
13488
|
+
if (text2 && text2.charCodeAt(0) === 65279) {
|
|
13489
|
+
text2 = text2.slice(1);
|
|
13490
13490
|
}
|
|
13491
|
-
const obj = JSON.parse(
|
|
13491
|
+
const obj = JSON.parse(text2, reviver);
|
|
13492
13492
|
if (obj === null || typeof obj !== "object") {
|
|
13493
13493
|
return obj;
|
|
13494
13494
|
}
|
|
@@ -13498,15 +13498,15 @@ var require_secure_json_parse = __commonJS({
|
|
|
13498
13498
|
return obj;
|
|
13499
13499
|
}
|
|
13500
13500
|
if (protoAction !== "ignore" && constructorAction !== "ignore") {
|
|
13501
|
-
if (suspectProtoRx.test(
|
|
13501
|
+
if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
|
|
13502
13502
|
return obj;
|
|
13503
13503
|
}
|
|
13504
13504
|
} else if (protoAction !== "ignore" && constructorAction === "ignore") {
|
|
13505
|
-
if (suspectProtoRx.test(
|
|
13505
|
+
if (suspectProtoRx.test(text2) === false) {
|
|
13506
13506
|
return obj;
|
|
13507
13507
|
}
|
|
13508
13508
|
} else {
|
|
13509
|
-
if (suspectConstructorRx.test(
|
|
13509
|
+
if (suspectConstructorRx.test(text2) === false) {
|
|
13510
13510
|
return obj;
|
|
13511
13511
|
}
|
|
13512
13512
|
}
|
|
@@ -13544,20 +13544,20 @@ var require_secure_json_parse = __commonJS({
|
|
|
13544
13544
|
}
|
|
13545
13545
|
return obj;
|
|
13546
13546
|
}
|
|
13547
|
-
function parse(
|
|
13547
|
+
function parse(text2, reviver, options) {
|
|
13548
13548
|
const { stackTraceLimit } = Error;
|
|
13549
13549
|
Error.stackTraceLimit = 0;
|
|
13550
13550
|
try {
|
|
13551
|
-
return _parse(
|
|
13551
|
+
return _parse(text2, reviver, options);
|
|
13552
13552
|
} finally {
|
|
13553
13553
|
Error.stackTraceLimit = stackTraceLimit;
|
|
13554
13554
|
}
|
|
13555
13555
|
}
|
|
13556
|
-
function safeParse(
|
|
13556
|
+
function safeParse(text2, reviver) {
|
|
13557
13557
|
const { stackTraceLimit } = Error;
|
|
13558
13558
|
Error.stackTraceLimit = 0;
|
|
13559
13559
|
try {
|
|
13560
|
-
return _parse(
|
|
13560
|
+
return _parse(text2, reviver, { safe: true });
|
|
13561
13561
|
} catch {
|
|
13562
13562
|
return void 0;
|
|
13563
13563
|
} finally {
|
|
@@ -18229,7 +18229,7 @@ var require_core = __commonJS({
|
|
|
18229
18229
|
errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
|
|
18230
18230
|
if (!errors || errors.length === 0)
|
|
18231
18231
|
return "No errors";
|
|
18232
|
-
return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((
|
|
18232
|
+
return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text2, msg) => text2 + separator + msg);
|
|
18233
18233
|
}
|
|
18234
18234
|
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
|
18235
18235
|
const rules = this.RULES.all;
|
|
@@ -41154,6 +41154,9 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
|
|
|
41154
41154
|
if (!sessColumns.some((c) => c.name === "origin_app_id")) {
|
|
41155
41155
|
database.exec("ALTER TABLE sessions ADD COLUMN origin_app_id TEXT");
|
|
41156
41156
|
}
|
|
41157
|
+
if (!sessColumns.some((c) => c.name === "origin_app_workspace")) {
|
|
41158
|
+
database.exec("ALTER TABLE sessions ADD COLUMN origin_app_workspace TEXT");
|
|
41159
|
+
}
|
|
41157
41160
|
if (!sessColumns.some((c) => c.name === "user_touched")) {
|
|
41158
41161
|
database.exec("ALTER TABLE sessions ADD COLUMN user_touched INTEGER NOT NULL DEFAULT 0");
|
|
41159
41162
|
}
|
|
@@ -41301,7 +41304,15 @@ function handleUpgrade(wss3, request, socket, head) {
|
|
|
41301
41304
|
socket.destroy();
|
|
41302
41305
|
}
|
|
41303
41306
|
}
|
|
41307
|
+
var taps = /* @__PURE__ */ new Set();
|
|
41308
|
+
function tapBroadcast(tap) {
|
|
41309
|
+
taps.add(tap);
|
|
41310
|
+
return () => {
|
|
41311
|
+
taps.delete(tap);
|
|
41312
|
+
};
|
|
41313
|
+
}
|
|
41304
41314
|
function broadcast(event, data) {
|
|
41315
|
+
for (const tap of taps) tap(event, data);
|
|
41305
41316
|
if (!wss) return;
|
|
41306
41317
|
const message = JSON.stringify({ event, data });
|
|
41307
41318
|
for (const client of wss.clients) {
|
|
@@ -41381,7 +41392,8 @@ function bundledCliDir() {
|
|
|
41381
41392
|
function shellEnv() {
|
|
41382
41393
|
const env = {};
|
|
41383
41394
|
for (const [key, value] of Object.entries(process.env)) {
|
|
41384
|
-
if (value
|
|
41395
|
+
if (value === void 0 || key === "CLAUDECODE" || key === "AGENT_PANE_SESSION_ID") continue;
|
|
41396
|
+
if (!key.startsWith("CLAUDE_CODE_RESUME_")) env[key] = value;
|
|
41385
41397
|
}
|
|
41386
41398
|
env.TERM = "xterm-256color";
|
|
41387
41399
|
env.COLORTERM = "truecolor";
|
|
@@ -41688,6 +41700,59 @@ async function shutdownAllProviders() {
|
|
|
41688
41700
|
}
|
|
41689
41701
|
}
|
|
41690
41702
|
|
|
41703
|
+
// src/routes/session-guard.ts
|
|
41704
|
+
var LIVE_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') LIMIT 1`;
|
|
41705
|
+
var LIVE_MAIN_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') AND thread_id IS NULL LIMIT 1`;
|
|
41706
|
+
var LIVE_THREAD_TURN_SQL = `SELECT id FROM turns WHERE thread_id = ? AND status IN ('pending', 'running') LIMIT 1`;
|
|
41707
|
+
function isSessionBusy(db2, session, opts) {
|
|
41708
|
+
if (opts?.threadId) {
|
|
41709
|
+
return !!db2.prepare(LIVE_THREAD_TURN_SQL).get(opts.threadId);
|
|
41710
|
+
}
|
|
41711
|
+
if (opts?.mainOnly) {
|
|
41712
|
+
if (db2.prepare(LIVE_MAIN_TURN_SQL).get(session.id)) return true;
|
|
41713
|
+
if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return false;
|
|
41714
|
+
} else {
|
|
41715
|
+
if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return true;
|
|
41716
|
+
}
|
|
41717
|
+
if (!session.is_running) return false;
|
|
41718
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
41719
|
+
db2.prepare("UPDATE sessions SET is_running = 0, status = ?, updated_at = ? WHERE id = ?").run(
|
|
41720
|
+
"active",
|
|
41721
|
+
now,
|
|
41722
|
+
session.id
|
|
41723
|
+
);
|
|
41724
|
+
return false;
|
|
41725
|
+
}
|
|
41726
|
+
function turnResponse(db2, turnId) {
|
|
41727
|
+
const row = db2.prepare("SELECT agent_response FROM turns WHERE id = ?").get(turnId);
|
|
41728
|
+
return row?.agent_response || null;
|
|
41729
|
+
}
|
|
41730
|
+
function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnreviewed = false) {
|
|
41731
|
+
const live = db2.prepare(
|
|
41732
|
+
`SELECT COUNT(*) AS c,
|
|
41733
|
+
COALESCE(SUM(CASE WHEN status = 'pending' AND resume_state = 'waiting' THEN 1 ELSE 0 END), 0) AS w
|
|
41734
|
+
FROM turns WHERE session_id = ? AND status IN ('pending', 'running')`
|
|
41735
|
+
).get(sessionId);
|
|
41736
|
+
const isRunning = live.c > 0 ? 1 : 0;
|
|
41737
|
+
const liveStatus = live.c > 0 && live.w === live.c ? "interrupted" : "running";
|
|
41738
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
41739
|
+
if (hasUnreviewed && isRunning === 0) {
|
|
41740
|
+
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
41741
|
+
isRunning,
|
|
41742
|
+
idleStatus,
|
|
41743
|
+
now,
|
|
41744
|
+
sessionId
|
|
41745
|
+
);
|
|
41746
|
+
} else {
|
|
41747
|
+
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, updated_at = ? WHERE id = ?").run(
|
|
41748
|
+
isRunning,
|
|
41749
|
+
isRunning ? liveStatus : idleStatus,
|
|
41750
|
+
now,
|
|
41751
|
+
sessionId
|
|
41752
|
+
);
|
|
41753
|
+
}
|
|
41754
|
+
}
|
|
41755
|
+
|
|
41691
41756
|
// src/routes/session-touch.ts
|
|
41692
41757
|
function markSessionTouched(db2, sessionId) {
|
|
41693
41758
|
const { changes } = db2.prepare("UPDATE sessions SET user_touched = 1 WHERE id = ? AND user_touched = 0").run(sessionId);
|
|
@@ -41696,6 +41761,70 @@ function markSessionTouched(db2, sessionId) {
|
|
|
41696
41761
|
return true;
|
|
41697
41762
|
}
|
|
41698
41763
|
|
|
41764
|
+
// src/routes/session-actions.ts
|
|
41765
|
+
function createSession(db2, input) {
|
|
41766
|
+
const {
|
|
41767
|
+
title = null,
|
|
41768
|
+
runtime_type = "codex",
|
|
41769
|
+
model = null,
|
|
41770
|
+
model_reasoning_effort = null,
|
|
41771
|
+
cwd = null,
|
|
41772
|
+
runtime_config = null,
|
|
41773
|
+
origin_app_id = null,
|
|
41774
|
+
origin_app_workspace = null
|
|
41775
|
+
} = input;
|
|
41776
|
+
const id = v4_default();
|
|
41777
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
41778
|
+
const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
|
|
41779
|
+
db2.prepare(
|
|
41780
|
+
`INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status, is_running, sort_order, created_at, updated_at, runtime_config, origin_app_id, origin_app_workspace)
|
|
41781
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, ?, ?, ?, ?, ?, ?)`
|
|
41782
|
+
).run(
|
|
41783
|
+
id,
|
|
41784
|
+
title,
|
|
41785
|
+
runtime_type,
|
|
41786
|
+
model,
|
|
41787
|
+
model_reasoning_effort,
|
|
41788
|
+
cwd,
|
|
41789
|
+
maxOrder.m + 1,
|
|
41790
|
+
now,
|
|
41791
|
+
now,
|
|
41792
|
+
runtime_config,
|
|
41793
|
+
origin_app_id,
|
|
41794
|
+
origin_app_workspace
|
|
41795
|
+
);
|
|
41796
|
+
return db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
41797
|
+
}
|
|
41798
|
+
var SessionBusyError = class extends Error {
|
|
41799
|
+
constructor() {
|
|
41800
|
+
super("A turn is already running for this session");
|
|
41801
|
+
this.name = "SessionBusyError";
|
|
41802
|
+
}
|
|
41803
|
+
};
|
|
41804
|
+
function startTurn(db2, session, { prompt, attachments, originAppId }) {
|
|
41805
|
+
if (isSessionBusy(db2, session, { mainOnly: true })) throw new SessionBusyError();
|
|
41806
|
+
const provider = getProvider(session.runtime_type);
|
|
41807
|
+
const turnId = v4_default();
|
|
41808
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
41809
|
+
const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
|
|
41810
|
+
db2.prepare(
|
|
41811
|
+
`INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
|
|
41812
|
+
VALUES (?, ?, ?, NULL, NULL, NULL, NULL, 'pending', NULL, ?, ?, ?)`
|
|
41813
|
+
).run(turnId, session.id, prompt, attachmentsJson, now, now);
|
|
41814
|
+
const turn = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
|
|
41815
|
+
if (!originAppId) markSessionTouched(db2, session.id);
|
|
41816
|
+
const rawTurn = turn;
|
|
41817
|
+
const parsedTurn = {
|
|
41818
|
+
...turn,
|
|
41819
|
+
attachments: rawTurn.attachments ? JSON.parse(rawTurn.attachments) : null
|
|
41820
|
+
};
|
|
41821
|
+
broadcast("turn:created", { sessionId: session.id, turn: parsedTurn });
|
|
41822
|
+
provider.startTurn(session, rawTurn).catch((err) => {
|
|
41823
|
+
console.error(`[provider] Unhandled error for session ${session.id}:`, err);
|
|
41824
|
+
});
|
|
41825
|
+
return parsedTurn;
|
|
41826
|
+
}
|
|
41827
|
+
|
|
41699
41828
|
// src/routes/sessions.ts
|
|
41700
41829
|
async function registerSessionRoutes(fastify) {
|
|
41701
41830
|
fastify.get("/api/sessions", async () => {
|
|
@@ -41770,31 +41899,12 @@ async function registerSessionRoutes(fastify) {
|
|
|
41770
41899
|
model_reasoning_effort: { type: ["string", "null"] },
|
|
41771
41900
|
cwd: { type: ["string", "null"] },
|
|
41772
41901
|
runtime_config: { type: ["string", "null"] },
|
|
41773
|
-
origin_app_id: { type: ["string", "null"] }
|
|
41902
|
+
origin_app_id: { type: ["string", "null"] },
|
|
41903
|
+
origin_app_workspace: { type: ["string", "null"] }
|
|
41774
41904
|
}
|
|
41775
41905
|
}
|
|
41776
41906
|
}
|
|
41777
|
-
}, async (request) => {
|
|
41778
|
-
const {
|
|
41779
|
-
title = null,
|
|
41780
|
-
runtime_type = "codex",
|
|
41781
|
-
model = null,
|
|
41782
|
-
model_reasoning_effort = null,
|
|
41783
|
-
cwd = null,
|
|
41784
|
-
runtime_config = null,
|
|
41785
|
-
origin_app_id = null
|
|
41786
|
-
} = request.body || {};
|
|
41787
|
-
const id = v4_default();
|
|
41788
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
41789
|
-
const db2 = getDb();
|
|
41790
|
-
const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
|
|
41791
|
-
db2.prepare(
|
|
41792
|
-
`INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status, is_running, sort_order, created_at, updated_at, runtime_config, origin_app_id)
|
|
41793
|
-
VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, ?, ?, ?, ?, ?)`
|
|
41794
|
-
).run(id, title, runtime_type, model, model_reasoning_effort, cwd, maxOrder.m + 1, now, now, runtime_config, origin_app_id);
|
|
41795
|
-
const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
41796
|
-
return session;
|
|
41797
|
-
});
|
|
41907
|
+
}, async (request) => createSession(getDb(), request.body || {}));
|
|
41798
41908
|
fastify.delete("/api/sessions/:id", async (request, reply) => {
|
|
41799
41909
|
const { id } = request.params;
|
|
41800
41910
|
const db2 = getDb();
|
|
@@ -42119,59 +42229,6 @@ async function registerSessionRoutes(fastify) {
|
|
|
42119
42229
|
);
|
|
42120
42230
|
}
|
|
42121
42231
|
|
|
42122
|
-
// src/routes/session-guard.ts
|
|
42123
|
-
var LIVE_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') LIMIT 1`;
|
|
42124
|
-
var LIVE_MAIN_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') AND thread_id IS NULL LIMIT 1`;
|
|
42125
|
-
var LIVE_THREAD_TURN_SQL = `SELECT id FROM turns WHERE thread_id = ? AND status IN ('pending', 'running') LIMIT 1`;
|
|
42126
|
-
function isSessionBusy(db2, session, opts) {
|
|
42127
|
-
if (opts?.threadId) {
|
|
42128
|
-
return !!db2.prepare(LIVE_THREAD_TURN_SQL).get(opts.threadId);
|
|
42129
|
-
}
|
|
42130
|
-
if (opts?.mainOnly) {
|
|
42131
|
-
if (db2.prepare(LIVE_MAIN_TURN_SQL).get(session.id)) return true;
|
|
42132
|
-
if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return false;
|
|
42133
|
-
} else {
|
|
42134
|
-
if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return true;
|
|
42135
|
-
}
|
|
42136
|
-
if (!session.is_running) return false;
|
|
42137
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42138
|
-
db2.prepare("UPDATE sessions SET is_running = 0, status = ?, updated_at = ? WHERE id = ?").run(
|
|
42139
|
-
"active",
|
|
42140
|
-
now,
|
|
42141
|
-
session.id
|
|
42142
|
-
);
|
|
42143
|
-
return false;
|
|
42144
|
-
}
|
|
42145
|
-
function turnResponse(db2, turnId) {
|
|
42146
|
-
const row = db2.prepare("SELECT agent_response FROM turns WHERE id = ?").get(turnId);
|
|
42147
|
-
return row?.agent_response || null;
|
|
42148
|
-
}
|
|
42149
|
-
function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnreviewed = false) {
|
|
42150
|
-
const live = db2.prepare(
|
|
42151
|
-
`SELECT COUNT(*) AS c,
|
|
42152
|
-
COALESCE(SUM(CASE WHEN status = 'pending' AND resume_state = 'waiting' THEN 1 ELSE 0 END), 0) AS w
|
|
42153
|
-
FROM turns WHERE session_id = ? AND status IN ('pending', 'running')`
|
|
42154
|
-
).get(sessionId);
|
|
42155
|
-
const isRunning = live.c > 0 ? 1 : 0;
|
|
42156
|
-
const liveStatus = live.c > 0 && live.w === live.c ? "interrupted" : "running";
|
|
42157
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42158
|
-
if (hasUnreviewed && isRunning === 0) {
|
|
42159
|
-
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
|
|
42160
|
-
isRunning,
|
|
42161
|
-
idleStatus,
|
|
42162
|
-
now,
|
|
42163
|
-
sessionId
|
|
42164
|
-
);
|
|
42165
|
-
} else {
|
|
42166
|
-
db2.prepare("UPDATE sessions SET is_running = ?, status = ?, updated_at = ? WHERE id = ?").run(
|
|
42167
|
-
isRunning,
|
|
42168
|
-
isRunning ? liveStatus : idleStatus,
|
|
42169
|
-
now,
|
|
42170
|
-
sessionId
|
|
42171
|
-
);
|
|
42172
|
-
}
|
|
42173
|
-
}
|
|
42174
|
-
|
|
42175
42232
|
// src/resume/interruptions.ts
|
|
42176
42233
|
var HOST_RESTART_ERROR = "Backend restarted while turn was running";
|
|
42177
42234
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -42662,28 +42719,12 @@ async function registerTurnRoutes(fastify) {
|
|
|
42662
42719
|
if (!session) {
|
|
42663
42720
|
return reply.code(404).send({ error: "Session not found" });
|
|
42664
42721
|
}
|
|
42665
|
-
|
|
42666
|
-
return
|
|
42722
|
+
try {
|
|
42723
|
+
return startTurn(db2, session, { prompt: user_prompt, attachments, originAppId: origin_app_id });
|
|
42724
|
+
} catch (err) {
|
|
42725
|
+
if (err instanceof SessionBusyError) return reply.code(409).send({ error: err.message });
|
|
42726
|
+
throw err;
|
|
42667
42727
|
}
|
|
42668
|
-
const turnId = v4_default();
|
|
42669
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42670
|
-
const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
|
|
42671
|
-
db2.prepare(
|
|
42672
|
-
`INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
|
|
42673
|
-
VALUES (?, ?, ?, NULL, NULL, NULL, NULL, 'pending', NULL, ?, ?, ?)`
|
|
42674
|
-
).run(turnId, id, user_prompt, attachmentsJson, now, now);
|
|
42675
|
-
const turn = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
|
|
42676
|
-
if (!origin_app_id) markSessionTouched(db2, id);
|
|
42677
|
-
const rawTurn = turn;
|
|
42678
|
-
const parsedTurn = {
|
|
42679
|
-
...turn,
|
|
42680
|
-
attachments: rawTurn.attachments ? JSON.parse(rawTurn.attachments) : null
|
|
42681
|
-
};
|
|
42682
|
-
broadcast("turn:created", { sessionId: id, turn: parsedTurn });
|
|
42683
|
-
getProvider(session.runtime_type).startTurn(session, rawTurn).catch((err) => {
|
|
42684
|
-
console.error(`[provider] Unhandled error for session ${id}:`, err);
|
|
42685
|
-
});
|
|
42686
|
-
return parsedTurn;
|
|
42687
42728
|
}
|
|
42688
42729
|
);
|
|
42689
42730
|
fastify.get(
|
|
@@ -43527,8 +43568,8 @@ var AppServerClient = class {
|
|
|
43527
43568
|
this.proc.stdout?.setEncoding("utf-8");
|
|
43528
43569
|
this.proc.stdout?.on("data", this.stdoutListener);
|
|
43529
43570
|
this.proc.stderr?.on("data", (chunk) => {
|
|
43530
|
-
const
|
|
43531
|
-
if (
|
|
43571
|
+
const text2 = chunk.toString().trim();
|
|
43572
|
+
if (text2) console.error("[app-server] stderr:", text2);
|
|
43532
43573
|
});
|
|
43533
43574
|
this.proc.on("exit", (code, signal) => {
|
|
43534
43575
|
this.onProcessExit(code, signal);
|
|
@@ -98807,7 +98848,8 @@ Each subdirectory of this folder is one mini app:
|
|
|
98807
98848
|
|
|
98808
98849
|
<app-id>/
|
|
98809
98850
|
manifest.json - { "title": string, "description"?: string, "icon"?: string,
|
|
98810
|
-
"tools"?: [{ "name", "description", "inputSchema" }]
|
|
98851
|
+
"tools"?: [{ "name", "description", "inputSchema" }],
|
|
98852
|
+
"headlessSessions"?: boolean }
|
|
98811
98853
|
"icon" is the app logo: a Lucide icon name (see
|
|
98812
98854
|
"Icons and logos" below)
|
|
98813
98855
|
index.html - markup only (full HTML document); do NOT reference app.js
|
|
@@ -98863,14 +98905,21 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
|
|
|
98863
98905
|
|
|
98864
98906
|
## Bridge API (window.AgentPane)
|
|
98865
98907
|
|
|
98866
|
-
- getApp() - app info (id, title)
|
|
98908
|
+
- getApp() - app info (id, title, workspace = the folder of this instance, '' = global)
|
|
98867
98909
|
- getState() / setState(data, { ifVersion }?) - persistent JSON state, survives page reload; getState reads the stored copy on every call (see "Shared state" below)
|
|
98868
98910
|
- onStateChanged(callback) - callback({ version }) when somebody else (an agent, another tab) wrote the state; not fired for this tab's own setState
|
|
98869
98911
|
- createSession({ cwd, runtime_type, model, model_reasoning_effort, title }) - agent session owned by this app; model_reasoning_effort is the effort for its turns ("low" | "medium" | "high" | "xhigh" | "max" | "ultra", the levels the model supports), omitted = the runtime's default
|
|
98870
98912
|
- submitTurn(sessionId, prompt, { attachments }?) - send a prompt to a session; attachments (optional) are stored files (id, url or the uploadFile result) or inline Blobs / { name, type, data } sent with that turn only; the agent sees attached images (Claude and Codex)
|
|
98871
|
-
-
|
|
98913
|
+
- getSession(sessionId) - one of this app's sessions, also read headless: { id, title, status, running, backgroundTasks, lastTurn: { id, status, response, error, resumeState } | null }, null for any other id. A turn waiting to continue after an interruption has running true and resumeState 'waiting'
|
|
98914
|
+
- cancelTurn(sessionId) - stop the running main turn of one of this app's sessions: { cancelled }, false when none runs; a discussion thread keeps running; rejects for any other session
|
|
98915
|
+
- setSessionLifecycle(sessionId, 'finished' | 'working') - finish or reopen one of this app's sessions, as the sidebar does; rejects for any other session
|
|
98916
|
+
- callTool(tool, args) - tab only: run one of this app's manifest tools, by its bare name; it is answered like an agent's call, with caller null. The app's frame has an opaque origin and cannot fetch the pane's API, so this is how a tab gets the headless runtime to do something
|
|
98917
|
+
- listProviders() - tab only: the runtimes this pane offers, as /api/providers lists them (id, label, capability flags)
|
|
98918
|
+
- listModels(runtime, cwd?) - tab only: a runtime's models, as /api/providers/:id/models lists them; cwd for runtimes that list per workspace
|
|
98919
|
+
- pickDirectory() - tab only: the folder dialog of the machine the pane runs on: { path }, or { cancelled: true } when the user dismissed it; works only while the app is on screen, so call it from a click handler
|
|
98920
|
+
- onTurnCompleted(callback) - callback(event, { sessionId, turnId, response }) when a turn ends; event is 'turn:completed' or 'turn:failed' ({ sessionId, turnId, error })
|
|
98872
98921
|
- onBackgroundTasks(callback) - callback({ sessionId, tasks }) when the live background-task set of one of the app's sessions changes (Monitor shells, backgrounded subagents); tasks is the CURRENT set, empty when none are left
|
|
98873
|
-
- onToolCall(callback) - callback({ callId, name, tool, args }) when the AGENT calls one of the manifest tools (name and tool carry the same tool name); answer with resolveToolCall(callId, result)
|
|
98922
|
+
- onToolCall(callback) - callback({ callId, name, tool, args, caller }) when the AGENT calls one of the manifest tools (name and tool carry the same tool name); answer with resolveToolCall(callId, result). caller: see "Who called" below
|
|
98874
98923
|
- openSession(sessionId) - show that session in the pane (the view switches to its conversation); works only while the app is on screen, so call it from a click handler
|
|
98875
98924
|
- openUrl(url) - open an absolute http(s) URL in a new browser tab; call it from a click handler (popup blockers allow tabs opened by a click)
|
|
98876
98925
|
- uploadFile(blob | { name, type, data }) - store an image for this app (data = base64 or a base64 data: URL); returns { id, url, path, type, size }
|
|
@@ -98928,8 +98977,8 @@ viewer; it refreshes via AgentPane.onStateChanged(cb).
|
|
|
98928
98977
|
|
|
98929
98978
|
Headless contract for apps that declare tools:
|
|
98930
98979
|
- register AgentPane.onToolCall(handler) synchronously at startup
|
|
98931
|
-
- the handler gets one payload, handler({ callId, name, tool, args }),
|
|
98932
|
-
same as in the tab; a handler declaring two parameters still gets the
|
|
98980
|
+
- the handler gets one payload, handler({ callId, name, tool, args, caller }),
|
|
98981
|
+
the same as in the tab; a handler declaring two parameters still gets the
|
|
98933
98982
|
older headless form ('tool_call', payload)
|
|
98934
98983
|
- tool handlers must not depend on the DOM or the live UI
|
|
98935
98984
|
- headless state is the instance of the CALLING session's workspace; open
|
|
@@ -98937,8 +98986,8 @@ Headless contract for apps that declare tools:
|
|
|
98937
98986
|
above it; one in an app folder, or with no workspace, uses the global
|
|
98938
98987
|
instance. A path the pane does not know (unregistered, deleted) fails the
|
|
98939
98988
|
call with "Unknown workspace", and no state is read or written
|
|
98940
|
-
-
|
|
98941
|
-
|
|
98989
|
+
- openSession/openUrl are not available in the headless runtime;
|
|
98990
|
+
createSession/submitTurn only with "headlessSessions" (see below)
|
|
98942
98991
|
- stored files are: getFile(ref)/fileUrl(ref)/uploadFile({ name, type, data })
|
|
98943
98992
|
work headless (url is root-relative there); return file.path to the agent
|
|
98944
98993
|
so it can open the image
|
|
@@ -98948,6 +98997,46 @@ falls back to relaying calls into the OPEN app iframe \u2014 the app must be
|
|
|
98948
98997
|
open in AgentPane, on the calling session's workspace, for a tool call to
|
|
98949
98998
|
succeed in that case.
|
|
98950
98999
|
|
|
99000
|
+
## Who called
|
|
99001
|
+
|
|
99002
|
+
payload.caller names the session behind a tool call:
|
|
99003
|
+
{ sessionId, runtime, workspace, appOwned }. appOwned is true for a session
|
|
99004
|
+
this app opened with createSession, false for any other, Edit App sessions
|
|
99005
|
+
included. caller is null for a call from outside the pane's sessions (a
|
|
99006
|
+
script over REST, a session of a Repoburg backend).
|
|
99007
|
+
|
|
99008
|
+
Use it to keep management tools away from the app's own workers:
|
|
99009
|
+
if (payload.caller?.appOwned) refuse. This stops a worker that strays from its
|
|
99010
|
+
prompt, not one working around it: nothing proves the id, so anything that can
|
|
99011
|
+
reach the pane's API can name another session or none.
|
|
99012
|
+
|
|
99013
|
+
A worker reporting over REST is not an MCP call and has no caller unless it
|
|
99014
|
+
says so. Claude sessions have their id in the environment, so have the prompt
|
|
99015
|
+
add "caller": { "sessionId": "$AGENT_PANE_SESSION_ID" } to the
|
|
99016
|
+
POST /api/apps/mcp/call body.
|
|
99017
|
+
|
|
99018
|
+
## Agent sessions without a tab
|
|
99019
|
+
|
|
99020
|
+
Set "headlessSessions": true in manifest.json to run an app's agent work with
|
|
99021
|
+
no tab open. Without it, createSession/submitTurn reject in the headless
|
|
99022
|
+
runtime and events go to the open tab only.
|
|
99023
|
+
|
|
99024
|
+
- createSession, submitTurn, cancelTurn and setSessionLifecycle work headless,
|
|
99025
|
+
from a tool handler or an event callback. All but createSession reach only
|
|
99026
|
+
sessions this app opened; attachments are stored files or inline
|
|
99027
|
+
{ name, type, data } (no Blobs in the sandbox)
|
|
99028
|
+
- onTurnCompleted and onBackgroundTasks fire in the headless runtime, for every
|
|
99029
|
+
session of the app, also the ones its tab opened. They go to the instance
|
|
99030
|
+
that opened the session, and it loads again when it has to
|
|
99031
|
+
- a turn stopped by the user arrives as 'turn:failed' with cancelled: true
|
|
99032
|
+
- these events no longer reach the tab, so each is handled once. Put what the
|
|
99033
|
+
tab shows in the state; the tab follows with onStateChanged
|
|
99034
|
+
- onTurnDelta stays tab-only
|
|
99035
|
+
- app.js runs again on every load of the runtime (pane restart, hot reload):
|
|
99036
|
+
start sessions from a tool call or an event, never at startup
|
|
99037
|
+
- events are not replayed. Keep the session ids in the state, and when the
|
|
99038
|
+
runtime loads ask getSession(id) what happened while the pane was down
|
|
99039
|
+
|
|
98951
99040
|
## Result contract
|
|
98952
99041
|
|
|
98953
99042
|
To give the app a structured result, put this requirement in the job prompt:
|
|
@@ -98967,7 +99056,8 @@ function readManifestIn(dir) {
|
|
|
98967
99056
|
title: parsed.title,
|
|
98968
99057
|
description: typeof parsed.description === "string" ? parsed.description : void 0,
|
|
98969
99058
|
icon: typeof parsed.icon === "string" ? parsed.icon : void 0,
|
|
98970
|
-
tools: Array.isArray(parsed.tools) ? parsed.tools.filter((t) => t && typeof t.name === "string" && typeof t.description === "string") : void 0
|
|
99059
|
+
tools: Array.isArray(parsed.tools) ? parsed.tools.filter((t) => t && typeof t.name === "string" && typeof t.description === "string") : void 0,
|
|
99060
|
+
headlessSessions: parsed.headlessSessions === true ? true : void 0
|
|
98971
99061
|
};
|
|
98972
99062
|
} catch {
|
|
98973
99063
|
return null;
|
|
@@ -99114,6 +99204,17 @@ function updateInstanceState(appId, workspace, patch) {
|
|
|
99114
99204
|
return next;
|
|
99115
99205
|
}).immediate();
|
|
99116
99206
|
}
|
|
99207
|
+
function resolveToolWorkspace(workspace) {
|
|
99208
|
+
if (!workspace) return "";
|
|
99209
|
+
const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
|
|
99210
|
+
const active = rows.filter((w) => !w.deleted).map((w) => w.path);
|
|
99211
|
+
if (active.includes(workspace)) return workspace;
|
|
99212
|
+
const cwd = path5.isAbsolute(workspace) ? path5.resolve(workspace) : "";
|
|
99213
|
+
if (isInAppFolder(cwd)) return "";
|
|
99214
|
+
const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path5.sep)).sort((a, b) => b.path.length - a.path.length)[0];
|
|
99215
|
+
if (covering && !covering.deleted) return covering.path;
|
|
99216
|
+
throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
|
|
99217
|
+
}
|
|
99117
99218
|
function deleteAppInstances(appId) {
|
|
99118
99219
|
getDb().prepare("DELETE FROM app_instances WHERE app_id = ?").run(appId);
|
|
99119
99220
|
}
|
|
@@ -99121,21 +99222,305 @@ function deleteAppInstances(appId) {
|
|
|
99121
99222
|
// src/apps/mcp-tools.ts
|
|
99122
99223
|
import fs5 from "node:fs";
|
|
99123
99224
|
|
|
99225
|
+
// src/apps/app-files.ts
|
|
99226
|
+
import crypto2 from "node:crypto";
|
|
99227
|
+
import fs4 from "node:fs";
|
|
99228
|
+
import os4 from "node:os";
|
|
99229
|
+
import path6 from "node:path";
|
|
99230
|
+
var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
|
|
99231
|
+
var APP_FILE_TYPES = {
|
|
99232
|
+
"image/png": "png",
|
|
99233
|
+
"image/jpeg": "jpg",
|
|
99234
|
+
"image/gif": "gif",
|
|
99235
|
+
"image/webp": "webp"
|
|
99236
|
+
};
|
|
99237
|
+
var EXT_TYPES = Object.fromEntries(
|
|
99238
|
+
Object.entries(APP_FILE_TYPES).map(([type, ext]) => [ext, type])
|
|
99239
|
+
);
|
|
99240
|
+
var APP_FILE_ID_RE = /^[a-f0-9]{64}\.(?:png|jpg|gif|webp)$/;
|
|
99241
|
+
var FILE_URL_RE = /^(?:https?:\/\/[^/?#]+)?\/api\/apps\/([^/?#]+)\/files\/([^/?#]+)$/i;
|
|
99242
|
+
var AppFileError = class extends Error {
|
|
99243
|
+
constructor(message, status) {
|
|
99244
|
+
super(message);
|
|
99245
|
+
this.status = status;
|
|
99246
|
+
this.name = "AppFileError";
|
|
99247
|
+
}
|
|
99248
|
+
};
|
|
99249
|
+
var rootOverride2 = null;
|
|
99250
|
+
function setAppFilesRootOverride(root) {
|
|
99251
|
+
rootOverride2 = root;
|
|
99252
|
+
}
|
|
99253
|
+
function appFilesRoot() {
|
|
99254
|
+
return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
|
|
99255
|
+
}
|
|
99256
|
+
function appFilesDir(appId) {
|
|
99257
|
+
if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
|
|
99258
|
+
return path6.join(appFilesRoot(), appId);
|
|
99259
|
+
}
|
|
99260
|
+
function appFileUrl(appId, fileId) {
|
|
99261
|
+
return `/api/apps/${appId}/files/${fileId}`;
|
|
99262
|
+
}
|
|
99263
|
+
function fileType(fileId) {
|
|
99264
|
+
return EXT_TYPES[fileId.slice(fileId.lastIndexOf(".") + 1)] ?? "application/octet-stream";
|
|
99265
|
+
}
|
|
99266
|
+
function sniffImageType(bytes) {
|
|
99267
|
+
if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
99268
|
+
return "image/png";
|
|
99269
|
+
}
|
|
99270
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
99271
|
+
if (bytes.length >= 6 && /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString("latin1"))) return "image/gif";
|
|
99272
|
+
if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP") {
|
|
99273
|
+
return "image/webp";
|
|
99274
|
+
}
|
|
99275
|
+
return null;
|
|
99276
|
+
}
|
|
99277
|
+
function decodeBase64(data) {
|
|
99278
|
+
let b64 = data;
|
|
99279
|
+
let dataUrlType = null;
|
|
99280
|
+
const dataUrl = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
|
|
99281
|
+
if (dataUrl) {
|
|
99282
|
+
dataUrlType = dataUrl[1].toLowerCase() || null;
|
|
99283
|
+
b64 = data.slice(dataUrl[0].length);
|
|
99284
|
+
} else if (/^data:/i.test(data)) {
|
|
99285
|
+
return null;
|
|
99286
|
+
}
|
|
99287
|
+
b64 = b64.replace(/\s+/g, "");
|
|
99288
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 === 1) return null;
|
|
99289
|
+
return { bytes: Buffer.from(b64, "base64"), dataUrlType };
|
|
99290
|
+
}
|
|
99291
|
+
function normalizeType(type) {
|
|
99292
|
+
if (typeof type !== "string") return null;
|
|
99293
|
+
const t = type.split(";")[0].trim().toLowerCase();
|
|
99294
|
+
return t || null;
|
|
99295
|
+
}
|
|
99296
|
+
var ACCEPTED = "PNG, JPEG, GIF or WebP";
|
|
99297
|
+
function saveAppFile(appId, upload) {
|
|
99298
|
+
const dir = appFilesDir(appId);
|
|
99299
|
+
if (typeof upload.data !== "string" || !upload.data) {
|
|
99300
|
+
throw new AppFileError("data is required (base64 or a base64 data: URL)", 400);
|
|
99301
|
+
}
|
|
99302
|
+
const decoded = decodeBase64(upload.data);
|
|
99303
|
+
if (!decoded) throw new AppFileError("data is not valid base64", 400);
|
|
99304
|
+
const declared = normalizeType(upload.type) ?? decoded.dataUrlType;
|
|
99305
|
+
if (declared && !APP_FILE_TYPES[declared]) {
|
|
99306
|
+
throw new AppFileError(`Unsupported file type '${declared}' \u2014 upload a ${ACCEPTED} image`, 400);
|
|
99307
|
+
}
|
|
99308
|
+
const { bytes } = decoded;
|
|
99309
|
+
if (bytes.length === 0) throw new AppFileError("The file is empty", 400);
|
|
99310
|
+
if (bytes.length > APP_FILE_MAX_BYTES) {
|
|
99311
|
+
throw new AppFileError(
|
|
99312
|
+
`The file is ${bytes.length} bytes \u2014 the limit is ${APP_FILE_MAX_BYTES} bytes (${APP_FILE_MAX_BYTES / (1024 * 1024)} MB)`,
|
|
99313
|
+
413
|
|
99314
|
+
);
|
|
99315
|
+
}
|
|
99316
|
+
const type = sniffImageType(bytes);
|
|
99317
|
+
if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
|
|
99318
|
+
const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
|
|
99319
|
+
const file = path6.join(dir, fileId);
|
|
99320
|
+
if (!fs4.existsSync(file)) {
|
|
99321
|
+
fs4.mkdirSync(dir, { recursive: true });
|
|
99322
|
+
const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
|
|
99323
|
+
fs4.writeFileSync(tmp, bytes);
|
|
99324
|
+
fs4.renameSync(tmp, file);
|
|
99325
|
+
}
|
|
99326
|
+
return { id: fileId, url: appFileUrl(appId, fileId), path: file, type, size: bytes.length };
|
|
99327
|
+
}
|
|
99328
|
+
function appFileRefId(appId, ref) {
|
|
99329
|
+
let value = ref;
|
|
99330
|
+
if (value && typeof value === "object") {
|
|
99331
|
+
const obj = value;
|
|
99332
|
+
value = typeof obj.id === "string" ? obj.id : obj.url;
|
|
99333
|
+
}
|
|
99334
|
+
if (typeof value !== "string") return null;
|
|
99335
|
+
const s = value.trim();
|
|
99336
|
+
if (APP_FILE_ID_RE.test(s)) return s;
|
|
99337
|
+
const m = FILE_URL_RE.exec(s);
|
|
99338
|
+
if (!m) return null;
|
|
99339
|
+
let owner;
|
|
99340
|
+
try {
|
|
99341
|
+
owner = decodeURIComponent(m[1]);
|
|
99342
|
+
} catch {
|
|
99343
|
+
return null;
|
|
99344
|
+
}
|
|
99345
|
+
return owner === appId && APP_FILE_ID_RE.test(m[2]) ? m[2] : null;
|
|
99346
|
+
}
|
|
99347
|
+
function getAppFile(appId, ref) {
|
|
99348
|
+
if (!APP_ID_RE.test(appId)) return null;
|
|
99349
|
+
const fileId = appFileRefId(appId, ref);
|
|
99350
|
+
if (!fileId) return null;
|
|
99351
|
+
const file = path6.join(appFilesDir(appId), fileId);
|
|
99352
|
+
try {
|
|
99353
|
+
const stat2 = fs4.statSync(file);
|
|
99354
|
+
if (!stat2.isFile()) return null;
|
|
99355
|
+
return { id: fileId, url: appFileUrl(appId, fileId), path: file, type: fileType(fileId), size: stat2.size };
|
|
99356
|
+
} catch {
|
|
99357
|
+
return null;
|
|
99358
|
+
}
|
|
99359
|
+
}
|
|
99360
|
+
function readAppFileData(appId, fileId) {
|
|
99361
|
+
if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
|
|
99362
|
+
try {
|
|
99363
|
+
return { bytes: fs4.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
|
|
99364
|
+
} catch {
|
|
99365
|
+
return null;
|
|
99366
|
+
}
|
|
99367
|
+
}
|
|
99368
|
+
function deleteAppFiles(appId) {
|
|
99369
|
+
if (!APP_ID_RE.test(appId)) return;
|
|
99370
|
+
fs4.rmSync(appFilesDir(appId), { recursive: true, force: true });
|
|
99371
|
+
}
|
|
99372
|
+
|
|
99373
|
+
// src/apps/app-sessions.ts
|
|
99374
|
+
function text(value) {
|
|
99375
|
+
return typeof value === "string" ? value : void 0;
|
|
99376
|
+
}
|
|
99377
|
+
var AppSessionError = class extends Error {
|
|
99378
|
+
};
|
|
99379
|
+
function openedByApp(session, appId) {
|
|
99380
|
+
if (session.origin_app_id !== appId) return false;
|
|
99381
|
+
return session.origin_app_workspace !== null || !isInAppFolder(session.cwd);
|
|
99382
|
+
}
|
|
99383
|
+
function sessionOwner(sessionId) {
|
|
99384
|
+
const session = getDb().prepare("SELECT origin_app_id, origin_app_workspace, cwd FROM sessions WHERE id = ?").get(sessionId);
|
|
99385
|
+
const appId = session?.origin_app_id;
|
|
99386
|
+
if (!session || !appId || !openedByApp(session, appId)) return null;
|
|
99387
|
+
return { appId, workspace: session.origin_app_workspace ?? cwdInstance(session.cwd) };
|
|
99388
|
+
}
|
|
99389
|
+
function cwdInstance(cwd) {
|
|
99390
|
+
try {
|
|
99391
|
+
return resolveToolWorkspace(cwd);
|
|
99392
|
+
} catch {
|
|
99393
|
+
return "";
|
|
99394
|
+
}
|
|
99395
|
+
}
|
|
99396
|
+
function isMainTurn(turnId) {
|
|
99397
|
+
const turn = getDb().prepare("SELECT thread_id FROM turns WHERE id = ?").get(turnId);
|
|
99398
|
+
return !!turn && !turn.thread_id;
|
|
99399
|
+
}
|
|
99400
|
+
function createAppSession(appId, workspace, opts) {
|
|
99401
|
+
const o = opts && typeof opts === "object" ? opts : {};
|
|
99402
|
+
const runtime = text(o.runtime_type);
|
|
99403
|
+
if (runtime && !hasProvider(runtime)) throw new Error(`createSession: unknown runtime ${runtime}`);
|
|
99404
|
+
const session = createSession(getDb(), {
|
|
99405
|
+
title: text(o.title),
|
|
99406
|
+
runtime_type: runtime,
|
|
99407
|
+
model: text(o.model),
|
|
99408
|
+
model_reasoning_effort: text(o.model_reasoning_effort),
|
|
99409
|
+
cwd: text(o.cwd),
|
|
99410
|
+
origin_app_id: appId,
|
|
99411
|
+
origin_app_workspace: workspace
|
|
99412
|
+
});
|
|
99413
|
+
broadcast("session:created", { session });
|
|
99414
|
+
return session;
|
|
99415
|
+
}
|
|
99416
|
+
function splitDataUrl(data, type) {
|
|
99417
|
+
const m = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
|
|
99418
|
+
if (!m) return { type, data };
|
|
99419
|
+
return { type: type || m[1] || void 0, data: data.slice(m[0].length) };
|
|
99420
|
+
}
|
|
99421
|
+
function turnAttachments(appId, list) {
|
|
99422
|
+
if (list == null) return [];
|
|
99423
|
+
if (!Array.isArray(list)) throw new Error("submitTurn: attachments must be an array");
|
|
99424
|
+
return list.map((item, i) => {
|
|
99425
|
+
const inline = item && typeof item === "object" ? item : null;
|
|
99426
|
+
if (typeof inline?.data === "string") {
|
|
99427
|
+
const { type, data } = splitDataUrl(inline.data, text(inline.type) || void 0);
|
|
99428
|
+
if (!type) throw new Error(`submitTurn: attachment ${i + 1} has no type`);
|
|
99429
|
+
return { name: text(inline.name) || `attachment-${i + 1}`, media_type: type, data };
|
|
99430
|
+
}
|
|
99431
|
+
const fileId = appFileRefId(appId, item);
|
|
99432
|
+
const file = fileId ? readAppFileData(appId, fileId) : null;
|
|
99433
|
+
if (!fileId || !file) throw new Error(`submitTurn: attachment ${i + 1} is not a file of this app`);
|
|
99434
|
+
return { name: fileId, media_type: file.type, data: file.bytes.toString("base64") };
|
|
99435
|
+
});
|
|
99436
|
+
}
|
|
99437
|
+
function submitAppTurn(appId, sessionId, prompt, opts) {
|
|
99438
|
+
const db2 = getDb();
|
|
99439
|
+
const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
|
|
99440
|
+
if (!session || !openedByApp(session, appId)) {
|
|
99441
|
+
throw new Error(`submitTurn: ${String(sessionId)} is not a session of this app`);
|
|
99442
|
+
}
|
|
99443
|
+
if (typeof prompt !== "string" || !prompt.trim()) throw new Error("submitTurn: prompt is required");
|
|
99444
|
+
const attachments = turnAttachments(appId, opts?.attachments);
|
|
99445
|
+
return startTurn(db2, session, { prompt, attachments, originAppId: appId });
|
|
99446
|
+
}
|
|
99447
|
+
function appSessionInfo(appId, sessionId) {
|
|
99448
|
+
const db2 = getDb();
|
|
99449
|
+
const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
|
|
99450
|
+
if (!session || !openedByApp(session, appId)) return null;
|
|
99451
|
+
const turn = db2.prepare(
|
|
99452
|
+
`SELECT id, status, agent_response, error, resume_state FROM turns
|
|
99453
|
+
WHERE session_id = ? AND thread_id IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1`
|
|
99454
|
+
).get(session.id);
|
|
99455
|
+
return {
|
|
99456
|
+
id: session.id,
|
|
99457
|
+
title: session.title,
|
|
99458
|
+
status: session.status,
|
|
99459
|
+
running: !!session.is_running,
|
|
99460
|
+
backgroundTasks: listAllBackgroundTasks()[session.id] ?? [],
|
|
99461
|
+
lastTurn: turn ? {
|
|
99462
|
+
id: turn.id,
|
|
99463
|
+
status: turn.status,
|
|
99464
|
+
response: turn.agent_response || null,
|
|
99465
|
+
error: turn.error,
|
|
99466
|
+
resumeState: turn.resume_state
|
|
99467
|
+
} : null
|
|
99468
|
+
};
|
|
99469
|
+
}
|
|
99470
|
+
function ownSession(appId, sessionId, api) {
|
|
99471
|
+
const session = getDb().prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
|
|
99472
|
+
if (!session || !openedByApp(session, appId)) {
|
|
99473
|
+
throw new AppSessionError(`${api}: ${String(sessionId)} is not a session of this app`);
|
|
99474
|
+
}
|
|
99475
|
+
return session;
|
|
99476
|
+
}
|
|
99477
|
+
async function cancelAppTurn(appId, sessionId) {
|
|
99478
|
+
const session = ownSession(appId, sessionId, "cancelTurn");
|
|
99479
|
+
const live = getDb().prepare(`SELECT 1 FROM turns WHERE session_id = ? AND thread_id IS NULL AND status IN ('pending', 'running') LIMIT 1`).get(session.id);
|
|
99480
|
+
if (!live) return { cancelled: false };
|
|
99481
|
+
return { cancelled: await getProvider(session.runtime_type).interruptTurn(session.id) };
|
|
99482
|
+
}
|
|
99483
|
+
function setAppSessionLifecycle(appId, sessionId, lifecycle) {
|
|
99484
|
+
const session = ownSession(appId, sessionId, "setSessionLifecycle");
|
|
99485
|
+
if (lifecycle !== "working" && lifecycle !== "finished") {
|
|
99486
|
+
throw new Error(`setSessionLifecycle: lifecycle must be 'working' or 'finished'`);
|
|
99487
|
+
}
|
|
99488
|
+
const db2 = getDb();
|
|
99489
|
+
db2.prepare("UPDATE sessions SET lifecycle = ?, updated_at = ? WHERE id = ?").run(
|
|
99490
|
+
lifecycle,
|
|
99491
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
99492
|
+
session.id
|
|
99493
|
+
);
|
|
99494
|
+
broadcast("session:updated", { session: db2.prepare("SELECT * FROM sessions WHERE id = ?").get(session.id) });
|
|
99495
|
+
return { lifecycle };
|
|
99496
|
+
}
|
|
99497
|
+
function toolCaller(appId, sessionId) {
|
|
99498
|
+
if (!sessionId) return null;
|
|
99499
|
+
const session = getDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
|
|
99500
|
+
if (!session) return null;
|
|
99501
|
+
return {
|
|
99502
|
+
sessionId: session.id,
|
|
99503
|
+
runtime: session.runtime_type,
|
|
99504
|
+
workspace: session.cwd ?? "",
|
|
99505
|
+
appOwned: openedByApp(session, appId)
|
|
99506
|
+
};
|
|
99507
|
+
}
|
|
99508
|
+
|
|
99124
99509
|
// src/apps/headless-runtime.ts
|
|
99125
99510
|
import vm2 from "node:vm";
|
|
99126
99511
|
|
|
99127
99512
|
// src/apps/app-compile.ts
|
|
99128
99513
|
import vm from "node:vm";
|
|
99129
|
-
import
|
|
99514
|
+
import path7 from "node:path";
|
|
99130
99515
|
import ts from "typescript";
|
|
99131
99516
|
|
|
99132
99517
|
// src/apps/app-lint.ts
|
|
99133
99518
|
var EMOJI_RE = /[\u{1F1E6}-\u{1F1FF}]{2}|[0-9#*]\uFE0F?\u20E3|(?:\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F)\p{Emoji_Modifier}?(?:\u200D(?:\p{Emoji_Presentation}|\p{Extended_Pictographic})\uFE0F?\p{Emoji_Modifier}?)*/gu;
|
|
99134
99519
|
var MAX_EMOJI_WARNINGS = 30;
|
|
99135
99520
|
var EMOJI_HINT = 'mini apps must not use emoji. Use a Lucide icon instead (see "Icons and logos" in the apps CLAUDE.md / AGENTS.md).';
|
|
99136
|
-
function findEmoji(
|
|
99521
|
+
function findEmoji(text2) {
|
|
99137
99522
|
const found = [];
|
|
99138
|
-
const lines =
|
|
99523
|
+
const lines = text2.split("\n");
|
|
99139
99524
|
for (let i = 0; i < lines.length; i++) {
|
|
99140
99525
|
for (const m of lines[i].matchAll(EMOJI_RE)) {
|
|
99141
99526
|
found.push({ emoji: m[0], line: i + 1, column: (m.index ?? 0) + 1 });
|
|
@@ -99192,7 +99577,12 @@ function lintAppSources(files, manifestIcon) {
|
|
|
99192
99577
|
var APP_TS = "app.ts";
|
|
99193
99578
|
var BRIDGE_DTS_FILE = "agentpane.d.ts";
|
|
99194
99579
|
var BRIDGE_DTS = `/** AgentPane bridge \u2014 typed contract for mini apps (ambient, no import). */
|
|
99195
|
-
interface AgentPaneAppInfo {
|
|
99580
|
+
interface AgentPaneAppInfo {
|
|
99581
|
+
id: string;
|
|
99582
|
+
title?: string;
|
|
99583
|
+
/** Folder of this instance ('' = global). Absent on older panes. */
|
|
99584
|
+
workspace?: string;
|
|
99585
|
+
}
|
|
99196
99586
|
interface AgentPaneState {
|
|
99197
99587
|
pinned: boolean;
|
|
99198
99588
|
data: Record<string, unknown> | null;
|
|
@@ -99225,13 +99615,53 @@ interface AgentPaneCreateSessionOptions {
|
|
|
99225
99615
|
model_reasoning_effort?: string;
|
|
99226
99616
|
cwd?: string;
|
|
99227
99617
|
}
|
|
99228
|
-
interface AgentPaneTurnPayload {
|
|
99618
|
+
interface AgentPaneTurnPayload {
|
|
99619
|
+
sessionId?: string;
|
|
99620
|
+
turnId?: string;
|
|
99621
|
+
response?: string | null;
|
|
99622
|
+
error?: string;
|
|
99623
|
+
/** Headless: the user stopped the turn (event 'turn:failed'). */
|
|
99624
|
+
cancelled?: boolean;
|
|
99625
|
+
}
|
|
99229
99626
|
interface AgentPaneDeltaPayload { sessionId?: string; turnId?: string; itemId?: string; delta?: string }
|
|
99230
|
-
|
|
99627
|
+
/** The session behind a tool call. A plain claim, nothing proves it: enough to
|
|
99628
|
+
* keep the app's workers to their prompt, not to stop one working around it. */
|
|
99629
|
+
interface AgentPaneToolCaller {
|
|
99630
|
+
sessionId: string;
|
|
99631
|
+
runtime: string;
|
|
99632
|
+
workspace: string;
|
|
99633
|
+
/** This app opened that session with createSession. */
|
|
99634
|
+
appOwned: boolean;
|
|
99635
|
+
}
|
|
99636
|
+
interface AgentPaneToolCallPayload {
|
|
99637
|
+
callId: string;
|
|
99638
|
+
tool: string;
|
|
99639
|
+
name: string;
|
|
99640
|
+
args: Record<string, unknown>;
|
|
99641
|
+
/** null: the call came from outside the pane's sessions. */
|
|
99642
|
+
caller: AgentPaneToolCaller | null;
|
|
99643
|
+
}
|
|
99231
99644
|
/** Live background tasks of a session (Monitor shells, backgrounded subagents):
|
|
99232
99645
|
* the CURRENT set, REPLACE semantics \u2014 an empty array means none are left. */
|
|
99233
99646
|
interface AgentPaneBackgroundTasksPayload { sessionId?: string; tasks?: AgentPaneBackgroundTask[] }
|
|
99234
99647
|
interface AgentPaneBackgroundTask { task_id: string; task_type: string; description: string }
|
|
99648
|
+
/** One of the app's sessions (getSession). */
|
|
99649
|
+
interface AgentPaneSessionState {
|
|
99650
|
+
id: string;
|
|
99651
|
+
title: string | null;
|
|
99652
|
+
status: string;
|
|
99653
|
+
/** A turn is live, also one waiting to continue after an interruption. */
|
|
99654
|
+
running: boolean;
|
|
99655
|
+
backgroundTasks: AgentPaneBackgroundTask[];
|
|
99656
|
+
lastTurn: {
|
|
99657
|
+
id: string;
|
|
99658
|
+
status: string;
|
|
99659
|
+
response: string | null;
|
|
99660
|
+
error: string | null;
|
|
99661
|
+
/** 'waiting' = it waits to continue. */
|
|
99662
|
+
resumeState: string | null;
|
|
99663
|
+
} | null;
|
|
99664
|
+
}
|
|
99235
99665
|
/** A file the app stored with uploadFile (PNG, JPEG, GIF or WebP, max 5 MB). */
|
|
99236
99666
|
interface AgentPaneFile {
|
|
99237
99667
|
/** Content id "<sha256>.<ext>": the same bytes always get the same id. */
|
|
@@ -99269,6 +99699,25 @@ declare const AgentPane: {
|
|
|
99269
99699
|
createSession(opts?: AgentPaneCreateSessionOptions): Promise<AgentPaneSessionInfo>;
|
|
99270
99700
|
/** Send a prompt to a session; opts.attachments go with it (the agent sees images). */
|
|
99271
99701
|
submitTurn(sessionId: string, prompt: string, opts?: AgentPaneSubmitTurnOptions): Promise<unknown>;
|
|
99702
|
+
/** One of this app's sessions, null for any other id. Works headless too. */
|
|
99703
|
+
getSession(sessionId: string): Promise<AgentPaneSessionState | null>;
|
|
99704
|
+
/** Stop the running main turn of one of this app's sessions; cancelled is
|
|
99705
|
+
* false when none runs. Rejects for any other session. */
|
|
99706
|
+
cancelTurn(sessionId: string): Promise<{ cancelled: boolean }>;
|
|
99707
|
+
/** Finish or reopen one of this app's sessions, as the sidebar does. Rejects
|
|
99708
|
+
* for any other session. */
|
|
99709
|
+
setSessionLifecycle(sessionId: string, lifecycle: 'working' | 'finished'): Promise<{ lifecycle: 'working' | 'finished' }>;
|
|
99710
|
+
/** Tab only: run one of this app's manifest tools; it is answered like an
|
|
99711
|
+
* agent's call, with no caller. A sandboxed tab has no way to the API of its
|
|
99712
|
+
* own, and this is how it gets the headless runtime to do something. */
|
|
99713
|
+
callTool?(tool: string, args?: Record<string, unknown>): Promise<unknown>;
|
|
99714
|
+
/** Tab only: the runtimes this pane offers, as /api/providers lists them. */
|
|
99715
|
+
listProviders?(): Promise<unknown[]>;
|
|
99716
|
+
/** Tab only: a runtime's models; cwd for runtimes that list per workspace. */
|
|
99717
|
+
listModels?(runtime: string, cwd?: string): Promise<unknown[]>;
|
|
99718
|
+
/** Tab only, and only while the app is on screen, so call it from a click
|
|
99719
|
+
* handler: the folder dialog of the machine the pane runs on. */
|
|
99720
|
+
pickDirectory?(): Promise<{ path?: string; cancelled?: boolean }>;
|
|
99272
99721
|
onTurnCompleted(cb: (event: 'turn:completed' | 'turn:failed', payload: AgentPaneTurnPayload | null) => void): void;
|
|
99273
99722
|
onTurnDelta(cb: (payload: AgentPaneDeltaPayload) => void): void;
|
|
99274
99723
|
onToolCall(cb: (payload: AgentPaneToolCallPayload) => void): void;
|
|
@@ -99418,15 +99867,15 @@ function typeCheckModules(appId, modules) {
|
|
|
99418
99867
|
};
|
|
99419
99868
|
const host = ts.createCompilerHost(options);
|
|
99420
99869
|
const origReadFile = host.readFile.bind(host);
|
|
99421
|
-
host.readFile = (fname) =>
|
|
99870
|
+
host.readFile = (fname) => path7.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
|
|
99422
99871
|
host.writeFile = () => {
|
|
99423
99872
|
};
|
|
99424
|
-
const bridgePath =
|
|
99425
|
-
const rootNames = [...modules.map((m) =>
|
|
99873
|
+
const bridgePath = path7.join(dir, BRIDGE_DTS_FILE);
|
|
99874
|
+
const rootNames = [...modules.map((m) => path7.join(dir, m.file)), bridgePath];
|
|
99426
99875
|
const program = ts.createProgram(rootNames, options, host);
|
|
99427
99876
|
const out = [];
|
|
99428
99877
|
for (const mod of modules) {
|
|
99429
|
-
const sf = program.getSourceFile(
|
|
99878
|
+
const sf = program.getSourceFile(path7.join(dir, mod.file));
|
|
99430
99879
|
if (!sf) continue;
|
|
99431
99880
|
out.push(
|
|
99432
99881
|
...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
|
|
@@ -99505,154 +99954,6 @@ function compileAppJs(appId) {
|
|
|
99505
99954
|
return result;
|
|
99506
99955
|
}
|
|
99507
99956
|
|
|
99508
|
-
// src/apps/app-files.ts
|
|
99509
|
-
import crypto2 from "node:crypto";
|
|
99510
|
-
import fs4 from "node:fs";
|
|
99511
|
-
import os4 from "node:os";
|
|
99512
|
-
import path7 from "node:path";
|
|
99513
|
-
var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
|
|
99514
|
-
var APP_FILE_TYPES = {
|
|
99515
|
-
"image/png": "png",
|
|
99516
|
-
"image/jpeg": "jpg",
|
|
99517
|
-
"image/gif": "gif",
|
|
99518
|
-
"image/webp": "webp"
|
|
99519
|
-
};
|
|
99520
|
-
var EXT_TYPES = Object.fromEntries(
|
|
99521
|
-
Object.entries(APP_FILE_TYPES).map(([type, ext]) => [ext, type])
|
|
99522
|
-
);
|
|
99523
|
-
var APP_FILE_ID_RE = /^[a-f0-9]{64}\.(?:png|jpg|gif|webp)$/;
|
|
99524
|
-
var FILE_URL_RE = /^(?:https?:\/\/[^/?#]+)?\/api\/apps\/([^/?#]+)\/files\/([^/?#]+)$/i;
|
|
99525
|
-
var AppFileError = class extends Error {
|
|
99526
|
-
constructor(message, status) {
|
|
99527
|
-
super(message);
|
|
99528
|
-
this.status = status;
|
|
99529
|
-
this.name = "AppFileError";
|
|
99530
|
-
}
|
|
99531
|
-
};
|
|
99532
|
-
var rootOverride2 = null;
|
|
99533
|
-
function setAppFilesRootOverride(root) {
|
|
99534
|
-
rootOverride2 = root;
|
|
99535
|
-
}
|
|
99536
|
-
function appFilesRoot() {
|
|
99537
|
-
return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
|
|
99538
|
-
}
|
|
99539
|
-
function appFilesDir(appId) {
|
|
99540
|
-
if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
|
|
99541
|
-
return path7.join(appFilesRoot(), appId);
|
|
99542
|
-
}
|
|
99543
|
-
function appFileUrl(appId, fileId) {
|
|
99544
|
-
return `/api/apps/${appId}/files/${fileId}`;
|
|
99545
|
-
}
|
|
99546
|
-
function fileType(fileId) {
|
|
99547
|
-
return EXT_TYPES[fileId.slice(fileId.lastIndexOf(".") + 1)] ?? "application/octet-stream";
|
|
99548
|
-
}
|
|
99549
|
-
function sniffImageType(bytes) {
|
|
99550
|
-
if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
99551
|
-
return "image/png";
|
|
99552
|
-
}
|
|
99553
|
-
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
99554
|
-
if (bytes.length >= 6 && /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString("latin1"))) return "image/gif";
|
|
99555
|
-
if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP") {
|
|
99556
|
-
return "image/webp";
|
|
99557
|
-
}
|
|
99558
|
-
return null;
|
|
99559
|
-
}
|
|
99560
|
-
function decodeBase64(data) {
|
|
99561
|
-
let b64 = data;
|
|
99562
|
-
let dataUrlType = null;
|
|
99563
|
-
const dataUrl = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
|
|
99564
|
-
if (dataUrl) {
|
|
99565
|
-
dataUrlType = dataUrl[1].toLowerCase() || null;
|
|
99566
|
-
b64 = data.slice(dataUrl[0].length);
|
|
99567
|
-
} else if (/^data:/i.test(data)) {
|
|
99568
|
-
return null;
|
|
99569
|
-
}
|
|
99570
|
-
b64 = b64.replace(/\s+/g, "");
|
|
99571
|
-
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 === 1) return null;
|
|
99572
|
-
return { bytes: Buffer.from(b64, "base64"), dataUrlType };
|
|
99573
|
-
}
|
|
99574
|
-
function normalizeType(type) {
|
|
99575
|
-
if (typeof type !== "string") return null;
|
|
99576
|
-
const t = type.split(";")[0].trim().toLowerCase();
|
|
99577
|
-
return t || null;
|
|
99578
|
-
}
|
|
99579
|
-
var ACCEPTED = "PNG, JPEG, GIF or WebP";
|
|
99580
|
-
function saveAppFile(appId, upload) {
|
|
99581
|
-
const dir = appFilesDir(appId);
|
|
99582
|
-
if (typeof upload.data !== "string" || !upload.data) {
|
|
99583
|
-
throw new AppFileError("data is required (base64 or a base64 data: URL)", 400);
|
|
99584
|
-
}
|
|
99585
|
-
const decoded = decodeBase64(upload.data);
|
|
99586
|
-
if (!decoded) throw new AppFileError("data is not valid base64", 400);
|
|
99587
|
-
const declared = normalizeType(upload.type) ?? decoded.dataUrlType;
|
|
99588
|
-
if (declared && !APP_FILE_TYPES[declared]) {
|
|
99589
|
-
throw new AppFileError(`Unsupported file type '${declared}' \u2014 upload a ${ACCEPTED} image`, 400);
|
|
99590
|
-
}
|
|
99591
|
-
const { bytes } = decoded;
|
|
99592
|
-
if (bytes.length === 0) throw new AppFileError("The file is empty", 400);
|
|
99593
|
-
if (bytes.length > APP_FILE_MAX_BYTES) {
|
|
99594
|
-
throw new AppFileError(
|
|
99595
|
-
`The file is ${bytes.length} bytes \u2014 the limit is ${APP_FILE_MAX_BYTES} bytes (${APP_FILE_MAX_BYTES / (1024 * 1024)} MB)`,
|
|
99596
|
-
413
|
|
99597
|
-
);
|
|
99598
|
-
}
|
|
99599
|
-
const type = sniffImageType(bytes);
|
|
99600
|
-
if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
|
|
99601
|
-
const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
|
|
99602
|
-
const file = path7.join(dir, fileId);
|
|
99603
|
-
if (!fs4.existsSync(file)) {
|
|
99604
|
-
fs4.mkdirSync(dir, { recursive: true });
|
|
99605
|
-
const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
|
|
99606
|
-
fs4.writeFileSync(tmp, bytes);
|
|
99607
|
-
fs4.renameSync(tmp, file);
|
|
99608
|
-
}
|
|
99609
|
-
return { id: fileId, url: appFileUrl(appId, fileId), path: file, type, size: bytes.length };
|
|
99610
|
-
}
|
|
99611
|
-
function appFileRefId(appId, ref) {
|
|
99612
|
-
let value = ref;
|
|
99613
|
-
if (value && typeof value === "object") {
|
|
99614
|
-
const obj = value;
|
|
99615
|
-
value = typeof obj.id === "string" ? obj.id : obj.url;
|
|
99616
|
-
}
|
|
99617
|
-
if (typeof value !== "string") return null;
|
|
99618
|
-
const s = value.trim();
|
|
99619
|
-
if (APP_FILE_ID_RE.test(s)) return s;
|
|
99620
|
-
const m = FILE_URL_RE.exec(s);
|
|
99621
|
-
if (!m) return null;
|
|
99622
|
-
let owner;
|
|
99623
|
-
try {
|
|
99624
|
-
owner = decodeURIComponent(m[1]);
|
|
99625
|
-
} catch {
|
|
99626
|
-
return null;
|
|
99627
|
-
}
|
|
99628
|
-
return owner === appId && APP_FILE_ID_RE.test(m[2]) ? m[2] : null;
|
|
99629
|
-
}
|
|
99630
|
-
function getAppFile(appId, ref) {
|
|
99631
|
-
if (!APP_ID_RE.test(appId)) return null;
|
|
99632
|
-
const fileId = appFileRefId(appId, ref);
|
|
99633
|
-
if (!fileId) return null;
|
|
99634
|
-
const file = path7.join(appFilesDir(appId), fileId);
|
|
99635
|
-
try {
|
|
99636
|
-
const stat2 = fs4.statSync(file);
|
|
99637
|
-
if (!stat2.isFile()) return null;
|
|
99638
|
-
return { id: fileId, url: appFileUrl(appId, fileId), path: file, type: fileType(fileId), size: stat2.size };
|
|
99639
|
-
} catch {
|
|
99640
|
-
return null;
|
|
99641
|
-
}
|
|
99642
|
-
}
|
|
99643
|
-
function readAppFileData(appId, fileId) {
|
|
99644
|
-
if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
|
|
99645
|
-
try {
|
|
99646
|
-
return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
|
|
99647
|
-
} catch {
|
|
99648
|
-
return null;
|
|
99649
|
-
}
|
|
99650
|
-
}
|
|
99651
|
-
function deleteAppFiles(appId) {
|
|
99652
|
-
if (!APP_ID_RE.test(appId)) return;
|
|
99653
|
-
fs4.rmSync(appFilesDir(appId), { recursive: true, force: true });
|
|
99654
|
-
}
|
|
99655
|
-
|
|
99656
99957
|
// src/apps/headless-runtime.ts
|
|
99657
99958
|
var HEADLESS_TOOL_TIMEOUT_MS = Number(process.env.AGENT_PANE_TOOL_TIMEOUT_MS ?? 3e4);
|
|
99658
99959
|
function stub() {
|
|
@@ -99675,24 +99976,59 @@ function stub() {
|
|
|
99675
99976
|
function runtimeKey(appId, workspace) {
|
|
99676
99977
|
return `${appId}\0${workspace}`;
|
|
99677
99978
|
}
|
|
99979
|
+
function runAppCode(appId, code) {
|
|
99980
|
+
const report = (err) => console.error(`[headless:${appId}] app code failed:`, err);
|
|
99981
|
+
try {
|
|
99982
|
+
const result = code();
|
|
99983
|
+
if (typeof result?.then === "function") result.then(void 0, report);
|
|
99984
|
+
} catch (err) {
|
|
99985
|
+
report(err);
|
|
99986
|
+
}
|
|
99987
|
+
}
|
|
99678
99988
|
var runtimes = /* @__PURE__ */ new Map();
|
|
99679
99989
|
var pendingCalls = /* @__PURE__ */ new Map();
|
|
99680
|
-
function
|
|
99990
|
+
function loadRuntime(appId, workspace) {
|
|
99681
99991
|
const key = runtimeKey(appId, workspace);
|
|
99682
99992
|
const cached = runtimes.get(key);
|
|
99683
|
-
if (cached) return cached
|
|
99993
|
+
if (cached) return cached;
|
|
99684
99994
|
const js = compileAppJs(appId).js;
|
|
99685
99995
|
if (!js.trim()) return null;
|
|
99686
99996
|
const manifest = readManifest(appId);
|
|
99687
|
-
|
|
99997
|
+
const headlessSessions = manifest?.headlessSessions === true;
|
|
99998
|
+
const appSetTimeout = (callback, ms, ...args) => setTimeout(() => runAppCode(appId, () => callback(...args)), ms);
|
|
99999
|
+
const sandbox = {
|
|
100000
|
+
console: {
|
|
100001
|
+
log: (...a) => console.log(`[app:${appId}]`, ...a),
|
|
100002
|
+
warn: (...a) => console.warn(`[app:${appId}]`, ...a),
|
|
100003
|
+
error: (...a) => console.error(`[app:${appId}]`, ...a)
|
|
100004
|
+
},
|
|
100005
|
+
setTimeout: appSetTimeout,
|
|
100006
|
+
clearTimeout,
|
|
100007
|
+
document: stub(),
|
|
100008
|
+
navigator: stub()
|
|
100009
|
+
};
|
|
100010
|
+
const context = vm2.createContext(sandbox);
|
|
100011
|
+
const SandboxPromise = vm2.runInContext("Promise", context);
|
|
100012
|
+
const answer = (work) => new SandboxPromise((resolve, reject) => {
|
|
100013
|
+
try {
|
|
100014
|
+
resolve(work());
|
|
100015
|
+
} catch (err) {
|
|
100016
|
+
reject(err);
|
|
100017
|
+
}
|
|
100018
|
+
});
|
|
100019
|
+
const requireHeadlessSessions = (api) => {
|
|
100020
|
+
if (headlessSessions) return;
|
|
100021
|
+
throw new Error(`${api} is not available in the headless runtime without "headlessSessions": true in manifest.json`);
|
|
100022
|
+
};
|
|
100023
|
+
const entry = { handler: null, turnListeners: [], taskListeners: [] };
|
|
99688
100024
|
const bridge = {
|
|
99689
|
-
getApp: () =>
|
|
100025
|
+
getApp: () => answer(() => ({ id: appId, title: manifest?.title ?? appId, workspace })),
|
|
99690
100026
|
// State is scoped to the calling session's workspace instance; '' = global
|
|
99691
100027
|
// (no known workspace). The open tab keeps its own workspace-scoped view.
|
|
99692
|
-
getState: () =>
|
|
100028
|
+
getState: () => answer(() => getInstanceState(appId, workspace)),
|
|
99693
100029
|
// opts.ifVersion: write only on top of that version — same contract as
|
|
99694
100030
|
// the iframe bridge (rejects with code 'conflict' + the stored state).
|
|
99695
|
-
setState: (data, opts) => {
|
|
100031
|
+
setState: (data, opts) => answer(() => {
|
|
99696
100032
|
const ifVersion = opts?.ifVersion;
|
|
99697
100033
|
let next;
|
|
99698
100034
|
try {
|
|
@@ -99702,61 +100038,72 @@ function getHeadlessToolHandler(appId, workspace = "") {
|
|
|
99702
100038
|
});
|
|
99703
100039
|
} catch (err) {
|
|
99704
100040
|
if (err instanceof StateConflictError) {
|
|
99705
|
-
|
|
100041
|
+
throw Object.assign(new Error(err.message), { code: "conflict", state: err.current });
|
|
99706
100042
|
}
|
|
99707
|
-
|
|
100043
|
+
throw err;
|
|
99708
100044
|
}
|
|
99709
100045
|
broadcast("app:state_changed", { appId, workspace, version: next.version });
|
|
99710
|
-
return
|
|
99711
|
-
},
|
|
100046
|
+
return next;
|
|
100047
|
+
}),
|
|
99712
100048
|
onToolCall: (cb) => {
|
|
99713
100049
|
if (typeof cb !== "function") return;
|
|
99714
|
-
handler = cb.length >= 2 ? (payload) => cb("tool_call", payload) : (payload) => cb(payload);
|
|
100050
|
+
entry.handler = cb.length >= 2 ? (payload) => cb("tool_call", payload) : (payload) => cb(payload);
|
|
99715
100051
|
},
|
|
99716
|
-
resolveToolCall: (callId, result) => {
|
|
100052
|
+
resolveToolCall: (callId, result) => answer(() => {
|
|
99717
100053
|
resolveHeadlessToolCall(String(callId), result);
|
|
99718
|
-
return
|
|
99719
|
-
},
|
|
100054
|
+
return { ok: true };
|
|
100055
|
+
}),
|
|
99720
100056
|
// Stored files (shared with the open tab). Tool handlers hand the agent
|
|
99721
100057
|
// `path`, which it opens with its own file tools.
|
|
99722
|
-
getFile: (ref) =>
|
|
100058
|
+
getFile: (ref) => answer(() => getAppFile(appId, ref)),
|
|
99723
100059
|
fileUrl: (ref) => {
|
|
99724
100060
|
const fileId = appFileRefId(appId, ref);
|
|
99725
100061
|
if (fileId) return appFileUrl(appId, fileId);
|
|
99726
100062
|
return typeof ref === "string" ? ref : "";
|
|
99727
100063
|
},
|
|
99728
|
-
uploadFile: (file) => {
|
|
100064
|
+
uploadFile: (file) => answer(() => {
|
|
99729
100065
|
try {
|
|
99730
100066
|
const upload = file && typeof file === "object" ? file : {};
|
|
99731
|
-
return
|
|
100067
|
+
return saveAppFile(appId, upload);
|
|
99732
100068
|
} catch (err) {
|
|
99733
|
-
|
|
100069
|
+
throw new Error(`uploadFile: ${err.message}`);
|
|
99734
100070
|
}
|
|
100071
|
+
}),
|
|
100072
|
+
getSession: (sessionId) => answer(() => appSessionInfo(appId, sessionId)),
|
|
100073
|
+
createSession: (opts) => answer(() => {
|
|
100074
|
+
requireHeadlessSessions("createSession");
|
|
100075
|
+
return createAppSession(appId, workspace, opts);
|
|
100076
|
+
}),
|
|
100077
|
+
submitTurn: (sessionId, prompt, opts) => answer(() => {
|
|
100078
|
+
requireHeadlessSessions("submitTurn");
|
|
100079
|
+
return submitAppTurn(appId, sessionId, prompt, opts);
|
|
100080
|
+
}),
|
|
100081
|
+
cancelTurn: (sessionId) => answer(() => {
|
|
100082
|
+
requireHeadlessSessions("cancelTurn");
|
|
100083
|
+
return cancelAppTurn(appId, sessionId);
|
|
100084
|
+
}),
|
|
100085
|
+
setSessionLifecycle: (sessionId, lifecycle) => answer(() => {
|
|
100086
|
+
requireHeadlessSessions("setSessionLifecycle");
|
|
100087
|
+
return setAppSessionLifecycle(appId, sessionId, lifecycle);
|
|
100088
|
+
}),
|
|
100089
|
+
onTurnCompleted: (cb) => {
|
|
100090
|
+
if (typeof cb === "function") entry.turnListeners.push(cb);
|
|
99735
100091
|
},
|
|
99736
|
-
|
|
99737
|
-
|
|
99738
|
-
submitTurn: () => Promise.reject(new Error("submitTurn is not available in the headless runtime")),
|
|
99739
|
-
openSession: () => Promise.reject(new Error("openSession is not available in the headless runtime")),
|
|
99740
|
-
openUrl: () => Promise.reject(new Error("openUrl is not available in the headless runtime")),
|
|
99741
|
-
onTurnCompleted: () => {
|
|
100092
|
+
onBackgroundTasks: (cb) => {
|
|
100093
|
+
if (typeof cb === "function") entry.taskListeners.push(cb);
|
|
99742
100094
|
},
|
|
100095
|
+
// Live streaming is for a screen; nothing here renders.
|
|
99743
100096
|
onTurnDelta: () => {
|
|
99744
100097
|
},
|
|
99745
|
-
|
|
99746
|
-
|
|
99747
|
-
|
|
99748
|
-
|
|
99749
|
-
|
|
99750
|
-
|
|
99751
|
-
|
|
99752
|
-
error: (...a) => console.error(`[app:${appId}]`, ...a)
|
|
99753
|
-
},
|
|
99754
|
-
setTimeout,
|
|
99755
|
-
clearTimeout,
|
|
99756
|
-
document: stub(),
|
|
99757
|
-
navigator: stub(),
|
|
99758
|
-
AgentPane: bridge
|
|
100098
|
+
// UI actions are intentionally unavailable headless.
|
|
100099
|
+
openSession: () => answer(() => {
|
|
100100
|
+
throw new Error("openSession is not available in the headless runtime");
|
|
100101
|
+
}),
|
|
100102
|
+
openUrl: () => answer(() => {
|
|
100103
|
+
throw new Error("openUrl is not available in the headless runtime");
|
|
100104
|
+
})
|
|
99759
100105
|
};
|
|
100106
|
+
sandbox.AgentPane = bridge;
|
|
99760
100107
|
const windowObj = {
|
|
99761
100108
|
addEventListener: () => {
|
|
99762
100109
|
},
|
|
@@ -99764,24 +100111,26 @@ function getHeadlessToolHandler(appId, workspace = "") {
|
|
|
99764
100111
|
},
|
|
99765
100112
|
document: sandbox.document,
|
|
99766
100113
|
navigator: sandbox.navigator,
|
|
99767
|
-
setTimeout,
|
|
100114
|
+
setTimeout: appSetTimeout,
|
|
99768
100115
|
clearTimeout,
|
|
99769
100116
|
AgentPane: bridge
|
|
99770
100117
|
};
|
|
99771
100118
|
sandbox.window = windowObj;
|
|
99772
100119
|
sandbox.self = windowObj;
|
|
99773
100120
|
try {
|
|
99774
|
-
const context = vm2.createContext(sandbox);
|
|
99775
100121
|
vm2.runInContext(js, context, { filename: `${appId}/app.js` });
|
|
99776
100122
|
} catch (err) {
|
|
99777
100123
|
console.warn(`[headless:${appId}] app.js load failed: ${err.message}`);
|
|
99778
100124
|
return null;
|
|
99779
100125
|
}
|
|
99780
|
-
if (!handler) return null;
|
|
99781
|
-
runtimes.set(key,
|
|
99782
|
-
return
|
|
100126
|
+
if (!entry.handler && !entry.turnListeners.length && !entry.taskListeners.length) return null;
|
|
100127
|
+
runtimes.set(key, entry);
|
|
100128
|
+
return entry;
|
|
100129
|
+
}
|
|
100130
|
+
function getHeadlessToolHandler(appId, workspace = "") {
|
|
100131
|
+
return loadRuntime(appId, workspace)?.handler ?? null;
|
|
99783
100132
|
}
|
|
99784
|
-
function dispatchHeadlessToolCall(handler, tool, args) {
|
|
100133
|
+
function dispatchHeadlessToolCall(handler, tool, args, caller = null) {
|
|
99785
100134
|
const callId = v4_default();
|
|
99786
100135
|
const result = new Promise((resolve, reject) => {
|
|
99787
100136
|
const timer2 = setTimeout(() => {
|
|
@@ -99794,15 +100143,18 @@ function dispatchHeadlessToolCall(handler, tool, args) {
|
|
|
99794
100143
|
}, HEADLESS_TOOL_TIMEOUT_MS);
|
|
99795
100144
|
pendingCalls.set(callId, { resolve, reject, timer: timer2 });
|
|
99796
100145
|
});
|
|
100146
|
+
const crashed = (err) => {
|
|
100147
|
+
const pending = pendingCalls.get(callId);
|
|
100148
|
+
if (!pending) return;
|
|
100149
|
+
pendingCalls.delete(callId);
|
|
100150
|
+
clearTimeout(pending.timer);
|
|
100151
|
+
pending.reject(new Error(`Headless tool handler crashed: ${err?.message ?? String(err)}`));
|
|
100152
|
+
};
|
|
99797
100153
|
try {
|
|
99798
|
-
handler({ callId, tool, name: tool, args: args ?? {} });
|
|
100154
|
+
const running = handler({ callId, tool, name: tool, args: args ?? {}, caller });
|
|
100155
|
+
if (typeof running?.then === "function") running.then(void 0, crashed);
|
|
99799
100156
|
} catch (err) {
|
|
99800
|
-
|
|
99801
|
-
if (pending) {
|
|
99802
|
-
pendingCalls.delete(callId);
|
|
99803
|
-
clearTimeout(pending.timer);
|
|
99804
|
-
pending.reject(new Error(`Headless tool handler crashed: ${err.message}`));
|
|
99805
|
-
}
|
|
100157
|
+
crashed(err);
|
|
99806
100158
|
}
|
|
99807
100159
|
return { callId, result };
|
|
99808
100160
|
}
|
|
@@ -99814,6 +100166,60 @@ function resolveHeadlessToolCall(callId, result) {
|
|
|
99814
100166
|
pending.resolve(result ?? null);
|
|
99815
100167
|
return true;
|
|
99816
100168
|
}
|
|
100169
|
+
function turnEvent(event, data) {
|
|
100170
|
+
const { sessionId, turnId } = data;
|
|
100171
|
+
if (event === "turn:completed") return [event, { sessionId, turnId, response: data.response ?? null }];
|
|
100172
|
+
if (event === "turn:failed") return [event, { sessionId, turnId, error: data.error }];
|
|
100173
|
+
return ["turn:failed", { sessionId, turnId, error: "The turn was stopped", cancelled: true }];
|
|
100174
|
+
}
|
|
100175
|
+
function deliverSessionEvent(event, data) {
|
|
100176
|
+
const sessionId = String(data.sessionId);
|
|
100177
|
+
const owner = sessionOwner(sessionId);
|
|
100178
|
+
if (!owner || !readManifest(owner.appId)?.headlessSessions) return;
|
|
100179
|
+
const { appId, workspace } = owner;
|
|
100180
|
+
const isTaskEvent = event === "background_tasks";
|
|
100181
|
+
if (!isTaskEvent && !isMainTurn(String(data.turnId))) return;
|
|
100182
|
+
const runtime = loadRuntime(appId, workspace);
|
|
100183
|
+
if (!runtime) {
|
|
100184
|
+
console.warn(`[headless:${appId}] ${event} of session ${sessionId} dropped: the app cannot load headless`);
|
|
100185
|
+
return;
|
|
100186
|
+
}
|
|
100187
|
+
if (isTaskEvent) {
|
|
100188
|
+
const payload2 = { sessionId, tasks: data.tasks };
|
|
100189
|
+
for (const listener of runtime.taskListeners) runAppCode(appId, () => listener(payload2));
|
|
100190
|
+
return;
|
|
100191
|
+
}
|
|
100192
|
+
const [name, payload] = turnEvent(event, data);
|
|
100193
|
+
for (const listener of runtime.turnListeners) runAppCode(appId, () => listener(name, payload));
|
|
100194
|
+
}
|
|
100195
|
+
var SESSION_EVENTS = /* @__PURE__ */ new Set(["turn:completed", "turn:failed", "turn:cancelled", "background_tasks"]);
|
|
100196
|
+
function handleUnhandledRejection(reason, promise) {
|
|
100197
|
+
if (promise instanceof Promise) throw reason;
|
|
100198
|
+
console.error("[headless] unhandled rejection in app code:", reason);
|
|
100199
|
+
}
|
|
100200
|
+
var stopSessionEvents = null;
|
|
100201
|
+
function startHeadlessEvents() {
|
|
100202
|
+
stopHeadlessEvents();
|
|
100203
|
+
const untap = tapBroadcast((event, data) => {
|
|
100204
|
+
if (!SESSION_EVENTS.has(event)) return;
|
|
100205
|
+
setImmediate(() => {
|
|
100206
|
+
try {
|
|
100207
|
+
deliverSessionEvent(event, data);
|
|
100208
|
+
} catch (err) {
|
|
100209
|
+
console.error(`[headless] ${event} delivery failed:`, err);
|
|
100210
|
+
}
|
|
100211
|
+
});
|
|
100212
|
+
});
|
|
100213
|
+
process.on("unhandledRejection", handleUnhandledRejection);
|
|
100214
|
+
stopSessionEvents = () => {
|
|
100215
|
+
untap();
|
|
100216
|
+
process.off("unhandledRejection", handleUnhandledRejection);
|
|
100217
|
+
};
|
|
100218
|
+
}
|
|
100219
|
+
function stopHeadlessEvents() {
|
|
100220
|
+
stopSessionEvents?.();
|
|
100221
|
+
stopSessionEvents = null;
|
|
100222
|
+
}
|
|
99817
100223
|
function invalidateHeadlessRuntime(appId) {
|
|
99818
100224
|
invalidateCompiledApp(appId);
|
|
99819
100225
|
if (!appId) {
|
|
@@ -99853,7 +100259,7 @@ function splitToolName(name) {
|
|
|
99853
100259
|
return { appId: name.slice(0, idx), localName: name.slice(idx + TOOL_NS.length) };
|
|
99854
100260
|
}
|
|
99855
100261
|
var pendingCalls2 = /* @__PURE__ */ new Map();
|
|
99856
|
-
function dispatchAppTool(toolName, args, workspace = "") {
|
|
100262
|
+
function dispatchAppTool(toolName, args, workspace = "", callerSessionId) {
|
|
99857
100263
|
const split = splitToolName(toolName);
|
|
99858
100264
|
if (!split) {
|
|
99859
100265
|
throw new Error(`Invalid tool name: ${toolName}`);
|
|
@@ -99864,9 +100270,10 @@ function dispatchAppTool(toolName, args, workspace = "") {
|
|
|
99864
100270
|
if (!manifest || !tool) {
|
|
99865
100271
|
throw new Error(`Unknown mini-app tool: ${toolName}`);
|
|
99866
100272
|
}
|
|
100273
|
+
const caller = toolCaller(appId, callerSessionId);
|
|
99867
100274
|
const headlessHandler = getHeadlessToolHandler(appId, workspace);
|
|
99868
100275
|
if (headlessHandler) {
|
|
99869
|
-
return dispatchHeadlessToolCall(headlessHandler, localName, args);
|
|
100276
|
+
return dispatchHeadlessToolCall(headlessHandler, localName, args, caller);
|
|
99870
100277
|
}
|
|
99871
100278
|
const callId = v4_default();
|
|
99872
100279
|
const result = new Promise((resolve, reject) => {
|
|
@@ -99879,12 +100286,12 @@ function dispatchAppTool(toolName, args, workspace = "") {
|
|
|
99879
100286
|
);
|
|
99880
100287
|
}, TOOL_CALL_TIMEOUT_MS);
|
|
99881
100288
|
pendingCalls2.set(callId, { resolve, reject, timer: timer2, appId });
|
|
99882
|
-
broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {}, workspace });
|
|
100289
|
+
broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {}, workspace, caller });
|
|
99883
100290
|
});
|
|
99884
100291
|
return { callId, result };
|
|
99885
100292
|
}
|
|
99886
|
-
async function callAppTool(toolName, args, workspace = "") {
|
|
99887
|
-
return dispatchAppTool(toolName, args, workspace).result;
|
|
100293
|
+
async function callAppTool(toolName, args, workspace = "", callerSessionId) {
|
|
100294
|
+
return dispatchAppTool(toolName, args, workspace, callerSessionId).result;
|
|
99888
100295
|
}
|
|
99889
100296
|
function resolveAppToolCall(callId, result, error) {
|
|
99890
100297
|
const pending = pendingCalls2.get(callId);
|
|
@@ -99902,17 +100309,6 @@ function anyAppHasTools() {
|
|
|
99902
100309
|
// src/routes/apps.ts
|
|
99903
100310
|
var FILE_UPLOAD_BODY_LIMIT = Math.ceil(APP_FILE_MAX_BYTES * 4 / 3) + 64 * 1024;
|
|
99904
100311
|
var IMPORT_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
99905
|
-
function resolveToolWorkspace(workspace) {
|
|
99906
|
-
if (!workspace) return "";
|
|
99907
|
-
const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
|
|
99908
|
-
const active = rows.filter((w) => !w.deleted).map((w) => w.path);
|
|
99909
|
-
if (active.includes(workspace)) return workspace;
|
|
99910
|
-
const cwd = path8.isAbsolute(workspace) ? path8.resolve(workspace) : "";
|
|
99911
|
-
if (isInAppFolder(cwd)) return "";
|
|
99912
|
-
const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path8.sep)).sort((a, b) => b.path.length - a.path.length)[0];
|
|
99913
|
-
if (covering && !covering.deleted) return covering.path;
|
|
99914
|
-
throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
|
|
99915
|
-
}
|
|
99916
100312
|
var IMPORT_MAX_FILES = 50;
|
|
99917
100313
|
var IMPORT_MAX_FILE_BYTES = 512 * 1024;
|
|
99918
100314
|
var SKELETON_HTML = `<!DOCTYPE html>
|
|
@@ -99961,6 +100357,8 @@ async function registerAppRoutes(fastify, opts) {
|
|
|
99961
100357
|
broadcast("app:source:updated", { appId });
|
|
99962
100358
|
});
|
|
99963
100359
|
fastify.addHook("onClose", async () => stopAppsWatch());
|
|
100360
|
+
startHeadlessEvents();
|
|
100361
|
+
fastify.addHook("onClose", async () => stopHeadlessEvents());
|
|
99964
100362
|
fastify.get("/api/apps", async () => {
|
|
99965
100363
|
try {
|
|
99966
100364
|
ensureAppsRoot();
|
|
@@ -100118,15 +100516,16 @@ async function registerAppRoutes(fastify, opts) {
|
|
|
100118
100516
|
properties: {
|
|
100119
100517
|
tool: { type: "string" },
|
|
100120
100518
|
args: { type: ["object", "null"] },
|
|
100121
|
-
workspace: { type: ["string", "null"] }
|
|
100519
|
+
workspace: { type: ["string", "null"] },
|
|
100520
|
+
caller: { type: ["object", "null"], properties: { sessionId: { type: "string" } } }
|
|
100122
100521
|
}
|
|
100123
100522
|
}
|
|
100124
100523
|
}
|
|
100125
100524
|
},
|
|
100126
100525
|
async (request, reply) => {
|
|
100127
|
-
const { tool, args, workspace } = request.body || {};
|
|
100526
|
+
const { tool, args, workspace, caller } = request.body || {};
|
|
100128
100527
|
try {
|
|
100129
|
-
const result = await callAppTool(tool, args ?? {}, resolveToolWorkspace(workspace));
|
|
100528
|
+
const result = await callAppTool(tool, args ?? {}, resolveToolWorkspace(workspace), caller?.sessionId);
|
|
100130
100529
|
return { ok: true, result };
|
|
100131
100530
|
} catch (err) {
|
|
100132
100531
|
return reply.code(200).send({ ok: false, error: err.message });
|
|
@@ -100280,6 +100679,51 @@ async function registerAppRoutes(fastify, opts) {
|
|
|
100280
100679
|
const tasks = listAllBackgroundTasks();
|
|
100281
100680
|
return rows.map((row) => ({ ...row, background_tasks: tasks[row.id] ?? [] }));
|
|
100282
100681
|
});
|
|
100682
|
+
fastify.get(
|
|
100683
|
+
"/api/apps/:id/sessions/:sessionId",
|
|
100684
|
+
async (request, reply) => {
|
|
100685
|
+
const { id, sessionId } = request.params;
|
|
100686
|
+
if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
|
|
100687
|
+
const session = appSessionInfo(id, sessionId);
|
|
100688
|
+
if (!session) return reply.code(404).send({ error: "Session not found" });
|
|
100689
|
+
return session;
|
|
100690
|
+
}
|
|
100691
|
+
);
|
|
100692
|
+
fastify.post(
|
|
100693
|
+
"/api/apps/:id/sessions/:sessionId/cancel",
|
|
100694
|
+
async (request, reply) => {
|
|
100695
|
+
const { id, sessionId } = request.params;
|
|
100696
|
+
if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
|
|
100697
|
+
try {
|
|
100698
|
+
return await cancelAppTurn(id, sessionId);
|
|
100699
|
+
} catch (err) {
|
|
100700
|
+
if (err instanceof AppSessionError) return reply.code(404).send({ error: err.message });
|
|
100701
|
+
throw err;
|
|
100702
|
+
}
|
|
100703
|
+
}
|
|
100704
|
+
);
|
|
100705
|
+
fastify.patch(
|
|
100706
|
+
"/api/apps/:id/sessions/:sessionId",
|
|
100707
|
+
{
|
|
100708
|
+
schema: {
|
|
100709
|
+
body: {
|
|
100710
|
+
type: "object",
|
|
100711
|
+
required: ["lifecycle"],
|
|
100712
|
+
properties: { lifecycle: { type: "string", enum: ["working", "finished"] } }
|
|
100713
|
+
}
|
|
100714
|
+
}
|
|
100715
|
+
},
|
|
100716
|
+
async (request, reply) => {
|
|
100717
|
+
const { id, sessionId } = request.params;
|
|
100718
|
+
if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
|
|
100719
|
+
try {
|
|
100720
|
+
return setAppSessionLifecycle(id, sessionId, request.body.lifecycle);
|
|
100721
|
+
} catch (err) {
|
|
100722
|
+
if (err instanceof AppSessionError) return reply.code(404).send({ error: err.message });
|
|
100723
|
+
throw err;
|
|
100724
|
+
}
|
|
100725
|
+
}
|
|
100726
|
+
);
|
|
100283
100727
|
fastify.post(
|
|
100284
100728
|
"/api/apps/:id/edit-session",
|
|
100285
100729
|
{
|
|
@@ -100799,13 +101243,13 @@ function mapAssistantContent(content, messageId, thinkingTexts) {
|
|
|
100799
101243
|
}
|
|
100800
101244
|
case "thinking": {
|
|
100801
101245
|
const tb = block;
|
|
100802
|
-
let
|
|
100803
|
-
if (!
|
|
100804
|
-
|
|
101246
|
+
let text2 = tb.thinking;
|
|
101247
|
+
if (!text2 && thinkingTexts) {
|
|
101248
|
+
text2 = thinkingTexts.get(i) ?? "";
|
|
100805
101249
|
}
|
|
100806
101250
|
descriptors.push({
|
|
100807
101251
|
type: "reasoning",
|
|
100808
|
-
data: { text },
|
|
101252
|
+
data: { text: text2 },
|
|
100809
101253
|
externalId: messageId
|
|
100810
101254
|
});
|
|
100811
101255
|
break;
|
|
@@ -100879,11 +101323,11 @@ function extractToolResultText(content) {
|
|
|
100879
101323
|
function applyToolResult(itemType, existingData, toolResult, toolUseResult, isError) {
|
|
100880
101324
|
switch (itemType) {
|
|
100881
101325
|
case "command_execution": {
|
|
100882
|
-
const
|
|
101326
|
+
const text2 = extractToolResultText(toolResult?.content);
|
|
100883
101327
|
const tur = toolUseResult && typeof toolUseResult === "object" ? toolUseResult : {};
|
|
100884
101328
|
const stdout = typeof tur.stdout === "string" ? tur.stdout : "";
|
|
100885
101329
|
const stderr = typeof tur.stderr === "string" ? tur.stderr : "";
|
|
100886
|
-
let aggregated =
|
|
101330
|
+
let aggregated = text2 || stdout;
|
|
100887
101331
|
if (stderr) aggregated = aggregated ? `${aggregated}
|
|
100888
101332
|
${stderr}` : stderr;
|
|
100889
101333
|
return {
|
|
@@ -100894,11 +101338,11 @@ ${stderr}` : stderr;
|
|
|
100894
101338
|
};
|
|
100895
101339
|
}
|
|
100896
101340
|
case "mcp_tool_call": {
|
|
100897
|
-
const
|
|
101341
|
+
const text2 = extractToolResultText(toolResult?.content);
|
|
100898
101342
|
return {
|
|
100899
101343
|
...existingData,
|
|
100900
|
-
result:
|
|
100901
|
-
error: isError ?
|
|
101344
|
+
result: text2 ? [{ type: "text", text: text2 }] : toolUseResult ?? null,
|
|
101345
|
+
error: isError ? text2 || "Tool error" : null,
|
|
100902
101346
|
status: isError ? "failed" : "completed"
|
|
100903
101347
|
};
|
|
100904
101348
|
}
|
|
@@ -100934,9 +101378,9 @@ function mapUsage(usage) {
|
|
|
100934
101378
|
|
|
100935
101379
|
// src/claude/transcript-history.ts
|
|
100936
101380
|
var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant"]);
|
|
100937
|
-
function parseTranscript(
|
|
101381
|
+
function parseTranscript(text2) {
|
|
100938
101382
|
const entries = [];
|
|
100939
|
-
for (const line of
|
|
101383
|
+
for (const line of text2.split("\n")) {
|
|
100940
101384
|
if (!line.trim()) continue;
|
|
100941
101385
|
let raw;
|
|
100942
101386
|
try {
|
|
@@ -100994,17 +101438,17 @@ function mainChain(entries) {
|
|
|
100994
101438
|
return chain.reverse();
|
|
100995
101439
|
}
|
|
100996
101440
|
var INJECTED_BLOCK = /^\s*<(system-reminder|ide_opened_file|ide_selection|ide_diagnostics)>/;
|
|
100997
|
-
function tagValue(
|
|
100998
|
-
const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(
|
|
101441
|
+
function tagValue(text2, tag) {
|
|
101442
|
+
const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(text2);
|
|
100999
101443
|
return match ? match[1] : null;
|
|
101000
101444
|
}
|
|
101001
101445
|
function classifyUserInput(entry) {
|
|
101002
101446
|
if (entry.origin?.kind && entry.origin.kind !== "human") return { kind: "ignore" };
|
|
101003
101447
|
const content = entry.message?.content;
|
|
101004
|
-
let
|
|
101448
|
+
let text2 = "";
|
|
101005
101449
|
let images = 0;
|
|
101006
101450
|
if (typeof content === "string") {
|
|
101007
|
-
|
|
101451
|
+
text2 = content;
|
|
101008
101452
|
} else if (Array.isArray(content)) {
|
|
101009
101453
|
const parts = [];
|
|
101010
101454
|
for (const block of content) {
|
|
@@ -101015,9 +101459,9 @@ function classifyUserInput(entry) {
|
|
|
101015
101459
|
images++;
|
|
101016
101460
|
}
|
|
101017
101461
|
}
|
|
101018
|
-
|
|
101462
|
+
text2 = parts.join("\n");
|
|
101019
101463
|
}
|
|
101020
|
-
const trimmed =
|
|
101464
|
+
const trimmed = text2.trim();
|
|
101021
101465
|
if (trimmed.startsWith("[Request interrupted by user")) return { kind: "interrupt" };
|
|
101022
101466
|
const commandName = tagValue(trimmed, "command-name");
|
|
101023
101467
|
if (commandName !== null) {
|
|
@@ -101159,12 +101603,12 @@ function buildTurns(chain) {
|
|
|
101159
101603
|
if (!current) current = openTurn("", entry);
|
|
101160
101604
|
const turn = current;
|
|
101161
101605
|
if (entry.isApiErrorMessage || message.model === "<synthetic>") {
|
|
101162
|
-
const
|
|
101163
|
-
if (entry.isApiErrorMessage &&
|
|
101606
|
+
const text2 = syntheticText(message.content);
|
|
101607
|
+
if (entry.isApiErrorMessage && text2) {
|
|
101164
101608
|
addItem(turn, entry, {
|
|
101165
101609
|
type: "error",
|
|
101166
101610
|
externalId: `api-error-${entry.uuid}`,
|
|
101167
|
-
data: { message:
|
|
101611
|
+
data: { message: text2, error: "api_error" },
|
|
101168
101612
|
status: "completed"
|
|
101169
101613
|
});
|
|
101170
101614
|
}
|
|
@@ -101197,8 +101641,8 @@ function buildTurns(chain) {
|
|
|
101197
101641
|
)
|
|
101198
101642
|
}));
|
|
101199
101643
|
}
|
|
101200
|
-
function transcriptToTurns(
|
|
101201
|
-
return buildTurns(mainChain(parseTranscript(
|
|
101644
|
+
function transcriptToTurns(text2) {
|
|
101645
|
+
return buildTurns(mainChain(parseTranscript(text2)));
|
|
101202
101646
|
}
|
|
101203
101647
|
|
|
101204
101648
|
// src/claude/session-import.ts
|
|
@@ -101268,8 +101712,8 @@ async function listImportableClaudeSessions(db2, workspacePath, now = Date.now()
|
|
|
101268
101712
|
if (known.has(info.sessionId) || !info.cwd) continue;
|
|
101269
101713
|
if (!await sameDir(info.cwd, dir)) continue;
|
|
101270
101714
|
if ((info.fileSize ?? 0) < CHECK_EMPTY_BELOW_BYTES) {
|
|
101271
|
-
const
|
|
101272
|
-
if (!
|
|
101715
|
+
const text2 = await readTranscript(info);
|
|
101716
|
+
if (!text2 || transcriptToTurns(text2).length === 0) continue;
|
|
101273
101717
|
}
|
|
101274
101718
|
sessions.push({
|
|
101275
101719
|
session_id: info.sessionId,
|
|
@@ -101290,9 +101734,9 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
|
|
|
101290
101734
|
const dir = workspacePath ? await realDir(workspacePath) : null;
|
|
101291
101735
|
const info = (dir ? await getSessionInfo(claudeSessionId, { dir }) : void 0) ?? await getSessionInfo(claudeSessionId);
|
|
101292
101736
|
if (!info) throw new ClaudeImportError(404, "Claude Code session not found");
|
|
101293
|
-
const
|
|
101294
|
-
if (
|
|
101295
|
-
const turns = transcriptToTurns(
|
|
101737
|
+
const text2 = await readTranscript(info);
|
|
101738
|
+
if (text2 === null) throw new ClaudeImportError(404, "The session transcript could not be read");
|
|
101739
|
+
const turns = transcriptToTurns(text2);
|
|
101296
101740
|
if (turns.length === 0) throw new ClaudeImportError(422, "This session has no conversation to import");
|
|
101297
101741
|
const cwd = workspacePath && dir && info.cwd && await sameDir(info.cwd, dir) ? workspacePath : info.cwd ?? null;
|
|
101298
101742
|
const sessionId = v4_default();
|
|
@@ -101513,7 +101957,7 @@ async function registerMiniAppMcp(baseUrl, workspace = "") {
|
|
|
101513
101957
|
[MCP_SERVER_NAME]: {
|
|
101514
101958
|
command: process.execPath,
|
|
101515
101959
|
args: [script, panePublicUrl(), workspace],
|
|
101516
|
-
env: {}
|
|
101960
|
+
env: { AGENT_PANE_SESSION_ID: "" }
|
|
101517
101961
|
}
|
|
101518
101962
|
})
|
|
101519
101963
|
};
|
|
@@ -101528,19 +101972,19 @@ async function registerMiniAppMcp(baseUrl, workspace = "") {
|
|
|
101528
101972
|
registered.add(key);
|
|
101529
101973
|
return true;
|
|
101530
101974
|
}
|
|
101531
|
-
const
|
|
101532
|
-
if (res.status === 400 && /already exists/i.test(
|
|
101975
|
+
const text2 = await res.text();
|
|
101976
|
+
if (res.status === 400 && /already exists/i.test(text2)) {
|
|
101533
101977
|
registered.add(key);
|
|
101534
101978
|
return true;
|
|
101535
101979
|
}
|
|
101536
|
-
console.warn(`[miniapp-mcp] registration failed (${res.status}): ${
|
|
101980
|
+
console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
|
|
101537
101981
|
return false;
|
|
101538
101982
|
} catch (err) {
|
|
101539
101983
|
console.warn(`[miniapp-mcp] registration error: ${err.message}`);
|
|
101540
101984
|
return false;
|
|
101541
101985
|
}
|
|
101542
101986
|
}
|
|
101543
|
-
function codexMiniAppLaunchArgs(workspace = "") {
|
|
101987
|
+
function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
|
|
101544
101988
|
const script = stdioScriptPath();
|
|
101545
101989
|
if (!script || !anyAppHasTools()) return null;
|
|
101546
101990
|
return [
|
|
@@ -101551,7 +101995,7 @@ function codexMiniAppLaunchArgs(workspace = "") {
|
|
|
101551
101995
|
"-c",
|
|
101552
101996
|
`mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
|
|
101553
101997
|
"-c",
|
|
101554
|
-
`mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace])}`
|
|
101998
|
+
`mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
|
|
101555
101999
|
];
|
|
101556
102000
|
}
|
|
101557
102001
|
|
|
@@ -101612,11 +102056,11 @@ function shouldSkipItem(type) {
|
|
|
101612
102056
|
function isEmptyReasoning(item) {
|
|
101613
102057
|
const summary = Array.isArray(item.summary) ? item.summary : [];
|
|
101614
102058
|
const content = Array.isArray(item.content) ? item.content : [];
|
|
101615
|
-
const
|
|
101616
|
-
return summary.length === 0 && content.length === 0 &&
|
|
102059
|
+
const text2 = item.text ?? "";
|
|
102060
|
+
return summary.length === 0 && content.length === 0 && text2.length === 0;
|
|
101617
102061
|
}
|
|
101618
|
-
function appServerClientOptions(
|
|
101619
|
-
const launchArgs = codexMiniAppLaunchArgs(cwd);
|
|
102062
|
+
function appServerClientOptions(session, cwd) {
|
|
102063
|
+
const launchArgs = codexMiniAppLaunchArgs(cwd, session.id);
|
|
101620
102064
|
return launchArgs ? { cwd, launchArgs } : { cwd, launchArgs: [] };
|
|
101621
102065
|
}
|
|
101622
102066
|
function threadInstructionParams(cwd) {
|
|
@@ -101679,7 +102123,7 @@ async function getOrCreateThread(session) {
|
|
|
101679
102123
|
sessionMap.set(session.id, entry);
|
|
101680
102124
|
return entry;
|
|
101681
102125
|
}
|
|
101682
|
-
function
|
|
102126
|
+
function turnAttachments2(turn) {
|
|
101683
102127
|
const raw = turn.attachments;
|
|
101684
102128
|
if (!raw) return [];
|
|
101685
102129
|
if (Array.isArray(raw)) return raw;
|
|
@@ -101692,7 +102136,7 @@ function turnAttachments(turn) {
|
|
|
101692
102136
|
}
|
|
101693
102137
|
function buildCodexInput(turn) {
|
|
101694
102138
|
const input = [{ type: "text", text: turn.user_prompt }];
|
|
101695
|
-
for (const att of
|
|
102139
|
+
for (const att of turnAttachments2(turn)) {
|
|
101696
102140
|
if (!att || typeof att.data !== "string" || !att.data) continue;
|
|
101697
102141
|
const type = String(att.media_type ?? "").toLowerCase();
|
|
101698
102142
|
if (type.startsWith("image/")) {
|
|
@@ -101712,7 +102156,7 @@ ${decoded}
|
|
|
101712
102156
|
}
|
|
101713
102157
|
return input;
|
|
101714
102158
|
}
|
|
101715
|
-
async function
|
|
102159
|
+
async function startTurn2(session, turn) {
|
|
101716
102160
|
const db2 = getDb();
|
|
101717
102161
|
let entry;
|
|
101718
102162
|
try {
|
|
@@ -102144,7 +102588,7 @@ async function shutdown() {
|
|
|
102144
102588
|
clearAllThreads();
|
|
102145
102589
|
}
|
|
102146
102590
|
var codexProvider = {
|
|
102147
|
-
startTurn,
|
|
102591
|
+
startTurn: startTurn2,
|
|
102148
102592
|
interruptTurn,
|
|
102149
102593
|
clearThread,
|
|
102150
102594
|
clearAllThreads,
|
|
@@ -102287,12 +102731,12 @@ var NETWORK_TEXTS = [
|
|
|
102287
102731
|
];
|
|
102288
102732
|
var SIGN_IN_ADVICE = /\/login|(sign|log) in again/i;
|
|
102289
102733
|
var OUTSIDE_LOGIN_TEXTS = /api[ -]key|gateway|bedrock|vertex|foundry|mantle/i;
|
|
102290
|
-
function isSignedOut(
|
|
102291
|
-
if (!
|
|
102292
|
-
return SIGN_IN_ADVICE.test(
|
|
102734
|
+
function isSignedOut(text2) {
|
|
102735
|
+
if (!text2) return true;
|
|
102736
|
+
return SIGN_IN_ADVICE.test(text2) || !OUTSIDE_LOGIN_TEXTS.test(text2);
|
|
102293
102737
|
}
|
|
102294
|
-
function classifyApiError({ error, status, text, limitRejected }) {
|
|
102295
|
-
if (error === "authentication_failed" || !error && status === 401) return isSignedOut(
|
|
102738
|
+
function classifyApiError({ error, status, text: text2, limitRejected }) {
|
|
102739
|
+
if (error === "authentication_failed" || !error && status === 401) return isSignedOut(text2) ? "auth" : "fatal";
|
|
102296
102740
|
if (limitRejected && (error === "rate_limit" || !error && status === 429)) return "usage_limit";
|
|
102297
102741
|
if (error && FATAL_ERRORS.has(error)) return "fatal";
|
|
102298
102742
|
if (error && TRANSIENT_ERRORS.has(error)) return "network";
|
|
@@ -102300,7 +102744,7 @@ function classifyApiError({ error, status, text, limitRejected }) {
|
|
|
102300
102744
|
if (status === 408 || status >= 500) return "network";
|
|
102301
102745
|
return "fatal";
|
|
102302
102746
|
}
|
|
102303
|
-
if (
|
|
102747
|
+
if (text2 && NETWORK_TEXTS.some((re) => re.test(text2))) return "network";
|
|
102304
102748
|
if (status === null && (!error || error === "unknown")) return "network";
|
|
102305
102749
|
return "fatal";
|
|
102306
102750
|
}
|
|
@@ -102467,10 +102911,8 @@ function rescueWaitMs() {
|
|
|
102467
102911
|
return Number.isFinite(ms) && ms > 0 ? ms : 15e3;
|
|
102468
102912
|
}
|
|
102469
102913
|
var RESCUE_ENV = ["CLAUDE_CODE_RESUME_INTERRUPTED_TURN", "CLAUDE_CODE_RESUME_REASON"];
|
|
102470
|
-
function spawnEnv(resume) {
|
|
102471
|
-
const
|
|
102472
|
-
if (!resume && !inherited) return void 0;
|
|
102473
|
-
const env = { ...process.env };
|
|
102914
|
+
function spawnEnv(sessionId, resume) {
|
|
102915
|
+
const env = { ...process.env, AGENT_PANE_SESSION_ID: sessionId };
|
|
102474
102916
|
for (const k of RESCUE_ENV) delete env[k];
|
|
102475
102917
|
if (resume) {
|
|
102476
102918
|
env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN = "1";
|
|
@@ -102609,7 +103051,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
102609
103051
|
const key = mapKey ?? session.id;
|
|
102610
103052
|
const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
|
|
102611
103053
|
const rescue = resume && resumeId ? resume : void 0;
|
|
102612
|
-
const env = spawnEnv(rescue);
|
|
103054
|
+
const env = spawnEnv(session.id, rescue);
|
|
102613
103055
|
let cliPid = null;
|
|
102614
103056
|
const options = {
|
|
102615
103057
|
cwd: session.cwd ?? process.cwd(),
|
|
@@ -102709,7 +103151,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
|
|
|
102709
103151
|
})();
|
|
102710
103152
|
return entry;
|
|
102711
103153
|
}
|
|
102712
|
-
async function
|
|
103154
|
+
async function startTurn3(session, turn) {
|
|
102713
103155
|
const db2 = getDb();
|
|
102714
103156
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
102715
103157
|
const mapKey = turn.thread_id ? `${session.id}:thread:${turn.thread_id}` : session.id;
|
|
@@ -102891,16 +103333,16 @@ function handleAssistantMessage(message, sessionId, turnId, entry, db2) {
|
|
|
102891
103333
|
const apiError = message.error;
|
|
102892
103334
|
if (apiError && message.message?.model === "<synthetic>") {
|
|
102893
103335
|
const blocks = Array.isArray(message.message?.content) ? message.message.content : [];
|
|
102894
|
-
const
|
|
103336
|
+
const text2 = blocks.map((b) => {
|
|
102895
103337
|
const block = b;
|
|
102896
103338
|
return block?.type === "text" && typeof block.text === "string" ? block.text : "";
|
|
102897
103339
|
}).join("").trim() || `API error (${apiError})`;
|
|
102898
|
-
entry.lastApiError = { error: apiError, text };
|
|
103340
|
+
entry.lastApiError = { error: apiError, text: text2 };
|
|
102899
103341
|
thinkingAccumulator.delete(messageId);
|
|
102900
103342
|
streamingMessageIds.delete(turnId);
|
|
102901
103343
|
upsertItem(
|
|
102902
103344
|
db2,
|
|
102903
|
-
{ type: "error", data: { message:
|
|
103345
|
+
{ type: "error", data: { message: text2, error: apiError }, externalId: `api-error-${messageId}` },
|
|
102904
103346
|
sessionId,
|
|
102905
103347
|
turnId,
|
|
102906
103348
|
"completed",
|
|
@@ -102925,13 +103367,13 @@ function handleAssistantMessage(message, sessionId, turnId, entry, db2) {
|
|
|
102925
103367
|
if (!isToolCall) {
|
|
102926
103368
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
102927
103369
|
if (desc.type === "agent_message") {
|
|
102928
|
-
const
|
|
102929
|
-
db2.prepare("UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ?").run(
|
|
103370
|
+
const text2 = desc.data.text;
|
|
103371
|
+
db2.prepare("UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ?").run(text2, now, turnId);
|
|
102930
103372
|
}
|
|
102931
103373
|
if (desc.type === "reasoning") {
|
|
102932
|
-
const
|
|
102933
|
-
if (
|
|
102934
|
-
db2.prepare("UPDATE turns SET thoughts = ?, updated_at = ? WHERE id = ?").run(
|
|
103374
|
+
const text2 = desc.data.text;
|
|
103375
|
+
if (text2) {
|
|
103376
|
+
db2.prepare("UPDATE turns SET thoughts = ?, updated_at = ? WHERE id = ?").run(text2, now, turnId);
|
|
102935
103377
|
}
|
|
102936
103378
|
}
|
|
102937
103379
|
}
|
|
@@ -103217,18 +103659,18 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
|
|
|
103217
103659
|
const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
|
|
103218
103660
|
if (row?.status !== "pending" && row?.status !== "running") return;
|
|
103219
103661
|
if (row.status === "pending" && row.resume_state === "waiting") return;
|
|
103220
|
-
const
|
|
103662
|
+
const text2 = (message.result || apiError?.text || "Claude API error").trim();
|
|
103221
103663
|
const kind = classifyApiError({
|
|
103222
103664
|
error: apiError?.error,
|
|
103223
103665
|
status: message.api_error_status,
|
|
103224
|
-
text,
|
|
103666
|
+
text: text2,
|
|
103225
103667
|
limitRejected: entry.rateLimit?.status === "rejected"
|
|
103226
103668
|
});
|
|
103227
103669
|
const resumeAt = kind === "usage_limit" ? usageLimitResumeAt(entry.rateLimit?.resetsAt) : null;
|
|
103228
|
-
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail:
|
|
103670
|
+
if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
|
|
103229
103671
|
return;
|
|
103230
103672
|
}
|
|
103231
|
-
failTurn(db2, sessionId, turnId,
|
|
103673
|
+
failTurn(db2, sessionId, turnId, text2);
|
|
103232
103674
|
return;
|
|
103233
103675
|
}
|
|
103234
103676
|
await refreshContext(entry, sessionId, db2);
|
|
@@ -103685,7 +104127,7 @@ async function forkClaudeSession(session, targetTurn) {
|
|
|
103685
104127
|
}
|
|
103686
104128
|
}
|
|
103687
104129
|
var claudeProvider = {
|
|
103688
|
-
startTurn:
|
|
104130
|
+
startTurn: startTurn3,
|
|
103689
104131
|
interruptTurn: interruptTurn2,
|
|
103690
104132
|
clearThread: clearThread2,
|
|
103691
104133
|
clearThreadBranch,
|
|
@@ -103706,8 +104148,8 @@ var claudeProvider = {
|
|
|
103706
104148
|
function defaultRepoburgBaseUrl() {
|
|
103707
104149
|
return process.env.REPOBURG_BACKEND_URL || "http://localhost:3000";
|
|
103708
104150
|
}
|
|
103709
|
-
function isHtml(
|
|
103710
|
-
return /^\s*<(?:!doctype|html)/i.test(
|
|
104151
|
+
function isHtml(text2) {
|
|
104152
|
+
return /^\s*<(?:!doctype|html)/i.test(text2);
|
|
103711
104153
|
}
|
|
103712
104154
|
var RepoburgHttpClient = class {
|
|
103713
104155
|
/** Base URL of the repoburg backend (public — the projector opens the
|
|
@@ -103723,18 +104165,18 @@ var RepoburgHttpClient = class {
|
|
|
103723
104165
|
headers: { "Content-Type": "application/json" },
|
|
103724
104166
|
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
103725
104167
|
});
|
|
103726
|
-
const
|
|
104168
|
+
const text2 = await response.text();
|
|
103727
104169
|
if (!response.ok) {
|
|
103728
|
-
if (isHtml(
|
|
104170
|
+
if (isHtml(text2)) {
|
|
103729
104171
|
throw new Error(
|
|
103730
104172
|
`${method} ${path12} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
|
|
103731
104173
|
);
|
|
103732
104174
|
}
|
|
103733
|
-
throw new Error(`${method} ${path12} failed: ${response.status} ${
|
|
104175
|
+
throw new Error(`${method} ${path12} failed: ${response.status} ${text2}`);
|
|
103734
104176
|
}
|
|
103735
|
-
if (
|
|
104177
|
+
if (text2.length === 0) return void 0;
|
|
103736
104178
|
try {
|
|
103737
|
-
return JSON.parse(
|
|
104179
|
+
return JSON.parse(text2);
|
|
103738
104180
|
} catch {
|
|
103739
104181
|
throw new Error(
|
|
103740
104182
|
`${method} ${path12} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
|
|
@@ -103815,12 +104257,12 @@ async function fetchJson(url, init, timeoutMs = 5e3) {
|
|
|
103815
104257
|
} finally {
|
|
103816
104258
|
clearTimeout(timer2);
|
|
103817
104259
|
}
|
|
103818
|
-
const
|
|
104260
|
+
const text2 = await response.text();
|
|
103819
104261
|
if (!response.ok) {
|
|
103820
|
-
throw new HttpError(response.status,
|
|
104262
|
+
throw new HttpError(response.status, text2, url);
|
|
103821
104263
|
}
|
|
103822
104264
|
try {
|
|
103823
|
-
return JSON.parse(
|
|
104265
|
+
return JSON.parse(text2);
|
|
103824
104266
|
} catch {
|
|
103825
104267
|
throw new Error(`Unexpected non-JSON response from ${url}`);
|
|
103826
104268
|
}
|
|
@@ -104052,12 +104494,12 @@ function mapActionToItem(action) {
|
|
|
104052
104494
|
case "final":
|
|
104053
104495
|
case "html_final": {
|
|
104054
104496
|
const groups = parseSelectionGroups(action.selections);
|
|
104055
|
-
const
|
|
104497
|
+
const text2 = action.action_type === "final" ? action.plain ?? "" : "";
|
|
104056
104498
|
const html = action.action_type === "html_final" ? action.content ?? null : null;
|
|
104057
|
-
if (!
|
|
104499
|
+
if (!text2 && !html && groups.length === 0) return null;
|
|
104058
104500
|
return {
|
|
104059
104501
|
type: "final_result",
|
|
104060
|
-
data: { question: "", groups, text, html },
|
|
104502
|
+
data: { question: "", groups, text: text2, html },
|
|
104061
104503
|
status
|
|
104062
104504
|
};
|
|
104063
104505
|
}
|
|
@@ -104388,9 +104830,9 @@ var TurnProjector = class {
|
|
|
104388
104830
|
if (msg.usage && msg.usage.input_tokens > 0) {
|
|
104389
104831
|
this.lastContextTokens = msg.usage.input_tokens;
|
|
104390
104832
|
}
|
|
104391
|
-
const
|
|
104833
|
+
const text2 = msg.content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
104392
104834
|
const thinking = msg.content.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
|
|
104393
|
-
if (
|
|
104835
|
+
if (text2) info.text = text2;
|
|
104394
104836
|
if (thinking) info.thoughts = thinking;
|
|
104395
104837
|
this.upsertCompletedTextItem(info, "message", info.text);
|
|
104396
104838
|
this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
|
|
@@ -104398,8 +104840,8 @@ var TurnProjector = class {
|
|
|
104398
104840
|
}
|
|
104399
104841
|
/** Complete a round's text/thoughts item — creates it when deltas were
|
|
104400
104842
|
* off or missed, otherwise completes the streamed in_progress item. */
|
|
104401
|
-
upsertCompletedTextItem(info, kind,
|
|
104402
|
-
if (!
|
|
104843
|
+
upsertCompletedTextItem(info, kind, text2) {
|
|
104844
|
+
if (!text2) return;
|
|
104403
104845
|
const db2 = getDb();
|
|
104404
104846
|
const externalId = kind === "message" ? info.messageExternalId : info.reasoningExternalId;
|
|
104405
104847
|
const itemId = kind === "message" ? info.messageItemId : info.reasoningItemId;
|
|
@@ -104407,7 +104849,7 @@ var TurnProjector = class {
|
|
|
104407
104849
|
if (itemId) {
|
|
104408
104850
|
const itemRow = db2.prepare("SELECT * FROM items WHERE id = ?").get(itemId);
|
|
104409
104851
|
if (itemRow) {
|
|
104410
|
-
completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, itemRow, { text }, "completed");
|
|
104852
|
+
completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, itemRow, { text: text2 }, "completed");
|
|
104411
104853
|
return;
|
|
104412
104854
|
}
|
|
104413
104855
|
}
|
|
@@ -104419,7 +104861,7 @@ var TurnProjector = class {
|
|
|
104419
104861
|
this.deps.turnId,
|
|
104420
104862
|
externalId,
|
|
104421
104863
|
type,
|
|
104422
|
-
{ text },
|
|
104864
|
+
{ text: text2 },
|
|
104423
104865
|
"completed",
|
|
104424
104866
|
"item:completed"
|
|
104425
104867
|
);
|
|
@@ -105070,7 +105512,7 @@ ${conventions}` : `${conventions}
|
|
|
105070
105512
|
|
|
105071
105513
|
${prompt}`;
|
|
105072
105514
|
}
|
|
105073
|
-
async function
|
|
105515
|
+
async function startTurn4(session, turn) {
|
|
105074
105516
|
const db2 = getDb();
|
|
105075
105517
|
let client;
|
|
105076
105518
|
let baseUrl;
|
|
@@ -105294,7 +105736,7 @@ async function shutdown3() {
|
|
|
105294
105736
|
clearAllThreads3();
|
|
105295
105737
|
}
|
|
105296
105738
|
var repoburgProvider = {
|
|
105297
|
-
startTurn:
|
|
105739
|
+
startTurn: startTurn4,
|
|
105298
105740
|
interruptTurn: interruptTurn3,
|
|
105299
105741
|
clearThread: clearThread3,
|
|
105300
105742
|
clearThreadBranch: clearThreadBranch2,
|