stitchkit 0.131.0 → 0.132.1

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
  3. package/dist/agent-executor/claude/limits.d.ts.map +1 -1
  4. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  5. package/dist/agent-executor/claude/transcript.d.ts +1 -1
  6. package/dist/agent-executor/claude/transcript.d.ts.map +1 -1
  7. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  8. package/dist/agent-executor/codex/event-routing.d.ts +8 -1
  9. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -1
  10. package/dist/agent-executor/codex/handlers.d.ts +1 -0
  11. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  12. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  13. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  14. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  15. package/dist/agent-executor/codex/shared-thread.d.ts +1 -0
  16. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  17. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  18. package/dist/agent-executor/profile.d.ts +2 -1
  19. package/dist/agent-executor/profile.d.ts.map +1 -1
  20. package/dist/entrypoints/agent-executor/acp.js +18 -4
  21. package/dist/entrypoints/agent-executor/claude-sdk.js +11 -10
  22. package/dist/entrypoints/agent-executor/claude.js +9 -8
  23. package/dist/entrypoints/agent-executor/codex.js +243 -102
  24. package/dist/entrypoints/agent-executor/testing.js +3 -3
  25. package/dist/entrypoints/agent-executor.js +2 -2
  26. package/dist/entrypoints/sync.js +8 -4
  27. package/dist/{index-32vaajec.js → index-athc412x.js} +1 -1
  28. package/dist/{index-g2d9kws8.js → index-f9p62ean.js} +20 -4
  29. package/dist/{index-gm9yz82v.js → index-jcrj0b8z.js} +1 -1
  30. package/dist/{index-64e9p079.js → index-z114ax5e.js} +7 -7
  31. package/dist/sync/session-machine.d.ts.map +1 -1
  32. package/dist/sync/session.d.ts +3 -3
  33. package/llms/agent-executor-claude.txt +1 -1
  34. package/llms/agent-executor-codex.txt +1 -1
  35. package/llms/agent-executor.txt +7 -1
  36. package/llms/stitchkit.txt +74 -74
  37. package/llms/sync.txt +1 -1
  38. package/llms/{upgrading-0.128.0-0.131.0.txt → upgrading-0.128.0-0.132.0.txt} +23 -3
  39. package/llms/upgrading.txt +1 -1
  40. package/llms-full.txt +104 -78
  41. package/llms.txt +4 -4
  42. package/package.json +1 -1
@@ -24,7 +24,7 @@ import {
24
24
  invokeSafely,
25
25
  emitStartupPhase,
26
26
  clampUniqueWindowName
27
- } from "../../index-g2d9kws8.js";
27
+ } from "../../index-f9p62ean.js";
28
28
  import {
29
29
  JsonRpcValueSchema2,
30
30
  JsonRpcError2,
@@ -88,7 +88,7 @@ import {
88
88
  drainEngineRequests,
89
89
  endEngineTurn,
90
90
  loseEngineTurn
91
- } from "../../index-gm9yz82v.js";
91
+ } from "../../index-jcrj0b8z.js";
92
92
  import {
93
93
  spawnEngineProcess2
94
94
  } from "../../index-rxh3qy4x.js";
@@ -96,7 +96,7 @@ import"../../index-3fym4j8n.js";
96
96
  import {
97
97
  planLimitsReadFailed2,
98
98
  mergeRateLimitEvent2
99
- } from "../../index-32vaajec.js";
99
+ } from "../../index-athc412x.js";
100
100
  import"../../index-pzhqydxb.js";
