zcode-acp-server 0.85.0 → 0.85.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +10 -6
  2. package/dist/backend/client.d.ts +1 -1
  3. package/dist/backend/client.d.ts.map +1 -1
  4. package/dist/backend/client.js +2 -1
  5. package/dist/backend/client.js.map +1 -1
  6. package/dist/backend/jsonrpc-child.d.ts +2 -0
  7. package/dist/backend/jsonrpc-child.d.ts.map +1 -1
  8. package/dist/backend/jsonrpc-child.js +12 -3
  9. package/dist/backend/jsonrpc-child.js.map +1 -1
  10. package/dist/backend/resolve.d.ts +8 -2
  11. package/dist/backend/resolve.d.ts.map +1 -1
  12. package/dist/backend/resolve.js +43 -6
  13. package/dist/backend/resolve.js.map +1 -1
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +11 -1
  17. package/dist/cli.js.map +1 -1
  18. package/dist/code-fingerprint.json +2 -2
  19. package/dist/config/deferred-probe-capability.d.ts +10 -0
  20. package/dist/config/deferred-probe-capability.d.ts.map +1 -0
  21. package/dist/config/deferred-probe-capability.js +100 -0
  22. package/dist/config/deferred-probe-capability.js.map +1 -0
  23. package/dist/config/initial-model-catalog.d.ts +6 -0
  24. package/dist/config/initial-model-catalog.d.ts.map +1 -0
  25. package/dist/config/initial-model-catalog.js +167 -0
  26. package/dist/config/initial-model-catalog.js.map +1 -0
  27. package/dist/config/options.d.ts +3 -0
  28. package/dist/config/options.d.ts.map +1 -1
  29. package/dist/config/options.js +75 -10
  30. package/dist/config/options.js.map +1 -1
  31. package/dist/config/runtime-model.d.ts.map +1 -1
  32. package/dist/config/runtime-model.js +18 -1
  33. package/dist/config/runtime-model.js.map +1 -1
  34. package/dist/handlers/session.d.ts +1 -1
  35. package/dist/handlers/session.d.ts.map +1 -1
  36. package/dist/handlers/session.js +142 -21
  37. package/dist/handlers/session.js.map +1 -1
  38. package/dist/index.d.ts +22 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/remote/terminal-relay.d.ts.map +1 -1
  43. package/dist/remote/terminal-relay.js +15 -6
  44. package/dist/remote/terminal-relay.js.map +1 -1
  45. package/dist/server.d.ts +17 -1
  46. package/dist/server.d.ts.map +1 -1
  47. package/dist/server.js +32 -4
  48. package/dist/server.js.map +1 -1
  49. package/docs/BACKLOG.md +45 -5
  50. package/package.json +2 -2
@@ -21,13 +21,14 @@ import { backendCapabilities } from "../backend/adapter.js";
21
21
  import { EventStreamListener, TurnMonitor } from "../backend/listener.js";
22
22
  import { disallowedToolList } from "../backend/resolve.js";
23
23
  import { resolveReal } from "../backend/sandbox.js";
24
- import { buildModes, buildConfigOptions, DEFAULT_MODEL_ID, DEFAULT_PROVIDER_ID, formatModelValue, loadAllModels, modelContextWindow, parseModelValue, } from "../config/options.js";
24
+ import { buildModes, buildConfigOptions, buildInitialConfigOptions, DEFAULT_MODEL_ID, DEFAULT_PROVIDER_ID, formatModelValue, loadAllModels, modelContextWindow, parseModelValue, } from "../config/options.js";
25
25
  import { currentModelCached, emitInitialUsage } from "../config/model-cache.js";
26
26
  import { forceRefreshQuota, scheduleQuotaDockBackstop, startQuotaRefresher, } from "../quota/live.js";
27
27
  import { noteUserActivity, pushSettled, pushSourceLabel } from "../push/push.js";
28
28
  import { buildProviderRegistry } from "../config/provider-registry.js";
29
29
  import { configProviderIdFor, pushAccountProviderConfig } from "../config/account-provider.js";
30
30
  import { initialSessionMode } from "../config/settings.js";
31
+ import { probeInitialModelCatalog } from "../config/initial-model-catalog.js";
31
32
  import { applyModelSwitch, buildResumeRuntimeModel } from "../config/runtime-model.js";
