@get-bb/plugin-sdk 0.6.59 → 0.6.65

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.
@@ -0,0 +1,18 @@
1
+ // src/internal/rpc-tags.ts
2
+ import { z } from "zod";
3
+ var rpcInvalidationTags = z.array(z.string().min(1)).min(1);
4
+ function rpcResponseTags(declarations, input, output) {
5
+ const tags = z.array(z.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
6
+ const keyTags = {};
7
+ if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
8
+ for (const [key, value] of Object.entries(output)) {
9
+ keyTags[key] = z.array(z.string().min(1)).parse(declarations.keyTags(key, value));
10
+ }
11
+ }
12
+ const invalidated = z.array(z.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
13
+ return { tags, keyTags, invalidated };
14
+ }
15
+ export {
16
+ rpcInvalidationTags,
17
+ rpcResponseTags
18
+ };
@@ -11663,6 +11663,18 @@ function whichCommandSync(command, options = {}) {
11663
11663
  }
11664
11664
 
11665
11665
  // ../process-utils/src/exec-portable-file.ts
11666
+ function resolvePortableCommand(command, options) {
11667
+ const envKeys = Object.keys(options.env).sort();
11668
+ const pathKey2 = envKeys.find((key) => key.toUpperCase() === "PATH");
11669
+ const pathExtKey = envKeys.find((key) => key.toUpperCase() === "PATHEXT");
11670
+ const commandExtension = extname2(command);
11671
+ const pathExt = options.env[pathExtKey ?? "PATHEXT"];
11672
+ return whichCommandSync(command, {
11673
+ cwd: options.cwd,
11674
+ path: options.env[pathKey2 ?? "PATH"],
11675
+ pathExt: commandExtension ? `${commandExtension};${pathExt ?? ".EXE;.COM;.CMD;.BAT"}` : pathExt
11676
+ });
11677
+ }
11666
11678
  async function execPortableFile(command, args, options) {
11667
11679
  const executable = basename(command).toLowerCase().replace(/\.(exe|cmd|bat)$/u, "");
11668
11680
  if (executable === "git" || executable === "gh") {
@@ -11680,26 +11692,15 @@ async function execPortableFile(command, args, options) {
11680
11692
  }
11681
11693
  async function execPortableFileUnbounded(command, args, options) {
11682
11694
  if (options.signal?.aborted) throw options.signal.reason;
11683
- if (process.platform === "win32") {
11684
- const envKeys = Object.keys(options.env).sort();
11685
- const pathKey2 = envKeys.find((key) => key.toUpperCase() === "PATH");
11686
- const pathExtKey = envKeys.find((key) => key.toUpperCase() === "PATHEXT");
11687
- const commandExtension = extname2(command);
11688
- const pathExt = options.env[pathExtKey ?? "PATHEXT"];
11689
- if (whichCommandSync(command, {
11690
- cwd: options.cwd,
11691
- path: options.env[pathKey2 ?? "PATH"],
11692
- pathExt: commandExtension ? `${commandExtension};${pathExt ?? ".EXE;.COM;.CMD;.BAT"}` : pathExt
11693
- }) === void 0) {
11694
- throw Object.assign(new Error(`spawn ${command} ENOENT`), {
11695
- code: "ENOENT",
11696
- syscall: `spawn ${command}`,
11697
- stdout: "",
11698
- stderr: "",
11699
- signal: null,
11700
- killed: false
11701
- });
11702
- }
11695
+ if (process.platform === "win32" && resolvePortableCommand(command, options) === void 0) {
11696
+ throw Object.assign(new Error(`spawn ${command} ENOENT`), {
11697
+ code: "ENOENT",
11698
+ syscall: `spawn ${command}`,
11699
+ stdout: "",
11700
+ stderr: "",
11701
+ signal: null,
11702
+ killed: false
11703
+ });
11703
11704
  }
11704
11705
  const subprocess = execa(command, args, {
11705
11706
  cwd: options.cwd,
@@ -11841,20 +11842,6 @@ function versionFrom(value) {
11841
11842
  const candidate = value?.match(/\bv?(\d+\.\d+\.\d+[0-9A-Za-z.+-]*)/u)?.[1];
11842
11843
  return candidate !== void 0 && (0, import_valid.default)(candidate) !== null ? candidate : null;
11843
11844
  }
11844
- async function readCliVersion(command) {
11845
- try {
11846
- const { stdout, stderr } = await execPortableFile(command, ["--version"], {
11847
- cwd: process.cwd(),
11848
- env: process.env,
11849
- maxBuffer: 1024 * 1024,
11850
- timeout: CLI_PROBE_TIMEOUT_MS
11851
- });
11852
- return versionFrom(`${stdout}
11853
- ${stderr}`);
11854
- } catch {
11855
- return null;
11856
- }
11857
- }
11858
11845
  function downloadedInstallerCommand(url2, options = {}) {
11859
11846
  if ((options.platform ?? process.platform) === "win32" && options.powershellUrl !== void 0) {
11860
11847
  const powershellScript = `irm ${options.powershellUrl} | iex`;
@@ -11909,7 +11896,7 @@ var ignoredJsonRpcResultSchema = z35.unknown();
11909
11896
 
11910
11897
  // ../provider-bridge-acp/src/bridge/bridge.ts
11911
11898
  import { randomBytes as randomBytes2 } from "node:crypto";
11912
- import { promises as fs4, readFileSync as readFileSync3 } from "node:fs";
11899
+ import { promises as fs4, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
11913
11900
  import { createServer } from "node:net";
11914
11901
  import { dirname as dirname2, isAbsolute as isAbsolute2, basename as basename4, relative as relative2, resolve as resolve4 } from "node:path";
11915
11902
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -12283,6 +12270,7 @@ var acpBridgeCommandMethodValues = acpBridgeCommandSchema.options.map(
12283
12270
  );
12284
12271
  var ACP_TURN_STARTED_METHOD = "acp/turn/started";
12285
12272
  var ACP_TURN_COMPLETED_METHOD = "acp/turn/completed";
12273
+ var ACP_PROMPT_INTERRUPTED_METHOD = "acp/prompt/interrupted";
12286
12274
  var ACP_COMPACTION_STARTED_METHOD = "acp/compaction/started";
12287
12275
  var ACP_COMPACTION_COMPLETED_METHOD = "acp/compaction/completed";
12288
12276
  var ACP_UPDATE_METHOD = "acp/update";
@@ -12378,6 +12366,7 @@ var storedOAuthSchema = z38.object({
12378
12366
  orgID: z38.string().min(1)
12379
12367
  })
12380
12368
  });
12369
+ var OPENCODE_2_CREDENTIAL_IMPORT_MIGRATION = "20260805200742_import_legacy_credentials";
12381
12370
  function isOfficialConsole(url2) {
12382
12371
  const issuer = new URL(url2);
12383
12372
  return issuer.origin === "https://opencode.ai" && ["/", "/console", "/console/"].includes(issuer.pathname);
@@ -12432,7 +12421,7 @@ function readStoredCredential(database) {
12432
12421
  ).get();
12433
12422
  if (!table) return null;
12434
12423
  const query = database.prepare(
12435
- "SELECT value FROM credential WHERE integration_id = ? AND active = 1 ORDER BY time_created DESC, id DESC LIMIT 1"
12424
+ "SELECT value FROM credential WHERE integration_id = ? ORDER BY active DESC, time_created DESC, id DESC LIMIT 1"
12436
12425
  );
12437
12426
  for (const provider of ["opencode-go", "opencode"]) {
12438
12427
  const row = query.get(provider);
@@ -12460,6 +12449,13 @@ function readStoredCredential(database) {
12460
12449
  }
12461
12450
  return null;
12462
12451
  }
12452
+ function isOpenCode2Database(database) {
12453
+ const table = database.prepare(
12454
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'migration'"
12455
+ ).get();
12456
+ if (!table) return false;
12457
+ return database.prepare("SELECT id FROM migration WHERE id = ?").get(OPENCODE_2_CREDENTIAL_IMPORT_MIGRATION) !== void 0;
12458
+ }
12463
12459
  async function readLegacyApiKey(env) {
12464
12460
  let content = env.OPENCODE_AUTH_CONTENT;
12465
12461
  if (content) {
@@ -12500,25 +12496,27 @@ async function readOpenCodeGoUsage(env) {
12500
12496
  });
12501
12497
  let apiKey;
12502
12498
  let account = null;
12499
+ let openCode2 = false;
12503
12500
  try {
12504
12501
  apiKey = env.OPENCODE_API_KEY?.trim() || null;
12505
12502
  if (apiKey === null) {
12506
12503
  const database = await openDatabase(env);
12507
12504
  if (database) {
12508
12505
  try {
12509
- account = readAccount(database);
12510
- if (account) {
12511
- apiKey = account.access_token;
12512
- } else {
12506
+ openCode2 = isOpenCode2Database(database);
12507
+ if (openCode2) {
12513
12508
  const stored = readStoredCredential(database);
12514
12509
  apiKey = stored?.apiKey ?? null;
12515
12510
  account = stored?.account ?? null;
12511
+ } else {
12512
+ account = readAccount(database);
12513
+ apiKey = account?.access_token ?? null;
12516
12514
  }
12517
12515
  } finally {
12518
12516
  database.close();
12519
12517
  }
12520
12518
  }
12521
- apiKey ??= await readLegacyApiKey(env);
12519
+ if (!openCode2) apiKey ??= await readLegacyApiKey(env);
12522
12520
  }
12523
12521
  } catch {
12524
12522
  return failure("OpenCode credentials could not be read.");
@@ -12691,6 +12689,23 @@ function healthResult(args) {
12691
12689
  }
12692
12690
  };
12693
12691
  }
12692
+ async function readAcpCliVersion(command) {
12693
+ try {
12694
+ const { stdout, stderr } = await execPortableFile(command, ["--version"], {
12695
+ cwd: process.cwd(),
12696
+ env: process.env,
12697
+ maxBuffer: 1024 * 1024,
12698
+ timeout: 5e3
12699
+ });
12700
+ const output = `${stdout}
12701
+ ${stderr}`;
12702
+ return versionFrom(output) ?? output.match(
12703
+ /(?:^|\s)(\d{4}\.(?:0[1-9]|1[0-2])\.(?:0[1-9]|[12]\d|3[01])-[0-9a-f]+)(?=\s|$)/u
12704
+ )?.[1] ?? null;
12705
+ } catch {
12706
+ return null;
12707
+ }
12708
+ }
12694
12709
  async function getAcpProviderHealth(args) {
12695
12710
  const maintenance = args.maintenance;
12696
12711
  if (args.command === null) {
@@ -12703,7 +12718,7 @@ async function getAcpProviderHealth(args) {
12703
12718
  if (await resolveExecutablePath(args.command) === null) {
12704
12719
  return healthResult({ maintenance, status: "not_installed" });
12705
12720
  }
12706
- const version = await readCliVersion(args.command);
12721
+ const version = await readAcpCliVersion(args.command);
12707
12722
  if (maintenance === void 0) {
12708
12723
  return healthResult({
12709
12724
  maintenance,
@@ -12732,7 +12747,7 @@ async function getAcpProviderInstallationStatus(args) {
12732
12747
  const executableName = args.command ?? "";
12733
12748
  const resolvedExecutable = args.command === null ? null : await resolveExecutablePath(args.command);
12734
12749
  const installed = resolvedExecutable !== null;
12735
- const currentVersion = installed && args.command !== null ? await readCliVersion(args.command) : null;
12750
+ const currentVersion = installed && args.command !== null ? await readAcpCliVersion(args.command) : null;
12736
12751
  const installAction = args.maintenance !== void 0 && !installed ? {
12737
12752
  kind: "install",
12738
12753
  label: "Install",
@@ -13308,25 +13323,35 @@ function fileChangeVerb(changes, fallback) {
13308
13323
  }
13309
13324
  return "update";
13310
13325
  }
13326
+ var DEV_NULL_OLD_TEXT = /^-{2,3} \/dev\/null$/u;
13327
+ var NEW_FILE_HEADER = /^\+{2,3} b\/[^\n]*(?:\n|$)/u;
13311
13328
  function buildAcpFileChanges(event, operation, options) {
13312
13329
  const changes = [];
13313
13330
  for (const entry of event.content ?? []) {
13314
13331
  if (entry.type !== "diff") {
13315
13332
  continue;
13316
13333
  }
13317
- const oldText = entry.oldText ?? void 0;
13334
+ const createsFile = entry.oldText === null || entry.oldText === void 0 || DEV_NULL_OLD_TEXT.test(entry.oldText);
13318
13335
  changes.push({
13319
13336
  path: resolveAcpToolCallPath(entry.path, options),
13320
- kind: oldText === void 0 ? "add" : "update",
13321
- ...oldText === void 0 ? {} : { oldText },
13322
- newText: entry.newText
13337
+ kind: createsFile ? "add" : "update",
13338
+ ...createsFile ? {} : { oldText: entry.oldText ?? void 0 },
13339
+ newText: createsFile ? entry.newText.replace(NEW_FILE_HEADER, "") : entry.newText
13323
13340
  });
13324
13341
  }
13325
13342
  if (changes.length > 0) {
13326
13343
  return changes;
13327
13344
  }
13328
13345
  const [path13] = operation.paths;
13329
- return path13 === void 0 ? [] : [{ path: path13, kind: operation.changeKind }];
13346
+ if (path13 === void 0) {
13347
+ return [];
13348
+ }
13349
+ return [
13350
+ {
13351
+ path: path13,
13352
+ kind: operation.changeKind === "update" && options?.existedBefore?.get(path13) === false ? "add" : operation.changeKind
13353
+ }
13354
+ ];
13330
13355
  }
13331
13356
  function fileChangeItem(changes, fallbackVerb) {
13332
13357
  return {
@@ -14218,6 +14243,34 @@ function createAcpDeltaTranslator(options = {}) {
14218
14243
  const dialect = options.dialect ?? GENERIC_ACP_DIALECT;
14219
14244
  const pathOptions = { cwd: options.cwd };
14220
14245
  const mergedToolCalls = /* @__PURE__ */ new Map();
14246
+ const fileExistence = /* @__PURE__ */ new Map();
14247
+ const filesAddedThisTurn = /* @__PURE__ */ new Set();
14248
+ function noteEditedPaths(key, event) {
14249
+ const fileCreatedThisTurn = options.fileCreatedThisTurn;
14250
+ if (fileCreatedThisTurn === void 0 || event.kind !== "edit") {
14251
+ return;
14252
+ }
14253
+ const seen = fileExistence.get(key) ?? /* @__PURE__ */ new Map();
14254
+ for (const location of event.locations ?? []) {
14255
+ const resolved = resolveAcpToolCallPath(location.path, pathOptions);
14256
+ if (seen.has(resolved)) {
14257
+ continue;
14258
+ }
14259
+ const created = fileCreatedThisTurn(resolved);
14260
+ if (created === void 0) {
14261
+ seen.set(resolved, void 0);
14262
+ continue;
14263
+ }
14264
+ const added = created && !filesAddedThisTurn.has(resolved);
14265
+ if (added) {
14266
+ filesAddedThisTurn.add(resolved);
14267
+ }
14268
+ seen.set(resolved, !added);
14269
+ }
14270
+ if (seen.size > 0) {
14271
+ fileExistence.set(key, seen);
14272
+ }
14273
+ }
14221
14274
  let lastUsageCost;
14222
14275
  let lastAgentTitle;
14223
14276
  let injectedToolsByName = /* @__PURE__ */ new Map();
@@ -14302,7 +14355,10 @@ function createAcpDeltaTranslator(options = {}) {
14302
14355
  return dialectShape;
14303
14356
  }
14304
14357
  }
14305
- return classifyAcpToolCall2(event, injected, pathOptions);
14358
+ return classifyAcpToolCall2(event, injected, {
14359
+ ...pathOptions,
14360
+ existedBefore: fileExistence.get(callKey(context, event.toolCallId))
14361
+ });
14306
14362
  }
14307
14363
  function withClientFileWrites(event, writes) {
14308
14364
  if (writes.length === 0) {
@@ -14473,6 +14529,7 @@ function createAcpDeltaTranslator(options = {}) {
14473
14529
  args.permissionTitle
14474
14530
  );
14475
14531
  injectedToolBindings.delete(callKey(args.context, args.event.toolCallId));
14532
+ fileExistence.delete(callKey(args.context, args.event.toolCallId));
14476
14533
  const closeFields = classified.item.type === "command" ? commandCloseFields(args.event, args.status) : genericCloseFields(args.event);
14477
14534
  return {
14478
14535
  kind: "item.close",
@@ -14570,6 +14627,7 @@ function createAcpDeltaTranslator(options = {}) {
14570
14627
  if (bound !== void 0) {
14571
14628
  injectedToolBindings.set(announcedKey, bound);
14572
14629
  }
14630
+ noteEditedPaths(announcedKey, event);
14573
14631
  if (isTerminalAcpStatus(event.status)) {
14574
14632
  return [
14575
14633
  ...flush,
@@ -14611,6 +14669,7 @@ function createAcpDeltaTranslator(options = {}) {
14611
14669
  mergeAcpToolCallEvents(open?.event, event),
14612
14670
  open?.clientFileWrites ?? []
14613
14671
  );
14672
+ noteEditedPaths(key, merged);
14614
14673
  if (isTerminalAcpStatus(merged.status)) {
14615
14674
  mergedToolCalls.delete(key);
14616
14675
  return [
@@ -14787,8 +14846,18 @@ function createAcpDeltaTranslator(options = {}) {
14787
14846
  return [];
14788
14847
  }
14789
14848
  clearThreadCalls(context);
14849
+ filesAddedThisTurn.clear();
14790
14850
  return [{ kind: "turn.open" }];
14791
14851
  }
14852
+ case ACP_PROMPT_INTERRUPTED_METHOD: {
14853
+ const params = acpTurnStartedNotificationParamsSchema.safeParse(
14854
+ envelope.data.params
14855
+ );
14856
+ if (!params.success) {
14857
+ return [];
14858
+ }
14859
+ return drainOpenToolCalls(context, "interrupted");
14860
+ }
14792
14861
  case ACP_TURN_COMPLETED_METHOD: {
14793
14862
  const params = acpTurnCompletedNotificationParamsSchema.safeParse(
14794
14863
  envelope.data.params
@@ -21429,6 +21498,7 @@ var pendingRuntimeRequests = /* @__PURE__ */ new Map();
21429
21498
  var runtimeRequestIdCounter = 0;
21430
21499
  var dynamicToolBridgePromise = null;
21431
21500
  var THREAD_STOP_CANCEL_TIMEOUT_MS = 4e3;
21501
+ var SHUTDOWN_CANCEL_TIMEOUT_MS = 1500;
21432
21502
  var AGENT_TURN_QUIET_MS = 5e3;
21433
21503
  var SESSION_BUSY_QUIET_MS = 2e3;
21434
21504
  var SESSION_BUSY_MAX_WAITS = 300;
@@ -22482,23 +22552,39 @@ async function selectAcpNativeServiceTier(args) {
22482
22552
  });
22483
22553
  recordAcpConfigValue(args.session, configState, fastOption.id, value);
22484
22554
  }
22485
- function textWithoutUnknownLeadingSkillCommand(session, item) {
22486
- const advertised = session.model.snapshot().commands;
22487
- if (advertised.length === 0) {
22488
- return item.text;
22489
- }
22490
- const firstCharacter = item.text.search(/\S/u);
22491
- const leading = item.mentions.find(
22492
- (mention) => mention.start === firstCharacter && mention.resource.kind === "command" && mention.resource.source === "skill" && mention.resource.trigger === "/"
22555
+ function textWithBbSkillCommandsSpelledOut(session, item) {
22556
+ const bbSkillNames = new Set(
22557
+ (configuredSkillRoots ?? []).flatMap(
22558
+ (root) => root.skills.map((skill) => skill.name)
22559
+ )
22493
22560
  );
22494
- if (!leading || leading.resource.kind !== "command") {
22561
+ if (bbSkillNames.size === 0) {
22495
22562
  return item.text;
22496
22563
  }
22497
- const name = leading.resource.name;
22498
- if (advertised.some((command) => command.name === name)) {
22499
- return item.text;
22564
+ const advertised = new Set(
22565
+ session.model.snapshot().commands.map((command) => command.name)
22566
+ );
22567
+ const mentions = item.mentions.flatMap(
22568
+ (mention) => mention.resource.kind === "command" && mention.resource.source === "skill" && mention.resource.trigger === "/" && bbSkillNames.has(mention.resource.name) && !advertised.has(mention.resource.name) && item.text.slice(mention.start, mention.end) === `/${mention.resource.name}` ? [
22569
+ {
22570
+ start: mention.start,
22571
+ end: mention.end,
22572
+ name: mention.resource.name
22573
+ }
22574
+ ] : []
22575
+ ).sort((a2, b) => b.start - a2.start);
22576
+ const firstCharacter = item.text.search(/\S/u);
22577
+ let text = item.text;
22578
+ let nextStart = text.length;
22579
+ for (const mention of mentions) {
22580
+ if (mention.end > nextStart) {
22581
+ continue;
22582
+ }
22583
+ const leadsText = mention.start === firstCharacter && text.slice(mention.end).trim().length > 0;
22584
+ text = `${text.slice(0, mention.start)}Use the bb skill "${mention.name}"${leadsText ? ":" : ""}${text.slice(mention.end)}`;
22585
+ nextStart = mention.start;
22500
22586
  }
22501
- return `${item.text.slice(0, leading.start)}Use the bb skill "${name}":${item.text.slice(leading.end)}`;
22587
+ return text;
22502
22588
  }
22503
22589
  function buildPromptContentBlocks(session, input) {
22504
22590
  const blocks = [];
@@ -22512,12 +22598,12 @@ ${instructions}
22512
22598
  </system_instructions>`
22513
22599
  });
22514
22600
  }
22515
- for (const [index, item] of input.entries()) {
22601
+ for (const item of input) {
22516
22602
  switch (item.type) {
22517
22603
  case "text":
22518
22604
  blocks.push({
22519
22605
  type: "text",
22520
- text: index === 0 ? textWithoutUnknownLeadingSkillCommand(session, item) : item.text
22606
+ text: textWithBbSkillCommandsSpelledOut(session, item)
22521
22607
  });
22522
22608
  break;
22523
22609
  case "image":
@@ -22817,6 +22903,33 @@ function getSessionByProviderThreadId(providerThreadId) {
22817
22903
  const bbThreadId = bbThreadIdByProviderThreadId.get(providerThreadId);
22818
22904
  return bbThreadId ? sessionsByBbThreadId.get(bbThreadId) : void 0;
22819
22905
  }
22906
+ function fileCreatedSince(path13, sinceMs) {
22907
+ if (sinceMs === void 0) {
22908
+ return void 0;
22909
+ }
22910
+ try {
22911
+ const { birthtimeMs } = statSync2(path13);
22912
+ return birthtimeMs > 0 ? birthtimeMs >= sinceMs : void 0;
22913
+ } catch {
22914
+ return void 0;
22915
+ }
22916
+ }
22917
+ function dialectLaunchEnv(dialectId, permissionMode) {
22918
+ if (dialectId !== "opencode") {
22919
+ return {};
22920
+ }
22921
+ const outsideEdits = permissionMode === "full" ? "allow" : "ask";
22922
+ return {
22923
+ OPENCODE_CLIENT: "acp",
22924
+ OPENCODE_ENABLE_QUESTION_TOOL: "false",
22925
+ OPENCODE_PERMISSION: JSON.stringify({
22926
+ edit: "allow",
22927
+ bash: outsideEdits,
22928
+ webfetch: outsideEdits,
22929
+ external_directory: outsideEdits
22930
+ })
22931
+ };
22932
+ }
22820
22933
  async function startAgentSession(request) {
22821
22934
  const params = request.params;
22822
22935
  const bbThreadId = params.threadId;
@@ -22830,7 +22943,8 @@ async function startAgentSession(request) {
22830
22943
  });
22831
22944
  const translator = createAcpDeltaTranslator({
22832
22945
  cwd: params.cwd,
22833
- dialect
22946
+ dialect,
22947
+ fileCreatedThisTurn: (path13) => fileCreatedSince(path13, session.turnStartedAtMs)
22834
22948
  });
22835
22949
  translator.configureInjectedTools(
22836
22950
  (params.dynamicTools ?? []).map((tool) => ({
@@ -22859,7 +22973,7 @@ async function startAgentSession(request) {
22859
22973
  const childEnv = {
22860
22974
  ...withoutBridgeRuntimeEnv(process.env),
22861
22975
  ...params.envVars,
22862
- ...dialect.id === "opencode" ? { OPENCODE_CLIENT: "acp", OPENCODE_ENABLE_QUESTION_TOOL: "false" } : {}
22976
+ ...dialectLaunchEnv(dialect.id, params.permissionMode)
22863
22977
  };
22864
22978
  const connection = createBridgeAgentConnection({
22865
22979
  command: params.agent.command,
@@ -22917,6 +23031,7 @@ async function startAgentSession(request) {
22917
23031
  queuedInputs: [],
22918
23032
  promptRequestPending: false,
22919
23033
  cancelRequested: false,
23034
+ turnStartedAtMs: void 0,
22920
23035
  restartAfterCancelError: false,
22921
23036
  loading: false,
22922
23037
  loadingSessionId: void 0,
@@ -23125,7 +23240,7 @@ async function startAgentSession(request) {
23125
23240
  });
23126
23241
  }
23127
23242
  }
23128
- async function stopSession(session) {
23243
+ async function stopSession(session, cancelTimeoutMs = THREAD_STOP_CANCEL_TIMEOUT_MS) {
23129
23244
  if (session.stopping) {
23130
23245
  return;
23131
23246
  }
@@ -23143,7 +23258,7 @@ async function stopSession(session) {
23143
23258
  await Promise.race([
23144
23259
  session.turnSettled,
23145
23260
  new Promise(
23146
- (resolveTimeout) => setTimeout(resolveTimeout, THREAD_STOP_CANCEL_TIMEOUT_MS)
23261
+ (resolveTimeout) => setTimeout(resolveTimeout, cancelTimeoutMs)
23147
23262
  )
23148
23263
  ]);
23149
23264
  }
@@ -23425,6 +23540,7 @@ function finishTurn(session, stopReason) {
23425
23540
  if (session.activePromptKind !== "turn") {
23426
23541
  return;
23427
23542
  }
23543
+ session.turnStartedAtMs = void 0;
23428
23544
  for (const controller of session.pendingToolCalls) controller.abort();
23429
23545
  setActivePromptKind(session, null);
23430
23546
  dropQueuedTurnInputs(session, "ACP turn ended before the steer was sent");
@@ -23503,6 +23619,7 @@ function runTurn(session, firstInput, turnAlreadyOpen = false) {
23503
23619
  const prompt = buildPromptContentBlocks(session, pending.input);
23504
23620
  let inputAccepted = false;
23505
23621
  let busyRetries = 0;
23622
+ session.turnStartedAtMs ??= Date.now();
23506
23623
  for (; ; ) {
23507
23624
  session.promptRequestPending = true;
23508
23625
  const promptResult = session.connection.request({
@@ -23563,6 +23680,11 @@ function runTurn(session, firstInput, turnAlreadyOpen = false) {
23563
23680
  if (!session.stopping) {
23564
23681
  const next = session.queuedInputs.shift();
23565
23682
  if (next) {
23683
+ if (stopReason === "cancelled") {
23684
+ emitForSession(session, ACP_PROMPT_INTERRUPTED_METHOD, {
23685
+ threadId: session.bbThreadId
23686
+ });
23687
+ }
23566
23688
  pending = next;
23567
23689
  continue;
23568
23690
  }
@@ -23606,6 +23728,15 @@ function reconcileExecutionSettings(session, options) {
23606
23728
  permissionMode: options.permissionMode,
23607
23729
  workspaceWriteRoots
23608
23730
  };
23731
+ const launchModelChanged = !isDeepStrictEqual(
23732
+ launchModelSelection(session.construction),
23733
+ launchModelSelection(construction)
23734
+ );
23735
+ if (launchModelChanged && !session.supportsLoadSession) {
23736
+ throw new Error(
23737
+ "This ACP agent cannot restore its session. Start a new thread to change the launch-time model or reasoning level."
23738
+ );
23739
+ }
23609
23740
  const launchArgsChanged = !isDeepStrictEqual(
23610
23741
  permissionCliArgsForMode(
23611
23742
  session.construction.permissionCli,
@@ -23616,9 +23747,9 @@ function reconcileExecutionSettings(session, options) {
23616
23747
  construction.permissionMode
23617
23748
  )
23618
23749
  ) || !isDeepStrictEqual(
23619
- launchModelSelection(session.construction),
23620
- launchModelSelection(construction)
23621
- );
23750
+ dialectLaunchEnv(session.dialect.id, session.construction.permissionMode),
23751
+ dialectLaunchEnv(session.dialect.id, construction.permissionMode)
23752
+ ) || launchModelChanged;
23622
23753
  const restart = session.connection.exited || session.restartAfterCancelError || launchArgsChanged || !isDeepStrictEqual(envVars ?? {}, session.construction.envVars ?? {});
23623
23754
  cancelPendingPermissions(session);
23624
23755
  session.policy = {
@@ -24235,13 +24366,21 @@ function handleParsedMessage(parsed) {
24235
24366
  }
24236
24367
  var handleLine = createBridgeLineHandler({ handleParsedMessage });
24237
24368
  async function stopAllSessions() {
24369
+ const sessions = Array.from(sessionsByBbThreadId.values());
24370
+ const sessionConnections = new Set(
24371
+ sessions.map((session) => session.connection)
24372
+ );
24238
24373
  const results = await Promise.allSettled([
24239
- ...Array.from(
24240
- sessionsByBbThreadId.values(),
24241
- (session) => releaseSession(session)
24374
+ ...sessions.map(
24375
+ (session) => stopSession(session, SHUTDOWN_CANCEL_TIMEOUT_MS)
24242
24376
  ),
24243
- ...Array.from(agentConnections, (connection) => connection.kill())
24377
+ ...Array.from(agentConnections).filter((connection) => !sessionConnections.has(connection)).map((connection) => connection.kill())
24244
24378
  ]);
24379
+ results.push(
24380
+ ...await Promise.allSettled(
24381
+ Array.from(agentConnections, (connection) => connection.kill())
24382
+ )
24383
+ );
24245
24384
  for (const result of results) {
24246
24385
  if (result.status === "rejected") {
24247
24386
  process.stderr.write(