repoburg 1.3.316 → 1.3.318

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.
@@ -41180,6 +41180,9 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41180
41180
  if (!sessColumns.some((c) => c.name === "pre_rewind_thread_id")) {
41181
41181
  database.exec("ALTER TABLE sessions ADD COLUMN pre_rewind_thread_id TEXT");
41182
41182
  }
41183
+ if (!sessColumns.some((c) => c.name === "pre_rewind_turn_ids")) {
41184
+ database.exec("ALTER TABLE sessions ADD COLUMN pre_rewind_turn_ids TEXT");
41185
+ }
41183
41186
  if (!sessColumns.some((c) => c.name === "context_usage")) {
41184
41187
  database.exec("ALTER TABLE sessions ADD COLUMN context_usage TEXT");
41185
41188
  }
@@ -41931,6 +41934,80 @@ function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnrev
41931
41934
  }
41932
41935
  }
41933
41936
 
41937
+ // src/routes/rewind-state.ts
41938
+ function forkPoint(db2, sessionId, target) {
41939
+ const row = db2.prepare(
41940
+ `SELECT external_turn_id FROM turns
41941
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
41942
+ AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
41943
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`
41944
+ ).get(sessionId, target.id, target.created_at);
41945
+ return row?.external_turn_id ?? null;
41946
+ }
41947
+ function snapshotTurnIds(db2, sessionId) {
41948
+ const rows = db2.prepare("SELECT id, external_turn_id FROM turns WHERE session_id = ? AND thread_id IS NULL").all(sessionId);
41949
+ return JSON.stringify(Object.fromEntries(rows.map((r) => [r.id, r.external_turn_id])));
41950
+ }
41951
+ function restoreTurnIds(db2, sessionId, snapshot) {
41952
+ if (!snapshot) return;
41953
+ let ids;
41954
+ try {
41955
+ ids = JSON.parse(snapshot);
41956
+ } catch {
41957
+ return;
41958
+ }
41959
+ const update = db2.prepare("UPDATE turns SET external_turn_id = ? WHERE id = ? AND session_id = ?");
41960
+ for (const [turnId, externalId] of Object.entries(ids)) update.run(externalId, turnId, sessionId);
41961
+ }
41962
+ function applyTurnIdMap(db2, sessionId, map2, upToCreatedAt = null) {
41963
+ if (map2.size === 0) return;
41964
+ const rows = db2.prepare(
41965
+ `SELECT id, external_turn_id FROM turns
41966
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL` + (upToCreatedAt ? " AND created_at <= ?" : "")
41967
+ ).all(...upToCreatedAt ? [sessionId, upToCreatedAt] : [sessionId]);
41968
+ const update = db2.prepare("UPDATE turns SET external_turn_id = ? WHERE id = ?");
41969
+ for (const row of rows) {
41970
+ const mapped = map2.get(row.external_turn_id);
41971
+ if (mapped) update.run(mapped, row.id);
41972
+ }
41973
+ }
41974
+ function dropRewoundTurns(db2, sessionId) {
41975
+ const session = db2.prepare("SELECT rewound_at_turn_id FROM sessions WHERE id = ?").get(sessionId);
41976
+ if (!session?.rewound_at_turn_id) return null;
41977
+ const target = db2.prepare("SELECT created_at FROM turns WHERE id = ?").get(session.rewound_at_turn_id);
41978
+ let threadIds = [];
41979
+ db2.transaction(() => {
41980
+ if (target) {
41981
+ const hidden = "SELECT id FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at > ?";
41982
+ threadIds = db2.prepare(`SELECT id FROM discussion_threads WHERE session_id = ? AND turn_id IN (${hidden})`).all(sessionId, sessionId, target.created_at).map((r) => r.id);
41983
+ for (const threadId of threadIds) {
41984
+ db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE thread_id = ?)").run(threadId);
41985
+ db2.prepare("DELETE FROM turns WHERE thread_id = ?").run(threadId);
41986
+ db2.prepare("DELETE FROM discussion_threads WHERE id = ?").run(threadId);
41987
+ }
41988
+ db2.prepare(`DELETE FROM items WHERE turn_id IN (${hidden})`).run(sessionId, target.created_at);
41989
+ db2.prepare("DELETE FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at > ?").run(
41990
+ sessionId,
41991
+ target.created_at
41992
+ );
41993
+ }
41994
+ db2.prepare(
41995
+ "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_turn_ids = NULL, updated_at = ? WHERE id = ?"
41996
+ ).run((/* @__PURE__ */ new Date()).toISOString(), sessionId);
41997
+ })();
41998
+ return { threadIds };
41999
+ }
42000
+ function commitRewind(db2, sessionId, clearThreadBranch4) {
42001
+ const dropped = dropRewoundTurns(db2, sessionId);
42002
+ if (!dropped) return;
42003
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
42004
+ broadcast("session:updated", { session });
42005
+ for (const threadId of dropped.threadIds) {
42006
+ clearThreadBranch4?.(sessionId, threadId);
42007
+ broadcast("thread:deleted", { sessionId, threadId });
42008
+ }
42009
+ }
42010
+
41934
42011
  // src/routes/session-touch.ts