32
33
  import { effectiveWorkflowGate, effectiveWorkflowGateNow, ensureWorkflowPolicyPushed, filterWorkflowCommands, } from "../config/workflow-gate.js";
33
34
  import { messages } from "../i18n.js";
@@ -37,7 +38,7 @@ import { isClosedSessionId } from "../closed-sessions.js";
37
38
  import { buildDiffContent, EventTranslator, extractLocations, formatTurnError, isBackendLostError, isContentLiveDelivered, isGatewayBlipTurnError, isTransientTurnError, ProjectionDiffer, } from "../translators/index.js";
38
39
  import { clientConnectionRoot, log, warn, zcodeHomeDir } from "../utils.js";
39
40
  import { dispatchEvent } from "./dispatch.js";
40
- import { echoSteeredInputs, emitSessionTurnState, sendAvailableCommandsDeferred, sendSessionUpdate, sendTextChunk, withReplayBatch, } from "./io.js";
41
+ import { echoSteeredInputs, emitSessionTurnState, enqueueSessionSend, sendAvailableCommandsDeferred, sendSessionUpdate, sendTextChunk, withReplayBatch, } from "./io.js";
41
42
  import { EDIT_DIFF_READ_LIMIT, fetchMessages, fetchMessagesSinceAnchor, fullSlice, readLoadIntent, readTailLimit, REPLY_READ_LIMIT, replayMessages, sliceTail, TURN_READ, } from "./replay.js";
42
43
  import { extractPermDeniedPath, extractSandboxDenial, GENERIC_HINT_KEY, handleSandboxDenial, READ_ONLY_TOOLS, waitForSandboxBatchFlush, } from "./sandbox-allow.js";
43
44
  import { handleServerRequests } from "./server-requests.js";
@@ -46,6 +47,87 @@ function workspaceFor(cwd) {
46
47
  const p = cwd || process.cwd();
47
48
  return { workspacePath: p, workspaceKey: p };
48
49
  }
