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.
@@ -13456,13 +13456,13 @@ var require_context = __commonJS({
13456
13456
  this.server = server;
13457
13457
  }
13458
13458
  function defaultSchemaErrorFormatter(errors, dataVar) {
13459
- let text = "";
13459
+ let text2 = "";
13460
13460
  const separator = ", ";
13461
13461
  for (let i = 0; i !== errors.length; ++i) {
13462
13462
  const e = errors[i];
13463
- text += dataVar + (e.instancePath || "") + " " + e.message + separator;
13463
+ text2 += dataVar + (e.instancePath || "") + " " + e.message + separator;
13464
13464
  }
13465
- return new Error(text.slice(0, -separator.length));
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(text, reviver, options) {
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(text)) {
13486
- text = text.toString();
13485
+ if (hasBuffer && Buffer.isBuffer(text2)) {
13486
+ text2 = text2.toString();
13487
13487
  }
13488
- if (text && text.charCodeAt(0) === 65279) {
13489
- text = text.slice(1);
13488
+ if (text2 && text2.charCodeAt(0) === 65279) {
13489
+ text2 = text2.slice(1);
13490
13490
  }
13491
- const obj = JSON.parse(text, reviver);
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(text) === false && suspectConstructorRx.test(text) === false) {
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(text) === false) {
13505
+ if (suspectProtoRx.test(text2) === false) {
13506
13506
  return obj;
13507
13507
  }
13508
13508
  } else {
13509
- if (suspectConstructorRx.test(text) === false) {
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(text, reviver, options) {
13547
+ function parse(text2, reviver, options) {
13548
13548
  const { stackTraceLimit } = Error;
13549
13549
  Error.stackTraceLimit = 0;
13550
13550
  try {
13551
- return _parse(text, reviver, options);
13551
+ return _parse(text2, reviver, options);
13552
13552
  } finally {
13553
13553
  Error.stackTraceLimit = stackTraceLimit;
13554
13554
  }
13555
13555
  }
13556
- function safeParse(text, reviver) {
13556
+ function safeParse(text2, reviver) {
13557
13557
  const { stackTraceLimit } = Error;
13558
13558
  Error.stackTraceLimit = 0;
13559
13559
  try {
13560
- return _parse(text, reviver, { safe: true });
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((text, msg) => text + separator + msg);
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
  }
@@ -41291,7 +41294,15 @@ function initWs(allowRequest = isLocalRequest) {
41291
41294
  });
41292
41295
  return wss;
41293
41296
  }
41297
+ var taps = /* @__PURE__ */ new Set();
41298
+ function tapBroadcast(tap) {
41299
+ taps.add(tap);
41300
+ return () => {
41301
+ taps.delete(tap);
41302
+ };
41303
+ }
41294
41304
  function broadcast(event, data) {
41305
+ for (const tap of taps) tap(event, data);
41295
41306
  if (!wss) return;
41296
41307
  const message = JSON.stringify({ event, data });
41297
41308
  for (const client of wss.clients) {
@@ -41367,7 +41378,8 @@ function bundledCliDir() {
41367
41378
  function shellEnv() {
41368
41379
  const env = {};
41369
41380
  for (const [key, value] of Object.entries(process.env)) {
41370
- if (value !== void 0 && key !== "CLAUDECODE" && !key.startsWith("CLAUDE_CODE_RESUME_")) env[key] = value;
41381
+ if (value === void 0 || key === "CLAUDECODE" || key === "AGENT_PANE_SESSION_ID") continue;
41382
+ if (!key.startsWith("CLAUDE_CODE_RESUME_")) env[key] = value;
41371
41383
  }
41372
41384
  env.TERM = "xterm-256color";
41373
41385
  env.COLORTERM = "truecolor";
@@ -41671,6 +41683,59 @@ async function shutdownAllProviders() {
41671
41683
  }
41672
41684
  }
41673
41685
 
41686
+ // src/routes/session-guard.ts
41687
+ var LIVE_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') LIMIT 1`;
41688
+ var LIVE_MAIN_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') AND thread_id IS NULL LIMIT 1`;
41689
+ var LIVE_THREAD_TURN_SQL = `SELECT id FROM turns WHERE thread_id = ? AND status IN ('pending', 'running') LIMIT 1`;
41690
+ function isSessionBusy(db2, session, opts) {
41691
+ if (opts?.threadId) {
41692
+ return !!db2.prepare(LIVE_THREAD_TURN_SQL).get(opts.threadId);
41693
+ }
41694
+ if (opts?.mainOnly) {
41695
+ if (db2.prepare(LIVE_MAIN_TURN_SQL).get(session.id)) return true;
41696
+ if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return false;
41697
+ } else {
41698
+ if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return true;
41699
+ }
41700
+ if (!session.is_running) return false;
41701
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41702
+ db2.prepare("UPDATE sessions SET is_running = 0, status = ?, updated_at = ? WHERE id = ?").run(
41703
+ "active",
41704
+ now,
41705
+ session.id
41706
+ );
41707
+ return false;
41708
+ }
41709
+ function turnResponse(db2, turnId) {
41710
+ const row = db2.prepare("SELECT agent_response FROM turns WHERE id = ?").get(turnId);
41711
+ return row?.agent_response || null;
41712
+ }
41713
+ function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnreviewed = false) {
41714
+ const live = db2.prepare(
41715
+ `SELECT COUNT(*) AS c,
41716
+ COALESCE(SUM(CASE WHEN status = 'pending' AND resume_state = 'waiting' THEN 1 ELSE 0 END), 0) AS w
41717
+ FROM turns WHERE session_id = ? AND status IN ('pending', 'running')`
41718
+ ).get(sessionId);
41719
+ const isRunning = live.c > 0 ? 1 : 0;
41720
+ const liveStatus = live.c > 0 && live.w === live.c ? "interrupted" : "running";
41721
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41722
+ if (hasUnreviewed && isRunning === 0) {
41723
+ db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
41724
+ isRunning,
41725
+ idleStatus,
41726
+ now,
41727
+ sessionId
41728
+ );
41729
+ } else {
41730
+ db2.prepare("UPDATE sessions SET is_running = ?, status = ?, updated_at = ? WHERE id = ?").run(
41731
+ isRunning,
41732
+ isRunning ? liveStatus : idleStatus,
41733
+ now,
41734
+ sessionId
41735
+ );
41736
+ }
41737
+ }
41738
+
41674
41739
  // src/routes/session-touch.ts
41675
41740
  function markSessionTouched(db2, sessionId) {
41676
41741
  const { changes } = db2.prepare("UPDATE sessions SET user_touched = 1 WHERE id = ? AND user_touched = 0").run(sessionId);
@@ -41679,6 +41744,70 @@ function markSessionTouched(db2, sessionId) {
41679
41744
  return true;
41680
41745
  }
41681
41746
 
41747
+ // src/routes/session-actions.ts
41748
+ function createSession(db2, input) {
41749
+ const {
41750
+ title = null,
41751
+ runtime_type = "codex",
41752
+ model = null,
41753
+ model_reasoning_effort = null,
41754
+ cwd = null,
41755
+ runtime_config = null,
41756
+ origin_app_id = null,
41757
+ origin_app_workspace = null
41758
+ } = input;
41759
+ const id = v4_default();
41760
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41761
+ const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
41762
+ db2.prepare(
41763
+ `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)
41764
+ VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, ?, ?, ?, ?, ?, ?)`
41765
+ ).run(
41766
+ id,
41767
+ title,
41768
+ runtime_type,
41769
+ model,
41770
+ model_reasoning_effort,
41771
+ cwd,
41772
+ maxOrder.m + 1,
41773
+ now,
41774
+ now,
41775
+ runtime_config,
41776
+ origin_app_id,
41777
+ origin_app_workspace
41778
+ );
41779
+ return db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
41780
+ }
41781
+ var SessionBusyError = class extends Error {
41782
+ constructor() {
41783
+ super("A turn is already running for this session");
41784
+ this.name = "SessionBusyError";
41785
+ }
41786
+ };
41787
+ function startTurn(db2, session, { prompt, attachments, originAppId }) {
41788
+ if (isSessionBusy(db2, session, { mainOnly: true })) throw new SessionBusyError();
41789
+ const provider = getProvider(session.runtime_type);
41790
+ const turnId = v4_default();
41791
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41792
+ const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
41793
+ db2.prepare(
41794
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
41795
+ VALUES (?, ?, ?, NULL, NULL, NULL, NULL, 'pending', NULL, ?, ?, ?)`
41796
+ ).run(turnId, session.id, prompt, attachmentsJson, now, now);
41797
+ const turn = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
41798
+ if (!originAppId) markSessionTouched(db2, session.id);
41799
+ const rawTurn = turn;
41800
+ const parsedTurn = {
41801
+ ...turn,
41802
+ attachments: rawTurn.attachments ? JSON.parse(rawTurn.attachments) : null
41803
+ };
41804
+ broadcast("turn:created", { sessionId: session.id, turn: parsedTurn });
41805
+ provider.startTurn(session, rawTurn).catch((err) => {
41806
+ console.error(`[provider] Unhandled error for session ${session.id}:`, err);
41807
+ });
41808
+ return parsedTurn;
41809
+ }
41810
+
41682
41811
  // src/routes/sessions.ts
41683
41812
  async function registerSessionRoutes(fastify) {
41684
41813
  fastify.get("/api/sessions", async () => {
@@ -41753,31 +41882,12 @@ async function registerSessionRoutes(fastify) {
41753
41882
  model_reasoning_effort: { type: ["string", "null"] },
41754
41883
  cwd: { type: ["string", "null"] },
41755
41884
  runtime_config: { type: ["string", "null"] },
41756
- origin_app_id: { type: ["string", "null"] }
41885
+ origin_app_id: { type: ["string", "null"] },
41886
+ origin_app_workspace: { type: ["string", "null"] }
41757
41887
  }
41758
41888
  }
41759
41889
  }
41760
- }, async (request) => {
41761
- const {
41762
- title = null,
41763
- runtime_type = "codex",
41764
- model = null,
41765
- model_reasoning_effort = null,
41766
- cwd = null,
41767
- runtime_config = null,
41768
- origin_app_id = null
41769
- } = request.body || {};
41770
- const id = v4_default();
41771
- const now = (/* @__PURE__ */ new Date()).toISOString();
41772
- const db2 = getDb();
41773
- const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
41774
- db2.prepare(
41775
- `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)
41776
- VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, ?, ?, ?, ?, ?)`
41777
- ).run(id, title, runtime_type, model, model_reasoning_effort, cwd, maxOrder.m + 1, now, now, runtime_config, origin_app_id);
41778
- const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
41779
- return session;
41780
- });
41890
+ }, async (request) => createSession(getDb(), request.body || {}));
41781
41891
  fastify.delete("/api/sessions/:id", async (request, reply) => {
41782
41892
  const { id } = request.params;
41783
41893
  const db2 = getDb();
@@ -42102,59 +42212,6 @@ async function registerSessionRoutes(fastify) {
42102
42212
  );
42103
42213
  }
42104
42214
 
42105
- // src/routes/session-guard.ts
42106
- var LIVE_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') LIMIT 1`;
42107
- var LIVE_MAIN_TURN_SQL = `SELECT id FROM turns WHERE session_id = ? AND status IN ('pending', 'running') AND thread_id IS NULL LIMIT 1`;
42108
- var LIVE_THREAD_TURN_SQL = `SELECT id FROM turns WHERE thread_id = ? AND status IN ('pending', 'running') LIMIT 1`;
42109
- function isSessionBusy(db2, session, opts) {
42110
- if (opts?.threadId) {
42111
- return !!db2.prepare(LIVE_THREAD_TURN_SQL).get(opts.threadId);
42112
- }
42113
- if (opts?.mainOnly) {
42114
- if (db2.prepare(LIVE_MAIN_TURN_SQL).get(session.id)) return true;
42115
- if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return false;
42116
- } else {
42117
- if (db2.prepare(LIVE_TURN_SQL).get(session.id)) return true;
42118
- }
42119
- if (!session.is_running) return false;
42120
- const now = (/* @__PURE__ */ new Date()).toISOString();
42121
- db2.prepare("UPDATE sessions SET is_running = 0, status = ?, updated_at = ? WHERE id = ?").run(
42122
- "active",
42123
- now,
42124
- session.id
42125
- );
42126
- return false;
42127
- }
42128
- function turnResponse(db2, turnId) {
42129
- const row = db2.prepare("SELECT agent_response FROM turns WHERE id = ?").get(turnId);
42130
- return row?.agent_response || null;
42131
- }
42132
- function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnreviewed = false) {
42133
- const live = db2.prepare(
42134
- `SELECT COUNT(*) AS c,
42135
- COALESCE(SUM(CASE WHEN status = 'pending' AND resume_state = 'waiting' THEN 1 ELSE 0 END), 0) AS w
42136
- FROM turns WHERE session_id = ? AND status IN ('pending', 'running')`
42137
- ).get(sessionId);
42138
- const isRunning = live.c > 0 ? 1 : 0;
42139
- const liveStatus = live.c > 0 && live.w === live.c ? "interrupted" : "running";
42140
- const now = (/* @__PURE__ */ new Date()).toISOString();
42141
- if (hasUnreviewed && isRunning === 0) {
42142
- db2.prepare("UPDATE sessions SET is_running = ?, status = ?, has_unreviewed = 1, updated_at = ? WHERE id = ?").run(
42143
- isRunning,
42144
- idleStatus,
42145
- now,
42146
- sessionId
42147
- );
42148
- } else {
42149
- db2.prepare("UPDATE sessions SET is_running = ?, status = ?, updated_at = ? WHERE id = ?").run(
42150
- isRunning,
42151
- isRunning ? liveStatus : idleStatus,
42152
- now,
42153
- sessionId
42154
- );
42155
- }
42156
- }
42157
-
42158
42215
  // src/resume/interruptions.ts
42159
42216
  var HOST_RESTART_ERROR = "Backend restarted while turn was running";
42160
42217
  var listeners = /* @__PURE__ */ new Set();
@@ -42645,28 +42702,12 @@ async function registerTurnRoutes(fastify) {
42645
42702
  if (!session) {
42646
42703
  return reply.code(404).send({ error: "Session not found" });
42647
42704
  }
42648
- if (isSessionBusy(db2, session, { mainOnly: true })) {
42649
- return reply.code(409).send({ error: "A turn is already running for this session" });
42705
+ try {
42706
+ return startTurn(db2, session, { prompt: user_prompt, attachments, originAppId: origin_app_id });
42707
+ } catch (err) {
42708
+ if (err instanceof SessionBusyError) return reply.code(409).send({ error: err.message });
42709
+ throw err;
42650
42710
  }
42651
- const turnId = v4_default();
42652
- const now = (/* @__PURE__ */ new Date()).toISOString();
42653
- const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
42654
- db2.prepare(
42655
- `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
42656
- VALUES (?, ?, ?, NULL, NULL, NULL, NULL, 'pending', NULL, ?, ?, ?)`
42657
- ).run(turnId, id, user_prompt, attachmentsJson, now, now);
42658
- const turn = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
42659
- if (!origin_app_id) markSessionTouched(db2, id);
42660
- const rawTurn = turn;
42661
- const parsedTurn = {
42662
- ...turn,
42663
- attachments: rawTurn.attachments ? JSON.parse(rawTurn.attachments) : null
42664
- };
42665
- broadcast("turn:created", { sessionId: id, turn: parsedTurn });
42666
- getProvider(session.runtime_type).startTurn(session, rawTurn).catch((err) => {
42667
- console.error(`[provider] Unhandled error for session ${id}:`, err);
42668
- });
42669
- return parsedTurn;
42670
42711
  }
42671
42712
  );
42672
42713
  fastify.get(
@@ -43510,8 +43551,8 @@ var AppServerClient = class {
43510
43551
  this.proc.stdout?.setEncoding("utf-8");
43511
43552
  this.proc.stdout?.on("data", this.stdoutListener);
43512
43553
  this.proc.stderr?.on("data", (chunk) => {
43513
- const text = chunk.toString().trim();
43514
- if (text) console.error("[app-server] stderr:", text);
43554
+ const text2 = chunk.toString().trim();
43555
+ if (text2) console.error("[app-server] stderr:", text2);
43515
43556
  });
43516
43557
  this.proc.on("exit", (code, signal) => {
43517
43558
  this.onProcessExit(code, signal);
@@ -98790,7 +98831,8 @@ Each subdirectory of this folder is one mini app:
98790
98831
 
98791
98832
  <app-id>/
98792
98833
  manifest.json - { "title": string, "description"?: string, "icon"?: string,
98793
- "tools"?: [{ "name", "description", "inputSchema" }] }
98834
+ "tools"?: [{ "name", "description", "inputSchema" }],
98835
+ "headlessSessions"?: boolean }
98794
98836
  "icon" is the app logo: a Lucide icon name (see
98795
98837
  "Icons and logos" below)
98796
98838
  index.html - markup only (full HTML document); do NOT reference app.js
@@ -98846,14 +98888,21 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
98846
98888
 
98847
98889
  ## Bridge API (window.AgentPane)
98848
98890
 
98849
- - getApp() - app info (id, title)
98891
+ - getApp() - app info (id, title, workspace = the folder of this instance, '' = global)
98850
98892
  - getState() / setState(data, { ifVersion }?) - persistent JSON state, survives page reload; getState reads the stored copy on every call (see "Shared state" below)
98851
98893
  - onStateChanged(callback) - callback({ version }) when somebody else (an agent, another tab) wrote the state; not fired for this tab's own setState
98852
98894
  - 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
98853
98895
  - 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)
98854
- - onTurnCompleted(callback) - callback(event, { turnId, response }) when a turn ends
98896
+ - 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'
98897
+ - 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
98898
+ - setSessionLifecycle(sessionId, 'finished' | 'working') - finish or reopen one of this app's sessions, as the sidebar does; rejects for any other session
98899
+ - 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
98900
+ - listProviders() - tab only: the runtimes this pane offers, as /api/providers lists them (id, label, capability flags)
98901
+ - listModels(runtime, cwd?) - tab only: a runtime's models, as /api/providers/:id/models lists them; cwd for runtimes that list per workspace
98902
+ - 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
98903
+ - onTurnCompleted(callback) - callback(event, { sessionId, turnId, response }) when a turn ends; event is 'turn:completed' or 'turn:failed' ({ sessionId, turnId, error })
98855
98904
  - 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
98856
- - 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)
98905
+ - 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
98857
98906
  - 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
98858
98907
  - 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)
98859
98908
  - uploadFile(blob | { name, type, data }) - store an image for this app (data = base64 or a base64 data: URL); returns { id, url, path, type, size }
@@ -98911,8 +98960,8 @@ viewer; it refreshes via AgentPane.onStateChanged(cb).
98911
98960
 
98912
98961
  Headless contract for apps that declare tools:
98913
98962
  - register AgentPane.onToolCall(handler) synchronously at startup
98914
- - the handler gets one payload, handler({ callId, name, tool, args }), the
98915
- same as in the tab; a handler declaring two parameters still gets the
98963
+ - the handler gets one payload, handler({ callId, name, tool, args, caller }),
98964
+ the same as in the tab; a handler declaring two parameters still gets the
98916
98965
  older headless form ('tool_call', payload)
98917
98966
  - tool handlers must not depend on the DOM or the live UI
98918
98967
  - headless state is the instance of the CALLING session's workspace; open
@@ -98920,8 +98969,8 @@ Headless contract for apps that declare tools:
98920
98969
  above it; one in an app folder, or with no workspace, uses the global
98921
98970
  instance. A path the pane does not know (unregistered, deleted) fails the
98922
98971
  call with "Unknown workspace", and no state is read or written
98923
- - createSession/submitTurn/openSession/openUrl are not available in the
98924
- headless runtime
98972
+ - openSession/openUrl are not available in the headless runtime;
98973
+ createSession/submitTurn only with "headlessSessions" (see below)
98925
98974
  - stored files are: getFile(ref)/fileUrl(ref)/uploadFile({ name, type, data })
98926
98975
  work headless (url is root-relative there); return file.path to the agent
98927
98976
  so it can open the image
@@ -98931,6 +98980,46 @@ falls back to relaying calls into the OPEN app iframe \u2014 the app must be
98931
98980
  open in AgentPane, on the calling session's workspace, for a tool call to
98932
98981
  succeed in that case.
98933
98982
 
98983
+ ## Who called
98984
+
98985
+ payload.caller names the session behind a tool call:
98986
+ { sessionId, runtime, workspace, appOwned }. appOwned is true for a session
98987
+ this app opened with createSession, false for any other, Edit App sessions
98988
+ included. caller is null for a call from outside the pane's sessions (a
98989
+ script over REST, a session of a Repoburg backend).
98990
+
98991
+ Use it to keep management tools away from the app's own workers:
98992
+ if (payload.caller?.appOwned) refuse. This stops a worker that strays from its
98993
+ prompt, not one working around it: nothing proves the id, so anything that can
98994
+ reach the pane's API can name another session or none.
98995
+
98996
+ A worker reporting over REST is not an MCP call and has no caller unless it
98997
+ says so. Claude sessions have their id in the environment, so have the prompt
98998
+ add "caller": { "sessionId": "$AGENT_PANE_SESSION_ID" } to the
98999
+ POST /api/apps/mcp/call body.
99000
+
99001
+ ## Agent sessions without a tab
99002
+
99003
+ Set "headlessSessions": true in manifest.json to run an app's agent work with
99004
+ no tab open. Without it, createSession/submitTurn reject in the headless
99005
+ runtime and events go to the open tab only.
99006
+
99007
+ - createSession, submitTurn, cancelTurn and setSessionLifecycle work headless,
99008
+ from a tool handler or an event callback. All but createSession reach only
99009
+ sessions this app opened; attachments are stored files or inline
99010
+ { name, type, data } (no Blobs in the sandbox)
99011
+ - onTurnCompleted and onBackgroundTasks fire in the headless runtime, for every
99012
+ session of the app, also the ones its tab opened. They go to the instance
99013
+ that opened the session, and it loads again when it has to
99014
+ - a turn stopped by the user arrives as 'turn:failed' with cancelled: true
99015
+ - these events no longer reach the tab, so each is handled once. Put what the
99016
+ tab shows in the state; the tab follows with onStateChanged
99017
+ - onTurnDelta stays tab-only
99018
+ - app.js runs again on every load of the runtime (pane restart, hot reload):
99019
+ start sessions from a tool call or an event, never at startup
99020
+ - events are not replayed. Keep the session ids in the state, and when the
99021
+ runtime loads ask getSession(id) what happened while the pane was down
99022
+
98934
99023
  ## Result contract
98935
99024
 
98936
99025
  To give the app a structured result, put this requirement in the job prompt:
@@ -98950,7 +99039,8 @@ function readManifestIn(dir) {
98950
99039
  title: parsed.title,
98951
99040
  description: typeof parsed.description === "string" ? parsed.description : void 0,
98952
99041
  icon: typeof parsed.icon === "string" ? parsed.icon : void 0,
98953
- tools: Array.isArray(parsed.tools) ? parsed.tools.filter((t) => t && typeof t.name === "string" && typeof t.description === "string") : void 0
99042
+ tools: Array.isArray(parsed.tools) ? parsed.tools.filter((t) => t && typeof t.name === "string" && typeof t.description === "string") : void 0,
99043
+ headlessSessions: parsed.headlessSessions === true ? true : void 0
98954
99044
  };
98955
99045
  } catch {
98956
99046
  return null;
@@ -99097,6 +99187,17 @@ function updateInstanceState(appId, workspace, patch) {
99097
99187
  return next;
99098
99188
  }).immediate();
99099
99189
  }
99190
+ function resolveToolWorkspace(workspace) {
99191
+ if (!workspace) return "";
99192
+ const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99193
+ const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99194
+ if (active.includes(workspace)) return workspace;
99195
+ const cwd = path5.isAbsolute(workspace) ? path5.resolve(workspace) : "";
99196
+ if (isInAppFolder(cwd)) return "";
99197
+ const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path5.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99198
+ if (covering && !covering.deleted) return covering.path;
99199
+ throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99200
+ }
99100
99201
  function deleteAppInstances(appId) {
99101
99202
  getDb().prepare("DELETE FROM app_instances WHERE app_id = ?").run(appId);
99102
99203
  }
@@ -99104,21 +99205,305 @@ function deleteAppInstances(appId) {
99104
99205
  // src/apps/mcp-tools.ts
99105
99206
  import fs5 from "node:fs";
99106
99207
 
99208
+ // src/apps/app-files.ts
99209
+ import crypto2 from "node:crypto";
99210
+ import fs4 from "node:fs";
99211
+ import os4 from "node:os";
99212
+ import path6 from "node:path";
99213
+ var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99214
+ var APP_FILE_TYPES = {
99215
+ "image/png": "png",
99216
+ "image/jpeg": "jpg",
99217
+ "image/gif": "gif",
99218
+ "image/webp": "webp"
99219
+ };
99220
+ var EXT_TYPES = Object.fromEntries(
99221
+ Object.entries(APP_FILE_TYPES).map(([type, ext]) => [ext, type])
99222
+ );
99223
+ var APP_FILE_ID_RE = /^[a-f0-9]{64}\.(?:png|jpg|gif|webp)$/;
99224
+ var FILE_URL_RE = /^(?:https?:\/\/[^/?#]+)?\/api\/apps\/([^/?#]+)\/files\/([^/?#]+)$/i;
99225
+ var AppFileError = class extends Error {
99226
+ constructor(message, status) {
99227
+ super(message);
99228
+ this.status = status;
99229
+ this.name = "AppFileError";
99230
+ }
99231
+ };
99232
+ var rootOverride2 = null;
99233
+ function setAppFilesRootOverride(root) {
99234
+ rootOverride2 = root;
99235
+ }
99236
+ function appFilesRoot() {
99237
+ return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99238
+ }
99239
+ function appFilesDir(appId) {
99240
+ if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99241
+ return path6.join(appFilesRoot(), appId);
99242
+ }
99243
+ function appFileUrl(appId, fileId) {
99244
+ return `/api/apps/${appId}/files/${fileId}`;
99245
+ }
99246
+ function fileType(fileId) {
99247
+ return EXT_TYPES[fileId.slice(fileId.lastIndexOf(".") + 1)] ?? "application/octet-stream";
99248
+ }
99249
+ function sniffImageType(bytes) {
99250
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
99251
+ return "image/png";
99252
+ }
99253
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
99254
+ if (bytes.length >= 6 && /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString("latin1"))) return "image/gif";
99255
+ if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP") {
99256
+ return "image/webp";
99257
+ }
99258
+ return null;
99259
+ }
99260
+ function decodeBase64(data) {
99261
+ let b64 = data;
99262
+ let dataUrlType = null;
99263
+ const dataUrl = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
99264
+ if (dataUrl) {
99265
+ dataUrlType = dataUrl[1].toLowerCase() || null;
99266
+ b64 = data.slice(dataUrl[0].length);
99267
+ } else if (/^data:/i.test(data)) {
99268
+ return null;
99269
+ }
99270
+ b64 = b64.replace(/\s+/g, "");
99271
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 === 1) return null;
99272
+ return { bytes: Buffer.from(b64, "base64"), dataUrlType };
99273
+ }
99274
+ function normalizeType(type) {
99275
+ if (typeof type !== "string") return null;
99276
+ const t = type.split(";")[0].trim().toLowerCase();
99277
+ return t || null;
99278
+ }
99279
+ var ACCEPTED = "PNG, JPEG, GIF or WebP";
99280
+ function saveAppFile(appId, upload) {
99281
+ const dir = appFilesDir(appId);
99282
+ if (typeof upload.data !== "string" || !upload.data) {
99283
+ throw new AppFileError("data is required (base64 or a base64 data: URL)", 400);
99284
+ }
99285
+ const decoded = decodeBase64(upload.data);
99286
+ if (!decoded) throw new AppFileError("data is not valid base64", 400);
99287
+ const declared = normalizeType(upload.type) ?? decoded.dataUrlType;
99288
+ if (declared && !APP_FILE_TYPES[declared]) {
99289
+ throw new AppFileError(`Unsupported file type '${declared}' \u2014 upload a ${ACCEPTED} image`, 400);
99290
+ }
99291
+ const { bytes } = decoded;
99292
+ if (bytes.length === 0) throw new AppFileError("The file is empty", 400);
99293
+ if (bytes.length > APP_FILE_MAX_BYTES) {
99294
+ throw new AppFileError(
99295
+ `The file is ${bytes.length} bytes \u2014 the limit is ${APP_FILE_MAX_BYTES} bytes (${APP_FILE_MAX_BYTES / (1024 * 1024)} MB)`,
99296
+ 413
99297
+ );
99298
+ }
99299
+ const type = sniffImageType(bytes);
99300
+ if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99301
+ const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99302
+ const file = path6.join(dir, fileId);
99303
+ if (!fs4.existsSync(file)) {
99304
+ fs4.mkdirSync(dir, { recursive: true });
99305
+ const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
99306
+ fs4.writeFileSync(tmp, bytes);
99307
+ fs4.renameSync(tmp, file);
99308
+ }
99309
+ return { id: fileId, url: appFileUrl(appId, fileId), path: file, type, size: bytes.length };
99310
+ }
99311
+ function appFileRefId(appId, ref) {
99312
+ let value = ref;
99313
+ if (value && typeof value === "object") {
99314
+ const obj = value;
99315
+ value = typeof obj.id === "string" ? obj.id : obj.url;
99316
+ }
99317
+ if (typeof value !== "string") return null;
99318
+ const s = value.trim();
99319
+ if (APP_FILE_ID_RE.test(s)) return s;
99320
+ const m = FILE_URL_RE.exec(s);
99321
+ if (!m) return null;
99322
+ let owner;
99323
+ try {
99324
+ owner = decodeURIComponent(m[1]);
99325
+ } catch {
99326
+ return null;
99327
+ }
99328
+ return owner === appId && APP_FILE_ID_RE.test(m[2]) ? m[2] : null;
99329
+ }
99330
+ function getAppFile(appId, ref) {
99331
+ if (!APP_ID_RE.test(appId)) return null;
99332
+ const fileId = appFileRefId(appId, ref);
99333
+ if (!fileId) return null;
99334
+ const file = path6.join(appFilesDir(appId), fileId);
99335
+ try {
99336
+ const stat2 = fs4.statSync(file);
99337
+ if (!stat2.isFile()) return null;
99338
+ return { id: fileId, url: appFileUrl(appId, fileId), path: file, type: fileType(fileId), size: stat2.size };
99339
+ } catch {
99340
+ return null;
99341
+ }
99342
+ }
99343
+ function readAppFileData(appId, fileId) {
99344
+ if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99345
+ try {
99346
+ return { bytes: fs4.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99347
+ } catch {
99348
+ return null;
99349
+ }
99350
+ }
99351
+ function deleteAppFiles(appId) {
99352
+ if (!APP_ID_RE.test(appId)) return;
99353
+ fs4.rmSync(appFilesDir(appId), { recursive: true, force: true });
99354
+ }
99355
+
99356
+ // src/apps/app-sessions.ts
99357
+ function text(value) {
99358
+ return typeof value === "string" ? value : void 0;
99359
+ }
99360
+ var AppSessionError = class extends Error {
99361
+ };
99362
+ function openedByApp(session, appId) {
99363
+ if (session.origin_app_id !== appId) return false;
99364
+ return session.origin_app_workspace !== null || !isInAppFolder(session.cwd);
99365
+ }
99366
+ function sessionOwner(sessionId) {
99367
+ const session = getDb().prepare("SELECT origin_app_id, origin_app_workspace, cwd FROM sessions WHERE id = ?").get(sessionId);
99368
+ const appId = session?.origin_app_id;
99369
+ if (!session || !appId || !openedByApp(session, appId)) return null;
99370
+ return { appId, workspace: session.origin_app_workspace ?? cwdInstance(session.cwd) };
99371
+ }
99372
+ function cwdInstance(cwd) {
99373
+ try {
99374
+ return resolveToolWorkspace(cwd);
99375
+ } catch {
99376
+ return "";
99377
+ }
99378
+ }
99379
+ function isMainTurn(turnId) {
99380
+ const turn = getDb().prepare("SELECT thread_id FROM turns WHERE id = ?").get(turnId);
99381
+ return !!turn && !turn.thread_id;
99382
+ }
99383
+ function createAppSession(appId, workspace, opts) {
99384
+ const o = opts && typeof opts === "object" ? opts : {};
99385
+ const runtime = text(o.runtime_type);
99386
+ if (runtime && !hasProvider(runtime)) throw new Error(`createSession: unknown runtime ${runtime}`);
99387
+ const session = createSession(getDb(), {
99388
+ title: text(o.title),
99389
+ runtime_type: runtime,
99390
+ model: text(o.model),
99391
+ model_reasoning_effort: text(o.model_reasoning_effort),
99392
+ cwd: text(o.cwd),
99393
+ origin_app_id: appId,
99394
+ origin_app_workspace: workspace
99395
+ });
99396
+ broadcast("session:created", { session });
99397
+ return session;
99398
+ }
99399
+ function splitDataUrl(data, type) {
99400
+ const m = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
99401
+ if (!m) return { type, data };
99402
+ return { type: type || m[1] || void 0, data: data.slice(m[0].length) };
99403
+ }
99404
+ function turnAttachments(appId, list) {
99405
+ if (list == null) return [];
99406
+ if (!Array.isArray(list)) throw new Error("submitTurn: attachments must be an array");
99407
+ return list.map((item, i) => {
99408
+ const inline = item && typeof item === "object" ? item : null;
99409
+ if (typeof inline?.data === "string") {
99410
+ const { type, data } = splitDataUrl(inline.data, text(inline.type) || void 0);
99411
+ if (!type) throw new Error(`submitTurn: attachment ${i + 1} has no type`);
99412
+ return { name: text(inline.name) || `attachment-${i + 1}`, media_type: type, data };
99413
+ }
99414
+ const fileId = appFileRefId(appId, item);
99415
+ const file = fileId ? readAppFileData(appId, fileId) : null;
99416
+ if (!fileId || !file) throw new Error(`submitTurn: attachment ${i + 1} is not a file of this app`);
99417
+ return { name: fileId, media_type: file.type, data: file.bytes.toString("base64") };
99418
+ });
99419
+ }
99420
+ function submitAppTurn(appId, sessionId, prompt, opts) {
99421
+ const db2 = getDb();
99422
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
99423
+ if (!session || !openedByApp(session, appId)) {
99424
+ throw new Error(`submitTurn: ${String(sessionId)} is not a session of this app`);
99425
+ }
99426
+ if (typeof prompt !== "string" || !prompt.trim()) throw new Error("submitTurn: prompt is required");
99427
+ const attachments = turnAttachments(appId, opts?.attachments);
99428
+ return startTurn(db2, session, { prompt, attachments, originAppId: appId });
99429
+ }
99430
+ function appSessionInfo(appId, sessionId) {
99431
+ const db2 = getDb();
99432
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
99433
+ if (!session || !openedByApp(session, appId)) return null;
99434
+ const turn = db2.prepare(
99435
+ `SELECT id, status, agent_response, error, resume_state FROM turns
99436
+ WHERE session_id = ? AND thread_id IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1`
99437
+ ).get(session.id);
99438
+ return {
99439
+ id: session.id,
99440
+ title: session.title,
99441
+ status: session.status,
99442
+ running: !!session.is_running,
99443
+ backgroundTasks: listAllBackgroundTasks()[session.id] ?? [],
99444
+ lastTurn: turn ? {
99445
+ id: turn.id,
99446
+ status: turn.status,
99447
+ response: turn.agent_response || null,
99448
+ error: turn.error,
99449
+ resumeState: turn.resume_state
99450
+ } : null
99451
+ };
99452
+ }
99453
+ function ownSession(appId, sessionId, api) {
99454
+ const session = getDb().prepare("SELECT * FROM sessions WHERE id = ?").get(String(sessionId));
99455
+ if (!session || !openedByApp(session, appId)) {
99456
+ throw new AppSessionError(`${api}: ${String(sessionId)} is not a session of this app`);
99457
+ }
99458
+ return session;
99459
+ }
99460
+ async function cancelAppTurn(appId, sessionId) {
99461
+ const session = ownSession(appId, sessionId, "cancelTurn");
99462
+ 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);
99463
+ if (!live) return { cancelled: false };
99464
+ return { cancelled: await getProvider(session.runtime_type).interruptTurn(session.id) };
99465
+ }
99466
+ function setAppSessionLifecycle(appId, sessionId, lifecycle) {
99467
+ const session = ownSession(appId, sessionId, "setSessionLifecycle");
99468
+ if (lifecycle !== "working" && lifecycle !== "finished") {
99469
+ throw new Error(`setSessionLifecycle: lifecycle must be 'working' or 'finished'`);
99470
+ }
99471
+ const db2 = getDb();
99472
+ db2.prepare("UPDATE sessions SET lifecycle = ?, updated_at = ? WHERE id = ?").run(
99473
+ lifecycle,
99474
+ (/* @__PURE__ */ new Date()).toISOString(),
99475
+ session.id
99476
+ );
99477
+ broadcast("session:updated", { session: db2.prepare("SELECT * FROM sessions WHERE id = ?").get(session.id) });
99478
+ return { lifecycle };
99479
+ }
99480
+ function toolCaller(appId, sessionId) {
99481
+ if (!sessionId) return null;
99482
+ const session = getDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
99483
+ if (!session) return null;
99484
+ return {
99485
+ sessionId: session.id,
99486
+ runtime: session.runtime_type,
99487
+ workspace: session.cwd ?? "",
99488
+ appOwned: openedByApp(session, appId)
99489
+ };
99490
+ }
99491
+
99107
99492
  // src/apps/headless-runtime.ts
99108
99493
  import vm2 from "node:vm";
99109
99494
 
99110
99495
  // src/apps/app-compile.ts
99111
99496
  import vm from "node:vm";
99112
- import path6 from "node:path";
99497
+ import path7 from "node:path";
99113
99498
  import ts from "typescript";
99114
99499
 
99115
99500
  // src/apps/app-lint.ts
99116
99501
  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;
99117
99502
  var MAX_EMOJI_WARNINGS = 30;
99118
99503
  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).';
99119
- function findEmoji(text) {
99504
+ function findEmoji(text2) {
99120
99505
  const found = [];
99121
- const lines = text.split("\n");
99506
+ const lines = text2.split("\n");
99122
99507
  for (let i = 0; i < lines.length; i++) {
99123
99508
  for (const m of lines[i].matchAll(EMOJI_RE)) {
99124
99509
  found.push({ emoji: m[0], line: i + 1, column: (m.index ?? 0) + 1 });
@@ -99175,7 +99560,12 @@ function lintAppSources(files, manifestIcon) {
99175
99560
  var APP_TS = "app.ts";
99176
99561
  var BRIDGE_DTS_FILE = "agentpane.d.ts";
99177
99562
  var BRIDGE_DTS = `/** AgentPane bridge \u2014 typed contract for mini apps (ambient, no import). */
99178
- interface AgentPaneAppInfo { id: string; title?: string }
99563
+ interface AgentPaneAppInfo {
99564
+ id: string;
99565
+ title?: string;
99566
+ /** Folder of this instance ('' = global). Absent on older panes. */
99567
+ workspace?: string;
99568
+ }
99179
99569
  interface AgentPaneState {
99180
99570
  pinned: boolean;
99181
99571
  data: Record<string, unknown> | null;
@@ -99208,13 +99598,53 @@ interface AgentPaneCreateSessionOptions {
99208
99598
  model_reasoning_effort?: string;
99209
99599
  cwd?: string;
99210
99600
  }
99211
- interface AgentPaneTurnPayload { turnId?: string; response?: string | null; error?: string }
99601
+ interface AgentPaneTurnPayload {
99602
+ sessionId?: string;
99603
+ turnId?: string;
99604
+ response?: string | null;
99605
+ error?: string;
99606
+ /** Headless: the user stopped the turn (event 'turn:failed'). */
99607
+ cancelled?: boolean;
99608
+ }
99212
99609
  interface AgentPaneDeltaPayload { sessionId?: string; turnId?: string; itemId?: string; delta?: string }
99213
- interface AgentPaneToolCallPayload { callId: string; tool: string; name: string; args: Record<string, unknown> }
99610
+ /** The session behind a tool call. A plain claim, nothing proves it: enough to
99611
+ * keep the app's workers to their prompt, not to stop one working around it. */
99612
+ interface AgentPaneToolCaller {
99613
+ sessionId: string;
99614
+ runtime: string;
99615
+ workspace: string;
99616
+ /** This app opened that session with createSession. */
99617
+ appOwned: boolean;
99618
+ }
99619
+ interface AgentPaneToolCallPayload {
99620
+ callId: string;
99621
+ tool: string;
99622
+ name: string;
99623
+ args: Record<string, unknown>;
99624
+ /** null: the call came from outside the pane's sessions. */
99625
+ caller: AgentPaneToolCaller | null;
99626
+ }
99214
99627
  /** Live background tasks of a session (Monitor shells, backgrounded subagents):
99215
99628
  * the CURRENT set, REPLACE semantics \u2014 an empty array means none are left. */
99216
99629
  interface AgentPaneBackgroundTasksPayload { sessionId?: string; tasks?: AgentPaneBackgroundTask[] }
99217
99630
  interface AgentPaneBackgroundTask { task_id: string; task_type: string; description: string }
99631
+ /** One of the app's sessions (getSession). */
99632
+ interface AgentPaneSessionState {
99633
+ id: string;
99634
+ title: string | null;
99635
+ status: string;
99636
+ /** A turn is live, also one waiting to continue after an interruption. */
99637
+ running: boolean;
99638
+ backgroundTasks: AgentPaneBackgroundTask[];
99639
+ lastTurn: {
99640
+ id: string;
99641
+ status: string;
99642
+ response: string | null;
99643
+ error: string | null;
99644
+ /** 'waiting' = it waits to continue. */
99645
+ resumeState: string | null;
99646
+ } | null;
99647
+ }
99218
99648
  /** A file the app stored with uploadFile (PNG, JPEG, GIF or WebP, max 5 MB). */
99219
99649
  interface AgentPaneFile {
99220
99650
  /** Content id "<sha256>.<ext>": the same bytes always get the same id. */
@@ -99252,6 +99682,25 @@ declare const AgentPane: {
99252
99682
  createSession(opts?: AgentPaneCreateSessionOptions): Promise<AgentPaneSessionInfo>;
99253
99683
  /** Send a prompt to a session; opts.attachments go with it (the agent sees images). */
99254
99684
  submitTurn(sessionId: string, prompt: string, opts?: AgentPaneSubmitTurnOptions): Promise<unknown>;
99685
+ /** One of this app's sessions, null for any other id. Works headless too. */
99686
+ getSession(sessionId: string): Promise<AgentPaneSessionState | null>;
99687
+ /** Stop the running main turn of one of this app's sessions; cancelled is
99688
+ * false when none runs. Rejects for any other session. */
99689
+ cancelTurn(sessionId: string): Promise<{ cancelled: boolean }>;
99690
+ /** Finish or reopen one of this app's sessions, as the sidebar does. Rejects
99691
+ * for any other session. */
99692
+ setSessionLifecycle(sessionId: string, lifecycle: 'working' | 'finished'): Promise<{ lifecycle: 'working' | 'finished' }>;
99693
+ /** Tab only: run one of this app's manifest tools; it is answered like an
99694
+ * agent's call, with no caller. A sandboxed tab has no way to the API of its
99695
+ * own, and this is how it gets the headless runtime to do something. */
99696
+ callTool?(tool: string, args?: Record<string, unknown>): Promise<unknown>;
99697
+ /** Tab only: the runtimes this pane offers, as /api/providers lists them. */
99698
+ listProviders?(): Promise<unknown[]>;
99699
+ /** Tab only: a runtime's models; cwd for runtimes that list per workspace. */
99700
+ listModels?(runtime: string, cwd?: string): Promise<unknown[]>;
99701
+ /** Tab only, and only while the app is on screen, so call it from a click
99702
+ * handler: the folder dialog of the machine the pane runs on. */
99703
+ pickDirectory?(): Promise<{ path?: string; cancelled?: boolean }>;
99255
99704
  onTurnCompleted(cb: (event: 'turn:completed' | 'turn:failed', payload: AgentPaneTurnPayload | null) => void): void;
99256
99705
  onTurnDelta(cb: (payload: AgentPaneDeltaPayload) => void): void;
99257
99706
  onToolCall(cb: (payload: AgentPaneToolCallPayload) => void): void;
@@ -99401,15 +99850,15 @@ function typeCheckModules(appId, modules) {
99401
99850
  };
99402
99851
  const host = ts.createCompilerHost(options);
99403
99852
  const origReadFile = host.readFile.bind(host);
99404
- host.readFile = (fname) => path6.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
99853
+ host.readFile = (fname) => path7.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
99405
99854
  host.writeFile = () => {
99406
99855
  };
99407
- const bridgePath = path6.join(dir, BRIDGE_DTS_FILE);
99408
- const rootNames = [...modules.map((m) => path6.join(dir, m.file)), bridgePath];
99856
+ const bridgePath = path7.join(dir, BRIDGE_DTS_FILE);
99857
+ const rootNames = [...modules.map((m) => path7.join(dir, m.file)), bridgePath];
99409
99858
  const program = ts.createProgram(rootNames, options, host);
99410
99859
  const out = [];
99411
99860
  for (const mod of modules) {
99412
- const sf = program.getSourceFile(path6.join(dir, mod.file));
99861
+ const sf = program.getSourceFile(path7.join(dir, mod.file));
99413
99862
  if (!sf) continue;
99414
99863
  out.push(
99415
99864
  ...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
@@ -99488,154 +99937,6 @@ function compileAppJs(appId) {
99488
99937
  return result;
99489
99938
  }
99490
99939
 
99491
- // src/apps/app-files.ts
99492
- import crypto2 from "node:crypto";
99493
- import fs4 from "node:fs";
99494
- import os4 from "node:os";
99495
- import path7 from "node:path";
99496
- var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99497
- var APP_FILE_TYPES = {
99498
- "image/png": "png",
99499
- "image/jpeg": "jpg",
99500
- "image/gif": "gif",
99501
- "image/webp": "webp"
99502
- };
99503
- var EXT_TYPES = Object.fromEntries(
99504
- Object.entries(APP_FILE_TYPES).map(([type, ext]) => [ext, type])
99505
- );
99506
- var APP_FILE_ID_RE = /^[a-f0-9]{64}\.(?:png|jpg|gif|webp)$/;
99507
- var FILE_URL_RE = /^(?:https?:\/\/[^/?#]+)?\/api\/apps\/([^/?#]+)\/files\/([^/?#]+)$/i;
99508
- var AppFileError = class extends Error {
99509
- constructor(message, status) {
99510
- super(message);
99511
- this.status = status;
99512
- this.name = "AppFileError";
99513
- }
99514
- };
99515
- var rootOverride2 = null;
99516
- function setAppFilesRootOverride(root) {
99517
- rootOverride2 = root;
99518
- }
99519
- function appFilesRoot() {
99520
- return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99521
- }
99522
- function appFilesDir(appId) {
99523
- if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99524
- return path7.join(appFilesRoot(), appId);
99525
- }
99526
- function appFileUrl(appId, fileId) {
99527
- return `/api/apps/${appId}/files/${fileId}`;
99528
- }
99529
- function fileType(fileId) {
99530
- return EXT_TYPES[fileId.slice(fileId.lastIndexOf(".") + 1)] ?? "application/octet-stream";
99531
- }
99532
- function sniffImageType(bytes) {
99533
- if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
99534
- return "image/png";
99535
- }
99536
- if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
99537
- if (bytes.length >= 6 && /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString("latin1"))) return "image/gif";
99538
- if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP") {
99539
- return "image/webp";
99540
- }
99541
- return null;
99542
- }
99543
- function decodeBase64(data) {
99544
- let b64 = data;
99545
- let dataUrlType = null;
99546
- const dataUrl = /^data:([^;,]*)(?:;[^;,]*)*;base64,/i.exec(data);
99547
- if (dataUrl) {
99548
- dataUrlType = dataUrl[1].toLowerCase() || null;
99549
- b64 = data.slice(dataUrl[0].length);
99550
- } else if (/^data:/i.test(data)) {
99551
- return null;
99552
- }
99553
- b64 = b64.replace(/\s+/g, "");
99554
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 === 1) return null;
99555
- return { bytes: Buffer.from(b64, "base64"), dataUrlType };
99556
- }
99557
- function normalizeType(type) {
99558
- if (typeof type !== "string") return null;
99559
- const t = type.split(";")[0].trim().toLowerCase();
99560
- return t || null;
99561
- }
99562
- var ACCEPTED = "PNG, JPEG, GIF or WebP";
99563
- function saveAppFile(appId, upload) {
99564
- const dir = appFilesDir(appId);
99565
- if (typeof upload.data !== "string" || !upload.data) {
99566
- throw new AppFileError("data is required (base64 or a base64 data: URL)", 400);
99567
- }
99568
- const decoded = decodeBase64(upload.data);
99569
- if (!decoded) throw new AppFileError("data is not valid base64", 400);
99570
- const declared = normalizeType(upload.type) ?? decoded.dataUrlType;
99571
- if (declared && !APP_FILE_TYPES[declared]) {
99572
- throw new AppFileError(`Unsupported file type '${declared}' \u2014 upload a ${ACCEPTED} image`, 400);
99573
- }
99574
- const { bytes } = decoded;
99575
- if (bytes.length === 0) throw new AppFileError("The file is empty", 400);
99576
- if (bytes.length > APP_FILE_MAX_BYTES) {
99577
- throw new AppFileError(
99578
- `The file is ${bytes.length} bytes \u2014 the limit is ${APP_FILE_MAX_BYTES} bytes (${APP_FILE_MAX_BYTES / (1024 * 1024)} MB)`,
99579
- 413
99580
- );
99581
- }
99582
- const type = sniffImageType(bytes);
99583
- if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99584
- const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99585
- const file = path7.join(dir, fileId);
99586
- if (!fs4.existsSync(file)) {
99587
- fs4.mkdirSync(dir, { recursive: true });
99588
- const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
99589
- fs4.writeFileSync(tmp, bytes);
99590
- fs4.renameSync(tmp, file);
99591
- }
99592
- return { id: fileId, url: appFileUrl(appId, fileId), path: file, type, size: bytes.length };
99593
- }
99594
- function appFileRefId(appId, ref) {
99595
- let value = ref;
99596
- if (value && typeof value === "object") {
99597
- const obj = value;
99598
- value = typeof obj.id === "string" ? obj.id : obj.url;
99599
- }
99600
- if (typeof value !== "string") return null;
99601
- const s = value.trim();
99602
- if (APP_FILE_ID_RE.test(s)) return s;
99603
- const m = FILE_URL_RE.exec(s);
99604
- if (!m) return null;
99605
- let owner;
99606
- try {
99607
- owner = decodeURIComponent(m[1]);
99608
- } catch {
99609
- return null;
99610
- }
99611
- return owner === appId && APP_FILE_ID_RE.test(m[2]) ? m[2] : null;
99612
- }
99613
- function getAppFile(appId, ref) {
99614
- if (!APP_ID_RE.test(appId)) return null;
99615
- const fileId = appFileRefId(appId, ref);
99616
- if (!fileId) return null;
99617
- const file = path7.join(appFilesDir(appId), fileId);
99618
- try {
99619
- const stat2 = fs4.statSync(file);
99620
- if (!stat2.isFile()) return null;
99621
- return { id: fileId, url: appFileUrl(appId, fileId), path: file, type: fileType(fileId), size: stat2.size };
99622
- } catch {
99623
- return null;
99624
- }
99625
- }
99626
- function readAppFileData(appId, fileId) {
99627
- if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99628
- try {
99629
- return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99630
- } catch {
99631
- return null;
99632
- }
99633
- }
99634
- function deleteAppFiles(appId) {
99635
- if (!APP_ID_RE.test(appId)) return;
99636
- fs4.rmSync(appFilesDir(appId), { recursive: true, force: true });
99637
- }
99638
-
99639
99940
  // src/apps/headless-runtime.ts
99640
99941
  var HEADLESS_TOOL_TIMEOUT_MS = Number(process.env.AGENT_PANE_TOOL_TIMEOUT_MS ?? 3e4);
99641
99942
  function stub() {
@@ -99658,24 +99959,59 @@ function stub() {
99658
99959
  function runtimeKey(appId, workspace) {
99659
99960
  return `${appId}\0${workspace}`;
99660
99961
  }
99962
+ function runAppCode(appId, code) {
99963
+ const report = (err) => console.error(`[headless:${appId}] app code failed:`, err);
99964
+ try {
99965
+ const result = code();
99966
+ if (typeof result?.then === "function") result.then(void 0, report);
99967
+ } catch (err) {
99968
+ report(err);
99969
+ }
99970
+ }
99661
99971
  var runtimes = /* @__PURE__ */ new Map();
99662
99972
  var pendingCalls = /* @__PURE__ */ new Map();
99663
- function getHeadlessToolHandler(appId, workspace = "") {
99973
+ function loadRuntime(appId, workspace) {
99664
99974
  const key = runtimeKey(appId, workspace);
99665
99975
  const cached = runtimes.get(key);
99666
- if (cached) return cached.handler;
99976
+ if (cached) return cached;
99667
99977
  const js = compileAppJs(appId).js;
99668
99978
  if (!js.trim()) return null;
99669
99979
  const manifest = readManifest(appId);
99670
- let handler = null;
99980
+ const headlessSessions = manifest?.headlessSessions === true;
99981
+ const appSetTimeout = (callback, ms, ...args) => setTimeout(() => runAppCode(appId, () => callback(...args)), ms);
99982
+ const sandbox = {
99983
+ console: {
99984
+ log: (...a) => console.log(`[app:${appId}]`, ...a),
99985
+ warn: (...a) => console.warn(`[app:${appId}]`, ...a),
99986
+ error: (...a) => console.error(`[app:${appId}]`, ...a)
99987
+ },
99988
+ setTimeout: appSetTimeout,
99989
+ clearTimeout,
99990
+ document: stub(),
99991
+ navigator: stub()
99992
+ };
99993
+ const context = vm2.createContext(sandbox);
99994
+ const SandboxPromise = vm2.runInContext("Promise", context);
99995
+ const answer = (work) => new SandboxPromise((resolve, reject) => {
99996
+ try {
99997
+ resolve(work());
99998
+ } catch (err) {
99999
+ reject(err);
100000
+ }
100001
+ });
100002
+ const requireHeadlessSessions = (api) => {
100003
+ if (headlessSessions) return;
100004
+ throw new Error(`${api} is not available in the headless runtime without "headlessSessions": true in manifest.json`);
100005
+ };
100006
+ const entry = { handler: null, turnListeners: [], taskListeners: [] };
99671
100007
  const bridge = {
99672
- getApp: () => Promise.resolve({ id: appId, title: manifest?.title ?? appId }),
100008
+ getApp: () => answer(() => ({ id: appId, title: manifest?.title ?? appId, workspace })),
99673
100009
  // State is scoped to the calling session's workspace instance; '' = global
99674
100010
  // (no known workspace). The open tab keeps its own workspace-scoped view.
99675
- getState: () => Promise.resolve(getInstanceState(appId, workspace)),
100011
+ getState: () => answer(() => getInstanceState(appId, workspace)),
99676
100012
  // opts.ifVersion: write only on top of that version — same contract as
99677
100013
  // the iframe bridge (rejects with code 'conflict' + the stored state).
99678
- setState: (data, opts) => {
100014
+ setState: (data, opts) => answer(() => {
99679
100015
  const ifVersion = opts?.ifVersion;
99680
100016
  let next;
99681
100017
  try {
@@ -99685,61 +100021,72 @@ function getHeadlessToolHandler(appId, workspace = "") {
99685
100021
  });
99686
100022
  } catch (err) {
99687
100023
  if (err instanceof StateConflictError) {
99688
- return Promise.reject(Object.assign(new Error(err.message), { code: "conflict", state: err.current }));
100024
+ throw Object.assign(new Error(err.message), { code: "conflict", state: err.current });
99689
100025
  }
99690
- return Promise.reject(err);
100026
+ throw err;
99691
100027
  }
99692
100028
  broadcast("app:state_changed", { appId, workspace, version: next.version });
99693
- return Promise.resolve(next);
99694
- },
100029
+ return next;
100030
+ }),
99695
100031
  onToolCall: (cb) => {
99696
100032
  if (typeof cb !== "function") return;
99697
- handler = cb.length >= 2 ? (payload) => cb("tool_call", payload) : (payload) => cb(payload);
100033
+ entry.handler = cb.length >= 2 ? (payload) => cb("tool_call", payload) : (payload) => cb(payload);
99698
100034
  },
99699
- resolveToolCall: (callId, result) => {
100035
+ resolveToolCall: (callId, result) => answer(() => {
99700
100036
  resolveHeadlessToolCall(String(callId), result);
99701
- return Promise.resolve({ ok: true });
99702
- },
100037
+ return { ok: true };
100038
+ }),
99703
100039
  // Stored files (shared with the open tab). Tool handlers hand the agent
99704
100040
  // `path`, which it opens with its own file tools.
99705
- getFile: (ref) => Promise.resolve(getAppFile(appId, ref)),
100041
+ getFile: (ref) => answer(() => getAppFile(appId, ref)),
99706
100042
  fileUrl: (ref) => {
99707
100043
  const fileId = appFileRefId(appId, ref);
99708
100044
  if (fileId) return appFileUrl(appId, fileId);
99709
100045
  return typeof ref === "string" ? ref : "";
99710
100046
  },
99711
- uploadFile: (file) => {
100047
+ uploadFile: (file) => answer(() => {
99712
100048
  try {
99713
100049
  const upload = file && typeof file === "object" ? file : {};
99714
- return Promise.resolve(saveAppFile(appId, upload));
100050
+ return saveAppFile(appId, upload);
99715
100051
  } catch (err) {
99716
- return Promise.reject(new Error(`uploadFile: ${err.message}`));
100052
+ throw new Error(`uploadFile: ${err.message}`);
99717
100053
  }
100054
+ }),
100055
+ getSession: (sessionId) => answer(() => appSessionInfo(appId, sessionId)),
100056
+ createSession: (opts) => answer(() => {
100057
+ requireHeadlessSessions("createSession");
100058
+ return createAppSession(appId, workspace, opts);
100059
+ }),
100060
+ submitTurn: (sessionId, prompt, opts) => answer(() => {
100061
+ requireHeadlessSessions("submitTurn");
100062
+ return submitAppTurn(appId, sessionId, prompt, opts);
100063
+ }),
100064
+ cancelTurn: (sessionId) => answer(() => {
100065
+ requireHeadlessSessions("cancelTurn");
100066
+ return cancelAppTurn(appId, sessionId);
100067
+ }),
100068
+ setSessionLifecycle: (sessionId, lifecycle) => answer(() => {
100069
+ requireHeadlessSessions("setSessionLifecycle");
100070
+ return setAppSessionLifecycle(appId, sessionId, lifecycle);
100071
+ }),
100072
+ onTurnCompleted: (cb) => {
100073
+ if (typeof cb === "function") entry.turnListeners.push(cb);
99718
100074
  },
99719
- // UI-flow APIs are intentionally unavailable headless.
99720
- createSession: () => Promise.reject(new Error("createSession is not available in the headless runtime")),
99721
- submitTurn: () => Promise.reject(new Error("submitTurn is not available in the headless runtime")),
99722
- openSession: () => Promise.reject(new Error("openSession is not available in the headless runtime")),
99723
- openUrl: () => Promise.reject(new Error("openUrl is not available in the headless runtime")),
99724
- onTurnCompleted: () => {
100075
+ onBackgroundTasks: (cb) => {
100076
+ if (typeof cb === "function") entry.taskListeners.push(cb);
99725
100077
  },
100078
+ // Live streaming is for a screen; nothing here renders.
99726
100079
  onTurnDelta: () => {
99727
100080
  },
99728
- onBackgroundTasks: () => {
99729
- }
99730
- };
99731
- const sandbox = {
99732
- console: {
99733
- log: (...a) => console.log(`[app:${appId}]`, ...a),
99734
- warn: (...a) => console.warn(`[app:${appId}]`, ...a),
99735
- error: (...a) => console.error(`[app:${appId}]`, ...a)
99736
- },
99737
- setTimeout,
99738
- clearTimeout,
99739
- document: stub(),
99740
- navigator: stub(),
99741
- AgentPane: bridge
100081
+ // UI actions are intentionally unavailable headless.
100082
+ openSession: () => answer(() => {
100083
+ throw new Error("openSession is not available in the headless runtime");
100084
+ }),
100085
+ openUrl: () => answer(() => {
100086
+ throw new Error("openUrl is not available in the headless runtime");
100087
+ })
99742
100088
  };
100089
+ sandbox.AgentPane = bridge;
99743
100090
  const windowObj = {
99744
100091
  addEventListener: () => {
99745
100092
  },
@@ -99747,24 +100094,26 @@ function getHeadlessToolHandler(appId, workspace = "") {
99747
100094
  },
99748
100095
  document: sandbox.document,
99749
100096
  navigator: sandbox.navigator,
99750
- setTimeout,
100097
+ setTimeout: appSetTimeout,
99751
100098
  clearTimeout,
99752
100099
  AgentPane: bridge
99753
100100
  };
99754
100101
  sandbox.window = windowObj;
99755
100102
  sandbox.self = windowObj;
99756
100103
  try {
99757
- const context = vm2.createContext(sandbox);
99758
100104
  vm2.runInContext(js, context, { filename: `${appId}/app.js` });
99759
100105
  } catch (err) {
99760
100106
  console.warn(`[headless:${appId}] app.js load failed: ${err.message}`);
99761
100107
  return null;
99762
100108
  }
99763
- if (!handler) return null;
99764
- runtimes.set(key, { handler });
99765
- return handler;
100109
+ if (!entry.handler && !entry.turnListeners.length && !entry.taskListeners.length) return null;
100110
+ runtimes.set(key, entry);
100111
+ return entry;
100112
+ }
100113
+ function getHeadlessToolHandler(appId, workspace = "") {
100114
+ return loadRuntime(appId, workspace)?.handler ?? null;
99766
100115
  }
99767
- function dispatchHeadlessToolCall(handler, tool, args) {
100116
+ function dispatchHeadlessToolCall(handler, tool, args, caller = null) {
99768
100117
  const callId = v4_default();
99769
100118
  const result = new Promise((resolve, reject) => {
99770
100119
  const timer2 = setTimeout(() => {
@@ -99777,15 +100126,18 @@ function dispatchHeadlessToolCall(handler, tool, args) {
99777
100126
  }, HEADLESS_TOOL_TIMEOUT_MS);
99778
100127
  pendingCalls.set(callId, { resolve, reject, timer: timer2 });
99779
100128
  });
100129
+ const crashed = (err) => {
100130
+ const pending = pendingCalls.get(callId);
100131
+ if (!pending) return;
100132
+ pendingCalls.delete(callId);
100133
+ clearTimeout(pending.timer);
100134
+ pending.reject(new Error(`Headless tool handler crashed: ${err?.message ?? String(err)}`));
100135
+ };
99780
100136
  try {
99781
- handler({ callId, tool, name: tool, args: args ?? {} });
100137
+ const running = handler({ callId, tool, name: tool, args: args ?? {}, caller });
100138
+ if (typeof running?.then === "function") running.then(void 0, crashed);
99782
100139
  } catch (err) {
99783
- const pending = pendingCalls.get(callId);
99784
- if (pending) {
99785
- pendingCalls.delete(callId);
99786
- clearTimeout(pending.timer);
99787
- pending.reject(new Error(`Headless tool handler crashed: ${err.message}`));
99788
- }
100140
+ crashed(err);
99789
100141
  }
99790
100142
  return { callId, result };
99791
100143
  }
@@ -99797,6 +100149,60 @@ function resolveHeadlessToolCall(callId, result) {
99797
100149
  pending.resolve(result ?? null);
99798
100150
  return true;
99799
100151
  }
100152
+ function turnEvent(event, data) {
100153
+ const { sessionId, turnId } = data;
100154
+ if (event === "turn:completed") return [event, { sessionId, turnId, response: data.response ?? null }];
100155
+ if (event === "turn:failed") return [event, { sessionId, turnId, error: data.error }];
100156
+ return ["turn:failed", { sessionId, turnId, error: "The turn was stopped", cancelled: true }];
100157
+ }
100158
+ function deliverSessionEvent(event, data) {
100159
+ const sessionId = String(data.sessionId);
100160
+ const owner = sessionOwner(sessionId);
100161
+ if (!owner || !readManifest(owner.appId)?.headlessSessions) return;
100162
+ const { appId, workspace } = owner;
100163
+ const isTaskEvent = event === "background_tasks";
100164
+ if (!isTaskEvent && !isMainTurn(String(data.turnId))) return;
100165
+ const runtime = loadRuntime(appId, workspace);
100166
+ if (!runtime) {
100167
+ console.warn(`[headless:${appId}] ${event} of session ${sessionId} dropped: the app cannot load headless`);
100168
+ return;
100169
+ }
100170
+ if (isTaskEvent) {
100171
+ const payload2 = { sessionId, tasks: data.tasks };
100172
+ for (const listener of runtime.taskListeners) runAppCode(appId, () => listener(payload2));
100173
+ return;
100174
+ }
100175
+ const [name, payload] = turnEvent(event, data);
100176
+ for (const listener of runtime.turnListeners) runAppCode(appId, () => listener(name, payload));
100177
+ }
100178
+ var SESSION_EVENTS = /* @__PURE__ */ new Set(["turn:completed", "turn:failed", "turn:cancelled", "background_tasks"]);
100179
+ function handleUnhandledRejection(reason, promise) {
100180
+ if (promise instanceof Promise) throw reason;
100181
+ console.error("[headless] unhandled rejection in app code:", reason);
100182
+ }
100183
+ var stopSessionEvents = null;
100184
+ function startHeadlessEvents() {
100185
+ stopHeadlessEvents();
100186
+ const untap = tapBroadcast((event, data) => {
100187
+ if (!SESSION_EVENTS.has(event)) return;
100188
+ setImmediate(() => {
100189
+ try {
100190
+ deliverSessionEvent(event, data);
100191
+ } catch (err) {
100192
+ console.error(`[headless] ${event} delivery failed:`, err);
100193
+ }
100194
+ });
100195
+ });
100196
+ process.on("unhandledRejection", handleUnhandledRejection);
100197
+ stopSessionEvents = () => {
100198
+ untap();
100199
+ process.off("unhandledRejection", handleUnhandledRejection);
100200
+ };
100201
+ }
100202
+ function stopHeadlessEvents() {
100203
+ stopSessionEvents?.();
100204
+ stopSessionEvents = null;
100205
+ }
99800
100206
  function invalidateHeadlessRuntime(appId) {
99801
100207
  invalidateCompiledApp(appId);
99802
100208
  if (!appId) {
@@ -99836,7 +100242,7 @@ function splitToolName(name) {
99836
100242
  return { appId: name.slice(0, idx), localName: name.slice(idx + TOOL_NS.length) };
99837
100243
  }
99838
100244
  var pendingCalls2 = /* @__PURE__ */ new Map();
99839
- function dispatchAppTool(toolName, args, workspace = "") {
100245
+ function dispatchAppTool(toolName, args, workspace = "", callerSessionId) {
99840
100246
  const split = splitToolName(toolName);
99841
100247
  if (!split) {
99842
100248
  throw new Error(`Invalid tool name: ${toolName}`);
@@ -99847,9 +100253,10 @@ function dispatchAppTool(toolName, args, workspace = "") {
99847
100253
  if (!manifest || !tool) {
99848
100254
  throw new Error(`Unknown mini-app tool: ${toolName}`);
99849
100255
  }
100256
+ const caller = toolCaller(appId, callerSessionId);
99850
100257
  const headlessHandler = getHeadlessToolHandler(appId, workspace);
99851
100258
  if (headlessHandler) {
99852
- return dispatchHeadlessToolCall(headlessHandler, localName, args);
100259
+ return dispatchHeadlessToolCall(headlessHandler, localName, args, caller);
99853
100260
  }
99854
100261
  const callId = v4_default();
99855
100262
  const result = new Promise((resolve, reject) => {
@@ -99862,12 +100269,12 @@ function dispatchAppTool(toolName, args, workspace = "") {
99862
100269
  );
99863
100270
  }, TOOL_CALL_TIMEOUT_MS);
99864
100271
  pendingCalls2.set(callId, { resolve, reject, timer: timer2, appId });
99865
- broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {}, workspace });
100272
+ broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {}, workspace, caller });
99866
100273
  });
99867
100274
  return { callId, result };
99868
100275
  }
99869
- async function callAppTool(toolName, args, workspace = "") {
99870
- return dispatchAppTool(toolName, args, workspace).result;
100276
+ async function callAppTool(toolName, args, workspace = "", callerSessionId) {
100277
+ return dispatchAppTool(toolName, args, workspace, callerSessionId).result;
99871
100278
  }
99872
100279
  function resolveAppToolCall(callId, result, error) {
99873
100280
  const pending = pendingCalls2.get(callId);
@@ -99885,17 +100292,6 @@ function anyAppHasTools() {
99885
100292
  // src/routes/apps.ts
99886
100293
  var FILE_UPLOAD_BODY_LIMIT = Math.ceil(APP_FILE_MAX_BYTES * 4 / 3) + 64 * 1024;
99887
100294
  var IMPORT_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
99888
- function resolveToolWorkspace(workspace) {
99889
- if (!workspace) return "";
99890
- const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99891
- const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99892
- if (active.includes(workspace)) return workspace;
99893
- const cwd = path8.isAbsolute(workspace) ? path8.resolve(workspace) : "";
99894
- if (isInAppFolder(cwd)) return "";
99895
- const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path8.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99896
- if (covering && !covering.deleted) return covering.path;
99897
- throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99898
- }
99899
100295
  var IMPORT_MAX_FILES = 50;
99900
100296
  var IMPORT_MAX_FILE_BYTES = 512 * 1024;
99901
100297
  var SKELETON_HTML = `<!DOCTYPE html>
@@ -99944,6 +100340,8 @@ async function registerAppRoutes(fastify, opts) {
99944
100340
  broadcast("app:source:updated", { appId });
99945
100341
  });
99946
100342
  fastify.addHook("onClose", async () => stopAppsWatch());
100343
+ startHeadlessEvents();
100344
+ fastify.addHook("onClose", async () => stopHeadlessEvents());
99947
100345
  fastify.get("/api/apps", async () => {
99948
100346
  try {
99949
100347
  ensureAppsRoot();
@@ -100101,15 +100499,16 @@ async function registerAppRoutes(fastify, opts) {
100101
100499
  properties: {
100102
100500
  tool: { type: "string" },
100103
100501
  args: { type: ["object", "null"] },
100104
- workspace: { type: ["string", "null"] }
100502
+ workspace: { type: ["string", "null"] },
100503
+ caller: { type: ["object", "null"], properties: { sessionId: { type: "string" } } }
100105
100504
  }
100106
100505
  }
100107
100506
  }
100108
100507
  },
100109
100508
  async (request, reply) => {
100110
- const { tool, args, workspace } = request.body || {};
100509
+ const { tool, args, workspace, caller } = request.body || {};
100111
100510
  try {
100112
- const result = await callAppTool(tool, args ?? {}, resolveToolWorkspace(workspace));
100511
+ const result = await callAppTool(tool, args ?? {}, resolveToolWorkspace(workspace), caller?.sessionId);
100113
100512
  return { ok: true, result };
100114
100513
  } catch (err) {
100115
100514
  return reply.code(200).send({ ok: false, error: err.message });
@@ -100263,6 +100662,51 @@ async function registerAppRoutes(fastify, opts) {
100263
100662
  const tasks = listAllBackgroundTasks();
100264
100663
  return rows.map((row) => ({ ...row, background_tasks: tasks[row.id] ?? [] }));
100265
100664
  });
100665
+ fastify.get(
100666
+ "/api/apps/:id/sessions/:sessionId",
100667
+ async (request, reply) => {
100668
+ const { id, sessionId } = request.params;
100669
+ if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100670
+ const session = appSessionInfo(id, sessionId);
100671
+ if (!session) return reply.code(404).send({ error: "Session not found" });
100672
+ return session;
100673
+ }
100674
+ );
100675
+ fastify.post(
100676
+ "/api/apps/:id/sessions/:sessionId/cancel",
100677
+ async (request, reply) => {
100678
+ const { id, sessionId } = request.params;
100679
+ if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100680
+ try {
100681
+ return await cancelAppTurn(id, sessionId);
100682
+ } catch (err) {
100683
+ if (err instanceof AppSessionError) return reply.code(404).send({ error: err.message });
100684
+ throw err;
100685
+ }
100686
+ }
100687
+ );
100688
+ fastify.patch(
100689
+ "/api/apps/:id/sessions/:sessionId",
100690
+ {
100691
+ schema: {
100692
+ body: {
100693
+ type: "object",
100694
+ required: ["lifecycle"],
100695
+ properties: { lifecycle: { type: "string", enum: ["working", "finished"] } }
100696
+ }
100697
+ }
100698
+ },
100699
+ async (request, reply) => {
100700
+ const { id, sessionId } = request.params;
100701
+ if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100702
+ try {
100703
+ return setAppSessionLifecycle(id, sessionId, request.body.lifecycle);
100704
+ } catch (err) {
100705
+ if (err instanceof AppSessionError) return reply.code(404).send({ error: err.message });
100706
+ throw err;
100707
+ }
100708
+ }
100709
+ );
100266
100710
  fastify.post(
100267
100711
  "/api/apps/:id/edit-session",
100268
100712
  {
@@ -100782,13 +101226,13 @@ function mapAssistantContent(content, messageId, thinkingTexts) {
100782
101226
  }
100783
101227
  case "thinking": {
100784
101228
  const tb = block;
100785
- let text = tb.thinking;
100786
- if (!text && thinkingTexts) {
100787
- text = thinkingTexts.get(i) ?? "";
101229
+ let text2 = tb.thinking;
101230
+ if (!text2 && thinkingTexts) {
101231
+ text2 = thinkingTexts.get(i) ?? "";
100788
101232
  }
100789
101233
  descriptors.push({
100790
101234
  type: "reasoning",
100791
- data: { text },
101235
+ data: { text: text2 },
100792
101236
  externalId: messageId
100793
101237
  });
100794
101238
  break;
@@ -100862,11 +101306,11 @@ function extractToolResultText(content) {
100862
101306
  function applyToolResult(itemType, existingData, toolResult, toolUseResult, isError) {
100863
101307
  switch (itemType) {
100864
101308
  case "command_execution": {
100865
- const text = extractToolResultText(toolResult?.content);
101309
+ const text2 = extractToolResultText(toolResult?.content);
100866
101310
  const tur = toolUseResult && typeof toolUseResult === "object" ? toolUseResult : {};
100867
101311
  const stdout = typeof tur.stdout === "string" ? tur.stdout : "";
100868
101312
  const stderr = typeof tur.stderr === "string" ? tur.stderr : "";
100869
- let aggregated = text || stdout;
101313
+ let aggregated = text2 || stdout;
100870
101314
  if (stderr) aggregated = aggregated ? `${aggregated}
100871
101315
  ${stderr}` : stderr;
100872
101316
  return {
@@ -100877,11 +101321,11 @@ ${stderr}` : stderr;
100877
101321
  };
100878
101322
  }
100879
101323
  case "mcp_tool_call": {
100880
- const text = extractToolResultText(toolResult?.content);
101324
+ const text2 = extractToolResultText(toolResult?.content);
100881
101325
  return {
100882
101326
  ...existingData,
100883
- result: text ? [{ type: "text", text }] : toolUseResult ?? null,
100884
- error: isError ? text || "Tool error" : null,
101327
+ result: text2 ? [{ type: "text", text: text2 }] : toolUseResult ?? null,
101328
+ error: isError ? text2 || "Tool error" : null,
100885
101329
  status: isError ? "failed" : "completed"
100886
101330
  };
100887
101331
  }
@@ -100917,9 +101361,9 @@ function mapUsage(usage) {
100917
101361
 
100918
101362
  // src/claude/transcript-history.ts
100919
101363
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant"]);
100920
- function parseTranscript(text) {
101364
+ function parseTranscript(text2) {
100921
101365
  const entries = [];
100922
- for (const line of text.split("\n")) {
101366
+ for (const line of text2.split("\n")) {
100923
101367
  if (!line.trim()) continue;
100924
101368
  let raw;
100925
101369
  try {
@@ -100977,17 +101421,17 @@ function mainChain(entries) {
100977
101421
  return chain.reverse();
100978
101422
  }
100979
101423
  var INJECTED_BLOCK = /^\s*<(system-reminder|ide_opened_file|ide_selection|ide_diagnostics)>/;
100980
- function tagValue(text, tag) {
100981
- const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(text);
101424
+ function tagValue(text2, tag) {
101425
+ const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(text2);
100982
101426
  return match ? match[1] : null;
100983
101427
  }
100984
101428
  function classifyUserInput(entry) {
100985
101429
  if (entry.origin?.kind && entry.origin.kind !== "human") return { kind: "ignore" };
100986
101430
  const content = entry.message?.content;
100987
- let text = "";
101431
+ let text2 = "";
100988
101432
  let images = 0;
100989
101433
  if (typeof content === "string") {
100990
- text = content;
101434
+ text2 = content;
100991
101435
  } else if (Array.isArray(content)) {
100992
101436
  const parts = [];
100993
101437
  for (const block of content) {
@@ -100998,9 +101442,9 @@ function classifyUserInput(entry) {
100998
101442
  images++;
100999
101443
  }
101000
101444
  }
101001
- text = parts.join("\n");
101445
+ text2 = parts.join("\n");
101002
101446
  }
101003
- const trimmed = text.trim();
101447
+ const trimmed = text2.trim();
101004
101448
  if (trimmed.startsWith("[Request interrupted by user")) return { kind: "interrupt" };
101005
101449
  const commandName = tagValue(trimmed, "command-name");
101006
101450
  if (commandName !== null) {
@@ -101142,12 +101586,12 @@ function buildTurns(chain) {
101142
101586
  if (!current) current = openTurn("", entry);
101143
101587
  const turn = current;
101144
101588
  if (entry.isApiErrorMessage || message.model === "<synthetic>") {
101145
- const text = syntheticText(message.content);
101146
- if (entry.isApiErrorMessage && text) {
101589
+ const text2 = syntheticText(message.content);
101590
+ if (entry.isApiErrorMessage && text2) {
101147
101591
  addItem(turn, entry, {
101148
101592
  type: "error",
101149
101593
  externalId: `api-error-${entry.uuid}`,
101150
- data: { message: text, error: "api_error" },
101594
+ data: { message: text2, error: "api_error" },
101151
101595
  status: "completed"
101152
101596
  });
101153
101597
  }
@@ -101180,8 +101624,8 @@ function buildTurns(chain) {
101180
101624
  )
101181
101625
  }));
101182
101626
  }
101183
- function transcriptToTurns(text) {
101184
- return buildTurns(mainChain(parseTranscript(text)));
101627
+ function transcriptToTurns(text2) {
101628
+ return buildTurns(mainChain(parseTranscript(text2)));
101185
101629
  }
101186
101630
 
101187
101631
  // src/claude/session-import.ts
@@ -101251,8 +101695,8 @@ async function listImportableClaudeSessions(db2, workspacePath, now = Date.now()
101251
101695
  if (known.has(info.sessionId) || !info.cwd) continue;
101252
101696
  if (!await sameDir(info.cwd, dir)) continue;
101253
101697
  if ((info.fileSize ?? 0) < CHECK_EMPTY_BELOW_BYTES) {
101254
- const text = await readTranscript(info);
101255
- if (!text || transcriptToTurns(text).length === 0) continue;
101698
+ const text2 = await readTranscript(info);
101699
+ if (!text2 || transcriptToTurns(text2).length === 0) continue;
101256
101700
  }
101257
101701
  sessions.push({
101258
101702
  session_id: info.sessionId,
@@ -101273,9 +101717,9 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
101273
101717
  const dir = workspacePath ? await realDir(workspacePath) : null;
101274
101718
  const info = (dir ? await getSessionInfo(claudeSessionId, { dir }) : void 0) ?? await getSessionInfo(claudeSessionId);
101275
101719
  if (!info) throw new ClaudeImportError(404, "Claude Code session not found");
101276
- const text = await readTranscript(info);
101277
- if (text === null) throw new ClaudeImportError(404, "The session transcript could not be read");
101278
- const turns = transcriptToTurns(text);
101720
+ const text2 = await readTranscript(info);
101721
+ if (text2 === null) throw new ClaudeImportError(404, "The session transcript could not be read");
101722
+ const turns = transcriptToTurns(text2);
101279
101723
  if (turns.length === 0) throw new ClaudeImportError(422, "This session has no conversation to import");
101280
101724
  const cwd = workspacePath && dir && info.cwd && await sameDir(info.cwd, dir) ? workspacePath : info.cwd ?? null;
101281
101725
  const sessionId = v4_default();
@@ -101496,7 +101940,7 @@ async function registerMiniAppMcp(baseUrl, workspace = "") {
101496
101940
  [MCP_SERVER_NAME]: {
101497
101941
  command: process.execPath,
101498
101942
  args: [script, panePublicUrl(), workspace],
101499
- env: {}
101943
+ env: { AGENT_PANE_SESSION_ID: "" }
101500
101944
  }
101501
101945
  })
101502
101946
  };
@@ -101511,19 +101955,19 @@ async function registerMiniAppMcp(baseUrl, workspace = "") {
101511
101955
  registered.add(key);
101512
101956
  return true;
101513
101957
  }
101514
- const text = await res.text();
101515
- if (res.status === 400 && /already exists/i.test(text)) {
101958
+ const text2 = await res.text();
101959
+ if (res.status === 400 && /already exists/i.test(text2)) {
101516
101960
  registered.add(key);
101517
101961
  return true;
101518
101962
  }
101519
- console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text.slice(0, 200)}`);
101963
+ console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
101520
101964
  return false;
101521
101965
  } catch (err) {
101522
101966
  console.warn(`[miniapp-mcp] registration error: ${err.message}`);
101523
101967
  return false;
101524
101968
  }
101525
101969
  }
101526
- function codexMiniAppLaunchArgs(workspace = "") {
101970
+ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
101527
101971
  const script = stdioScriptPath();
101528
101972
  if (!script || !anyAppHasTools()) return null;
101529
101973
  return [
@@ -101534,7 +101978,7 @@ function codexMiniAppLaunchArgs(workspace = "") {
101534
101978
  "-c",
101535
101979
  `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
101536
101980
  "-c",
101537
- `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace])}`
101981
+ `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
101538
101982
  ];
101539
101983
  }
101540
101984
 
@@ -101595,11 +102039,11 @@ function shouldSkipItem(type) {
101595
102039
  function isEmptyReasoning(item) {
101596
102040
  const summary = Array.isArray(item.summary) ? item.summary : [];
101597
102041
  const content = Array.isArray(item.content) ? item.content : [];
101598
- const text = item.text ?? "";
101599
- return summary.length === 0 && content.length === 0 && text.length === 0;
102042
+ const text2 = item.text ?? "";
102043
+ return summary.length === 0 && content.length === 0 && text2.length === 0;
101600
102044
  }
101601
- function appServerClientOptions(_session, cwd) {
101602
- const launchArgs = codexMiniAppLaunchArgs(cwd);
102045
+ function appServerClientOptions(session, cwd) {
102046
+ const launchArgs = codexMiniAppLaunchArgs(cwd, session.id);
101603
102047
  return launchArgs ? { cwd, launchArgs } : { cwd, launchArgs: [] };
101604
102048
  }
101605
102049
  function threadInstructionParams(cwd) {
@@ -101662,7 +102106,7 @@ async function getOrCreateThread(session) {
101662
102106
  sessionMap.set(session.id, entry);
101663
102107
  return entry;
101664
102108
  }
101665
- function turnAttachments(turn) {
102109
+ function turnAttachments2(turn) {
101666
102110
  const raw = turn.attachments;
101667
102111
  if (!raw) return [];
101668
102112
  if (Array.isArray(raw)) return raw;
@@ -101675,7 +102119,7 @@ function turnAttachments(turn) {
101675
102119
  }
101676
102120
  function buildCodexInput(turn) {
101677
102121
  const input = [{ type: "text", text: turn.user_prompt }];
101678
- for (const att of turnAttachments(turn)) {
102122
+ for (const att of turnAttachments2(turn)) {
101679
102123
  if (!att || typeof att.data !== "string" || !att.data) continue;
101680
102124
  const type = String(att.media_type ?? "").toLowerCase();
101681
102125
  if (type.startsWith("image/")) {
@@ -101695,7 +102139,7 @@ ${decoded}
101695
102139
  }
101696
102140
  return input;
101697
102141
  }
101698
- async function startTurn(session, turn) {
102142
+ async function startTurn2(session, turn) {
101699
102143
  const db2 = getDb();
101700
102144
  let entry;
101701
102145
  try {
@@ -102127,7 +102571,7 @@ async function shutdown() {
102127
102571
  clearAllThreads();
102128
102572
  }
102129
102573
  var codexProvider = {
102130
- startTurn,
102574
+ startTurn: startTurn2,
102131
102575
  interruptTurn,
102132
102576
  clearThread,
102133
102577
  clearAllThreads,
@@ -102270,12 +102714,12 @@ var NETWORK_TEXTS = [
102270
102714
  ];
102271
102715
  var SIGN_IN_ADVICE = /\/login|(sign|log) in again/i;
102272
102716
  var OUTSIDE_LOGIN_TEXTS = /api[ -]key|gateway|bedrock|vertex|foundry|mantle/i;
102273
- function isSignedOut(text) {
102274
- if (!text) return true;
102275
- return SIGN_IN_ADVICE.test(text) || !OUTSIDE_LOGIN_TEXTS.test(text);
102717
+ function isSignedOut(text2) {
102718
+ if (!text2) return true;
102719
+ return SIGN_IN_ADVICE.test(text2) || !OUTSIDE_LOGIN_TEXTS.test(text2);
102276
102720
  }
102277
- function classifyApiError({ error, status, text, limitRejected }) {
102278
- if (error === "authentication_failed" || !error && status === 401) return isSignedOut(text) ? "auth" : "fatal";
102721
+ function classifyApiError({ error, status, text: text2, limitRejected }) {
102722
+ if (error === "authentication_failed" || !error && status === 401) return isSignedOut(text2) ? "auth" : "fatal";
102279
102723
  if (limitRejected && (error === "rate_limit" || !error && status === 429)) return "usage_limit";
102280
102724
  if (error && FATAL_ERRORS.has(error)) return "fatal";
102281
102725
  if (error && TRANSIENT_ERRORS.has(error)) return "network";
@@ -102283,7 +102727,7 @@ function classifyApiError({ error, status, text, limitRejected }) {
102283
102727
  if (status === 408 || status >= 500) return "network";
102284
102728
  return "fatal";
102285
102729
  }
102286
- if (text && NETWORK_TEXTS.some((re) => re.test(text))) return "network";
102730
+ if (text2 && NETWORK_TEXTS.some((re) => re.test(text2))) return "network";
102287
102731
  if (status === null && (!error || error === "unknown")) return "network";
102288
102732
  return "fatal";
102289
102733
  }
@@ -102450,10 +102894,8 @@ function rescueWaitMs() {
102450
102894
  return Number.isFinite(ms) && ms > 0 ? ms : 15e3;
102451
102895
  }
102452
102896
  var RESCUE_ENV = ["CLAUDE_CODE_RESUME_INTERRUPTED_TURN", "CLAUDE_CODE_RESUME_REASON"];
102453
- function spawnEnv(resume) {
102454
- const inherited = RESCUE_ENV.some((k) => k in process.env);
102455
- if (!resume && !inherited) return void 0;
102456
- const env = { ...process.env };
102897
+ function spawnEnv(sessionId, resume) {
102898
+ const env = { ...process.env, AGENT_PANE_SESSION_ID: sessionId };
102457
102899
  for (const k of RESCUE_ENV) delete env[k];
102458
102900
  if (resume) {
102459
102901
  env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN = "1";
@@ -102592,7 +103034,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102592
103034
  const key = mapKey ?? session.id;
102593
103035
  const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
102594
103036
  const rescue = resume && resumeId ? resume : void 0;
102595
- const env = spawnEnv(rescue);
103037
+ const env = spawnEnv(session.id, rescue);
102596
103038
  let cliPid = null;
102597
103039
  const options = {
102598
103040
  cwd: session.cwd ?? process.cwd(),
@@ -102692,7 +103134,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102692
103134
  })();
102693
103135
  return entry;
102694
103136
  }
102695
- async function startTurn2(session, turn) {
103137
+ async function startTurn3(session, turn) {
102696
103138
  const db2 = getDb();
102697
103139
  const now = (/* @__PURE__ */ new Date()).toISOString();
102698
103140
  const mapKey = turn.thread_id ? `${session.id}:thread:${turn.thread_id}` : session.id;
@@ -102874,16 +103316,16 @@ function handleAssistantMessage(message, sessionId, turnId, entry, db2) {
102874
103316
  const apiError = message.error;
102875
103317
  if (apiError && message.message?.model === "<synthetic>") {
102876
103318
  const blocks = Array.isArray(message.message?.content) ? message.message.content : [];
102877
- const text = blocks.map((b) => {
103319
+ const text2 = blocks.map((b) => {
102878
103320
  const block = b;
102879
103321
  return block?.type === "text" && typeof block.text === "string" ? block.text : "";
102880
103322
  }).join("").trim() || `API error (${apiError})`;
102881
- entry.lastApiError = { error: apiError, text };
103323
+ entry.lastApiError = { error: apiError, text: text2 };
102882
103324
  thinkingAccumulator.delete(messageId);
102883
103325
  streamingMessageIds.delete(turnId);
102884
103326
  upsertItem(
102885
103327
  db2,
102886
- { type: "error", data: { message: text, error: apiError }, externalId: `api-error-${messageId}` },
103328
+ { type: "error", data: { message: text2, error: apiError }, externalId: `api-error-${messageId}` },
102887
103329
  sessionId,
102888
103330
  turnId,
102889
103331
  "completed",
@@ -102908,13 +103350,13 @@ function handleAssistantMessage(message, sessionId, turnId, entry, db2) {
102908
103350
  if (!isToolCall) {
102909
103351
  const now = (/* @__PURE__ */ new Date()).toISOString();
102910
103352
  if (desc.type === "agent_message") {
102911
- const text = desc.data.text;
102912
- db2.prepare("UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ?").run(text, now, turnId);
103353
+ const text2 = desc.data.text;
103354
+ db2.prepare("UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ?").run(text2, now, turnId);
102913
103355
  }
102914
103356
  if (desc.type === "reasoning") {
102915
- const text = desc.data.text;
102916
- if (text) {
102917
- db2.prepare("UPDATE turns SET thoughts = ?, updated_at = ? WHERE id = ?").run(text, now, turnId);
103357
+ const text2 = desc.data.text;
103358
+ if (text2) {
103359
+ db2.prepare("UPDATE turns SET thoughts = ?, updated_at = ? WHERE id = ?").run(text2, now, turnId);
102918
103360
  }
102919
103361
  }
102920
103362
  }
@@ -103200,18 +103642,18 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
103200
103642
  const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
103201
103643
  if (row?.status !== "pending" && row?.status !== "running") return;
103202
103644
  if (row.status === "pending" && row.resume_state === "waiting") return;
103203
- const text = (message.result || apiError?.text || "Claude API error").trim();
103645
+ const text2 = (message.result || apiError?.text || "Claude API error").trim();
103204
103646
  const kind = classifyApiError({
103205
103647
  error: apiError?.error,
103206
103648
  status: message.api_error_status,
103207
- text,
103649
+ text: text2,
103208
103650
  limitRejected: entry.rateLimit?.status === "rejected"
103209
103651
  });
103210
103652
  const resumeAt = kind === "usage_limit" ? usageLimitResumeAt(entry.rateLimit?.resetsAt) : null;
103211
- if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text, resumeAt })) {
103653
+ if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text2, resumeAt })) {
103212
103654
  return;
103213
103655
  }
103214
- failTurn(db2, sessionId, turnId, text);
103656
+ failTurn(db2, sessionId, turnId, text2);
103215
103657
  return;
103216
103658
  }
103217
103659
  await refreshContext(entry, sessionId, db2);
@@ -103668,7 +104110,7 @@ async function forkClaudeSession(session, targetTurn) {
103668
104110
  }
103669
104111
  }
103670
104112
  var claudeProvider = {
103671
- startTurn: startTurn2,
104113
+ startTurn: startTurn3,
103672
104114
  interruptTurn: interruptTurn2,
103673
104115
  clearThread: clearThread2,
103674
104116
  clearThreadBranch,
@@ -103689,8 +104131,8 @@ var claudeProvider = {
103689
104131
  function defaultRepoburgBaseUrl() {
103690
104132
  return process.env.REPOBURG_BACKEND_URL || "http://localhost:3000";
103691
104133
  }
103692
- function isHtml(text) {
103693
- return /^\s*<(?:!doctype|html)/i.test(text);
104134
+ function isHtml(text2) {
104135
+ return /^\s*<(?:!doctype|html)/i.test(text2);
103694
104136
  }
103695
104137
  var RepoburgHttpClient = class {
103696
104138
  /** Base URL of the repoburg backend (public — the projector opens the
@@ -103706,18 +104148,18 @@ var RepoburgHttpClient = class {
103706
104148
  headers: { "Content-Type": "application/json" },
103707
104149
  body: body === void 0 ? void 0 : JSON.stringify(body)
103708
104150
  });
103709
- const text = await response.text();
104151
+ const text2 = await response.text();
103710
104152
  if (!response.ok) {
103711
- if (isHtml(text)) {
104153
+ if (isHtml(text2)) {
103712
104154
  throw new Error(
103713
104155
  `${method} ${path12} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
103714
104156
  );
103715
104157
  }
103716
- throw new Error(`${method} ${path12} failed: ${response.status} ${text}`);
104158
+ throw new Error(`${method} ${path12} failed: ${response.status} ${text2}`);
103717
104159
  }
103718
- if (text.length === 0) return void 0;
104160
+ if (text2.length === 0) return void 0;
103719
104161
  try {
103720
- return JSON.parse(text);
104162
+ return JSON.parse(text2);
103721
104163
  } catch {
103722
104164
  throw new Error(
103723
104165
  `${method} ${path12} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
@@ -103798,12 +104240,12 @@ async function fetchJson(url, init, timeoutMs = 5e3) {
103798
104240
  } finally {
103799
104241
  clearTimeout(timer2);
103800
104242
  }
103801
- const text = await response.text();
104243
+ const text2 = await response.text();
103802
104244
  if (!response.ok) {
103803
- throw new HttpError(response.status, text, url);
104245
+ throw new HttpError(response.status, text2, url);
103804
104246
  }
103805
104247
  try {
103806
- return JSON.parse(text);
104248
+ return JSON.parse(text2);
103807
104249
  } catch {
103808
104250
  throw new Error(`Unexpected non-JSON response from ${url}`);
103809
104251
  }
@@ -104035,12 +104477,12 @@ function mapActionToItem(action) {
104035
104477
  case "final":
104036
104478
  case "html_final": {
104037
104479
  const groups = parseSelectionGroups(action.selections);
104038
- const text = action.action_type === "final" ? action.plain ?? "" : "";
104480
+ const text2 = action.action_type === "final" ? action.plain ?? "" : "";
104039
104481
  const html = action.action_type === "html_final" ? action.content ?? null : null;
104040
- if (!text && !html && groups.length === 0) return null;
104482
+ if (!text2 && !html && groups.length === 0) return null;
104041
104483
  return {
104042
104484
  type: "final_result",
104043
- data: { question: "", groups, text, html },
104485
+ data: { question: "", groups, text: text2, html },
104044
104486
  status
104045
104487
  };
104046
104488
  }
@@ -104371,9 +104813,9 @@ var TurnProjector = class {
104371
104813
  if (msg.usage && msg.usage.input_tokens > 0) {
104372
104814
  this.lastContextTokens = msg.usage.input_tokens;
104373
104815
  }
104374
- const text = msg.content.filter((b) => b.type === "text").map((b) => b.text).join("");
104816
+ const text2 = msg.content.filter((b) => b.type === "text").map((b) => b.text).join("");
104375
104817
  const thinking = msg.content.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
104376
- if (text) info.text = text;
104818
+ if (text2) info.text = text2;
104377
104819
  if (thinking) info.thoughts = thinking;
104378
104820
  this.upsertCompletedTextItem(info, "message", info.text);
104379
104821
  this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
@@ -104381,8 +104823,8 @@ var TurnProjector = class {
104381
104823
  }
104382
104824
  /** Complete a round's text/thoughts item — creates it when deltas were
104383
104825
  * off or missed, otherwise completes the streamed in_progress item. */
104384
- upsertCompletedTextItem(info, kind, text) {
104385
- if (!text) return;
104826
+ upsertCompletedTextItem(info, kind, text2) {
104827
+ if (!text2) return;
104386
104828
  const db2 = getDb();
104387
104829
  const externalId = kind === "message" ? info.messageExternalId : info.reasoningExternalId;
104388
104830
  const itemId = kind === "message" ? info.messageItemId : info.reasoningItemId;
@@ -104390,7 +104832,7 @@ var TurnProjector = class {
104390
104832
  if (itemId) {
104391
104833
  const itemRow = db2.prepare("SELECT * FROM items WHERE id = ?").get(itemId);
104392
104834
  if (itemRow) {
104393
- completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, itemRow, { text }, "completed");
104835
+ completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, itemRow, { text: text2 }, "completed");
104394
104836
  return;
104395
104837
  }
104396
104838
  }
@@ -104402,7 +104844,7 @@ var TurnProjector = class {
104402
104844
  this.deps.turnId,
104403
104845
  externalId,
104404
104846
  type,
104405
- { text },
104847
+ { text: text2 },
104406
104848
  "completed",
104407
104849
  "item:completed"
104408
104850
  );
@@ -105053,7 +105495,7 @@ ${conventions}` : `${conventions}
105053
105495
 
105054
105496
  ${prompt}`;
105055
105497
  }
105056
- async function startTurn3(session, turn) {
105498
+ async function startTurn4(session, turn) {
105057
105499
  const db2 = getDb();
105058
105500
  let client;
105059
105501
  let baseUrl;
@@ -105277,7 +105719,7 @@ async function shutdown3() {
105277
105719
  clearAllThreads3();
105278
105720
  }
105279
105721
  var repoburgProvider = {
105280
- startTurn: startTurn3,
105722
+ startTurn: startTurn4,
105281
105723
  interruptTurn: interruptTurn3,
105282
105724
  clearThread: clearThread3,
105283
105725
  clearThreadBranch: clearThreadBranch2,