@musdrop/ds-harness-remote 0.6.22 → 0.6.23

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.
package/dist/index.js CHANGED
@@ -64980,6 +64980,77 @@ var workspaceGitTurnsResultSchema = external_exports.object({
64980
64980
  turns: external_exports.array(workspaceGitTurnSummarySchema).max(WORKSPACE_GIT_MAX_TURNS)
64981
64981
  }).strict();
64982
64982
 
64983
+ // packages/protocol/dist/model-share.js
64984
+ var MODEL_SHARE_CAPABILITY = "model.share.v1";
64985
+ var MODEL_SHARE_FAILURE_CODES = {
64986
+ AUTH: "MODEL_SHARE_AUTH",
64987
+ QUOTA: "MODEL_SHARE_QUOTA",
64988
+ RATE_LIMIT: "MODEL_SHARE_RATE_LIMIT",
64989
+ CONTEXT: "MODEL_SHARE_CONTEXT",
64990
+ MODEL_UNAVAILABLE: "MODEL_SHARE_MODEL_UNAVAILABLE",
64991
+ PROVIDER_UNAVAILABLE: "MODEL_SHARE_PROVIDER_UNAVAILABLE",
64992
+ FAILED: "MODEL_SHARE_HOST_FAILED",
64993
+ BUFFER_LIMIT: "MODEL_SHARE_BUFFER_LIMIT"
64994
+ };
64995
+ var MODEL_SHARE_METHODS = [
64996
+ "model.share.list",
64997
+ "model.share.open",
64998
+ "model.share.chunk",
64999
+ "model.share.close"
65000
+ ];
65001
+ var sharedModelSchema = external_exports.object({
65002
+ /** Stable route key: `${provider}::${model}`. Also the borrower-facing model id. */
65003
+ id: external_exports.string().min(1).max(256),
65004
+ provider: external_exports.string().min(1).max(128),
65005
+ model: external_exports.string().min(1).max(256),
65006
+ /** Display label, defaults to the raw model id. */
65007
+ name: external_exports.string().min(1).max(256),
65008
+ contextWindow: external_exports.number().int().positive().optional(),
65009
+ maxTokens: external_exports.number().int().positive().optional(),
65010
+ reasoningEfforts: external_exports.array(external_exports.string().min(1).max(64)).optional(),
65011
+ inputModalities: external_exports.array(external_exports.enum(["text", "image"])).optional()
65012
+ }).strict();
65013
+ var listRequestSchema = external_exports.object({}).strict();
65014
+ var openRequestSchema = external_exports.object({
65015
+ /** Stable route key from `model.share.list`. */
65016
+ modelId: external_exports.string().min(1).max(256),
65017
+ /** Opaque correlation id chosen by the borrower, echoed back in chunks. */
65018
+ streamId: external_exports.string().min(1).max(128),
65019
+ /** Normalized conversation passed to the Host's local LLM service. */
65020
+ messages: external_exports.array(external_exports.unknown()).min(1),
65021
+ system: external_exports.string().optional(),
65022
+ tools: external_exports.array(external_exports.unknown()).optional(),
65023
+ temperature: external_exports.number().optional(),
65024
+ maxTokens: external_exports.number().int().positive().optional(),
65025
+ stop: external_exports.array(external_exports.string()).optional(),
65026
+ reasoningEffort: external_exports.string().min(1).max(64).optional()
65027
+ }).strict();
65028
+ var chunkRequestSchema = external_exports.object({
65029
+ streamId: external_exports.string().min(1).max(128),
65030
+ /** Long-poll budget; the Host answers `done: false` on expiry. */
65031
+ waitMs: external_exports.number().int().min(0).max(3e4).optional()
65032
+ }).strict();
65033
+ var closeRequestSchema = external_exports.object({
65034
+ streamId: external_exports.string().min(1).max(128)
65035
+ }).strict();
65036
+ var modelShareListResponseSchema = external_exports.object({
65037
+ enabled: external_exports.boolean(),
65038
+ models: external_exports.array(sharedModelSchema)
65039
+ }).strict();
65040
+ var modelShareOpenResponseSchema = external_exports.object({
65041
+ streamId: external_exports.string().min(1).max(128)
65042
+ }).strict();
65043
+ var modelShareChunkResponseSchema = external_exports.object({
65044
+ streamId: external_exports.string().min(1).max(128),
65045
+ chunks: external_exports.array(external_exports.unknown()).max(513),
65046
+ done: external_exports.boolean(),
65047
+ finished: external_exports.object({
65048
+ reason: external_exports.string(),
65049
+ failure: external_exports.object({ code: external_exports.string(), message: external_exports.string() }).strict().optional()
65050
+ }).strict().optional()
65051
+ }).strict();
65052
+ var modelShareCloseResponseSchema = external_exports.object({ closed: external_exports.boolean() }).strict();
65053
+
64983
65054
  // packages/protocol/dist/close-semantics.js
64984
65055
  var SERVER_SHUTDOWN_REASON = "server shutdown";
64985
65056
  var SERVER_SHUTDOWN_CLOSE_CODES = [4009, 4001, 1013];
@@ -65216,6 +65287,7 @@ var rpcMethods = [
65216
65287
  ...sessionTransferMethods,
65217
65288
  ...attentionRpcMethods,
65218
65289
  ...WORKSPACE_GIT_METHODS,
65290
+ ...MODEL_SHARE_METHODS,
65219
65291
  "workspace.upload.lan.open",
65220
65292
  "workspace.upload.open",
65221
65293
  "workspace.upload.chunk",
@@ -66674,16 +66746,24 @@ var RemoteSessionToolError = class extends Error {
66674
66746
  this.explicit = explicit;
66675
66747
  }
66676
66748
  };
