@koda-sl/baker-bridge 0.152.0-dev.1a19b1876 → 0.155.0-dev.25961ab20

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 (35) hide show
  1. package/README.md +29 -7
  2. package/dist/hono/agent-session.d.ts +0 -1
  3. package/dist/hono/agent-session.d.ts.map +1 -1
  4. package/dist/hono/agent-session.js +0 -7
  5. package/dist/hono/agent-session.js.map +1 -1
  6. package/dist/hono/agent-session.test.js +1 -7
  7. package/dist/hono/agent-session.test.js.map +1 -1
  8. package/dist/hono/agent.d.ts.map +1 -1
  9. package/dist/hono/agent.js +1 -7
  10. package/dist/hono/agent.js.map +1 -1
  11. package/dist/hono/bridge-job.d.ts +3 -1
  12. package/dist/hono/bridge-job.d.ts.map +1 -1
  13. package/dist/hono/bridge-job.js +117 -18
  14. package/dist/hono/bridge-job.js.map +1 -1
  15. package/dist/hono/bridge-job.test.js +165 -2
  16. package/dist/hono/bridge-job.test.js.map +1 -1
  17. package/dist/hono/main-sync.d.ts.map +1 -1
  18. package/dist/hono/main-sync.js +18 -5
  19. package/dist/hono/main-sync.js.map +1 -1
  20. package/dist/hono/main-sync.test.js +12 -0
  21. package/dist/hono/main-sync.test.js.map +1 -1
  22. package/dist/hono/session-continuity.d.ts +30 -0
  23. package/dist/hono/session-continuity.d.ts.map +1 -1
  24. package/dist/hono/session-continuity.integration.test.js +200 -5
  25. package/dist/hono/session-continuity.integration.test.js.map +1 -1
  26. package/dist/hono/session-continuity.js +99 -8
  27. package/dist/hono/session-continuity.js.map +1 -1
  28. package/dist/hono/session-store.d.ts +2 -0
  29. package/dist/hono/session-store.d.ts.map +1 -1
  30. package/dist/hono/session-store.js +6 -0
  31. package/dist/hono/session-store.js.map +1 -1
  32. package/dist/hono/turn-events.d.ts +1 -1
  33. package/dist/hono/turn-events.d.ts.map +1 -1
  34. package/dist/hono/turn-events.js.map +1 -1
  35. package/package.json +1 -1