50
+ function initialCatalog(server, cwd) {
51
+ const cached = server.initialCatalogCache.get(cwd);
52
+ if (cached)
53
+ return { cached };
54
+ let flight = server.initialCatalogFlights.get(cwd);
55
+ if (!flight) {
56
+ const generation = server.backendGeneration;
57
+ flight = new Promise((resolve) => {
58
+ setImmediate(() => {
59
+ if (server.disposed || server.backendGeneration !== generation) {
60
+ resolve(null);
61
+ return;
62
+ }
63
+ void probeInitialModelCatalog(cwd).then(resolve, () => resolve(null));
64
+ });
65
+ })
66
+ .then((result) => {
67
+ const model = result?.settings?.model;
68
+ if (server.disposed ||
69
+ generation !== server.backendGeneration ||
70
+ !model?.current?.providerId ||
71
+ !model.current.modelId ||
72
+ !Array.isArray(model.available) ||
73
+ model.available.some((entry) => !entry?.ref?.providerId || !entry.ref.modelId) ||
74
+ !model.available.some((entry) => entry.ref?.providerId === model.current?.providerId &&
75
+ entry.ref?.modelId === model.current?.modelId))
76
+ return null;
77
+ server.initialCatalogCache.set(cwd, result);
78
+ return result;
79
+ })
80
+ .catch(() => null);
81
+ server.initialCatalogFlights.set(cwd, flight);
82
+ const ownedFlight = flight;
83
+ void flight.finally(() => {
84
+ if (server.initialCatalogFlights.get(cwd) === ownedFlight)
85
+ server.initialCatalogFlights.delete(cwd);
86
+ });
87
+ }
88
+ return { cached: null, flight };
89
+ }
90
+ /** Send only to the connection that adopted this still-unmodified placeholder. */
91
+ function updateInitialCatalog(server, cwd, sid, client, flight) {
92
+ if (!flight)
93
+ return;
94
+ const pending = server.pendingSessions.get(sid);
95
+ if (!pending)
96
+ return;
97
+ const generation = server.backendGeneration;
98
+ const root = clientConnectionRoot(client);
99
+ const tracked = !!client && server.clients.snapshot().some((cx) => clientConnectionRoot(cx) === root);
100
+ const valid = () => !server.disposed &&
101
+ server.backendGeneration === generation &&
102
+ server.sessionCwds.get(sid) === cwd &&
103
+ server.pendingSessions.get(sid) === pending &&
104
+ pending.cwd === cwd &&
105
+ !pending.creating &&
106
+ !server.resolveSid(sid) &&
107
+ (!tracked || server.clients.snapshot().some((cx) => clientConnectionRoot(cx) === root));
108
+ void flight.then((result) => {
109
+ if (!result || !valid())
110
+ return;
111
+ // The request handler returns synchronously after newSession. The SDK's
112
+ // response enters its per-connection write queue before this callback;
113
+ // that queue orders the update behind the response even under backpressure.
114
+ setImmediate(() => {
115
+ void (async () => {
116
+ if (!valid())
117
+ return;
118
+ const options = await buildInitialConfigOptions(server, root, result);
119
+ await enqueueSessionSend(sid, async () => {
120
+ if (!valid())
121
+ return;
122
+ await (client ?? server.clients.broadcast()).notify("session/update", {
123
+ sessionId: sid,
124
+ update: { sessionUpdate: "config_option_update", configOptions: options },
125
+ });
126
+ });
127
+ })().catch((err) => log(`initial model catalog update failed: ${String(err)}`));
128
+ });
129
+ });
130
+ }
49
131
  /**
50
132
  * A pre-3.15 backend's strict mode-enum rejection of `guarded` (zod wording:
51
133
  * "Invalid enum value. Expected 'plan' | …, received 'guarded'"). Drove the
@@ -441,11 +523,11 @@ export async function newSession(server, params, client) {
441
523
  server.lastMode.set(bindSid, modes.currentModeId);
442
524
  emitBootUsageUpdate(server, bindSid);
443
525
  scheduleQuotaDockBackstop(server);
444
- return {
445
- sessionId: bindSid,
446
- modes,
447
- configOptions: await buildConfigOptions(server, null, bindRoot),
448
- };
526
+ const cwd = server.sessionCwds.get(bindSid) ?? process.cwd();
527
+ const catalog = initialCatalog(server, cwd);
528
+ const configOptions = await buildInitialConfigOptions(server, bindRoot, catalog.cached);
529
+ updateInitialCatalog(server, cwd, bindSid, client, catalog.flight);
530
+ return { sessionId: bindSid, modes, configOptions };
449
531
  }
450
532
  const bootResume = consumeBootResumeTarget();
451
533
  if (bootResume) {
@@ -555,11 +637,10 @@ export async function newSession(server, params, client) {
555
637
  server.lastMode.set(acpSid, modes.currentModeId);
556
638
  emitBootUsageUpdate(server, acpSid);
557
639
  scheduleQuotaDockBackstop(server);
558
- return {
559
- sessionId: acpSid,
560
- modes,
561
- configOptions: await buildConfigOptions(server, null, clientConnectionRoot(client)),
562
- };
640
+ const catalog = initialCatalog(server, cwd);
641
+ const configOptions = await buildInitialConfigOptions(server, clientConnectionRoot(client), catalog.cached);
642
+ updateInitialCatalog(server, cwd, acpSid, client, catalog.flight);
643
+ return { sessionId: acpSid, modes, configOptions };
563
644
  }
564
645
  /**
565
646
  * Initial usage_update after a session/new binding (ADR-0021): martty only —
@@ -828,6 +909,7 @@ export async function ensureRealSession(server, acpSid, opts = {}) {
828
909
  // promise is stored before any concurrent caller can observe the entry.
829
910
  const creating = (async () => {
830
911
  const backend = await server.ensureBackend();
912
+ const generation = server.backendGeneration;
831
913
  // Push the provider registry BEFORE session/create: the backend resolves
832
914
  // the session's default model against the registry, and without the
833
915
  // provider's reasoning/model definitions it falls back to the bare
@@ -868,6 +950,8 @@ export async function ensureRealSession(server, acpSid, opts = {}) {
868
950
  // Compat retries build on the params ACTUALLY sent last, so a second
869
951
  // rejection does not resurrect a key the first retry already dropped.
870
952
  let sent = createParams;
953
+ if (generation !== server.backendGeneration)
954
+ throw new Error("backend generation changed during create");
871
955
  let resp = await backend.request(server.nextId(), "session/create", sent, 15000);
872
956
  if (resp.error && sent.mode === "guarded" && rejectsModeGuarded(resp.error.message)) {
873
957
  // 3.15.1's `guarded` on a pre-3.15 backend: the strict mode enum rejects
@@ -888,6 +972,8 @@ export async function ensureRealSession(server, acpSid, opts = {}) {
888
972
  if (resp.error) {
889
973
  throw new Error(`zcode create failed: ${resp.error.message ?? ""}`);
890
974
  }
975
+ if (generation !== server.backendGeneration)
976
+ throw new Error("backend generation changed during create");
891
977
  const result = (resp.result ?? {});
892
978
  const session = result.session ?? {};
893
979
  const sid = session.sessionId;
@@ -2320,8 +2406,13 @@ async function runPrompt(server, params, cx, requestId, continuationRound = fals
2320
2406
  // A failure here (evicted session, dead backend) abandons the prompt before
2321
2407
  // the send — staged files must go with it.
2322
2408
  let zcodeSid;
2409
+ const wasPending = !server.resolveSid(params.sessionId);
2323
2410
  try {
2324
2411
  zcodeSid = await ensureRealSession(server, params.sessionId);
2412
+ if (wasPending) {
2413
+ const { emitConfigOptionUpdate } = await import("../config/options.js");
2414
+ await emitConfigOptionUpdate(server, cx, params.sessionId, zcodeSid, "model").catch(() => undefined);
2415
+ }
2325
2416
  // Re-arm the session's out-of-band listeners (background tasks, backend
2326
2417
  // titles): a mid-session backend respawn (sandbox flip, dynamic allow
2327
2418
  // batches, dead-reader recovery) replaces the instance the listeners were
@@ -3080,20 +3171,32 @@ async function reassertModelChoice(server, zcodeSid) {
3080
3171
  * cache, and the object form of `session/setModel` hard-fails a level-bearing
3081
3172
  * model without one ("Reasoning level is required").
3082
3173
  *
3083
- * Best-effort: an empty or missing list leaves any previous cache intact.
3174
+ * Empty or malformed lists invalidate the cache; the backend validates switches.
3084
3175
  */
