@cotal-ai/cli 0.191.0 → 0.192.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +8 -2
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +12 -3
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/app-identity.d.ts +6 -1
  8. package/dist/commands/app-identity.d.ts.map +1 -1
  9. package/dist/commands/app-identity.js +16 -5
  10. package/dist/commands/app-identity.js.map +1 -1
  11. package/dist/commands/chat.d.ts.map +1 -1
  12. package/dist/commands/chat.js +19 -5
  13. package/dist/commands/chat.js.map +1 -1
  14. package/dist/commands/completion.d.ts.map +1 -1
  15. package/dist/commands/completion.js +3 -2
  16. package/dist/commands/completion.js.map +1 -1
  17. package/dist/commands/down-preserve.js +4 -4
  18. package/dist/commands/down-preserve.js.map +1 -1
  19. package/dist/commands/endpoint.d.ts.map +1 -1
  20. package/dist/commands/endpoint.js +2 -1
  21. package/dist/commands/endpoint.js.map +1 -1
  22. package/dist/commands/ext.d.ts +1 -0
  23. package/dist/commands/ext.d.ts.map +1 -1
  24. package/dist/commands/ext.js +133 -6
  25. package/dist/commands/ext.js.map +1 -1
  26. package/dist/commands/help.js +12 -11
  27. package/dist/commands/help.js.map +1 -1
  28. package/dist/commands/history.d.ts.map +1 -1
  29. package/dist/commands/history.js +4 -0
  30. package/dist/commands/history.js.map +1 -1
  31. package/dist/commands/send.d.ts.map +1 -1
  32. package/dist/commands/send.js +54 -31
  33. package/dist/commands/send.js.map +1 -1
  34. package/dist/commands/service-actions.d.ts.map +1 -1
  35. package/dist/commands/service-actions.js +7 -2
  36. package/dist/commands/service-actions.js.map +1 -1
  37. package/dist/commands/spawn-flags.d.ts +5 -1
  38. package/dist/commands/spawn-flags.d.ts.map +1 -1
  39. package/dist/commands/spawn-flags.js +4 -0
  40. package/dist/commands/spawn-flags.js.map +1 -1
  41. package/dist/commands/spawn-preview.d.ts.map +1 -1
  42. package/dist/commands/spawn-preview.js +15 -9
  43. package/dist/commands/spawn-preview.js.map +1 -1
  44. package/dist/commands/spawn.d.ts.map +1 -1
  45. package/dist/commands/spawn.js +3 -4
  46. package/dist/commands/spawn.js.map +1 -1
  47. package/dist/commands/stack-up.d.ts +1 -0
  48. package/dist/commands/stack-up.d.ts.map +1 -1
  49. package/dist/commands/stack-up.js +8 -4
  50. package/dist/commands/stack-up.js.map +1 -1
  51. package/dist/commands/stack-user-auth.d.ts.map +1 -1
  52. package/dist/commands/stack-user-auth.js +2 -1
  53. package/dist/commands/stack-user-auth.js.map +1 -1
  54. package/dist/commands/status-delivery.d.ts +6 -1
  55. package/dist/commands/status-delivery.d.ts.map +1 -1
  56. package/dist/commands/status-delivery.js +3 -1
  57. package/dist/commands/status-delivery.js.map +1 -1
  58. package/dist/commands/status-health.d.ts +7 -2
  59. package/dist/commands/status-health.d.ts.map +1 -1
  60. package/dist/commands/status-health.js +24 -16
  61. package/dist/commands/status-health.js.map +1 -1
  62. package/dist/commands/status-legacy.d.ts +7 -0
  63. package/dist/commands/status-legacy.d.ts.map +1 -1
  64. package/dist/commands/status-legacy.js +9 -3
  65. package/dist/commands/status-legacy.js.map +1 -1
  66. package/dist/commands/status-meshes.d.ts.map +1 -1
  67. package/dist/commands/status-meshes.js +18 -13
  68. package/dist/commands/status-meshes.js.map +1 -1
  69. package/dist/commands/status-render.d.ts.map +1 -1
  70. package/dist/commands/status-render.js +31 -11
  71. package/dist/commands/status-render.js.map +1 -1
  72. package/dist/commands/status.d.ts.map +1 -1
  73. package/dist/commands/status.js +44 -26
  74. package/dist/commands/status.js.map +1 -1
  75. package/dist/commands/up-args.d.ts +1 -0
  76. package/dist/commands/up-args.d.ts.map +1 -1
  77. package/dist/commands/up-args.js +14 -1
  78. package/dist/commands/up-args.js.map +1 -1
  79. package/dist/commands/up-detach.d.ts +3 -0
  80. package/dist/commands/up-detach.d.ts.map +1 -1
  81. package/dist/commands/up-detach.js +2 -0
  82. package/dist/commands/up-detach.js.map +1 -1
  83. package/dist/commands/up-foreground-listener.d.ts +2 -0
  84. package/dist/commands/up-foreground-listener.d.ts.map +1 -1
  85. package/dist/commands/up-foreground-listener.js +7 -2
  86. package/dist/commands/up-foreground-listener.js.map +1 -1
  87. package/dist/commands/up.d.ts.map +1 -1
  88. package/dist/commands/up.js +15 -15
  89. package/dist/commands/up.js.map +1 -1
  90. package/dist/commands/update-offline.d.ts +2 -0
  91. package/dist/commands/update-offline.d.ts.map +1 -1
  92. package/dist/commands/update-offline.js +89 -16
  93. package/dist/commands/update-offline.js.map +1 -1
  94. package/dist/commands/update-release.d.ts +1 -1
  95. package/dist/commands/update-release.d.ts.map +1 -1
  96. package/dist/commands/update-release.js +27 -18
  97. package/dist/commands/update-release.js.map +1 -1
  98. package/dist/commands/update.d.ts.map +1 -1
  99. package/dist/commands/update.js +5 -7
  100. package/dist/commands/update.js.map +1 -1
  101. package/dist/commands/watch.d.ts.map +1 -1
  102. package/dist/commands/watch.js +7 -2
  103. package/dist/commands/watch.js.map +1 -1
  104. package/dist/commands/whoami.d.ts.map +1 -1
  105. package/dist/commands/whoami.js +5 -1
  106. package/dist/commands/whoami.js.map +1 -1
  107. package/dist/console/tool-calls.d.ts +7 -1
  108. package/dist/console/tool-calls.d.ts.map +1 -1
  109. package/dist/console/tool-calls.js +29 -34
  110. package/dist/console/tool-calls.js.map +1 -1
  111. package/dist/index.js +3 -3
  112. package/dist/index.js.map +1 -1
  113. package/dist/lib/app-user-identity.d.ts +8 -2
  114. package/dist/lib/app-user-identity.d.ts.map +1 -1
  115. package/dist/lib/app-user-identity.js +349 -110
  116. package/dist/lib/app-user-identity.js.map +1 -1
  117. package/dist/lib/choose-target.d.ts.map +1 -1
  118. package/dist/lib/choose-target.js +7 -3
  119. package/dist/lib/choose-target.js.map +1 -1
  120. package/dist/lib/control.js +2 -2
  121. package/dist/lib/control.js.map +1 -1
  122. package/dist/lib/controller-preserve.js +2 -2
  123. package/dist/lib/controller-preserve.js.map +1 -1
  124. package/dist/lib/controller-restore.d.ts.map +1 -1
  125. package/dist/lib/controller-restore.js +17 -7
  126. package/dist/lib/controller-restore.js.map +1 -1
  127. package/dist/lib/conversation-identity.d.ts +3 -3
  128. package/dist/lib/conversation-identity.d.ts.map +1 -1
  129. package/dist/lib/conversation-identity.js +8 -11
  130. package/dist/lib/conversation-identity.js.map +1 -1
  131. package/dist/lib/delivery-proc.d.ts +1 -0
  132. package/dist/lib/delivery-proc.d.ts.map +1 -1
  133. package/dist/lib/manager-proc.d.ts +1 -0
  134. package/dist/lib/manager-proc.d.ts.map +1 -1
  135. package/dist/lib/manager-proc.js +1 -0
  136. package/dist/lib/manager-proc.js.map +1 -1
  137. package/dist/lib/release-archive.d.ts +13 -0
  138. package/dist/lib/release-archive.d.ts.map +1 -0
  139. package/dist/lib/release-archive.js +39 -0
  140. package/dist/lib/release-archive.js.map +1 -0
  141. package/dist/lib/seat-restore.d.ts.map +1 -1
  142. package/dist/lib/seat-restore.js +15 -19
  143. package/dist/lib/seat-restore.js.map +1 -1
  144. package/dist/lib/service-process.d.ts +2 -0
  145. package/dist/lib/service-process.d.ts.map +1 -1
  146. package/dist/lib/service-process.js +5 -5
  147. package/dist/lib/service-process.js.map +1 -1
  148. package/dist/lib/systemd-supervision.d.ts +12 -5
  149. package/dist/lib/systemd-supervision.d.ts.map +1 -1
  150. package/dist/lib/systemd-supervision.js +9 -6
  151. package/dist/lib/systemd-supervision.js.map +1 -1
  152. package/dist/lib/update-managers.d.ts +1 -1
  153. package/dist/lib/update-managers.d.ts.map +1 -1
  154. package/dist/lib/update-managers.js +4 -2
  155. package/dist/lib/update-managers.js.map +1 -1
  156. package/dist/lib/version.d.ts +5 -0
  157. package/dist/lib/version.d.ts.map +1 -1
  158. package/dist/lib/version.js +6 -2
  159. package/dist/lib/version.js.map +1 -1
  160. package/dist/seed/manager-guard.d.ts +2 -0
  161. package/dist/seed/manager-guard.d.ts.map +1 -1
  162. package/dist/seed/manager-guard.js +6 -2
  163. package/dist/seed/manager-guard.js.map +1 -1
  164. package/dist/seed/paths.d.ts +1 -1
  165. package/dist/seed/paths.d.ts.map +1 -1
  166. package/dist/seed/paths.js +2 -2
  167. package/dist/seed/paths.js.map +1 -1
  168. package/dist/seed/reconcile.d.ts.map +1 -1
  169. package/dist/seed/reconcile.js +9 -3
  170. package/dist/seed/reconcile.js.map +1 -1
  171. package/dist/seed/store.d.ts +1 -0
  172. package/dist/seed/store.d.ts.map +1 -1
  173. package/dist/seed/store.js +1 -1
  174. package/dist/seed/store.js.map +1 -1
  175. package/dist/telemetry.d.ts.map +1 -1
  176. package/dist/telemetry.js +10 -3
  177. package/dist/telemetry.js.map +1 -1
  178. package/package.json +6 -5
