@bike4mind/cli 4.6.0 → 4.8.0

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 (40) hide show
  1. package/README.md +98 -0
  2. package/dist/{AgentHistoryStore--J3sgO_-.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +23 -17
  3. package/dist/{ApiClient-CdO4Gamg.mjs → ApiClient-Yp2LPlX3.mjs} +3 -3
  4. package/dist/{BubblewrapRuntime-3jAbC60G.mjs → BubblewrapRuntime-OI4qFPNB.mjs} +2 -2
  5. package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
  6. package/dist/{ConfigStore-Dusy6glb.mjs → ConfigStore-CP1W86Ui.mjs} +100 -26
  7. package/dist/{Logger-C1Wj6xla.mjs → Logger-3RbeTZ9o.mjs} +1921 -319
  8. package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
  9. package/dist/{SandboxOrchestrator-CQwYq_uy.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +1 -1
  10. package/dist/{SandboxRuntimeAdapter-BsT2iLky.mjs → SandboxRuntimeAdapter-C3xICJtQ.mjs} +2 -2
  11. package/dist/{SandboxRuntimeAdapter-Zg_0th7V.mjs → SandboxRuntimeAdapter-u6c_IrjP.mjs} +1 -1
  12. package/dist/{SeatbeltRuntime-C2DEkrjy.mjs → SeatbeltRuntime-Ccd_QbjX.mjs} +2 -2
  13. package/dist/{WorkItemsClient-CxNZaOmc.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
  14. package/dist/{buildToolSearch-DOb7mx6F.mjs → buildToolSearch-CqHKSLtG.mjs} +2 -2
  15. package/dist/commands/acpCommand.mjs +6 -6
  16. package/dist/commands/apiCommand.mjs +1 -1
  17. package/dist/commands/doctorCommand.mjs +2 -2
  18. package/dist/commands/envCommand.mjs +1 -1
  19. package/dist/commands/headlessCommand.mjs +7 -7
  20. package/dist/commands/hostCommand.mjs +1 -1
  21. package/dist/commands/mcpCommand.mjs +3 -3
  22. package/dist/commands/mirrorCommand.mjs +2 -2
  23. package/dist/commands/modelsCommand.mjs +5 -5
  24. package/dist/commands/pluginCommand.mjs +1 -1
  25. package/dist/commands/skillsCommand.mjs +4 -4
  26. package/dist/commands/updateCommand.mjs +2 -2
  27. package/dist/{dist-CbViwiS9.mjs → dist-BPhZ0dCz.mjs} +48 -11
  28. package/dist/{dist-Citbv0y0.mjs → dist-K7a9yOUb.mjs} +3 -3
  29. package/dist/{fit-CVWDiavv.mjs → fit-BOnDsgbk.mjs} +4 -4
  30. package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
  31. package/dist/index.mjs +2493 -222
  32. package/dist/{modelServers-BaegigV-.mjs → modelServers-B7zI5XnO.mjs} +2 -2
  33. package/dist/{package-C9pfAdGF.mjs → package-WlxLVpUb.mjs} +1 -1
  34. package/dist/{serve-8wyGb8of.mjs → serve-DpsV0mag.mjs} +13 -9
  35. package/dist/store-Bpdo9Syo.mjs +2 -0
  36. package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
  37. package/dist/{updateChecker-BAKb8KWP.mjs → updateChecker-Boq0RruU.mjs} +1 -1
  38. package/package.json +12 -12
  39. package/dist/ConfigStore-CausUCzY.mjs +0 -2
  40. package/dist/store-BYeE0shc.mjs +0 -2
package/README.md CHANGED
@@ -988,6 +988,104 @@ to trust it. Pending repo MCP servers stay off with the usual warning. Context t
988
988
  host needs should reach the session through `--append-system-prompt` and
989
989
  `--mcp-config`.
990
990
 
991
+ ## Local CLI session messaging
992
+
993
+ On macOS and Linux, independently launched interactive CLI sessions can discover
994
+ and message each other without Desktop running. Messaging is off at startup;
995
+ repository settings, agent tools, and saved histories cannot enable it.
996
+
997
+ In two terminals working in the same repository (separate Git worktrees work):
998
+
999
+ 1. Run `/peers on api-worker` in the first terminal and `/peers on client-worker`
1000
+ in the second. Each command prints that process's session ID.
1001
+ 2. Run `/peers list` to see reachable sessions and their advertised readiness.
1002
+ 3. Run `/peers send <session-id> The response field is now displayName.`
1003
+ 4. In the recipient, inspect `/peers inbox`, then run `/peers release <message-id>`
1004
+ to approve that message. It runs only when the recipient is safely idle.
1005
+ 5. The sender can run `/peers status <session-id> <message-id>` for the exact
1006
+ correlated result. The recipient can send an explicit reply with
1007
+ `/peers reply <received-message-id> Confirmed; the client uses displayName.`
1008
+
1009
+ Incoming messages are held by default. `/peers accept` explicitly allows pending
1010
+ and future incoming messages to start idle model turns and incur usage.
1011
+ `/peers hold` pauses pending delivery; `/peers refuse` rejects incoming work.
1012
+ `/peers cancel <session-id> <message-id>` withdraws an undelivered message, and
1013
+ `/peers delete <message-id>` removes stored message content when safe.
1014
+ `/peers off` unregisters the session and closes its local endpoint.
1015
+ If a receiver has gone away, deleting an unresolved outgoing receipt archives it
1016
+ locally and retains a bounded tombstone. It does not cancel or retry remote work.
1017
+ Already running work may still finish after `/peers off`; its correlated outcome
1018
+ is saved for this conversation's history without starting more work.
1019
+
1020
+ While enabled, the agent has `peer_list`, `peer_send`, and `peer_status` tools, but cannot enable
1021
+ messaging or change inbound policy. Every agent send requires a separate human
1022
+ review, including in auto-accept mode. Peer-origin turns can only send back to
1023
+ their sender and preserve the reply hop limit. A message is peer input, never
1024
+ human permission, and cannot answer approval prompts or bypass denied actions.
1025
+ Approval identifies the recipient process and conversation before sending. If
1026
+ that recipient restarts while approval is pending, request a new approval.
1027
+ The recipient-specific review is the single normal send prompt, and it runs
1028
+ for every payload even in auto-accept mode. Plan mode and explicit tool denials
1029
+ still apply before that review. Human `/peers send` and `/peers reply`
1030
+ commands are independent of the agent's reply chain and send allowance.
1031
+
1032
+ Discovery is limited to the same local user, account/API environment, canonical
1033
+ repository, and additional granted directories. Local-only profiles use the
1034
+ user-owned CLI profile identity. Other projects/accounts and different folder
1035
+ grants cannot communicate in this release; explicit cross-scope pairing is not
1036
+ implemented. Session/model/account/folder changes disable messaging and require
1037
+ another `/peers on`. Automatic delivery is paused outside normal permission mode,
1038
+ while drafting input, while another turn holds the session, and during dialogs.
1039
+
1040
+ Only explicit text crosses the connection. Messages do not expand `@file` or
1041
+ image references, execute slash commands, or attach full conversation histories.
1042
+ Receiving agents can use their own tools subject to their existing permissions.
1043
+ Human input entered during peer work waits for a separate human turn. Its text
1044
+ and expanded file references are not steered into the peer's turn or its result.
1045
+ Custom commands, generated handoffs, compaction, and rewind are unavailable until
1046
+ peer work finishes. Replacing the conversation retires peer enrollment and prevents late
1047
+ peer output from entering the replacement conversation.
1048
+ Transport credentials stay outside model context in owner-only registry files
1049
+ under `~/.bike4mind/peers`. These controls do not isolate malicious programs
1050
+ already running as the same OS user.
1051
+ The CLI secures its own config and peer directories to 0700 when enabling peers;
1052
+ it does not change arbitrary parent-directory permissions. Unsafe ancestors or
1053
+ uncertain stale enrollment claims produce an actionable error instead of being
1054
+ silently trusted. A terminal transport failure disables peer tools and prints a
1055
+ notice; re-enroll only after resolving the reported problem.
1056
+
1057
+ Messages are limited to 8 KiB UTF-8, with 20 pending messages per recipient,
1058
+ two agent sends per turn, a five-hop reply-chain limit, and per-sender rate
1059
+ limits. Pending messages expire after 15 minutes. Receipt content is bounded
1060
+ and retained for up to seven days; unresolved outgoing receipts in the current
1061
+ process retain visible status metadata until reconciled. Correlated result
1062
+ previews are bounded separately.
1063
+ Queued/held, delivered, completed, stopped, cancelled, failed, expired, rejected,
1064
+ and unknown are separate states. Completed means the turn finished, not that its
1065
+ claims were independently verified. An ambiguous disconnect is unknown; do not
1066
+ blindly resend it.
1067
+ Sender-side deadlines cannot prove remote work expired. Unconfirmed outgoing
1068
+ work remains unknown and visible until its remote status is reconciled, including
1069
+ when the recipient started running before the deadline. If that receiver is no
1070
+ longer discoverable, the user can archive the local receipt without claiming the
1071
+ execution stopped.
1072
+ If a model turn finishes but its conversation history cannot be saved, the receipt
1073
+ reports a storage failure with the completed result. This does not mean the work
1074
+ never ran; do not automatically retry it.
1075
+
1076
+ Each launch has a new process identity, separate from its saved conversation.
1077
+ Use distinct saved conversations for concurrent processes. Peer enrollment is
1078
+ serialized per account, project, and saved conversation. This is not a general
1079
+ lock on history files used by sessions that have not enabled peer messaging.
1080
+ Old process addresses are not redirected to resumed histories. Restarted work
1081
+ does not replay pending peer messages automatically. `/peers inbox` can show
1082
+ retired receipts for the same saved conversation; unfinished historical work is
1083
+ marked unknown and must be reconciled manually. When context needs compaction,
1084
+ peer work stops before starting a model turn; compact manually and enable peers
1085
+ again. Native Windows, headless/ACP
1086
+ enrollment, cross-machine delivery, mid-turn injection, shared task boards, and
1087
+ autonomous coordination are outside this first release.
1088
+
991
1089
  ## License
992
1090
 
993
1091
  Private - Bike4Mind
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { C as NotAuthenticatedError, D as sanitizeTerminalText, d as sandboxedCommandArg, l as commandTextOf, p as writePathOf, s as loadContextFiles, u as isReadOnlyTool, w as SessionRevokedError } from "./ConfigStore-Dusy6glb.mjs";
3
- import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, l as OllamaBackend, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-CbViwiS9.mjs";
4
- import { A as DecisionsRequestSchema, At as reasoningChannelOf, C as CUSTOM_MCP_DATA_NOTICE, Ct as isRetryableError, Ft as signImageUrl, Gt as withRetry, It as splitEquals, Kt as withholdsReasoning, L as LOCATION_MAP_LANGUAGE, N as ExpectedToolError, Nt as secureParameters, Ot as obfuscateApiKey, R as LOW_CONFIDENCE_COMPLETION_MODES, St as isProviderRefusalStopReason, U as NotFoundError, V as McpServerName, Y as SEARCH_RESULT_CARDS_LANGUAGE, a as htmlFirstH1, at as assertAuthOriginMatchesApiKey, b as CONFIDENCE_GATE_MODES, bt as isExpectedToolError, ct as createReasoningWithholder, en as frontmatterHasSourceStamp, gt as googleMapsSearchUrl, i as htmlErrorTitle, it as WORK_ITEM_STATUSES, k as DecisionTextPartSchema, m as ApiKeyType, mt as getMcpProviderMetadata, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, q as PermissionDeniedError, r as isValidSessionId, t as logger, tt as UnprocessableEntityError, w as ChatModels, xt as isPlaceholderImageSigningSecret, z as MODEL_DECLINED_MESSAGE } from "./Logger-C1Wj6xla.mjs";
5
- import { n as COMMANDS, r as isReservedCommandName } from "./RemoteSkillSource-qTvRkaNA.mjs";
2
+ import { C as NotAuthenticatedError, D as sanitizeTerminalText, d as sandboxedCommandArg, l as commandTextOf, p as writePathOf, s as loadContextFiles, u as isReadOnlyTool, w as SessionRevokedError } from "./ConfigStore-CP1W86Ui.mjs";
3
+ import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, l as OllamaBackend, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-BPhZ0dCz.mjs";
4
+ import { $t as frontmatterHasSourceStamp, A as DecisionTextPartSchema, B as MODEL_DECLINED_MESSAGE, Dt as obfuscateApiKey, Ft as splitEquals, Gt as withholdsReasoning, H as McpServerName, J as PermissionDeniedError, Mt as secureParameters, P as ExpectedToolError, Pt as signImageUrl, R as LOCATION_MAP_LANGUAGE, St as isRetryableError, T as ChatModels, W as NotFoundError, Wt as withRetry, X as SEARCH_RESULT_CARDS_LANGUAGE, a as htmlFirstH1, bt as isPlaceholderImageSigningSecret, et as UnprocessableEntityError, h as ApiKeyType, ht as googleMapsSearchUrl, i as htmlErrorTitle, it as assertAuthOriginMatchesApiKey, j as DecisionsRequestSchema, kt as reasoningChannelOf, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, pt as getMcpProviderMetadata, r as isValidSessionId, rt as WORK_ITEM_STATUSES, st as createReasoningWithholder, t as logger, w as CUSTOM_MCP_DATA_NOTICE, x as CONFIDENCE_GATE_MODES, xt as isProviderRefusalStopReason, yt as isExpectedToolError, z as LOW_CONFIDENCE_COMPLETION_MODES } from "./Logger-3RbeTZ9o.mjs";
5
+ import { n as COMMANDS, r as isReservedCommandName } from "./RemoteSkillSource-D_F99yBR.mjs";
6
6
  import { n as isPathAllowed, t as assertPathAllowed } from "./pathValidation-BRqf4HFX-CHwtwp3O.mjs";
7
7
  import { n as isTerminalShellStatus, t as getShellSessionManager } from "./ShellSessionManager-6o8KZzl1-vrbPAUTq.mjs";
8
- import { d as detectRuntimes, m as modelBlobsOf } from "./dist-Citbv0y0.mjs";
9
- import { A as serverRuntimeId, B as parseGenerationInput, Ct as withDefaultOllamaPort, F as GENERATION_FIELDS, H as parseModelContextSetting, I as LOCAL_OLLAMA_RUNTIME_ID, L as REASONING_EFFORT_SETTINGS, R as effortSent, S as desktopUserDataFile, V as parseLocalModelId, X as clean, a as needsCredential, f as serverFetch, i as loginHint, l as resolveServerTarget, m as unusableStatus, r as loadModelServers, y as SSH_PROBE_TIMEOUT_MS, z as localModelId } from "./modelServers-BaegigV-.mjs";
8
+ import { d as detectRuntimes, m as modelBlobsOf } from "./dist-K7a9yOUb.mjs";
9
+ import { A as serverRuntimeId, B as parseGenerationInput, Ct as withDefaultOllamaPort, F as GENERATION_FIELDS, H as parseModelContextSetting, I as LOCAL_OLLAMA_RUNTIME_ID, L as REASONING_EFFORT_SETTINGS, R as effortSent, S as desktopUserDataFile, V as parseLocalModelId, X as clean, a as needsCredential, f as serverFetch, i as loginHint, l as resolveServerTarget, m as unusableStatus, r as loadModelServers, y as SSH_PROBE_TIMEOUT_MS, z as localModelId } from "./modelServers-B7zI5XnO.mjs";
10
10
  import { createHash, randomBytes } from "crypto";
11
11
  import { existsSync, lstatSync, promises, readdirSync, realpathSync, rmSync, statSync } from "fs";
12
12
  import os, { homedir } from "os";
@@ -36,7 +36,7 @@ import times from "lodash/times.js";
36
36
  import * as Diff from "diff";
37
37
  import { diffLines } from "diff";
38
38
  import matter from "gray-matter";
39
- import { parse } from "shell-quote";
39
+ import { parse as parse$1 } from "shell-quote";
40
40
  import { EventEmitter } from "events";
41
41
  import { fileURLToPath } from "url";
42
42
  import WebSocket from "ws";
@@ -1278,6 +1278,7 @@ var __exportAll = (all, no_symbols) => {
1278
1278
  //#endregion
1279
1279
  //#region ../../b4m-core/auth/dist/apiKeyService/index.mjs
1280
1280
  var apiKeyService_exports$1 = /* @__PURE__ */ __exportAll$2({
1281
+ EXPIRED_API_KEY: () => EXPIRED_API_KEY,
1281
1282
  createApiKey: () => createApiKey,
1282
1283
  createApiKeySchema: () => createApiKeySchema,
1283
1284
  deleteApiKey: () => deleteApiKey,
@@ -1373,6 +1374,8 @@ const ENV_KEY_MAP = {
1373
1374
  [ApiKeyType.typesafe]: "TYPESAFE_API_KEY"
1374
1375
  };
1375
1376
  const envKey = (name) => process.env.B4M_SELF_HOST === "true" && process.env[name]?.trim() || null;
1377
+ /** What getEffectiveLLMApiKeys returns in place of a user's own key once it has expired. */
1378
+ const EXPIRED_API_KEY = "expired";
1376
1379
  const getSerperKey = async (adapters) => {
1377
1380
  const { db } = adapters;
1378
1381
  return (await db.adminSettings.findBySettingName("SerperKey"))?.settingValue;
@@ -1481,7 +1484,7 @@ const getEffectiveLLMApiKeys = async (userId, adapters, options) => {
1481
1484
  const ollamaEnabled = enableOllama === "true" || enableOllama === true;
1482
1485
  const keyOrExpired = (apiKey) => {
1483
1486
  if (!apiKey) return null;
1484
- if (apiKey.expiresAt && apiKey.expiresAt < /* @__PURE__ */ new Date()) return "expired";
1487
+ if (apiKey.expiresAt && apiKey.expiresAt < /* @__PURE__ */ new Date()) return EXPIRED_API_KEY;
1485
1488
  return apiKey.apiKey;
1486
1489
  };
1487
1490
  const keys = {
@@ -1536,6 +1539,7 @@ const deleteApiKey = async (userId, parameters, { db }) => {
1536
1539
  return apiKey;
1537
1540
  };
1538
1541
  var apiKeyService_exports$2 = /* @__PURE__ */ __exportAll({
1542
+ EXPIRED_API_KEY: () => EXPIRED_API_KEY,
1539
1543
  createApiKey: () => createApiKey,
1540
1544
  createApiKeySchema: () => createApiKeySchema,
1541
1545
  deleteApiKey: () => deleteApiKey,
@@ -3643,7 +3647,7 @@ async function getModelForWrite(user, modelId, deps) {
3643
3647
  return isModelOwner(model, user) ? model : null;
3644
3648
  }
3645
3649
  //#endregion
3646
- //#region ../../b4m-core/services/dist/toolGenerators-DEf7KPNr.mjs
3650
+ //#region ../../b4m-core/services/dist/toolGenerators-ByeEdDON.mjs
3647
3651
  const diceRoll = async (parameters) => {
3648
3652
  if (!parameters?.sides || !parameters?.times) throw new Error("Tool dice roll: Missing required parameters");
3649
3653
  return sum(times(parameters.times, () => random(1, parameters.sides))).toString();
@@ -4482,7 +4486,7 @@ const askUserQuestionTool = {
4482
4486
  * re-export them without pulling the full tool graph. `index.ts` re-exports them
4483
4487
  * so the server barrel's public API is unchanged.
4484
4488
  */
4485
- const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFilter, kbScope, inlinedAttachmentIds, attachedFileIds, fullyInlinedAttachmentIds, suppressLakeArms, sessionRetrievalTags, sessionReaderConsentDatalakeTags, sessionLakeScopeExplicit, sessionIncludeLibraryFiles, sessionPreauthorizedLakeIds, organizationId, authOrigin, apiKeyId, questId, requestConfirmation, slackDestination, numberCitables, decide, toLedgerModel, getAbortSignal }, storage, imageGenerateStorage, statusUpdate, onStart, onFinish, llm, config, model, imageProcessorLambdaName, tools, allowedDirectories, entitlementKeys = [], sessionId, codeMinifier, availableModels, onToolLlmUsage, servingModel) => {
4489
+ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFilter, kbScope, inlinedAttachmentIds, attachedFileIds, fullyInlinedAttachmentIds, suppressLakeArms, sessionRetrievalTags, sessionReaderConsentDatalakeTags, sessionLakeScopeExplicit, sessionIncludeLibraryFiles, sessionPreauthorizedLakeIds, organizationId, governingOrgModelPolicy, authOrigin, apiKeyId, questId, requestConfirmation, slackDestination, numberCitables, decide, toLedgerModel, getAbortSignal }, storage, imageGenerateStorage, statusUpdate, onStart, onFinish, llm, config, model, imageProcessorLambdaName, tools, allowedDirectories, entitlementKeys = [], sessionId, codeMinifier, availableModels, onToolLlmUsage, servingModel) => {
4486
4490
  assertAuthOriginMatchesApiKey(authOrigin, apiKeyId);
4487
4491
  const context = {
4488
4492
  userId,
@@ -4516,6 +4520,7 @@ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFil
4516
4520
  sessionIncludeLibraryFiles,
4517
4521
  sessionPreauthorizedLakeIds,
4518
4522
  organizationId,
4523
+ governingOrgModelPolicy,
4519
4524
  authOrigin,
4520
4525
  apiKeyId,
4521
4526
  codeMinifier,
@@ -6793,7 +6798,7 @@ const getCliOnlyTools = async () => {
6793
6798
  const [{ createFileTool }, { globFilesTool }, { grepSearchTool }, { deleteFileTool }, { bashExecuteTool }] = await Promise.all([
6794
6799
  import("./createFile-B8bur5Rb-CVzCarEA.mjs"),
6795
6800
  import("./globFiles-CwJ8qmYo-BR5b2KvO.mjs"),
6796
- import("./grepSearch-BgoOOwGe-B388GxRD.mjs"),
6801
+ import("./grepSearch-CLtEqT4j-BnKPtNWr.mjs"),
6797
6802
  import("./deleteFile-9B3gW_Nb-DG2sovIl.mjs"),
6798
6803
  import("./bashExecute-CrdPpBqk-CgK1gZa2.mjs")
6799
6804
  ]);
@@ -7754,7 +7759,7 @@ function isWriteTargetingPlanFile(writePath, cwd = process.cwd()) {
7754
7759
  * it and the live mode so they never exceed the parent but still honor a mid-run plan switch.
7755
7760
  */
7756
7761
  async function resolveInteractionMode(override) {
7757
- const { useCliStore } = await import("./store-BYeE0shc.mjs");
7762
+ const { useCliStore } = await import("./store-Bpdo9Syo.mjs");
7758
7763
  const liveInteractionMode = useCliStore.getState().interactionMode;
7759
7764
  return override ? clampInteractionMode(liveInteractionMode, override) : liveInteractionMode;
7760
7765
  }
@@ -8368,7 +8373,7 @@ function classifyAtDepth(command, depth) {
8368
8373
  };
8369
8374
  let tokens;
8370
8375
  try {
8371
- tokens = parse(trimmed);
8376
+ tokens = parse$1(trimmed);
8372
8377
  } catch {
8373
8378
  return {
8374
8379
  level: "high",
@@ -14269,6 +14274,7 @@ function buildCliToolList(input, wrapDeps) {
14269
14274
  input.findDefinitionTool,
14270
14275
  input.getFileStructureTool,
14271
14276
  ...input.workItemTools ?? [],
14277
+ ...input.peerTools ?? [],
14272
14278
  ...input.skillTool ? [input.skillTool] : [],
14273
14279
  ...input.dynamicAgentTool ? [input.dynamicAgentTool] : [],
14274
14280
  ...input.coordinateTaskTool ? [input.coordinateTaskTool] : []
@@ -15147,7 +15153,7 @@ function sessionCommandPrefixes(command) {
15147
15153
  if (classifyCommandRisk(text).level === "high") return null;
15148
15154
  let tokens;
15149
15155
  try {
15150
- tokens = parse(text, (key) => `$${key}`);
15156
+ tokens = parse$1(text, (key) => `$${key}`);
15151
15157
  } catch {
15152
15158
  return null;
15153
15159
  }
@@ -19994,8 +20000,8 @@ async function buildSandbox(input) {
19994
20000
  const { config, sessionId, permissionManager, checkpointStore } = input;
19995
20001
  const log = input.log ?? consoleLog;
19996
20002
  const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
19997
- import("./SandboxRuntimeAdapter-Zg_0th7V.mjs"),
19998
- import("./SandboxOrchestrator-CQwYq_uy.mjs"),
20003
+ import("./SandboxRuntimeAdapter-u6c_IrjP.mjs"),
20004
+ import("./SandboxOrchestrator-lpxVEFO7.mjs"),
19999
20005
  import("./types-BFIvwByC.mjs"),
20000
20006
  import("./ProxyManager-TxEKlgdO.mjs"),
20001
20007
  import("./ViolationLogStore-byEhxa2A.mjs")
@@ -21360,7 +21366,7 @@ var SubagentOrchestrator = class {
21360
21366
  const depth = options.depth ?? 1;
21361
21367
  if (depth >= 3) throw new Error(`Cannot spawn agent "${agentName}": subagent nesting depth ${depth} reached the limit of 3. Deeper delegation is blocked to prevent unbounded recursion.`);
21362
21368
  const resumeId = options.resumeId ?? `sub-${randomBytes(4).toString("hex")}`;
21363
- const { useCliStore } = await import("./store-BYeE0shc.mjs");
21369
+ const { useCliStore } = await import("./store-Bpdo9Syo.mjs");
21364
21370
  const parentInteractionMode = options.parentInteractionMode ?? useCliStore.getState().interactionMode;
21365
21371
  const effectiveInteractionMode = clampInteractionMode(options.interactionMode ?? parentInteractionMode, parentInteractionMode);
21366
21372
  let agentDef;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { b as AuthenticatedApiClient, t as ConfigStore, x as DeviceFlowClient } from "./ConfigStore-Dusy6glb.mjs";
3
- import { t as logger } from "./Logger-C1Wj6xla.mjs";
4
- import { t as version } from "./package-C9pfAdGF.mjs";
2
+ import { b as AuthenticatedApiClient, t as ConfigStore, x as DeviceFlowClient } from "./ConfigStore-CP1W86Ui.mjs";
3
+ import { t as logger } from "./Logger-3RbeTZ9o.mjs";
4
+ import { t as version } from "./package-WlxLVpUb.mjs";
5
5
  import { isAxiosError } from "axios";
6
6
  import { Readable } from "node:stream";
7
7
  //#region src/auth/OAuthClient.ts
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as logger } from "./Logger-C1Wj6xla.mjs";
3
- import { a as getContainerSocketPaths, c as resolveSandboxPath, o as getProtectedWorkspacePaths, s as isBinaryAvailable, t as assertProxyPort } from "./SandboxRuntimeAdapter-BsT2iLky.mjs";
2
+ import { t as logger } from "./Logger-3RbeTZ9o.mjs";
3
+ import { a as getContainerSocketPaths, c as resolveSandboxPath, o as getProtectedWorkspacePaths, s as isBinaryAvailable, t as assertProxyPort } from "./SandboxRuntimeAdapter-C3xICJtQ.mjs";
4
4
  import { lstatSync, mkdirSync, statSync } from "fs";
5
5
  import os from "os";
6
6
  import path from "path";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export { t as ConfigStore } from "./ConfigStore-CP1W86Ui.mjs";
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as logger, w as ChatModels } from "./Logger-C1Wj6xla.mjs";
2
+ import { T as ChatModels, t as logger } from "./Logger-3RbeTZ9o.mjs";
3
3
  import { t as DEFAULT_SANDBOX_CONFIG } from "./types-CxrzVXel.mjs";
4
4
  import { existsSync, promises } from "fs";
5
5
  import { homedir, hostname } from "os";
@@ -195,6 +195,15 @@ var NotAuthenticatedError = class extends Error {
195
195
  this.name = "NotAuthenticatedError";
196
196
  }
197
197
  };
198
+ /** A captured session no longer owns this operation. */
199
+ var SessionChangedError = class extends Error {
200
+ beforeRequest;
201
+ constructor(beforeRequest = false) {
202
+ super("The account or environment changed. Please try again from the current session.");
203
+ this.beforeRequest = beforeRequest;
204
+ this.name = "SessionChangedError";
205
+ }
206
+ };
198
207
  /** Enough of an error body to classify it; a 401 body is a few hundred bytes. */
199
208
  const ERROR_BODY_LIMIT = 65536;
200
209
  function isReadableStream(data) {
@@ -228,7 +237,8 @@ function bearerToken(config) {
228
237
  * Authenticated API client for B4M services.
229
238
  * Injects access tokens from the supplied {@link TokenStore} and refreshes them on a 401.
230
239
  */
231
- var AuthenticatedApiClient = class {
240
+ var AuthenticatedApiClient = class AuthenticatedApiClient {
241
+ options;
232
242
  client;
233
243
  tokenStore;
234
244
  oauthClient;
@@ -240,8 +250,10 @@ var AuthenticatedApiClient = class {
240
250
  refreshUnexpiredOn401;
241
251
  reauthMessages;
242
252
  /** The one refresh exchange in flight, shared by every caller - see {@link refreshSession}. */
243
- inFlightRefresh = null;
253
+ refreshState = { inFlight: null };
254
+ sessionAdapters = /* @__PURE__ */ new WeakMap();
244
255
  constructor(options) {
256
+ this.options = options;
245
257
  this.tokenStore = options.tokenStore;
246
258
  this.oauthClient = options.oauthClient;
247
259
  this.logger = options.logger;
@@ -266,31 +278,37 @@ var AuthenticatedApiClient = class {
266
278
  });
267
279
  this.client.interceptors.request.use(async (config) => {
268
280
  if (this.apiKey) {
281
+ this.assertSession(null, !("_retry" in config && config._retry === true));
282
+ this.guardTransport(config, null);
269
283
  config.headers["x-api-key"] = this.apiKey;
270
284
  return config;
271
285
  }
272
286
  const tokens = await this.tokenStore.getAuthTokens();
287
+ this.assertSession(tokens, !("_retry" in config && config._retry === true));
288
+ if (this.options.isSessionCurrent && !tokens) throw new SessionChangedError(!("_retry" in config && config._retry === true));
289
+ this.guardTransport(config, tokens);
273
290
  if (tokens) config.headers.Authorization = `Bearer ${tokens.accessToken}`;
274
291
  return config;
275
292
  }, (error) => Promise.reject(error));
276
293
  this.client.interceptors.response.use((response) => response, async (error) => {
277
294
  const originalRequest = error.config;
278
295
  if (error.response?.status === 401) this.logger.debug("AUTH: Received 401 Unauthorized");
279
- else if (error.response?.status === 403) this.logger.error("403 Forbidden", error);
296
+ else if (error.response?.status === 403) this.logger.error("AUTH: Received 403 Forbidden");
280
297
  if (this.apiKey) return Promise.reject(error);
281
298
  if (error.response?.status === 401) await bufferStreamedBody(error.response);
282
299
  if (error.response?.status === 401 && this.isPassThrough401?.(error.response.data)) return Promise.reject(error);
283
300
  if (error.response?.status === 401 && !originalRequest._retry) {
284
301
  originalRequest._retry = true;
285
302
  const tokens = await this.tokenStore.getAuthTokens();
303
+ this.assertSession(tokens);
286
304
  if (!tokens) throw new NotAuthenticatedError(notLoggedIn);
287
305
  const sentAccessToken = bearerToken(originalRequest);
288
- if (sentAccessToken !== tokens.accessToken && !isExpired(tokens) && !this.inFlightRefresh) {
306
+ if (sentAccessToken !== tokens.accessToken && !isExpired(tokens) && !this.refreshState.inFlight) {
289
307
  this.logger.debug("AUTH: Retrying with the access token stored since this request was sent");
290
308
  originalRequest.headers.Authorization = `Bearer ${tokens.accessToken}`;
291
309
  return this.client(originalRequest);
292
310
  }
293
- if (!this.refreshUnexpiredOn401 && !isExpired(tokens) && !this.inFlightRefresh) {
311
+ if (!this.refreshUnexpiredOn401 && !isExpired(tokens) && !this.refreshState.inFlight) {
294
312
  this.logger.debug("AUTH: Access token has not expired, skipping refresh - 401 is likely transient");
295
313
  return Promise.reject(error);
296
314
  }
@@ -298,9 +316,8 @@ var AuthenticatedApiClient = class {
298
316
  try {
299
317
  refreshed = await this.refreshSession(sentAccessToken);
300
318
  } catch (refreshError) {
301
- if (refreshError instanceof SessionRevokedError || refreshError instanceof NotAuthenticatedError) throw refreshError;
302
- const refreshMsg = refreshError instanceof Error ? refreshError.message : "Unknown error";
303
- this.logger.warn(`AUTH: Token refresh failed: ${refreshMsg}`);
319
+ if (refreshError instanceof SessionRevokedError || refreshError instanceof NotAuthenticatedError || refreshError instanceof SessionChangedError) throw refreshError;
320
+ this.logger.warn("AUTH: Token refresh temporarily unavailable");
304
321
  throw new Error(refreshUnavailable);
305
322
  }
306
323
  originalRequest.headers.Authorization = `Bearer ${refreshed.accessToken}`;
@@ -308,8 +325,10 @@ var AuthenticatedApiClient = class {
308
325
  return this.client(originalRequest);
309
326
  }
310
327
  if (error.response?.status === 401 && originalRequest._retry) {
328
+ const current = await this.readStoredTokens();
329
+ this.assertSession(current);
311
330
  this.logger.debug("AUTH: Token refresh retry failed");
312
- this.onStillUnauthorized?.("a request was still refused after the session was refreshed");
331
+ if (current?.accessToken === bearerToken(originalRequest)) this.onStillUnauthorized?.("a request was still refused after the session was refreshed");
313
332
  throw new SessionRevokedError(stillUnauthorized);
314
333
  }
315
334
  return Promise.reject(error);
@@ -330,11 +349,38 @@ var AuthenticatedApiClient = class {
330
349
  * the one case in which the stored tokens are cleared. Any other failure (network, timeout,
331
350
  * 5xx, 429) is rethrown as-is and leaves the tokens untouched.
332
351
  */
333
- refreshSession(rejectedAccessToken) {
334
- if (!this.inFlightRefresh) this.inFlightRefresh = this.lockedExchange(rejectedAccessToken).finally(() => {
335
- this.inFlightRefresh = null;
352
+ async refreshSession(rejectedAccessToken) {
353
+ await this.readStoredTokens();
354
+ if (!this.refreshState.inFlight) this.refreshState.inFlight = this.lockedExchange(rejectedAccessToken).finally(() => {
355
+ this.refreshState.inFlight = null;
356
+ });
357
+ const refreshed = await this.refreshState.inFlight;
358
+ this.assertSession(refreshed);
359
+ return refreshed;
360
+ }
361
+ /** A session-bound client that shares refresh rotations with this client. */
362
+ withSessionGuard(isSessionCurrent) {
363
+ const inherited = this.options.isSessionCurrent;
364
+ const fork = new AuthenticatedApiClient({
365
+ ...this.options,
366
+ isSessionCurrent: (tokens) => (inherited === void 0 || inherited(tokens) === true) && isSessionCurrent(tokens) === true
336
367
  });
337
- return this.inFlightRefresh;
368
+ fork.refreshState = this.refreshState;
369
+ return fork;
370
+ }
371
+ assertSession(tokens, beforeRequest = false) {
372
+ if (this.options.isSessionCurrent && this.options.isSessionCurrent(tokens) !== true) throw new SessionChangedError(beforeRequest);
373
+ }
374
+ guardTransport(config, tokens) {
375
+ if (!this.options.isSessionCurrent) return;
376
+ const selected = axios.getAdapter(config.adapter ?? this.client.defaults.adapter);
377
+ const adapter = this.sessionAdapters.get(selected) ?? selected;
378
+ const guarded = (request) => {
379
+ this.assertSession(tokens, !("_retry" in request && request._retry === true));
380
+ return adapter(request);
381
+ };
382
+ this.sessionAdapters.set(guarded, adapter);
383
+ config.adapter = guarded;
338
384
  }
339
385
  async lockedExchange(rejectedAccessToken) {
340
386
  const store = this.tokenStore;
@@ -354,9 +400,11 @@ var AuthenticatedApiClient = class {
354
400
  }
355
401
  this.logger.debug("AUTH: Attempting token refresh");
356
402
  let response;
403
+ this.assertSession(presented);
357
404
  try {
358
405
  response = await this.oauthClient.refreshToken(presented.refreshToken);
359
406
  } catch (refreshError) {
407
+ if (this.options.isSessionCurrent) await this.readStoredTokens();
360
408
  const status = isAxiosError(refreshError) ? refreshError.response?.status : void 0;
361
409
  if (status !== 400 && status !== 401) throw refreshError;
362
410
  const current = await this.readStoredTokens();
@@ -367,15 +415,18 @@ var AuthenticatedApiClient = class {
367
415
  if (current) {
368
416
  const reason = `refresh token rejected by the server (HTTP ${status})`;
369
417
  this.logger.warn(`AUTH: Clearing stored tokens: ${reason}`);
370
- if (await this.tokenStore.clearAuthTokens(presented.refreshToken) === false) {
371
- const now = await this.readStoredTokens();
372
- if (now) return now;
373
- } else this.onTokensCleared?.(reason);
418
+ this.assertSession(current);
419
+ const cleared = await this.tokenStore.clearAuthTokens(presented.refreshToken);
420
+ const now = await this.readStoredTokens();
421
+ this.assertSession(now);
422
+ if (now && (now.accessToken !== presented.accessToken || now.refreshToken !== presented.refreshToken || now.userId !== presented.userId)) return now;
423
+ if (!now && cleared !== false) this.onTokensCleared?.(reason);
374
424
  }
375
425
  throw new SessionRevokedError(this.reauthMessages.refreshFailed);
376
426
  }
377
427
  this.logger.debug("AUTH: Token refresh successful");
378
428
  const current = await this.readStoredTokens();
429
+ this.assertSession(current);
379
430
  if (!current) throw new NotAuthenticatedError(this.reauthMessages.notLoggedIn);
380
431
  if (current.refreshToken !== presented.refreshToken) {
381
432
  this.logger.debug("AUTH: Stored tokens changed during refresh, keeping the stored ones");
@@ -394,8 +445,10 @@ var AuthenticatedApiClient = class {
394
445
  }
395
446
  return next;
396
447
  }
397
- readStoredTokens() {
398
- return this.tokenStore.reloadAuthTokens ? this.tokenStore.reloadAuthTokens() : this.tokenStore.getAuthTokens();
448
+ async readStoredTokens() {
449
+ const tokens = await (this.tokenStore.reloadAuthTokens ? this.tokenStore.reloadAuthTokens() : this.tokenStore.getAuthTokens());
450
+ this.assertSession(tokens);
451
+ return tokens;
399
452
  }
400
453
  /**
401
454
  * Make a GET request
@@ -407,8 +460,7 @@ var AuthenticatedApiClient = class {
407
460
  * Make a POST request
408
461
  */
409
462
  async post(url, data, config) {
410
- this.logger.debug(`[ApiClient] POST ${this.client.defaults.baseURL}${url}`);
411
- this.logger.debug(`[ApiClient] Request body: ${JSON.stringify(data)}`);
463
+ this.logger.debug("[ApiClient] POST request");
412
464
  const response = await this.client.post(url, data, config);
413
465
  this.logger.debug(`[ApiClient] Response status: ${response.status}`);
414
466
  return response.data;
@@ -435,6 +487,7 @@ var AuthenticatedApiClient = class {
435
487
  * Check if user is authenticated
436
488
  */
437
489
  async isAuthenticated() {
490
+ if (this.options.isSessionCurrent) return await this.readStoredTokens() !== null;
438
491
  return this.tokenStore.isAuthenticated();
439
492
  }
440
493
  /**
@@ -442,7 +495,7 @@ var AuthenticatedApiClient = class {
442
495
  */
443
496
  async getCurrentUser() {
444
497
  try {
445
- const tokens = await this.tokenStore.getAuthTokens();
498
+ const tokens = await this.readStoredTokens();
446
499
  if (!tokens) return null;
447
500
  return { id: tokens.userId };
448
501
  } catch {
@@ -690,6 +743,21 @@ const CORE_TOOL_DESCRIPTORS = new Map(Object.entries({
690
743
  effect: "read",
691
744
  approval: "auto_approve"
692
745
  },
746
+ peer_list: {
747
+ source: CLI,
748
+ effect: "read",
749
+ approval: "prompt_default"
750
+ },
751
+ peer_status: {
752
+ source: CLI,
753
+ effect: "read",
754
+ approval: "prompt_default"
755
+ },
756
+ peer_send: {
757
+ source: CLI,
758
+ effect: "execute",
759
+ approval: "auto_approve"
760
+ },
693
761
  ask_user_question: {
694
762
  source: CORE,
695
763
  effect: "session",
@@ -1552,10 +1620,16 @@ function migrateApiConfig(raw) {
1552
1620
  const { environment, customUrl } = old;
1553
1621
  raw.apiConfig = environment === "custom" && customUrl ? { customUrl } : {};
1554
1622
  }
1623
+ /**
1624
+ * The default model every config was born with before 0.3.0. It is deprecated, so each
1625
+ * chat on it was served by its successor anyway and counted as a deprecated-model request.
1626
+ */
1627
+ const LEGACY_DEFAULT_MODEL = ChatModels.CLAUDE_4_5_SONNET;
1555
1628
  /** The one-time upgrade of a file not yet at CONFIG_SCHEMA_VERSION, in place. */
1556
1629
  function upgradeConfig(raw) {
1557
1630
  const preferences = raw.preferences;
1558
- if (typeof preferences === "object" && preferences?.maxTokens === LEGACY_PINNED_MAX_TOKENS) delete preferences.maxTokens;
1631
+ if ((raw.version === void 0 || raw.version === "0.1.0") && typeof preferences === "object" && preferences?.maxTokens === LEGACY_PINNED_MAX_TOKENS) delete preferences.maxTokens;
1632
+ if (raw.defaultModel === LEGACY_DEFAULT_MODEL) raw.defaultModel = DEFAULT_CONFIG.defaultModel;
1559
1633
  raw.version = CONFIG_SCHEMA_VERSION;
1560
1634
  }
1561
1635
  /** A refresh lock whose heartbeat stopped this long ago (ms) is abandoned. */
@@ -1693,14 +1767,14 @@ function removeRawListItems(raw, key, drop) {
1693
1767
  * rewritten at the current version; a file already at it is left alone. Bump this when
1694
1768
  * adding a migration, and gate the new step on the version it needs to run from.
1695
1769
  */
1696
- const CONFIG_SCHEMA_VERSION = "0.2.0";
1770
+ const CONFIG_SCHEMA_VERSION = "0.3.0";
1697
1771
  /**
1698
1772
  * Default configuration
1699
1773
  */
1700
1774
  const DEFAULT_CONFIG = {
1701
1775
  version: CONFIG_SCHEMA_VERSION,
1702
1776
  userId: v4(),
1703
- defaultModel: ChatModels.CLAUDE_4_5_SONNET,
1777
+ defaultModel: ChatModels.CLAUDE_5_5_SONNET,
1704
1778
  toolApiKeys: {
1705
1779
  openweather: void 0,
1706
1780
  serper: void 0