@abelxiaoxing/cadence 2.1.5 → 2.1.6

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.
@@ -60,7 +60,8 @@ If the conversation cannot be read, Send can prepare execution but cannot infer
60
60
  Preparation failure keeps the draft; an owner may already have started, but the message was not sent.
61
61
  If the actual Send reply is lost instead, its original command is observed, never resubmitted automatically.
62
62
  Project navigation remounts only the browser client; the original owner's work continues.
63
- Browser proxy traffic keeps browser authority and the owner's own attachments, CSRF/build checks, grants and history proofs; native management routes and local-capability headers are not forwarded.
63
+ Browser proxy traffic keeps browser authority and the owner's own attachments, CSRF checks, grants and history proofs; native management routes and local-capability headers are not forwarded.
64
+ Build differences never block an authenticated page or require restarting work.
64
65
  The gateway also refuses the legacy project-level Open command, so every Send preparation is associated through the workbench instead of returning an independent backend token link.
65
66
  The gateway's token, backend cookies and native capabilities are never returned in project DTOs or stored in browser localStorage.
66
67
  Token rotation retires and detaches its exact browser attachments without cancelling admitted work.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.1.5",
3
+ "version": "2.1.6",
4
4
  "description": "Conversation-driven Pi workspace: persistent native and WebUI workflows, explicit plan approval, checks and local delivery.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,7 +16,6 @@ import { LIMITS } from "./service-contract.ts";
16
16
  export interface FeedConnection {
17
17
  attach(cwd: string): Promise<FeedClient>;
18
18
  refresh(): Promise<unknown>;
19
- compatible(): boolean;
20
19
  detach(): Promise<void>;
21
20
  forgetSuperseded?(cwd: string): boolean;
22
21
  }
@@ -243,7 +242,6 @@ class Feed {
243
242
  await this.connection.detach().catch(() => {});
244
243
  return;
245
244
  }
246
- if (!this.connection.compatible()) throw new Error("incompatible");
247
245
  this.client = client;
248
246
  }
249
247
  await this.observe(this.client);
@@ -435,9 +435,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
435
435
  if (generation !== expected) throw new ContractError("stale");
436
436
  };