@@ -1,11 +1,12 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve } from "node:path";
4
- import { acquireLock, assertLifecycleToken, canonicalJson, checkConversationApprovalPending, checkConversationPendingAnswer, checkConversationSelection, conversationApprovalRefusal, conversationGrant, deprovisionAgent, mintCreds, mkSecretDir, newIdentity, principalKey, provisionAgentDurables, processStartToken, registry, resolveAuthProvider, writeSecretFileAtomic, } from "@cotal-ai/core";
5
- import { checkDiscoveryDocument, checkIdpUrl, discoveryDocumentUrl, pinnedFetch, getSpaceAuth, homeCotalDir, oneLine, resolveTargetOrThrow, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
4
+ import { acquireLock, assertLifecycleToken, canonicalJson, checkConversationApprovalDecision, checkConversationApprovalPending, checkConversationPendingAnswer, checkConversationSelection, conversationApprovalRefusal, conversationGrant, deprovisionAgent, isReachable, mintCreds, mkSecretDir, newIdentity, principalKey, provisionAgentDurables, processStartToken, registry, resolveAuthProvider, writeSecretFileAtomic, } from "@cotal-ai/core";
5
+ import { checkDiscoveryDocument, checkIdpUrl, codeSpan, discoveryDocumentUrl, pinnedFetch, getSpaceAuth, homeCotalDir, loginRecoveryCommand, oneLine, resolveTargetOrThrow, userAuthStateDir, windowsShellWord, workspaceSecretStore } from "@cotal-ai/workspace";
6
6
  import { CONVERSATION_RESUME_PREFIX } from "@cotal-ai/workspace/conversation-resume";
7
7
  import { agentCapRefusal, checkConversationMaterial, conversationRetirementPhase, discoverConversationAuthority, legacyAgentCapRefusal, legacyNameTakenRefusal, nameTakenRefusal, selectionRefusal, signedInSpace, } from "./conversation-identity.js";
8
8
  import { withProvisioner } from "./provisioner.js";
9
+ import { shellWord } from "./endpoint-errors.js";
9
10
  import { confirmConversationResume, ConversationRequestError, createResumeProof, matchesResumeBinding, resumeToken } from "./conversation-resume.js";
10
11
  const RECORD = "identity.json";
11
12
  const hash = (text) => createHash("sha256").update(text).digest("hex");
@@ -42,7 +43,9 @@ function read(dir) {
42
43
  const record = JSON.parse(readFileSync(file, "utf8"));
43
44
  if (record.v !== 1 || typeof record.space !== "string" || typeof record.root !== "string" ||
44
45
  typeof record.session !== "string" || !/^[A-Za-z0-9_-]{22,64}$/.test(record.requestId) ||
45
- !(record.proof ? /^[a-f0-9]{64}$/ : /^[A-Za-z0-9_-]{43}$/).test(record.token) || !["creating", "ready", "retiring"].includes(record.state) ||
46
+ (record.replaces !== undefined && (typeof record.replaces !== "string" || record.replaces === record.requestId || !/^[A-Za-z0-9_-]{22,64}$/.test(record.replaces))) ||
47
+ (record.tokenHashOnly !== undefined && (record.tokenHashOnly !== true || record.proof || !record.remote?.material)) ||
48
+ !(record.proof || record.tokenHashOnly ? /^[a-f0-9]{64}$/ : /^[A-Za-z0-9_-]{43}$/).test(record.token) || !["creating", "ready", "retiring"].includes(record.state) ||
46
49
  !record.consumer || !Number.isInteger(record.consumer.pid) || record.consumer.pid <= 0 ||
47
50
  Boolean(record.remote) === Boolean(record.local))
48
51
  throw new Error("conversation identity recovery record is invalid; it was retained");
@@ -73,7 +76,7 @@ function consumerGone(consumer) {
73
76
  }
74
77
  /** The creation body. A replay sends the same one, so its digest names the same request. */
75
78
  function creationBody(record) {
76
- return { v: 1, requestId: record.requestId, tokenHash: record.proof ? record.token : hash(record.token), label: record.label,
79
+ return { v: 1, requestId: record.requestId, tokenHash: record.proof || record.tokenHashOnly ? record.token : hash(record.token), label: record.label,
77
80
  ...(record.selection ? { selection: record.selection } : {}) };
78
81
  }
79
82
  /** An issued answer must carry the person's decision on the approval the request saw. Only the exact
@@ -103,15 +106,39 @@ export class ConversationRefusal extends Error {
103
106
  }
104
107
  }
105
108
  export { ConversationRequestError } from "./conversation-resume.js";
109
+ const HELD_APPROVAL_NAME = "The name is in use, and the earlier conversation still holds it.";
110
+ const HELD_PROOFLESS_NAME = "This conversation's earlier approval still holds the name and has no resume proof. Connect with another name to request new approval. To end the earlier grant, run `cotal logout` or ask the space operator to revoke the identity.";
111
+ function accountRefusalExplanation(value) {
112
+ if (!value || typeof value !== "object" || Array.isArray(value))
113
+ return undefined;
114
+ const { reason, code, error } = value;
115
+ switch (reason ?? code ?? error) {
116
+ case "not signed in": return "This computer is not signed in.";
117
+ case "machine-forgotten": return "This computer was forgotten by the account service.";
118
+ case "computer-removed": return "This computer was removed from your account.";
119
+ default: return undefined;
120
+ }
121
+ }
122
+ /** Use the saved provider pin, not any value from the refusal. */
123
+ function accountSignInHint(idpUrl) {
124
+ const checked = checkIdpUrl(idpUrl);
125
+ if (!checked.ok)
126
+ return " Sign in to the space's provider on this computer again.";
127
+ const url = checked.url.href;
128
+ const word = process.platform === "win32" ? windowsShellWord(url) : shellWord(url);
129
+ if (!word)
130
+ return ` Sign in on this computer again. Pass the space's provider address ${codeSpan(url)} to \`cotal login --idp\`.`;
131
+ return ` Sign in on this computer again with ${codeSpan(loginRecoveryCommand(url) === "cotal login" ? "cotal login" : `cotal login --idp ${word}`)}.`;
132
+ }
106
133
  /** What one creation answer proves. A selection refusal, a recorded denial, expiry or cap refusal,
107
134
  * and a pending approval each prove that nothing was issued. Any other answer than an exact issued identity
108
135
  * leaves the outcome unknown, so it throws and the request stays saved. */
109
- function creationOutcome(record, authority, response, what) {
136
+ function creationOutcome(record, authority, response, what, heldName = HELD_APPROVAL_NAME) {
110
137
  const remote = record.remote;
111
138
  if (!remote.material) {
112
139
  const nameTaken = nameTakenRefusal(response.status, response.body, record.requestId);
113
140
  if (nameTaken)
114
- return { refused: nameTaken, decision: "refused" };
141
+ return { refused: heldName, decision: "refused" };
115
142
  const cap = agentCapRefusal(response.status, response.body, authority, record.requestId);
116
143
  if (cap)
117
144
  return { refused: cap, decision: "refused" };
@@ -130,9 +157,14 @@ function creationOutcome(record, authority, response, what) {
130
157
  return { pending };
131
158
  }
132
159
  }
133
- if (response.status !== 200 && response.status !== 201)
134
- throw new ConversationRequestError(legacyNameTakenRefusal(response.status, response.body) ?? legacyAgentCapRefusal(response.status, response.body) ??
135
- `conversation identity ${what} answered HTTP ${response.status}; its original request was retained`, response.status >= 500 || [408, 425, 429].includes(response.status));
160
+ if (response.status !== 200 && response.status !== 201) {
161
+ if (legacyNameTakenRefusal(response.status, response.body))
162
+ throw new ConversationRequestError(heldName, false);
163
+ const explanation = response.status === 401 ? accountRefusalExplanation(response.body) : undefined;
164
+ const hint = explanation ? `. ${explanation}${accountSignInHint(remote.idpUrl)}` : "";
165
+ throw new ConversationRequestError(legacyAgentCapRefusal(response.status, response.body) ??
166
+ `conversation identity ${what} answered HTTP ${response.status}; its original request was retained${hint}`, response.status >= 500 || [408, 425, 429].includes(response.status));
167
+ }
136
168
  return { material: checkConversationMaterial(response.body, authority, record.requestId, record.selection, approvalExpectation(remote)) };
137
169
  }
138
170
  function request(provider) {
@@ -163,7 +195,7 @@ async function noNativeSession(target) {
163
195
  /** The session key is supplied by the native host, not guessed from a parent pid or an open inbox.
164
196
  * A new request waits for a person's approval: until it is decided this returns `pending`, and
165
197
  * connecting again replays the same saved request and secret. */
166
- export async function provisionUserApp(target, name, session, events, selection) {
198
+ export async function provisionUserApp(target, name, session, events, selection, watch = false) {
167
199
  if (!session || !/^[A-Za-z0-9_-]{1,128}$/.test(session))
168
200
  throw new Error(await noNativeSession(target));
169
201
  const root = identityRoot();
@@ -173,40 +205,44 @@ export async function provisionUserApp(target, name, session, events, selection)
173
205
  // hosts cannot open different identities for the same native conversation at the same time.
174
206
  const sessionLock = acquireLock(join(root, `session-${hash(session)}.lock`), { waitMs: 0 });
175
207
  try {
176
- for (const entry of readdirSync(root)) {
177
- const dir = join(root, entry);
178
- if (!isUserAppDir(dir) || !existsSync(join(dir, RECORD)))
179
- continue;
180
- const previous = read(dir);
181
- if (previous.session !== session || previous.space === target.space)
182
- continue;
183
- if (previous.proof && !matchesResumeBinding(previous, previous.proof))
184
- continue;
185
- if (previous.consumer.pid !== process.ppid && !consumerGone(previous.consumer))
186
- throw new Error("this native conversation still has a live consumer on another space; disconnect it before choosing another");
187
- // A pending request or a dead consumer must finish its exact retirement before a new target
188
- // receives a request. Failure keeps the old record and sends nothing to the new authority.
189
- await retireUserApp(dir);
190
- }
191
- return await provisionOnSpace(target, name, session, events, selection);
208
+ await prepareOtherSpaces(session, target.space);
209
+ return await provisionOnSpace(target, name, session, events, selection, watch);
192
210
  }
193
211
  finally {
194
212
  sessionLock.release();
195
213
  }
196
214
  }
197
- async function provisionOnSpace(target, name, session, events, selection) {
215
+ /** A native session has one live consumer. Ready approvals on other spaces stay intact. */
216
+ async function prepareOtherSpaces(session, space) {
217
+ const records = [...savedSessionRecords(session)];
218
+ const retire = [];
219
+ for (const { dir, record } of records) {
220
+ if (record.state !== "retiring" && record.consumer.pid !== process.ppid && !consumerGone(record.consumer))
221
+ throw new Error(record.space === space ? "this native conversation still has a live inbox consumer; no identity was reissued"
222
+ : "this native conversation still has a live consumer on another space; disconnect it before choosing another");
223
+ if (record.space === space)
224
+ continue;
225
+ if (!hasIssuedApproval(record))
226
+ retire.push(dir);
227
+ }
228
+ for (const dir of retire)
229
+ await retireUserApp(dir);
230
+ }
231
+ async function provisionOnSpace(target, name, session, events, selection, watch = false) {
198
232
  const store = workspaceSecretStore(target.root);
199
233
  const infra = target.userAuth?.remote === true ? undefined : await getSpaceAuth(store, target.space);
200
- const dir = join(identityRoot(), hash(`${target.space}\0${session}`));
201
- const saved = existsSync(join(dir, RECORD)) ? read(dir) : undefined;
202
- if (saved?.proof && saved.session === session && matchesResumeBinding(saved, saved.proof)) {
203
- requireResumeLogin(saved);
204
- if (saved.state === "ready" && saved.trust !== trust(target))
234
+ const selected = selectSavedApproval(target.space, session, name, selection);
235
+ let { dir } = selected;
236
+ const saved = selected.record;
237
+ if (saved?.remote && saved.session === session) {
238
+ if ((saved.accountKey && saved.state !== "retiring") || (saved.proof && matchesResumeBinding(saved, saved.proof)))
239
+ requireResumeLogin(saved);
240
+ if (hasIssuedApproval(saved) && saved.trust !== trust(target))
205
241
  throw new Error(RESUME_UNAVAILABLE);
206
242
  }
207
243
  const authority = infra ? undefined : await discoverConversationAuthority(target).catch((error) => {
208
244
  if (saved?.proof && saved.state === "ready")
209
- throw new Error(`Conversation identity discovery did not confirm the saved authority. The saved identity was retained. ${oneLine(error.message)}`, { cause: error });
245
+ throw new Error(`Conversation identity discovery did not confirm the saved authority. The saved identity was retained. ${oneLine(error.message)}${FRESH_CONVERSATION}`, { cause: error });
210
246
  throw error;
211
247
  });
212
248
  const policy = authority?.bundle.policy ?? target.policy;
@@ -220,9 +256,31 @@ async function provisionOnSpace(target, name, session, events, selection) {
220
256
  const root = identityRoot();
221
257
  mkSecretDir(root);
222
258
  privateDir(root);
223
- const { reason, resumed } = await prepareSavedIdentity(dir, { name, session, trust: trust(target), selection }, authority);
224
- // A reconnect first finishes the previous explicit departure, or preserves an older record
225
- // whose original registration is unavailable before releasing its session key.
259
+ const expected = { name, session, trust: trust(target), selection };
260
+ const prepared = await prepareSavedIdentity(dir, expected, authority);
261
+ let { reason, resumed } = prepared;
262
+ let replaces;
263
+ let heldName = HELD_APPROVAL_NAME;
264
+ const visited = new Set();
265
+ for (let prior = prepared.replacement ? saved : undefined; prior;) {
266
+ if (prior.label === name && !prior.proof && hasIssuedApproval(prior))
267
+ heldName = HELD_PROOFLESS_NAME;
268
+ replaces = prior.requestId;
269
+ if (visited.has(replaces))
270
+ throw new Error("saved conversation approval history is invalid; no new approval was requested");
271
+ visited.add(replaces);
272
+ dir = join(root, replacementKey(prior, replaces));
273
+ const stagedRecord = existsSync(join(dir, RECORD)) ? read(dir) : undefined;
274
+ if (stagedRecord && (stagedRecord.replaces !== replaces || stagedRecord.session !== session || stagedRecord.trust !== expected.trust))
275
+ throw new Error("the saved replacement does not match this conversation; it was retained");
276
+ if (stagedRecord?.accountKey)
277
+ requireResumeLogin(stagedRecord);
278
+ const staged = await prepareSavedIdentity(dir, expected, authority);
279
+ resumed = staged.resumed;
280
+ reason = staged.reason ?? reason;
281
+ prior = staged.replacement ? stagedRecord : undefined;
282
+ }
283
+ // A reconnect first finishes the previous explicit departure.
226
284
  if (existsSync(join(dir, RECORD)) && read(dir).state === "retiring") {
227
285
  try {
228
286
  await retireUserApp(dir);
@@ -239,7 +297,7 @@ async function provisionOnSpace(target, name, session, events, selection) {
239
297
  record = read(dir);
240
298
  if (record.session !== session || record.trust !== trust(target) || record.label !== name)
241
299
  throw new Error("this conversation has a saved identity under different mesh pins or a different name; disconnect it before connecting again");
242
- if (canonicalJson(record.selection ?? null) !== canonicalJson(selection ?? null))
300
+ if (resumed !== record.requestId && canonicalJson(record.selection ?? null) !== canonicalJson(selection ?? null))
243
301
  throw new Error("this conversation has a saved identity with a different selection; connect with that selection to resume it, then disconnect before choosing another");
244
302
  if (record.state === "retiring")
245
303
  throw new Error("this conversation's prior identity is still retiring; retry disconnect before connecting again");
@@ -263,7 +321,7 @@ async function provisionOnSpace(target, name, session, events, selection) {
263
321
  record = {
264
322
  v: 1, space: target.space, root: target.root, trust: trust(target), retirementTarget: { space: target.space, root: target.root, server: target.server,
265
323
  tlsRequired: target.tlsRequired, userAuth: target.userAuth }, session,
266
- requestId: randomBytes(24).toString("base64url"), label: name, token, state: "creating",
324
+ requestId: randomBytes(24).toString("base64url"), ...(replaces ? { replaces } : {}), label: name, token, state: "creating",
267
325
  consumer: { pid: process.ppid, start: processStartToken(process.ppid) }, ...(selection ? { selection } : {}),
268
326
  remote: { url: authority.url, idpUrl: target.userAuth.idp.url, approval: {} },
269
327
  };
@@ -282,7 +340,7 @@ async function provisionOnSpace(target, name, session, events, selection) {
282
340
  throw new Error("the selected mesh does not advertise connection approval v1; the saved request was retained and not sent");
283
341
  markUnderApproval(dir, record);
284
342
  const response = await requestForRecord(provider, record)({ url: authority.url, idpUrl: record.remote.idpUrl, method: "POST", body: creationBody(record) });
285
- const outcome = creationOutcome(record, authority, response, "creation");
343
+ const outcome = creationOutcome(record, authority, response, "creation", heldName);
286
344
  if ("refused" in outcome) {
287
345
  discard(dir);
288
346
  throw new ConversationRefusal(outcome.decision, outcome.refused);
@@ -305,6 +363,10 @@ async function provisionOnSpace(target, name, session, events, selection) {
305
363
  const grant = conversationGrant(local, record.selection);
306
364
  await withProvisioner({ space: target.space, servers: target.server, auth: infra }, "app-provisioner", (provisioner) => provisionAgentDurables(provisioner, local, { subscribe: [], allowSubscribe: grant.allowSubscribe, ...(grant.role ? { role: grant.role } : {}) }));
307
365
  }
366
+ if (watch && record.remote) {
367
+ save(dir, record);
368
+ return { env: {}, retire: { dir }, grant: record.remote.material.grant };
369
+ }
308
370
  record.state = "ready";
309
371
  save(dir, record);
310
372
  const material = record.remote?.material ?? record.local;
@@ -321,7 +383,9 @@ async function provisionOnSpace(target, name, session, events, selection) {
321
383
  COTAL_SUBSCRIBE: "", COTAL_ALLOW_SUBSCRIBE: grant.allowSubscribe.join(","), COTAL_ALLOW_PUBLISH: grant.allowPublish.join(","),
322
384
  ...(grant.role ? { COTAL_ROLE: grant.role } : {}), ...(grant.scope.length ? { COTAL_CAPABILITIES: grant.scope.join(",") } : {}),
323
385
  COTAL_WORKSPACE_ROOT: homeCotalDir(), ...(events ? { COTAL_EVENTS: "1" } : {}),
324
- ...(record.proof ? { COTAL_CONVERSATION_APPROVAL: resumed === record.requestId ? "resumed" : "resumable" } : {}),
386
+ ...(record.remote ? { COTAL_RETIRE_APPROVAL_SESSION: "1" } : {}),
387
+ ...(record.remote && !record.proof ? { COTAL_RELEASE_PROOFLESS_APPROVAL: "1" } : {}),
388
+ ...(hasIssuedApproval(record) ? { COTAL_CONVERSATION_APPROVAL: resumed === record.requestId ? "resumed" : "resumable" } : {}),
325
389
  ...(policy?.events === "required" ? { COTAL_EVENTS_REQUIRED: "1" } : {}),
326
390
  }, retire: { dir }, grant };
327
391
  }
@@ -330,8 +394,6 @@ async function provisionOnSpace(target, name, session, events, selection) {
330
394
  }
331
395
  }
332
396
  function attachResumeProof(record, authority, provider) {
333
- if (!authority.resume)
334
- return;
335
397
  const binding = account(provider);
336
398
  let accountKey;
337
399
  try {
@@ -342,71 +404,45 @@ function attachResumeProof(record, authority, provider) {
342
404
  } // A legacy login without a subject still uses ordinary approval.
343
405
  if (!accountKey)
344
406
  return;
407
+ record.accountKey = accountKey;
408
+ if (!authority.resume)
409
+ return;
345
410
  const resume = createResumeProof(record);
346
411
  if (resume)
347
- Object.assign(record, { accountKey, proof: resume.proof, token: resume.tokenHash });
412
+ Object.assign(record, { proof: resume.proof, token: resume.tokenHash });
348
413
  }
349
414
  async function prepareSavedIdentity(dir, expected, authority) {
350
415
  if (!existsSync(join(dir, RECORD)))
351
416
  return {};
352
417
  const previous = read(dir);
353
- if (previous.state === "retiring")
418
+ if (previous.state === "retiring") {
354
419
  return {};
355
- const changed = previous.label !== expected.name || canonicalJson(previous.selection ?? null) !== canonicalJson(expected.selection ?? null);
420
+ }
421
+ const selectionChanged = canonicalJson(previous.selection ?? null) !== canonicalJson(expected.selection ?? null);
422
+ const changed = previous.label !== expected.name || selectionChanged;
356
423
  if (previous.proof) {
357
424
  if (matchesResumeBinding(previous, previous.proof) && previous.trust !== expected.trust)
358
425
  throw new Error(RESUME_UNAVAILABLE);
359
426
  if (previous.consumer.pid !== process.ppid && !consumerGone(previous.consumer))
360
427
  throw new Error("this native conversation still has a live inbox consumer; no identity was reissued");
361
- if (previous.session !== expected.session || !matchesResumeBinding(previous, previous.proof)) {
362
- const lock = acquireLock(`${dir}.lock`, { waitMs: 0 });
363
- try {
364
- const current = read(dir);
365
- if (current.requestId !== previous.requestId || current.state === "retiring")
366
- return {};
367
- setAside(dir, current, `-${randomBytes(8).toString("hex")}`);
368
- }
369
- finally {
370
- lock.release();
371
- }
372
- return { reason: "The saved approval could not be used on this computer." };
373
- }
374
- if (!previous.accountKey) {
375
- await retireUserApp(dir);
376
- return { reason: "The saved approval does not identify its approving account. Fresh approval is required." };
428
+ if (previous.session !== expected.session)
429
+ throw new Error("This native session does not match the saved approval. Nothing was connected.");
430
+ if (!matchesResumeBinding(previous, previous.proof) && hasIssuedApproval(previous)) {
431
+ if (previous.trust === expected.trust && authority?.approval && matchesSavedAuthority(previous, authority))
432
+ return replacementApproval("The saved approval could not be used on this computer.");
433
+ throw new Error(`The saved approval could not be used on this computer. The saved identity was retained.${FRESH_CONVERSATION}`);
377
434
  }
378
435
  if (previous.state === "ready")
379
- requireResumeAuthority(previous, authority);
380
- if (!resumeToken({ ...previous, proof: previous.proof })) {
381
- try {
382
- await retireUserApp(dir);
383
- }
384
- catch (error) {
385
- throw new Error(`The saved approval could not be used on this computer, and retirement is not confirmed. ${oneLine(error.message)}`);
386
- }
387
- return { reason: "The saved approval could not be used on this computer." };
388
- }
389
- if (previous.state === "ready") {
390
- if (changed) {
391
- await retireUserApp(dir);
392
- return { reason: "The saved approval does not cover this name or selection." };
393
- }
394
- const lock = acquireLock(`${dir}.lock`, { waitMs: 0 });
395
- try {
396
- const current = read(dir);
397
- if (current.state !== "ready" || current.requestId !== previous.requestId)
398
- return {};
399
- if (await resumeSavedIdentity(current, authority))
400
- return { resumed: current.requestId };
401
- current.state = "retiring";
402
- save(dir, current);
403
- }
404
- finally {
405
- lock.release();
406
- }
407
- await retireUserApp(dir);
408
- return { reason: "The authority did not accept the saved approval." };
436
+ return prepareReadyApproval(dir, previous, authority, !matchesApprovedRequest(previous, expected.name, expected.selection));
437
+ }
438
+ if (!previous.proof && previous.remote?.material && previous.state === "ready" &&
439
+ (changed || previous.tokenHashOnly || previous.consumer.pid !== process.ppid)) {
440
+ if (previous.trust === expected.trust && authority?.approval && matchesSavedAuthority(previous, authority)) {
441
+ if (consumerGone(previous.consumer))
442
+ releaseUserApp(dir, false);
443
+ return replacementApproval(changed ? "This request differs from the saved approval." : "The saved approval has no resume proof.");
409
444
  }
445
+ throw new Error(RESUME_UNAVAILABLE);
410
446
  }
411
447
  if (previous.session !== expected.session || previous.trust !== expected.trust)
412
448
  return {};
@@ -414,11 +450,122 @@ async function prepareSavedIdentity(dir, expected, authority) {
414
450
  if (changed && previous.state === "creating" && previous.remote && !previous.remote.material) {
415
451
  if (previous.consumer.pid !== process.ppid && !consumerGone(previous.consumer))
416
452
  throw new Error("this native conversation still has a live inbox consumer; its pending request was not replaced");
417
- await retireUserApp(dir);
453
+ await retire(dir, (record) => record.state === "creating" && !record.remote?.material);
418
454
  }
419
455
  return {};
420
456
  }
421
- const RESUME_UNAVAILABLE = "The space does not currently offer resume at the saved authority and trust pins. The saved identity was retained.";
457
+ function replacementApproval(reason) {
458
+ return { replacement: true, reason: `${reason} The saved approval and its grant were retained. This request needs its own approval.` };
459
+ }
460
+ const primaryKey = (space, session) => hash(`${space}\0${session}`);
461
+ const replacementKey = (r, prior) => hash(`${r.space}\0${r.session}\0replacement\0${prior}`);
462
+ function matchesApprovedRequest(record, name, selection) {
463
+ if (record.label !== name)
464
+ return false;
465
+ if (!selection && record.proof)
466
+ return true;
467
+ const wanted = canonicalJson(selection ?? null);
468
+ return wanted === canonicalJson(record.selection ?? null) || wanted === canonicalJson(record.remote?.material?.approval?.approved ?? null);
469
+ }
470
+ /** Prefer a matching approved selection, never an identity from another space. */
471
+ function selectSavedApproval(space, session, name, selection) {
472
+ const dir = join(identityRoot(), primaryKey(space, session));
473
+ const original = existsSync(join(dir, RECORD)) ? read(dir) : undefined;
474
+ const records = [...savedSessionRecords(session)].filter((entry) => entry.record.space === space);
475
+ const matching = records.filter(({ record }) => hasIssuedApproval(record) && record.label === name &&
476
+ canonicalJson(record.selection ?? null) === canonicalJson(selection ?? null));
477
+ const exact = matching.find(({ record }) => !matching.some(({ record: other }) => other.replaces === record.requestId));
478
+ return exact ?? (original ? { dir, record: original } : records.find(({ record }) => matchesApprovedRequest(record, name, selection)) ?? records[0] ?? { dir });
479
+ }
480
+ async function prepareReadyApproval(dir, previous, authority, mismatch) {
481
+ const lock = acquireLock(`${dir}.lock`, { waitMs: 0 });
482
+ try {
483
+ const current = read(dir);
484
+ if (current.state !== "ready" || current.requestId !== previous.requestId)
485
+ return {};
486
+ if (authority?.approval && matchesSavedAuthority(current, authority)) {
487
+ checkedSavedMaterial(current, authority, "retire");
488
+ if (mismatch)
489
+ return replacementApproval("This request differs from the saved approval.");
490
+ if (!current.accountKey || !current.proof || !resumeToken({ ...current, proof: current.proof }))
491
+ return replacementApproval("The saved approval could not be used on this computer.");
492
+ if (!authority.resume)
493
+ return replacementApproval("The space does not currently offer approval resume.");
494
+ if (canonicalJson(current.remote?.material?.policy ?? null) !== canonicalJson(authority.bundle.policy ?? null))
495
+ return replacementApproval("The space changed its event policy.");
496
+ }
497
+ if (await resumeSavedIdentity(current, authority))
498
+ return { resumed: current.requestId };
499
+ if (authority?.approval)
500
+ return replacementApproval("The authority did not accept the saved approval for reconnecting.");
501
+ }
502
+ finally {
503
+ lock.release();
504
+ }
505
+ throw new Error(`The authority did not accept the saved approval. The saved identity was retained.${FRESH_CONVERSATION}`);
506
+ }
507
+ const FRESH_CONVERSATION = " If the problem persists, use a new conversation to request fresh approval without replacing this saved approval.";
508
+ const RESUME_UNAVAILABLE = `The space does not currently offer resume at the saved authority and trust pins. The saved identity was retained.${FRESH_CONVERSATION}`;
509
+ function savedApprovalDescription(record) {
510
+ const decision = record.remote?.material?.approval;
511
+ if (!decision)
512
+ return undefined;
513
+ const { approved } = checkConversationApprovalDecision(decision);
514
+ const channels = approved.channels.map(({ channel, access }) => `#${channel} (${access})`).join(", ") || "none";
515
+ const capabilities = approved.capabilities.filter((c) => !c.startsWith("role:")).join(", ") || "none";
516
+ return `Saved approval: name ${JSON.stringify(record.label)}, space ${JSON.stringify(record.space)}. ` +
517
+ `Channels: ${channels}. Role: ${approved.role ?? "none"}. Capabilities: ${capabilities}. ` +
518
+ `To reconnect, call \`cotal_connect\` with name ${JSON.stringify(record.label)} and space ${JSON.stringify(record.space)}, omitting channels, role and capabilities.`;
519
+ }
520
+ async function savedSpaceCanResume(record) {
521
+ if (!record.accountKey || !record.proof || !record.remote?.material || !resumeToken({ ...record, proof: record.proof }))
522
+ return false;
523
+ try {
524
+ const target = await resolveTargetOrThrow({ space: record.space, readOnly: true });
525
+ if (trust(target) !== record.trust || !await isReachable(target.server))
526
+ return false;
527
+ const authority = requireResumeAuthority(record, await discoverConversationAuthority(target));
528
+ checkConversationMaterial(record.remote.material, authority, record.requestId, record.selection, approvalExpectation(record.remote));
529
+ return true;
530
+ }
531
+ catch {
532
+ return false;
533
+ }
534
+ }
535
+ function* savedSessionRecords(session, retiring = false) {
536
+ if (!session || !/^[A-Za-z0-9_-]{1,128}$/.test(session))
537
+ return;
538
+ const root = identityRoot();
539
+ if (!existsSync(root))
540
+ return;
541
+ privateDir(root);
542
+ for (const entry of readdirSync(root)) {
543
+ const dir = join(root, entry);
544
+ const setAside = retiring && isUnconfirmedDirectory(entry);
545
+ if ((!isUserAppDir(dir) && !setAside) || !existsSync(join(dir, RECORD)))
546
+ continue;
547
+ let record;
548
+ try {
549
+ record = read(dir);
550
+ }
551
+ catch {
552
+ continue;
553
+ }
554
+ if (record.session === session && (setAside ? matchesUnconfirmed(entry, record) :
555
+ entry === (record.replaces ? replacementKey(record, record.replaces) : primaryKey(record.space, session))) &&
556
+ (retiring || !record.proof || matchesResumeBinding(record, record.proof)))
557
+ yield { dir, record };
558
+ }
559
+ }
560
+ /** Return guidance only for the bound native session on the approving account and device. */
561
+ export async function savedUserAppApproval(session) {
562
+ const records = [...savedSessionRecords(session)].filter(({ record }) => hasIssuedApproval(record) && record.proof);
563
+ const [record, other] = records.map((entry) => entry.record);
564
+ if (!record?.proof || !record.accountKey || other)
565
+ return undefined;
566
+ requireResumeLogin(record);
567
+ return await savedSpaceCanResume(record) ? savedApprovalDescription(record) : undefined;
568
+ }
422
569
  function requireResumeLogin(record) {
423
570
  let key;
424
571
  try {
@@ -433,22 +580,41 @@ function requireResumeLogin(record) {
433
580
  if (record.accountKey && record.accountKey !== key)
434
581
  throw new Error("This conversation was approved by another account. Sign in with the original account or connect a different conversation for fresh approval. The saved identity was retained.");
435
582
  }
583
+ function matchesSavedAuthority(record, authority) {
584
+ return record.remote?.url === authority.url && record.remote.idpUrl === authority.bundle.userAuth.idp.url;
585
+ }
436
586
  function requireResumeAuthority(record, authority) {
437
- if (!authority?.resume || record.remote?.url !== authority.url || record.remote.idpUrl !== authority.bundle.userAuth.idp.url)
587
+ if (!authority?.resume || !matchesSavedAuthority(record, authority))
438
588
  throw new Error(RESUME_UNAVAILABLE);
439
589
  return authority;
440
590
  }
591
+ function checkedSavedMaterial(record, authority, use) {
592
+ const remote = record.remote;
593
+ if (!remote.material)
594
+ throw new Error(`The saved approval has no issued identity. The saved record was retained.${FRESH_CONVERSATION}`);
595
+ try {
596
+ return checkConversationMaterial(remote.material, authority, record.requestId, record.selection, approvalExpectation(remote), use);
597
+ }
598
+ catch (error) {
599
+ throw new Error(`${oneLine(error.message)}. The saved identity was retained.${FRESH_CONVERSATION}`, { cause: error });
600
+ }
601
+ }
441
602
  async function resumeSavedIdentity(record, discovered) {
442
603
  if (!record.accountKey)
443
604
  throw new Error("The saved approval does not identify its approving account. Fresh approval is required.");
444
605
  requireResumeLogin(record);
445
- const authority = requireResumeAuthority(record, discovered);
446
- const remote = record.remote;
447
- if (!remote.material)
448
- throw new Error("The saved approval has no issued identity. The saved record was retained.");
449
- const material = checkConversationMaterial(remote.material, authority, record.requestId, record.selection, approvalExpectation(remote));
606
+ const material = checkedSavedMaterial(record, requireResumeAuthority(record, discovered), "connect");
450
607
  const token = record.proof && resumeToken({ ...record, proof: record.proof });
451
- return !!token && !!material.approval && await confirmConversationResume(material, token);
608
+ if (!token || !material.approval)
609
+ return false;
610
+ try {
611
+ return await confirmConversationResume(material, token);
612
+ }
613
+ catch (error) {
614
+ if (error instanceof ConversationRequestError)
615
+ throw new ConversationRequestError(`${error.message}${FRESH_CONVERSATION}`, error.retryable);
616
+ throw new ConversationRequestError(`The conversation resume exchange could not be reached. The saved identity was retained. Wait before trying again.${FRESH_CONVERSATION}`, true);
617
+ }
452
618
  }
453
619
  /** Remove a creation record the authority refused before writing anything. */
454
620
  function discard(dir) {
@@ -467,10 +633,78 @@ export function isUserAppDir(dir) {
467
633
  export function retireUserApp(dir) {
468
634
  return retire(dir);
469
635
  }
636
+ /** Release a stopped, claimed proofless approval's secret. Pending retirement keeps its retry material. */
637
+ export function releaseUserApp(dir, ownsConsumer = true) {
638
+ if (!isUserAppDir(dir) || !existsSync(join(dir, RECORD)))
639
+ return;
640
+ const lock = acquireLock(`${dir}.lock`, { waitMs: 0 });
641
+ try {
642
+ const record = read(dir);
643
+ if (record.state !== "ready" || record.proof || !record.remote?.material ||
644
+ !(ownsConsumer && record.consumer.pid === process.ppid) && !consumerGone(record.consumer))
645
+ return;
646
+ discardProoflessSecret(dir, record);
647
+ }
648
+ finally {
649
+ lock.release();
650
+ }
651
+ }
652
+ function discardProoflessSecret(dir, record) {
653
+ if (record.proof || !record.remote?.material)
654
+ return;
655
+ if (!record.tokenHashOnly) {
656
+ record.token = hash(record.token);
657
+ record.tokenHashOnly = true;
658
+ save(dir, record);
659
+ }
660
+ const token = join(dir, "actor.token");
661
+ if (existsSync(token))
662
+ unlinkSync(token);
663
+ if (process.platform !== "win32")
664
+ syncFile(dir);
665
+ }
666
+ /** Retire a native session's approvals without touching another process's live consumer. */
667
+ export async function retireUserAppSession(session) {
668
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session))
669
+ throw new Error("retire needs a valid native session");
670
+ const root = identityRoot();
671
+ if (!existsSync(root))
672
+ return;
673
+ privateDir(root);
674
+ const lock = acquireLock(join(root, `session-${hash(session)}.lock`), { waitMs: 0 });
675
+ try {
676
+ const remaining = [];
677
+ for (const { dir, record } of [...savedSessionRecords(session, true)]) {
678
+ try {
679
+ await retire(dir, (current) => {
680
+ if (current.session !== session || current.requestId !== record.requestId || current.proof && !matchesResumeBinding(current, current.proof) ||
681
+ (current.consumer.pid !== process.ppid && !consumerGone(current.consumer)))
682
+ throw new Error("the saved record changed or is still held by another process");
683
+ return true;
684
+ }, homeCotalDir(), true);
685
+ }
686
+ catch (error) {
687
+ const detail = error instanceof Error
688
+ ? /^conversation identity retirement is pending at phase "(?:retired|draining)"/.exec(error.message)?.[0] : undefined;
689
+ remaining.push(`${JSON.stringify(oneLine(record.label))} in ${JSON.stringify(oneLine(record.space))}${detail ? `: ${detail}` : ""}`);
690
+ }
691
+ }
692
+ if (remaining.length)
693
+ throw new Error(`retirement was not confirmed for ${remaining.join(", ")}; retry disconnect or revoke the listed approvals at their space authorities`);
694
+ }
695
+ finally {
696
+ lock.release();
697
+ }
698
+ }
470
699
  function idpKey(url) {
471
700
  const checked = checkIdpUrl(url);
472
701
  return checked.ok ? checked.url.origin + checked.url.pathname.replace(/\/+$/, "") : undefined;
473
702
  }
703
+ function matchesSignOut(entry, record, idp, accountKey) {
704
+ return !!record.remote && idpKey(record.remote.idpUrl) === idp &&
705
+ (!record.accountKey || !accountKey || record.accountKey === accountKey) &&
706
+ (!isUnconfirmedDirectory(entry) || matchesUnconfirmed(entry, record));
707
+ }
474
708
  export const conversationSignOut = {
475
709
  kind: "conversation-sign-out", name: "native",
476
710
  async retire({ dir: home, idp, accountKey }) {
@@ -486,14 +720,14 @@ export const conversationSignOut = {
486
720
  continue;
487
721
  let failure = {};
488
722
  try {
489
- const matches = (r) => !!r.remote && idpKey(r.remote.idpUrl) === idp &&
490
- (!r.accountKey || !accountKey || r.accountKey === accountKey) && (setAside ? matchesUnconfirmed(entry, r) : !!r.proof) &&
491
- (!r.proof || matchesResumeBinding(r, r.proof));
723
+ const matches = (r) => matchesSignOut(entry, r, idp, accountKey);
492
724
  const record = read(dir);
493
725
  if (!matches(record))
494
726
  continue;
495
727
  failure = { label: oneLine(record.label), space: oneLine(record.space) };
496
- await retire(dir, matches, home, true);
728
+ if (record.proof && !matchesResumeBinding(record, record.proof))
729
+ throw new Error("the saved proof does not match this record");
730
+ await retire(dir, (current) => matches(current) && (!current.proof || matchesResumeBinding(current, current.proof)), home, true);
497
731
  }
498
732
  catch {
499
733
  failures.push(failure);
@@ -521,8 +755,7 @@ export const conversationSignOut = {
521
755
  continue;
522
756
  try {
523
757
  const r = read(dir);
524
- if (r.remote?.material && idpKey(r.remote.idpUrl) === idp && r.accountKey === accountKey && r.proof &&
525
- matchesResumeBinding(r, r.proof) && (!setAside || matchesUnconfirmed(entry, r)))
758
+ if (r.remote?.material && matchesSignOut(entry, r, idp, accountKey))
526
759
  total++;
527
760
  }
528
761
  catch { /* unreadable entry does not block sign-in */ }
@@ -537,19 +770,25 @@ function matchesUnconfirmed(entry, record) {
537
770
  const prefix = `unconfirmed-${record.requestId}`;
538
771
  return record.state === "retiring" && (entry === prefix || (entry.startsWith(prefix) && /^-[a-f0-9]{16}$/.test(entry.slice(prefix.length))));
539
772
  }
540
- /** Clean up dead consumers in this mesh. Resumable approvals stay saved unless retirement is
773
+ const hasIssuedApproval = (r) => r.state === "ready" && !!r.remote?.material;
774
+ /** Clean up dead consumers in this mesh. Issued approvals stay saved unless retirement is
541
775
  * underway. A live or unknown consumer keeps its identity and is never locked. */
542
776
  export async function retireDeadUserApps(target) {
543
777
  const root = identityRoot();
544
778
  if (!existsSync(root))
545
779
  return;
546
780
  const dead = (record) => record.trust === trust(target) && consumerGone(record.consumer) &&
547
- !(record.proof && record.state === "ready");
781
+ (record.state !== "ready" || !record.remote?.material && !record.local?.sentinelCreds);
548
782
  for (const name of readdirSync(root)) {
549
783
  const dir = join(root, name);
550
784
  try {
551
- if (isUserAppDir(dir) && existsSync(join(dir, RECORD)) && dead(read(dir)))
785
+ if (!isUserAppDir(dir) || !existsSync(join(dir, RECORD)))
786
+ continue;
787
+ const record = read(dir);
788
+ if (dead(record))
552
789
  await retire(dir, dead);
790
+ else if (record.trust === trust(target) && consumerGone(record.consumer))
791
+ releaseUserApp(dir, false);
553
792
  }
554
793
  catch { /* retained for a later run */ }
555
794
  }
@@ -646,7 +885,7 @@ async function retire(dir, when, home = homeCotalDir(), signOut = false) {
646
885
  record.remote.material = material;
647
886
  save(dir, record);
648
887
  }
649
- material = checkConversationMaterial(material, authority, record.requestId, record.selection, approvalExpectation(record.remote));
888
+ material = checkConversationMaterial(material, authority, record.requestId, record.selection, approvalExpectation(record.remote), "retire");
650
889
  const expected = new URL(`${authority.url}/${material.actor}`);
651
890
  expected.searchParams.set("lifecycleUid", assertLifecycleToken(material.lifecycleUid));
652
891
  if (material.retire.url !== expected.href)