101
101
  import {
102
102
  assertExpectedOwnerUid
@@ -1984,7 +1984,14 @@ class CodexStartingTurn {
1984
1984
  waiting = [];
1985
1985
  bytes = 0;
1986
1986
  failure;
1987
+ discarded = false;
1988
+ flushing = false;
1989
+ get isBuffering() {
1990
+ return !this.discarded && !this.flushing;
1991
+ }
1987
1992
  defer(params, deliver) {
1993
+ if (!this.isBuffering)
1994
+ return;
1988
1995
  if (this.failure !== undefined)
1989
1996
  throw this.failure;
1990
1997
  this.bytes += JSON.stringify(params ?? null).length;
@@ -1994,13 +2001,37 @@ class CodexStartingTurn {
1994
2001
  }
1995
2002
  this.waiting.push(deliver);
1996
2003
  }
1997
- flush() {
1998
- for (const deliver of this.waiting.splice(0))
1999
- deliver();
2000
- if (this.failure !== undefined)
2001
- throw this.failure;
2004
+ discard() {
2005
+ this.discarded = true;
2006
+ this.waiting.length = 0;
2007
+ this.bytes = 0;
2008
+ this.failure = undefined;
2009
+ }
2010
+ flush(shouldContinue) {
2011
+ this.flushing = true;
2012
+ try {
2013
+ for (const deliver of this.waiting.splice(0)) {
2014
+ if (this.discarded || shouldContinue?.() === false) {
2015
+ this.discard();
2016
+ return;
2017
+ }
2018
+ deliver();
2019
+ }
2020
+ if (!this.discarded && shouldContinue?.() !== false && this.failure !== undefined) {
2021
+ throw this.failure;
2022
+ }
2023
+ } finally {
2024
+ this.flushing = false;
2025
+ }
2002
2026
  }
2003
2027
  }
2028
+ function discardStartingTurn(turn) {
2029
+ if (turn?.starting === undefined)
2030
+ return;
2031
+ const starting = turn.starting;
2032
+ delete turn.starting;
2033
+ starting.discard();
2034
+ }
2004
2035
  function codexEventTurn(current, params) {
2005
2036
  if (current === undefined)
2006
2037
  return;
@@ -2297,20 +2328,51 @@ function createCodexStartTurn(input) {
2297
2328
  channel: createTurnDeltaChannel(),
2298
2329
  pending: new Map
2299
2330
  };
2331
+ const isAlive = () => {
2332
+ if (input.signal.aborted)
2333
+ return false;
2334
+ try {
2335
+ input.ensureAlive();
2336
+ return true;
2337
+ } catch {
2338
+ return false;
2339
+ }
2340
+ };
2300
2341
  input.setTurn(turn);
2301
2342
  let nativeTurnId;
2302
2343
  try {
2303
- const started = await input.peer.request("turn/start", turnParams);
2344
+ const started = await input.peer.request("turn/start", turnParams, {
2345
+ signal: input.signal
2346
+ });
2347
+ if (!isAlive() || input.getTurn() !== turn) {
2348
+ if (input.getTurn() === turn)
2349
+ input.setTurn(undefined);
2350
+ discardStartingTurn(turn);
2351
+ input.ensureAlive();
2352
+ throw new Error("The Codex session is closed");
2353
+ }
2304
2354
  nativeTurnId = parseCodexResponse("turn/start", CodexStartedTurnSchema, started).turn.id;
2305
2355
  turn.codexTurnId = nativeTurnId;
2306
- delete turn.starting;
2307
- starting.flush();
2356
+ try {
2357
+ starting.flush(isAlive);
2358
+ } finally {
2359
+ if (turn.starting === starting)
2360
+ delete turn.starting;
2361
+ }
2308
2362
  } catch (error) {
2309
2363
  if (input.getTurn() === turn)
2310
2364
  input.setTurn(undefined);
2311
2365
  if (turn.starting !== undefined) {
2312
- delete turn.starting;
2313
- starting.flush();
2366
+ const pending = turn.starting;
2367
+ try {
2368
+ if (isAlive())
2369
+ pending.flush(isAlive);
2370
+ else
2371
+ pending.discard();
2372
+ } finally {
2373
+ if (turn.starting === pending)
2374
+ delete turn.starting;
2375
+ }
2314
2376
  }
2315
2377
  throw error;
2316
2378
  }
@@ -2325,6 +2387,7 @@ function createCodexStartTurn(input) {
2325
2387
  });
2326
2388
  },
2327
2389
  async respond(interactionId, rawReply) {
2390
+ input.ensureAlive();
2328
2391
  answerActiveCodexTurnRequest(turn, interactionId, rawReply);
2329
2392
  }
2330
2393
  };
@@ -2519,75 +2582,107 @@ function resolveWindowFields(raw) {
2519
2582
  const resetsAt = parseCodexResetsAt(window.resetsAt ?? window.resets_at);
2520
2583
  return { usedPercent, mins, resetsAt };
2521
2584
  }