66677
- var RpcError = class extends Error {
66678
- constructor(code, message, details2, retryable = false) {
66749
+ var SAFE_ERROR_CODE_RE = /^[A-Z][A-Z0-9_]{2,63}$/;
66750
+ var SafeCodedError = class extends Error {
66751
+ code;
66752
+ constructor(code, message) {
66679
66753
  super(message);
66680
66754
  this.code = code;
66755
+ }
66756
+ };
66757
+ var RpcError = class extends SafeCodedError {
66758
+ constructor(code, message, details2, retryable = false) {
66759
+ super(code, message);
66681
66760
  this.details = details2;
66682
66761
  this.retryable = retryable;
66683
66762
  }
66684
66763
  };
66685
66764
  function safeErrorCode(error62) {
66686
66765
  if (error62 instanceof RpcError) return error62.code;
66766
+ if (error62 instanceof SafeCodedError) return SAFE_ERROR_CODE_RE.test(error62.code) ? error62.code : "INTERNAL_ERROR";
66687
66767
  if (error62 instanceof external_exports.ZodError) return "INVALID_MESSAGE";
66688
66768
  return "INTERNAL_ERROR";
66689
66769
  }
@@ -66778,13 +66858,12 @@ function safeStartupError(error62) {
66778
66858
  }
66779
66859
 
66780
66860
  // packages/plugin/src/account-two-factor-required.ts
66781
- var AccountTwoFactorRequired = class extends Error {
66861
+ var AccountTwoFactorRequired = class extends SafeCodedError {
66782
66862
  constructor(challenge, serverUrl) {
66783
- super("Two-factor verification is required.");
66863
+ super("TWO_FACTOR_REQUIRED", "Two-factor verification is required.");
66784
66864
  this.challenge = challenge;
66785
66865
  this.serverUrl = serverUrl;
66786
66866
  }
66787
- code = "TWO_FACTOR_REQUIRED";
66788
66867
  };
66789
66868
 
66790
66869
  // packages/plugin/src/server-api.ts
@@ -73865,10 +73944,9 @@ var revisions = /* @__PURE__ */ new WeakMap();
73865
73944
  function sameCredentialSnapshot(a, b) {
73866
73945
  return a !== void 0 && revisions.has(a) && revisions.has(b) && a.deviceId === b.deviceId && a.serverUrl === b.serverUrl && a.refreshToken === b.refreshToken && a.accessToken === b.accessToken && revisions.get(a) === revisions.get(b);
73867
73946
  }
73868
- var AuthorizationChangedError = class extends Error {
73869
- code = "CONNECTION_CLOSED";
73947
+ var AuthorizationChangedError = class extends SafeCodedError {
73870
73948
  constructor() {
73871
- super("Authorization changed during the request.");
73949
+ super("CONNECTION_CLOSED", "Authorization changed during the request.");
73872
73950
  }
73873
73951
  };
73874
73952
  var ServerCredentialStore = class {
@@ -74040,25 +74118,24 @@ async function withQueueLock(lock, operation) {
74040
74118
  await rm(holder, { force: true });
74041
74119
  }
74042
74120
  }
74043
- var ServerCredentialsInvalidError = class extends Error {
74044
- code = "SERVER_CREDENTIALS_INVALID";
74121
+ var ServerCredentialsInvalidError = class extends SafeCodedError {
74122
+ constructor(message = "") {
74123
+ super("SERVER_CREDENTIALS_INVALID", message);
74124
+ }
74045
74125
  };
74046
- var ServerCredentialsBusyError = class extends Error {
74047
- code = "SERVER_CREDENTIALS_BUSY";
74126
+ var ServerCredentialsBusyError = class extends SafeCodedError {
74048
74127
  constructor() {
74049
- super("Credential refresh is busy. Stop other instances. Remove a legacy refresh lock only after every instance stops.");
74128
+ super("SERVER_CREDENTIALS_BUSY", "Credential refresh is busy. Stop other instances. Remove a legacy refresh lock only after every instance stops.");
74050
74129
  }
74051
74130
  };
74052
- var ServerCredentialsLockUnsupportedError = class extends Error {
74053
- code = "SERVER_CREDENTIALS_LOCK_UNSUPPORTED";
74131
+ var ServerCredentialsLockUnsupportedError = class extends SafeCodedError {
74054
74132
  constructor() {
74055
- super(CREDENTIALS_LOCK_UNSUPPORTED_MESSAGE);
74133
+ super("SERVER_CREDENTIALS_LOCK_UNSUPPORTED", CREDENTIALS_LOCK_UNSUPPORTED_MESSAGE);
74056
74134
  }
74057
74135
  };
74058
- var ServerCredentialsLockDirectoryError = class extends Error {
74059
- code = "SERVER_CREDENTIALS_LOCK_DIRECTORY";
74136
+ var ServerCredentialsLockDirectoryError = class extends SafeCodedError {
74060
74137
  constructor() {
74061
- super(CREDENTIALS_LOCK_DIRECTORY_MESSAGE);
74138
+ super("SERVER_CREDENTIALS_LOCK_DIRECTORY", CREDENTIALS_LOCK_DIRECTORY_MESSAGE);
74062
74139
  }
74063
74140
  };
74064
74141
  var SERVER_CREDENTIALS_QUEUE_MARKER = "DSH_REFRESH_LOCK_V2\n";
@@ -75387,7 +75464,7 @@ function parseIpv6(value) {
75387
75464
  }
75388
75465
 
75389
75466
  // packages/plugin/src/version.ts
75390
- var PLUGIN_VERSION = "0.6.22";
75467
+ var PLUGIN_VERSION = "0.6.23";
75391
75468
 
75392
75469
  // packages/plugin/src/server-api.ts
75393
75470
  var TERMINAL_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u;
@@ -75464,7 +75541,7 @@ var HostServerApi = class {
75464
75541
  if (result.pairingRestricted) await this.store.restrictPairingHostOnly();
75465
75542
  }
75466
75543
  this.assertCredentialsEpoch(epoch);
75467
- if (existing && (alreadyAdopted || existing.refreshTokenExpiresAt > Date.now() + 3e4)) {
75544
+ if (existing && alreadyAdopted) {
75468
75545
  this.credentials = existing;
75469
75546
  } else {
75470
75547
  await this.saveEnrollmentWhileLocked(epoch, {
@@ -76082,10 +76159,9 @@ var ClientServerApi = class extends HostServerApi {
76082
76159
  return this.baseUrl;
76083
76160
  }
76084
76161
  };
76085
- var ServerApiError = class extends Error {
76162
+ var ServerApiError = class extends SafeCodedError {
76086
76163
  constructor(code, message, retryable, status2, phase, reason) {
76087
- super(message);
76088
- this.code = code;
76164
+ super(code, message);
76089
76165
  this.retryable = retryable;
76090
76166
  this.status = status2;
76091
76167
  this.phase = phase;
@@ -77522,6 +77598,7 @@ function isRecord(value) {
77522
77598
  // packages/client-core/dist/acp-client.js
77523
77599
  var ACP_PROMPT_RPC_TIMEOUT_MS = 10 * 6e4;
77524
77600
  var ACP_HISTORY_RPC_TIMEOUT_MS = 15e4;
77601
+ var ACP_RELOAD_MUTATION_RPC_TIMEOUT_MS = 27e4;
77525
77602
  var AgentAcpClient = class {
77526
77603
  core;
77527
77604
  capabilities;
@@ -77705,6 +77782,7 @@ var AgentAcpClient = class {
77705
77782
  const running = typeof result.running === "boolean" ? result.running : void 0;
77706
77783
  const hasMore = typeof result.hasMore === "boolean" ? result.hasMore : void 0;
77707
77784
  const oldestSeq = typeof result.oldestSeq === "number" && Number.isSafeInteger(result.oldestSeq) && result.oldestSeq >= 0 ? result.oldestSeq : void 0;
77785
+ const models = isRecord2(result.models) && isRecord2(result.models.current) && typeof result.models.current.model === "string" && typeof result.models.current.provider === "string" && (backend === void 0 || result.models.current.provider === backend) && Array.isArray(result.models.groups) ? result.models : void 0;
77708
77786
  const modes = isRecord2(result.modes) && Array.isArray(result.modes.availableModes) ? {
77709
77787
  ...typeof result.modes.currentModeId === "string" ? { currentModeId: result.modes.currentModeId } : {},
77710
77788
  availableModes: result.modes.availableModes.flatMap((item) => isRecord2(item) && typeof item.id === "string" && typeof item.name === "string" ? [{ id: item.id, name: item.name, ...typeof item.description === "string" ? { description: item.description } : {} }] : [])
@@ -77717,6 +77795,7 @@ var AgentAcpClient = class {
77717
77795
  return {
77718
77796
  events,
77719
77797
  ...permissionPreset2 ? { permissionPreset: permissionPreset2 } : {},
77798
+ ...models ? { models } : {},
77720
77799
  ...modes ? { modes } : {},
77721
77800
  ...commands ? { commands } : {},
77722
77801
  ...running !== void 0 ? { running } : {},
@@ -77903,8 +77982,10 @@ var AgentAcpClient = class {
77903
77982
  function rpcTimeoutForMethod(method) {
77904
77983
  if (method === "session/prompt")
77905
77984
  return ACP_PROMPT_RPC_TIMEOUT_MS;
77906
- if (method === "dsh/sessionHistory" || method === "session/load")
77985
+ if (["dsh/sessionHistory", "session/load", "dsh/sessionModels", "dsh/sessionModes"].includes(method))
77907
77986
  return ACP_HISTORY_RPC_TIMEOUT_MS;
77987
+ if (["dsh/selectModel", "dsh/selectPermission", "session/set_mode", "session/fork"].includes(method))
77988
+ return ACP_RELOAD_MUTATION_RPC_TIMEOUT_MS;
77908
77989
  return void 0;
77909
77990
  }
77910
77991
  function readString(value, key) {
@@ -84737,10 +84818,9 @@ var HOST_AUTHORIZATION_ERRORS = /* @__PURE__ */ new Set([
84737
84818
  "DEVICE_REVOKED",
84738
84819
  "TOKEN_EXPIRED"
84739
84820
  ]);
84740
- var ClientModeError = class extends Error {
84821
+ var ClientModeError = class extends SafeCodedError {
84741
84822
  constructor(code, message, retryable = false) {
84742
- super(message);
84743
- this.code = code;
84823
+ super(code, message);
84744
84824
  this.retryable = retryable;
84745
84825
  }
84746
84826
  };
@@ -92423,13 +92503,19 @@ function resolveExternalNodeBinaryForRtc() {
92423
92503
  cachedNodeBinaryResolved = true;
92424
92504
  const requireFrom = resolveNativeRtcRequireFrom();
92425
92505
  for (const candidate of nodeBinaryCandidates()) {
92426
- if (isUsableExternalNode(candidate, requireFrom)) {
92506
+ const result = probeExternalNode(candidate, requireFrom);
92507
+ if (result === "usable") {
92427
92508
  cachedNodeBinary = candidate;
92428
92509
  return candidate;
92429
92510
  }
92511
+ if (result === "missing-package") return void 0;
92430
92512
  }
92431
92513
  return void 0;
92432
92514
  }
92515
+ function isElectronRuntime() {
92516
+ const versions = process.versions;
92517
+ return typeof versions.electron === "string" || process.env.ELECTRON_RUN_AS_NODE === "1";
92518
+ }
92433
92519
  function nodeBinaryCandidates() {
92434
92520
  const candidates = [];
92435
92521
  const add3 = (value) => {
@@ -92437,6 +92523,7 @@ function nodeBinaryCandidates() {
92437
92523
  if (!candidates.includes(value)) candidates.push(value);
92438
92524
  };
92439
92525
  add3(process.env.DSH_REMOTE_NODE);
92526
+ if (!isElectronRuntime()) add3(process.execPath);
92440
92527
  addBundledPrimaryRuntimeNode(candidates, process.env.DSH_PRIMARY_RUNTIME);
92441
92528
  addBundledPrimaryRuntimeNode(candidates, process.env.DSH_BUNDLED_PRIMARY_RUNTIME);
92442
92529
  add3(process.env.NODE);
@@ -92468,8 +92555,8 @@ function nvmNodeCandidates() {
92468
92555
  return [];
92469
92556
  }
92470
92557
  }
92471
- function isUsableExternalNode(candidate, requireFrom) {
92472
- if (!isExecutableFile(candidate)) return false;
92558
+ function probeExternalNode(candidate, requireFrom) {
92559
+ if (!isExecutableFile(candidate)) return "unusable";
92473
92560
  const env = { ...process.env, DSH_REMOTE_RTC_HELPER_REQUIRE_FROM: requireFrom };
92474
92561
  env.ELECTRON_RUN_AS_NODE = "1";
92475
92562
  const probe = spawnSync(candidate, [
@@ -92479,10 +92566,17 @@ function isUsableExternalNode(candidate, requireFrom) {
92479
92566
  "import { createRequire } from 'node:module';",
92480
92567
  "const require = createRequire(process.env.DSH_REMOTE_RTC_HELPER_REQUIRE_FROM);",
92481
92568
  "if (process.versions.electron) throw new Error('electron-node');",
92482
- "const wrtc = require('@roamhq/wrtc');",
92483
- "const RTCPeerConnection = wrtc.RTCPeerConnection ?? wrtc.default?.RTCPeerConnection;",
92484
- "if (typeof RTCPeerConnection !== 'function') throw new Error('missing-rtc');",
92485
- "console.log(`node:${process.versions.node}`);"
92569
+ "let resolved = true;",
92570
+ "try { require.resolve('@roamhq/wrtc'); } catch (error) {",
92571
+ " if (error?.code === 'MODULE_NOT_FOUND') { resolved = false; console.log('missing-package:@roamhq/wrtc'); }",
92572
+ " else throw error;",
92573
+ "}",
92574
+ "if (resolved) {",
92575
+ " const wrtc = require('@roamhq/wrtc');",
92576
+ " const RTCPeerConnection = wrtc.RTCPeerConnection ?? wrtc.default?.RTCPeerConnection;",
92577
+ " if (typeof RTCPeerConnection !== 'function') throw new Error('missing-rtc');",
92578
+ " console.log(`node:${process.versions.node}`);",
92579
+ "}"
92486
92580
  ].join("")
92487
92581
  ], {
92488
92582
  cwd: dirname4(requireFrom),
@@ -92491,7 +92585,9 @@ function isUsableExternalNode(candidate, requireFrom) {
92491
92585
  timeout: 3e3,
92492
92586
  windowsHide: true
92493
92587
  });
92494
- return probe.status === 0 && probe.stdout.startsWith("node:");
92588
+ if (probe.status === 0 && probe.stdout.startsWith("node:")) return "usable";
92589
+ if (probe.status === 0 && probe.stdout.startsWith("missing-package:")) return "missing-package";
92590
+ return "unusable";
92495
92591
  }
92496
92592
  function isExecutableFile(candidate) {
92497
92593
  try {
@@ -92520,6 +92616,7 @@ var ExternalNativePeerConnection = class {
92520
92616
  this.child.on("error", (error62) => this.handleExit(error62));
92521
92617
  this.child.stdin.on("error", (error62) => this.handleExit(error62));
92522
92618
  this.ready = this.request("init", { iceServers: configuration.iceServers ?? [], iceTransportPolicy: configuration.iceTransportPolicy }).then(() => void 0);
92619
+ void this.ready.catch(() => void 0);
92523
92620
  }
92524
92621
  connectionState = "new";
92525
92622
  iceConnectionState = "new";
@@ -92673,11 +92770,19 @@ var ExternalNativePeerConnection = class {
92673
92770
  return channel;
92674
92771
  }
92675
92772
  handleExit(error62) {
92676
- if (!this.closed) this.closed = true;
92773
+ const unexpected = !this.closed;
92774
+ this.closed = true;
92677
92775
  const reason = error62 ?? new Error("native rtc helper exited");
92678
92776
  for (const pending of this.pending.values()) pending.reject(reason);
92679
92777
  this.pending.clear();
92680
92778
  for (const channel of this.channels.values()) channel.updateState("closed", 0);
92779
+ if (unexpected) {
92780
+ this.connectionState = "failed";
92781
+ this.iceConnectionState = "failed";
92782
+ this.signalingState = "closed";
92783
+ this.onconnectionstatechange?.();
92784
+ this.oniceconnectionstatechange?.();
92785
+ }
92681
92786
  }
92682
92787
  };
92683
92788
  var ExternalNativeDataChannel = class {
@@ -92918,7 +93023,8 @@ var cachedFactory;
92918
93023
  var cachedWerift;
92919
93024
  var cachedNativeFactory;
92920
93025
  async function loadNodeRtcFactory(options = {}) {
92921
- const nativeFactory = process.env.DSH_REMOTE_WEBRTC_BACKEND === "werift" || shouldUseWeriftForLinuxLibc(process.platform, linuxGlibcVersion()) ? void 0 : isElectronRuntime() ? await loadExternalNativeRtcFactory().catch(() => void 0) : await loadNativeRtcFactory().catch(() => void 0);
93026
+ const backend = process.env.DSH_REMOTE_WEBRTC_BACKEND?.trim().toLowerCase();
93027
+ const nativeFactory = backend === "werift" || shouldUseWeriftForLinuxLibc(process.platform, linuxGlibcVersion()) ? void 0 : backend === "native-inprocess" && !isElectronRuntime2() ? await loadNativeRtcFactory().catch(() => void 0) : await loadExternalNativeRtcFactory().catch(() => void 0);
92922
93028
  const factory = nativeFactory ?? await loadWeriftFactory(options);
92923
93029
  return factory === void 0 ? void 0 : wrapLocalCandidateFilterFactory(factory, options);
92924
93030
  }
@@ -92961,7 +93067,7 @@ async function loadNativeRtcFactory() {
92961
93067
  return void 0;
92962
93068
  }
92963
93069
  }
92964
- function isElectronRuntime() {
93070
+ function isElectronRuntime2() {
92965
93071
  const versions = process.versions;
92966
93072
  return typeof versions.electron === "string" || process.env.ELECTRON_RUN_AS_NODE === "1";
92967
93073
  }
@@ -93851,6 +93957,8 @@ var ClientModeRuntime = class {
93851
93957
  createModelShareTransport(hostId, hostName) {
93852
93958
  let held;
93853
93959
  let holding;
93960
+ let generation = 0;
93961
+ const streams = /* @__PURE__ */ new Map();
93854
93962
  const acquire = async () => {
93855
93963
  const closed = () => this.closed || this.remoteLifetime.signal.aborted;
93856
93964
  if (this.connected?.target.deviceId === hostId) {
@@ -93866,56 +93974,91 @@ var ClientModeRuntime = class {
93866
93974
  holding = void 0;
93867
93975
  held = void 0;
93868
93976
  }
93977
+ const acquiredGeneration = generation;
93869
93978
  holding = (async () => {
93870
93979
  if (this.identity === void 0) await this.ensureIdentity();
93871
93980
  const signal = this.remoteLifetime.signal;
93872
93981
  const remote = await this.connection.connect(hostId, signal, { background: true });
93873
93982
  const entry = { remote, signal };
93983
+ if (generation !== acquiredGeneration) {
93984
+ await remote.client.close().catch(() => void 0);
93985
+ throw new ClientModeError("CANCELLED", "The borrowed-stream connection was released.");
93986
+ }
93874
93987
  if (!remote.client.getStats().connected) {
93875
93988
  holding = void 0;
93876
93989
  throw new ClientModeError("TRANSPORT_CLOSED", "The borrowed-stream connection closed during setup.", true);
93877
93990
  }
93878
93991
  held = entry;
93879
93992
  remote.client.onClose(() => {
93880
- if (held?.remote === remote) held = void 0;
93881
- holding = void 0;
93993
+ if (held?.remote === remote) {
93994
+ held = void 0;
93995
+ holding = void 0;
93996
+ }
93882
93997
  });
93883
93998
  return entry;
93884
93999
  })().catch((error62) => {
93885
- holding = void 0;
94000
+ if (generation === acquiredGeneration) holding = void 0;
93886
94001
  throw closed() ? new ClientModeError("CANCELLED", "The Remote runtime is closed.") : error62;
93887
94002
  });
93888
94003
  return holding;
93889
94004
  };
93890
- const rpc = async (method, params, signal) => {
93891
- const { remote, signal: activeSignal } = await acquire();
93892
- const scoped = signal === void 0 ? activeSignal : AbortSignal.any([activeSignal, signal]);
93893
- return await remote.client.rpc(method, params, scoped);
93894
- };
93895
94005
  return {
93896
94006
  hostId,
93897
94007
  hostName,
93898
94008
  models: () => [],
93899
- open: async (request2) => await rpc("model.share.open", request2),
93900
- drain: async (streamId, waitMs) => await rpc(
93901
- "model.share.chunk",
93902
- { streamId, waitMs }
93903
- ),
94009
+ open: async (request2) => {
94010
+ const openGeneration = generation;
94011
+ const connection = await acquire();
94012
+ if (generation !== openGeneration) throw new ClientModeError("CANCELLED", "The borrowed-stream connection was released.");
94013
+ let result;
94014
+ try {
94015
+ result = await connection.remote.client.rpc("model.share.open", request2, connection.signal);
94016
+ } catch (error62) {
94017
+ void connection.remote.client.rpc("model.share.close", { streamId: request2.streamId }, connection.signal).catch(() => void 0);
94018
+ throw error62;
94019
+ }
94020
+ if (generation !== openGeneration) {
94021
+ await connection.remote.client.rpc("model.share.close", { streamId: request2.streamId }, connection.signal).catch(() => void 0);
94022
+ throw new ClientModeError("CANCELLED", "The borrowed-stream connection was released.");
94023
+ }
94024
+ const parsed = modelShareOpenResponseSchema.safeParse(result);
94025
+ if (!parsed.success || parsed.data.streamId !== request2.streamId) {
94026
+ void connection.remote.client.rpc("model.share.close", { streamId: request2.streamId }, connection.signal).catch(() => void 0);
94027
+ throw new ClientModeError("INVALID_MESSAGE", "The lending Host returned an unexpected stream id.");
94028
+ }
94029
+ const response = parsed.data;
94030
+ streams.set(request2.streamId, connection);
94031
+ return response;
94032
+ },
94033
+ drain: async (streamId, waitMs) => {
94034
+ const connection = streams.get(streamId);
94035
+ if (connection === void 0) throw new ClientModeError("TRANSPORT_CLOSED", "The borrowed-stream connection is unavailable.", true);
94036
+ const response = modelShareChunkResponseSchema.parse(await connection.remote.client.rpc("model.share.chunk", { streamId, waitMs }, connection.signal));
94037
+ if (response.streamId !== streamId) throw new ClientModeError("INVALID_MESSAGE", "The lending Host returned an unexpected stream id.");
94038
+ return response;
94039
+ },
93904
94040
  close: async (streamId) => {
93905
- await rpc("model.share.close", { streamId }).catch(() => void 0);
94041
+ const connection = streams.get(streamId);
94042
+ streams.delete(streamId);
94043
+ if (connection !== void 0) await connection.remote.client.rpc("model.share.close", { streamId }, connection.signal).catch(() => void 0);
93906
94044
  },
93907
94045
  /** Drop the held connection when the borrowing runtime withdraws. */
93908
94046
  release: () => {
93909
94047
  const current = held;
94048
+ generation += 1;
93910
94049
  held = void 0;
93911
94050
  holding = void 0;
94051
+ for (const [streamId, connection] of streams) {
94052
+ void connection.remote.client.rpc("model.share.close", { streamId }, connection.signal).catch(() => void 0);
94053
+ }
94054
+ streams.clear();
93912
94055
  void current?.remote.client.close().catch(() => void 0);
93913
94056
  }
93914
94057
  };
93915
94058
  }
93916
94059
  /** List what one Host lends to this device. */
93917
94060
  async listSharedModels(hostId, signal) {
93918
- return await this.withToolRemote(hostId, signal ?? this.remoteLifetime.signal, async (remote, activeSignal) => await remote.client.rpc("model.share.list", {}, activeSignal));
94061
+ return await this.withToolRemote(hostId, signal ?? this.remoteLifetime.signal, async (remote, activeSignal) => modelShareListResponseSchema.parse(await remote.client.rpc("model.share.list", {}, activeSignal)));
93919
94062
  }
93920
94063
  async start() {
93921
94064
  if (this.closed) throw new Error("client remote-mode runtime is closed");
@@ -93936,7 +94079,7 @@ var ClientModeRuntime = class {
93936
94079
  await this.authorizeHostByDefault();
93937
94080
  }
93938
94081
  } catch (error62) {
93939
- this.logger.warn("automatic Host authorization failed", { code: error62 instanceof ServerApiError ? error62.code : safeErrorCode(error62) });
94082
+ this.logger.warn("automatic Host authorization failed", { code: safeErrorCode(error62) });
93940
94083
  }
93941
94084
  }
93942
94085
  }
@@ -93969,7 +94112,7 @@ var ClientModeRuntime = class {
93969
94112
  }
93970
94113
  if (epoch === this.clientAuthorizationEpoch) await this.enrollLocalHost(this.host, status2.deviceId, true);
93971
94114
  } catch (error62) {
93972
- this.logger.warn("automatic Host authorization failed", { code: error62 instanceof ServerApiError ? error62.code : safeErrorCode(error62) });
94115
+ this.logger.warn("automatic Host authorization failed", { code: safeErrorCode(error62) });
93973
94116
  }
93974
94117
  }
93975
94118
  registerControl(connection, webServer) {
@@ -95021,10 +95164,9 @@ var LEGACY_IDENTITY_RECORD_NAMES = /* @__PURE__ */ new Set([
95021
95164
  "host-pairing.json",
95022
95165
  "pairing-host-only.json"
95023
95166
  ]);
95024
- var IdentityInvalidError = class extends Error {
95167
+ var IdentityInvalidError = class extends SafeCodedError {
95025
95168
  constructor(message, code = "IDENTITY_INVALID") {
95026
- super(message);
95027
- this.code = code;
95169
+ super(code, message);
95028
95170
  }
95029
95171
  };
95030
95172
  var IdentityStore = class {
@@ -96127,7 +96269,7 @@ var ControlStatusStream = class {
96127
96269
  // packages/plugin/src/codex/domain.ts
96128
96270
  import { randomUUID as randomUUID14 } from "node:crypto";
96129
96271
  import { accessSync, constants as constants4, existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync3 } from "node:fs";
96130
- import { readdir as readdir3, realpath as realpath3, stat as stat4 } from "node:fs/promises";
96272
+ import { readdir as readdir3, realpath as realpath4, stat as stat4 } from "node:fs/promises";
96131
96273
  import { homedir as homedir3 } from "node:os";
96132
96274
  import { basename as basename6, isAbsolute as isAbsolute4, join as join8, relative as relative2, resolve as resolve5 } from "node:path";
96133
96275
 
@@ -100859,6 +101001,272 @@ function formatCandidateDiffLines(candidateLines, maxBytes2, maxLines) {
100859
101001
  };
100860
101002
  }
100861
101003
 
101004
+ // packages/plugin/src/workspace-path-guard.ts
101005
+ import { realpath as realpath3 } from "node:fs/promises";
101006
+ import { homedir as osHomedir } from "node:os";
101007
+ import { posix as posix2, win32 as win322 } from "node:path";
101008
+ var INVALID_WORKSPACE_PATH_MESSAGE = "Workspace path must be an absolute, non-root directory path.";
101009
+ var DENIED_WORKSPACE_PATH_MESSAGE = "Workspace path cannot be the user home directory, DSH_HOME, or a system directory.";
101010
+ function toComparisonKey(normalized, targetPlatform) {
101011
+ return targetPlatform === "win32" || targetPlatform === "darwin" ? normalized.toLowerCase() : normalized;
101012
+ }
101013
+ function normalizeCandidate(raw, targetPlatform) {
101014
+ if (typeof raw !== "string" || raw.trim() === "" || raw.includes("\0")) return void 0;
101015
+ const isWin = targetPlatform === "win32";
101016
+ if (!isWin) {
101017
+ if (!posix2.isAbsolute(raw)) return void 0;
101018
+ let normalized2 = posix2.normalize(raw);
101019
+ if (normalized2.length > 1) {
101020
+ normalized2 = normalized2.replace(/\/+$/u, "") || "/";
101021
+ }
101022
+ const isRoot2 = normalized2 === "/";
101023
+ return {
101024
+ normalized: normalized2,
101025
+ key: toComparisonKey(normalized2, targetPlatform),
101026
+ isRoot: isRoot2
101027
+ };
101028
+ }
101029
+ let cleaned = raw.replace(/\//gu, "\\");
101030
+ if (/^\\\\[?.]\\UNC\\/iu.test(cleaned)) {
101031
+ cleaned = `\\\\${cleaned.slice(8)}`;
101032
+ } else if (/^\\\\[?.]\\[A-Za-z]:(?:\\|$)/u.test(cleaned)) {
101033
+ cleaned = cleaned.slice(4);
101034
+ }
101035
+ if (/^\\+$/u.test(cleaned)) {
101036
+ return { normalized: "\\", key: "\\", isRoot: true };
101037
+ }
101038
+ const isDriveQualified = /^[A-Za-z]:\\/u.test(cleaned);
101039
+ const isUnc = /^\\\\[^\\]+\\[^\\]+/u.test(cleaned);
101040
+ if (!isDriveQualified && !isUnc) return void 0;
101041
+ let normalized = win322.normalize(cleaned);
101042
+ const parsedRoot = win322.parse(normalized).root;
101043
+ const isRoot = normalized === parsedRoot || parsedRoot.length > 0 && normalized.replace(/\\+$/u, "").toLowerCase() === parsedRoot.replace(/\\+$/u, "").toLowerCase();
101044
+ if (!isRoot) {
101045
+ normalized = normalized.replace(/\\+$/u, "");
101046
+ }
101047
+ return {
101048
+ normalized,
101049
+ key: toComparisonKey(normalized, targetPlatform),
101050
+ isRoot
101051
+ };
101052
+ }
101053
+ function readEnv(env, name2) {
101054
+ const direct = env[name2];
101055
+ if (typeof direct === "string" && direct.length > 0) return direct;
101056
+ const lower = name2.toLowerCase();
101057
+ for (const [key, value] of Object.entries(env)) {
101058
+ if (key.toLowerCase() === lower && typeof value === "string" && value.length > 0) {
101059
+ return value;
101060
+ }
101061
+ }
101062
+ return void 0;
101063
+ }
101064
+ function combineHomeDrivePath(env) {
101065
+ const drive = readEnv(env, "HOMEDRIVE")?.trim();
101066
+ const homePath = readEnv(env, "HOMEPATH");
101067
+ if (!drive || !/^[A-Za-z]:$/u.test(drive) || !homePath || homePath.trim() === "") return void 0;
101068
+ return homePath.startsWith("\\") || homePath.startsWith("/") ? `${drive}${homePath}` : `${drive}\\${homePath}`;
101069
+ }
101070
+ async function resolveNearestRealpath(normalizedPath, targetPlatform, realpathFn) {
101071
+ if (realpathFn === void 0) return void 0;
101072
+ const pathApi = targetPlatform === "win32" ? win322 : posix2;
101073
+ const suffix = [];
101074
+ let current = normalizedPath;
101075
+ while (true) {
101076
+ try {
101077
+ const resolved = await realpathFn(current);
101078
+ const combined = suffix.length === 0 ? resolved : pathApi.join(resolved, ...suffix);
101079
+ return normalizeCandidate(combined, targetPlatform);
101080
+ } catch (error62) {
101081
+ const code = error62?.code;
101082
+ if (code !== void 0 && code !== "ENOENT" && code !== "ENOTDIR") return void 0;
101083
+ const parent = pathApi.dirname(current);
101084
+ if (parent === current) return void 0;
101085
+ suffix.unshift(pathApi.basename(current));
101086
+ current = parent;
101087
+ }
101088
+ }
101089
+ }
101090
+ function matchesSubtree(candidateKey, rootKey, sep6) {
101091
+ return candidateKey === rootKey || candidateKey.startsWith(`${rootKey}${sep6}`);
101092
+ }
101093
+ async function addExactNormalized(target3, rawPath, targetPlatform) {
101094
+ const parsed = normalizeCandidate(rawPath, targetPlatform);
101095
+ if (parsed === void 0 || parsed.isRoot) return;
101096
+ target3.add(parsed.key);
101097
+ }
101098
+ async function addWithOptionalRealpath(target3, rawPath, targetPlatform, realpathFn) {
101099
+ const parsed = normalizeCandidate(rawPath, targetPlatform);
101100
+ if (parsed === void 0 || parsed.isRoot) return;
101101
+ target3.add(parsed.key);
101102
+ const resolvedParsed = await resolveNearestRealpath(parsed.normalized, targetPlatform, realpathFn);
101103
+ if (resolvedParsed !== void 0 && !resolvedParsed.isRoot) {
101104
+ target3.add(resolvedParsed.key);
101105
+ }
101106
+ }
101107
+ async function inspectWorkspacePath(path, options) {
101108
+ const targetPlatform = options?.platform ?? process.platform;
101109
+ const isWin = targetPlatform === "win32";
101110
+ const pathApi = isWin ? win322 : posix2;
101111
+ const env = options?.env ?? process.env;
101112
+ const readHomedir = options?.homedir ?? osHomedir;
101113
+ const realpathFn = options?.resolveRealpath ?? (isWin === (process.platform === "win32") ? realpath3 : void 0);
101114
+ const lexical = normalizeCandidate(path, targetPlatform);
101115
+ if (lexical === void 0) {
101116
+ return { allowed: false, kind: "invalid", reason: "syntax" };
101117
+ }
101118
+ if (lexical.isRoot) {
101119
+ return { allowed: false, kind: "invalid", reason: "root" };
101120
+ }
101121
+ let osHome;
101122
+ try {
101123
+ osHome = readHomedir();
101124
+ } catch {
101125
+ osHome = void 0;
101126
+ }
101127
+ const rawHomes = [
101128
+ osHome,
101129
+ readEnv(env, "HOME"),
101130
+ ...isWin ? [readEnv(env, "USERPROFILE"), combineHomeDrivePath(env)] : []
101131
+ ].filter((value) => typeof value === "string" && value.trim().length > 0);
101132
+ const homeExact = /* @__PURE__ */ new Set();
101133
+ for (const home of rawHomes) {
101134
+ await addWithOptionalRealpath(homeExact, home, targetPlatform, realpathFn);
101135
+ }
101136
+ const dshHomeSubtree = /* @__PURE__ */ new Set();
101137
+ const explicitDshHome = readEnv(env, "DSH_HOME");
101138
+ if (explicitDshHome !== void 0) {
101139
+ await addWithOptionalRealpath(dshHomeSubtree, explicitDshHome, targetPlatform, realpathFn);
101140
+ }
101141
+ for (const home of rawHomes) {
101142
+ const parsedHome = normalizeCandidate(home, targetPlatform);
101143
+ if (parsedHome === void 0 || parsedHome.isRoot) continue;
101144
+ await addWithOptionalRealpath(
101145
+ dshHomeSubtree,
101146
+ pathApi.join(parsedHome.normalized, ".dsh"),
101147
+ targetPlatform,
101148
+ realpathFn
101149
+ );
101150
+ }
101151
+ const systemSubtree = /* @__PURE__ */ new Set();
101152
+ const systemExact = /* @__PURE__ */ new Set();
101153
+ if (!isWin) {
101154
+ for (const dir of ["/home", "/Users"]) {
101155
+ await addWithOptionalRealpath(homeExact, dir, targetPlatform, realpathFn);
101156
+ }
101157
+ for (const dir of [
101158
+ "/etc",
101159
+ "/private/etc",
101160
+ "/bin",
101161
+ "/sbin",
101162
+ "/usr",
101163
+ "/lib",
101164
+ "/lib64",
101165
+ "/boot",
101166
+ "/dev",
101167
+ "/proc",
101168
+ "/sys",
101169
+ "/run",
101170
+ "/System",
101171
+ "/Library"
101172
+ ]) {
101173
+ await addExactNormalized(systemSubtree, dir, targetPlatform);
101174
+ }
101175
+ for (const dir of [
101176
+ "/var",
101177
+ "/private",
101178
+ "/private/var",
101179
+ "/opt",
101180
+ "/srv",
101181
+ "/root",
101182
+ "/Volumes",
101183
+ "/mnt",
101184
+ "/media",
101185
+ "/Applications"
101186
+ ]) {
101187
+ await addExactNormalized(systemExact, dir, targetPlatform);
101188
+ }
101189
+ } else {
101190
+ const rawSystemDrive = readEnv(env, "SystemDrive")?.trim();
101191
+ const systemDrive = rawSystemDrive && /^[A-Za-z]:$/u.test(rawSystemDrive) ? rawSystemDrive : "C:";
101192
+ await addWithOptionalRealpath(homeExact, `${systemDrive}\\Users`, targetPlatform, realpathFn);
101193
+ for (const dir of [
101194
+ `${systemDrive}\\Windows`,
101195
+ readEnv(env, "SystemRoot"),
101196
+ readEnv(env, "WINDIR"),
101197
+ `${systemDrive}\\Program Files`,
101198
+ readEnv(env, "ProgramFiles"),
101199
+ readEnv(env, "ProgramW6432"),
101200
+ `${systemDrive}\\Program Files (x86)`,
101201
+ readEnv(env, "ProgramFiles(x86)"),
101202
+ `${systemDrive}\\ProgramData`,
101203
+ readEnv(env, "ProgramData")
101204
+ ]) {
101205
+ await addWithOptionalRealpath(systemSubtree, dir, targetPlatform, realpathFn);
101206
+ }
101207
+ for (const dir of [readEnv(env, "APPDATA"), readEnv(env, "LOCALAPPDATA")]) {
101208
+ await addWithOptionalRealpath(systemExact, dir, targetPlatform, realpathFn);
101209
+ }
101210
+ for (const home of rawHomes) {
101211
+ const parsedHome = normalizeCandidate(home, targetPlatform);
101212
+ if (parsedHome === void 0 || parsedHome.isRoot) continue;
101213
+ await addWithOptionalRealpath(
101214
+ systemExact,
101215
+ win322.join(parsedHome.normalized, "AppData", "Roaming"),
101216
+ targetPlatform,
101217
+ realpathFn
101218
+ );
101219
+ await addWithOptionalRealpath(
101220
+ systemExact,
101221
+ win322.join(parsedHome.normalized, "AppData", "Local"),
101222
+ targetPlatform,
101223
+ realpathFn
101224
+ );
101225
+ }
101226
+ }
101227
+ const resolved = await resolveNearestRealpath(lexical.normalized, targetPlatform, realpathFn);
101228
+ const candidates = resolved !== void 0 && resolved.key !== lexical.key ? [lexical, resolved] : [lexical];
101229
+ const sep6 = pathApi.sep;
101230
+ for (const candidate of candidates) {
101231
+ if (candidate.isRoot) {
101232
+ return { allowed: false, kind: "invalid", reason: "root" };
101233
+ }
101234
+ if (homeExact.has(candidate.key)) {
101235
+ return { allowed: false, kind: "disallowed", reason: "home" };
101236
+ }
101237
+ for (const dshRoot of dshHomeSubtree) {
101238
+ if (matchesSubtree(candidate.key, dshRoot, sep6)) {
101239
+ return { allowed: false, kind: "disallowed", reason: "dsh-home" };
101240
+ }
101241
+ }
101242
+ if (systemExact.has(candidate.key)) {
101243
+ return { allowed: false, kind: "disallowed", reason: "system" };
101244
+ }
101245
+ for (const sysRoot of systemSubtree) {
101246
+ if (matchesSubtree(candidate.key, sysRoot, sep6)) {
101247
+ return { allowed: false, kind: "disallowed", reason: "system" };
101248
+ }
101249
+ }
101250
+ }
101251
+ return { allowed: true };
101252
+ }
101253
+ async function assertAllowedWorkspacePath(path, options) {
101254
+ const result = await inspectWorkspacePath(path, options);
101255
+ if (!result.allowed) {
101256
+ if (result.kind === "invalid") {
101257
+ throw new RpcError(
101258
+ options?.invalidCode ?? "INVALID_MESSAGE",
101259
+ options?.invalidMessage ?? INVALID_WORKSPACE_PATH_MESSAGE
101260
+ );
101261
+ }
101262
+ throw new RpcError(
101263
+ options?.deniedCode ?? "WORKSPACE_PATH_DENIED",
101264
+ options?.deniedMessage ?? DENIED_WORKSPACE_PATH_MESSAGE
101265
+ );
101266
+ }
101267
+ return path;
101268
+ }
101269
+
100862
101270
  // packages/plugin/src/codex/app-server.ts
100863
101271
  import { Buffer as Buffer2 } from "node:buffer";
100864
101272
 
@@ -100869,7 +101277,7 @@ import {
100869
101277
  spawn as spawn3
100870
101278
  } from "node:child_process";
100871
101279
  import { readFileSync, statSync as statSync2 } from "node:fs";
100872
- import { win32 as win322 } from "node:path";
101280
+ import { win32 as win323 } from "node:path";
100873
101281
  import { promisify as promisify3 } from "node:util";
100874
101282
  var execFileAsync = promisify3(execFile2);
100875
101283
  var WINDOWS_EXECUTABLE_EXTENSIONS = [".exe", ".cmd", ".bat", ".com"];
@@ -100883,15 +101291,15 @@ var MAX_SHIM_BYTES = 64 * 1024;
100883
101291
  var ALLOWED_SHIM_SET_VARS = /* @__PURE__ */ new Set(["dp0", "_prog", "pathext"]);
100884
101292
  var NPM_SHIM_INVOCATION_PATTERN = /(?:^|[&\s])(?:"(?:%_prog%|%~dp0\\+node\.exe|%dp0%\\+node\.exe)"|node)\s+"((?:%~dp0|%dp0%)[^"]+\.(?:[cm]?js))"\s+%\*\s*$/im;
100885
101293
  function isWindowsExecutablePath(filePath) {
100886
- const ext = win322.extname(filePath.trim()).toLowerCase();
101294
+ const ext = win323.extname(filePath.trim()).toLowerCase();
100887
101295
  return Object.prototype.hasOwnProperty.call(EXTENSION_PRIORITY, ext);
100888
101296
  }
100889
101297
  function windowsExecutableRank(filePath) {
100890
- const ext = win322.extname(filePath.trim()).toLowerCase();
101298
+ const ext = win323.extname(filePath.trim()).toLowerCase();
100891
101299
  return EXTENSION_PRIORITY[ext] ?? Number.POSITIVE_INFINITY;
100892
101300
  }
100893
101301
  function isWindowsBatchFile(filePath) {
100894
- const ext = win322.extname(filePath.trim()).toLowerCase();
101302
+ const ext = win323.extname(filePath.trim()).toLowerCase();
100895
101303
  return ext === ".cmd" || ext === ".bat";
100896
101304
  }
100897
101305
  function selectWindowsExecutable(lines, checkExecutable = defaultIsFile) {
@@ -100900,7 +101308,7 @@ function selectWindowsExecutable(lines, checkExecutable = defaultIsFile) {
100900
101308
  const candidate = rawLine.trim();
100901
101309
  if (!candidate || !isWindowsExecutablePath(candidate)) continue;
100902
101310
  if (!checkExecutable(candidate)) continue;
100903
- matches.push(win322.resolve(candidate));
101311
+ matches.push(win323.resolve(candidate));
100904
101312
  }
100905
101313
  if (matches.length === 0) return void 0;
100906
101314
  matches.sort((left, right) => windowsExecutableRank(left) - windowsExecutableRank(right));
@@ -100948,7 +101356,7 @@ function resolveNpmCmdShim(cmdPath, hooks = {}) {
100948
101356
  if (!match?.[1]) return void 0;
100949
101357
  const relativeTarget = match[1].replace(/^%~?dp0%?[\\/]?/i, "");
100950
101358
  if (relativeTarget.includes("%")) return void 0;
100951
- const resolvedScript = win322.resolve(win322.dirname(cmdPath), relativeTarget);
101359
+ const resolvedScript = win323.resolve(win323.dirname(cmdPath), relativeTarget);
100952
101360
  if (!isFile(resolvedScript)) return void 0;
100953
101361
  const isElectron = hooks.isElectron ?? Boolean(process.versions.electron);
100954
101362
  return {
@@ -104276,7 +104684,7 @@ var CodexRemoteDomain = class {
104276
104684
  const lexicalCandidate = resolve5(path);
104277
104685
  let candidate;
104278
104686
  try {
104279
- candidate = await realpath3(path);
104687
+ candidate = await realpath4(path);
104280
104688
  if (!(await stat4(candidate)).isDirectory()) throw new Error("not a directory");
104281
104689
  } catch {
104282
104690
  throw new RpcError("CODEX_PATH_NOT_ALLOWED", "The CodeX working directory is not available as a Workspace.");
@@ -104284,7 +104692,7 @@ var CodexRemoteDomain = class {
104284
104692
  for (const root2 of paths.values()) {
104285
104693
  try {
104286
104694
  if (!containsCodexPath(resolve5(root2), lexicalCandidate)) continue;
104287
- const canonicalRoot = await realpath3(root2);
104695
+ const canonicalRoot = await realpath4(root2);
104288
104696
  if (containsCodexPath(canonicalRoot, candidate)) return lexicalCandidate;
104289
104697
  } catch {
104290
104698
  }
@@ -104296,10 +104704,19 @@ var CodexRemoteDomain = class {
104296
104704
  throw new RpcError("CODEX_PATH_NOT_ALLOWED", "The CodeX project directory must be an existing absolute directory.");
104297
104705
  }
104298
104706
  try {
104299
- const canonical = await realpath3(resolve5(path));
104707
+ const canonical = await realpath4(resolve5(path));
104300
104708
  if (!(await stat4(canonical)).isDirectory()) throw new Error("not a directory");
104709
+ await assertAllowedWorkspacePath(path, {
104710
+ invalidCode: "CODEX_PATH_NOT_ALLOWED",
104711
+ deniedCode: "CODEX_PATH_NOT_ALLOWED"
104712
+ });
104713
+ await assertAllowedWorkspacePath(canonical, {
104714
+ invalidCode: "CODEX_PATH_NOT_ALLOWED",
104715
+ deniedCode: "CODEX_PATH_NOT_ALLOWED"
104716
+ });
104301
104717
  return canonical;
104302
- } catch {
104718
+ } catch (error62) {
104719
+ if (error62 instanceof RpcError) throw error62;
104303
104720
  throw new RpcError("CODEX_PATH_NOT_ALLOWED", "The CodeX project directory must be an existing absolute directory.");
104304
104721
  }
104305
104722
  }
@@ -104318,7 +104735,7 @@ var CodexRemoteDomain = class {
104318
104735
  }
104319
104736
  if (!directory) continue;
104320
104737
  try {
104321
- const canonicalChild = await realpath3(child);
104738
+ const canonicalChild = await realpath4(child);
104322
104739
  if (!(await stat4(canonicalChild)).isDirectory()) continue;
104323
104740
  if (!containsCodexPath(target3.canonicalRoot, canonicalChild)) continue;
104324
104741
  } catch {
@@ -104347,7 +104764,7 @@ var CodexRemoteDomain = class {
104347
104764
  const lexicalCandidate = resolve5(path);
104348
104765
  let canonicalCandidate;
104349
104766
  try {
104350
- canonicalCandidate = await realpath3(path);
104767
+ canonicalCandidate = await realpath4(path);
104351
104768
  if (!(await stat4(canonicalCandidate)).isDirectory()) throw new Error("not a directory");
104352
104769
  } catch {
104353
104770
  throw new RpcError("CODEX_PATH_NOT_ALLOWED", "The CodeX working directory is not available as a Workspace.");
@@ -104356,7 +104773,7 @@ var CodexRemoteDomain = class {
104356
104773
  try {
104357
104774
  const lexicalRoot = resolve5(root2);
104358
104775
  if (!containsCodexPath(lexicalRoot, lexicalCandidate)) continue;
104359
- const canonicalRoot = await realpath3(root2);
104776
+ const canonicalRoot = await realpath4(root2);
104360
104777
  if (containsCodexPath(canonicalRoot, canonicalCandidate)) {
104361
104778
  return { path: lexicalCandidate, root: lexicalRoot, canonicalRoot };
104362
104779
  }
@@ -105171,7 +105588,7 @@ function record9(value) {
105171
105588
  }
105172
105589
 
105173
105590
  // packages/plugin/src/acp/adapters/cursor-process.ts
105174
- import { Buffer as Buffer5 } from "node:buffer";
105591
+ import { Buffer as Buffer6 } from "node:buffer";
105175
105592
 
105176
105593
  // packages/plugin/src/acp/adapters/stdio-jsonrpc.ts
105177
105594
  import { Buffer as Buffer4 } from "node:buffer";
@@ -105301,10 +105718,284 @@ function isRecord16(value) {
105301
105718
  return typeof value === "object" && value !== null && !Array.isArray(value);
105302
105719
  }
105303
105720
 
105721
+ // packages/plugin/src/acp/history-events.ts
105722
+ import { Buffer as Buffer5 } from "node:buffer";
105723
+ var ACP_HISTORY_SOFT_MAX_BYTES = 8 * 1024 * 1024;
105724
+ var ACP_HISTORY_HARD_MAX_BYTES = 16 * 1024 * 1024;
105725
+ var ACP_HISTORY_MULTIMODAL_HARD_MAX_BYTES = 48 * 1024 * 1024;
105726
+ var ACP_HISTORY_SOFT_MAX_EVENTS = 1e4;
105727
+ var ACP_HISTORY_HARD_MAX_EVENTS = 2e4;
105728
+ var ACP_HISTORY_MAX_RAW_BYTES = 256 * 1024 * 1024;
105729
+ var ACP_HISTORY_MAX_RAW_UPDATES = 5e5;
105730
+ var ACP_HISTORY_LOAD_TIMEOUT_MS = 12e4;
105731
+ var MULTIMODAL_ACP_HISTORY_BACKENDS = /* @__PURE__ */ new Set(["antigravity", "hermes", "kimi"]);
105732
+ function acpHistoryLimitsForBackend(backend) {
105733
+ return {
105734
+ maxBytes: ACP_HISTORY_SOFT_MAX_BYTES,
105735
+ hardMaxBytes: MULTIMODAL_ACP_HISTORY_BACKENDS.has(backend) ? ACP_HISTORY_MULTIMODAL_HARD_MAX_BYTES : ACP_HISTORY_HARD_MAX_BYTES,
105736
+ maxEvents: ACP_HISTORY_SOFT_MAX_EVENTS,
105737
+ hardMaxEvents: ACP_HISTORY_HARD_MAX_EVENTS
105738
+ };
105739
+ }
105740
+ var MESSAGE_ENVELOPE_OVERHEAD_BYTES = 192;
105741
+ var AcpHistoryAccumulator = class {
105742
+ constructor(sessionId, provider, limits = {}) {
105743
+ this.sessionId = sessionId;
105744
+ this.provider = provider;
105745
+ this.limits = limits;
105746
+ }
105747
+ completedTurns = [];
105748
+ tools = /* @__PURE__ */ new Map();
105749
+ currentTurn;
105750
+ completedBytes = 0;
105751
+ completedEventCount = 0;
105752
+ emittedCount = 0;
105753
+ turn = 0;
105754
+ step = 1;
105755
+ afterTools = false;
105756
+ pending;
105757
+ toolPendingBytes = 0;
105758
+ truncated = false;
105759
+ overflowed = false;
105760
+ /**
105761
+ * Consume one inbound ACP message during `session/load` replay.
105762
+ * Returns `false` if a hard single-turn safety limit was exceeded.
105763
+ */
105764
+ push(message) {
105765
+ if (this.overflowed) return false;
105766
+ const params = message.params;
105767
+ if (message.kind !== "notification" || message.method !== "session/update" || params?.sessionId !== this.sessionId) {
105768
+ return true;
105769
+ }
105770
+ const update = params.update;
105771
+ if (!update) return true;
105772
+ const kind = update.sessionUpdate;
105773
+ if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
105774
+ const content = update.content;
105775
+ const isText = content?.type === "text" && typeof content.text === "string";
105776
+ const isImage = kind === "user_message_chunk" && content?.type === "image" && typeof content.mimeType === "string" && typeof content.data === "string";
105777
+ if (!isText && !isImage) return true;
105778
+ const role2 = kind === "user_message_chunk" ? "user" : "assistant";
105779
+ if (role2 === "user" && this.pending?.role !== "user") {
105780
+ this.startNewTurn(true);
105781
+ } else if (!this.turn) {
105782
+ this.startNewTurn(false);
105783
+ }
105784
+ if (this.pending && this.pending.role !== role2) this.flushMessage();
105785
+ this.flushTools();
105786
+ if (role2 === "assistant" && this.afterTools) {
105787
+ this.pushEvent("step/end", { turn: this.turn, step: this.step });
105788
+ this.step++;
105789
+ this.pushEvent("step/start", { turn: this.turn, step: this.step });
105790
+ this.afterTools = false;
105791
+ }
105792
+ this.pending ??= { role: role2, content: [], bytes: MESSAGE_ENVELOPE_OVERHEAD_BYTES };
105793
+ if (isImage) {
105794
+ try {
105795
+ const parsed = parseAcpImage(content);
105796
+ const ext = parsed.mimeType === "image/jpeg" ? "jpg" : parsed.mimeType.slice(6);
105797
+ const attachmentId = `agy-image:history-${this.sessionId}-${this.emittedCount}-${this.pending.content.length}.${ext}`;
105798
+ const block = {
105799
+ ...acpImageContent(parsed, attachmentId),
105800
+ mimeType: parsed.mimeType
105801
+ };
105802
+ this.pending.content.push(block);
105803
+ this.pending.bytes += Buffer5.byteLength(JSON.stringify(block), "utf8");
105804
+ } catch {
105805
+ const block = {
105806
+ type: "image",
105807
+ mimeType: content.mimeType,
105808
+ mediaType: content.mimeType,
105809
+ data: content.data
105810
+ };
105811
+ this.pending.content.push(block);
105812
+ this.pending.bytes += Buffer5.byteLength(content.data, "utf8") + Buffer5.byteLength(content.mimeType, "utf8") + 64;
105813
+ }
105814
+ } else {
105815
+ const type = kind === "agent_thought_chunk" ? "reasoning" : "text";
105816
+ const previous = this.pending.content.at(-1);
105817
+ const textBytes = Buffer5.byteLength(content.text, "utf8");
105818
+ if (previous?.type === type && typeof previous.text === "string") {
105819
+ previous.text += content.text;
105820
+ this.pending.bytes += textBytes;
105821
+ } else {
105822
+ this.pending.content.push({ type, text: content.text });
105823
+ this.pending.bytes += textBytes + 32;
105824
+ }
105825
+ }
105826
+ return this.enforceLimits();
105827
+ }
105828
+ if ((kind === "tool_call" || kind === "tool_call_update") && typeof update.toolCallId === "string") {
105829
+ this.flushMessage();
105830
+ if (!this.turn) this.startNewTurn(false);
105831
+ this.afterTools = true;
105832
+ let tool = this.tools.get(update.toolCallId);
105833
+ if (!tool) {
105834
+ tool = {
105835
+ id: update.toolCallId,
105836
+ name: typeof update.title === "string" ? update.title : typeof update.name === "string" ? update.name : "tool",
105837
+ input: update.rawInput ?? update.args,
105838
+ output: [],
105839
+ outputBytes: 0,
105840
+ failed: false,
105841
+ terminal: false,
105842
+ emitted: false
105843
+ };
105844
+ this.tools.set(tool.id, tool);
105845
+ this.pushEvent("tool/call", {
105846
+ turn: this.turn,
105847
+ step: this.step,
105848
+ callId: tool.id,
105849
+ name: tool.name,
105850
+ arguments: typeof tool.input === "string" ? tool.input : JSON.stringify(tool.input ?? {})
105851
+ });
105852
+ }
105853
+ const decoded = piToolResult(update);
105854
+ if (!decoded.content.length && update.rawOutput !== void 0) {
105855
+ decoded.content.push({
105856
+ type: "text",
105857
+ text: typeof update.rawOutput === "string" ? update.rawOutput : JSON.stringify(update.rawOutput)
105858
+ });
105859
+ }
105860
+ if (decoded.content.length) {
105861
+ if (!tool.emitted) {
105862
+ const nextOutputBytes = Buffer5.byteLength(JSON.stringify(decoded.content), "utf8");
105863
+ this.toolPendingBytes += nextOutputBytes - tool.outputBytes;
105864
+ tool.outputBytes = nextOutputBytes;
105865
+ }
105866
+ tool.output = decoded.content;
105867
+ }
105868
+ tool.failed ||= decoded.isError || update.status === "failed";
105869
+ tool.terminal ||= update.status === "completed" || update.status === "failed";
105870
+ if (kind === "tool_call_update" && tool.terminal) this.emitToolResult(tool);
105871
+ return this.enforceLimits();
105872
+ }
105873
+ return true;
105874
+ }
105875
+ /** Finalize any open turn, enforce limits on serialized output, and return retained events. */
105876
+ finish() {
105877
+ if (this.overflowed) {
105878
+ return { events: [], truncated: this.truncated, overflow: true };
105879
+ }
105880
+ this.endTurn();
105881
+ if (!this.enforceLimits()) {
105882
+ return { events: [], truncated: this.truncated, overflow: true };
105883
+ }
105884
+ const events = [];
105885
+ for (const bucket of this.completedTurns) events.push(...bucket.events);
105886
+ if (this.currentTurn) events.push(...this.currentTurn.events);
105887
+ if (this.truncated) {
105888
+ for (let i = 0; i < events.length; i += 1) {
105889
+ events[i].event.seq = i;
105890
+ }
105891
+ }
105892
+ return { events, truncated: this.truncated, overflow: false };
105893
+ }
105894
+ nextId() {
105895
+ return `${this.provider}-history:${this.sessionId}:${this.emittedCount}`;
105896
+ }
105897
+ pushEvent(type, data2, surface = false) {
105898
+ this.currentTurn ??= { events: [], bytes: 0 };
105899
+ const entry = {
105900
+ type: "event",
105901
+ event: {
105902
+ type,
105903
+ seq: this.emittedCount,
105904
+ time: 0,
105905
+ data: data2,
105906
+ ...surface ? { surfaceOp: "append" } : {}
105907
+ }
105908
+ };
105909
+ this.emittedCount++;
105910
+ this.currentTurn.events.push(entry);
105911
+ this.currentTurn.bytes += Buffer5.byteLength(JSON.stringify(entry), "utf8");
105912
+ }
105913
+ flushMessage() {
105914
+ if (!this.pending) return;
105915
+ const message = { id: this.nextId(), role: this.pending.role, content: this.pending.content };
105916
+ if (this.pending.role === "user") this.pushEvent("user/message", { ...message, source: { kind: "user" } }, true);
105917
+ else this.pushEvent("assistant/message", { turn: this.turn, step: this.step, message: { ...message, source: { kind: "model", provider: this.provider, model: "" } }, stream: [] }, true);
105918
+ this.pending = void 0;
105919
+ }
105920
+ emitToolResult(tool) {
105921
+ if (tool.emitted || !tool.terminal) return;
105922
+ tool.emitted = true;
105923
+ if (tool.outputBytes > 0) {
105924
+ this.toolPendingBytes -= tool.outputBytes;
105925
+ tool.outputBytes = 0;
105926
+ }
105927
+ this.pushEvent("tool/result", {
105928
+ turn: this.turn,
105929
+ step: this.step,
105930
+ message: {
105931
+ id: this.nextId(),
105932
+ role: "user",
105933
+ source: { kind: "tool", callId: tool.id },
105934
+ content: [{
105935
+ type: "tool-result",
105936
+ toolCallId: tool.id,
105937
+ content: tool.output,
105938
+ ...tool.failed ? { isError: true } : {}
105939
+ }]
105940
+ }
105941
+ }, true);
105942
+ }
105943
+ flushTools() {
105944
+ for (const tool of this.tools.values()) this.emitToolResult(tool);
105945
+ }
105946
+ endTurn() {
105947
+ this.flushMessage();
105948
+ this.flushTools();
105949
+ if (this.turn) {
105950
+ this.pushEvent("step/end", { turn: this.turn, step: this.step });
105951
+ this.pushEvent("turn/end", { turn: this.turn, reason: { kind: "completed" } });
105952
+ }
105953
+ this.tools.clear();
105954
+ this.toolPendingBytes = 0;
105955
+ this.afterTools = false;
105956
+ }
105957
+ startNewTurn(resetStep) {
105958
+ this.endTurn();
105959
+ if (this.currentTurn && this.currentTurn.events.length > 0) {
105960
+ this.completedTurns.push(this.currentTurn);
105961
+ this.completedBytes += this.currentTurn.bytes;
105962
+ this.completedEventCount += this.currentTurn.events.length;
105963
+ }
105964
+ this.currentTurn = { events: [], bytes: 0 };
105965
+ this.turn++;
105966
+ if (resetStep) this.step = 1;
105967
+ this.pushEvent("turn/start", { turn: this.turn });
105968
+ this.pushEvent("step/start", { turn: this.turn, step: this.step });
105969
+ }
105970
+ totalBytes() {
105971
+ return this.completedBytes + (this.currentTurn?.bytes ?? 0) + (this.pending?.bytes ?? 0) + this.toolPendingBytes;
105972
+ }
105973
+ totalEvents() {
105974
+ return this.completedEventCount + (this.currentTurn?.events.length ?? 0);
105975
+ }
105976
+ enforceLimits() {
105977
+ const { maxBytes: maxBytes2, maxEvents } = this.limits;
105978
+ while (this.completedTurns.length > 0 && (maxBytes2 !== void 0 && this.totalBytes() > maxBytes2 || maxEvents !== void 0 && this.totalEvents() > maxEvents)) {
105979
+ const evicted = this.completedTurns.shift();
105980
+ this.completedBytes -= evicted.bytes;
105981
+ this.completedEventCount -= evicted.events.length;
105982
+ this.truncated = true;
105983
+ }
105984
+ const hardMaxBytes = this.limits.hardMaxBytes ?? maxBytes2;
105985
+ const hardMaxEvents = this.limits.hardMaxEvents ?? maxEvents;
105986
+ if (hardMaxBytes !== void 0 && this.totalBytes() > hardMaxBytes || hardMaxEvents !== void 0 && this.totalEvents() > hardMaxEvents) {
105987
+ this.overflowed = true;
105988
+ return false;
105989
+ }
105990
+ return true;
105991
+ }
105992
+ };
105993
+
105304
105994
  // packages/plugin/src/acp/adapters/cursor-process.ts
105305
105995
  var ACP_REQUEST_TIMEOUT_MS = 6e4;
105306
105996
  var ACP_PROMPT_TIMEOUT_MS = 10 * 6e4;
105307
105997
  var ACP_START_TIMEOUT_MS = 2e4;
105998
+ var MAX_SESSION_COMMANDS = 128;
105308
105999
  var MAX_STDERR_CAPTURE_BYTES2 = 4 * 1024;
105309
106000
  var ADAPTER_LABELS = Object.freeze({
105310
106001
  cursor: "Cursor",
@@ -105345,6 +106036,21 @@ var CursorAcpClient = class {
105345
106036
  startPromise;
105346
106037
  modelStates = /* @__PURE__ */ new Map();
105347
106038
  modelBusy = /* @__PURE__ */ new Set();
106039
+ isSessionBusy(sessionId) {
106040
+ return this.modelBusy.has(sessionId);
106041
+ }
106042
+ evictSessionState(sessionId) {
106043
+ this.modelStates.delete(sessionId);
106044
+ this.sessionCommands.delete(sessionId);
106045
+ }
106046
+ sessionMetadata(sessionId) {
106047
+ const state2 = this.modelStates.get(sessionId);
106048
+ return {
106049
+ models: state2?.catalog(),
106050
+ modes: state2?.modesCatalog(),
106051
+ commands: this.sessionCommands.get(sessionId)
106052
+ };
106053
+ }
105348
106054
  sessionCommands = /* @__PURE__ */ new Map();
105349
106055
  initMetadata;
105350
106056
  lastAuthDiagnostic;
@@ -105458,7 +106164,7 @@ var CursorAcpClient = class {
105458
106164
  this.write({ jsonrpc: "2.0", method, params });
105459
106165
  return {};
105460
106166
  }
105461
- const budget = timeoutMs ?? (method === "session/prompt" ? ACP_PROMPT_TIMEOUT_MS : ACP_REQUEST_TIMEOUT_MS);
106167
+ const budget = timeoutMs ?? (method === "session/prompt" ? ACP_PROMPT_TIMEOUT_MS : method === "session/load" ? ACP_HISTORY_LOAD_TIMEOUT_MS : ACP_REQUEST_TIMEOUT_MS);
105462
106168
  const provisionalLoad = Boolean(backend && method === "session/load" && id7 && !this.modelStates.has(id7));
105463
106169
  if (provisionalLoad && backend && id7) {
105464
106170
  this.modelStates.set(id7, new AcpSessionModelState(backend));
@@ -105502,6 +106208,7 @@ var CursorAcpClient = class {
105502
106208
  this.closed = true;
105503
106209
  this.ready = false;
105504
106210
  this.modelStates.clear();
106211
+ this.sessionCommands.clear();
105505
106212
  this.rpc.failPending(new CursorAcpError(this.code("CLOSED"), `${this.adapterLabel} ACP was closed.`));
105506
106213
  const child = this.process;
105507
106214
  this.process = void 0;
@@ -105536,11 +106243,11 @@ var CursorAcpClient = class {
105536
106243
  this.rpc.resetBuffer();
105537
106244
  this.stderrBytes = 0;
105538
106245
  child.stdout.on("data", (chunk) => {
105539
- if (this.process === child) this.rpc.consumeStdout(Buffer5.from(chunk));
106246
+ if (this.process === child) this.rpc.consumeStdout(Buffer6.from(chunk));
105540
106247
  });
105541
106248
  child.stderr.on("data", (chunk) => {
105542
106249
  if (this.process !== child) return;
105543
- this.stderrBytes = Math.min(MAX_STDERR_CAPTURE_BYTES2, this.stderrBytes + Buffer5.byteLength(chunk));
106250
+ this.stderrBytes = Math.min(MAX_STDERR_CAPTURE_BYTES2, this.stderrBytes + Buffer6.byteLength(chunk));
105544
106251
  });
105545
106252
  child.on("error", (error62) => {
105546
106253
  if (this.process === child) this.handleProcessFailure(this.code("BINARY_UNAVAILABLE"), error62);
@@ -105550,6 +106257,7 @@ var CursorAcpClient = class {
105550
106257
  this.process = void 0;
105551
106258
  this.ready = false;
105552
106259
  this.modelStates.clear();
106260
+ this.sessionCommands.clear();
105553
106261
  this.rpc.failPending(new CursorAcpError(this.code("ACP_EXITED"), `${this.adapterLabel} ACP exited unexpectedly.`));
105554
106262
  if (!this.closed) {
105555
106263
  this.logger?.warn(`${this.adapterLabel} ACP exited`, {
@@ -105584,6 +106292,7 @@ var CursorAcpClient = class {
105584
106292
  } catch (error62) {
105585
106293
  this.ready = false;
105586
106294
  this.modelStates.clear();
106295
+ this.sessionCommands.clear();
105587
106296
  if (this.process === child) this.process = void 0;
105588
106297
  child.kill("SIGTERM");
105589
106298
  if (error62 instanceof CursorAcpError) throw error62;
@@ -105607,7 +106316,12 @@ var CursorAcpClient = class {
105607
106316
  if (inbound.kind === "notification" && inbound.method === "session/update" && isRecord17(params) && typeof params.sessionId === "string") {
105608
106317
  this.modelStates.get(params.sessionId)?.update(params.update);
105609
106318
  if (isRecord17(params.update) && params.update.sessionUpdate === "available_commands_update") {
106319
+ this.sessionCommands.delete(params.sessionId);
105610
106320
  this.sessionCommands.set(params.sessionId, parseAvailableCommands(params.update));
106321
+ if (this.sessionCommands.size > MAX_SESSION_COMMANDS) {
106322
+ const oldest = this.sessionCommands.keys().next().value;
106323
+ if (oldest !== void 0) this.sessionCommands.delete(oldest);
106324
+ }
105611
106325
  }
105612
106326
  }
105613
106327
  for (const handler of this.inboundHandlers) handler(inbound);
@@ -105615,6 +106329,7 @@ var CursorAcpClient = class {
105615
106329
  handleProcessFailure(code, cause) {
105616
106330
  this.ready = false;
105617
106331
  this.modelStates.clear();
106332
+ this.sessionCommands.clear();
105618
106333
  this.rpc.failPending(new CursorAcpError(code, `${this.adapterLabel} ACP communication failed.`, { cause }));
105619
106334
  const child = this.process;
105620
106335
  this.process = void 0;
@@ -105632,279 +106347,6 @@ function isRecord17(value) {
105632
106347
  return typeof value === "object" && value !== null && !Array.isArray(value);
105633
106348
  }
105634
106349
 
105635
- // packages/plugin/src/acp/history-events.ts
105636
- import { Buffer as Buffer6 } from "node:buffer";
105637
- var ACP_HISTORY_SOFT_MAX_BYTES = 8 * 1024 * 1024;
105638
- var ACP_HISTORY_HARD_MAX_BYTES = 16 * 1024 * 1024;
105639
- var ACP_HISTORY_MULTIMODAL_HARD_MAX_BYTES = 48 * 1024 * 1024;
105640
- var ACP_HISTORY_SOFT_MAX_EVENTS = 1e4;
105641
- var ACP_HISTORY_HARD_MAX_EVENTS = 2e4;
105642
- var ACP_HISTORY_MAX_RAW_BYTES = 256 * 1024 * 1024;
105643
- var ACP_HISTORY_MAX_RAW_UPDATES = 5e5;
105644
- var ACP_HISTORY_LOAD_TIMEOUT_MS = 12e4;
105645
- var MULTIMODAL_ACP_HISTORY_BACKENDS = /* @__PURE__ */ new Set(["antigravity", "hermes", "kimi"]);
105646
- function acpHistoryLimitsForBackend(backend) {
105647
- return {
105648
- maxBytes: ACP_HISTORY_SOFT_MAX_BYTES,
105649
- hardMaxBytes: MULTIMODAL_ACP_HISTORY_BACKENDS.has(backend) ? ACP_HISTORY_MULTIMODAL_HARD_MAX_BYTES : ACP_HISTORY_HARD_MAX_BYTES,
105650
- maxEvents: ACP_HISTORY_SOFT_MAX_EVENTS,
105651
- hardMaxEvents: ACP_HISTORY_HARD_MAX_EVENTS
105652
- };
105653
- }
105654
- var MESSAGE_ENVELOPE_OVERHEAD_BYTES = 192;
105655
- var AcpHistoryAccumulator = class {
105656
- constructor(sessionId, provider, limits = {}) {
105657
- this.sessionId = sessionId;
105658
- this.provider = provider;
105659
- this.limits = limits;
105660
- }
105661
- completedTurns = [];
105662
- tools = /* @__PURE__ */ new Map();
105663
- currentTurn;
105664
- completedBytes = 0;
105665
- completedEventCount = 0;
105666
- emittedCount = 0;
105667
- turn = 0;
105668
- step = 1;
105669
- afterTools = false;
105670
- pending;
105671
- toolPendingBytes = 0;
105672
- truncated = false;
105673
- overflowed = false;
105674
- /**
105675
- * Consume one inbound ACP message during `session/load` replay.
105676
- * Returns `false` if a hard single-turn safety limit was exceeded.
105677
- */
105678
- push(message) {
105679
- if (this.overflowed) return false;
105680
- const params = message.params;
105681
- if (message.kind !== "notification" || message.method !== "session/update" || params?.sessionId !== this.sessionId) {
105682
- return true;
105683
- }
105684
- const update = params.update;
105685
- if (!update) return true;
105686
- const kind = update.sessionUpdate;
105687
- if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
105688
- const content = update.content;
105689
- const isText = content?.type === "text" && typeof content.text === "string";
105690
- const isImage = kind === "user_message_chunk" && content?.type === "image" && typeof content.mimeType === "string" && typeof content.data === "string";
105691
- if (!isText && !isImage) return true;
105692
- const role2 = kind === "user_message_chunk" ? "user" : "assistant";
105693
- if (role2 === "user" && this.pending?.role !== "user") {
105694
- this.startNewTurn(true);
105695
- } else if (!this.turn) {
105696
- this.startNewTurn(false);
105697
- }
105698
- if (this.pending && this.pending.role !== role2) this.flushMessage();
105699
- this.flushTools();
105700
- if (role2 === "assistant" && this.afterTools) {
105701
- this.pushEvent("step/end", { turn: this.turn, step: this.step });
105702
- this.step++;
105703
- this.pushEvent("step/start", { turn: this.turn, step: this.step });
105704
- this.afterTools = false;
105705
- }
105706
- this.pending ??= { role: role2, content: [], bytes: MESSAGE_ENVELOPE_OVERHEAD_BYTES };
105707
- if (isImage) {
105708
- try {
105709
- const parsed = parseAcpImage(content);
105710
- const ext = parsed.mimeType === "image/jpeg" ? "jpg" : parsed.mimeType.slice(6);
105711
- const attachmentId = `agy-image:history-${this.sessionId}-${this.emittedCount}-${this.pending.content.length}.${ext}`;
105712
- const block = {
105713
- ...acpImageContent(parsed, attachmentId),
105714
- mimeType: parsed.mimeType
105715
- };
105716
- this.pending.content.push(block);
105717
- this.pending.bytes += Buffer6.byteLength(JSON.stringify(block), "utf8");
105718
- } catch {
105719
- const block = {
105720
- type: "image",
105721
- mimeType: content.mimeType,
105722
- mediaType: content.mimeType,
105723
- data: content.data
105724
- };
105725
- this.pending.content.push(block);
105726
- this.pending.bytes += Buffer6.byteLength(content.data, "utf8") + Buffer6.byteLength(content.mimeType, "utf8") + 64;
105727
- }
105728
- } else {
105729
- const type = kind === "agent_thought_chunk" ? "reasoning" : "text";
105730
- const previous = this.pending.content.at(-1);
105731
- const textBytes = Buffer6.byteLength(content.text, "utf8");
105732
- if (previous?.type === type && typeof previous.text === "string") {
105733
- previous.text += content.text;
105734
- this.pending.bytes += textBytes;
105735
- } else {
105736
- this.pending.content.push({ type, text: content.text });
105737
- this.pending.bytes += textBytes + 32;
105738
- }
105739
- }
105740
- return this.enforceLimits();
105741
- }
105742
- if ((kind === "tool_call" || kind === "tool_call_update") && typeof update.toolCallId === "string") {
105743
- this.flushMessage();
105744
- if (!this.turn) this.startNewTurn(false);
105745
- this.afterTools = true;
105746
- let tool = this.tools.get(update.toolCallId);
105747
- if (!tool) {
105748
- tool = {
105749
- id: update.toolCallId,
105750
- name: typeof update.title === "string" ? update.title : typeof update.name === "string" ? update.name : "tool",
105751
- input: update.rawInput ?? update.args,
105752
- output: [],
105753
- outputBytes: 0,
105754
- failed: false,
105755
- terminal: false,
105756
- emitted: false
105757
- };
105758
- this.tools.set(tool.id, tool);
105759
- this.pushEvent("tool/call", {
105760
- turn: this.turn,
105761
- step: this.step,
105762
- callId: tool.id,
105763
- name: tool.name,
105764
- arguments: typeof tool.input === "string" ? tool.input : JSON.stringify(tool.input ?? {})
105765
- });
105766
- }
105767
- const decoded = piToolResult(update);
105768
- if (!decoded.content.length && update.rawOutput !== void 0) {
105769
- decoded.content.push({
105770
- type: "text",
105771
- text: typeof update.rawOutput === "string" ? update.rawOutput : JSON.stringify(update.rawOutput)
105772
- });
105773
- }
105774
- if (decoded.content.length) {
105775
- if (!tool.emitted) {
105776
- const nextOutputBytes = Buffer6.byteLength(JSON.stringify(decoded.content), "utf8");
105777
- this.toolPendingBytes += nextOutputBytes - tool.outputBytes;
105778
- tool.outputBytes = nextOutputBytes;
105779
- }
105780
- tool.output = decoded.content;
105781
- }
105782
- tool.failed ||= decoded.isError || update.status === "failed";
105783
- tool.terminal ||= update.status === "completed" || update.status === "failed";
105784
- if (kind === "tool_call_update" && tool.terminal) this.emitToolResult(tool);
105785
- return this.enforceLimits();
105786
- }
105787
- return true;
105788
- }
105789
- /** Finalize any open turn, enforce limits on serialized output, and return retained events. */
105790
- finish() {
105791
- if (this.overflowed) {
105792
- return { events: [], truncated: this.truncated, overflow: true };
105793
- }
105794
- this.endTurn();
105795
- if (!this.enforceLimits()) {
105796
- return { events: [], truncated: this.truncated, overflow: true };
105797
- }
105798
- const events = [];
105799
- for (const bucket of this.completedTurns) events.push(...bucket.events);
105800
- if (this.currentTurn) events.push(...this.currentTurn.events);
105801
- if (this.truncated) {
105802
- for (let i = 0; i < events.length; i += 1) {
105803
- events[i].event.seq = i;
105804
- }
105805
- }
105806
- return { events, truncated: this.truncated, overflow: false };
105807
- }
105808
- nextId() {
105809
- return `${this.provider}-history:${this.sessionId}:${this.emittedCount}`;
105810
- }
105811
- pushEvent(type, data2, surface = false) {
105812
- this.currentTurn ??= { events: [], bytes: 0 };
105813
- const entry = {
105814
- type: "event",
105815
- event: {
105816
- type,
105817
- seq: this.emittedCount,
105818
- time: 0,
105819
- data: data2,
105820
- ...surface ? { surfaceOp: "append" } : {}
105821
- }
105822
- };
105823
- this.emittedCount++;
105824
- this.currentTurn.events.push(entry);
105825
- this.currentTurn.bytes += Buffer6.byteLength(JSON.stringify(entry), "utf8");
105826
- }
105827
- flushMessage() {
105828
- if (!this.pending) return;
105829
- const message = { id: this.nextId(), role: this.pending.role, content: this.pending.content };
105830
- if (this.pending.role === "user") this.pushEvent("user/message", { ...message, source: { kind: "user" } }, true);
105831
- else this.pushEvent("assistant/message", { turn: this.turn, step: this.step, message: { ...message, source: { kind: "model", provider: this.provider, model: "" } }, stream: [] }, true);
105832
- this.pending = void 0;
105833
- }
105834
- emitToolResult(tool) {
105835
- if (tool.emitted || !tool.terminal) return;
105836
- tool.emitted = true;
105837
- if (tool.outputBytes > 0) {
105838
- this.toolPendingBytes -= tool.outputBytes;
105839
- tool.outputBytes = 0;
105840
- }
105841
- this.pushEvent("tool/result", {
105842
- turn: this.turn,
105843
- step: this.step,
105844
- message: {
105845
- id: this.nextId(),
105846
- role: "user",
105847
- source: { kind: "tool", callId: tool.id },
105848
- content: [{
105849
- type: "tool-result",
105850
- toolCallId: tool.id,
105851
- content: tool.output,
105852
- ...tool.failed ? { isError: true } : {}
105853
- }]
105854
- }
105855
- }, true);
105856
- }
105857
- flushTools() {
105858
- for (const tool of this.tools.values()) this.emitToolResult(tool);
105859
- }
105860
- endTurn() {
105861
- this.flushMessage();
105862
- this.flushTools();
105863
- if (this.turn) {
105864
- this.pushEvent("step/end", { turn: this.turn, step: this.step });
105865
- this.pushEvent("turn/end", { turn: this.turn, reason: { kind: "completed" } });
105866
- }
105867
- this.tools.clear();
105868
- this.toolPendingBytes = 0;
105869
- this.afterTools = false;
105870
- }
105871
- startNewTurn(resetStep) {
105872
- this.endTurn();
105873
- if (this.currentTurn && this.currentTurn.events.length > 0) {
105874
- this.completedTurns.push(this.currentTurn);
105875
- this.completedBytes += this.currentTurn.bytes;
105876
- this.completedEventCount += this.currentTurn.events.length;
105877
- }
105878
- this.currentTurn = { events: [], bytes: 0 };
105879
- this.turn++;
105880
- if (resetStep) this.step = 1;
105881
- this.pushEvent("turn/start", { turn: this.turn });
105882
- this.pushEvent("step/start", { turn: this.turn, step: this.step });
105883
- }
105884
- totalBytes() {
105885
- return this.completedBytes + (this.currentTurn?.bytes ?? 0) + (this.pending?.bytes ?? 0) + this.toolPendingBytes;
105886
- }
105887
- totalEvents() {
105888
- return this.completedEventCount + (this.currentTurn?.events.length ?? 0);
105889
- }
105890
- enforceLimits() {
105891
- const { maxBytes: maxBytes2, maxEvents } = this.limits;
105892
- while (this.completedTurns.length > 0 && (maxBytes2 !== void 0 && this.totalBytes() > maxBytes2 || maxEvents !== void 0 && this.totalEvents() > maxEvents)) {
105893
- const evicted = this.completedTurns.shift();
105894
- this.completedBytes -= evicted.bytes;
105895
- this.completedEventCount -= evicted.events.length;
105896
- this.truncated = true;
105897
- }
105898
- const hardMaxBytes = this.limits.hardMaxBytes ?? maxBytes2;
105899
- const hardMaxEvents = this.limits.hardMaxEvents ?? maxEvents;
105900
- if (hardMaxBytes !== void 0 && this.totalBytes() > hardMaxBytes || hardMaxEvents !== void 0 && this.totalEvents() > hardMaxEvents) {
105901
- this.overflowed = true;
105902
- return false;
105903
- }
105904
- return true;
105905
- }
105906
- };
105907
-
105908
106350
  // packages/plugin/src/acp/adapters/isolated-process.ts
105909
106351
  var IsolatedAcpClient = class {
105910
106352
  constructor(binary, logger2, options = {}, factory = () => new CursorAcpClient(
@@ -105920,6 +106362,9 @@ var IsolatedAcpClient = class {
105920
106362
  }
105921
106363
  catalog;
105922
106364
  clients = /* @__PURE__ */ new Map();
106365
+ retiring = /* @__PURE__ */ new Map();
106366
+ closingSessions = /* @__PURE__ */ new Map();
106367
+ activeCalls = /* @__PURE__ */ new Map();
105923
106368
  starting = /* @__PURE__ */ new Set();
105924
106369
  inbound = /* @__PURE__ */ new Set();
105925
106370
  unavailable = /* @__PURE__ */ new Set();
@@ -105930,6 +106375,7 @@ var IsolatedAcpClient = class {
105930
106375
  configurations = /* @__PURE__ */ new Map();
105931
106376
  busy = /* @__PURE__ */ new Set();
105932
106377
  loading = /* @__PURE__ */ new Map();
106378
+ historyMetadata = /* @__PURE__ */ new Map();
105933
106379
  historyBusy = false;
105934
106380
  historyStop;
105935
106381
  prewarmedHistory;
@@ -105961,7 +106407,10 @@ var IsolatedAcpClient = class {
105961
106407
  }
105962
106408
  async create() {
105963
106409
  if (this.closed) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
105964
- if (this.all.size >= 31) throw new CursorAcpError("ACP_PROCESS_LIMIT", `Too many ${this.label} ACP sessions are active.`);
106410
+ while (this.all.size >= 31) {
106411
+ await (this.retiring.size > 0 ? Promise.race(this.retiring.values()) : this.evictIdleSession());
106412
+ if (this.closed) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
106413
+ }
105965
106414
  const client = this.factory();
105966
106415
  this.starting.add(client);
105967
106416
  this.all.add(client);
@@ -105976,6 +106425,44 @@ var IsolatedAcpClient = class {
105976
106425
  this.starting.delete(client);
105977
106426
  }
105978
106427
  }
106428
+ isSessionLoaded(id7) {
106429
+ return this.clients.has(id7);
106430
+ }
106431
+ sessionLoadToken(id7) {
106432
+ return this.clients.get(id7);
106433
+ }
106434
+ lastHistoryMetadata(id7) {
106435
+ return this.historyMetadata.get(id7);
106436
+ }
106437
+ invalidateHistoryMetadata(id7) {
106438
+ this.historyMetadata.delete(id7);
106439
+ }
106440
+ touchSession(id7, client) {
106441
+ if (this.clients.get(id7) !== client) return;
106442
+ this.clients.delete(id7);
106443
+ this.clients.set(id7, client);
106444
+ }
106445
+ evictIdleSession() {
106446
+ let victim;
106447
+ for (const entry of this.clients) {
106448
+ const [id8, client2] = entry;
106449
+ if (this.busy.has(id8) || this.loading.has(id8) || this.activeCalls.has(client2) || this.options.isSessionPinned?.(id8) || [...this.callbacks.values()].some((pending) => pending.client === client2)) continue;
106450
+ victim ??= entry;
106451
+ if (!this.options.hasOpenStream?.(id8)) {
106452
+ victim = entry;
106453
+ break;
106454
+ }
106455
+ }
106456
+ if (!victim) throw new CursorAcpError("ACP_PROCESS_LIMIT", `Too many ${this.label} ACP sessions are active.`);
106457
+ const [id7, client] = victim;
106458
+ this.clients.delete(id7);
106459
+ this.configurations.delete(id7);
106460
+ const closing = this.dispose(client).finally(() => {
106461
+ this.closingSessions.delete(id7);
106462
+ });
106463
+ this.closingSessions.set(id7, closing);
106464
+ return closing;
106465
+ }
105979
106466
  async call(method, params, timeoutMs) {
105980
106467
  const p = params;
105981
106468
  if (method === "session/load" && typeof p.sessionId === "string") {
@@ -105989,14 +106476,28 @@ var IsolatedAcpClient = class {
105989
106476
  this.loading.delete(p.sessionId);
105990
106477
  }
105991
106478
  }
105992
- return this.callOnce(method, params, timeoutMs);
106479
+ const client = typeof p.sessionId === "string" ? this.clients.get(p.sessionId) : void 0;
106480
+ if (!client) return this.callOnce(method, params, timeoutMs);
106481
+ this.activeCalls.set(client, (this.activeCalls.get(client) ?? 0) + 1);
106482
+ try {
106483
+ return await this.callOnce(method, params, timeoutMs);
106484
+ } finally {
106485
+ const remaining = (this.activeCalls.get(client) ?? 1) - 1;
106486
+ if (remaining) this.activeCalls.set(client, remaining);
106487
+ else this.activeCalls.delete(client);
106488
+ }
105993
106489
  }
105994
106490
  async callOnce(method, params, timeoutMs) {
105995
106491
  const p = params;
105996
106492
  if (method === "session/list") return this.catalog.call(method, params, timeoutMs);
105997
106493
  if (method === "session/new" || method === "session/load") {
105998
106494
  const known = typeof p.sessionId === "string" ? this.clients.get(p.sessionId) : void 0;
105999
- if (known) return { sessionId: p.sessionId };
106495
+ if (known) {
106496
+ this.touchSession(p.sessionId, known);
106497
+ return { sessionId: p.sessionId };
106498
+ }
106499
+ const closing = typeof p.sessionId === "string" ? this.closingSessions.get(p.sessionId) : void 0;
106500
+ if (closing) await closing;
106000
106501
  const client2 = await this.create();
106001
106502
  let boundId = typeof p.sessionId === "string" ? p.sessionId : void 0;
106002
106503
  const queued = [];
@@ -106016,7 +106517,8 @@ var IsolatedAcpClient = class {
106016
106517
  if (queued.length < 200) queued.push(message);
106017
106518
  return;
106018
106519
  }
106019
- if (incomingId !== boundId) return;
106520
+ if (incomingId !== boundId || this.clients.get(boundId) !== client2) return;
106521
+ if (message.method === "session/update") this.touchSession(boundId, client2);
106020
106522
  this.updateConfiguration(boundId, message);
106021
106523
  if (message.kind === "request") {
106022
106524
  const id8 = `${this.backend}-callback:${++this.nextCallback}`;
@@ -106038,20 +106540,8 @@ var IsolatedAcpClient = class {
106038
106540
  const id8 = method === "session/load" ? p.sessionId : result.sessionId;
106039
106541
  if (typeof id8 !== "string" || !/^[A-Za-z0-9_-]{1,240}$/.test(id8) || this.clients.has(id8) || this.closed || method === "session/load" && typeof result.sessionId === "string" && result.sessionId !== id8) throw new CursorAcpError("ACP_INVALID_SESSION", `${this.label} returned an invalid session.`);
106040
106542
  this.clients.set(id8, client2);
106041
- const config2 = { ...result };
106042
- if (config2.modes && Array.isArray(config2.modes.availableModes) && !config2.sessionModes) {
106043
- config2.sessionModes = { ...config2.modes };
106044
- }
106045
- this.updateConfiguration(id8, { kind: "notification", method: "session/update", params: {
106046
- update: { sessionUpdate: "config_option_update", configOptions: config2.configOptions }
106047
- } }, config2);
106048
- for (const key of ["models", "modes", "sessionModes"]) {
106049
- if (replayConfiguration[key]) config2[key] = { ...config2[key], ...replayConfiguration[key] };
106050
- }
106051
- if (typeof replayConfiguration.sessionModeConfigId === "string") {
106052
- config2.sessionModeConfigId = replayConfiguration.sessionModeConfigId;
106053
- }
106054
- this.configurations.set(id8, config2);
106543
+ this.historyMetadata.delete(id8);
106544
+ this.configurations.set(id8, this.sessionConfiguration(id8, result, replayConfiguration));
106055
106545
  boundId = id8;
106056
106546
  replaying = false;
106057
106547
  for (const message of queued) receive(message);
@@ -106064,6 +106554,7 @@ var IsolatedAcpClient = class {
106064
106554
  const client = this.clients.get(String(p.sessionId));
106065
106555
  if (!client) throw new CursorAcpError("ACP_SESSION_NOT_LOADED", `Load the ${this.label} session before using it.`);
106066
106556
  const id7 = String(p.sessionId);
106557
+ this.touchSession(id7, client);
106067
106558
  if (method === "dsh/sessionCommands") return client.call(method, params, timeoutMs);
106068
106559
  if (method === "dsh/sessionModes" || method === "session/set_mode") {
106069
106560
  if (this.backend === "cursor") return client.call(method, params, timeoutMs);
@@ -106095,7 +106586,7 @@ var IsolatedAcpClient = class {
106095
106586
  }
106096
106587
  }
106097
106588
  if (this.backend === "cursor" && (method === "dsh/sessionModels" || method === "dsh/selectModel")) return client.call(method, params, timeoutMs);
106098
- if (method === "dsh/sessionModels") return this.models(id7);
106589
+ if (method === "dsh/sessionModels") return this.models(this.configurations.get(id7));
106099
106590
  if (method === "dsh/selectModel") {
106100
106591
  if (this.busy.has(id7)) throw new CursorAcpError("PROMPT_IN_PROGRESS", `Stop the ${this.label} reply before changing its model.`);
106101
106592
  const config2 = this.configurations.get(id7);
@@ -106115,7 +106606,7 @@ var IsolatedAcpClient = class {
106115
106606
  this.updateConfiguration(id7, { kind: "notification", method: "session/update", params: { update: { sessionUpdate: "config_option_update", configOptions: thinkingResult.configOptions } } });
106116
106607
  if (this.configurations.get(id7)?.modes?.currentModeId !== p.reasoningEffort) throw new CursorAcpError("ACP_MODEL_NOT_CONFIRMED", `${this.label} did not confirm the thinking change.`);
106117
106608
  }
106118
- return { selected: this.models(id7).current };
106609
+ return { selected: this.models(this.configurations.get(id7)).current };
106119
106610
  } finally {
106120
106611
  this.busy.delete(id7);
106121
106612
  }
@@ -106131,6 +106622,22 @@ var IsolatedAcpClient = class {
106131
106622
  }
106132
106623
  return client.call(method, params, timeoutMs);
106133
106624
  }
106625
+ sessionConfiguration(id7, result, replayConfiguration) {
106626
+ const config2 = { ...result };
106627
+ if (config2.modes && Array.isArray(config2.modes.availableModes) && !config2.sessionModes) {
106628
+ config2.sessionModes = { ...config2.modes };
106629
+ }
106630
+ this.updateConfiguration(id7, { kind: "notification", method: "session/update", params: {
106631
+ update: { sessionUpdate: "config_option_update", configOptions: config2.configOptions }
106632
+ } }, config2);
106633
+ for (const key of ["models", "modes", "sessionModes"]) {
106634
+ if (replayConfiguration[key]) config2[key] = { ...config2[key], ...replayConfiguration[key] };
106635
+ }
106636
+ if (typeof replayConfiguration.sessionModeConfigId === "string") {
106637
+ config2.sessionModeConfigId = replayConfiguration.sessionModeConfigId;
106638
+ }
106639
+ return config2;
106640
+ }
106134
106641
  updateConfiguration(id7, message, initial) {
106135
106642
  if (message.method !== "session/update") return;
106136
106643
  const update = message.params.update;
@@ -106166,8 +106673,7 @@ var IsolatedAcpClient = class {
106166
106673
  }
106167
106674
  }
106168
106675
  }
106169
- models(id7) {
106170
- const config2 = this.configurations.get(id7);
106676
+ models(config2) {
106171
106677
  const modes = config2?.modes;
106172
106678
  return {
106173
106679
  current: { provider: "pi", model: config2?.models?.currentModelId ?? "", reasoningEffort: modes?.currentModeId },
@@ -106182,7 +106688,11 @@ var IsolatedAcpClient = class {
106182
106688
  }
106183
106689
  /** Keeps at most one warm idle history reader outside `this.all` so the 30-session pool is unaffected. */
106184
106690
  prewarmHistory() {
106185
- if (this.closed || !this.isReady() || this.prewarmedHistory !== void 0 || this.retiringHistoryStops.size >= 2) return;
106691
+ if (this.closed || !this.isReady() || this.historyBusy || this.prewarmedHistory !== void 0) return;
106692
+ if (this.retiringHistoryStops.size > 0) {
106693
+ void Promise.all(this.retiringHistoryStops).then(() => this.prewarmHistory());
106694
+ return;
106695
+ }
106186
106696
  const client = this.factory();
106187
106697
  const timer2 = setTimeout(() => {
106188
106698
  if (this.prewarmedHistory === entry) this.discardPrewarmedHistory();
@@ -106250,7 +106760,7 @@ var IsolatedAcpClient = class {
106250
106760
  let rawCount = 0;
106251
106761
  let overflow = false;
106252
106762
  try {
106253
- while (this.retiringHistoryStops.size >= 2) {
106763
+ while (this.retiringHistoryStops.size > 0) {
106254
106764
  await Promise.race(this.retiringHistoryStops);
106255
106765
  signal?.throwIfAborted();
106256
106766
  if (this.closed) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
@@ -106264,8 +106774,10 @@ var IsolatedAcpClient = class {
106264
106774
  if (ok4 && !claimed.unavailable && claimed.client.isReady()) {
106265
106775
  client = claimed.client;
106266
106776
  } else {
106267
- this.retireHistoryStop(currentStop);
106777
+ await currentStop();
106268
106778
  currentStop = void 0;
106779
+ signal?.throwIfAborted();
106780
+ if (this.closed) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
106269
106781
  }
106270
106782
  }
106271
106783
  if (!client) {
@@ -106278,6 +106790,7 @@ var IsolatedAcpClient = class {
106278
106790
  }
106279
106791
  const reader = client;
106280
106792
  const stopReader = currentStop;
106793
+ const replayConfiguration = {};
106281
106794
  unsubscribe = reader.onInbound((message) => {
106282
106795
  if (message.kind === "request") {
106283
106796
  void reader.respondError(message.id, -32601, "History reader does not support requests.").catch(() => void 0);
@@ -106289,6 +106802,8 @@ var IsolatedAcpClient = class {
106289
106802
  if (rawBytes > ACP_HISTORY_MAX_RAW_BYTES || rawCount > ACP_HISTORY_MAX_RAW_UPDATES || !accumulator.push(message)) {
106290
106803
  overflow = true;
106291
106804
  void stopReader().catch(() => void 0);
106805
+ } else if (this.backend === "pi") {
106806
+ this.updateConfiguration(sessionId, message, replayConfiguration);
106292
106807
  }
106293
106808
  });
106294
106809
  const result = await reader.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
@@ -106304,6 +106819,26 @@ var IsolatedAcpClient = class {
106304
106819
  retainedEvents: folded.events.length
106305
106820
  });
106306
106821
  }
106822
+ const params = { sessionId };
106823
+ const piConfig = this.backend === "pi" ? this.sessionConfiguration(sessionId, result, replayConfiguration) : void 0;
106824
+ const [models, modes, commands] = await Promise.all([
106825
+ piConfig ? piConfig.models ? this.models(piConfig) : void 0 : reader.call("dsh/sessionModels", params).catch(() => void 0),
106826
+ piConfig ? piConfig.sessionModes : reader.call("dsh/sessionModes", params).catch(() => void 0),
106827
+ reader.call("dsh/sessionCommands", params).catch(() => void 0)
106828
+ ]);
106829
+ signal?.throwIfAborted();
106830
+ if (!this.closed) {
106831
+ this.historyMetadata.delete(sessionId);
106832
+ this.historyMetadata.set(sessionId, {
106833
+ ...models && typeof models === "object" ? { models } : {},
106834
+ ...Array.isArray(modes?.availableModes) ? { modes } : {},
106835
+ ...Array.isArray(commands?.commands) ? { commands: commands.commands } : {}
106836
+ });
106837
+ if (this.historyMetadata.size > 64) {
106838
+ const oldest = this.historyMetadata.keys().next().value;
106839
+ if (oldest !== void 0) this.historyMetadata.delete(oldest);
106840
+ }
106841
+ }
106307
106842
  return folded.events;
106308
106843
  } catch (error62) {
106309
106844
  signal?.throwIfAborted();
@@ -106344,10 +106879,17 @@ var IsolatedAcpClient = class {
106344
106879
  this.unavailable.add(handler);
106345
106880
  return () => this.unavailable.delete(handler);
106346
106881
  }
106347
- async dispose(client) {
106348
- await client.close();
106349
- this.all.delete(client);
106350
- for (const [key, pending] of this.callbacks) if (pending.client === client) this.callbacks.delete(key);
106882
+ dispose(client) {
106883
+ const pending = this.retiring.get(client);
106884
+ if (pending) return pending;
106885
+ const closing = Promise.resolve().then(() => client.close()).then(() => {
106886
+ this.all.delete(client);
106887
+ for (const [key, pending2] of this.callbacks) if (pending2.client === client) this.callbacks.delete(key);
106888
+ }).finally(() => {
106889
+ this.retiring.delete(client);
106890
+ });
106891
+ this.retiring.set(client, closing);
106892
+ return closing;
106351
106893
  }
106352
106894
  async close() {
106353
106895
  this.closed = true;
@@ -106359,13 +106901,15 @@ var IsolatedAcpClient = class {
106359
106901
  ...this.retiringHistoryStops
106360
106902
  ]);
106361
106903
  this.clients.clear();
106904
+ this.configurations.clear();
106905
+ this.historyMetadata.clear();
106362
106906
  this.all.clear();
106363
106907
  this.callbacks.clear();
106364
106908
  }
106365
106909
  };
106366
106910
 
106367
106911
  // packages/plugin/src/workspace-bridge.ts
106368
- import { realpath as realpath4, lstat as lstat6, readdir as readdir4, open as open6, stat as stat5, watch } from "node:fs/promises";
106912
+ import { realpath as realpath5, lstat as lstat6, readdir as readdir4, open as open6, stat as stat5, watch } from "node:fs/promises";
106369
106913
  import { isAbsolute as isAbsolute6, join as join10, parse as parse4, relative as relative3, resolve as resolve6, sep as sep3 } from "node:path";
106370
106914
 
106371
106915
  // packages/plugin/src/remote-terminal-controller.ts
@@ -107151,8 +107695,21 @@ var WorkspaceBridge = class {
107151
107695
  };
107152
107696
  }
107153
107697
  const text = bytes.toString("utf8");
107698
+ if (endpoint === "workspaceFiles/read") {
107699
+ const lineOffset = Math.max(1, offset2);
107700
+ let pageStart = 0;
107701
+ let pageEnd = 0;
107702
+ let lines = 0;
107703
+ for (let line = 1; pageEnd < text.length && lines < limit; line++) {
107704
+ const newline = text.indexOf("\n", pageEnd);
107705
+ pageEnd = newline === -1 ? text.length : newline + 1;
107706
+ if (line < lineOffset) pageStart = pageEnd;
107707
+ else lines++;
107708
+ }
107709
+ return { ok: true, value: { absolutePath, version: version3, text: text.slice(pageStart, pageEnd), offset: lineOffset, lines, eof: pageEnd === text.length } };
107710
+ }
107154
107711
  const slice = text.slice(offset2, offset2 + limit);
107155
- return { ok: true, value: { absolutePath: target3, version: `${info.mtimeMs}:${info.size}`, text: slice, offset: offset2, lines: slice.split("\n").length, eof: offset2 + slice.length >= text.length } };
107712
+ return { ok: true, value: { absolutePath, version: version3, text: slice, offset: offset2, lines: slice.split("\n").length, eof: offset2 + slice.length >= text.length } };
107156
107713
  } catch (error62) {
107157
107714
  if (error62 instanceof RpcError) throw error62;
107158
107715
  const reason = error62?.code === "ENOENT" ? "not-found" : "io";
@@ -107190,7 +107747,7 @@ var WorkspaceBridge = class {
107190
107747
  const cwd2 = await this.resolveCwd(parsed.nativeId, signal);
107191
107748
  if (!cwd2) throw this.scopeError("WORKSPACE_UNAVAILABLE", "The CodeX thread has no available workspace.", { reason: "authority-unavailable" });
107192
107749
  try {
107193
- const root2 = await realpath4(cwd2);
107750
+ const root2 = await realpath5(cwd2);
107194
107751
  const info = await stat5(root2);
107195
107752
  if (!info.isDirectory()) throw this.scopeError("WORKSPACE_UNAVAILABLE", "The CodeX workspace is unavailable.", { reason: "root-invalid" });
107196
107753
  return root2;
@@ -107234,7 +107791,7 @@ var WorkspaceBridge = class {
107234
107791
  if (info.isSymbolicLink()) {
107235
107792
  throw this.scopeError("WORKSPACE_PATH_DENIED", "The requested workspace path is not a regular file.", { reason: "symlink" });
107236
107793
  }
107237
- const canonical = await realpath4(candidate);
107794
+ const canonical = await realpath5(candidate);
107238
107795
  if (process.platform === "win32") {
107239
107796
  const rootDrive = parse4(root2).root.toLowerCase();
107240
107797
  const canonicalDrive = parse4(canonical).root.toLowerCase();
@@ -107432,7 +107989,7 @@ var AcpWorkspaceTools = class {
107432
107989
 
107433
107990
  // packages/plugin/src/acp/gateway.ts
107434
107991
  import { randomUUID as randomUUID16 } from "node:crypto";
107435
- import { readdir as readdir5, realpath as realpath7, stat as stat6 } from "node:fs/promises";
107992
+ import { readdir as readdir5, realpath as realpath8, stat as stat6 } from "node:fs/promises";
107436
107993
  import { homedir as homedir6 } from "node:os";
107437
107994
  import { basename as basename8, isAbsolute as isAbsolute8, join as join15, relative as relative5, resolve as resolve8 } from "node:path";
107438
107995
 
@@ -107443,25 +108000,10 @@ var MAX_LOAD_TOMBSTONE_TTL_MS = 5 * 6e4;
107443
108000
  var MAX_LOAD_TOMBSTONES = 256;
107444
108001
  var MAX_HISTORY_METADATA = 64;
107445
108002
  var ClaudeAcpClient = class extends CursorAcpClient {
107446
- live = /* @__PURE__ */ new Map();
107447
- loads = /* @__PURE__ */ new Map();
107448
- claudeInboundHandlers = /* @__PURE__ */ new Set();
107449
- loadSuppressions = /* @__PURE__ */ new Map();
107450
- liveHistoryCollectors = /* @__PURE__ */ new Map();
107451
- loadGen = 0;
107452
- pendingNew = 0;
107453
- awaitHistoryCloseOnReturn = false;
107454
- historyStop;
107455
- historyReading = false;
107456
- shuttingDown = false;
107457
- prewarmedHistory;
107458
- retiringHistoryStops = /* @__PURE__ */ new Set();
107459
- historyMetadata = /* @__PURE__ */ new Map();
107460
- makeClient;
107461
- historyLogger;
107462
- constructor(binary = "claude-agent-acp", logger2, spawnAcp, options = {}, backend = "claude") {
107463
- const config2 = { ...options, args: options.args ?? [], authenticationMethod: null, modelBackend: backend, backend };
108003
+ constructor(binary = "claude-agent-acp", logger2, spawnAcp, retention = {}, backend = "claude") {
108004
+ const config2 = { args: retention.args ?? [], cwd: retention.cwd, authenticationMethod: null, modelBackend: backend, backend };
107464
108005
  super(binary, logger2, spawnAcp, config2);
108006
+ this.retention = retention;
107465
108007
  this.historyLogger = logger2;
107466
108008
  this.makeClient = () => new CursorAcpClient(binary, logger2, spawnAcp, config2);
107467
108009
  this.modelLabel = backend;
@@ -107473,7 +108015,7 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107473
108015
  });
107474
108016
  super.onInbound((message) => {
107475
108017
  const id7 = isRecord19(message.params) && typeof message.params.sessionId === "string" ? message.params.sessionId : void 0;
107476
- if (id7 && this.loadSuppressions.has(id7)) {
108018
+ if (id7 && (this.loadSuppressions.has(id7) || this.closingSessions.has(id7))) {
107477
108019
  if (message.kind === "request") {
107478
108020
  void (message.method === "session/request_permission" ? this.respond(message.id, { outcome: { outcome: "cancelled" } }) : this.respondError(message.id, -32600, `${this.label} session is not loaded.`)).catch(() => void 0);
107479
108021
  } else if (message.kind === "notification" && message.method === "session/update") {
@@ -107481,9 +108023,27 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107481
108023
  }
107482
108024
  return;
107483
108025
  }
108026
+ if (id7 && message.method === "session/update") this.touchLive(id7);
107484
108027
  for (const handler of this.claudeInboundHandlers) handler(message);
107485
108028
  });
107486
108029
  }
108030
+ live = /* @__PURE__ */ new Map();
108031
+ closingSessions = /* @__PURE__ */ new Map();
108032
+ loads = /* @__PURE__ */ new Map();
108033
+ claudeInboundHandlers = /* @__PURE__ */ new Set();
108034
+ loadSuppressions = /* @__PURE__ */ new Map();
108035
+ liveHistoryCollectors = /* @__PURE__ */ new Map();
108036
+ loadGen = 0;
108037
+ pendingNew = 0;
108038
+ awaitHistoryCloseOnReturn = false;
108039
+ historyStop;
108040
+ historyReading = false;
108041
+ shuttingDown = false;
108042
+ prewarmedHistory;
108043
+ retiringHistoryStops = /* @__PURE__ */ new Set();
108044
+ historyMetadata = /* @__PURE__ */ new Map();
108045
+ makeClient;
108046
+ historyLogger;
107487
108047
  /** History events and model catalogs are labelled with the backend that produced them. */
107488
108048
  modelLabel;
107489
108049
  get label() {
@@ -107499,17 +108059,23 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107499
108059
  if (method === "session/load" && typeof id7 === "string") {
107500
108060
  if (this.live.has(id7)) {
107501
108061
  if (!this.liveHistoryCollectors.has(id7)) this.clearLoadSuppression(id7);
107502
- return this.live.get(id7);
108062
+ return this.touchLive(id7);
107503
108063
  }
107504
108064
  const pending = this.loads.get(id7);
107505
108065
  if (pending) return pending;
107506
- this.checkSessionLimit();
108066
+ const closing = this.closingSessions.get(id7);
108067
+ const eviction = this.reserveLiveSlot();
108068
+ const budget = timeoutMs ?? ACP_HISTORY_LOAD_TIMEOUT_MS;
107507
108069
  const gen = this.beginLoadSuppression(id7);
107508
108070
  let responded = false;
107509
- const load = Promise.resolve().then(() => super.call(method, params, timeoutMs)).then((result) => {
108071
+ const load = Promise.all([closing, eviction]).then(() => {
108072
+ if (this.shuttingDown) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
108073
+ return super.call(method, params, budget);
108074
+ }).then((result) => {
107510
108075
  responded = true;
107511
108076
  this.assertLoaded(result, id7);
107512
- this.live.set(id7, result);
108077
+ this.loads.delete(id7);
108078
+ this.rememberLive(id7, result);
107513
108079
  this.historyMetadata.delete(id7);
107514
108080
  this.clearLoadSuppression(id7, gen);
107515
108081
  return result;
@@ -107521,21 +108087,23 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107521
108087
  if (responded || this.shuttingDown || !this.isReady()) {
107522
108088
  this.clearLoadSuppression(id7, gen);
107523
108089
  } else {
107524
- this.armLoadTombstone(id7, gen, timeoutMs);
108090
+ this.armLoadTombstone(id7, gen, budget);
107525
108091
  }
107526
108092
  throw error62;
107527
108093
  } finally {
107528
- this.loads.delete(id7);
108094
+ if (this.loads.get(id7) === load) this.loads.delete(id7);
107529
108095
  }
107530
108096
  }
107531
108097
  if (method === "session/new" || method === "session/fork") {
107532
- this.checkSessionLimit();
108098
+ const eviction = this.reserveLiveSlot(id7);
107533
108099
  this.pendingNew++;
107534
108100
  try {
108101
+ if (eviction) await eviction;
108102
+ if (this.shuttingDown) throw new CursorAcpError("ACP_CLOSED", `${this.label} ACP is closed.`);
107535
108103
  const result = await super.call(method, params, timeoutMs);
107536
108104
  const newId = result?.sessionId;
107537
108105
  if (typeof newId !== "string" || this.shuttingDown) throw new CursorAcpError("ACP_INVALID_SESSION", `${this.label} returned an invalid session.`);
107538
- this.live.set(newId, result);
108106
+ this.rememberLive(newId, result);
107539
108107
  this.historyMetadata.delete(newId);
107540
108108
  this.clearLoadSuppression(newId);
107541
108109
  return result;
@@ -107543,6 +108111,15 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107543
108111
  this.pendingNew--;
107544
108112
  }
107545
108113
  }
108114
+ if (typeof id7 === "string") this.touchLive(id7);
108115
+ if (method === "session/delete" && typeof id7 === "string") {
108116
+ const result = await super.call(method, params, timeoutMs);
108117
+ this.live.delete(id7);
108118
+ this.historyMetadata.delete(id7);
108119
+ this.evictSessionState(id7);
108120
+ this.onSessionReleased(id7);
108121
+ return result;
108122
+ }
107546
108123
  if (method === "session/prompt" && typeof id7 === "string" && !this.liveHistoryCollectors.has(id7)) {
107547
108124
  this.clearLoadSuppression(id7);
107548
108125
  }
@@ -107600,8 +108177,50 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107600
108177
  }
107601
108178
  this.loadSuppressions.clear();
107602
108179
  }
107603
- checkSessionLimit() {
107604
- if (this.live.size + this.loads.size + this.pendingNew >= 30) throw new CursorAcpError("ACP_PROCESS_LIMIT", `Too many ${this.label} sessions are active.`);
108180
+ touchLive(id7) {
108181
+ const entry = this.live.get(id7);
108182
+ if (entry) {
108183
+ this.live.delete(id7);
108184
+ this.live.set(id7, entry);
108185
+ }
108186
+ return entry?.result;
108187
+ }
108188
+ rememberLive(id7, result) {
108189
+ this.live.delete(id7);
108190
+ this.live.set(id7, { result });
108191
+ this.onSessionLoaded(id7);
108192
+ }
108193
+ onSessionLoaded(_id) {
108194
+ }
108195
+ onSessionReleased(_id) {
108196
+ }
108197
+ pendingSessionClose(id7) {
108198
+ return this.closingSessions.get(id7);
108199
+ }
108200
+ reserveLiveSlot(exclude) {
108201
+ if (this.live.size + this.loads.size + this.pendingNew < 30) return;
108202
+ let victim;
108203
+ for (const id7 of this.live.keys()) {
108204
+ if (id7 === exclude || this.isSessionBusy(id7) || this.loads.has(id7) || this.liveHistoryCollectors.has(id7) || this.retention.isSessionPinned?.(id7)) continue;
108205
+ victim ??= id7;
108206
+ if (!this.retention.hasOpenStream?.(id7)) {
108207
+ victim = id7;
108208
+ break;
108209
+ }
108210
+ }
108211
+ if (victim === void 0) throw new CursorAcpError("ACP_PROCESS_LIMIT", `Too many ${this.label} sessions are active.`);
108212
+ return this.evictLive(victim);
108213
+ }
108214
+ evictLive(id7) {
108215
+ this.live.delete(id7);
108216
+ this.rememberHistoryMetadata(id7, this.sessionMetadata(id7));
108217
+ this.evictSessionState(id7);
108218
+ if (this.capabilities().sessionCapabilities?.close !== true) return;
108219
+ const closing = super.call("session/close", { sessionId: id7 }, 5e3).then(() => this.onSessionReleased(id7), () => void 0).finally(() => {
108220
+ this.closingSessions.delete(id7);
108221
+ });
108222
+ this.closingSessions.set(id7, closing);
108223
+ return closing;
107605
108224
  }
107606
108225
  assertLoaded(result, sessionId) {
107607
108226
  const id7 = result?.sessionId;
@@ -107611,6 +108230,9 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107611
108230
  isSessionLoaded(sessionId) {
107612
108231
  return this.live.has(sessionId);
107613
108232
  }
108233
+ sessionLoadToken(sessionId) {
108234
+ return this.live.get(sessionId);
108235
+ }
107614
108236
  pendingSessionLoad(sessionId) {
107615
108237
  return this.loads.get(sessionId);
107616
108238
  }
@@ -107654,7 +108276,12 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107654
108276
  const result = await super.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
107655
108277
  responded = true;
107656
108278
  this.assertLoaded(result, sessionId);
107657
- this.live.set(sessionId, result);
108279
+ const entry = this.live.get(sessionId);
108280
+ if (entry) {
108281
+ entry.result = result;
108282
+ this.touchLive(sessionId);
108283
+ }
108284
+ this.onSessionLoaded(sessionId);
107658
108285
  this.clearLoadSuppression(sessionId, gen);
107659
108286
  signal?.throwIfAborted();
107660
108287
  if (overflow) throw new CursorAcpError("ACP_HISTORY_TOO_LARGE", `${this.label} history exceeds the transfer limit.`);
@@ -107678,6 +108305,7 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107678
108305
  throw error62;
107679
108306
  } finally {
107680
108307
  this.liveHistoryCollectors.delete(sessionId);
108308
+ if (!this.live.has(sessionId)) this.evictSessionState(sessionId);
107681
108309
  this.historyReading = false;
107682
108310
  }
107683
108311
  }
@@ -107691,18 +108319,15 @@ var ClaudeAcpClient = class extends CursorAcpClient {
107691
108319
  const models = isRecord19(modelsRaw) ? modelsRaw : void 0;
107692
108320
  const modes = isRecord19(modesRaw) && Array.isArray(modesRaw.availableModes) ? modesRaw : void 0;
107693
108321
  const commands = isRecord19(commandsRaw) && Array.isArray(commandsRaw.commands) && commandsRaw.commands.length > 0 ? commandsRaw.commands : void 0;
107694
- if (models !== void 0 || modes !== void 0 || commands !== void 0) {
107695
- this.historyMetadata.delete(sessionId);
107696
- this.historyMetadata.set(sessionId, {
107697
- ...models !== void 0 ? { models } : {},
107698
- ...modes !== void 0 ? { modes } : {},
107699
- ...commands !== void 0 ? { commands } : {}
107700
- });
107701
- while (this.historyMetadata.size > MAX_HISTORY_METADATA) {
107702
- const oldest = this.historyMetadata.keys().next().value;
107703
- if (oldest === void 0) break;
107704
- this.historyMetadata.delete(oldest);
107705
- }
108322
+ this.rememberHistoryMetadata(sessionId, { models, modes, commands });
108323
+ }
108324
+ rememberHistoryMetadata(id7, metadata) {
108325
+ if (metadata.models === void 0 && metadata.modes === void 0 && metadata.commands === void 0) return;
108326
+ this.historyMetadata.delete(id7);
108327
+ this.historyMetadata.set(id7, metadata);
108328
+ if (this.historyMetadata.size > MAX_HISTORY_METADATA) {
108329
+ const oldest = this.historyMetadata.keys().next().value;
108330
+ if (oldest !== void 0) this.historyMetadata.delete(oldest);
107706
108331
  }
107707
108332
  }
107708
108333
  /** Keeps at most one warm idle history reader ready for the next `history()` call. */
@@ -107890,6 +108515,7 @@ var TURN_RESET_UPDATES = /* @__PURE__ */ new Set([
107890
108515
  ]);
107891
108516
  var KimiAcpClient = class extends ClaudeAcpClient {
107892
108517
  awaitHistoryCloseOnReturn = true;
108518
+ processLockedSessions = /* @__PURE__ */ new Set();
107893
108519
  activePromptCounts = /* @__PURE__ */ new Map();
107894
108520
  liveHistoryPromises = /* @__PURE__ */ new Map();
107895
108521
  unloadedHistoryPromises = /* @__PURE__ */ new Map();
@@ -107897,6 +108523,7 @@ var KimiAcpClient = class extends ClaudeAcpClient {
107897
108523
  constructor(binary = KIMI_ACP_COMMAND, logger2, spawnAcp, options = {}) {
107898
108524
  super(binary, logger2, spawnAcp, { ...options, args: options.args ?? [...KIMI_ACP_ARGS] }, "kimi");
107899
108525
  super.onUnavailable(() => {
108526
+ this.processLockedSessions.clear();
107900
108527
  this.activePromptCounts.clear();
107901
108528
  this.lastKnownHistory.clear();
107902
108529
  });
@@ -107917,8 +108544,8 @@ var KimiAcpClient = class extends ClaudeAcpClient {
107917
108544
  }
107918
108545
  }
107919
108546
  if (method === "session/load" && id7 !== void 0) {
107920
- while (this.unloadedHistoryPromises.has(id7)) {
107921
- await this.unloadedHistoryPromises.get(id7)?.catch(() => void 0);
108547
+ while (this.liveHistoryPromises.has(id7) || this.unloadedHistoryPromises.has(id7)) {
108548
+ await (this.liveHistoryPromises.get(id7) ?? this.unloadedHistoryPromises.get(id7))?.catch(() => void 0);
107922
108549
  }
107923
108550
  return super.call(method, params, timeoutMs);
107924
108551
  }
@@ -107949,7 +108576,12 @@ var KimiAcpClient = class extends ClaudeAcpClient {
107949
108576
  if (inFlightLive) {
107950
108577
  return [...await raceAbortSignal(inFlightLive, signal)];
107951
108578
  }
107952
- if (this.isSessionLoaded(sessionId)) {
108579
+ const closing = this.pendingSessionClose(sessionId);
108580
+ if (closing) {
108581
+ await raceAbortSignal(closing, signal);
108582
+ continue;
108583
+ }
108584
+ if (this.isSessionLoaded(sessionId) || this.processLockedSessions.has(sessionId)) {
107953
108585
  const read2 = this.startHistoryRead(
107954
108586
  this.liveHistoryPromises,
107955
108587
  sessionId,
@@ -107969,7 +108601,14 @@ var KimiAcpClient = class extends ClaudeAcpClient {
107969
108601
  return [...await raceAbortSignal(read, signal)];
107970
108602
  }
107971
108603
  }
108604
+ onSessionLoaded(id7) {
108605
+ this.processLockedSessions.add(id7);
108606
+ }
108607
+ onSessionReleased(id7) {
108608
+ this.processLockedSessions.delete(id7);
108609
+ }
107972
108610
  async close() {
108611
+ this.processLockedSessions.clear();
107973
108612
  this.activePromptCounts.clear();
107974
108613
  this.lastKnownHistory.clear();
107975
108614
  await super.close();
@@ -109151,12 +109790,12 @@ var AntigravityNativeAcpClient = class extends ClaudeAcpClient {
109151
109790
 
109152
109791
  // packages/plugin/src/acp/adapters/opencode-process.ts
109153
109792
  import { Buffer as Buffer10 } from "node:buffer";
109154
- import { realpath as realpath6 } from "node:fs/promises";
109793
+ import { realpath as realpath7 } from "node:fs/promises";
109155
109794
 
109156
109795
  // packages/plugin/src/acp/adapters/opencode-native-api.ts
109157
109796
  import { randomBytes as randomBytes13 } from "node:crypto";
109158
109797
  import { createServer as createServer3 } from "node:net";
109159
- import { realpath as realpath5 } from "node:fs/promises";
109798
+ import { realpath as realpath6 } from "node:fs/promises";
109160
109799
  import { stripVTControlCharacters } from "node:util";
109161
109800
  var MAX_RESPONSE_BYTES = 64 * 1024;
109162
109801
  var MAX_LIST_RESPONSE_BYTES = 4 * 1024 * 1024;
@@ -109208,7 +109847,7 @@ var OpencodeNativeApi = class {
109208
109847
  if (archived.has(row.id) || typeof row.directory !== "string" || !isNativeRecord(row.time)) throw unavailable();
109209
109848
  let path = paths.get(row.directory);
109210
109849
  if (!path) {
109211
- path = realpath5(row.directory);
109850
+ path = realpath6(row.directory);
109212
109851
  paths.set(row.directory, path);
109213
109852
  }
109214
109853
  if (await path !== cwd2) throw unavailable();
@@ -109239,7 +109878,7 @@ var OpencodeNativeApi = class {
109239
109878
  MAX_RESPONSE_BYTES,
109240
109879
  method === "PATCH" ? JSON.stringify({ time: { archived: Date.now() } }) : void 0
109241
109880
  );
109242
- if (!isNativeRecord(result) || result.id !== sessionId || typeof result.directory !== "string" || !isNativeRecord(result.time) || await realpath5(result.directory) !== cwd2) throw unavailable();
109881
+ if (!isNativeRecord(result) || result.id !== sessionId || typeof result.directory !== "string" || !isNativeRecord(result.time) || await realpath6(result.directory) !== cwd2) throw unavailable();
109243
109882
  return result;
109244
109883
  } catch {
109245
109884
  throw unavailable();
@@ -109643,7 +110282,7 @@ var OpencodeAcpClient = class _OpencodeAcpClient {
109643
110282
  const resolveCwd = (rawCwd) => {
109644
110283
  let cached2 = realpathCache.get(rawCwd);
109645
110284
  if (!cached2) {
109646
- cached2 = realpath6(rawCwd).catch(() => void 0);
110285
+ cached2 = realpath7(rawCwd).catch(() => void 0);
109647
110286
  realpathCache.set(rawCwd, cached2);
109648
110287
  }
109649
110288
  return cached2;
@@ -111133,6 +111772,7 @@ function isRecord24(value) {
111133
111772
  }
111134
111773
 
111135
111774
  // packages/plugin/src/acp/gateway.ts
111775
+ var PINNED_SESSION_METHODS = /* @__PURE__ */ new Set(["dsh/sessionModels", "dsh/sessionModes", "dsh/selectModel", "session/set_mode", "session/fork", "dsh/selectPermission"]);
111136
111776
  var APPROVAL_TTL_MS2 = 5 * 6e4;
111137
111777
  var MAX_SESSION_TITLE_ENTRIES = 256;
111138
111778
  var DETACHED_ACP_APPROVAL_METHODS = /* @__PURE__ */ new Set([
@@ -111169,23 +111809,29 @@ var AcpRemoteGateway = class {
111169
111809
  this.detachedApprovalGraceMs = clampDetachedApprovalGraceSec(detachedApprovalGraceSec) * 1e3;
111170
111810
  this.customCreateAcp = createAcp !== void 0;
111171
111811
  this.createAcp = createAcp ?? ((binary, targetLogger, backend) => {
111812
+ const options = {
111813
+ args: backend.args,
111814
+ cwd: backend.cwd,
111815
+ isSessionPinned: (id7) => this.promptsInProgress.get(id7)?.backend === backend.id || this.sessionOperations.has(`${backend.id}:${id7}`) || [...this.approvals.values()].some((approval) => approval.backend === backend.id && approval.sessionId === id7),
111816
+ hasOpenStream: (id7) => [...this.peers.values()].some((peer) => peer.hasStreamFor(id7))
111817
+ };
111172
111818
  if (backend.id === "antigravity") {
111173
111819
  if (isLegacyAntigravityStreamJsonArgs(backend.args)) {
111174
111820
  return new AntigravityAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111175
111821
  }
111176
- return new AntigravityNativeAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111822
+ return new AntigravityNativeAcpClient(binary, targetLogger, void 0, options);
111177
111823
  }
111178
- if (backend.id === "claude") return new ClaudeAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111179
- if (backend.id === "hermes") return new HermesAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111180
- if (backend.id === "kimi") return new KimiAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111181
- if (backend.id === "pi") return new PiAcpClient(binary, targetLogger, { args: backend.args, cwd: backend.cwd });
111824
+ if (backend.id === "claude") return new ClaudeAcpClient(binary, targetLogger, void 0, options);
111825
+ if (backend.id === "hermes") return new HermesAcpClient(binary, targetLogger, void 0, options);
111826
+ if (backend.id === "kimi") return new KimiAcpClient(binary, targetLogger, void 0, options);
111827
+ if (backend.id === "pi") return new PiAcpClient(binary, targetLogger, options);
111182
111828
  if (backend.id === "opencode") {
111183
111829
  return new OpencodeAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd });
111184
111830
  }
111185
111831
  if (backend.id === "cursor") {
111186
- return new IsolatedAcpClient(binary, targetLogger, { args: backend.args, cwd: backend.cwd, backend: "cursor" });
111832
+ return new IsolatedAcpClient(binary, targetLogger, { ...options, backend: "cursor" });
111187
111833
  }
111188
- return new ClaudeAcpClient(binary, targetLogger, void 0, { args: backend.args, cwd: backend.cwd }, backend.id);
111834
+ return new ClaudeAcpClient(binary, targetLogger, void 0, options, backend.id);
111189
111835
  });
111190
111836
  }
111191
111837
  backendInstances = /* @__PURE__ */ new Map();
@@ -111197,6 +111843,8 @@ var AcpRemoteGateway = class {
111197
111843
  sessionOwners = /* @__PURE__ */ new Map();
111198
111844
  sessionBackends = /* @__PURE__ */ new Map();
111199
111845
  sessionPermissions = /* @__PURE__ */ new Map();
111846
+ appliedPermissionPresets = /* @__PURE__ */ new WeakMap();
111847
+ sessionOperations = /* @__PURE__ */ new Map();
111200
111848
  approvals = /* @__PURE__ */ new Map();
111201
111849
  approvalExpiryTimer;
111202
111850
  restartAttempts = /* @__PURE__ */ new Map();
@@ -111344,6 +111992,8 @@ var AcpRemoteGateway = class {
111344
111992
  if (this.archivingSessions.has(sessionId)) throw new RpcError("ACP_SESSION_BUSY", "The OpenCode session is being archived.");
111345
111993
  this.opencodeOperations.set(sessionId, (this.opencodeOperations.get(sessionId) ?? 0) + 1);
111346
111994
  }
111995
+ const pin = backend !== void 0 && sessionId !== void 0 && PINNED_SESSION_METHODS.has(call.method) ? `${backend}:${sessionId}` : void 0;
111996
+ if (pin) this.sessionOperations.set(pin, (this.sessionOperations.get(pin) ?? 0) + 1);
111347
111997
  try {
111348
111998
  const result = await this.callInternal(connectionId, call, assertCurrent, diagnosticScope, historySignal);
111349
111999
  assertCurrent();
@@ -111359,6 +112009,11 @@ var AcpRemoteGateway = class {
111359
112009
  );
111360
112010
  throw mapAcpError(error62, includeUpstream);
111361
112011
  } finally {
112012
+ if (pin) {
112013
+ const remaining = (this.sessionOperations.get(pin) ?? 1) - 1;
112014
+ if (remaining) this.sessionOperations.set(pin, remaining);
112015
+ else this.sessionOperations.delete(pin);
112016
+ }
111362
112017
  if (reserve) {
111363
112018
  const remaining = (this.opencodeOperations.get(sessionId) ?? 1) - 1;
111364
112019
  if (remaining) this.opencodeOperations.set(sessionId, remaining);
@@ -111457,7 +112112,7 @@ var AcpRemoteGateway = class {
111457
112112
  if (call.method === "dsh/workspaceCreate") {
111458
112113
  const backend = String(call.params.backend);
111459
112114
  this.requireAcp(backend);
111460
- const canonical = await this.requireExistingDirectory(String(call.params.path));
112115
+ const canonical = await this.requireAllowedWorkspaceDirectory(String(call.params.path));
111461
112116
  assertCurrent();
111462
112117
  const title = typeof call.params.title === "string" ? call.params.title : void 0;
111463
112118
  const entry = await this.workspaceStore.upsertWorkspace(backend, canonical, title);
@@ -111466,16 +112121,29 @@ var AcpRemoteGateway = class {
111466
112121
  if (call.method === "dsh/workspaceRename") {
111467
112122
  const backend = String(call.params.backend);
111468
112123
  this.requireAcp(backend);
111469
- const canonical = await this.requireExistingDirectory(String(call.params.path)).catch(() => String(call.params.path));
112124
+ const rawPath = String(call.params.path);
112125
+ const { workspaces: persisted } = await this.workspaceStore.listWorkspaces(backend);
112126
+ assertCurrent();
112127
+ const persistedPaths = new Set(persisted.map((item) => item.path));
112128
+ const resolved = await this.requireExistingDirectory(rawPath).catch(() => void 0);
111470
112129
  assertCurrent();
111471
- const entry = await this.workspaceStore.renameWorkspace(backend, canonical, String(call.params.title));
112130
+ let targetPath;
112131
+ if (resolved !== void 0 && persistedPaths.has(resolved)) {
112132
+ targetPath = resolved;
112133
+ } else if (persistedPaths.has(rawPath)) {
112134
+ targetPath = rawPath;
112135
+ } else {
112136
+ targetPath = await this.requireAllowedWorkspaceDirectory(rawPath);
112137
+ assertCurrent();
112138
+ }
112139
+ const entry = await this.workspaceStore.renameWorkspace(backend, targetPath, String(call.params.title));
111472
112140
  return { path: entry.path, title: entry.title ?? (basename8(entry.path) || "workspace"), updatedAt: entry.updatedAt };
111473
112141
  }
111474
112142
  if (call.method === "dsh/workspaceDelete") {
111475
112143
  const backend = String(call.params.backend);
111476
112144
  this.requireAcp(backend);
111477
112145
  const rawPath = String(call.params.path);
111478
- const canonical = await realpath7(rawPath).catch(() => rawPath);
112146
+ const canonical = await realpath8(rawPath).catch(() => rawPath);
111479
112147
  assertCurrent();
111480
112148
  await this.workspaceStore.deleteWorkspace(backend, canonical);
111481
112149
  if (canonical !== rawPath) await this.workspaceStore.deleteWorkspace(backend, rawPath);
@@ -111485,8 +112153,23 @@ var AcpRemoteGateway = class {
111485
112153
  const backend = String(call.params.backend);
111486
112154
  this.requireAcp(backend);
111487
112155
  const rawPaths = Array.isArray(call.params.paths) ? call.params.paths.filter((p) => typeof p === "string") : [];
111488
- const canonicalPaths = await Promise.all(rawPaths.map((p) => realpath7(p).catch(() => p)));
112156
+ const { workspaces: persisted } = await this.workspaceStore.listWorkspaces(backend);
111489
112157
  assertCurrent();
112158
+ const persistedPaths = new Set(persisted.map((item) => item.path));
112159
+ const canonicalPaths = [];
112160
+ for (const rawPath of rawPaths) {
112161
+ const resolved = await realpath8(rawPath).catch(() => void 0);
112162
+ assertCurrent();
112163
+ if (resolved !== void 0 && persistedPaths.has(resolved)) {
112164
+ canonicalPaths.push(resolved);
112165
+ } else if (persistedPaths.has(rawPath)) {
112166
+ canonicalPaths.push(rawPath);
112167
+ } else {
112168
+ const allowed = await this.requireAllowedWorkspaceDirectory(rawPath);
112169
+ assertCurrent();
112170
+ canonicalPaths.push(allowed);
112171
+ }
112172
+ }
111490
112173
  const paths = await this.workspaceStore.reorderWorkspaces(backend, canonicalPaths);
111491
112174
  return { paths };
111492
112175
  }
@@ -111578,18 +112261,10 @@ var AcpRemoteGateway = class {
111578
112261
  }
111579
112262
  if (merged.size === 0 && deletedPaths.size === 0 && (requestedBackend === "opencode" || requestedBackend === "cursor" || requestedBackend === "antigravity")) {
111580
112263
  const defaultCandidates = /* @__PURE__ */ new Set();
111581
- const cwd2 = process.cwd();
111582
- if (cwd2) {
111583
- const canonical = await this.requireExistingDirectory(cwd2).catch(() => void 0);
111584
- assertCurrent();
111585
- if (canonical) defaultCandidates.add(canonical);
111586
- }
111587
112264
  for (const candidate of ["/var/lib/dsh/workspace/ds-harness-remote", "/srv/dsh-workspace", "/var/lib/dsh/local"]) {
111588
- try {
111589
- const s = await stat6(candidate);
111590
- if (s.isDirectory()) defaultCandidates.add(candidate);
111591
- } catch {
111592
- }
112265
+ const canonical = await this.requireAllowedWorkspaceDirectory(candidate).catch(() => void 0);
112266
+ assertCurrent();
112267
+ if (canonical && !deletedPaths.has(canonical)) defaultCandidates.add(canonical);
111593
112268
  }
111594
112269
  return [...defaultCandidates].map((path) => ({ path, title: basename8(path) || "workspace" }));
111595
112270
  }
@@ -111597,14 +112272,10 @@ var AcpRemoteGateway = class {
111597
112272
  }
111598
112273
  const candidates = /* @__PURE__ */ new Set();
111599
112274
  if (merged.size === 0 && deletedPaths.size === 0) {
111600
- const cwd2 = process.cwd();
111601
- if (cwd2) candidates.add(cwd2);
111602
- for (const candidate of ["/var/lib/dsh/workspace/ds-harness-remote", "/var/lib/dsh/local"]) {
111603
- try {
111604
- const s = await stat6(candidate);
111605
- if (s.isDirectory()) candidates.add(candidate);
111606
- } catch {
111607
- }
112275
+ for (const candidate of ["/var/lib/dsh/workspace/ds-harness-remote", "/srv/dsh-workspace", "/var/lib/dsh/local"]) {
112276
+ const canonical = await this.requireAllowedWorkspaceDirectory(candidate).catch(() => void 0);
112277
+ assertCurrent();
112278
+ if (canonical && !deletedPaths.has(canonical)) candidates.add(canonical);
111608
112279
  }
111609
112280
  }
111610
112281
  if (requestedBackend === "antigravity") {
@@ -111727,8 +112398,7 @@ var AcpRemoteGateway = class {
111727
112398
  fullEvents = cached2.events;
111728
112399
  cachedMeta = cached2.metadata ?? client.lastHistoryMetadata?.(conversationId);
111729
112400
  } else {
111730
- const cacheEpoch = ++this.historyEpoch;
111731
- fullEvents = await this.readCatalogHistory(
112401
+ const read = await this.readCatalogHistory(
111732
112402
  backend,
111733
112403
  client,
111734
112404
  client.history.bind(client),
@@ -111737,16 +112407,19 @@ var AcpRemoteGateway = class {
111737
112407
  assertCurrent,
111738
112408
  historySignal
111739
112409
  );
111740
- cachedMeta = client.lastHistoryMetadata?.(conversationId);
112410
+ fullEvents = read.events;
111741
112411
  if (!this.backendHistoryChains.has(backend)) client.prewarmHistory?.();
111742
- if (paginated && this.isHistoryEpochValid(conversationId, cacheEpoch)) {
111743
- this.setPagedHistoryCache(cacheKey, {
111744
- readEpoch: cacheEpoch,
111745
- client,
111746
- cwd: cwd2,
111747
- events: fullEvents,
111748
- metadata: cachedMeta
111749
- });
112412
+ if (this.isHistoryEpochValid(conversationId, read.readEpoch)) {
112413
+ cachedMeta = read.metadata;
112414
+ if (paginated) {
112415
+ this.setPagedHistoryCache(cacheKey, {
112416
+ readEpoch: read.readEpoch,
112417
+ client,
112418
+ cwd: cwd2,
112419
+ events: fullEvents,
112420
+ metadata: cachedMeta
112421
+ });
112422
+ }
111750
112423
  }
111751
112424
  }
111752
112425
  const page = paginated ? sliceAcpHistoryEvents(fullEvents, beforeSeq, maxMessages) : void 0;
@@ -111757,6 +112430,7 @@ var AcpRemoteGateway = class {
111757
112430
  ...page ? { hasMore: page.hasMore, ...page.oldestSeq !== void 0 ? { oldestSeq: page.oldestSeq } : {} } : {},
111758
112431
  running: this.hasTurnInFlight(conversationId),
111759
112432
  ...persistedPreset ? { permissionPreset: persistedPreset } : {},
112433
+ ...cachedMeta?.models !== void 0 ? { models: cachedMeta.models } : {},
111760
112434
  ...nonEmptyModes ? { modes: nonEmptyModes } : {},
111761
112435
  ...cachedMeta?.commands && cachedMeta.commands.length > 0 ? { commands: cachedMeta.commands } : {}
111762
112436
  };
@@ -111804,7 +112478,7 @@ var AcpRemoteGateway = class {
111804
112478
  };
111805
112479
  }
111806
112480
  if (call.method === "session/new") {
111807
- const cwd2 = await this.requireExistingDirectory(String(call.params.cwd));
112481
+ const cwd2 = await this.requireAllowedWorkspaceDirectory(String(call.params.cwd));
111808
112482
  assertCurrent();
111809
112483
  const requestedBackend = typeof call.params.backend === "string" ? call.params.backend : this.defaultBackend();
111810
112484
  const acp = this.requireAcp(requestedBackend);
@@ -111870,7 +112544,7 @@ var AcpRemoteGateway = class {
111870
112544
  }
111871
112545
  const acp = this.requireAcp(targetBackend);
111872
112546
  diagnosticScope.authorized = true;
111873
- const result = await acp.call(call.method, { ...call.params, ...sessionId && this.sessionCwds.get(sessionId) ? { cwd: this.sessionCwds.get(sessionId).cwd, mcpServers: [] } : {} });
112547
+ const result = await acp.call(call.method, { ...call.params, ...sessionId && this.sessionCwds.get(sessionId) ? { cwd: this.sessionCwds.get(sessionId).cwd, mcpServers: [] } : {} }, ACP_HISTORY_LOAD_TIMEOUT_MS);
111874
112548
  assertCurrent();
111875
112549
  const loadedId = readSessionId(result) ?? sessionId;
111876
112550
  if (loadedId !== void 0) {
@@ -111904,32 +112578,38 @@ var AcpRemoteGateway = class {
111904
112578
  if (isSessionMutation(call.method) && sessionId !== void 0) {
111905
112579
  this.requireSessionOwner(connectionId, sessionId);
111906
112580
  }
111907
- if (call.method === "dsh/sessionModels" || call.method === "dsh/selectModel" || call.method === "dsh/sessionModes" || call.method === "session/set_mode") {
112581
+ const metadataField = call.method === "dsh/sessionModels" ? "models" : call.method === "dsh/sessionModes" ? "modes" : call.method === "dsh/sessionCommands" ? "commands" : void 0;
112582
+ if (metadataField !== void 0 || call.method === "dsh/selectModel" || call.method === "session/set_mode") {
111908
112583
  const preloadBackend = typeof call.params.backend === "string" ? call.params.backend : sessionId ? this.sessionBackends.get(sessionId) : void 0;
111909
- if (preloadBackend !== void 0 && sessionId !== void 0 && this.requiresCatalogCwd(preloadBackend)) {
111910
- this.requireSessionOwner(connectionId, sessionId);
111911
- const cwd2 = await this.catalogSessionCwd(preloadBackend, sessionId);
112584
+ if (preloadBackend !== void 0 && sessionId !== void 0) {
112585
+ const strict = this.requiresCatalogCwd(preloadBackend);
112586
+ if (strict && metadataField !== "commands") this.requireSessionOwner(connectionId, sessionId);
112587
+ const cwd2 = strict && metadataField !== "commands" ? await this.catalogSessionCwd(preloadBackend, sessionId) : void 0;
111912
112588
  assertCurrent();
111913
112589
  const acp = this.requireAcp(preloadBackend);
111914
- if ((call.method === "dsh/sessionModels" || call.method === "dsh/sessionModes") && acp.isSessionLoaded?.(sessionId) === false) {
111915
- const cachedMeta = acp.lastHistoryMetadata?.(sessionId);
111916
- if (call.method === "dsh/sessionModels" && cachedMeta?.models !== void 0) return cachedMeta.models;
111917
- if (call.method === "dsh/sessionModes" && cachedMeta?.modes !== void 0) return cachedMeta.modes;
111918
- }
111919
- diagnosticScope.authorized = true;
111920
- await acp.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] });
111921
- assertCurrent();
111922
- } else if (preloadBackend === "cursor" && sessionId !== void 0) {
111923
- if (!this.sessionCwds.has(sessionId) && this.isNativeCatalogBackend("cursor")) {
111924
- await this.listCatalogSessions("cursor").catch(() => void 0);
111925
- assertCurrent();
111926
- }
111927
- const entry = this.sessionCwds.get(sessionId);
111928
- if (entry?.backend === "cursor") {
111929
- this.requireSessionOwner(connectionId, sessionId);
112590
+ if (metadataField !== void 0 && acp.isSessionLoaded?.(sessionId) === false) {
112591
+ const entry = this.sessionCwds.get(sessionId);
112592
+ const paged = entry?.backend === preloadBackend ? this.getPagedHistoryCache(`${preloadBackend}:${sessionId}`, acp, sessionId, entry.cwd)?.metadata : void 0;
112593
+ const cached2 = acp.lastHistoryMetadata?.(sessionId)?.[metadataField] ?? paged?.[metadataField];
112594
+ if (metadataField === "commands") return { commands: cached2 ?? [] };
112595
+ if (cached2 !== void 0) return cached2;
112596
+ }
112597
+ if (cwd2 !== void 0) {
111930
112598
  diagnosticScope.authorized = true;
111931
- await this.requireAcp("cursor").call("session/load", { sessionId, cwd: entry.cwd, mcpServers: [] });
112599
+ await acp.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
111932
112600
  assertCurrent();
112601
+ } else if (preloadBackend === "cursor" && metadataField !== "commands") {
112602
+ if (!this.sessionCwds.has(sessionId) && this.isNativeCatalogBackend("cursor")) {
112603
+ await this.listCatalogSessions("cursor").catch(() => void 0);
112604
+ assertCurrent();
112605
+ }
112606
+ const entry = this.sessionCwds.get(sessionId);
112607
+ if (entry?.backend === "cursor") {
112608
+ this.requireSessionOwner(connectionId, sessionId);
112609
+ diagnosticScope.authorized = true;
112610
+ await acp.call("session/load", { sessionId, cwd: entry.cwd, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
112611
+ assertCurrent();
112612
+ }
111933
112613
  }
111934
112614
  }
111935
112615
  }
@@ -111943,6 +112623,7 @@ var AcpRemoteGateway = class {
111943
112623
  const result = await this.requireAcp(session2.backend).call(call.method, { ...call.params, cwd: session2.cwd });
111944
112624
  assertCurrent();
111945
112625
  this.sessionBackends.set(sessionId, session2.backend);
112626
+ this.invalidateSessionHistory(sessionId);
111946
112627
  return sanitizeSessionResult(result);
111947
112628
  }
111948
112629
  if (call.method === "session/set_mode") {
@@ -111952,6 +112633,10 @@ var AcpRemoteGateway = class {
111952
112633
  diagnosticScope.authorized = true;
111953
112634
  const result = await acp.call("session/set_mode", { sessionId, modeId: call.params.modeId });
111954
112635
  assertCurrent();
112636
+ const token = acp.sessionLoadToken?.(sessionId);
112637
+ const preset = this.sessionPermissions.get(sessionId);
112638
+ if (token && preset) this.appliedPermissionPresets.set(token, preset);
112639
+ this.invalidateSessionHistory(sessionId);
111955
112640
  return sanitizeSessionResult(result);
111956
112641
  }
111957
112642
  if (call.method === "dsh/sessionModes" || call.method === "dsh/sessionCommands") {
@@ -111977,6 +112662,10 @@ var AcpRemoteGateway = class {
111977
112662
  }
111978
112663
  const session2 = this.sessionCwds.get(sessionId);
111979
112664
  diagnosticScope.authorized = true;
112665
+ if (session2?.backend === backend && acp.isSessionLoaded?.(sessionId) === false) {
112666
+ await acp.call("session/load", { sessionId, cwd: session2.cwd, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
112667
+ assertCurrent();
112668
+ }
111980
112669
  const result = await acp.call("session/fork", { sessionId, ...session2 ? { cwd: session2.cwd } : {} });
111981
112670
  assertCurrent();
111982
112671
  const forkedId = readSessionId(result);
@@ -111993,12 +112682,29 @@ var AcpRemoteGateway = class {
111993
112682
  if (preset !== "workspace-write" && preset !== "danger-full-access") {
111994
112683
  throw new RpcError("INVALID_MESSAGE", "Unknown permission preset.");
111995
112684
  }
112685
+ const backend = typeof call.params.backend === "string" ? call.params.backend : this.sessionBackends.get(sessionId);
112686
+ const client = backend === void 0 ? void 0 : this.backendInstances.get(backend)?.client;
112687
+ if (backend !== void 0 && client?.isSessionLoaded?.(sessionId) === false) {
112688
+ const cwd2 = await this.catalogSessionCwd(backend, sessionId);
112689
+ assertCurrent();
112690
+ await client.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
112691
+ assertCurrent();
112692
+ }
111996
112693
  this.sessionPermissions.set(sessionId, preset);
111997
112694
  await this.workspaceStore.setSessionPermission(sessionId, preset);
111998
112695
  assertCurrent();
111999
- const backend = typeof call.params.backend === "string" ? call.params.backend : this.sessionBackends.get(sessionId);
112000
112696
  if (backend) {
112001
- await this.syncPermissionModeIfCompatible(backend, sessionId, preset).catch(() => void 0);
112697
+ const token = client?.sessionLoadToken?.(sessionId);
112698
+ if (token) this.appliedPermissionPresets.delete(token);
112699
+ try {
112700
+ await this.syncPermissionModeIfCompatible(backend, sessionId, preset);
112701
+ assertCurrent();
112702
+ if (token) this.appliedPermissionPresets.set(token, preset);
112703
+ } catch (error62) {
112704
+ if (client?.sessionLoadToken) throw error62;
112705
+ } finally {
112706
+ this.invalidateSessionHistory(sessionId);
112707
+ }
112002
112708
  }
112003
112709
  return { preset };
112004
112710
  }
@@ -112017,7 +112723,8 @@ var AcpRemoteGateway = class {
112017
112723
  this.promptsInProgress.set(sessionId, task);
112018
112724
  this.cancelledSessions.delete(sessionId);
112019
112725
  const preparationBackend = this.sessionBackends.get(sessionId);
112020
- if (preparationBackend && (scoped || this.requiresPrePromptLoad(preparationBackend))) {
112726
+ const supportsRetention = task.client.sessionLoadToken !== void 0;
112727
+ if (preparationBackend && (scoped || this.requiresPrePromptLoad(preparationBackend) || task.client.isSessionLoaded?.(sessionId) === false || supportsRetention && this.sessionPermissions.has(sessionId))) {
112021
112728
  const preparation = { cancelled: false, turnId: task.turnId };
112022
112729
  this.preparingPrompts.set(sessionId, preparation);
112023
112730
  try {
@@ -112025,7 +112732,15 @@ var AcpRemoteGateway = class {
112025
112732
  if (preparation.cancelled) return { accepted: false, stopReason: "cancelled" };
112026
112733
  assertCurrent();
112027
112734
  diagnosticScope.authorized = true;
112028
- await task.client.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] });
112735
+ await task.client.call("session/load", { sessionId, cwd: cwd2, mcpServers: [] }, ACP_HISTORY_LOAD_TIMEOUT_MS);
112736
+ assertCurrent();
112737
+ const preset = this.sessionPermissions.get(sessionId);
112738
+ const token = task.client.sessionLoadToken?.(sessionId);
112739
+ if (!preparation.cancelled && token && (preset === "workspace-write" || preset === "danger-full-access") && this.appliedPermissionPresets.get(token) !== preset) {
112740
+ await this.syncPermissionModeIfCompatible(backend, sessionId, preset);
112741
+ assertCurrent();
112742
+ this.appliedPermissionPresets.set(token, preset);
112743
+ }
112029
112744
  if (preparation.cancelled) return { accepted: false, stopReason: "cancelled" };
112030
112745
  assertCurrent();
112031
112746
  } catch (error62) {
@@ -112183,7 +112898,6 @@ var AcpRemoteGateway = class {
112183
112898
  }
112184
112899
  }
112185
112900
  for (const instance of this.backendInstances.values()) {
112186
- ;
112187
112901
  instance.client.invalidateHistoryMetadata?.(sessionId);
112188
112902
  }
112189
112903
  }
@@ -112233,7 +112947,7 @@ var AcpRemoteGateway = class {
112233
112947
  const key = `${backend}:${conversationId}`;
112234
112948
  let read = this.pendingHistoryReads.get(key);
112235
112949
  if (read === void 0 || read.client !== client || read.controller.signal.aborted || !this.isHistoryEpochValid(conversationId, read.readEpoch)) {
112236
- const readEpoch = ++this.historyEpoch;
112950
+ const readEpoch2 = ++this.historyEpoch;
112237
112951
  const controller2 = new AbortController();
112238
112952
  const waiters2 = /* @__PURE__ */ new Set();
112239
112953
  const previous = this.backendHistoryChains.get(backend) ?? Promise.resolve();
@@ -112253,17 +112967,22 @@ var AcpRemoteGateway = class {
112253
112967
  if (this.requireAcp(backend) !== client) {
112254
112968
  throw new RpcError("CURSOR_UNAVAILABLE", "The ACP backend is not ready.");
112255
112969
  }
112256
- return history2(conversationId, cwd2, controller2.signal);
112970
+ const events = await history2(conversationId, cwd2, controller2.signal);
112971
+ if (!this.isHistoryEpochValid(conversationId, readEpoch2)) {
112972
+ client.invalidateHistoryMetadata?.(conversationId);
112973
+ return { events };
112974
+ }
112975
+ return { events, metadata: client.lastHistoryMetadata?.(conversationId) };
112257
112976
  }).finally(() => {
112258
112977
  if (this.backendHistoryChains.get(backend) === nextChain) this.backendHistoryChains.delete(backend);
112259
112978
  if (this.pendingHistoryReads.get(key)?.promise === promise3) this.pendingHistoryReads.delete(key);
112260
112979
  });
112261
112980
  const nextChain = promise3.then(() => void 0, () => void 0);
112262
112981
  this.backendHistoryChains.set(backend, nextChain);
112263
- read = { client, readEpoch, controller: controller2, waiters: waiters2, promise: promise3 };
112982
+ read = { client, readEpoch: readEpoch2, controller: controller2, waiters: waiters2, promise: promise3 };
112264
112983
  this.pendingHistoryReads.set(key, read);
112265
112984
  }
112266
- const { controller, waiters, promise: promise2 } = read;
112985
+ const { controller, waiters, promise: promise2, readEpoch } = read;
112267
112986
  waiters.add(assertCurrent);
112268
112987
  const onAbort = () => {
112269
112988
  waiters.delete(assertCurrent);
@@ -112271,9 +112990,9 @@ var AcpRemoteGateway = class {
112271
112990
  };
112272
112991
  signal?.addEventListener("abort", onAbort, { once: true });
112273
112992
  try {
112274
- const events = await promise2;
112993
+ const result = await promise2;
112275
112994
  assertCurrent();
112276
- return events;
112995
+ return { ...result, readEpoch };
112277
112996
  } finally {
112278
112997
  signal?.removeEventListener("abort", onAbort);
112279
112998
  waiters.delete(assertCurrent);
@@ -113276,7 +113995,7 @@ var AcpRemoteGateway = class {
113276
113995
  throw new RpcError("CURSOR_PATH_NOT_ALLOWED", "The Cursor working directory must be an absolute path.");
113277
113996
  }
113278
113997
  try {
113279
- const canonical = await realpath7(path);
113998
+ const canonical = await realpath8(path);
113280
113999
  const info = await stat6(canonical);
113281
114000
  if (!info.isDirectory()) {
113282
114001
  throw new RpcError("CURSOR_PATH_NOT_ALLOWED", "The Cursor working directory must be an existing directory.");
@@ -113287,6 +114006,18 @@ var AcpRemoteGateway = class {
113287
114006
  throw new RpcError("CURSOR_PATH_NOT_ALLOWED", "The Cursor working directory must be an existing directory.");
113288
114007
  }
113289
114008
  }
114009
+ async requireAllowedWorkspaceDirectory(path) {
114010
+ const canonical = await this.requireExistingDirectory(path);
114011
+ await assertAllowedWorkspacePath(path, {
114012
+ invalidCode: "CURSOR_PATH_NOT_ALLOWED",
114013
+ deniedCode: "CURSOR_PATH_NOT_ALLOWED"
114014
+ });
114015
+ await assertAllowedWorkspacePath(canonical, {
114016
+ invalidCode: "CURSOR_PATH_NOT_ALLOWED",
114017
+ deniedCode: "CURSOR_PATH_NOT_ALLOWED"
114018
+ });
114019
+ return canonical;
114020
+ }
113290
114021
  async listDirectory(path) {
113291
114022
  const home = homedir6();
113292
114023
  const target3 = path.trim() === "~" || path.trim() === "" ? home : path.startsWith("~/") ? join15(home, path.slice(2)) : path;
@@ -113604,7 +114335,7 @@ function acpDetachedBudgetKey(backend, handle) {
113604
114335
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
113605
114336
  import { existsSync as existsSync4, constants as constants7, accessSync as accessSync2, statSync as statSync4 } from "node:fs";
113606
114337
  import { homedir as homedir7 } from "node:os";
113607
- import { dirname as dirname8, join as join16, posix as posix2, win32 as win323 } from "node:path";
114338
+ import { dirname as dirname8, join as join16, posix as posix3, win32 as win324 } from "node:path";
113608
114339
  import { promisify as promisify5 } from "node:util";
113609
114340
  var execFileAsync2 = promisify5(execFile4);
113610
114341
  var BUILTIN_ACP_SPECS = Object.freeze({
@@ -113702,7 +114433,7 @@ function discoverSystemNpmPrefix(platform3 = process.platform) {
113702
114433
  }
113703
114434
  function candidateBinaryPaths(id7, options = {}) {
113704
114435
  const platform3 = options.platform ?? process.platform;
113705
- const pJoin = platform3 === "win32" ? win323.join : posix2.join;
114436
+ const pJoin = platform3 === "win32" ? win324.join : posix3.join;
113706
114437
  const env = options.env ?? process.env;
113707
114438
  const home = options.homedir ?? homedir7();
113708
114439
  const localAppData = env.LOCALAPPDATA ?? (platform3 === "win32" ? pJoin(home, "AppData", "Local") : "");
@@ -113871,7 +114602,7 @@ function lookupSystemPath(command, platform3 = process.platform, checkExecutable
113871
114602
  }
113872
114603
  const firstLine = lines.find((line) => line.trim().length > 0);
113873
114604
  if (firstLine && checkExecutable(firstLine.trim())) {
113874
- return posix2.resolve(firstLine.trim());
114605
+ return posix3.resolve(firstLine.trim());
113875
114606
  }
113876
114607
  return void 0;
113877
114608
  } catch {
@@ -113884,7 +114615,7 @@ function findExistingBinary(id7, options = {}) {
113884
114615
  const candidates = candidateBinaryPaths(id7, options);
113885
114616
  for (const candidate of candidates) {
113886
114617
  if (check2(candidate)) {
113887
- return platform3 === "win32" ? win323.resolve(candidate) : posix2.resolve(candidate);
114618
+ return platform3 === "win32" ? win324.resolve(candidate) : posix3.resolve(candidate);
113888
114619
  }
113889
114620
  }
113890
114621
  const defaultCommands = {
@@ -113971,7 +114702,7 @@ async function installOrConfigureBackend(backendId2, options = {}) {
113971
114702
  // packages/plugin/src/model-share/settings-store.ts
113972
114703
  import { watch as watch2 } from "node:fs";
113973
114704
  import { mkdir as mkdir5, readFile as readFile6, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
113974
- import { dirname as dirname9, join as join17 } from "node:path";
114705
+ import { join as join17 } from "node:path";
113975
114706
  var DEFAULT_STORE = {
113976
114707
  version: 1,
113977
114708
  host: {
@@ -113984,24 +114715,35 @@ var DEFAULT_STORE = {
113984
114715
  sources: {}
113985
114716
  }
113986
114717
  };
113987
- var ROUTE_PATTERN = /^[a-z0-9][a-z0-9._-]*::(\*|[a-z0-9][a-z0-9._-]*)$/i;
113988
114718
  function normalizeRoute(value) {
113989
114719
  if (typeof value !== "string") return void 0;
113990
114720
  const route = value.trim();
113991
- return ROUTE_PATTERN.test(route) ? route : void 0;
114721
+ const separator = route.indexOf("::");
114722
+ if (separator <= 0 || route.length > 256 || /[\u0000-\u001f\u007f]/.test(route)) return void 0;
114723
+ const provider = route.slice(0, separator);
114724
+ const model = route.slice(separator + 2);
114725
+ if (provider.length > 128 || provider.trim() !== provider || model.length === 0 || model.trim() !== model) return void 0;
114726
+ return route;
114727
+ }
114728
+ function normalizeDevices(value) {
114729
+ if (!Array.isArray(value) || !value.every((id7) => typeof id7 === "string" && id7.trim() !== "")) return void 0;
114730
+ return [...new Set(value.map((id7) => id7.trim()))];
113992
114731
  }
113993
114732
  function normalizeStore2(input4) {
113994
114733
  const raw = typeof input4 === "object" && input4 !== null ? input4 : {};
113995
114734
  const hostRaw = typeof raw.host === "object" && raw.host !== null ? raw.host : {};
113996
114735
  const borrowerRaw = typeof raw.borrower === "object" && raw.borrower !== null ? raw.borrower : {};
114736
+ const allowedDevices = normalizeDevices(hostRaw.allowedDevices);
113997
114737
  const rules = Array.isArray(hostRaw.rules) ? hostRaw.rules.flatMap((entry) => {
113998
114738
  if (typeof entry !== "object" || entry === null) return [];
113999
114739
  const rule = entry;
114740
+ const devices = normalizeDevices(rule.devices);
114741
+ if (devices === void 0) return [];
114000
114742
  const models = Array.isArray(rule.models) ? [...new Set(rule.models.map(normalizeRoute).filter((route) => route !== void 0))] : [];
114001
114743
  if (models.length === 0) return [];
114002
114744
  return [{
114003
114745
  models,
114004
- devices: Array.isArray(rule.devices) ? [...new Set(rule.devices.filter((id7) => typeof id7 === "string" && id7.trim() !== "").map((id7) => id7.trim()))] : []
114746
+ devices
114005
114747
  }];
114006
114748
  }) : [];
114007
114749
  const sourcesRaw = typeof borrowerRaw.sources === "object" && borrowerRaw.sources !== null ? borrowerRaw.sources : {};
@@ -114019,8 +114761,8 @@ function normalizeStore2(input4) {
114019
114761
  return {
114020
114762
  version: 1,
114021
114763
  host: {
114022
- enabled: hostRaw.enabled === true,
114023
- allowedDevices: Array.isArray(hostRaw.allowedDevices) ? hostRaw.allowedDevices.filter((id7) => typeof id7 === "string" && id7.trim() !== "").map((id7) => id7.trim()) : [],
114764
+ enabled: hostRaw.enabled === true && allowedDevices !== void 0,
114765
+ allowedDevices: allowedDevices ?? [],
114024
114766
  rules,
114025
114767
  maxConcurrent: Number.isFinite(maxConcurrentRaw) ? Math.min(Math.max(maxConcurrentRaw, 1), 16) : DEFAULT_STORE.host.maxConcurrent
114026
114768
  },
@@ -114033,7 +114775,6 @@ var ModelShareStoreFile = class {
114033
114775
  this.fileName = fileName;
114034
114776
  }
114035
114777
  cache;
114036
- writing = Promise.resolve();
114037
114778
  /** Active directory watcher and every callback it serves, if `watch()` was called. */
114038
114779
  watcher;
114039
114780
  get path() {
@@ -114041,33 +114782,47 @@ var ModelShareStoreFile = class {
114041
114782
  }
114042
114783
  async read() {
114043
114784
  if (this.cache !== void 0) return this.cache;
114785
+ this.cache = await this.readDisk();
114786
+ return this.cache;
114787
+ }
114788
+ async readDisk() {
114044
114789
  try {
114045
114790
  const text = await readFile6(this.path, "utf8");
114046
- this.cache = normalizeStore2(JSON.parse(text));
114791
+ return normalizeStore2(JSON.parse(text));
114047
114792
  } catch {
114048
- this.cache = normalizeStore2(void 0);
114793
+ return normalizeStore2(void 0);
114049
114794
  }
114050
- return this.cache;
114051
114795
  }
114052
114796
  async write(next) {
114797
+ await mkdir5(this.directory, { recursive: true });
114798
+ return withIdentityLock(this.directory, () => this.writeLocked(next));
114799
+ }
114800
+ /** Read-modify-write helper for concurrent callers. */
114801
+ async update(mutate) {
114802
+ await mkdir5(this.directory, { recursive: true });
114803
+ return withIdentityLock(this.directory, async () => {
114804
+ const current = await this.readDisk();
114805
+ return this.writeLocked(mutate(current));
114806
+ });
114807
+ }
114808
+ async replaceIfUnchanged(next, expected) {
114809
+ await mkdir5(this.directory, { recursive: true });
114810
+ return withIdentityLock(this.directory, async () => {
114811
+ const current = await this.readDisk();
114812
+ if (JSON.stringify(current) !== JSON.stringify(normalizeStore2(expected))) return void 0;
114813
+ return this.writeLocked(next);
114814
+ });
114815
+ }
114816
+ async writeLocked(next) {
114053
114817
  const normalized = normalizeStore2(next);
114054
- this.cache = normalized;
114055
114818
  const path = this.path;
114056
- this.writing = this.writing.catch(() => void 0).then(async () => {
114057
- await mkdir5(dirname9(path), { recursive: true });
114058
- const temporary = `${path}.${process.pid}.tmp`;
114059
- await writeFile4(temporary, `${JSON.stringify(normalized, void 0, 2)}
114819
+ const temporary = `${path}.${process.pid}.tmp`;
114820
+ await writeFile4(temporary, `${JSON.stringify(normalized, void 0, 2)}
114060
114821
  `, "utf8");
114061
- await rename4(temporary, path);
114062
- });
114063
- await this.writing;
114822
+ await rename4(temporary, path);
114823
+ this.cache = normalized;
114064
114824
  return normalized;
114065
114825
  }
114066
- /** Read-modify-write helper for concurrent callers. */
114067
- async update(mutate) {
114068
- const current = await this.read();
114069
- return this.write(mutate(current));
114070
- }
114071
114826
  /**
114072
114827
  * Observe on-disk policy changes so a CLI edit or a hand-edited JSON takes
114073
114828
  * effect without restarting the Harness. Returns an unsubscribe function.
@@ -114879,9 +115634,11 @@ var PluginControlRuntime = class {
114879
115634
  async modelShareSet(payload) {
114880
115635
  const binding = this.modelShareBinding();
114881
115636
  const raw = record10(payload);
114882
- const candidate = raw.store !== void 0 ? raw.store : raw;
114883
- const next = normalizeStore2(candidate);
114884
- await binding.store.write(next);
115637
+ if (raw.store === void 0 || raw.expected === void 0) {
115638
+ throw new ClientModeError("INVALID_MESSAGE", "The model sharing update requires the previous settings.");
115639
+ }
115640
+ const next = await binding.store.replaceIfUnchanged(normalizeStore2(raw.store), normalizeStore2(raw.expected));
115641
+ if (next === void 0) throw new ClientModeError("SETTINGS_CONFLICT", "Model sharing settings changed; reload them and try again.");
114885
115642
  await binding.resync?.();
114886
115643
  return {
114887
115644
  store: next,
@@ -115085,12 +115842,12 @@ function fail4(error62) {
115085
115842
  }
115086
115843
 
115087
115844
  // packages/plugin/src/index.ts
115088
- import { basename as basename10, dirname as dirname13 } from "node:path";
115845
+ import { basename as basename10, dirname as dirname12 } from "node:path";
115089
115846
 
115090
115847
  // packages/plugin/src/host-log-store.ts
115091
115848
  import { mkdir as mkdir6, open as open7, readFile as readFile7, rename as rename5, rm as rm4, stat as stat7, writeFile as writeFile5 } from "node:fs/promises";
115092
115849
  import { homedir as homedir8 } from "node:os";
115093
- import { dirname as dirname10, join as join18 } from "node:path";
115850
+ import { dirname as dirname9, join as join18 } from "node:path";
115094
115851
  var DEFAULT_MAX_ENTRIES = 1e3;
115095
115852
  var DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
115096
115853
  var DEFAULT_MAX_BACKUPS = 2;
@@ -115251,7 +116008,7 @@ var HostLogStore = class {
115251
116008
  async appendToDisk(payload) {
115252
116009
  const target3 = this.filePath;
115253
116010
  if (!this.dirEnsured) {
115254
- await mkdir6(dirname10(target3), { recursive: true, mode: 448 });
116011
+ await mkdir6(dirname9(target3), { recursive: true, mode: 448 });
115255
116012
  this.dirEnsured = true;
115256
116013
  }
115257
116014
  if (!this.sizeVerified) {
@@ -115289,7 +116046,7 @@ var HostLogStore = class {
115289
116046
  async clearDisk() {
115290
116047
  const target3 = this.filePath;
115291
116048
  if (!this.dirEnsured) {
115292
- await mkdir6(dirname10(target3), { recursive: true, mode: 448 });
116049
+ await mkdir6(dirname9(target3), { recursive: true, mode: 448 });
115293
116050
  this.dirEnsured = true;
115294
116051
  }
115295
116052
  await writeFile5(target3, "", { encoding: "utf8", mode: 384 });
@@ -116431,7 +117188,7 @@ var HostPairing = class {
116431
117188
  // packages/plugin/src/workspace-upload.ts
116432
117189
  import { randomUUID as randomUUID19 } from "node:crypto";
116433
117190
  import { constants as constants8 } from "node:fs";
116434
- import { link as link2, lstat as lstat7, open as open8, realpath as realpath8, stat as stat9, unlink as unlink2 } from "node:fs/promises";
117191
+ import { link as link2, lstat as lstat7, open as open8, realpath as realpath9, stat as stat9, unlink as unlink2 } from "node:fs/promises";
116435
117192
  import { extname, isAbsolute as isAbsolute9, join as join20 } from "node:path";
116436
117193
 
116437
117194
  // packages/plugin/src/workspace-upload-budget.ts
@@ -116577,7 +117334,7 @@ var WorkspaceUploadHost = class {
116577
117334
  const sourceRoot = await this.sessionRoot(p.sessionId);
116578
117335
  this.assertLive();
116579
117336
  if (!sourceRoot || !isAbsolute9(sourceRoot)) throw failure3("UPLOAD_WORKSPACE_UNAVAILABLE");
116580
- const root2 = await realpath8(sourceRoot);
117337
+ const root2 = await realpath9(sourceRoot);
116581
117338
  const directory = await stat9(root2);
116582
117339
  if (!directory.isDirectory()) throw failure3("UPLOAD_WORKSPACE_UNAVAILABLE");
116583
117340
  const reservation = await this.budget.reserve(root2, directory.dev, p.sessionId, p.totalBytes);
@@ -116703,11 +117460,11 @@ var WorkspaceUploadHost = class {
116703
117460
  if (recheckAuthority) {
116704
117461
  const current = await this.sessionRoot(upload.sessionId);
116705
117462
  this.assertLive();
116706
- if (current !== upload.sourceRoot || await realpath8(current) !== upload.root) throw failure3("UPLOAD_WORKSPACE_CHANGED");
117463
+ if (current !== upload.sourceRoot || await realpath9(current) !== upload.root) throw failure3("UPLOAD_WORKSPACE_CHANGED");
116707
117464
  upload.authorityCheckedAt = this.now();
116708
117465
  upload.authorityBytes = upload.received;
116709
117466
  }
116710
- if (await realpath8(upload.root) !== upload.root) throw failure3("UPLOAD_WORKSPACE_CHANGED");
117467
+ if (await realpath9(upload.root) !== upload.root) throw failure3("UPLOAD_WORKSPACE_CHANGED");
116711
117468
  const directory = await stat9(upload.root);
116712
117469
  if (!directory.isDirectory() || directory.dev !== upload.dev || directory.ino !== upload.ino) throw failure3("UPLOAD_WORKSPACE_CHANGED");
116713
117470
  }
@@ -117257,48 +118014,6 @@ var TransportUpgradeHost = class {
117257
118014
  }
117258
118015
  };
117259
118016
 
117260
- // packages/plugin/src/model-share/protocol.ts
117261
- var MODEL_SHARE_CAPABILITY = "model.share.v1";
117262
- var MODEL_SHARE_METHODS = [
117263
- "model.share.list",
117264
- "model.share.open",
117265
- "model.share.chunk",
117266
- "model.share.close"
117267
- ];
117268
- var sharedModelSchema = external_exports.object({
117269
- /** Stable route key: `${provider}::${model}`. Also the borrower-facing model id. */
117270
- id: external_exports.string().min(1).max(256),
117271
- provider: external_exports.string().min(1).max(128),
117272
- model: external_exports.string().min(1).max(256),
117273
- /** Display label, defaults to the raw model id. */
117274
- name: external_exports.string().min(1).max(256),
117275
- contextWindow: external_exports.number().int().positive().optional(),
117276
- maxTokens: external_exports.number().int().positive().optional(),
117277
- reasoningEfforts: external_exports.array(external_exports.string().min(1).max(64)).optional(),
117278
- inputModalities: external_exports.array(external_exports.enum(["text", "image"])).optional()
117279
- }).strict();
117280
- var listRequestSchema = external_exports.object({}).strict();
117281
- var openRequestSchema = external_exports.object({
117282
- /** Stable route key from `model.share.list`. */
117283
- modelId: external_exports.string().min(1).max(256),
117284
- /** Opaque correlation id chosen by the borrower, echoed back in chunks. */
117285
- streamId: external_exports.string().min(1).max(128),
117286
- /** Normalized conversation. Kept loose: the Host re-validates structure. */
117287
- messages: external_exports.array(external_exports.unknown()).min(1),
117288
- tools: external_exports.array(external_exports.unknown()).optional(),
117289
- temperature: external_exports.number().optional(),
117290
- maxTokens: external_exports.number().int().positive().optional(),
117291
- reasoningEffort: external_exports.string().min(1).max(64).optional()
117292
- }).strict();
117293
- var chunkRequestSchema = external_exports.object({
117294
- streamId: external_exports.string().min(1).max(128),
117295
- /** Long-poll budget; the Host answers `done: false` on expiry. */
117296
- waitMs: external_exports.number().int().min(0).max(3e4).optional()
117297
- }).strict();
117298
- var closeRequestSchema = external_exports.object({
117299
- streamId: external_exports.string().min(1).max(128)
117300
- }).strict();
117301
-
117302
118017
  // packages/plugin/src/rpc-router.ts
117303
118018
  var wireRequestSchema = external_exports.object({ method: external_exports.string().min(1), params: external_exports.unknown() }).strict();
117304
118019
  var emptyParamsSchema = external_exports.object({}).strict();
@@ -119468,26 +120183,24 @@ function closeCode(code) {
119468
120183
  // packages/plugin/src/harness-remote-bridge.ts
119469
120184
  import { randomUUID as randomUUID20 } from "node:crypto";
119470
120185
  import { homedir as homedir10 } from "node:os";
119471
- import { lstat as lstat8, realpath as realpath10, stat as stat11 } from "node:fs/promises";
119472
- import { dirname as dirname12, isAbsolute as isAbsolute11, join as join22, parse as parse6, relative as relative6, resolve as resolve11, sep as sep5 } from "node:path";
120186
+ import { lstat as lstat8, realpath as realpath11, stat as stat11 } from "node:fs/promises";
120187
+ import { dirname as dirname11, isAbsolute as isAbsolute11, join as join22, parse as parse6, relative as relative6, resolve as resolve11, sep as sep5 } from "node:path";
119473
120188
 
119474
120189
  // packages/plugin/src/remote-directory-browser.ts
119475
- import { mkdir as mkdir7, realpath as realpath9, readdir as readdir6, stat as stat10 } from "node:fs/promises";
120190
+ import { mkdir as mkdir7, realpath as realpath10, readdir as readdir6, stat as stat10 } from "node:fs/promises";
119476
120191
  import { homedir as homedir9, platform as platform2 } from "node:os";
119477
- import { basename as basename9, dirname as dirname11, isAbsolute as isAbsolute10, join as join21, parse as parse5, resolve as resolve10 } from "node:path";
120192
+ import { basename as basename9, dirname as dirname10, isAbsolute as isAbsolute10, join as join21, parse as parse5, resolve as resolve10 } from "node:path";
119478
120193
  var MAX_ENTRIES = 500;
119479
120194
  async function ensureHostWorkspaceDirectory(path) {
119480
- if (typeof path !== "string" || path.trim() === "" || path.includes("\0") || !isAbsolute10(path) || resolve10(path) === parse5(path).root) {
119481
- throw new RpcError("INVALID_MESSAGE", "Workspace path must be an absolute, non-root directory path.");
119482
- }
119483
- await mkdir7(path, { recursive: true });
120195
+ const validPath = await assertAllowedWorkspacePath(path);
120196
+ await mkdir7(validPath, { recursive: true });
119484
120197
  }
119485
120198
  async function createHostChildDirectory(parent, name2) {
119486
120199
  if (typeof parent !== "string" || !isAbsolute10(parent) || parent.includes("\0") || typeof name2 !== "string" || !name2.trim() || name2 === "." || name2 === ".." || /[/\\\0]/u.test(name2) || platform2() === "win32" && (/[<>:"|?*\x00-\x1f]|[. ]$/u.test(name2) || /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(name2))) {
119487
120200
  throw new RpcError("INVALID_MESSAGE", "Invalid parent path or folder name.");
119488
120201
  }
119489
120202
  try {
119490
- const target3 = join21(await realpath9(parent), name2);
120203
+ const target3 = join21(await realpath10(parent), name2);
119491
120204
  await mkdir7(target3);
119492
120205
  return target3;
119493
120206
  } catch (error62) {
@@ -119526,7 +120239,7 @@ function crumbs(path) {
119526
120239
  let current = path;
119527
120240
  while (current !== root2) {
119528
120241
  segments.unshift(basename9(current));
119529
- current = dirname11(current);
120242
+ current = dirname10(current);
119530
120243
  }
119531
120244
  for (const segment of segments) {
119532
120245
  current = resolve10(current, segment);
@@ -120436,6 +121149,20 @@ var HarnessRemoteBridge = class {
120436
121149
  const folder = typeof request2.path === "string" ? request2.path : "";
120437
121150
  await ensureHostWorkspaceDirectory(folder);
120438
121151
  }
121152
+ if (params.endpoint === "session/create") {
121153
+ const request2 = requestArgs(params.payload);
121154
+ const workspaceId = typeof request2.workspaceId === "string" ? request2.workspaceId.trim() : "";
121155
+ const hasRawCwd = request2.cwd !== void 0 && request2.cwd !== null;
121156
+ const rawCwd = typeof request2.cwd === "string" ? request2.cwd : void 0;
121157
+ const hasWorkspaceId = workspaceId.length > 0;
121158
+ const hasCwd = rawCwd !== void 0 && rawCwd.trim().length > 0;
121159
+ if (!hasWorkspaceId && !hasCwd) {
121160
+ throw new RpcError("INVALID_MESSAGE", "A workspaceId or explicit workspace cwd is required to create a session.");
121161
+ }
121162
+ if (hasRawCwd) {
121163
+ await assertAllowedWorkspacePath(rawCwd);
121164
+ }
121165
+ }
120439
121166
  const startedAt = performance.now();
120440
121167
  const timeoutMs = params.endpoint === "speech/transcribe" ? SPEECH_TRANSCRIBE_TIMEOUT_MS3 : DEFAULT_CALL_TIMEOUT_MS;
120441
121168
  const controller = new AbortController();
@@ -120959,7 +121686,7 @@ var HarnessRemoteBridge = class {
120959
121686
  if (path !== void 0 && isAbsolute11(path)) {
120960
121687
  const info = await lstat8(path);
120961
121688
  if (!info.isSymbolicLink() && info.isFile() && info.size === reference.bytes) {
120962
- path = await realpath10(path);
121689
+ path = await realpath11(path);
120963
121690
  } else {
120964
121691
  path = void 0;
120965
121692
  }
@@ -121024,7 +121751,7 @@ var HarnessRemoteBridge = class {
121024
121751
  }
121025
121752
  const safeBaseRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, rawBaseFile, endpoint, sessionWorkspace.cwd);
121026
121753
  const baseCandidate = resolve11(sessionWorkspace.root, safeBaseRel);
121027
- const baseDir = dirname12(baseCandidate);
121754
+ const baseDir = dirname11(baseCandidate);
121028
121755
  const targetCandidate = resolve11(baseDir, path);
121029
121756
  safeRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, targetCandidate, endpoint, sessionWorkspace.cwd);
121030
121757
  } else {
@@ -121073,7 +121800,7 @@ var HarnessRemoteBridge = class {
121073
121800
  throw workspaceFileFailure("WORKSPACE_UNAVAILABLE", "The workspace is unavailable.", "authority-unavailable");
121074
121801
  }
121075
121802
  try {
121076
- const root2 = await realpath10(cwd2);
121803
+ const root2 = await realpath11(cwd2);
121077
121804
  const info = await stat11(root2);
121078
121805
  if (!info.isDirectory()) {
121079
121806
  throw workspaceFileFailure("WORKSPACE_UNAVAILABLE", "The workspace is unavailable.", "root-invalid");
@@ -121110,7 +121837,7 @@ var HarnessRemoteBridge = class {
121110
121837
  throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The workspace root is invalid or a symlink.", "root-invalid");
121111
121838
  }
121112
121839
  if (endpoint === "workspaceFiles/list" || endpoint === "workspaceFiles/changes") {
121113
- const canonicalRel2 = relative6(root2, await realpath10(candidate));
121840
+ const canonicalRel2 = relative6(root2, await realpath11(candidate));
121114
121841
  if (isPathOutside3(canonicalRel2)) {
121115
121842
  throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root");
121116
121843
  }
@@ -121136,7 +121863,7 @@ var HarnessRemoteBridge = class {
121136
121863
  if (targetLstat.isSymbolicLink()) {
121137
121864
  throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is not a regular file.", "symlink");
121138
121865
  }
121139
- const canonical = await realpath10(candidate);
121866
+ const canonical = await realpath11(candidate);
121140
121867
  if (process.platform === "win32") {
121141
121868
  const rootDrive = parse6(root2).root.toLowerCase();
121142
121869
  const canonicalDrive = parse6(canonical).root.toLowerCase();
@@ -121157,7 +121884,7 @@ var HarnessRemoteBridge = class {
121157
121884
  }
121158
121885
  const safeRel = canonicalRel === "" ? "." : process.platform === "win32" ? canonicalRel.replaceAll("\\", "/") : canonicalRel;
121159
121886
  const dispatchedCandidate = resolve11(root2, safeRel);
121160
- const dispatchedCanonical = await realpath10(dispatchedCandidate);
121887
+ const dispatchedCanonical = await realpath11(dispatchedCandidate);
121161
121888
  const dispatchedRel = relative6(root2, dispatchedCanonical);
121162
121889
  if (isPathOutside3(dispatchedRel)) {
121163
121890
  throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root");
@@ -122743,6 +123470,24 @@ async function waitForStartupGrace(promise2, graceMs) {
122743
123470
 
122744
123471
  // packages/plugin/src/model-share/host.ts
122745
123472
  var ROUTE_SEPARATOR = "::";
123473
+ var MAX_BUFFERED_BYTES = 512 * 1024;
123474
+ var MAX_BUFFERED_CHUNKS = 512;
123475
+ var MAX_RETAINED_STREAMS = 32;
123476
+ var STREAM_IDLE_MS = 6e4;
123477
+ function safeProviderFailure(value) {
123478
+ const outer = value !== null && typeof value === "object" ? value : {};
123479
+ const nested = outer.failure !== null && typeof outer.failure === "object" ? outer.failure : outer;
123480
+ const code = typeof nested.code === "string" ? nested.code : typeof outer.code === "string" ? outer.code : "";
123481
+ const status2 = typeof nested.status === "number" ? nested.status : typeof outer.status === "number" ? outer.status : void 0;
123482
+ let safeCode = MODEL_SHARE_FAILURE_CODES.FAILED;
123483
+ if (["QUOTA", "ACCOUNT_QUOTA"].includes(code)) safeCode = MODEL_SHARE_FAILURE_CODES.QUOTA;
123484
+ else if (["AUTH", "INVALID_CREDENTIAL", "MISSING_CREDENTIAL", "ACCOUNT_SIGN_IN_REQUIRED", "ACCOUNT_TOKEN_INVALID", "HTTP_401", "HTTP_403"].includes(code) || status2 === 401 || status2 === 403) safeCode = MODEL_SHARE_FAILURE_CODES.AUTH;
123485
+ else if (code === "RATE_LIMIT" || code === "HTTP_429" || status2 === 429) safeCode = MODEL_SHARE_FAILURE_CODES.RATE_LIMIT;
123486
+ else if (code === "CONTEXT_WINDOW_EXCEEDED") safeCode = MODEL_SHARE_FAILURE_CODES.CONTEXT;
123487
+ else if (["MODEL_UNSUPPORTED", "UNKNOWN_MODEL"].includes(code)) safeCode = MODEL_SHARE_FAILURE_CODES.MODEL_UNAVAILABLE;
123488
+ else if (["TIMEOUT", "TRANSPORT", "SERVER", "HTTP_500", "HTTP_502", "HTTP_503", "HTTP_504"].includes(code) || status2 !== void 0 && status2 >= 500 && status2 <= 599) safeCode = MODEL_SHARE_FAILURE_CODES.PROVIDER_UNAVAILABLE;
123489
+ return { code: safeCode, message: "The lending Host could not complete the model call." };
123490
+ }
122746
123491
  function routeKey(provider, model) {
122747
123492
  return `${provider}${ROUTE_SEPARATOR}${model}`;
122748
123493
  }
@@ -122775,14 +123520,15 @@ function allowedRoutes(policy, deviceId) {
122775
123520
  return routes;
122776
123521
  }
122777
123522
  var ModelShareHost = class {
122778
- constructor(llm, store, logger2, deviceId = "") {
123523
+ constructor(llm, store, logger2, deviceId = "", concurrency = { active: 0 }) {
122779
123524
  this.llm = llm;
122780
123525
  this.store = store;
122781
123526
  this.logger = logger2;
122782
123527
  this.deviceId = deviceId;
123528
+ this.concurrency = concurrency;
122783
123529
  }
122784
123530
  streams = /* @__PURE__ */ new Map();
122785
- activeCount = 0;
123531
+ pending = /* @__PURE__ */ new Map();
122786
123532
  /**
122787
123533
  * Models this Host lends *to this device*, already filtered by grants.
122788
123534
  * Catalog failures degrade to an empty list rather than throwing: a broken
@@ -122865,34 +123611,52 @@ var ModelShareHost = class {
122865
123611
  const request2 = openRequestSchema.parse(params);
122866
123612
  const route = parseRouteKey(request2.modelId);
122867
123613
  if (route === void 0) throw new RpcError("INVALID_MESSAGE", "The model id is not a shared route key.");
122868
- const { host } = await this.store.read();
122869
- if (!grantAllows(host, deviceId, route.provider, route.model)) {
122870
- throw new RpcError("PERMISSION_DENIED", "This model is not lent to this device.");
123614
+ if (this.streams.has(request2.streamId) || this.pending.has(request2.streamId)) {
123615
+ throw new RpcError("REQUEST_CONFLICT", "That stream id is already active on this Host.");
122871
123616
  }
122872
- if (this.activeCount >= host.maxConcurrent) {
122873
- throw new RpcError("RATE_LIMITED", "The lending Host is at its concurrent stream limit.", void 0, true);
123617
+ if ((this.concurrency.retained ?? 0) + (this.concurrency.pending ?? 0) >= MAX_RETAINED_STREAMS) {
123618
+ throw new RpcError("RATE_LIMITED", "The lending Host has too many unread streams.", void 0, true);
122874
123619
  }
122875
- if (this.streams.has(request2.streamId)) {
122876
- throw new RpcError("REQUEST_CONFLICT", "That stream id is already active on this Host.");
123620
+ const pending = new AbortController();
123621
+ this.pending.set(request2.streamId, { deviceId, abort: pending });
123622
+ this.concurrency.pending = (this.concurrency.pending ?? 0) + 1;
123623
+ try {
123624
+ const { host } = await this.store.read();
123625
+ if (pending.signal.aborted) throw new RpcError("CANCELLED", "The model sharing request was cancelled.");
123626
+ if (!grantAllows(host, deviceId, route.provider, route.model)) {
123627
+ throw new RpcError("PERMISSION_DENIED", "This model is not lent to this device.");
123628
+ }
123629
+ if (this.concurrency.active >= host.maxConcurrent) {
123630
+ throw new RpcError("RATE_LIMITED", "The lending Host is at its concurrent stream limit.", void 0, true);
123631
+ }
123632
+ if ((this.concurrency.retained ?? 0) >= MAX_RETAINED_STREAMS) {
123633
+ throw new RpcError("RATE_LIMITED", "The lending Host has too many unread streams.", void 0, true);
123634
+ }
123635
+ const abort = new AbortController();
123636
+ const active2 = {
123637
+ streamId: request2.streamId,
123638
+ deviceId,
123639
+ chunks: [],
123640
+ bufferedBytes: 0,
123641
+ abort,
123642
+ notify: [],
123643
+ startedAt: Date.now()
123644
+ };
123645
+ this.streams.set(request2.streamId, active2);
123646
+ this.concurrency.active += 1;
123647
+ this.concurrency.retained = (this.concurrency.retained ?? 0) + 1;
123648
+ this.renewLease(active2);
123649
+ void this.pump(active2, route.provider, route.model, request2);
123650
+ this.logger?.info("model-share: stream opened", {
123651
+ deviceId,
123652
+ provider: route.provider,
123653
+ model: route.model
123654
+ });
123655
+ return { streamId: request2.streamId };
123656
+ } finally {
123657
+ this.pending.delete(request2.streamId);
123658
+ this.concurrency.pending = Math.max(0, (this.concurrency.pending ?? 0) - 1);
122877
123659
  }
122878
- const abort = new AbortController();
122879
- const active2 = {
122880
- streamId: request2.streamId,
122881
- deviceId,
122882
- chunks: [],
122883
- abort,
122884
- notify: [],
122885
- startedAt: Date.now()
122886
- };
122887
- this.streams.set(request2.streamId, active2);
122888
- this.activeCount += 1;
122889
- void this.pump(active2, route.provider, route.model, request2);
122890
- this.logger?.info("model-share: stream opened", {
122891
- deviceId,
122892
- provider: route.provider,
122893
- model: route.model
122894
- });
122895
- return { streamId: request2.streamId };
122896
123660
  }
122897
123661
  async pump(active2, provider, model, request2) {
122898
123662
  try {
@@ -122900,38 +123664,49 @@ var ModelShareHost = class {
122900
123664
  provider,
122901
123665
  model,
122902
123666
  messages: request2.messages,
123667
+ ...request2.system === void 0 ? {} : { system: request2.system },
122903
123668
  signal: active2.abort.signal,
122904
123669
  ...request2.tools === void 0 ? {} : { tools: request2.tools },
122905
123670
  ...request2.temperature === void 0 ? {} : { temperature: request2.temperature },
122906
123671
  ...request2.maxTokens === void 0 ? {} : { maxTokens: request2.maxTokens },
123672
+ ...request2.stop === void 0 ? {} : { stop: request2.stop },
122907
123673
  ...request2.reasoningEffort === void 0 ? {} : { reasoningEffort: request2.reasoningEffort }
122908
123674
  };
122909
123675
  for await (const chunk of this.llm.stream(options)) {
122910
- active2.chunks.push(chunk);
123676
+ const safeChunk = chunk.type === "finish" && (chunk.reason.kind === "error" || chunk.reason.kind === "aborted") ? { type: "finish", reason: { kind: chunk.reason.kind, failure: safeProviderFailure(chunk.reason.failure) } } : chunk;
123677
+ const bytes = Buffer.byteLength(JSON.stringify(safeChunk), "utf8");
123678
+ if (active2.chunks.length >= MAX_BUFFERED_CHUNKS || active2.bufferedBytes + bytes > MAX_BUFFERED_BYTES) {
123679
+ const failure4 = { code: MODEL_SHARE_FAILURE_CODES.BUFFER_LIMIT, message: "The model response exceeded the buffering limit." };
123680
+ active2.abort.abort();
123681
+ active2.chunks.push({ type: "finish", reason: { kind: "error", failure: failure4 } });
123682
+ active2.finished = { reason: "error", failure: failure4 };
123683
+ this.wake(active2);
123684
+ break;
123685
+ }
123686
+ active2.chunks.push(safeChunk);
123687
+ active2.bufferedBytes += bytes;
122911
123688
  this.wake(active2);
122912
- if (chunk.type === "finish") {
122913
- active2.finished = chunk.reason.kind === "error" || chunk.reason.kind === "aborted" ? {
122914
- reason: chunk.reason.kind,
123689
+ if (safeChunk.type === "finish") {
123690
+ active2.finished = safeChunk.reason.kind === "error" || safeChunk.reason.kind === "aborted" ? {
123691
+ reason: safeChunk.reason.kind,
122915
123692
  failure: {
122916
- code: chunk.reason.failure.code,
122917
- message: chunk.reason.failure.message
123693
+ code: safeChunk.reason.failure.code,
123694
+ message: safeChunk.reason.failure.message
122918
123695
  }
122919
- } : { reason: chunk.reason.kind };
123696
+ } : { reason: safeChunk.reason.kind };
122920
123697
  break;
122921
123698
  }
122922
123699
  }
122923
123700
  if (active2.finished === void 0) active2.finished = { reason: "stop" };
122924
123701
  } catch (error62) {
122925
- const code = "INTERNAL_ERROR";
123702
+ const failure4 = safeProviderFailure(error62);
122926
123703
  active2.finished = {
122927
123704
  reason: "error",
122928
- failure: {
122929
- code,
122930
- message: error62 instanceof Error ? error62.message.slice(0, 500) : "The Host could not run this model call."
122931
- }
123705
+ failure: failure4
122932
123706
  };
122933
- this.logger?.warn("model-share: stream failed", { streamId: active2.streamId, reason: code });
123707
+ this.logger?.warn("model-share: stream failed", { streamId: active2.streamId, reason: failure4.code });
122934
123708
  } finally {
123709
+ this.concurrency.active = Math.max(0, this.concurrency.active - 1);
122935
123710
  this.wake(active2);
122936
123711
  }
122937
123712
  }
@@ -122939,6 +123714,14 @@ var ModelShareHost = class {
122939
123714
  const waiters = active2.notify.splice(0, active2.notify.length);
122940
123715
  for (const waiter of waiters) waiter();
122941
123716
  }
123717
+ renewLease(active2) {
123718
+ if (active2.lease !== void 0) clearTimeout(active2.lease);
123719
+ active2.lease = setTimeout(() => {
123720
+ active2.abort.abort();
123721
+ this.release(active2.streamId);
123722
+ }, STREAM_IDLE_MS);
123723
+ active2.lease.unref?.();
123724
+ }
122942
123725
  /** `model.share.chunk` — drain whatever the local model produced so far. */
122943
123726
  async drain(deviceId, params) {
122944
123727
  const request2 = chunkRequestSchema.parse(params);
@@ -122946,10 +123729,12 @@ var ModelShareHost = class {
122946
123729
  if (active2 === void 0 || active2.deviceId !== deviceId) {
122947
123730
  return { streamId: request2.streamId, chunks: [], done: true, finished: { reason: "cancelled" } };
122948
123731
  }
123732
+ this.renewLease(active2);
122949
123733
  if (active2.chunks.length === 0 && active2.finished === void 0 && (request2.waitMs ?? 0) > 0) {
122950
123734
  await this.waitForChunks(active2, request2.waitMs ?? 0);
122951
123735
  }
122952
123736
  const chunks = active2.chunks.splice(0, active2.chunks.length);
123737
+ active2.bufferedBytes = 0;
122953
123738
  const finished = active2.finished;
122954
123739
  if (finished !== void 0 && active2.chunks.length === 0) {
122955
123740
  this.release(active2.streamId);
@@ -122978,6 +123763,8 @@ var ModelShareHost = class {
122978
123763
  /** `model.share.close` — cancel and release. Idempotent. */
122979
123764
  async close(deviceId, params) {
122980
123765
  const request2 = closeRequestSchema.parse(params);
123766
+ const pending = this.pending.get(request2.streamId);
123767
+ if (pending?.deviceId === deviceId) pending.abort.abort();
122981
123768
  const active2 = this.streams.get(request2.streamId);
122982
123769
  if (active2 !== void 0 && active2.deviceId === deviceId) {
122983
123770
  active2.abort.abort();
@@ -122989,7 +123776,8 @@ var ModelShareHost = class {
122989
123776
  const active2 = this.streams.get(streamId);
122990
123777
  if (active2 === void 0) return;
122991
123778
  this.streams.delete(streamId);
122992
- this.activeCount = Math.max(0, this.activeCount - 1);
123779
+ if (active2.lease !== void 0) clearTimeout(active2.lease);
123780
+ this.concurrency.retained = Math.max(0, (this.concurrency.retained ?? 0) - 1);
122993
123781
  this.wake(active2);
122994
123782
  this.logger?.info("model-share: stream released", {
122995
123783
  streamId,
@@ -122998,6 +123786,7 @@ var ModelShareHost = class {
122998
123786
  }
122999
123787
  /** Drop every stream when the connection or the plugin goes away. */
123000
123788
  closeAll() {
123789
+ for (const pending of this.pending.values()) pending.abort.abort();
123001
123790
  for (const streamId of [...this.streams.keys()]) {
123002
123791
  this.streams.get(streamId)?.abort.abort();
123003
123792
  this.release(streamId);
@@ -126955,6 +127744,49 @@ var BORROW_CODES = {
126955
127744
  /** The Host reported no such stream (already closed / server restarted). */
126956
127745
  STREAM_GONE: "BORROW_STREAM_GONE"
126957
127746
  };
127747
+ function explainProviderFailure(code, hostName, hostId) {
127748
+ const host = hostLabel(hostName, hostId);
127749
+ let guidance;
127750
+ switch (code) {
127751
+ case MODEL_SHARE_FAILURE_CODES.AUTH:
127752
+ case "AUTH":
127753
+ case "HTTP_401":
127754
+ case "HTTP_403":
127755
+ guidance = "\u8BF7\u5BF9\u65B9\u68C0\u67E5\u8BE5 provider \u7684\u767B\u5F55\u72B6\u6001\u548C\u51ED\u636E\u3002";
127756
+ break;
127757
+ case MODEL_SHARE_FAILURE_CODES.QUOTA:
127758
+ case "QUOTA":
127759
+ case "ACCOUNT_QUOTA":
127760
+ guidance = "\u8BF7\u5BF9\u65B9\u68C0\u67E5\u8BE5 provider \u8D26\u53F7\u7684\u989D\u5EA6\u6216\u4F59\u989D\u3002";
127761
+ break;
127762
+ case MODEL_SHARE_FAILURE_CODES.RATE_LIMIT:
127763
+ case "RATE_LIMIT":
127764
+ case "HTTP_429":
127765
+ guidance = "\u5BF9\u65B9\u7684 provider \u6682\u65F6\u9650\u5236\u4E86\u8BF7\u6C42\u9891\u7387\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002";
127766
+ break;
127767
+ case MODEL_SHARE_FAILURE_CODES.CONTEXT:
127768
+ case "CONTEXT_WINDOW_EXCEEDED":
127769
+ guidance = "\u8BF7\u6C42\u5185\u5BB9\u8D85\u8FC7\u4E86\u8BE5\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u9650\u5236\uFF0C\u8BF7\u538B\u7F29\u6216\u7F29\u77ED\u5BF9\u8BDD\u540E\u91CD\u8BD5\u3002";
127770
+ break;
127771
+ case MODEL_SHARE_FAILURE_CODES.MODEL_UNAVAILABLE:
127772
+ case "UNKNOWN_MODEL":
127773
+ case "MODEL_UNSUPPORTED":
127774
+ guidance = "\u8BF7\u5BF9\u65B9\u68C0\u67E5\u8BE5\u6A21\u578B\u662F\u5426\u4ECD\u53EF\u7528\u5E76\u5237\u65B0\u5171\u4EAB\u76EE\u5F55\u3002";
127775
+ break;
127776
+ case MODEL_SHARE_FAILURE_CODES.PROVIDER_UNAVAILABLE:
127777
+ case "TIMEOUT":
127778
+ case "TRANSPORT":
127779
+ case "SERVER":
127780
+ guidance = "\u5BF9\u65B9\u7684 provider \u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5BF9\u65B9\u68C0\u67E5\u7F51\u7EDC\u548C\u670D\u52A1\u72B6\u6001\u3002";
127781
+ break;
127782
+ case MODEL_SHARE_FAILURE_CODES.BUFFER_LIMIT:
127783
+ guidance = "\u54CD\u5E94\u4EA7\u751F\u8FC7\u5FEB\uFF0C\u8D85\u51FA\u4E86\u501F\u7528\u6D41\u7684\u7F13\u51B2\u4E0A\u9650\uFF1B\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002";
127784
+ break;
127785
+ default:
127786
+ guidance = "\u8BF7\u5BF9\u65B9\u68C0\u67E5\u6A21\u578B\u4E0E provider \u7684\u72B6\u6001\u540E\u91CD\u8BD5\u3002";
127787
+ }
127788
+ return { code: BORROW_CODES.HOST_FAILED, message: `\u300C${host}\u300D\u4EE3\u4E3A\u8C03\u7528\u6A21\u578B\u65F6\u5931\u8D25\u3002${guidance}` };
127789
+ }
126958
127790
  function hostLabel(hostName, hostId) {
126959
127791
  const name2 = hostName.trim();
126960
127792
  return name2 === "" ? hostId : name2;
@@ -126964,6 +127796,9 @@ function explainHostRejection(error62, hostName, hostId, modelId) {
126964
127796
  const remoteCode = error62?.code;
126965
127797
  const detail = error62 instanceof Error ? error62.message : typeof error62 === "string" ? error62 : "";
126966
127798
  const lower = detail.toLowerCase();
127799
+ if (["TRANSPORT_CLOSED", "CLIENT_CLOSED", "RPC_TIMEOUT", "CONNECTION_FAILED", "CONNECTION_REPLACED", "CANCELLED", "TIMEOUT", "ECONNRESET", "ETIMEDOUT", "EHOSTUNREACH", "ENOTFOUND"].includes(typeof remoteCode === "string" ? remoteCode : "") || lower.includes("cannot start after the remote client closed") || lower.includes("client closed") || lower.includes("socket hang up")) {
127800
+ return explainNotConnected(hostName, hostId);
127801
+ }
126967
127802
  if (remoteCode === "PERMISSION_DENIED" || lower.includes("not lent to this device")) {
126968
127803
  return {
126969
127804
  code: BORROW_CODES.NOT_LENT,
@@ -126988,11 +127823,7 @@ function explainHostRejection(error62, hostName, hostId, modelId) {
126988
127823
  message: `\u300C${host}\u300D\u7684\u63D2\u4EF6\u7248\u672C\u8F83\u65E7\uFF0C\u4E0D\u652F\u6301\u6A21\u578B\u501F\u7528\u3002\u8BF7\u628A\u5BF9\u65B9\u8BBE\u5907\u7684 @musdrop/ds-harness-remote \u5347\u7EA7\u5230\u4E0E\u4F60\u8FD9\u53F0\u76F8\u540C\u7684\u7248\u672C\u3002`
126989
127824
  };
126990
127825
  }
126991
- const suffix = detail === "" ? "" : `\uFF1A${detail}`;
126992
- return {
126993
- code: BORROW_CODES.HOST_FAILED,
126994
- message: `\u300C${host}\u300D\u4EE3\u4E3A\u8C03\u7528\u6A21\u578B\u65F6\u5931\u8D25\uFF08${modelId}\uFF09${suffix}\u3002\u95EE\u9898\u51FA\u5728\u5BF9\u65B9\u7684 provider \u6216\u5176\u8D26\u53F7\u72B6\u6001\uFF0C\u4E0D\u662F\u4F60\u672C\u673A\u7684\u914D\u7F6E\u3002`
126995
- };
127826
+ return explainProviderFailure(remoteCode, hostName, hostId);
126996
127827
  }
126997
127828
  function explainNotConnected(hostName, hostId) {
126998
127829
  const host = hostLabel(hostName, hostId);
@@ -127014,6 +127845,13 @@ function explainTransportFailure(error62, hostName, hostId) {
127014
127845
  message: `\u501F\u7528\u300C${host}\u300D\u7684\u6A21\u578B\u65F6\u8FDE\u63A5\u4E2D\u65AD${suffix}\u3002\u56DE\u590D\u53EF\u80FD\u5DF2\u88AB\u622A\u65AD\uFF1B\u91CD\u53D1\u8FD9\u6761\u6D88\u606F\u5373\u53EF\uFF0C\u63D2\u4EF6\u4F1A\u4E3A\u4E0B\u4E00\u6B21\u8BF7\u6C42\u91CD\u5EFA\u8FDE\u63A5\u3002`
127015
127846
  };
127016
127847
  }
127848
+ function explainStreamGone(hostName, hostId) {
127849
+ const host = hostLabel(hostName, hostId);
127850
+ return {
127851
+ code: BORROW_CODES.STREAM_GONE,
127852
+ message: `\u300C${host}\u300D\u4E0A\u7684\u8FD9\u6B21\u8BF7\u6C42\u5DF2\u4E0D\u5B58\u5728\uFF08\u5BF9\u65B9\u53EF\u80FD\u91CD\u542F\u4E86 DSH \u6216\u8BE5\u8BF7\u6C42\u5DF2\u8D85\u65F6\uFF09\u3002\u91CD\u53D1\u8FD9\u6761\u6D88\u606F\u4F1A\u91CD\u65B0\u53D1\u8D77\u4E00\u6B21\u501F\u7528\u8BF7\u6C42\u3002`
127853
+ };
127854
+ }
127017
127855
  function explainModelGone(hostName, hostId, modelId) {
127018
127856
  const host = hostLabel(hostName, hostId);
127019
127857
  return {
@@ -127108,31 +127946,48 @@ var RemoteModelAdapter = class extends LlmAdapter {
127108
127946
  }
127109
127947
  const streamId = nextStreamId();
127110
127948
  const signal = options.signal;
127949
+ let aborted2 = signal?.aborted === true;
127950
+ let opened = false;
127951
+ const onAbort = () => {
127952
+ aborted2 = true;
127953
+ if (opened) void this.transport.close(streamId).catch(() => void 0);
127954
+ };
127955
+ if (aborted2) {
127956
+ yield { type: "finish", reason: { kind: "aborted", failure: { code: "ABORTED", message: "The call was cancelled by the borrower." } } };
127957
+ return;
127958
+ }
127959
+ signal?.addEventListener("abort", onAbort, { once: true });
127111
127960
  try {
127112
127961
  await this.transport.open({
127113
127962
  modelId: route,
127114
127963
  streamId,
127115
127964
  messages: options.messages,
127965
+ ...options.system === void 0 ? {} : { system: options.system },
127116
127966
  ...options.tools === void 0 ? {} : { tools: options.tools },
127117
127967
  ...options.temperature === void 0 ? {} : { temperature: options.temperature },
127118
127968
  ...options.maxTokens === void 0 ? {} : { maxTokens: options.maxTokens },
127969
+ ...options.stop === void 0 ? {} : { stop: options.stop },
127119
127970
  ...options.reasoningEffort === void 0 ? {} : { reasoningEffort: options.reasoningEffort }
127120
127971
  });
127972
+ opened = true;
127121
127973
  } catch (error62) {
127974
+ signal?.removeEventListener("abort", onAbort);
127975
+ if (aborted2) {
127976
+ yield { type: "finish", reason: { kind: "aborted", failure: { code: "ABORTED", message: "The call was cancelled by the borrower." } } };
127977
+ return;
127978
+ }
127122
127979
  this.transport.onStale?.("model-missing");
127123
127980
  const failure4 = explainHostRejection(error62, this.transport.hostName, this.transport.hostId, route);
127124
127981
  yield failureChunk(failure4.code, failure4.message);
127125
127982
  return;
127126
127983
  }
127127
- let aborted2 = false;
127128
- const onAbort = () => {
127129
- aborted2 = true;
127130
- void this.transport.close(streamId).catch(() => void 0);
127131
- };
127132
- signal?.addEventListener("abort", onAbort, { once: true });
127133
127984
  try {
127134
127985
  for (; ; ) {
127135
127986
  if (aborted2) {
127987
+ if (opened) {
127988
+ await this.transport.close(streamId).catch(() => void 0);
127989
+ opened = false;
127990
+ }
127136
127991
  yield {
127137
127992
  type: "finish",
127138
127993
  reason: { kind: "aborted", failure: { code: "ABORTED", message: "The call was cancelled by the borrower." } }
@@ -127143,38 +127998,46 @@ var RemoteModelAdapter = class extends LlmAdapter {
127143
127998
  try {
127144
127999
  batch = await this.transport.drain(streamId, 2e4);
127145
128000
  } catch (error62) {
128001
+ if (aborted2) continue;
127146
128002
  this.transport.onStale?.("connection-failed");
127147
128003
  const failure4 = explainTransportFailure(error62, this.transport.hostName, this.transport.hostId);
127148
128004
  yield failureChunk(failure4.code, failure4.message);
127149
128005
  return;
127150
128006
  }
128007
+ if (aborted2) continue;
128008
+ let terminalSeen = false;
127151
128009
  for (const chunk of batch.chunks) {
127152
128010
  if (chunk !== null && typeof chunk === "object" && chunk.type === "finish") {
128011
+ terminalSeen = true;
127153
128012
  const reason = chunk.reason;
127154
- if (reason?.kind === "error" && reason.failure !== void 0) {
127155
- const host = this.transport.hostName.trim() === "" ? this.transport.hostId : this.transport.hostName;
127156
- const original = reason.failure.message ?? "";
127157
- yield {
127158
- type: "finish",
127159
- reason: {
127160
- kind: "error",
127161
- failure: {
127162
- code: BORROW_CODES.HOST_FAILED,
127163
- message: `\u300C${host}\u300D\u4EE3\u4E3A\u8C03\u7528\u6A21\u578B\u65F6\u5931\u8D25\uFF1A${original === "" ? "\u5BF9\u65B9\u672A\u63D0\u4F9B\u5177\u4F53\u539F\u56E0" : original}`
127164
- }
127165
- }
127166
- };
128013
+ if (reason?.kind === "error") {
128014
+ const failure4 = explainProviderFailure(reason.failure?.code, this.transport.hostName, this.transport.hostId);
128015
+ yield failureChunk(failure4.code, failure4.message);
128016
+ continue;
128017
+ }
128018
+ if (reason?.kind === "aborted") {
128019
+ yield { type: "finish", reason: { kind: "aborted", failure: { code: "ABORTED", message: "The lending Host cancelled the model call." } } };
127167
128020
  continue;
127168
128021
  }
127169
128022
  }
127170
128023
  yield chunk;
127171
128024
  }
127172
128025
  if (batch.finished !== void 0) {
128026
+ if (batch.finished.reason === "cancelled" && !terminalSeen && !aborted2) {
128027
+ const failure4 = explainStreamGone(this.transport.hostName, this.transport.hostId);
128028
+ yield failureChunk(failure4.code, failure4.message);
128029
+ }
127173
128030
  if (batch.finished.reason === "error") {
128031
+ const reportedCode = batch.finished.failure?.code;
128032
+ const safeCode = Object.values(MODEL_SHARE_FAILURE_CODES).some((code) => code === reportedCode) ? reportedCode : MODEL_SHARE_FAILURE_CODES.FAILED;
127174
128033
  this.logger?.warn("model-share: borrower stream failed on the Host", {
127175
128034
  hostId: this.transport.hostId,
127176
- code: batch.finished.failure?.code ?? "INTERNAL_ERROR"
128035
+ code: safeCode
127177
128036
  });
128037
+ if (!terminalSeen) {
128038
+ const failure4 = explainProviderFailure(batch.finished.failure?.code, this.transport.hostName, this.transport.hostId);
128039
+ yield failureChunk(failure4.code, failure4.message);
128040
+ }
127178
128041
  }
127179
128042
  return;
127180
128043
  }
@@ -127182,7 +128045,7 @@ var RemoteModelAdapter = class extends LlmAdapter {
127182
128045
  }
127183
128046
  } finally {
127184
128047
  signal?.removeEventListener("abort", onAbort);
127185
- void this.transport.close(streamId).catch(() => void 0);
128048
+ if (opened) void this.transport.close(streamId).catch(() => void 0);
127186
128049
  }
127187
128050
  }
127188
128051
  };
@@ -127192,6 +128055,11 @@ function providerIdForHost(hostId) {
127192
128055
  const slug = hostId.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
127193
128056
  return `remote-${slug === "" ? "host" : slug}`;
127194
128057
  }
128058
+ var MODEL_SHARE_SYNC_OK_MS = 6e4;
128059
+ var MODEL_SHARE_SYNC_RETRY_MS = 15e3;
128060
+ function modelShareSyncDue(last, successful, now) {
128061
+ return last === void 0 || now - last >= (successful === false ? MODEL_SHARE_SYNC_RETRY_MS : MODEL_SHARE_SYNC_OK_MS);
128062
+ }
127195
128063
  var BorrowerRuntime = class {
127196
128064
  constructor(llm, store, logger2) {
127197
128065
  this.llm = llm;
@@ -127230,7 +128098,7 @@ var BorrowerRuntime = class {
127230
128098
  } catch (error62) {
127231
128099
  this.logger?.warn("model-share: model list failed, withdrawing provider", {
127232
128100
  hostId,
127233
- reason: error62 instanceof Error ? error62.name : "unknown"
128101
+ reason: "unavailable"
127234
128102
  });
127235
128103
  this.states.set(hostId, { outcome: "failed", error: error62 instanceof Error ? error62.message : String(error62) });
127236
128104
  this.unregister(hostId);
@@ -127278,39 +128146,75 @@ var BorrowerRuntime = class {
127278
128146
  if (changed) {
127279
128147
  try {
127280
128148
  existing.handle.replace([providerId]);
127281
- } catch (error62) {
128149
+ } catch {
127282
128150
  this.logger?.warn("model-share: catalog republish failed", {
127283
128151
  hostId,
127284
- reason: error62 instanceof Error ? error62.message : "unknown"
128152
+ reason: "unavailable"
127285
128153
  });
127286
128154
  }
127287
128155
  }
127288
128156
  if (existing.transport !== transport) {
127289
- if (existing.transport?.release !== transport.release) {
127290
- try {
127291
- existing.transport?.release?.();
128157
+ if (existing.transport !== void 0 && existing.transport.release !== transport.release) {
128158
+ const previous = existing.transport;
128159
+ if ([...existing.holder.streams.values()].some((link3) => link3.release === previous.release)) existing.holder.retired.add(previous);
128160
+ else try {
128161
+ previous.release?.();
127292
128162
  } catch {
127293
128163
  }
127294
128164
  }
127295
128165
  existing.transport = transport;
128166
+ existing.holder.current = transport;
127296
128167
  }
127297
128168
  this.states.set(hostId, { outcome: "registered" });
127298
128169
  return;
127299
128170
  }
127300
- const holder = { models: [...selected] };
128171
+ const holder = { models: [...selected], current: transport, streams: /* @__PURE__ */ new Map(), retired: /* @__PURE__ */ new Set() };
128172
+ const releaseRetired = (link3) => {
128173
+ if ([...holder.streams.values()].some((value) => value.release === link3.release)) return;
128174
+ for (const retired of holder.retired) {
128175
+ if (retired.release !== link3.release) continue;
128176
+ holder.retired.delete(retired);
128177
+ try {
128178
+ retired.release?.();
128179
+ } catch {
128180
+ }
128181
+ }
128182
+ };
127301
128183
  const adapter = new RemoteModelAdapter({
127302
128184
  hostId,
127303
- hostName,
128185
+ get hostName() {
128186
+ return holder.current.hostName;
128187
+ },
127304
128188
  // The holder is the single source of truth for the catalog: `replace()`
127305
128189
  // on the registration cannot change model metadata, so reconcile writes
127306
128190
  // the new set here and the adapter reads it on every call.
127307
128191
  models: () => holder.models,
127308
128192
  // The stale hook has to reach the adapter, not stop at the bound object:
127309
128193
  // the adapter is what notices a missing model or a dropped connection.
127310
- ...transport.onStale === void 0 ? {} : { onStale: transport.onStale },
127311
- open: (request2) => transport.open(request2),
127312
- drain: (streamId, waitMs) => transport.drain(streamId, waitMs),
127313
- close: (streamId) => transport.close(streamId)
128194
+ onStale: (reason) => holder.current.onStale?.(reason),
128195
+ open: async (request2) => {
128196
+ const link3 = holder.current;
128197
+ holder.streams.set(request2.streamId, link3);
128198
+ try {
128199
+ return await link3.open(request2);
128200
+ } catch (error62) {
128201
+ holder.streams.delete(request2.streamId);
128202
+ releaseRetired(link3);
128203
+ throw error62;
128204
+ }
128205
+ },
128206
+ drain: (streamId, waitMs) => (holder.streams.get(streamId) ?? holder.current).drain(streamId, waitMs),
128207
+ close: async (streamId) => {
128208
+ const link3 = holder.streams.get(streamId);
128209
+ holder.streams.delete(streamId);
128210
+ if (link3 !== void 0) {
128211
+ try {
128212
+ await link3.close(streamId);
128213
+ } finally {
128214
+ releaseRetired(link3);
128215
+ }
128216
+ }
128217
+ }
127314
128218
  }, this.logger);
127315
128219
  try {
127316
128220
  const handle = this.llm.registerAdapter([providerId], adapter);
@@ -127325,7 +128229,7 @@ var BorrowerRuntime = class {
127325
128229
  this.logger?.warn("model-share: provider registration failed", {
127326
128230
  hostId,
127327
128231
  providerId,
127328
- reason: error62 instanceof Error ? error62.message : "unknown"
128232
+ reason: "unavailable"
127329
128233
  });
127330
128234
  this.states.set(hostId, {
127331
128235
  outcome: "failed",
@@ -127345,6 +128249,13 @@ var BorrowerRuntime = class {
127345
128249
  existing.transport?.release?.();
127346
128250
  } catch {
127347
128251
  }
128252
+ for (const retired of existing.holder.retired) {
128253
+ try {
128254
+ retired.release?.();
128255
+ } catch {
128256
+ }
128257
+ }
128258
+ existing.holder.retired.clear();
127348
128259
  this.registered.delete(hostId);
127349
128260
  this.logger?.info("model-share: borrower provider withdrawn", { hostId });
127350
128261
  }
@@ -128759,6 +129670,7 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128759
129670
  let replacement;
128760
129671
  let controlRuntime;
128761
129672
  const modelShareBorrowers = [];
129673
+ const lendingConcurrency = { active: 0 };
128762
129674
  let borrowerSync;
128763
129675
  let borrowerSyncOnStale;
128764
129676
  let modelShareStore;
@@ -128807,7 +129719,7 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128807
129719
  const lendingFactory = modelShareEnabled ? (deviceId) => {
128808
129720
  const llm = ctx.get("llm", false);
128809
129721
  if (llm === void 0) return void 0;
128810
- return new ModelShareHost(llm, activeStore, logger2, deviceId);
129722
+ return new ModelShareHost(llm, activeStore, logger2, deviceId, lendingConcurrency);
128811
129723
  } : void 0;
128812
129724
  const nextRuntime = new HostPluginRuntime(
128813
129725
  nextConfig,
@@ -128861,8 +129773,6 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128861
129773
  modelShareBorrowers.push(borrower);
128862
129774
  const clientRuntimeForSync = nextClientRuntime;
128863
129775
  const syncTransports = /* @__PURE__ */ new Map();
128864
- const SYNC_OK_MS = 6e4;
128865
- const SYNC_RETRY_MS = 15e3;
128866
129776
  const lastSyncAt = /* @__PURE__ */ new Map();
128867
129777
  const lastSyncOk = /* @__PURE__ */ new Map();
128868
129778
  const syncBorrowed = async (force = false) => {
@@ -128878,17 +129788,14 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128878
129788
  const now = Date.now();
128879
129789
  for (const [hostId, source] of Object.entries(policy.sources)) {
128880
129790
  if (!source.enabled) continue;
128881
- const elapsed = now - (lastSyncAt.get(hostId) ?? 0);
128882
- if (!force && elapsed < (lastSyncOk.get(hostId) === false ? SYNC_RETRY_MS : SYNC_OK_MS)) continue;
129791
+ if (!force && !modelShareSyncDue(lastSyncAt.get(hostId), lastSyncOk.get(hostId), now)) continue;
128883
129792
  lastSyncAt.set(hostId, now);
128884
129793
  const deviceName = source.hostName ?? hostId;
128885
129794
  let transport = syncTransports.get(hostId);
128886
129795
  if (transport === void 0 || transport.hostName !== deviceName) {
128887
- transport?.release?.();
128888
129796
  transport = clientRuntimeForSync.createModelShareTransport(hostId, deviceName);
128889
129797
  syncTransports.set(hostId, transport);
128890
129798
  }
128891
- const before = borrower.activeHosts().includes(hostId);
128892
129799
  await borrower.refresh(hostId, deviceName, {
128893
129800
  ...transport,
128894
129801
  list: () => clientRuntimeForSync.listSharedModels(hostId),
@@ -128897,7 +129804,7 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128897
129804
  borrowerSyncOnStale?.(hostId);
128898
129805
  }
128899
129806
  }).then(() => {
128900
- lastSyncOk.set(hostId, borrower.activeHosts().includes(hostId) || before);
129807
+ lastSyncOk.set(hostId, borrower.describeBorrower().find((entry) => entry.hostId === hostId)?.outcome !== "failed");
128901
129808
  }).catch(() => {
128902
129809
  lastSyncOk.set(hostId, false);
128903
129810
  });
@@ -128910,7 +129817,7 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) {
128910
129817
  });
128911
129818
  const syncTimer = setInterval(() => {
128912
129819
  void syncBorrowed();
128913
- }, SYNC_OK_MS);
129820
+ }, MODEL_SHARE_SYNC_RETRY_MS);
128914
129821
  syncTimer.unref?.();
128915
129822
  const previousDispose = borrower.close.bind(borrower);
128916
129823
  borrower.close = () => {
@@ -129215,7 +130122,7 @@ function extractProfileFromDirectoryPath(candidate) {
129215
130122
  if (typeof candidate !== "string") return void 0;
129216
130123
  const trimmed = candidate.trim().replace(/[\\/]+$/, "");
129217
130124
  if (trimmed.length === 0) return void 0;
129218
- if (basename10(dirname13(trimmed)) === "profiles") {
130125
+ if (basename10(dirname12(trimmed)) === "profiles") {
129219
130126
  const segment = basename10(trimmed);
129220
130127
  if (segment.length > 0) return segment;
129221
130128
  }