41935
42012
  function markSessionTouched(db2, sessionId) {
41936
42013
  const { changes } = db2.prepare("UPDATE sessions SET user_touched = 1 WHERE id = ? AND user_touched = 0").run(sessionId);
@@ -41940,17 +42017,20 @@ function markSessionTouched(db2, sessionId) {
41940
42017
  }
41941
42018
 
41942
42019
  // src/routes/session-actions.ts
42020
+ function blankToNull(value) {
42021
+ return value === "" ? null : value;
42022
+ }
41943
42023
  function createSession(db2, input) {
41944
42024
  const {
41945
42025
  title = null,
41946
42026
  runtime_type = "codex",
41947
- model = null,
41948
- model_reasoning_effort = null,
41949
42027
  cwd = null,
41950
42028
  runtime_config = null,
41951
42029
  origin_app_id = null,
41952
42030
  origin_app_workspace = null
41953
42031
  } = input;
42032
+ const model = blankToNull(input.model ?? null);
42033
+ const model_reasoning_effort = blankToNull(input.model_reasoning_effort ?? null);
41954
42034
  const id = v4_default();
41955
42035
  const now = (/* @__PURE__ */ new Date()).toISOString();
41956
42036
  const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
@@ -41982,6 +42062,7 @@ var SessionBusyError = class extends Error {
41982
42062
  function startTurn(db2, session, { prompt, attachments, originAppId }) {
41983
42063
  if (isSessionBusy(db2, session, { mainOnly: true })) throw new SessionBusyError();
41984
42064
  const provider = getProvider(session.runtime_type);
42065
+ commitRewind(db2, session.id, provider.clearThreadBranch?.bind(provider));
41985
42066
  const turnId = v4_default();
41986
42067
  const now = (/* @__PURE__ */ new Date()).toISOString();
41987
42068
  const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
@@ -42160,19 +42241,29 @@ async function registerSessionRoutes(fastify) {
42160
42241
  }
42161
42242
  }, async (request, reply) => {
42162
42243
  const { id } = request.params;
42163
- const { title, lifecycle, has_unreviewed, model, model_reasoning_effort, runtime_config, runtime_type, cwd, starred } = request.body || {};
42244
+ const body = request.body || {};
42245
+ const { title, lifecycle, has_unreviewed, runtime_config, runtime_type, cwd, starred } = body;
42246
+ const model = body.model === void 0 ? void 0 : blankToNull(body.model);
42247
+ const model_reasoning_effort = body.model_reasoning_effort === void 0 ? void 0 : blankToNull(body.model_reasoning_effort);
42164
42248
  const db2 = getDb();
42165
42249
  const existing = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42166
42250
  if (!existing) {
42167
42251
  return reply.code(404).send({ error: "Session not found" });
42168
42252
  }
42169
- if (runtime_type !== void 0 && runtime_type !== existing.runtime_type && existing.is_running) {
42170
- return reply.code(409).send({ error: "Cannot switch provider while a turn is running" });
42253
+ const providerChanged = runtime_type !== void 0 && runtime_type !== existing.runtime_type;
42254
+ if (providerChanged) {
42255
+ if (existing.is_running) {
42256
+ return reply.code(409).send({ error: "Cannot switch provider while a turn is running" });
42257
+ }
42258
+ if (db2.prepare("SELECT 1 FROM turns WHERE session_id = ? LIMIT 1").get(id)) {
42259
+ return reply.code(409).send({
42260
+ error: "The provider cannot change once the session has turns \u2014 start a new session to use another provider"
42261
+ });
42262
+ }
42171
42263
  }
42172
42264
  const now = (/* @__PURE__ */ new Date()).toISOString();
42173
42265
  const updates = ["updated_at = ?"];
42174
42266
  const params = [now];
42175
- let providerChanged = false;
42176
42267
  if (title !== void 0) {
42177
42268
  updates.push("title = ?");
42178
42269
  params.push(title);
@@ -42189,8 +42280,7 @@ async function registerSessionRoutes(fastify) {
42189
42280
  updates.push("starred = ?");
42190
42281
  params.push(starred);
42191
42282
  }
42192
- if (runtime_type !== void 0 && runtime_type !== existing.runtime_type) {
42193
- providerChanged = true;
42283
+ if (providerChanged) {
42194
42284
  updates.push("runtime_type = ?");
42195
42285
  params.push(runtime_type);
42196
42286
  if (model === void 0) {
@@ -42228,6 +42318,12 @@ async function registerSessionRoutes(fastify) {
42228
42318
  if (model_reasoning_effort !== void 0) {
42229
42319
  updates.push("model_reasoning_effort = ?");
42230
42320
  params.push(model_reasoning_effort);
42321
+ if (model_reasoning_effort !== existing.model_reasoning_effort && !providerChanged) {
42322
+ const provider = getProvider(existing.runtime_type);
42323
+ provider.setEffort?.(id, model_reasoning_effort).catch((err) => {
42324
+ console.error(`[patch] setEffort failed for session ${id}:`, err);
42325
+ });
42326
+ }
42231
42327
  }
42232
42328
  if (runtime_config !== void 0) {
42233
42329
  updates.push("runtime_config = ?");
@@ -42236,10 +42332,14 @@ async function registerSessionRoutes(fastify) {
42236
42332
  db2.prepare(`UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`).run(...params, id);
42237
42333
  if (title !== void 0) markSessionTouched(db2, id);
42238
42334
  if (providerChanged || workspaceChanged) {
42239
- if (existing.external_thread_id) {
42240
- db2.prepare("UPDATE sessions SET external_thread_id = NULL, rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, updated_at = ? WHERE id = ?").run(now, id);
42241
- }
42242
- getProvider(existing.runtime_type).clearThread(id);
42335
+ const provider = getProvider(existing.runtime_type);
42336
+ commitRewind(db2, id, provider.clearThreadBranch?.bind(provider));
42337
+ db2.prepare(
42338
+ `UPDATE sessions SET external_thread_id = NULL, rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL,
42339
+ pre_rewind_turn_ids = NULL, context_usage = NULL, updated_at = ? WHERE id = ?`
42340
+ ).run(now, id);
42341
+ db2.prepare("UPDATE turns SET external_turn_id = NULL WHERE session_id = ? AND thread_id IS NULL").run(id);
42342
+ provider.clearThread(id);
42243
42343
  }
42244
42344
  const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42245
42345
  broadcast("session:updated", { session });
@@ -42276,6 +42376,9 @@ async function registerSessionRoutes(fastify) {
42276
42376
  if (!targetTurnFull) {
42277
42377
  return reply.code(404).send({ error: "Turn not found" });
42278
42378
  }
42379
+ if (targetTurnFull.thread_id != null) {
42380
+ return reply.code(400).send({ error: "Cannot rewind to a discussion thread turn" });
42381
+ }
42279
42382
  const provider = getProvider(session.runtime_type);
42280
42383
  if (provider.rewindRuntime) {
42281
42384
  await provider.rewindRuntime(session, targetTurnFull);
@@ -42288,37 +42391,48 @@ async function registerSessionRoutes(fastify) {
42288
42391
  targetTurnFull.created_at
42289
42392
  );
42290
42393
  db2.prepare(
42291
- "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, updated_at = ? WHERE id = ?"
42394
+ "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, pre_rewind_turn_ids = NULL, updated_at = ? WHERE id = ?"
42292
42395
  ).run(now2, id);
42293
42396
  markSessionTouched(db2, id);
42294
42397
  const truncated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42295
42398
  return truncated;
42296
42399
  }
42297
- const now = (/* @__PURE__ */ new Date()).toISOString();
42298
- if (!session.pre_rewind_thread_id && session.external_thread_id) {
42299
- db2.prepare(
42300
- "UPDATE sessions SET rewound_at_turn_id = ?, pre_rewind_thread_id = ?, updated_at = ? WHERE id = ?"
42301
- ).run(turn_id, session.external_thread_id, now, id);
42302
- console.log(`[rewind] saved pre_rewind_thread_id=${session.external_thread_id} for session ${id}`);
42303
- } else {
42304
- db2.prepare(
42305
- "UPDATE sessions SET rewound_at_turn_id = ?, updated_at = ? WHERE id = ?"
42306
- ).run(turn_id, now, id);
42307
- console.log(`[rewind] pre_rewind_thread_id already set (${session.pre_rewind_thread_id}) or external_thread_id is null for session ${id}`);
42308
- }
42400
+ let forkedId = session.external_thread_id;
42401
+ let turnIds = /* @__PURE__ */ new Map();
42309
42402
  if (provider.forkSession) {
42310
42403
  try {
42311
- const forkedId = await provider.forkSession(session, targetTurnFull);
42312
- if (forkedId) {
42313
- db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(forkedId, now, id);
42314
- console.log(`[rewind] forked to ${forkedId} for session ${id}`);
42315
- } else {
42316
- console.warn(`[rewind] forkSession returned null for session ${id} (external_thread_id=${session.external_thread_id}, upToMessageId=${targetTurnFull.external_turn_id})`);
42317
- }
42404
+ forkedId = await provider.forkSession(session, targetTurnFull);
42318
42405
  } catch (err) {
42319
42406
  console.error(`[rewind] forkSession threw for session ${id}:`, err);
42407
+ return reply.code(409).send({
42408
+ error: `Cannot rewind to this turn: the runtime could not fork its conversation there (${err.message})`
42409
+ });
42410
+ }
42411
+ if (forkedId && provider.forkedTurnIds) {
42412
+ turnIds = await provider.forkedTurnIds(session, forkedId).catch((err) => {
42413
+ console.warn(`[rewind] could not read the turn ids of fork ${forkedId}:`, err);
42414
+ return /* @__PURE__ */ new Map();
42415
+ });
42320
42416
  }
42321
42417
  }
42418
+ const now = (/* @__PURE__ */ new Date()).toISOString();
42419
+ db2.transaction(() => {
42420
+ if (!session.rewound_at_turn_id) {
42421
+ db2.prepare("UPDATE sessions SET pre_rewind_thread_id = ?, pre_rewind_turn_ids = ? WHERE id = ?").run(
42422
+ session.external_thread_id,
42423
+ snapshotTurnIds(db2, id),
42424
+ id
42425
+ );
42426
+ }
42427
+ db2.prepare("UPDATE sessions SET rewound_at_turn_id = ?, external_thread_id = ?, updated_at = ? WHERE id = ?").run(
42428
+ turn_id,
42429
+ forkedId,
42430
+ now,
42431
+ id
42432
+ );
42433
+ applyTurnIdMap(db2, id, turnIds, targetTurnFull.created_at);
42434
+ })();
42435
+ console.log(`[rewind] session ${id} rewound to ${turn_id}, runtime thread ${forkedId ?? "(none)"}`);
42322
42436
  provider.clearThread(id);
42323
42437
  markSessionTouched(db2, id);
42324
42438
  const updated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
@@ -42340,10 +42454,17 @@ async function registerSessionRoutes(fastify) {
42340
42454
  error: "Restore is not available for repoburg sessions \u2014 the rewind permanently deleted the runtime history."
42341
42455
  });
42342
42456
  }
42457
+ if (session.is_running) {
42458
+ return reply.code(409).send({ error: "Cannot restore while a turn is running" });
42459
+ }
42343
42460
  const now = (/* @__PURE__ */ new Date()).toISOString();
42344
- db2.prepare(
42345
- "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, external_thread_id = COALESCE(pre_rewind_thread_id, external_thread_id), updated_at = ? WHERE id = ?"
42346
- ).run(now, id);
42461
+ db2.transaction(() => {
42462
+ restoreTurnIds(db2, id, session.pre_rewind_turn_ids);
42463
+ db2.prepare(
42464
+ `UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, pre_rewind_turn_ids = NULL,
42465
+ external_thread_id = COALESCE(pre_rewind_thread_id, external_thread_id), updated_at = ? WHERE id = ?`
42466
+ ).run(now, id);
42467
+ })();
42347
42468
  getProvider(session.runtime_type).clearThread(id);
42348
42469
  markSessionTouched(db2, id);
42349
42470
  const updated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
@@ -42381,78 +42502,88 @@ async function registerSessionRoutes(fastify) {
42381
42502
  if (targetTurn.thread_id != null) {
42382
42503
  return reply.code(400).send({ error: "Cannot branch from a discussion thread turn" });
42383
42504
  }
42505
+ const provider = getProvider(session.runtime_type);
42506
+ let forkedId = null;
42507
+ let turnIds = /* @__PURE__ */ new Map();
42508
+ if (provider.forkSession) {
42509
+ const targetTurnFull = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turn_id);
42510
+ try {
42511
+ forkedId = await provider.forkSession(session, targetTurnFull);
42512
+ } catch (err) {
42513
+ console.error(`[branch] forkSession threw for session ${id}:`, err);
42514
+ return reply.code(409).send({
42515
+ error: `Cannot branch from this turn: the runtime could not fork its conversation there (${err.message})`
42516
+ });
42517
+ }
42518
+ if (forkedId && provider.forkedTurnIds) {
42519
+ turnIds = await provider.forkedTurnIds(session, forkedId).catch((err) => {
42520
+ console.warn(`[branch] could not read the turn ids of fork ${forkedId}:`, err);
42521
+ return /* @__PURE__ */ new Map();
42522
+ });
42523
+ }
42524
+ }
42384
42525
  const newSessionId = v4_default();
42385
42526
  const now = (/* @__PURE__ */ new Date()).toISOString();
42386
42527
  const newTitle = title || `Branch of ${session.title || session.id.slice(0, 8)}`;
42387
- db2.prepare(
42388
- `INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status, is_running, lifecycle, has_unreviewed, created_at, updated_at, runtime_config)
42389
- VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, 'working', 0, ?, ?, ?)`
42390
- ).run(
42391
- newSessionId,
42392
- newTitle,
42393
- session.runtime_type,
42394
- session.model,
42395
- session.model_reasoning_effort,
42396
- session.cwd,
42397
- now,
42398
- now,
42399
- session.runtime_config
42400
- );
42401
- const turnRows = db2.prepare(
42402
- "SELECT * FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at <= ? ORDER BY created_at ASC"
42403
- ).all(id, targetTurn.created_at);
42404
- for (const turn of turnRows) {
42405
- const newTurnId = v4_default();
42528
+ db2.transaction(() => {
42406
42529
  db2.prepare(
42407
- `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, origin, origin_name, created_at, updated_at)
42408
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42530
+ `INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status, is_running, lifecycle, has_unreviewed, created_at, updated_at, runtime_config)
42531
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'active', 0, 'working', 0, ?, ?, ?)`
42409
42532
  ).run(
42410
- newTurnId,
42411
42533
  newSessionId,
42412
- turn.user_prompt,
42413
- turn.agent_response,
42414
- turn.thoughts,
42415
- turn.token_usage,
42416
- turn.external_turn_id,
42417
- turn.status,
42418
- turn.error,
42419
- turn.attachments,
42420
- turn.origin ?? null,
42421
- turn.origin_name ?? null,
42422
- turn.created_at,
42423
- turn.updated_at
42534
+ newTitle,
42535
+ session.runtime_type,
42536
+ session.model,
42537
+ session.model_reasoning_effort,
42538
+ session.cwd,
42539
+ forkedId,
42540
+ now,
42541
+ now,
42542
+ session.runtime_config
42424
42543
  );
42425
- const itemRows = db2.prepare("SELECT * FROM items WHERE turn_id = ? ORDER BY created_at ASC").all(turn.id);
42426
- for (const item of itemRows) {
42427
- const newItemId = v4_default();
42544
+ const turnRows = db2.prepare(
42545
+ "SELECT * FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at <= ? ORDER BY created_at ASC"
42546
+ ).all(id, targetTurn.created_at);
42547
+ for (const turn of turnRows) {
42548
+ const newTurnId = v4_default();
42428
42549
  db2.prepare(
42429
- `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
42430
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
42550
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, origin, origin_name, created_at, updated_at)
42551
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42431
42552
  ).run(
42432
- newItemId,
42433
42553
  newTurnId,
42434
- item.external_item_id,
42435
- item.type,
42436
- item.data,
42437
- item.status,
42438
- item.created_at,
42439
- item.updated_at
42554
+ newSessionId,
42555
+ turn.user_prompt,
42556
+ turn.agent_response,
42557
+ turn.thoughts,
42558
+ turn.token_usage,
42559
+ (turn.external_turn_id && turnIds.get(turn.external_turn_id)) ?? turn.external_turn_id,
42560
+ turn.status,
42561
+ turn.error,
42562
+ turn.attachments,
42563
+ turn.origin ?? null,
42564
+ turn.origin_name ?? null,
42565
+ turn.created_at,
42566
+ turn.updated_at
42440
42567
  );
42441
- }
42442
- }
42443
- const provider = getProvider(session.runtime_type);
42444
- if (provider.forkSession) {
42445
- const targetTurnFull = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turn_id);
42446
- try {
42447
- const forkedId = await provider.forkSession(session, targetTurnFull);
42448
- if (forkedId) {
42449
- db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(forkedId, now, newSessionId);
42568
+ const itemRows = db2.prepare("SELECT * FROM items WHERE turn_id = ? ORDER BY created_at ASC").all(turn.id);
42569
+ for (const item of itemRows) {
42570
+ const newItemId = v4_default();
42571
+ db2.prepare(
42572
+ `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
42573
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
42574
+ ).run(
42575
+ newItemId,
42576
+ newTurnId,
42577
+ item.external_item_id,
42578
+ item.type,
42579
+ item.data,
42580
+ item.status,
42581
+ item.created_at,
42582
+ item.updated_at
42583
+ );
42450
42584
  }
42451
- } catch (forkError) {
42452
- db2.prepare("DELETE FROM sessions WHERE id = ?").run(newSessionId);
42453
- throw forkError;
42454
42585
  }
42455
- }
42586
+ })();
42456
42587
  const newSession = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(newSessionId);
42457
42588
  return newSession;
42458
42589
  }
@@ -119686,7 +119817,7 @@ function threadParams(session, cwd, browserInstructions) {
119686
119817
  cwd,
119687
119818
  approvalPolicy: "never",
119688
119819
  sandbox: sandboxType(config3),
119689
- model: session.model ?? void 0,
119820
+ model: session.model || void 0,
119690
119821
  config: threadConfig(config3),
119691
119822
  ...threadInstructionParams(cwd, browserInstructions)
119692
119823
  };
@@ -120225,8 +120356,8 @@ async function sendTurnRequest(session, entry, threadId, request) {
120225
120356
  input: request.input,
120226
120357
  approvalPolicy: "never",
120227
120358
  ...policy ? { sandboxPolicy: policy } : {},
120228
- model: session.model ?? void 0,
120229
- effort: session.model_reasoning_effort ?? void 0
120359
+ model: session.model || void 0,
120360
+ effort: session.model_reasoning_effort || void 0
120230
120361
  });
120231
120362
  return result.turn.id;
120232
120363
  }
@@ -120666,10 +120797,19 @@ var EFFORT_LABELS = {
120666
120797
  max: "Max",
120667
120798
  ultra: "Ultra"
120668
120799
  };
120800
+ var MODEL_LIST_MAX_PAGES = 20;
120669
120801
  async function getModels() {
120670
120802
  try {
120671
- const result = await getSharedAppServer().request("model/list", {});
120672
- return (result.data ?? []).map((m) => ({
120803
+ const server = getSharedAppServer();
120804
+ const listed = [];
120805
+ let cursor = null;
120806
+ for (let page = 0; page < MODEL_LIST_MAX_PAGES; page++) {
120807
+ const result = await server.request("model/list", cursor ? { cursor } : {});
120808
+ listed.push(...result.data ?? []);
120809
+ cursor = result.nextCursor ?? null;
120810
+ if (!cursor) break;
120811
+ }
120812
+ return listed.filter((m) => !m.hidden).map((m) => ({
120673
120813
  slug: m.id,
120674
120814
  displayName: m.displayName,
120675
120815
  description: m.description,
@@ -120686,15 +120826,6 @@ async function getModels() {
120686
120826
  async function getCommands() {
120687
120827
  return CODEX_COMMANDS;
120688
120828
  }
120689
- function forkPoint(db2, sessionId, target) {
120690
- const row = db2.prepare(
120691
- `SELECT external_turn_id FROM turns
120692
- WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
120693
- AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
120694
- ORDER BY created_at DESC, rowid DESC LIMIT 1`
120695
- ).get(sessionId, target.id, target.created_at);
120696
- return row?.external_turn_id ?? null;
120697
- }
120698
120829
  async function forkSession(session, targetTurn) {
120699
120830
  const threadId = session.external_thread_id;
120700
120831
  if (!threadId) return null;
@@ -121213,7 +121344,7 @@ var codexProvider = {
121213
121344
  };
121214
121345
 
121215
121346
  // src/claude/claude-provider.ts
121216
- import { query, forkSession as sdkForkSession } from "@anthropic-ai/claude-agent-sdk";
121347
+ import { query, forkSession as sdkForkSession, importSessionToStore } from "@anthropic-ai/claude-agent-sdk";
121217
121348
  import { readFileSync as readFileSync4 } from "fs";
121218
121349
  import { tmpdir } from "os";
121219
121350
  import { join as join5 } from "path";
@@ -121704,8 +121835,9 @@ var PromptQueue = class {
121704
121835
  var CLI_OVERRIDE = process.env.CLAUDE_BIN ? { pathToClaudeCodeExecutable: process.env.CLAUDE_BIN } : {};
121705
121836
  var sessionMap2 = /* @__PURE__ */ new Map();
121706
121837
  var titleGenerating2 = /* @__PURE__ */ new Set();
121707
- var cachedModels = null;
121708
- var cachedCommands = null;
121838
+ var MODELS_TTL_MS = 10 * 6e4;
121839
+ var catalog = null;
121840
+ var catalogLoad = null;
121709
121841
  var thinkingAccumulator = /* @__PURE__ */ new Map();
121710
121842
  var streamingMessageIds = /* @__PURE__ */ new Map();
121711
121843
  var widgetStreams = /* @__PURE__ */ new WeakMap();
@@ -121973,7 +122105,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, ad
121973
122105
  }
121974
122106
  const options = {
121975
122107
  cwd,
121976
- model: session.model ?? void 0,
122108
+ model: session.model || void 0,
121977
122109
  permissionMode: "bypassPermissions",
121978
122110
  allowDangerouslySkipPermissions: true,
121979
122111
  includePartialMessages: true,
@@ -122183,6 +122315,7 @@ function openPeerTurn(entry, sessionId, peer, db2) {
122183
122315
  }
122184
122316
  if (previous) streamingMessageIds.delete(previous);
122185
122317
  const threadId = entry.threadId ?? null;
122318
+ if (!threadId) commitRewind(db2, sessionId, clearThreadBranch2);
122186
122319
  const turnId = v4_default();
122187
122320
  const now = (/* @__PURE__ */ new Date()).toISOString();
122188
122321
  const inputIds = peer.uuid ? JSON.stringify([peer.uuid]) : null;
@@ -123019,48 +123152,63 @@ function sweepFinishedSessions(now = Date.now()) {
123019
123152
  async function setModel(sessionId, model) {
123020
123153
  const entry = sessionMap2.get(sessionId);
123021
123154
  if (!entry) return;
123022
- await entry.query.setModel(model);
123155
+ await entry.query.setModel(model || void 0);
123023
123156
  void refreshContext(entry, sessionId, getDb());
123024
123157
  }
123158
+ async function setEffort(sessionId, effort) {
123159
+ const entry = sessionMap2.get(sessionId);
123160
+ if (!entry) return;
123161
+ await entry.query.applyFlagSettings({ effortLevel: effort || null });
123162
+ }
123025
123163
  async function stopTask2(sessionId, taskId) {
123026
123164
  const entry = sessionMap2.get(sessionId);
123027
123165
  if (!entry) return;
123028
123166
  await entry.query.stopTask(taskId);
123029
123167
  }
123030
- async function getModels2() {
123031
- if (cachedModels) return cachedModels;
123032
- try {
123033
- const q = query({
123034
- prompt: "",
123035
- options: {
123036
- cwd: process.cwd(),
123037
- permissionMode: "bypassPermissions",
123038
- allowDangerouslySkipPermissions: true,
123039
- ...CLI_OVERRIDE
123168
+ function loadCatalog() {
123169
+ catalogLoad ??= (async () => {
123170
+ try {
123171
+ const q = query({
123172
+ prompt: "",
123173
+ options: {
123174
+ cwd: process.cwd(),
123175
+ permissionMode: "bypassPermissions",
123176
+ allowDangerouslySkipPermissions: true,
123177
+ ...CLI_OVERRIDE
123178
+ }
123179
+ });
123180
+ const initResult = await q.initializationResult();
123181
+ q.close();
123182
+ const models = (initResult.models ?? []).map((m) => ({
123183
+ slug: m.value,
123184
+ displayName: m.displayName,
123185
+ description: m.description,
123186
+ // The SDK names no default effort (its levels list starts at 'low'):
123187
+ // '' = the CLI's own default for the model.
123188
+ defaultReasoning: "",
123189
+ reasoningLevels: (m.supportedEffortLevels ?? []).map((e) => ({
123190
+ effort: e,
123191
+ label: EFFORT_LABELS2[e] ?? e
123192
+ }))
123193
+ }));
123194
+ if (models.length > 0) {
123195
+ catalog = { models, commands: mapSdkCommands(initResult.commands ?? []), at: Date.now() };
123040
123196
  }
123041
- });
123042
- const initResult = await q.initializationResult();
123043
- q.close();
123044
- cachedCommands = mapSdkCommands(initResult.commands ?? []);
123045
- cachedModels = (initResult.models ?? []).map((m) => ({
123046
- slug: m.value,
123047
- displayName: m.displayName,
123048
- description: m.description,
123049
- defaultReasoning: m.supportedEffortLevels?.[0] ?? "medium",
123050
- reasoningLevels: (m.supportedEffortLevels ?? []).map((e) => ({
123051
- effort: e,
123052
- label: EFFORT_LABELS2[e] ?? e
123053
- }))
123054
- }));
123055
- return cachedModels;
123056
- } catch {
123057
- return [];
123058
- }
123197
+ } catch {
123198
+ } finally {
123199
+ catalogLoad = null;
123200
+ }
123201
+ })();
123202
+ return catalogLoad;
123203
+ }
123204
+ async function getModels2() {
123205
+ if (!catalog) await loadCatalog();
123206
+ else if (Date.now() - catalog.at > MODELS_TTL_MS) void loadCatalog();
123207
+ return catalog?.models ?? [];
123059
123208
  }
123060
123209
  async function getCommands2() {
123061
- if (cachedCommands) return cachedCommands;
123062
- await getModels2();
123063
- return cachedCommands ?? [];
123210
+ if (!catalog) await loadCatalog();
123211
+ return catalog?.commands ?? [];
123064
123212
  }
123065
123213
  function mapSdkCommands(commands) {
123066
123214
  return commands.map((c) => ({
@@ -123248,16 +123396,32 @@ async function summarizeClaudeThread(session, thread, transcript, directives) {
123248
123396
  }
123249
123397
  async function forkClaudeSession(session, targetTurn) {
123250
123398
  if (!session.external_thread_id) return null;
123251
- try {
123252
- const result = await sdkForkSession(session.external_thread_id, {
123253
- dir: session.cwd ?? process.cwd(),
123254
- ...targetTurn.external_turn_id ? { upToMessageId: targetTurn.external_turn_id } : {}
123255
- });
123256
- return result.sessionId;
123257
- } catch (err) {
123258
- console.error("[claude] forkSession failed:", err);
123259
- return null;
123399
+ const upToMessageId = forkPoint(getDb(), session.id, targetTurn);
123400
+ if (!upToMessageId) return null;
123401
+ const result = await sdkForkSession(session.external_thread_id, {
123402
+ dir: session.cwd ?? process.cwd(),
123403
+ upToMessageId
123404
+ });
123405
+ return result.sessionId;
123406
+ }
123407
+ async function forkedTurnIds(session, forkedId) {
123408
+ const entries = [];
123409
+ await importSessionToStore(
123410
+ forkedId,
123411
+ {
123412
+ append: async (_key, batch) => {
123413
+ entries.push(...batch);
123414
+ },
123415
+ load: async () => null
123416
+ },
123417
+ { dir: session.cwd ?? process.cwd(), includeSubagents: false }
123418
+ );
123419
+ const ids = /* @__PURE__ */ new Map();
123420
+ for (const entry of entries) {
123421
+ const source = entry.forkedFrom?.messageUuid;
123422
+ if (typeof source === "string" && entry.uuid) ids.set(source, entry.uuid);
123260
123423
  }
123424
+ return ids;
123261
123425
  }
123262
123426
  var REPLAY_WAIT_MS2 = 3e4;
123263
123427
  function startReplay(entry) {
@@ -123376,8 +123540,15 @@ function describeExit2(exit) {
123376
123540
  function deadEntry(session, row) {
123377
123541
  const gone = () => Promise.reject(new Error("the CLI is gone"));
123378
123542
  const entry = {
123379
- query: { getContextUsage: gone, interrupt: gone, setModel: gone, stopTask: gone, close: () => {
123380
- } },
123543
+ query: {
123544
+ getContextUsage: gone,
123545
+ interrupt: gone,
123546
+ setModel: gone,
123547
+ applyFlagSettings: gone,
123548
+ stopTask: gone,
123549
+ close: () => {
123550
+ }
123551
+ },
123381
123552
  sessionId: row.external_id,
123382
123553
  turnId: row.turn_id,
123383
123554
  cwd: session.cwd ?? process.cwd(),
@@ -123476,8 +123647,10 @@ var claudeProvider = {
123476
123647
  getModels: getModels2,
123477
123648
  getCommands: getCommands2,
123478
123649
  forkSession: forkClaudeSession,
123650
+ forkedTurnIds,
123479
123651
  summarizeThread: summarizeClaudeThread,
123480
123652
  setModel,
123653
+ setEffort,
123481
123654
  stopTask: stopTask2,
123482
123655
  listBackgroundTasks: listBackgroundTasks2,
123483
123656
  resumeInterruptedTurn: resumeInterruptedTurn2,
@@ -124780,7 +124953,7 @@ async function ensureSession(session, client, baseUrl) {
124780
124953
  repoburgSessionId: session.external_thread_id,
124781
124954
  client,
124782
124955
  baseUrl,
124783
- modelId: session.model ?? null,
124956
+ modelId: session.model || null,
124784
124957
  // undefined forces a re-push on the next turn — heals sessions created
124785
124958
  // before unsafe effort values (e.g. ollama xhigh) were clamped.
124786
124959
  reasoningEffort: void 0,
@@ -124795,7 +124968,7 @@ async function ensureSession(session, client, baseUrl) {
124795
124968
  const mappedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
124796
124969
  const created = await client.createSession({
124797
124970
  session_title: session.title ?? void 0,
124798
- model_id: session.model ?? void 0,
124971
+ model_id: session.model || void 0,
124799
124972
  reasoning_effort: mappedEffort
124800
124973
  });
124801
124974
  const db2 = getDb();
@@ -124810,7 +124983,7 @@ async function ensureSession(session, client, baseUrl) {
124810
124983
  repoburgSessionId: created.id,
124811
124984
  client,
124812
124985
  baseUrl,
124813
- modelId: session.model ?? null,
124986
+ modelId: session.model || null,
124814
124987
  reasoningEffort: mappedEffort,
124815
124988
  threadId: null,
124816
124989
  contextWindow: null,
@@ -124830,7 +125003,7 @@ async function ensureThreadSession(session, turn, client, baseUrl) {
124830
125003
  if (!runtimeId) {
124831
125004
  const created = await client.createSession({
124832
125005
  session_title: session.title ? `Discussion: ${session.title}` : "Discussion",
124833
- model_id: session.model ?? void 0,
125006
+ model_id: session.model || void 0,
124834
125007
  reasoning_effort: mapReasoningEffort(session.model, session.model_reasoning_effort)
124835
125008
  });
124836
125009
  runtimeId = created.id;
@@ -124846,7 +125019,7 @@ async function ensureThreadSession(session, turn, client, baseUrl) {
124846
125019
  repoburgSessionId: runtimeId,
124847
125020
  client,
124848
125021
  baseUrl,
124849
- modelId: session.model ?? null,
125022
+ modelId: session.model || null,
124850
125023
  reasoningEffort: void 0,
124851
125024
  // re-pushed on the first thread turn
124852
125025
  threadId: turn.thread_id,
@@ -125036,7 +125209,7 @@ async function startTurn4(session, turn) {
125036
125209
  entry.baseUrl = baseUrl;
125037
125210
  entry.client = client;
125038
125211
  }
125039
- const wantedModel = session.model ?? null;
125212
+ const wantedModel = session.model || null;
125040
125213
  const wantedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
125041
125214
  if (wantedModel !== entry.modelId || wantedEffort !== entry.reasoningEffort) {
125042
125215
  try {