437
437
  const operation = (async () => {
438
- const broken =
439
- !!connection.client &&
440
- (reattach || !connection.session || !connection.compatible());
438
+ const broken = !!connection.client && (reattach || !connection.session);
441
439
  if (connection.client && !broken) return;
442
440
  reattach = false;
443
441
  if (broken) connection.forgetSuperseded(ctx.cwd);
@@ -548,18 +546,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
548
546
  active(ctx);
549
547
  await ensureAttached(ctx);
550
548
  if (generation !== expected) throw new ContractError("stale");
551
- if (!connection.client || !connection.compatible()) {
552
- reattach = true;
553
- let stop = "its explicit stop command";
554
- try {
555
- stop = projectStopCommand(effectiveWorkspace(ctx.cwd).workspace);
556
- } catch {
557
- // The guidance keeps its generic wording.
558
- }
559
- throw new Error(
560
- `unsupported-context: the running Cadence project owner does not match this Cadence build or its WebUI assets. Nothing was started or replaced. When no accepted work is running, stop it with ${stop}; the next Cadence use starts the matching version.`,
561
- );
562
- }
549
+ if (!connection.client) throw new ContractError("unavailable");
563
550
  if (selectModel) await ensureModel(ctx);
564
551
  if (generation !== expected) throw new ContractError("stale");
565
552
  };
@@ -295,7 +295,6 @@ export function registerHistoryShell(pi: ExtensionAPI): void {
295
295
  attached = true;
296
296
  const session = connection.session;
297
297
  if (!session) throw new ContractError("unavailable");
298
- if (!connection.compatible()) ui.notify(MANAGEMENT_GUIDANCE);
299
298
  const workspace = value(await client.workspace(signal));
300
299
  current();
301
300
  if (
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245",
5
+ "63f28a34411aedbf5d88f62ce81cfb0eca9e8ed38396e731a2a01253d1287f48",
6
6
  } as const;
@@ -8,16 +8,12 @@ import { Agent, Dispatcher1Wrapper } from "undici";
8
8
  import { nativeBuild } from "./native-build.ts";
9
9
  import { ServiceCoordination } from "./service/coordination.ts";
10
10
  import { ServiceClient } from "./service-client.ts";
11
- import {
12
- ContractError,
13
- compatibleBuild,
14
- type SessionBootstrap,
15
- } from "./service-contract.ts";
11
+ import { ContractError, type SessionBootstrap } from "./service-contract.ts";
16
12
  import { HttpServiceTransport } from "./service-http-client.ts";
17
13
  import { effectiveWorkspace } from "./workspace.ts";
18
14
 
19
15
  export const MANAGEMENT_GUIDANCE =
20
- "Cadence owner absent, unavailable or incompatible. Start it with cadence start --workspace <path> (it recovers automatically from an unclean shutdown), or see what is wrong with cadence doctor --workspace <path>. Stop older Cadence sessions first. No service was started and no embedded executor is available.";
16
+ "Cadence owner absent or unavailable. Start it with cadence start --workspace <path> (it recovers automatically from an unclean shutdown), or see what is wrong with cadence doctor --workspace <path>. No service was started and no embedded executor is available.";
21
17
 
22
18
  const UNIT = "cadence.service";
23
19
  const LABEL = "com.abelxiaoxing.cadence";
@@ -249,9 +245,6 @@ export class NativeConnection {
249
245
  this.session = reply.value;
250
246
  return reply.value;
251
247
  }
252
- compatible(safety = false): boolean {
253
- return compatibleBuild(this.session?.build, nativeBuild, safety);
254
- }
255
248
  /** Forget an attachment only when the registry proves its owner instance is
256
249
  * gone: absent, stopped, or replaced by another epoch. Its slot ended with
257
250
  * that process, so no detach request is sent and a later attach may proceed.
@@ -1,4 +1,4 @@
1
- /** Compatibility is independent of authentication and of task confirmation. */
1
+ /** Build provenance for diagnostics and packaged assets, never access authority. */
2
2
  import { closed, decodeHash, oneOf } from "./core.ts";
3
3
  export interface BrowserBuild {
4
4
  sourceHash: string;
@@ -49,19 +49,3 @@ export function decodeServiceBuild(value: unknown): ServiceBuild {
49
49
  assets: decodeBrowserBuild(o.assets),
50
50
  };
51
51
  }
52
- export function compatibleBuild(
53
- server: ServiceBuild | undefined,
54
- client: ClientBuild | null,
55
- safety = false,
56
- ): boolean {
57
- return (
58
- !!server &&
59
- !!client &&
60
- client.contractHash === server.contractHash &&
61
- (safety ||
62
- (server.assets.contractHash === server.contractHash &&
63
- (client.kind === "native" ||
64
- (client.buildId === server.assets.buildId &&
65
- client.sourceHash === server.assets.sourceHash))))
66
- );
67
- }
@@ -2244,18 +2244,6 @@ function decodeBrowserBuild(value) {
2244
2244
  buildId: decodeHash(o.buildId)
2245
2245
  };
2246
2246
  }
2247
- function decodeClientBuild(value) {
2248
- const kind = oneOf(Object.getOwnPropertyDescriptor(value ?? {}, "kind")?.value, ["native", "browser"]);
2249
- const o = closed(value, kind === "native" ? ["kind", "contractHash"] : ["kind", "contractHash", "sourceHash", "buildId"]);
2250
- return kind === "native" ? { kind, contractHash: decodeHash(o.contractHash) } : {
2251
- kind,
2252
- ...decodeBrowserBuild({
2253
- contractHash: o.contractHash,
2254
- sourceHash: o.sourceHash,
2255
- buildId: o.buildId
2256
- })
2257
- };
2258
- }
2259
2247
  function decodeServiceBuild(value) {
2260
2248
  const o = closed(value, ["contractHash", "assets"]);
2261
2249
  return {
@@ -2263,9 +2251,6 @@ function decodeServiceBuild(value) {
2263
2251
  assets: decodeBrowserBuild(o.assets)
2264
2252
  };
2265
2253
  }
2266
- function compatibleBuild(server, client, safety = false) {
2267
- return !!server && !!client && client.contractHash === server.contractHash && (safety || server.assets.contractHash === server.contractHash && (client.kind === "native" || client.buildId === server.assets.buildId && client.sourceHash === server.assets.sourceHash));
2268
- }
2269
2254
  // src/service/contracts/history.ts
2270
2255
  function decodeReceipt(v) {
2271
2256
  canonicalJson(v);
@@ -10090,10 +10075,7 @@ class ActivityDiscoveryReader {
10090
10075
  const summary = decodeOwnerActivity(await o.readOwner(c, signal));
10091
10076
  if (signal.aborted)
10092
10077
  return;
10093
- if (summary.epoch !== row.epoch || c.localAccess().epoch !== row.epoch || !compatibleBuild(summary.build, {
10094
- kind: "native",
10095
- contractHash: o.build.contractHash
10096
- }))
10078
+ if (summary.epoch !== row.epoch || c.localAccess().epoch !== row.epoch)
10097
10079
  throw new Error;
10098
10080
  if (summary.activities.some((activity2) => activity2.epoch !== row.epoch || activity2.source === "terminal"))
10099
10081
  throw new Error("invalid-attribution");
@@ -16267,7 +16249,7 @@ Content-Length: 0\r
16267
16249
  this.attachments.set(attachmentId, attachment);
16268
16250
  }
16269
16251
  res.setHeader("X-Cadence-Attachment", attachmentId);
16270
- } else if (route.source === "body")
16252
+ } else if (route.source === "body" && (route.operation !== "detach" || this.attachments.has(attachmentId)))
16271
16253
  attachment = this.attachment(caller);
16272
16254
  const input = route.source === "body" ? await this.body(req, abort.signal) : route.input === null ? null : parseWireJson(route.input);
16273
16255
  if (route.source !== "body" && (req.headers["content-encoding"] !== undefined || req.headers["transfer-encoding"] || req.headers["content-length"] && req.headers["content-length"] !== "0"))
@@ -16276,26 +16258,14 @@ Content-Length: 0\r
16276
16258
  this.options.auth.current(caller);
16277
16259
  if (abort.signal.aborted || !this.accepting)
16278
16260
  unavailable();
16279
- if (attachment && this.attachment(caller) !== attachment)
16261
+ if (attachment && route.operation !== "detach" && this.attachment(caller) !== attachment)
16280
16262
  throw new ContractError("stale");
16281
16263
  if (route.operation === "export" || route.operation === "download") {
16282
16264
  await this.export(route.operation, input, caller, abort.signal, res, resetIdle);
16283
16265
  return;
16284
16266
  }
16285
- const rawBuild = boundary.headers.get("x-cadence-build");
16286
- const clientBuild = rawBuild === undefined ? null : decodeClientBuild(parseWireJson(rawBuild, 1024));
16287
- if (caller.authority === "browser" && clientBuild?.kind === "native")
16288
- throw new ContractError("forbidden");
16289
- if ([
16290
- "preflight",
16291
- "command",
16292
- "chooseModel",
16293
- "cancel",
16294
- "workbenchCommand"
16295
- ].includes(route.operation) && !compatibleBuild(this.options.build, clientBuild, route.operation === "cancel" || route.operation === "workbenchCommand" && decodeWorkbenchCommand(input).kind === "interrupt"))
16296
- throw new ContractError("unsupported-context");
16297
16267
  dispatched = route.operation === "command" || route.operation === "cancel" || route.operation === "chooseModel" || route.operation === "workbenchCommand";
16298
- const value = await this.dispatch(route.operation, input, caller, abort.signal, clientBuild);
16268
+ const value = await this.dispatch(route.operation, input, caller, abort.signal);
16299
16269
  this.options.auth.current(caller);
16300
16270
  if (abort.signal.aborted)
16301
16271
  unavailable();
@@ -16373,7 +16343,7 @@ Content-Length: 0\r
16373
16343
  const value = this.options.management.invoke(operation);
16374
16344
  send(res, 200, { kind: "ok", value });
16375
16345
  }