2522
- function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
2523
- const label = clampPlanName(snapshot.limitName ?? snapshot.limit_name, MAX_WINDOW_NAME_CHARS);
2585
+ function findMatchingWindowIndex(windows, bucket, slot, mins, other, excludeIndex) {
2586
+ const exact = windows.findIndex((w, i) => i !== excludeIndex && w.bucket === bucket && w.slot === slot && w.mins === mins);
2587
+ if (exact >= 0)
2588
+ return exact;
2589
+ let partialIndex = -1;
2590
+ let partialCount = 0;
2591
+ for (let i = 0;i < windows.length; i += 1) {
2592
+ if (i === excludeIndex)
2593
+ continue;
2594
+ const candidate = windows[i];
2595
+ if (candidate !== undefined && candidate.bucket === bucket && candidate.slot === slot && (candidate.mins === undefined || mins === undefined)) {
2596
+ partialIndex = i;
2597
+ partialCount += 1;
2598
+ }
2599
+ }
2600
+ if (partialCount === 1)
2601
+ return partialIndex;
2602
+ if (mins !== undefined) {
2603
+ const otherSlot = slot === "primary" ? "secondary" : "primary";
2604
+ return windows.findIndex((w, i) => i !== excludeIndex && w.bucket === bucket && w.mins === mins && !(other !== undefined && w.slot === otherSlot && (other.mins === undefined || other.mins === w.mins)));
2605
+ }
2606
+ return -1;
2607
+ }
2608
+ function mergeBucket(windows, bucket, snapshot) {
2524
2609
  const primary = resolveWindowFields(snapshot.primary);
2525
2610
  const secondary = resolveWindowFields(snapshot.secondary);
2526
- const duplicateDuration = primary !== undefined && secondary !== undefined && primary.mins !== undefined && primary.mins === secondary.mins;
2527
- const slots = [
2528
- ["primary", primary],
2529
- ["secondary", secondary]
2530
- ];
2531
- for (const [slot, window] of slots) {
2532
- if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
2611
+ const slots = { primary, secondary };
2612
+ let claimedIndex = -1;
2613
+ for (const slot of ["primary", "secondary"]) {
2614
+ const measurement = slots[slot];
2615
+ if (!measurement)
2533
2616
  continue;
2534
- const suffix = window.mins === undefined ? `:${slot}` : duplicateDuration ? `:${window.mins}m:${slot}` : `:${window.mins}m`;
2535
- const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
2536
- out.push(PlanWindowSchema2.parse({
2617
+ const other = slots[slot === "primary" ? "secondary" : "primary"];
2618
+ const previous = findMatchingWindowIndex(windows, bucket, slot, measurement.mins, other, claimedIndex);
2619
+ const existing = previous >= 0 ? windows[previous] : undefined;
2620
+ const window = {
2621
+ usedPercent: measurement.usedPercent,
2622
+ mins: measurement.mins ?? existing?.mins,
2623
+ resetsAt: measurement.resetsAt ?? existing?.resetsAt,
2624
+ bucket,
2625
+ slot
2626
+ };
2627
+ if (previous >= 0) {
2628
+ windows[previous] = window;
2629
+ claimedIndex = previous;
2630
+ } else if (windows.length < MAX_PLAN_WINDOWS) {
2631
+ claimedIndex = windows.length;
2632
+ windows.push(window);
2633
+ }
2634
+ }
2635
+ }
2636
+ function nameBucketWindows(windows, bucketLabels) {
2637
+ const seen = new Set;
2638
+ return windows.map((window) => {
2639
+ const { bucket, slot, usedPercent, mins, resetsAt } = window;
2640
+ const label = bucketLabels.get(bucket);
2641
+ const sharedDuration = mins !== undefined && windows.some((other) => other !== window && other.bucket === bucket && other.mins === mins);
2642
+ const suffix = mins === undefined ? `:${slot}` : sharedDuration ? `:${mins}m:${slot}` : `:${mins}m`;
2643
+ const name = clampUniqueWindowName(bucket, suffix, seen, `${bucket}:${slot}`, MAX_WINDOW_NAME_CHARS);
2644
+ return PlanWindowSchema2.parse({
2537
2645
  name,
2538
- usedPercent: Math.min(100, window.usedPercent),
2539
- ...window.resetsAt !== undefined && { resetsAt: window.resetsAt },
2540
- ...window.mins !== undefined && { windowDurationMins: window.mins },
2646
+ usedPercent: Math.min(100, usedPercent),
2647
+ ...resetsAt !== undefined && { resetsAt },
2648
+ ...mins !== undefined && { windowDurationMins: mins },
2541
2649
  ...label !== undefined && { label }
2542
- }));
2543
- }
2650
+ });
2651
+ });
2544
2652
  }
