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
  }
@@ -41914,6 +41917,80 @@ function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnrev
41914
41917
  }
41915
41918
  }
41916
41919
 
41920
+ // src/routes/rewind-state.ts
41921
+ function forkPoint(db2, sessionId, target) {
41922
+ const row = db2.prepare(
41923
+ `SELECT external_turn_id FROM turns
41924
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
41925
+ AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
41926
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`
41927
+ ).get(sessionId, target.id, target.created_at);
41928
+ return row?.external_turn_id ?? null;
41929
+ }
41930
+ function snapshotTurnIds(db2, sessionId) {
41931
+ const rows = db2.prepare("SELECT id, external_turn_id FROM turns WHERE session_id = ? AND thread_id IS NULL").all(sessionId);
41932
+ return JSON.stringify(Object.fromEntries(rows.map((r) => [r.id, r.external_turn_id])));
41933
+ }
41934
+ function restoreTurnIds(db2, sessionId, snapshot) {
41935
+ if (!snapshot) return;
41936
+ let ids;
41937
+ try {
41938
+ ids = JSON.parse(snapshot);
41939
+ } catch {
41940
+ return;
41941
+ }
41942
+ const update = db2.prepare("UPDATE turns SET external_turn_id = ? WHERE id = ? AND session_id = ?");
41943
+ for (const [turnId, externalId] of Object.entries(ids)) update.run(externalId, turnId, sessionId);
41944
+ }
41945
+ function applyTurnIdMap(db2, sessionId, map2, upToCreatedAt = null) {
41946
+ if (map2.size === 0) return;
41947
+ const rows = db2.prepare(
41948
+ `SELECT id, external_turn_id FROM turns
41949
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL` + (upToCreatedAt ? " AND created_at <= ?" : "")
41950
+ ).all(...upToCreatedAt ? [sessionId, upToCreatedAt] : [sessionId]);
41951
+ const update = db2.prepare("UPDATE turns SET external_turn_id = ? WHERE id = ?");
41952
+ for (const row of rows) {
41953
+ const mapped = map2.get(row.external_turn_id);
41954
+ if (mapped) update.run(mapped, row.id);
41955
+ }
41956
+ }
41957
+ function dropRewoundTurns(db2, sessionId) {
41958
+ const session = db2.prepare("SELECT rewound_at_turn_id FROM sessions WHERE id = ?").get(sessionId);
41959
+ if (!session?.rewound_at_turn_id) return null;
41960
+ const target = db2.prepare("SELECT created_at FROM turns WHERE id = ?").get(session.rewound_at_turn_id);
41961
+ let threadIds = [];
41962
+ db2.transaction(() => {
41963
+ if (target) {
41964
+ const hidden = "SELECT id FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at > ?";
41965
+ 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);
41966
+ for (const threadId of threadIds) {
41967
+ db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE thread_id = ?)").run(threadId);
41968
+ db2.prepare("DELETE FROM turns WHERE thread_id = ?").run(threadId);
41969
+ db2.prepare("DELETE FROM discussion_threads WHERE id = ?").run(threadId);
41970
+ }
41971
+ db2.prepare(`DELETE FROM items WHERE turn_id IN (${hidden})`).run(sessionId, target.created_at);
41972
+ db2.prepare("DELETE FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at > ?").run(
41973
+ sessionId,
41974
+ target.created_at
41975
+ );
41976
+ }
41977
+ db2.prepare(
41978
+ "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_turn_ids = NULL, updated_at = ? WHERE id = ?"
41979
+ ).run((/* @__PURE__ */ new Date()).toISOString(), sessionId);
41980
+ })();
41981
+ return { threadIds };
41982
+ }
41983
+ function commitRewind(db2, sessionId, clearThreadBranch4) {
41984
+ const dropped = dropRewoundTurns(db2, sessionId);
41985
+ if (!dropped) return;
41986
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
41987
+ broadcast("session:updated", { session });
41988
+ for (const threadId of dropped.threadIds) {
41989
+ clearThreadBranch4?.(sessionId, threadId);
41990
+ broadcast("thread:deleted", { sessionId, threadId });
41991
+ }
41992
+ }
41993
+
41917
41994
  // src/routes/session-touch.ts