3085
3176
  export function cacheModelAvailability(server, zcodeSid, result) {
3086
3177
  const settings = result?.settings;
3087
3178
  const model = settings?.model;
3088
- const avail = model?.available ?? [];
3089
- if (avail.length === 0)
3179
+ const avail = model?.available;
3180
+ if (!Array.isArray(avail) ||
3181
+ avail.length === 0 ||
3182
+ avail.some((a) => !a ||
3183
+ typeof a.ref?.providerId !== "string" ||
3184
+ !a.ref.providerId ||
3185
+ typeof a.ref?.modelId !== "string" ||
3186
+ !a.ref.modelId)) {
3187
+ server.modelAvailability.delete(zcodeSid);
3188
+ // The identity and the snapshot are read as a pair by buildConfigOptions:
3189
+ // a surviving registry-spelling identity over a deleted snapshot appends a
3190
+ // duplicate same-named current into the local-config dropdown.
3191
+ server.currentModelIdentity.delete(zcodeSid);
3090
3192
  return;
3193
+ }
3091
3194
  server.modelAvailability.set(zcodeSid, avail.map((a) => ({
3092
3195
  providerId: a.ref?.providerId,
3093
3196
  modelId: a.ref?.modelId,
3094
3197
  defaultLevel: a.reasoning?.defaultLevel ?? a.reasoning?.levels?.[0]?.value,
3095
- levels: (a.reasoning?.levels ?? [])
3096
- .map((l) => l.value)
3198
+ levels: (Array.isArray(a.reasoning?.levels) ? a.reasoning.levels : [])
3199
+ .map((l) => l?.value)
3097
3200
  .filter((v) => typeof v === "string"),
3098
3201
  })));
3099
3202
  }