16376
- async dispatch(operation, input, caller, signal, build2) {
16346
+ async dispatch(operation, input, caller, signal) {
16377
16347
  const a = this.options.adapters, p = a.projection;
16378
16348
  switch (operation) {
16379
16349
  case "workbenchRead":
@@ -16424,7 +16394,8 @@ Content-Length: 0\r
16424
16394
  value: a.modelChoice.choose(decodeChooseModelRequest(input))
16425
16395
  };
16426
16396
  case "detach":
16427
- this.detach(this.attachment(caller));
16397
+ if (this.attachments.has(caller.attachmentId))
16398
+ this.detach(this.attachment(caller));
16428
16399
  return { kind: "ok", value: null };
16429
16400
  case "preflight":
16430
16401
  case "command":
@@ -16451,7 +16422,7 @@ Content-Length: 0\r
16451
16422
  authority: caller.authority,
16452
16423
  csrf: caller.authority === "browser" ? this.options.auth.csrf : null,
16453
16424
  capabilities: {
16454
- actions: original.capabilities.actions && !!a.workbench && compatibleBuild(this.options.build, build2),
16425
+ actions: original.capabilities.actions && !!a.workbench,
16455
16426
  manualChecks: false,
16456
16427
  history: original.capabilities.history
16457
16428
  }
@@ -16960,7 +16931,7 @@ async function createGateway(value, hostUrl, source) {
16960
16931
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
16961
16932
  const web = loadWebAssets(source?.webDirectory);
16962
16933
  const build2 = {
16963
- contractHash: "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245",
16934
+ contractHash: "63f28a34411aedbf5d88f62ce81cfb0eca9e8ed38396e731a2a01253d1287f48",
16964
16935
  assets: {
16965
16936
  sourceHash: web.manifest.sourceHash,
16966
16937
  contractHash: web.manifest.contractHash,
@@ -17075,7 +17046,6 @@ Content-Length: 0\r
17075
17046
  stateHome: input.stateHome,
17076
17047
  agentDir: input.agentDir,
17077
17048
  epoch: auth.epoch,
17078
- build: build2,
17079
17049
  readOwner: (c, signal) => nativeCall(c, "activity", false, undefined, signal),
17080
17050
  secrets: () => acquired.access.redactionLiterals()
17081
17051
  });
@@ -17175,11 +17145,6 @@ Content-Length: 0\r
17175
17145
  requesting = false;
17176
17146
  }
17177
17147
  }
17178
- function browserBuild(boundary) {
17179
- const clientBuild = decodeClientBuild(parseWireJson(boundary.headers.get("x-cadence-build") ?? "null", 1024));
17180
- if (clientBuild.kind !== "browser" || !compatibleBuild(build2, clientBuild))
17181
- throw new ContractError("unsupported-context");
17182
- }
17183
17148
  function select(path, epoch) {
17184
17149
  assert();
17185
17150
  if (epoch !== auth.epoch)
@@ -17336,7 +17301,12 @@ Content-Length: 0\r
17336
17301
  throw new ContractError("stale");
17337
17302
  return { project, endpoint: local.endpoint, cookie };
17338
17303
  })();