41918
41995
  function markSessionTouched(db2, sessionId) {
41919
41996
  const { changes } = db2.prepare("UPDATE sessions SET user_touched = 1 WHERE id = ? AND user_touched = 0").run(sessionId);
@@ -41923,17 +42000,20 @@ function markSessionTouched(db2, sessionId) {
41923
42000
  }
41924
42001
 
41925
42002
  // src/routes/session-actions.ts
42003
+ function blankToNull(value) {
42004
+ return value === "" ? null : value;
42005
+ }
41926
42006
  function createSession(db2, input) {
41927
42007
  const {
41928
42008
  title = null,
41929
42009
  runtime_type = "codex",
41930
- model = null,
41931
- model_reasoning_effort = null,
41932
42010
  cwd = null,
41933
42011
  runtime_config = null,
41934
42012
  origin_app_id = null,
41935
42013
  origin_app_workspace = null
41936
42014
  } = input;
42015
+ const model = blankToNull(input.model ?? null);
42016
+ const model_reasoning_effort = blankToNull(input.model_reasoning_effort ?? null);
41937
42017
  const id = v4_default();
41938
42018
  const now = (/* @__PURE__ */ new Date()).toISOString();
41939
42019
  const maxOrder = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd ?? null);
@@ -41965,6 +42045,7 @@ var SessionBusyError = class extends Error {
41965
42045
  function startTurn(db2, session, { prompt, attachments, originAppId }) {
41966
42046
  if (isSessionBusy(db2, session, { mainOnly: true })) throw new SessionBusyError();
41967
42047
  const provider = getProvider(session.runtime_type);
42048
+ commitRewind(db2, session.id, provider.clearThreadBranch?.bind(provider));
41968
42049
  const turnId = v4_default();
41969
42050
  const now = (/* @__PURE__ */ new Date()).toISOString();
41970
42051
  const attachmentsJson = attachments && attachments.length > 0 ? JSON.stringify(attachments) : null;
@@ -42143,19 +42224,29 @@ async function registerSessionRoutes(fastify) {
42143
42224
  }
42144
42225
  }, async (request, reply) => {
42145
42226
  const { id } = request.params;
42146
- const { title, lifecycle, has_unreviewed, model, model_reasoning_effort, runtime_config, runtime_type, cwd, starred } = request.body || {};
42227
+ const body = request.body || {};
42228
+ const { title, lifecycle, has_unreviewed, runtime_config, runtime_type, cwd, starred } = body;
42229
+ const model = body.model === void 0 ? void 0 : blankToNull(body.model);
42230
+ const model_reasoning_effort = body.model_reasoning_effort === void 0 ? void 0 : blankToNull(body.model_reasoning_effort);
42147
42231
  const db2 = getDb();
42148
42232
  const existing = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42149
42233
  if (!existing) {
42150
42234
  return reply.code(404).send({ error: "Session not found" });
42151
42235
  }
42152
- if (runtime_type !== void 0 && runtime_type !== existing.runtime_type && existing.is_running) {
42153
- return reply.code(409).send({ error: "Cannot switch provider while a turn is running" });
42236
+ const providerChanged = runtime_type !== void 0 && runtime_type !== existing.runtime_type;
42237
+ if (providerChanged) {
42238
+ if (existing.is_running) {
42239
+ return reply.code(409).send({ error: "Cannot switch provider while a turn is running" });
42240
+ }
42241
+ if (db2.prepare("SELECT 1 FROM turns WHERE session_id = ? LIMIT 1").get(id)) {
42242
+ return reply.code(409).send({
42243
+ error: "The provider cannot change once the session has turns \u2014 start a new session to use another provider"
42244
+ });
42245
+ }
42154
42246
  }
42155
42247
  const now = (/* @__PURE__ */ new Date()).toISOString();
42156
42248
  const updates = ["updated_at = ?"];
42157
42249
  const params = [now];
42158
- let providerChanged = false;
42159
42250
  if (title !== void 0) {
42160
42251
  updates.push("title = ?");
42161
42252
  params.push(title);
@@ -42172,8 +42263,7 @@ async function registerSessionRoutes(fastify) {
42172
42263
  updates.push("starred = ?");
42173
42264
  params.push(starred);
42174
42265
  }
42175
- if (runtime_type !== void 0 && runtime_type !== existing.runtime_type) {
42176
- providerChanged = true;
42266
+ if (providerChanged) {
42177
42267
  updates.push("runtime_type = ?");
42178
42268
  params.push(runtime_type);
42179
42269
  if (model === void 0) {
@@ -42211,6 +42301,12 @@ async function registerSessionRoutes(fastify) {
42211
42301
  if (model_reasoning_effort !== void 0) {
42212
42302
  updates.push("model_reasoning_effort = ?");
42213
42303
  params.push(model_reasoning_effort);
42304
+ if (model_reasoning_effort !== existing.model_reasoning_effort && !providerChanged) {
42305
+ const provider = getProvider(existing.runtime_type);
42306
+ provider.setEffort?.(id, model_reasoning_effort).catch((err) => {
42307
+ console.error(`[patch] setEffort failed for session ${id}:`, err);
42308
+ });
42309
+ }
42214
42310
  }
42215
42311
  if (runtime_config !== void 0) {
42216
42312
  updates.push("runtime_config = ?");
@@ -42219,10 +42315,14 @@ async function registerSessionRoutes(fastify) {
42219
42315
  db2.prepare(`UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`).run(...params, id);
42220
42316
  if (title !== void 0) markSessionTouched(db2, id);
42221
42317
  if (providerChanged || workspaceChanged) {
42222
- if (existing.external_thread_id) {
42223
- 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);
42224
- }
42225
- getProvider(existing.runtime_type).clearThread(id);
42318
+ const provider = getProvider(existing.runtime_type);
42319
+ commitRewind(db2, id, provider.clearThreadBranch?.bind(provider));
42320
+ db2.prepare(
42321
+ `UPDATE sessions SET external_thread_id = NULL, rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL,
42322
+ pre_rewind_turn_ids = NULL, context_usage = NULL, updated_at = ? WHERE id = ?`
42323
+ ).run(now, id);
42324
+ db2.prepare("UPDATE turns SET external_turn_id = NULL WHERE session_id = ? AND thread_id IS NULL").run(id);
42325
+ provider.clearThread(id);
42226
42326
  }
42227
42327
  const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42228
42328
  broadcast("session:updated", { session });
@@ -42259,6 +42359,9 @@ async function registerSessionRoutes(fastify) {
42259
42359
  if (!targetTurnFull) {
42260
42360
  return reply.code(404).send({ error: "Turn not found" });
42261
42361
  }
42362
+ if (targetTurnFull.thread_id != null) {
42363
+ return reply.code(400).send({ error: "Cannot rewind to a discussion thread turn" });
42364
+ }
42262
42365
  const provider = getProvider(session.runtime_type);
42263
42366
  if (provider.rewindRuntime) {
42264
42367
  await provider.rewindRuntime(session, targetTurnFull);
@@ -42271,37 +42374,48 @@ async function registerSessionRoutes(fastify) {
42271
42374
  targetTurnFull.created_at
42272
42375
  );
42273
42376
  db2.prepare(
42274
- "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, updated_at = ? WHERE id = ?"
42377
+ "UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, pre_rewind_turn_ids = NULL, updated_at = ? WHERE id = ?"
42275
42378
  ).run(now2, id);
42276
42379
  markSessionTouched(db2, id);
42277
42380
  const truncated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
42278
42381
  return truncated;
42279
42382
  }
42280
- const now = (/* @__PURE__ */ new Date()).toISOString();
42281
- if (!session.pre_rewind_thread_id && session.external_thread_id) {
42282
- db2.prepare(
42283
- "UPDATE sessions SET rewound_at_turn_id = ?, pre_rewind_thread_id = ?, updated_at = ? WHERE id = ?"
42284
- ).run(turn_id, session.external_thread_id, now, id);
42285
- console.log(`[rewind] saved pre_rewind_thread_id=${session.external_thread_id} for session ${id}`);
42286
- } else {
42287
- db2.prepare(
42288
- "UPDATE sessions SET rewound_at_turn_id = ?, updated_at = ? WHERE id = ?"
42289
- ).run(turn_id, now, id);
42290
- console.log(`[rewind] pre_rewind_thread_id already set (${session.pre_rewind_thread_id}) or external_thread_id is null for session ${id}`);
42291
- }
42383
+ let forkedId = session.external_thread_id;
42384
+ let turnIds = /* @__PURE__ */ new Map();
42292
42385
  if (provider.forkSession) {
42293
42386
  try {
42294
- const forkedId = await provider.forkSession(session, targetTurnFull);
42295
- if (forkedId) {
42296
- db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(forkedId, now, id);
42297
- console.log(`[rewind] forked to ${forkedId} for session ${id}`);
42298
- } else {
42299
- console.warn(`[rewind] forkSession returned null for session ${id} (external_thread_id=${session.external_thread_id}, upToMessageId=${targetTurnFull.external_turn_id})`);
42300
- }
42387
+ forkedId = await provider.forkSession(session, targetTurnFull);
42301
42388
  } catch (err) {
42302
42389
  console.error(`[rewind] forkSession threw for session ${id}:`, err);
42390
+ return reply.code(409).send({
42391
+ error: `Cannot rewind to this turn: the runtime could not fork its conversation there (${err.message})`
42392
+ });
42393
+ }
42394
+ if (forkedId && provider.forkedTurnIds) {
42395
+ turnIds = await provider.forkedTurnIds(session, forkedId).catch((err) => {
42396
+ console.warn(`[rewind] could not read the turn ids of fork ${forkedId}:`, err);
42397
+ return /* @__PURE__ */ new Map();
42398
+ });
42303
42399
  }
42304
42400
  }
42401
+ const now = (/* @__PURE__ */ new Date()).toISOString();
42402
+ db2.transaction(() => {
42403
+ if (!session.rewound_at_turn_id) {
42404
+ db2.prepare("UPDATE sessions SET pre_rewind_thread_id = ?, pre_rewind_turn_ids = ? WHERE id = ?").run(
42405
+ session.external_thread_id,
42406
+ snapshotTurnIds(db2, id),
42407
+ id
42408
+ );
42409
+ }
42410
+ db2.prepare("UPDATE sessions SET rewound_at_turn_id = ?, external_thread_id = ?, updated_at = ? WHERE id = ?").run(
42411
+ turn_id,
42412
+ forkedId,
42413
+ now,
42414
+ id
42415
+ );
42416
+ applyTurnIdMap(db2, id, turnIds, targetTurnFull.created_at);
42417
+ })();
42418
+ console.log(`[rewind] session ${id} rewound to ${turn_id}, runtime thread ${forkedId ?? "(none)"}`);
42305
42419
  provider.clearThread(id);
42306
42420
  markSessionTouched(db2, id);
42307
42421
  const updated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
@@ -42323,10 +42437,17 @@ async function registerSessionRoutes(fastify) {
42323
42437
  error: "Restore is not available for repoburg sessions \u2014 the rewind permanently deleted the runtime history."
42324
42438
  });
42325
42439
  }
42440
+ if (session.is_running) {
42441
+ return reply.code(409).send({ error: "Cannot restore while a turn is running" });
42442
+ }
42326
42443
  const now = (/* @__PURE__ */ new Date()).toISOString();
42327
- db2.prepare(
42328
- "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 = ?"
42329
- ).run(now, id);
42444
+ db2.transaction(() => {
42445
+ restoreTurnIds(db2, id, session.pre_rewind_turn_ids);
42446
+ db2.prepare(
42447
+ `UPDATE sessions SET rewound_at_turn_id = NULL, pre_rewind_thread_id = NULL, pre_rewind_turn_ids = NULL,
42448
+ external_thread_id = COALESCE(pre_rewind_thread_id, external_thread_id), updated_at = ? WHERE id = ?`
42449
+ ).run(now, id);
42450
+ })();
42330
42451
  getProvider(session.runtime_type).clearThread(id);
42331
42452
  markSessionTouched(db2, id);
42332
42453
  const updated = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
@@ -42364,78 +42485,88 @@ async function registerSessionRoutes(fastify) {
42364
42485
  if (targetTurn.thread_id != null) {
42365
42486
  return reply.code(400).send({ error: "Cannot branch from a discussion thread turn" });
42366
42487
  }
42488
+ const provider = getProvider(session.runtime_type);
42489
+ let forkedId = null;
42490
+ let turnIds = /* @__PURE__ */ new Map();
42491
+ if (provider.forkSession) {
42492
+ const targetTurnFull = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turn_id);
42493
+ try {
42494
+ forkedId = await provider.forkSession(session, targetTurnFull);
42495
+ } catch (err) {
42496
+ console.error(`[branch] forkSession threw for session ${id}:`, err);
42497
+ return reply.code(409).send({
42498
+ error: `Cannot branch from this turn: the runtime could not fork its conversation there (${err.message})`
42499
+ });
42500
+ }
42501
+ if (forkedId && provider.forkedTurnIds) {
42502
+ turnIds = await provider.forkedTurnIds(session, forkedId).catch((err) => {
42503
+ console.warn(`[branch] could not read the turn ids of fork ${forkedId}:`, err);
42504
+ return /* @__PURE__ */ new Map();
42505
+ });
42506
+ }
42507
+ }
42367
42508
  const newSessionId = v4_default();
42368
42509
  const now = (/* @__PURE__ */ new Date()).toISOString();
42369
42510
  const newTitle = title || `Branch of ${session.title || session.id.slice(0, 8)}`;
42370
- db2.prepare(
42371
- `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)
42372
- VALUES (?, ?, ?, ?, ?, ?, NULL, 'active', 0, 'working', 0, ?, ?, ?)`
42373
- ).run(
42374
- newSessionId,
42375
- newTitle,
42376
- session.runtime_type,
42377
- session.model,
42378
- session.model_reasoning_effort,
42379
- session.cwd,
42380
- now,
42381
- now,
42382
- session.runtime_config
42383
- );
42384
- const turnRows = db2.prepare(
42385
- "SELECT * FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at <= ? ORDER BY created_at ASC"
42386
- ).all(id, targetTurn.created_at);
42387
- for (const turn of turnRows) {
42388
- const newTurnId = v4_default();
42511
+ db2.transaction(() => {
42389
42512
  db2.prepare(
42390
- `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)
42391
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42513
+ `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)
42514
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'active', 0, 'working', 0, ?, ?, ?)`
42392
42515
  ).run(
42393
- newTurnId,
42394
42516
  newSessionId,
42395
- turn.user_prompt,
42396
- turn.agent_response,
42397
- turn.thoughts,
42398
- turn.token_usage,
42399
- turn.external_turn_id,
42400
- turn.status,
42401
- turn.error,
42402
- turn.attachments,
42403
- turn.origin ?? null,
42404
- turn.origin_name ?? null,
42405
- turn.created_at,
42406
- turn.updated_at
42517
+ newTitle,
42518
+ session.runtime_type,
42519
+ session.model,
42520
+ session.model_reasoning_effort,
42521
+ session.cwd,
42522
+ forkedId,
42523
+ now,
42524
+ now,
42525
+ session.runtime_config
42407
42526
  );
42408
- const itemRows = db2.prepare("SELECT * FROM items WHERE turn_id = ? ORDER BY created_at ASC").all(turn.id);
42409
- for (const item of itemRows) {
42410
- const newItemId = v4_default();
42527
+ const turnRows = db2.prepare(
42528
+ "SELECT * FROM turns WHERE session_id = ? AND thread_id IS NULL AND created_at <= ? ORDER BY created_at ASC"
42529
+ ).all(id, targetTurn.created_at);
42530
+ for (const turn of turnRows) {
42531
+ const newTurnId = v4_default();
42411
42532
  db2.prepare(
42412
- `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
42413
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
42533
+ `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)
42534
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42414
42535
  ).run(
42415
- newItemId,
42416
42536
  newTurnId,
42417
- item.external_item_id,
42418
- item.type,
42419
- item.data,
42420
- item.status,
42421
- item.created_at,
42422
- item.updated_at
42537
+ newSessionId,
42538
+ turn.user_prompt,
42539
+ turn.agent_response,
42540
+ turn.thoughts,
42541
+ turn.token_usage,
42542
+ (turn.external_turn_id && turnIds.get(turn.external_turn_id)) ?? turn.external_turn_id,
42543
+ turn.status,
42544
+ turn.error,
42545
+ turn.attachments,
42546
+ turn.origin ?? null,
42547
+ turn.origin_name ?? null,
42548
+ turn.created_at,
42549
+ turn.updated_at
42423
42550
  );
42424
- }
42425
- }
42426
- const provider = getProvider(session.runtime_type);
42427
- if (provider.forkSession) {
42428
- const targetTurnFull = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turn_id);
42429
- try {
42430
- const forkedId = await provider.forkSession(session, targetTurnFull);
42431
- if (forkedId) {
42432
- db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(forkedId, now, newSessionId);
42551
+ const itemRows = db2.prepare("SELECT * FROM items WHERE turn_id = ? ORDER BY created_at ASC").all(turn.id);
42552
+ for (const item of itemRows) {
42553
+ const newItemId = v4_default();
42554
+ db2.prepare(
42555
+ `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
42556
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
42557
+ ).run(
42558
+ newItemId,
42559
+ newTurnId,
42560
+ item.external_item_id,
42561
+ item.type,
42562
+ item.data,
42563
+ item.status,
42564
+ item.created_at,
42565
+ item.updated_at
42566
+ );
42433
42567
  }
42434
- } catch (forkError) {
42435
- db2.prepare("DELETE FROM sessions WHERE id = ?").run(newSessionId);
42436
- throw forkError;
42437
42568
  }
42438
- }
42569
+ })();
42439
42570
  const newSession = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(newSessionId);
42440
42571
  return newSession;
42441
42572
  }
@@ -119699,7 +119830,7 @@ function threadParams(session, cwd, browserInstructions) {
119699
119830
  cwd,
119700
119831
  approvalPolicy: "never",
119701
119832
  sandbox: sandboxType(config3),
119702
- model: session.model ?? void 0,
119833
+ model: session.model || void 0,
119703
119834
  config: threadConfig(config3),
119704
119835
  ...threadInstructionParams(cwd, browserInstructions)
119705
119836
  };
@@ -120238,8 +120369,8 @@ async function sendTurnRequest(session, entry, threadId, request) {
120238
120369
  input: request.input,
120239
120370
  approvalPolicy: "never",
120240
120371
  ...policy ? { sandboxPolicy: policy } : {},
120241
- model: session.model ?? void 0,
120242
- effort: session.model_reasoning_effort ?? void 0
120372
+ model: session.model || void 0,
120373
+ effort: session.model_reasoning_effort || void 0
120243
120374
  });
120244
120375
  return result.turn.id;
120245
120376
  }
@@ -120679,10 +120810,19 @@ var EFFORT_LABELS = {
120679
120810
  max: "Max",
120680
120811
  ultra: "Ultra"
120681
120812
  };
120813
+ var MODEL_LIST_MAX_PAGES = 20;
120682
120814
  async function getModels() {
120683
120815
  try {
120684
- const result = await getSharedAppServer().request("model/list", {});
120685
- return (result.data ?? []).map((m) => ({
120816
+ const server = getSharedAppServer();
120817
+ const listed = [];
120818
+ let cursor = null;
120819
+ for (let page = 0; page < MODEL_LIST_MAX_PAGES; page++) {
120820
+ const result = await server.request("model/list", cursor ? { cursor } : {});
120821
+ listed.push(...result.data ?? []);
120822
+ cursor = result.nextCursor ?? null;
120823
+ if (!cursor) break;
120824
+ }
120825
+ return listed.filter((m) => !m.hidden).map((m) => ({
120686
120826
  slug: m.id,
120687
120827
  displayName: m.displayName,
120688
120828
  description: m.description,
@@ -120699,15 +120839,6 @@ async function getModels() {
120699
120839
  async function getCommands() {
120700
120840
  return CODEX_COMMANDS;
120701
120841
  }
120702
- function forkPoint(db2, sessionId, target) {
120703
- const row = db2.prepare(
120704
- `SELECT external_turn_id FROM turns
120705
- WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
120706
- AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
120707
- ORDER BY created_at DESC, rowid DESC LIMIT 1`
120708
- ).get(sessionId, target.id, target.created_at);
120709
- return row?.external_turn_id ?? null;
120710
- }
120711
120842
  async function forkSession(session, targetTurn) {
120712
120843
  const threadId = session.external_thread_id;
120713
120844
  if (!threadId) return null;
@@ -121226,7 +121357,7 @@ var codexProvider = {
121226
121357
  };
121227
121358
 
121228
121359
  // src/claude/claude-provider.ts
121229
- import { query, forkSession as sdkForkSession } from "@anthropic-ai/claude-agent-sdk";
121360
+ import { query, forkSession as sdkForkSession, importSessionToStore } from "@anthropic-ai/claude-agent-sdk";
121230
121361
  import { readFileSync as readFileSync4 } from "fs";
121231
121362
  import { tmpdir } from "os";
121232
121363
  import { join as join5 } from "path";
@@ -121717,8 +121848,9 @@ var PromptQueue = class {
121717
121848
  var CLI_OVERRIDE = process.env.CLAUDE_BIN ? { pathToClaudeCodeExecutable: process.env.CLAUDE_BIN } : {};
121718
121849
  var sessionMap2 = /* @__PURE__ */ new Map();
121719
121850
  var titleGenerating2 = /* @__PURE__ */ new Set();
121720
- var cachedModels = null;
121721
- var cachedCommands = null;
121851
+ var MODELS_TTL_MS = 10 * 6e4;
121852
+ var catalog = null;
121853
+ var catalogLoad = null;
121722
121854
  var thinkingAccumulator = /* @__PURE__ */ new Map();
121723
121855
  var streamingMessageIds = /* @__PURE__ */ new Map();
121724
121856
  var widgetStreams = /* @__PURE__ */ new WeakMap();
@@ -121986,7 +122118,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, ad
121986
122118
  }
121987
122119
  const options = {
121988
122120
  cwd,
121989
- model: session.model ?? void 0,
122121
+ model: session.model || void 0,
121990
122122
  permissionMode: "bypassPermissions",
121991
122123
  allowDangerouslySkipPermissions: true,
121992
122124
  includePartialMessages: true,
@@ -122196,6 +122328,7 @@ function openPeerTurn(entry, sessionId, peer, db2) {
122196
122328
  }
122197
122329
  if (previous) streamingMessageIds.delete(previous);
122198
122330
  const threadId = entry.threadId ?? null;
122331
+ if (!threadId) commitRewind(db2, sessionId, clearThreadBranch2);
122199
122332
  const turnId = v4_default();
122200
122333
  const now = (/* @__PURE__ */ new Date()).toISOString();
122201
122334
  const inputIds = peer.uuid ? JSON.stringify([peer.uuid]) : null;
@@ -123032,48 +123165,63 @@ function sweepFinishedSessions(now = Date.now()) {
123032
123165
  async function setModel(sessionId, model) {
123033
123166
  const entry = sessionMap2.get(sessionId);
123034
123167
  if (!entry) return;
123035
- await entry.query.setModel(model);
123168
+ await entry.query.setModel(model || void 0);
123036
123169
  void refreshContext(entry, sessionId, getDb());
123037
123170
  }
123171
+ async function setEffort(sessionId, effort) {
123172
+ const entry = sessionMap2.get(sessionId);
123173
+ if (!entry) return;
123174
+ await entry.query.applyFlagSettings({ effortLevel: effort || null });
123175
+ }
123038
123176
  async function stopTask2(sessionId, taskId) {
123039
123177
  const entry = sessionMap2.get(sessionId);
123040
123178
  if (!entry) return;
123041
123179
  await entry.query.stopTask(taskId);
123042
123180
  }
123043
- async function getModels2() {
123044
- if (cachedModels) return cachedModels;
123045
- try {
123046
- const q = query({
123047
- prompt: "",
123048
- options: {
123049
- cwd: process.cwd(),
123050
- permissionMode: "bypassPermissions",
123051
- allowDangerouslySkipPermissions: true,
123052
- ...CLI_OVERRIDE
123181
+ function loadCatalog() {
123182
+ catalogLoad ??= (async () => {
123183
+ try {
123184
+ const q = query({
123185
+ prompt: "",
123186
+ options: {
123187
+ cwd: process.cwd(),
123188
+ permissionMode: "bypassPermissions",
123189
+ allowDangerouslySkipPermissions: true,
123190
+ ...CLI_OVERRIDE
123191
+ }
123192
+ });
123193
+ const initResult = await q.initializationResult();
123194
+ q.close();
123195
+ const models = (initResult.models ?? []).map((m) => ({
123196
+ slug: m.value,
123197
+ displayName: m.displayName,
123198
+ description: m.description,
123199
+ // The SDK names no default effort (its levels list starts at 'low'):
123200
+ // '' = the CLI's own default for the model.
123201
+ defaultReasoning: "",
123202
+ reasoningLevels: (m.supportedEffortLevels ?? []).map((e) => ({
123203
+ effort: e,
123204
+ label: EFFORT_LABELS2[e] ?? e
123205
+ }))
123206
+ }));
123207
+ if (models.length > 0) {
123208
+ catalog = { models, commands: mapSdkCommands(initResult.commands ?? []), at: Date.now() };
123053
123209
  }
123054
- });
123055
- const initResult = await q.initializationResult();
123056
- q.close();
123057
- cachedCommands = mapSdkCommands(initResult.commands ?? []);
123058
- cachedModels = (initResult.models ?? []).map((m) => ({
123059
- slug: m.value,
123060
- displayName: m.displayName,
123061
- description: m.description,
123062
- defaultReasoning: m.supportedEffortLevels?.[0] ?? "medium",
123063
- reasoningLevels: (m.supportedEffortLevels ?? []).map((e) => ({
123064
- effort: e,
123065
- label: EFFORT_LABELS2[e] ?? e
123066
- }))
123067
- }));
123068
- return cachedModels;
123069
- } catch {
123070
- return [];
123071
- }
123210
+ } catch {
123211
+ } finally {
123212
+ catalogLoad = null;
123213
+ }
123214
+ })();
123215
+ return catalogLoad;
123216
+ }
123217
+ async function getModels2() {
123218
+ if (!catalog) await loadCatalog();
123219
+ else if (Date.now() - catalog.at > MODELS_TTL_MS) void loadCatalog();
123220
+ return catalog?.models ?? [];
123072
123221
  }
123073
123222
  async function getCommands2() {
123074
- if (cachedCommands) return cachedCommands;
123075
- await getModels2();
123076
- return cachedCommands ?? [];
123223
+ if (!catalog) await loadCatalog();
123224
+ return catalog?.commands ?? [];
123077
123225
  }
123078
123226
  function mapSdkCommands(commands) {
123079
123227
  return commands.map((c) => ({
@@ -123261,16 +123409,32 @@ async function summarizeClaudeThread(session, thread, transcript, directives) {
123261
123409
  }
123262
123410
  async function forkClaudeSession(session, targetTurn) {
123263
123411
  if (!session.external_thread_id) return null;
123264
- try {
123265
- const result = await sdkForkSession(session.external_thread_id, {
123266
- dir: session.cwd ?? process.cwd(),
123267
- ...targetTurn.external_turn_id ? { upToMessageId: targetTurn.external_turn_id } : {}
123268
- });
123269
- return result.sessionId;
123270
- } catch (err) {
123271
- console.error("[claude] forkSession failed:", err);
123272
- return null;
123412
+ const upToMessageId = forkPoint(getDb(), session.id, targetTurn);
123413
+ if (!upToMessageId) return null;
123414
+ const result = await sdkForkSession(session.external_thread_id, {
123415
+ dir: session.cwd ?? process.cwd(),
123416
+ upToMessageId
123417
+ });
123418
+ return result.sessionId;
123419
+ }
123420
+ async function forkedTurnIds(session, forkedId) {
123421
+ const entries = [];
123422
+ await importSessionToStore(
123423
+ forkedId,
123424
+ {
123425
+ append: async (_key, batch) => {
123426
+ entries.push(...batch);
123427
+ },
123428
+ load: async () => null
123429
+ },
123430
+ { dir: session.cwd ?? process.cwd(), includeSubagents: false }
123431
+ );
123432
+ const ids = /* @__PURE__ */ new Map();
123433
+ for (const entry of entries) {
123434
+ const source = entry.forkedFrom?.messageUuid;
123435
+ if (typeof source === "string" && entry.uuid) ids.set(source, entry.uuid);
123273
123436
  }
123437
+ return ids;
123274
123438
  }
123275
123439
  var REPLAY_WAIT_MS2 = 3e4;
123276
123440
  function startReplay(entry) {
@@ -123389,8 +123553,15 @@ function describeExit2(exit) {
123389
123553
  function deadEntry(session, row) {
123390
123554
  const gone = () => Promise.reject(new Error("the CLI is gone"));
123391
123555
  const entry = {
123392
- query: { getContextUsage: gone, interrupt: gone, setModel: gone, stopTask: gone, close: () => {
123393
- } },
123556
+ query: {
123557
+ getContextUsage: gone,
123558
+ interrupt: gone,
123559
+ setModel: gone,
123560
+ applyFlagSettings: gone,
123561
+ stopTask: gone,
123562
+ close: () => {
123563
+ }
123564
+ },
123394
123565
  sessionId: row.external_id,
123395
123566
  turnId: row.turn_id,
123396
123567
  cwd: session.cwd ?? process.cwd(),
@@ -123489,8 +123660,10 @@ var claudeProvider = {
123489
123660
  getModels: getModels2,
123490
123661
  getCommands: getCommands2,
123491
123662
  forkSession: forkClaudeSession,
123663
+ forkedTurnIds,
123492
123664
  summarizeThread: summarizeClaudeThread,
123493
123665
  setModel,
123666
+ setEffort,
123494
123667
  stopTask: stopTask2,
123495
123668
  listBackgroundTasks: listBackgroundTasks2,
123496
123669
  resumeInterruptedTurn: resumeInterruptedTurn2,
@@ -124793,7 +124966,7 @@ async function ensureSession(session, client, baseUrl) {
124793
124966
  repoburgSessionId: session.external_thread_id,
124794
124967
  client,
124795
124968
  baseUrl,
124796
- modelId: session.model ?? null,
124969
+ modelId: session.model || null,
124797
124970
  // undefined forces a re-push on the next turn — heals sessions created
124798
124971
  // before unsafe effort values (e.g. ollama xhigh) were clamped.
124799
124972
  reasoningEffort: void 0,
@@ -124808,7 +124981,7 @@ async function ensureSession(session, client, baseUrl) {
124808
124981
  const mappedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
124809
124982
  const created = await client.createSession({
124810
124983
  session_title: session.title ?? void 0,
124811
- model_id: session.model ?? void 0,
124984
+ model_id: session.model || void 0,
124812
124985
  reasoning_effort: mappedEffort
124813
124986
  });
124814
124987
  const db2 = getDb();
@@ -124823,7 +124996,7 @@ async function ensureSession(session, client, baseUrl) {
124823
124996
  repoburgSessionId: created.id,
124824
124997
  client,
124825
124998
  baseUrl,
124826
- modelId: session.model ?? null,
124999
+ modelId: session.model || null,
124827
125000
  reasoningEffort: mappedEffort,
124828
125001
  threadId: null,
124829
125002
  contextWindow: null,
@@ -124843,7 +125016,7 @@ async function ensureThreadSession(session, turn, client, baseUrl) {
124843
125016
  if (!runtimeId) {
124844
125017
  const created = await client.createSession({
124845
125018
  session_title: session.title ? `Discussion: ${session.title}` : "Discussion",
124846
- model_id: session.model ?? void 0,
125019
+ model_id: session.model || void 0,
124847
125020
  reasoning_effort: mapReasoningEffort(session.model, session.model_reasoning_effort)
124848
125021
  });
124849
125022
  runtimeId = created.id;
@@ -124859,7 +125032,7 @@ async function ensureThreadSession(session, turn, client, baseUrl) {
124859
125032
  repoburgSessionId: runtimeId,
124860
125033
  client,
124861
125034
  baseUrl,
124862
- modelId: session.model ?? null,
125035
+ modelId: session.model || null,
124863
125036
  reasoningEffort: void 0,
124864
125037
  // re-pushed on the first thread turn
124865
125038
  threadId: turn.thread_id,
@@ -125049,7 +125222,7 @@ async function startTurn4(session, turn) {
125049
125222
  entry.baseUrl = baseUrl;
125050
125223
  entry.client = client;
125051
125224
  }
125052
- const wantedModel = session.model ?? null;
125225
+ const wantedModel = session.model || null;
125053
125226
  const wantedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
125054
125227
  if (wantedModel !== entry.modelId || wantedEffort !== entry.reasoningEffort) {
125055
125228
  try {