2545
2653
  function parseCodexRateLimitsInternal(reported) {
2654
+ if (!isRecord(reported))
2655
+ return { windows: [], plan: undefined };
2546
2656
  const windows = [];
2547
- const seenNames = new Set;
2657
+ const bucketLabels = new Map;
2548
2658
  let plan;
2549
- const capturePlan = (snapshot) => {
2550
- if (plan === undefined) {
2551
- plan = clampPlanName(snapshot.planType ?? snapshot.plan_type, MAX_WINDOW_NAME_CHARS);
2552
- }
2553
- };
2554
- if (isRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported) || ("rate_limits" in reported) || ("rate_limits_by_limit_id" in reported))) {
2555
- const seenLimitIds = new Set;
2556
- const rawById = reported.rateLimitsByLimitId ?? reported.rate_limits_by_limit_id;
2557
- if (isRecord(rawById)) {
2558
- for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
2559
- const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
2560
- if (!parsed.success)
2561
- continue;
2562
- capturePlan(parsed.data);
2563
- const limitId = nonEmptyString(parsed.data.limitId ?? parsed.data.limit_id)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
2564
- seenLimitIds.add(limitId);
2565
- appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
2566
- if (windows.length >= MAX_PLAN_WINDOWS)
2567
- return { windows, plan };
2568
- }
2569
- }
2570
- const rawSingle = reported.rateLimits ?? reported.rate_limits;
2571
- if (windows.length < MAX_PLAN_WINDOWS && rawSingle !== undefined) {
2572
- const parsedSingle = SnapshotSchema.safeParse(rawSingle);
2573
- if (parsedSingle.success) {
2574
- capturePlan(parsedSingle.data);
2575
- const explicitId = nonEmptyString(parsedSingle.data.limitId ?? parsedSingle.data.limit_id)?.trim();
2576
- const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
2577
- if (shouldIncludeSingle) {
2578
- appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
2579
- }
2580
- }
2659
+ function readBucket(raw, fallbackId) {
2660
+ const parsed = SnapshotSchema.safeParse(raw);
2661
+ if (!parsed.success)
2662
+ return fallbackId;
2663
+ const snapshot = parsed.data;
2664
+ plan ??= clampPlanName(snapshot.planType ?? snapshot.plan_type, MAX_WINDOW_NAME_CHARS);
2665
+ const id = nonEmptyString(snapshot.limitId ?? snapshot.limit_id)?.trim() ?? fallbackId;
2666
+ const label = clampPlanName(snapshot.limitName ?? snapshot.limit_name, MAX_WINDOW_NAME_CHARS);
2667
+ if (label !== undefined)
2668
+ bucketLabels.set(id, label);
2669
+ mergeBucket(windows, id, snapshot);
2670
+ return id;
2671
+ }
2672
+ const byId = reported.rateLimitsByLimitId ?? reported.rate_limits_by_limit_id;
2673
+ const defaultId = isRecord(byId) && isRecord(byId.codex) ? "codex" : "limit";
2674
+ const accountId = readBucket(reported.rateLimits ?? reported.rate_limits ?? reported, defaultId);
2675
+ if (isRecord(byId)) {
2676
+ if (Object.hasOwn(byId, accountId))
2677
+ readBucket(byId[accountId], accountId);
2678
+ for (const key of Object.keys(byId).sort((a, b) => a.localeCompare(b))) {
2679
+ if (windows.length >= MAX_PLAN_WINDOWS)
2680
+ break;
2681
+ if (key !== accountId)
2682
+ readBucket(byId[key], nonEmptyString(key)?.trim() ?? "limit");
2581
2683
  }
2582
- return { windows, plan };
2583
2684
  }
2584
- const single = SnapshotSchema.safeParse(reported);
2585
- if (!single.success)
2586
- return { windows: [], plan: undefined };
2587
- capturePlan(single.data);
2588
- const limitId = nonEmptyString(single.data.limitId ?? single.data.limit_id)?.trim() ?? "limit";
2589
- appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
2590
- return { windows, plan };
2685
+ return { windows: nameBucketWindows(windows, bucketLabels), plan };
2591
2686
  }