17339
- bindings.set(id, { epoch: local.epoch, result });
17304
+ const pending2 = { epoch: local.epoch, result };
17305
+ bindings.set(id, pending2);
17306
+ result.catch(() => {
17307
+ if (bindings.get(id) === pending2)
17308
+ bindings.delete(id);
17309
+ });
17340
17310
  return result;
17341
17311
  }
17342
17312
  function stop() {
@@ -17523,9 +17493,9 @@ Content-Length: 0\r
17523
17493
  if (route2.operation === "session" && !store.associatedProjects().some((p) => p.id === project.id))
17524
17494
  throw new ContractError("unavailable");
17525
17495
  const attachment = boundary.headers.get("x-cadence-attachment");
17526
- if (attachment && attachments.get(attachment)?.projectId !== project.id || req.method === "POST" && !attachment)
17496
+ if (attachment && (attachments.has(attachment) ? attachments.get(attachment)?.projectId !== project.id : route2.operation !== "session") || req.method === "POST" && !attachment)
17527
17497
  throw new ContractError("stale");
17528
- if (route2.operation === "session" && !attachment && attachments.size >= 2048)
17498
+ if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048)
17529
17499
  throw new ContractError("capacity");
17530
17500
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
17531
17501
  throw new ContractError("forbidden");
@@ -17665,7 +17635,6 @@ Content-Length: 0\r
17665
17635
  return;
17666
17636
  }
17667
17637
  if (url.pathname === "/workbench/v1/models" && req.method === "GET") {
17668
- browserBuild(boundary);
17669
17638
  const keys2 = [...url.searchParams.keys()];
17670
17639
  if (keys2.length && (keys2.length !== 1 || keys2[0] !== "project"))
17671
17640
  throw new ContractError("invalid");
@@ -17680,7 +17649,6 @@ Content-Length: 0\r
17680
17649
  return;
17681
17650
  }