@@ -26,7 +26,7 @@ import { BEDROCK_SERVABLE_CAPABILITIES, buildAgentExtraBody, EXTRA_BODY_ENV, MOD
26
26
  import { credentialReminder, currentReferenceReminder, kickoffBriefReminder } from "./prompt-context.js";
27
27
  import { publishLanguageReminder, publishRunReminder } from "./publish-handoff.js";
28
28
  import { bridgeRuntimeFiles } from "./runtime-files.js";
29
- import { applyCurrentSenderAttribution, buildCleanBoundary, buildRehydratedPrompt, compactionRetryAttempt, emptyInProgressSession, interruptedResumeAttempt, isContextOverflowError, isResumeSessionError, observeInProgressSession, prepareSessionAttempt, stallContinuationAttempt, } from "./session-continuity.js";
29
+ import { applyCurrentSenderAttribution, buildCancelBoundary, buildCleanBoundary, buildRehydratedPrompt, compactionRetryAttempt, emptyInProgressSession, interruptedResumeAttempt, isCliResumeRefusal, isContextOverflowError, isResumeSessionError, observeInProgressSession, prepareSessionAttempt, stallContinuationAttempt, } from "./session-continuity.js";
30
30
  import { readSessionSkills } from "./session-skills.js";
31
31
  import { ownQueryUsage, readUsageBaseline } from "./session-usage-baseline.js";
32
32
  import { BridgeSlashCommands, leadingSkillCommand, verbatimSlashCommand } from "./slash-commands.js";
@@ -424,10 +424,20 @@ const CONTEXT_OVERFLOW_MESSAGE = "This chat has grown too long to continue in on
424
424
  // so the turn ends on this instead. The refused exchange is not saved to the
425
425
  // session, so a rephrased message starts from the conversation before it.
426
426
  const MODEL_REFUSAL_MESSAGE = "I couldn't help with that request. Try rephrasing what you need.";
427
- function userFacingTurnError(message) {
427
+ // What the user reads when the model provider failed the request itself — out
428
+ // of credit, rate-limited, down. The CLI's own text ("API Error: 402 Insufficient
429
+ // credits. Add more using https://openrouter.ai/…") is the provider talking to
430
+ // Baker: a vendor, a status code and a billing page the marketer cannot open.
431
+ // The raw text stays in the bridge log and the turn events.
432
+ const PROVIDER_FAILURE_MESSAGE = "Baker's AI service had a problem on our side, so this step stopped. Nothing you did caused it — send your message again to pick up where it stopped.";
433
+ function userFacingTurnError(error) {
434
+ const message = errorMessage(error);
428
435
  if (isContextOverflowError(message)) {
429
436
  return CONTEXT_OVERFLOW_MESSAGE;
430
437
  }
438
+ if (error instanceof SdkResultError && error.providerFailure) {
439
+ return PROVIDER_FAILURE_MESSAGE;
440
+ }
431
441
  return enrichImageError(message);
432
442
  }
433
443
  function enrichImageError(message) {
@@ -565,14 +575,35 @@ function sdkResultErrorMessage(msg) {
565
575
  function turnResultError(state, msg) {
566
576
  return state.refusedWithoutFallback ? undefined : sdkResultError(msg);
567
577
  }
578
+ class SdkResultError extends Error {
579
+ providerFailure;
580
+ name = "SdkResultError";
581
+ constructor(message,
582
+ /** The model provider refused or failed the request, rather than the turn's own work failing. */
583
+ providerFailure) {
584
+ super(`Claude Code returned an error result: ${message}`);
585
+ this.providerFailure = providerFailure;
586
+ }
587
+ }
588
+ // What the request's own content caused (an unreadable image, a malformed or
589
+ // oversized request): sending the same message again would fail the same way, so
590
+ // it keeps its own remediation instead of the provider-failure message.
591
+ const REQUEST_CONTENT_STATUSES = [400, 413, 422];
592
+ function isProviderFailureResult(msg) {
593
+ if (msg.subtype !== "success") {
594
+ return false;
595
+ }
596
+ const status = msg.api_error_status ?? Number(/^API Error: (\d{3})\b/.exec(msg.result)?.[1]);
597
+ if (REQUEST_CONTENT_STATUSES.includes(status)) {
598
+ return false;
599
+ }
600
+ return typeof msg.api_error_status === "number" || msg.result.startsWith("API Error");
601
+ }
568
602
  function sdkResultError(msg) {
569
603
  if (msg.type !== "result" || !msg.is_error) {
570
604
  return undefined;
571
605
  }
572
- const message = sdkResultErrorMessage(msg);
573
- const error = new Error(`Claude Code returned an error result: ${message}`);
574
- error.name = "SdkResultError";
575
- return error;
606
+ return new SdkResultError(sdkResultErrorMessage(msg), isProviderFailureResult(msg));
576
607
  }
577
608
  // When the bridge closes the sandbox CLI's stdin (its permission control
578
609
  // channel) — on abort/replace/timeout — while the CLI is still alive (a long
@@ -686,6 +717,15 @@ export function isContextOverflowRefusal(msg) {
686
717
  }
687
718
  return OVERFLOW_REFUSAL_LEADS.some((lead) => text.startsWith(lead));
688
719
  }
720
+ /**
721
+ * True when an assistant message is the CLI's own report of a failed model
722
+ * request ("API Error: 402 Insufficient credits…", "API Error: Server error
723
+ * mid-response…"), not anything the model wrote. The CLI writes it for a
724
+ * terminal user: a `<synthetic>` model and the request's `error` class.
725
+ */
726
+ function isApiErrorMessage(msg) {
727
+ return msg.type === "assistant" && msg.error !== undefined && msg.message.model === "<synthetic>";
728
+ }
689
729
  /** Content blocks of an assistant/user SDK message; [] for other shapes. */
690
730
  function messageContentBlocks(msg) {
691
731
  const content = msg.message?.content;
@@ -1122,12 +1162,14 @@ export class BridgeJobExecutor {
1122
1162
  replayAttempt = prepareSessionAttempt({
1123
1163
  requestPrompt: request.prompt,
1124
1164
  reminder: request.reminder,
1165
+ delivered: request.mainSync?.delivered,
1125
1166
  history: job.history,
1126
1167
  loaded,
1127
1168
  leadingCommand: request.leadingCommand,
1128
1169
  });
1129
- attempt = (await this.interruptedTurnAttempt(job, replayAttempt)) ?? replayAttempt;
1170
+ attempt = (await this.interruptedTurnAttempt(job, replayAttempt, request.mainSync)) ?? replayAttempt;
1130
1171
  state.usedBoundary = attempt.usedBoundary;
1172
+ state.requestPrompt = request.prompt;
1131
1173
  state.detachedSession = attempt.detachedSession === true;
1132
1174
  result.attemptedRehydration = attempt.attemptedRehydration;
1133
1175
  this.recordAttemptContextSource(job, attempt);
@@ -1138,6 +1180,7 @@ export class BridgeJobExecutor {
1138
1180
  const repaired = await this.fallbackAttempt(job, controls, { request, attempt, replayAttempt }, state, error);
1139
1181
  if (repaired && controls.isActive()) {
1140
1182
  const repairState = createBridgeJobState();
1183
+ repairState.detachedSession = repaired.detachedSession === true;
1141
1184
  let repairResult = { costUsd: 0, attemptedRehydration: repaired.attemptedRehydration };
1142
1185
  try {
1143
1186
  repairResult = await this.runAttempt(job, controls, repairState, repaired);
@@ -1163,9 +1206,9 @@ export class BridgeJobExecutor {
1163
1206
  return await this.invalidResumeFallbackAttempt(job, controls, tried.request, tried.attempt, state, error);
1164
1207
  }
1165
1208
  /** The turn's own session, when Convex sent again a turn this bridge was running when it went down. */
1166
- async interruptedTurnAttempt(job, replay) {
1209
+ async interruptedTurnAttempt(job, replay, mainSync) {
1167
1210
  const inFlight = await this.inFlightTurns.load(job.threadId).catch(() => undefined);
1168
- const resumed = interruptedResumeAttempt(replay, { jobTurnId: job.turnId, inFlight });
1211
+ const resumed = interruptedResumeAttempt(replay, { jobTurnId: job.turnId, inFlight, mainSync });
1169
1212
  if (inFlight && !resumed) {
1170
1213
  await this.inFlightTurns.clear(job.threadId, inFlight.turnId).catch(() => undefined);
1171
1214
  }
@@ -1178,7 +1221,7 @@ export class BridgeJobExecutor {
1178
1221
  async interruptedResumeFallbackAttempt(job, replay, state, error) {
1179
1222
  if (!replay ||
1180
1223
  state.sawUserVisibleSdkMessage ||
1181
- (error instanceof Error && error.name === "SdkResultError") ||
1224
+ (error instanceof Error && error.name === "SdkResultError" && !isCliResumeRefusal(error)) ||
1182
1225
  !isResumeSessionError(error)) {
1183
1226
  return null;
1184
1227
  }
@@ -1216,17 +1259,21 @@ export class BridgeJobExecutor {
1216
1259
  leadingSkillCommand(job.prompt, (await readSessionSkills(bridgeRuntimeFiles.projectRoot())) ?? []);
1217
1260
  let requestPrompt = verbatim ?? applyCurrentSenderAttribution(job.prompt, job.currentSender);
1218
1261
  // A command must stay the leading token, so it carries no note: the news waits for the next turn.
1219
- const reminder = turnReminder(job, verbatim, verbatim === null ? mainSyncReminder(mainSync) : undefined);
1262
+ const syncNote = verbatim === null ? mainSyncReminder(mainSync) : undefined;
1263
+ const reminder = turnReminder(job, verbatim, syncNote);
1220
1264
  if (job.attachments && job.attachments.length > 0) {
1221
1265
  requestPrompt += await this.prepareAttachments(job.attachments, "message");
1222
1266
  }
1223
1267
  if (!controls.isActive()) {
1224
1268
  return null;
1225
1269
  }
1226
- if (verbatim === null) {
1227
- await mainSync?.told();
1228
- }
1229
- return { prompt: requestPrompt, ...(reminder ? { reminder } : {}), leadingCommand: verbatim !== null };
1270
+ return {
1271
+ prompt: requestPrompt,
1272
+ ...(reminder ? { reminder } : {}),
1273
+ leadingCommand: verbatim !== null,
1274
+ // Told only when an attempt carrying the note is sent (`runQueryOnce`).
1275
+ ...(mainSync && syncNote ? { mainSync: { reminder: syncNote, delivered: mainSync.told } } : {}),
1276
+ };
1230
1277
  }
1231
1278
  /**
1232
1279
  * The reviewer's prompt: the brief Convex wrote, with the evidence block this
@@ -1383,12 +1430,16 @@ export class BridgeJobExecutor {
1383
1430
  if (!controls.isActive()) {
1384
1431
  return { kind: "cancelled", costUsd: result.costUsd, model, modelUsage };
1385
1432
  }
1433
+ const shown = userFacingTurnError(error);
1434
+ if (shown !== errorMessage(error)) {
1435
+ console.error(`[BridgeJob] turn failed for thread ${job.threadId}: ${errorMessage(error)}`);
1436
+ }
1386
1437
  return {
1387
1438
  kind: "errored",
1388
1439
  costUsd: result.costUsd,
1389
1440
  model,
1390
1441
  modelUsage,
1391
- errors: [userFacingTurnError(errorMessage(error))],
1442
+ errors: [shown],
1392
1443
  };
1393
1444
  }
1394
1445
  usageBaselineFor(attempt) {
@@ -1460,7 +1511,7 @@ export class BridgeJobExecutor {
1460
1511
  async invalidResumeFallbackAttempt(job, controls, request, attempt, state, error) {
1461
1512
  if (!attempt.usedBoundary ||
1462
1513
  state.sawUserVisibleSdkMessage ||
1463
- (error instanceof Error && error.name === "SdkResultError") ||
1514
+ (error instanceof Error && error.name === "SdkResultError" && !isCliResumeRefusal(error)) ||
1464
1515
  !isResumeSessionError(error)) {
1465
1516
  return null;
1466
1517
  }
@@ -1480,6 +1531,7 @@ export class BridgeJobExecutor {
1480
1531
  return {
1481
1532
  prompt: buildRehydratedPrompt(rebuilt.prompt, job.history),
1482
1533
  ...(rebuilt.reminder ? { reminder: rebuilt.reminder } : {}),
1534
+ ...(rebuilt.reminder && rebuilt.mainSync ? { delivered: rebuilt.mainSync.delivered } : {}),
1483
1535
  attemptedRehydration: true,
1484
1536
  resumeOptions: {},
1485
1537
  };
@@ -1772,6 +1824,7 @@ export class BridgeJobExecutor {
1772
1824
  },
1773
1825
  ...attempt.resumeOptions,
1774
1826
  };
1827
+ await markDelivered(attempt, controls);
1775
1828
  const query = this.sdk.query({ prompt: attempt.prompt, reminder: attempt.reminder, options });
1776
1829
  controls.reloadMcpServers = () => this.reloadMcpServers(job, query);
1777
1830
  let queryClosed = false;
@@ -2081,7 +2134,8 @@ export class BridgeJobExecutor {
2081
2134
  }
2082
2135
  /**
2083
2136
  * A message consumed here and never relayed or counted as the agent's work:
2084
- * a provider refusal for size, or part of a model refusal.
2137
+ * a provider refusal for size, the CLI's report of a failed model request, or
2138
+ * part of a model refusal.
2085
2139
  */
2086
2140
  droppedBeforeRelay(job, state, msg) {
2087
2141
  // Drop the size refusal outright. A recovered turn must not leave a raw
@@ -2103,6 +2157,22 @@ export class BridgeJobExecutor {
2103
2157
  state.turnText = "";
2104
2158
  return true;
2105
2159
  }
2160
+ if (isApiErrorMessage(msg)) {
2161
+ // The provider's words, never the product's: a turn that recovers shows
2162
+ // nothing, and one that fails says so once through the error outcome.
2163
+ const text = messageContentBlocks(msg)
2164
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
2165
+ .join(" ");
2166
+ console.error(`[BridgeJob] model request failed for thread ${job.threadId}: ${text}`);
2167
+ this.recordTurnEvent({
2168
+ threadId: job.threadId,
2169
+ turnId: job.turnId,
2170
+ event: "api_error",
2171
+ detail: { error: msg.error, text },
2172
+ });
2173
+ state.turnText = "";
2174
+ return true;
2175
+ }
2106
2176
  return this.observeModelRefusal(job, state, msg);
2107
2177
  }
2108
2178
  /**
@@ -2216,6 +2286,10 @@ export class BridgeJobExecutor {
2216
2286
  if (state.detachedSession) {
2217
2287
  return;
2218
2288
  }
2289
+ if (reason === "abort") {
2290
+ await this.keepCancelledTurn(job, controls, state);
2291
+ return;
2292
+ }
2219
2293
  if (!state.usedBoundary && !state.inProgressSession.sawSessionId) {
2220
2294
  return;
2221
2295
  }
@@ -2227,6 +2301,25 @@ export class BridgeJobExecutor {
2227
2301
  });
2228
2302
  await this.sessionStore.clear(job.threadId, { runToken: controls.runToken, reason });
2229
2303
  }
2304
+ // A cancel (Stop, a replacing message, an answered card) is not a broken
2305
+ // session: the next turn resumes what this one completed (`buildCancelBoundary`).
2306
+ async keepCancelledTurn(job, controls, state) {
2307
+ const boundary = buildCancelBoundary({
2308
+ inProgress: state.inProgressSession,
2309
+ resumed: state.usedBoundary,
2310
+ request: state.requestPrompt,
2311
+ nowMs: this.now(),
2312
+ });
2313
+ this.recordTurnEvent({
2314
+ threadId: job.threadId,
2315
+ turnId: job.turnId,
2316
+ event: "cancel_resume_point",
2317
+ detail: { resumeFrom: state.inProgressSession.cancelPoint ? "cancelled_turn" : "previous_turn" },
2318
+ });
2319
+ if (boundary) {
2320
+ await this.sessionStore.save(job.threadId, boundary, { runToken: controls.runToken });
2321
+ }
2322
+ }
2230
2323
  // Parks the turn on a blocking dashboard prompt. An unanswered prompt must
2231
2324
  // NOT error the turn: the wait window ending resolves to `unanswered` so the
2232
2325
  // caller can deny the tool gracefully — the agent ends its turn cleanly and
@@ -2641,6 +2734,12 @@ function registerOrAutomateCasting(job, controls, toolName, command) {
2641
2734
  controls.avatarAwaitingCasting = created;
2642
2735
  return null;
2643
2736
  }
2737
+ /** The last step before the prompt goes out: a turn stopped before here never carried its note. */
2738
+ async function markDelivered(attempt, controls) {
2739
+ if (attempt.delivered && controls.isActive()) {
2740
+ await attempt.delivered();
2741
+ }
2742
+ }
2644
2743
  /** Baker's notes for the turn, sent as their own block beside the prompt (see `SessionAttempt.reminder`). */
2645
2744
  function turnReminder(job, verbatim, mainSync) {
2646
2745
  const reminders = [