2592
2687
  function codexPlanWindows(reported) {
2593
2688
  return parseCodexRateLimitsInternal(reported).windows;
@@ -2701,6 +2796,14 @@ async function findCodexTurnByClientId(controls, params) {
2701
2796
  // src/agent-executor/codex/handlers.ts
2702
2797
  var JSON_RPC_INTERNAL_ERROR = -32603;
2703
2798
  var MAX_EXTERNAL_PENDING_REQUESTS = 256;
2799
+ function isHandlersAlive(state) {
2800
+ try {
2801
+ state.ensureAlive();
2802
+ return true;
2803
+ } catch {
2804
+ return false;
2805
+ }
2806
+ }
2704
2807
  function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
2705
2808
  if (state.onNotification === undefined)
2706
2809
  return;
@@ -2840,6 +2943,7 @@ function handleCodexRequest(state, method, params, id) {
2840
2943
  duringActiveTurn: true,
2841
2944
  delta,
2842
2945
  async respond(reply) {
2946
+ state.ensureAlive();
2843
2947
  answerActiveCodexTurnRequest(turn, interactionId, reply);
2844
2948
  }
2845
2949
  }));
@@ -2892,6 +2996,7 @@ function handleCodexRequest(state, method, params, id) {
2892
2996
  duringActiveTurn: false,
2893
2997
  delta,
2894
2998
  async respond(reply) {
2999
+ state.ensureAlive();
2895
3000
  answerCodexSessionRequest({
2896
3001
  turn: undefined,
2897
3002
  externalPending: state.externalPending,
@@ -2910,22 +3015,35 @@ function handleCodexRequest(state, method, params, id) {
2910
3015
  });
2911
3016
  }
2912
3017
  function createCodexHandlers(state) {
3018
+ const dropClosedRequest = () => new Promise(() => {
3019
+ return;
3020
+ });
2913
3021
  return {
2914
3022
  onNotification(method, params) {
3023
+ if (!isHandlersAlive(state))
3024
+ return;
2915
3025
  const starting = codexEventTurn(state.getTurn(), params)?.starting;
2916
- const deliver = () => handleCodexNotification(state, method, params);
2917
- if (starting === undefined)
3026
+ const deliver = () => {
3027
+ if (!isHandlersAlive(state))
3028
+ return;
3029
+ handleCodexNotification(state, method, params);
3030
+ };
3031
+ if (starting === undefined || !starting.isBuffering)
2918
3032
  deliver();
2919
3033
  else
2920
3034
  starting.defer(params, deliver);
2921
3035
  },
2922
3036
  onRequest(method, params, id) {
3037
+ if (!isHandlersAlive(state))
3038
+ return dropClosedRequest();
2923
3039
  const starting = codexEventTurn(state.getTurn(), params)?.starting;
2924
- const deliver = () => handleCodexRequest(state, method, params, id);
2925
- if (starting === undefined)
3040
+ const deliver = () => isHandlersAlive(state) ? handleCodexRequest(state, method, params, id) : dropClosedRequest();
3041
+ if (starting === undefined || !starting.isBuffering)
2926
3042
  return deliver();
2927
3043
  return new Promise((resolve, reject) => {
2928
3044
  starting.defer(params, () => {
3045
+ if (!isHandlersAlive(state))
3046
+ return;
2929
3047
  try {
2930
3048
  resolve(deliver());
2931
3049
  } catch (error) {
@@ -3028,12 +3146,21 @@ async function openCodexSession(config, input) {
3028
3146
  let dead;
3029
3147
  let opened = false;
3030
3148
  let closing = false;
3149
+ const ensureAlive = () => {
3150
+ if (closing)
3151
+ throw new Error("The Codex session is closed");
3152
+ if (dead !== undefined)
3153
+ throw dead;
3154
+ if (linked.signal.aborted)
3155
+ throw abortReason(linked.signal);
3156
+ };
3031
3157
  let connected;
3032
3158
  try {
3033
3159
  connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
3034
3160
  profileId: profile.profileId,
3035
3161
  limits: config.limits,
3036
3162
  externalPending,
3163
+ ensureAlive,
3037
3164
  getTurn: () => current,
3038
3165
  clearTurn: () => {
3039
3166
  current = undefined;
@@ -3050,6 +3177,7 @@ async function openCodexSession(config, input) {
3050
3177
  dead = error;
3051
3178
  const turn = current;
3052
3179
  current = undefined;
3180
+ discardStartingTurn(turn);
3053
3181
  externalPending.clear();
3054
3182
  loseEngineTurn(turn, codexStopped, error);
3055
3183
  linked.abort();
@@ -3061,14 +3189,9 @@ async function openCodexSession(config, input) {
3061
3189
  throw error;
3062
3190
  }
3063
3191
  const { peer, providerPid, userAgent } = connected;
3064
- const ensureAlive = () => {
3065
- if (closing)
3066
- throw new Error("The Codex session is closed");
3067
- if (dead !== undefined)
3068
- throw dead;
3069
- };
3070
3192
  const stop = async (primary) => {
3071
3193
  closing = true;
3194
+ discardStartingTurn(current);
3072
3195
  externalPending.clear();
3073
3196
  try {
3074
3197
  await stopConnection(connected, primary);
@@ -3171,12 +3294,21 @@ async function openCodexControlConnection(config, input) {
3171
3294
  let dead;
3172
3295
  let opened = false;
3173
3296
  let closing = false;
3297
+ const ensureAlive = () => {
3298
+ if (closing)
3299
+ throw new Error("The Codex control connection is closed");
3300
+ if (dead !== undefined)
3301
+ throw dead;
3302
+ if (linked.signal.aborted)
3303
+ throw abortReason(linked.signal);
3304
+ };
3174
3305
  let connected;
3175
3306
  try {
3176
3307
  connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
3177
3308
  profileId: profile.profileId,
3178
3309
  limits: config.limits,
3179
3310
  externalPending,
3311
+ ensureAlive,
3180
3312
  getTurn: () => {
3181
3313
  return;
3182
3314
  },
@@ -3214,12 +3346,6 @@ async function openCodexControlConnection(config, input) {
3214
3346
  }
3215
3347
  throw reason;
3216
3348
  }
3217
- const ensureAlive = () => {
3218
- if (closing)
3219
- throw new Error("The Codex control connection is closed");
3220
- if (dead !== undefined)
3221
- throw dead;
3222
- };
3223
3349
  const controlClient = createCodexControlClient({
3224
3350
  peer: connected.peer,
3225
3351
  imageOptions: config,
@@ -3262,14 +3388,7 @@ function bestEffortUnsubscribe(state, threadId) {
3262
3388
  }
3263
3389
  function buildSharedThreadSession(params) {
3264
3390
  const { state, slot, threadContext, activeModelProvider, threadAbort } = params;
3265
- const { threadId } = slot;
3266
- const ensureThreadAlive = () => {
3267
- if (slot.closed)
3268
- throw new Error("The Codex session is closed");
3269
- if (slot.dead !== undefined)
3270
- throw slot.dead;
3271
- state.ensureServerAlive();
3272
- };
3391
+ const { threadId, ensureAlive: ensureThreadAlive } = slot;
3273
3392
  const threadControlClient = createCodexControlClient({
3274
3393
  peer: state.peer,
3275
3394
  imageOptions: state.config,
@@ -3303,13 +3422,14 @@ function buildSharedThreadSession(params) {
3303
3422
  slot.closed = true;
3304
3423
  const turn = slot.current;
3305
3424
  slot.current = undefined;
3425
+ discardStartingTurn(turn);
3306
3426
  slot.externalPending.clear();
3307
3427
  loseEngineTurn(turn, codexStopped, new Error("The Codex session closed"));
3308
3428
  state.threads.delete(threadId);
3429
+ threadAbort.abort();
3309
3430
  try {
3310
3431
  await bestEffortUnsubscribe(state, threadId);
3311
3432
  } finally {
3312
- threadAbort.abort();
3313
3433
  slot.releaseThreadSignal();
3314
3434
  }
3315
3435
  };
@@ -3321,6 +3441,7 @@ function buildSharedThreadSession(params) {
3321
3441
  slot.dead = slot.dead ?? (reason instanceof Error ? reason : new Error(String(reason)));
3322
3442
  const turn = slot.current;
3323
3443
  slot.current = undefined;
3444
+ discardStartingTurn(turn);
3324
3445
  slot.externalPending.clear();
3325
3446
  loseEngineTurn(turn, codexStopped, slot.dead);
3326
3447
  state.threads.delete(threadId);
@@ -3415,10 +3536,20 @@ async function openSharedCodexThread(state, threadInput) {
3415
3536
  throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadId} is already open on this shared server`);
3416
3537
  }
3417
3538
  const externalPending = new Map;
3539
+ const ensureAlive = () => {
3540
+ if (slot.closed)
3541
+ throw new Error("The Codex session is closed");
3542
+ if (slot.dead !== undefined)
3543
+ throw slot.dead;
3544
+ state.ensureServerAlive();
3545
+ if (threadAbort.signal.aborted)
3546
+ throw abortReason(threadAbort.signal);
3547
+ };
3418
3548
  const slot = {
3419
3549
  threadId,
3420
3550
  current: undefined,
3421
3551
  externalPending,
3552
+ ensureAlive,
3422
3553
  closed: false,
3423
3554
  dead: undefined,
3424
3555
  abortThread: () => threadAbort.abort(),
@@ -3427,6 +3558,7 @@ async function openSharedCodexThread(state, threadInput) {
3427
3558
  profileId: state.profile.profileId,
3428
3559
  limits: state.config.limits,
3429
3560
  externalPending,
3561
+ ensureAlive,
3430
3562
  getTurn: () => slot.current,
3431
3563
  clearTurn: () => {
3432
3564
  slot.current = undefined;
@@ -3467,6 +3599,11 @@ async function openSharedCodexThread(state, threadInput) {
3467
3599
  });
3468
3600
  } catch (error) {
3469
3601
  if (registeredThreadId !== undefined) {
3602
+ const failedSlot = state.threads.get(registeredThreadId);
3603
+ if (failedSlot !== undefined) {
3604
+ failedSlot.closed = true;
3605
+ failedSlot.externalPending.clear();
3606
+ }
3470
3607
  state.threads.delete(registeredThreadId);
3471
3608
  await bestEffortUnsubscribe(state, registeredThreadId);
3472
3609
  }
@@ -3504,10 +3641,19 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3504
3641
  let serverDead;
3505
3642
  let serverClosing = false;
3506
3643
  let opened = false;
3644
+ const ensureServerAlive = () => {
3645
+ if (serverClosing)
3646
+ throw new Error("The Codex shared server is closed");
3647
+ if (serverDead !== undefined)
3648
+ throw serverDead;
3649
+ if (linked.signal.aborted)
3650
+ throw abortReason(linked.signal);
3651
+ };
3507
3652
  const globalHandlers = createCodexHandlers({
3508
3653
  profileId: profile.profileId,
3509
3654
  limits: config.limits,
3510
3655
  externalPending: globalExternalPending,
3656
+ ensureAlive: ensureServerAlive,
3511
3657
  getTurn: () => {
3512
3658
  return;
3513
3659
  },
@@ -3526,6 +3672,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3526
3672
  slot.dead = error;
3527
3673
  const turn = slot.current;
3528
3674
  slot.current = undefined;
3675
+ discardStartingTurn(turn);
3529
3676
  slot.externalPending.clear();
3530
3677
  loseEngineTurn(turn, codexStopped, error);
3531
3678
  slot.abortThread();
@@ -3570,12 +3717,6 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3570
3717
  throw error;
3571
3718
  }
3572
3719
  const { peer, providerPid, userAgent } = connected;
3573
- const ensureServerAlive = () => {
3574
- if (serverClosing)
3575
- throw new Error("The Codex shared server is closed");
3576
- if (serverDead !== undefined)
3577
- throw serverDead;
3578
- };
3579
3720
  const onBeforeInterruptTurn = (targetThreadId, turnId) => {
3580
3721
  interruptLocalCodexTurn(threads.get(targetThreadId)?.current, turnId);
3581
3722
  };
@@ -17,7 +17,7 @@ import {
17
17
  offerTurnDelta,
18
18
  sessionAbort,
19
19
  emitStartupPhase
20
- } from "../../index-g2d9kws8.js";
20
+ } from "../../index-f9p62ean.js";
21
21
  import {
22
22
  JsonRpcValueSchema2,
23
23
  JsonRpcError2,
@@ -41,14 +41,14 @@ import {
41
41
  drainEngineRequests,
42
42
  endEngineTurn,
43
43
  loseEngineTurn
44
- } from "../../index-gm9yz82v.js";
44
+ } from "../../index-jcrj0b8z.js";
45
45
  import {
46
46
  dispatchTurn2,
47
47
  projectExecutorDeltas2
48
48
  } from "../../index-x5ayy5bn.js";
49
49
  import {
50
50
  mergeRateLimitEvent2
51
- } from "../../index-32vaajec.js";
51
+ } from "../../index-athc412x.js";
52
52
  import"../../index-pzhqydxb.js";
53
53
  import {
54
54
  unlinkUnixSocketIfMatching,
@@ -48,7 +48,7 @@ import {
48
48
  engineEnvironment2,
49
49
  ownCredentials2,
50
50
  helloProfile2
51
- } from "../index-g2d9kws8.js";
51
+ } from "../index-f9p62ean.js";
52
52
  import"../index-v59pxmf1.js";
53
53
  import"../index-qa2jjb65.js";
54
54
  import"../index-6kec3b14.js";
@@ -75,7 +75,7 @@ import {
75
75
  planLimitsDue2,
76
76
  planLimitsReadFailed2,
77
77
  mergeRateLimitEvent2
78
- } from "../index-32vaajec.js";
78
+ } from "../index-athc412x.js";
79
79
  import"../index-pzhqydxb.js";
80
80
  import {
81
81
  AppError2
@@ -526,10 +526,14 @@ class SyncSessionMachine {
526
526
  this.continueSnapshot(checkedResume(cursor));
527
527
  return;
528
528
  }
529
- this.openSession(cursor ? "incremental" : "full");
530
- return chain(cursor ? undefined : this.ports.beginFullSync(), () => {
529
+ if (cursor !== null)
530
+ assertNonNegativeSafeInteger("saved sync cursor", cursor, TypeError, {
531
+ absent: "refused"
532
+ });
533
+ this.openSession(cursor === null ? "full" : "incremental");
534
+ return chain(cursor === null ? this.ports.beginFullSync() : undefined, () => {
531
535
  if (this.alive(stamp))
532
- this.sendPage({ after: cursor || null, token: null });
536
+ this.sendPage({ after: cursor, token: null });
533
537
  });
534
538
  }), (error) => {
535
539
  if (!this.alive(stamp))
@@ -621,7 +625,7 @@ class SyncSessionMachine {
621
625
  const full = this.mode === "full";
622
626
  const from = full ? this.snapshotFrom : null;
623
627
  const catchUp = from !== null && (page.latestVersion ?? from) > from;
624
- return chain(full ? this.rebasePending() : undefined, () => this.saveLastPage(stamp, expected, catchUp ? from : page.latestVersion, catchUp));
628
+ return chain(full ? this.rebasePending() : undefined, () => this.saveLastPage(stamp, expected, catchUp ? from : page.latestVersion ?? from ?? undefined, catchUp));
625
629
  }
626
630
  saveLastPage(stamp, expected, cursor, catchUp) {
627
631
  if (!this.alive(stamp))
@@ -2,7 +2,7 @@ import {
2
2
  PlanWindowSchema2,
3
3
  PlanLimitsSchema2,
4
4
  clampPlanName
5
- } from "./index-g2d9kws8.js";
5
+ } from "./index-f9p62ean.js";
6
6
  import {
7
7
  isPositiveSafeInteger
8
8
  } from "./index-gr0kxymw.js";