@@ -3120,17 +3223,26 @@ export function cacheModelAvailability(server, zcodeSid, result) {
3120
3223
  async function resumePreservingModel(server, zcParams, opts = {}) {
3121
3224
  const zcodeSid = String(zcParams["sessionId"] ?? "");
3122
3225
  const inFlight = server.resumeInFlight.get(zcodeSid);
3123
- if (inFlight) {
3226
+ if (inFlight && inFlight.generation === server.backendGeneration) {
3124
3227
  // Known limitation (#193): the joiner rides the performer's params as
3125
3228
  // frozen at flight start, so mcpServers the joiner just remembered are
3126
3229
  // NOT delivered by this resume. Window: only right after a bridge
3127
3230
  // restart (map empty) with two clients loading the same session; the
3128
3231
  // next eviction reload re-sends the set. Re-issuing a second resume
3129
3232
  // here would break the single-flight dehydration guarantee.
3130
- const shared = await inFlight; // rethrows the first flight's failure
3233
+ const shared = (await inFlight.promise); // rethrows the first flight's failure
3131
3234
  return { ...shared, performed: false };
3132
3235
  }
3236
+ const entry = {
3237
+ generation: server.backendGeneration,
3238
+ promise: Promise.resolve(),
3239
+ };
3133
3240
  const flight = (async () => {
3241
+ await server.ensureBackend();
3242
+ const generation = server.backendGeneration;
3243
+ // A cold spawn can advance the generation while this flight starts.
3244
+ if (server.resumeInFlight.get(zcodeSid) === entry)
3245
+ entry.generation = generation;
3134
3246
  // The backend can echo the supplied workspace in its resume snapshot.
3135
3247
  // Verify the stored record before resume itself can load foreign history.
3136
3248
  if (server.serveMode)
@@ -3140,6 +3252,8 @@ async function resumePreservingModel(server, zcParams, opts = {}) {
3140
3252
  result = await resumeBackendSession(server, zcParams);
3141
3253
  }
3142
3254
  catch (err) {
3255
+ if (generation !== server.backendGeneration)
3256
+ throw new Error("backend generation changed during resume");
3143
3257
  // A session the backend no longer stores cannot be repaired by ANY
3144
3258
  // overlay — rethrow the honest cause instead of retrying (3.12+
3145
3259
  // backends reject the runtimeModel key outright, so the retry would
@@ -3163,6 +3277,8 @@ async function resumePreservingModel(server, zcParams, opts = {}) {
3163
3277
  throw overlayErr;
3164
3278
  }
3165
3279
  }
3280
+ if (generation !== server.backendGeneration)
3281
+ throw new Error("backend generation changed during resume");
3166
3282
  // Validate in the shared flight before reading history or marking live.
3167
3283
  const backendWs = workspaceFromResumeResult(result);
3168
3284
  if (server.serveMode) {
@@ -3184,24 +3300,29 @@ async function resumePreservingModel(server, zcParams, opts = {}) {
3184
3300
  // session/read is hardcoded "current") — refresh the switch-time level
3185
3301
  // lookup for models added after create BEFORE the remembered choice
3186
3302
  // re-asserts (it resolves its level from this cache).
3303
+ if (generation !== server.backendGeneration)
3304
+ throw new Error("backend generation changed during resume");
3187
3305
  cacheModelAvailability(server, zcodeSid, result);
3188
3306
  // Re-apply the bridge-remembered model choice (best-effort — never fails
3189
3307
  // the resume): the resumed session may have silently reverted to the
3190
3308
  // workspace default when the backend's own selection entry was lost.
3191
3309
  await reassertModelChoice(server, zcodeSid);
3310
+ if (generation !== server.backendGeneration)
3311
+ throw new Error("backend generation changed during resume");
3192
3312
  return {
3193
3313
  performed: true,
3194
3314
  result,
3195
3315
  history,
3196
3316
  };
3197
3317
  })();
3198
- server.resumeInFlight.set(zcodeSid, flight);
3318
+ entry.promise = flight;
3319
+ server.resumeInFlight.set(zcodeSid, entry);
3199
3320
  try {
3200
3321
  return await flight;
3201
3322
  }
3202
3323
  finally {
3203
3324
  // Guarded delete: only the owner removes its own entry.
3204
- if (server.resumeInFlight.get(zcodeSid) === flight)
3325
+ if (server.resumeInFlight.get(zcodeSid) === entry)
3205
3326
  server.resumeInFlight.delete(zcodeSid);
3206
3327
  }
3207
3328
  }