17682
17651
  if (raw === "/workbench/v1/activity" && req.method === "GET") {
17683
- browserBuild(boundary);
17684
17652
  const value2 = await activity2.read();
17685
17653
  auth.current(caller);
17686
17654
  assert();
@@ -17717,7 +17685,6 @@ Content-Length: 0\r
17717
17685
  return;
17718
17686
  }
17719
17687
  if (raw === "/workbench/v1/service" && req.method === "POST") {
17720
- browserBuild(boundary);
17721
17688
  const value2 = await body(req);
17722
17689
  auth.current(caller);
17723
17690
  const job2 = await requestJob(value2, () => auth.current(caller));
@@ -17725,7 +17692,6 @@ Content-Length: 0\r
17725
17692
  return;
17726
17693
  }
17727
17694
  if (raw === "/workbench/v1/select" && req.method === "POST") {
17728
- browserBuild(boundary);
17729
17695
  const o = closed(await body(req), ["path", "epoch"]);
17730
17696
  const path = text(o.path, 4096, true), epoch = decodeId(o.epoch);
17731
17697
  auth.current(caller);
@@ -17734,7 +17700,6 @@ Content-Length: 0\r
17734
17700
  return;
17735
17701
  }
17736
17702
  if (raw === "/workbench/v1/prepare-send" && req.method === "POST") {
17737
- browserBuild(boundary);
17738
17703
  const value2 = await body(req);
17739
17704
  const o = closed(value2, [
17740
17705
  "commandId",
@@ -34218,8 +34183,8 @@ function workflowResultDetail(value, secrets) {
34218
34183
  var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
34219
34184
  ${RUN_ENVIRONMENT_POLICY}`;
34220
34185
  var OWNER_RUNTIME = Object.freeze({
34221
- version: "2.1.5",
34222
- build: "f394594500c6c18cd7ae0d307db53bbfbf13f988bfd92f5e3ca1bbc15b0d5e91",
34186
+ version: "2.1.6",
34187
+ build: "466def18bdfec1faaf999049b38e5cb08ae6861f57b1847aea4144d1d2180551",
34223
34188
  entry: fileURLToPath7(import.meta.url),
34224
34189
  pid: process.pid,
34225
34190
  node: process.versions.node,
@@ -37063,7 +37028,7 @@ var processLifetime = {
37063
37028
  }
37064
37029
  };
37065
37030
  async function createServiceHost(value, sourceBuild, lifetime) {
37066
- const embedded = "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245";
37031
+ const embedded = "63f28a34411aedbf5d88f62ce81cfb0eca9e8ed38396e731a2a01253d1287f48";
37067
37032
  if (embedded && sourceBuild)
37068
37033
  throw new ContractError("unsupported-context");
37069
37034
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -70,6 +70,7 @@ export class HttpServiceTransport implements ServiceTransport {
70
70
  origin: string;
71
71
  /** Authenticated same-origin project routing; never an arbitrary URL. */
72
72
  project?: string;
73
+ /** Diagnostic metadata only; authentication never depends on a build. */
73
74
  build?: ClientBuild;
74
75
  fetch?: typeof fetch;
75
76
  /** Optional total bound for finite replies only, never streaming export. */
@@ -105,11 +106,12 @@ export class HttpServiceTransport implements ServiceTransport {
105
106
  workbenchCommand(request: WorkbenchCommand): Promise<unknown> {
106
107
  return this.request("workbenchCommand", request);
107
108
  }
108
- private headers(write: boolean): Record<string, string> {
109
+ private headers(write: boolean, session = false): Record<string, string> {
109
110
  const headers: Record<string, string> = { "Cache-Control": "no-store" };
110
111
  if (this.options.build)
111
112
  headers["X-Cadence-Build"] = canonicalJson(this.options.build);
112
- if (this.attachment) headers["X-Cadence-Attachment"] = this.attachment;
113
+ if (this.attachment && (write || session))
114
+ headers["X-Cadence-Attachment"] = this.attachment;
113
115
  if (this.options.localCapability)
114
116
  headers["X-Cadence-Local"] = this.options.localCapability;
115
117
  if (write) {
@@ -128,8 +130,8 @@ export class HttpServiceTransport implements ServiceTransport {
128
130
  const input = decodeHttpInput(operation, value),
129
131
  wire = wireRequest(operation, input),
130
132
  write = wire.method === "POST";
131
- // No automatic session/preflight refresh, changed command ID, mutation retry,
132
- // credential query or redirect follow after an uncertain HTTP outcome.
133
+ // No command replay, preflight renewal, changed command ID or redirect
134
+ // follow after an uncertain HTTP outcome.
133
135
  const scope =
134
136
  this.options.requestTimeoutMs === undefined
135
137
  ? undefined
@@ -137,27 +139,30 @@ export class HttpServiceTransport implements ServiceTransport {
137
139
  const requestSignal = scope?.signal ?? signal;
138
140
  try {
139
141
  if (requestSignal?.aborted) throw requestSignal.reason;
142
+ // One client-chosen observation ID survives a lost header/body. Repeating
143
+ // session reuses that slot and recovers CSRF, never a command or grant.
144
+ if (operation === "session") this.attachment ??= crypto.randomUUID();
140
145
  const response = await this.fetcher(
141
146
  `${this.origin}${this.options.project ? `/projects/${this.options.project}` : ""}${wire.path}`,
142
147
  {
143
148
  method: wire.method,
144
- headers: this.headers(write),
149
+ headers: this.headers(write, operation === "session"),
145
150
  credentials: "same-origin",
146
151
  redirect: "error",
147
152
  signal: requestSignal,
148
153
  ...(write ? { body: wire.body } : {}),
149
154
  },
150
155
  );
151
- // Keep a known allocation even if its original response body is lost or
152
- // malformed. Without a validated CSRF challenge detach may remain blocked;
153
- // never silently forget that slot and acquire 16 replacement sessions.
156
+ // Validate the reply's allocation without losing our original ID when
157
+ // its header or body is missing. A later session read can recover it.
154
158
  let sessionAttachment: string | undefined;
155
159
  try {
156
160
  if (operation === "session" && response.ok) {
157
161
  sessionAttachment = decodeId(
158
162
  response.headers.get("x-cadence-attachment"),
159
163
  );
160
- this.attachment = sessionAttachment;
164
+ if (sessionAttachment !== this.attachment)
165
+ throw new ContractError("invalid");
161
166
  }
162
167
  } catch (error) {
163
168
  await response.body?.cancel().catch(() => {});
@@ -276,19 +281,41 @@ export class HttpServiceTransport implements ServiceTransport {
276
281
  async detach(): Promise<unknown> {
277
282
  const attachment = this.attachment;
278
283
  if (!attachment) return;
284
+ // A lost session body may leave the exact allocation without its CSRF.
285
+ // Read that same ID again so departure/reconnection can release it instead
286
+ // of blocking forever or abandoning a slot. This cannot submit work.
287
+ if (!this.options.localCapability && !this.csrf) {
288
+ const session = decodeReply(await this.session(), decodeSessionBootstrap);
289
+ if (session.kind === "error") {
290
+ if (!["stale", "unauthenticated"].includes(session.error.code))
291
+ throw new ContractError(session.error.code);
292
+ if (this.attachment === attachment) this.attachment = undefined;
293
+ return session;
294
+ }
295
+ }
279
296
  const result = decodeReply(await this.request("detach", null), (value) => {
280
297
  if (value !== null) throw new ContractError("invalid");
281
298
  return null;
282
299
  });
283
300
  // A lost reply does not prove release. Retain the exact attachment for a
284
- // later explicit detach rather than allocating another of the 16 slots.
301
+ // later detach rather than allocating another of the 16 slots.
285
302
  // Stale means the server no longer owns this ID; rotation also revokes it.
286
303
  if (
287
304
  result.kind === "error" &&
288
305
  result.error.code !== "stale" &&
289
306
  result.error.code !== "unauthenticated"
290
- )
307
+ ) {
308
+ // A restarted direct owner can keep the access token but replace CSRF.
309
+ // The next detach recovers it by reading the same allocation, rather than
310
+ // repeatedly sending this refused challenge. No work command is retried.
311
+ if (
312
+ result.error.code === "forbidden" &&
313
+ !this.options.localCapability &&
314
+ this.attachment === attachment
315
+ )
316
+ this.csrf = null;
291
317
  throw new ContractError(result.error.code);
318
+ }
292
319
  if (this.attachment === attachment) {
293
320
  this.attachment = undefined;
294
321
  this.csrf = null;