@songsid/agend 2.4.0-beta.14 → 2.4.0-beta.16

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 (184) hide show
  1. package/dist/accounts-profiles.d.ts +1 -1
  2. package/dist/accounts-view.d.ts +3 -0
  3. package/dist/accounts-view.js.map +1 -1
  4. package/dist/auth-api.js +5 -0
  5. package/dist/auth-api.js.map +1 -1
  6. package/dist/backend/claude-code.d.ts +6 -1
  7. package/dist/backend/claude-code.js +63 -8
  8. package/dist/backend/claude-code.js.map +1 -1
  9. package/dist/backend/kiro.js +6 -1
  10. package/dist/backend/kiro.js.map +1 -1
  11. package/dist/backend/types.d.ts +2 -0
  12. package/dist/backend/types.js.map +1 -1
  13. package/dist/backend-command.d.ts +4 -2
  14. package/dist/backend-command.js +3 -0
  15. package/dist/backend-command.js.map +1 -1
  16. package/dist/browser-backend-signins.d.ts +1 -0
  17. package/dist/browser-backend-signins.js +3 -1
  18. package/dist/browser-backend-signins.js.map +1 -1
  19. package/dist/build-provenance.json +1 -1
  20. package/dist/classic-channel-manager.d.ts +1 -0
  21. package/dist/classic-channel-manager.js +4 -1
  22. package/dist/classic-channel-manager.js.map +1 -1
  23. package/dist/claude-credential-change.d.ts +22 -0
  24. package/dist/claude-credential-change.js +47 -0
  25. package/dist/claude-credential-change.js.map +1 -0
  26. package/dist/claude-credential-launch.d.ts +62 -0
  27. package/dist/claude-credential-launch.js +304 -0
  28. package/dist/claude-credential-launch.js.map +1 -0
  29. package/dist/claude-credential-runner.d.ts +1 -0
  30. package/dist/claude-credential-runner.js +56 -0
  31. package/dist/claude-credential-runner.js.map +1 -0
  32. package/dist/claude-credential-vault.d.ts +51 -0
  33. package/dist/claude-credential-vault.js +252 -0
  34. package/dist/claude-credential-vault.js.map +1 -0
  35. package/dist/claude-setup-token-transport.d.ts +9 -0
  36. package/dist/claude-setup-token-transport.js +82 -0
  37. package/dist/claude-setup-token-transport.js.map +1 -0
  38. package/dist/claude-setup-token.d.ts +51 -0
  39. package/dist/claude-setup-token.js +83 -0
  40. package/dist/claude-setup-token.js.map +1 -0
  41. package/dist/cli-audited.js +7 -6
  42. package/dist/cli-audited.js.map +1 -1
  43. package/dist/command-report.d.ts +11 -0
  44. package/dist/command-report.js +2 -0
  45. package/dist/command-report.js.map +1 -0
  46. package/dist/config-validator.js +9 -0
  47. package/dist/config-validator.js.map +1 -1
  48. package/dist/config.js +4 -2
  49. package/dist/config.js.map +1 -1
  50. package/dist/contact-auth-api.d.ts +2 -1
  51. package/dist/contact-auth-api.js +15 -5
  52. package/dist/contact-auth-api.js.map +1 -1
  53. package/dist/contact-auth-policy.d.ts +5 -0
  54. package/dist/contact-auth-policy.js +2 -0
  55. package/dist/contact-auth-policy.js.map +1 -1
  56. package/dist/contact-auth-store.d.ts +12 -1
  57. package/dist/contact-auth-store.js +67 -5
  58. package/dist/contact-auth-store.js.map +1 -1
  59. package/dist/contact-auth-types.d.ts +27 -1
  60. package/dist/contact-auth-types.js.map +1 -1
  61. package/dist/daemon.d.ts +5 -0
  62. package/dist/daemon.js +59 -3
  63. package/dist/daemon.js.map +1 -1
  64. package/dist/fleet-level-config.d.ts +1 -1
  65. package/dist/fleet-level-config.js +1 -0
  66. package/dist/fleet-level-config.js.map +1 -1
  67. package/dist/fleet-manager.d.ts +48 -3
  68. package/dist/fleet-manager.js +446 -27
  69. package/dist/fleet-manager.js.map +1 -1
  70. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +16 -6
  71. package/dist/general-knowledge/skills/web-appearance/SKILL.md +4 -1
  72. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +23 -5
  73. package/dist/host-monitoring-config.d.ts +14 -0
  74. package/dist/host-monitoring-config.js +31 -0
  75. package/dist/host-monitoring-config.js.map +1 -0
  76. package/dist/hub/group-policy/resources.d.ts +1 -1
  77. package/dist/instance-config-impact.js +1 -1
  78. package/dist/instance-config-impact.js.map +1 -1
  79. package/dist/instructions.js +1 -0
  80. package/dist/instructions.js.map +1 -1
  81. package/dist/locale.d.ts +2 -0
  82. package/dist/locale.js +19 -1
  83. package/dist/locale.js.map +1 -1
  84. package/dist/needs-you-hub.js +3 -0
  85. package/dist/needs-you-hub.js.map +1 -1
  86. package/dist/needs-you.d.ts +2 -0
  87. package/dist/needs-you.js.map +1 -1
  88. package/dist/office-share-page.js +1 -1
  89. package/dist/office-share-page.js.map +1 -1
  90. package/dist/profile-signins.d.ts +1 -0
  91. package/dist/profile-signins.js +3 -1
  92. package/dist/profile-signins.js.map +1 -1
  93. package/dist/public-web-gateway.js +2 -0
  94. package/dist/public-web-gateway.js.map +1 -1
  95. package/dist/public-web-link.d.ts +21 -2
  96. package/dist/public-web-link.js +22 -2
  97. package/dist/public-web-link.js.map +1 -1
  98. package/dist/settings-api.d.ts +12 -0
  99. package/dist/settings-api.js +146 -7
  100. package/dist/settings-api.js.map +1 -1
  101. package/dist/settings-change.js +2 -0
  102. package/dist/settings-change.js.map +1 -1
  103. package/dist/settings-effect.js +13 -1
  104. package/dist/settings-effect.js.map +1 -1
  105. package/dist/topic-commands.d.ts +7 -1
  106. package/dist/topic-commands.js +98 -88
  107. package/dist/topic-commands.js.map +1 -1
  108. package/dist/types.d.ts +2 -0
  109. package/dist/ui/accounts-view.js +12 -6
  110. package/dist/ui/backend-signin.js +3 -1
  111. package/dist/ui/chat-commands.js +2 -0
  112. package/dist/ui/chat-popout-transport.js +49 -19
  113. package/dist/ui/chat-popout.js +15 -1
  114. package/dist/ui/chat-store.js +1 -1
  115. package/dist/ui/claude-credentials.js +112 -0
  116. package/dist/ui/claude-setup-token.js +36 -0
  117. package/dist/ui/contact-auth-client.js +9 -2
  118. package/dist/ui/contact-auth-strings.js +78 -16
  119. package/dist/ui/contact-authorizations.js +47 -26
  120. package/dist/ui/contact-needs.js +22 -6
  121. package/dist/ui/contact-permissions.js +55 -10
  122. package/dist/ui/contact-tool-groups.js +39 -0
  123. package/dist/ui/fleet-canvas.js +3 -2
  124. package/dist/ui/fleet-office-card.js +414 -41
  125. package/dist/ui/fleet-office-dialogue.js +3 -3
  126. package/dist/ui/fleet-office-pack.d.ts +67 -1
  127. package/dist/ui/fleet-office-pack.js +412 -18
  128. package/dist/ui/fleet-office-play.js +262 -3
  129. package/dist/ui/fleet-office-skin.js +67 -20
  130. package/dist/ui/fleet-office-zones.js +19 -1
  131. package/dist/ui/fleet-office.js +393 -47
  132. package/dist/ui/office-share-page.js +5 -1
  133. package/dist/ui/panel-chat.js +47 -3
  134. package/dist/ui/panel-fleet.js +1 -1
  135. package/dist/ui/panel-needs.js +7 -4
  136. package/dist/ui/panel-settings.js +2 -1
  137. package/dist/ui/preview-popout.js +134 -0
  138. package/dist/ui/reply-file-preview.js +1 -1
  139. package/dist/ui/settings-appearance.js +6 -1
  140. package/dist/ui/settings-host-monitoring.js +51 -0
  141. package/dist/ui/settings-registry.js +1 -1
  142. package/dist/ui/settings-shared.js +3 -2
  143. package/dist/ui/shared/app-i18n.js +4 -0
  144. package/dist/ui/shared/app-shell.js +16 -7
  145. package/dist/ui/shared/app.css +266 -27
  146. package/dist/ui/shared/app.js +7 -1
  147. package/dist/ui/shared/chat-strings.js +8 -2
  148. package/dist/ui/shared/info-tip.js +64 -0
  149. package/dist/ui/shared/office-dialogue.css +12 -0
  150. package/dist/ui/shared/preview-panel.js +44 -18
  151. package/dist/ui/shared/preview-popout.css +11 -0
  152. package/dist/ui/shared/theme-picker.js +46 -0
  153. package/dist/ui/shared/theme.js +47 -4
  154. package/dist/ui/shared/tokens.css +273 -0
  155. package/dist/ui/shared/ui-confirm.js +5 -2
  156. package/dist/ui/shared/usage-dialog.js +9 -34
  157. package/dist/ui/shared/view-strings.js +2 -0
  158. package/dist/usage/i18n-keys.d.ts +1 -1
  159. package/dist/usage/i18n-keys.js +1 -1
  160. package/dist/usage/i18n-keys.js.map +1 -1
  161. package/dist/usage/providers.d.ts +1 -0
  162. package/dist/usage/providers.js +14 -1
  163. package/dist/usage/providers.js.map +1 -1
  164. package/dist/usage/usage-api.js +5 -2
  165. package/dist/usage/usage-api.js.map +1 -1
  166. package/dist/web-api.d.ts +5 -1
  167. package/dist/web-api.js +29 -9
  168. package/dist/web-api.js.map +1 -1
  169. package/dist/web-claude-credentials.d.ts +31 -0
  170. package/dist/web-claude-credentials.js +138 -0
  171. package/dist/web-claude-credentials.js.map +1 -0
  172. package/dist/web-commands.d.ts +5 -2
  173. package/dist/web-commands.js +4 -2
  174. package/dist/web-commands.js.map +1 -1
  175. package/dist/web-office-skins.d.ts +7 -2
  176. package/dist/web-office-skins.js +42 -16
  177. package/dist/web-office-skins.js.map +1 -1
  178. package/dist/web-session.d.ts +20 -1
  179. package/dist/web-session.js +27 -0
  180. package/dist/web-session.js.map +1 -1
  181. package/dist/web-terminal.d.ts +4 -0
  182. package/dist/web-terminal.js +16 -1
  183. package/dist/web-terminal.js.map +1 -1
  184. package/package.json +1 -1
@@ -1,7 +1,11 @@
1
+ import { ClaudeSetupTokens } from "./claude-setup-token.js";
2
+ import { changeIdleClaudeCredential } from "./claude-credential-change.js";
3
+ import { readClaudeCredentialSelection, claudeSubscriptionSuppressed } from "./claude-credential-launch.js";
4
+ import { ClaudeCredentialVault, ClaudeCredentialError } from "./claude-credential-vault.js";
1
5
  import { withHubRoomReplyWarning } from "./hub-room-reply-warning.js";
2
6
  import { ContactAuthService } from "./contact-auth-service.js";
3
7
  import { stageContactFiles } from "./contact-auth-files.js";
4
- import { ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
8
+ import { ContactOriginClearSchema, ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
5
9
  import { CLASSIC_RESTRICTED_TOOLS } from "./contact-auth-types.js";
6
10
  import { hubSharingNoticeText } from "./hub-sharing-notice.js";
7
11
  import { hubPageSharingSettings } from "./hub-page-sharing-settings.js";
@@ -312,7 +316,7 @@ import { BrowserBackendSignIns } from "./browser-backend-signins.js";
312
316
  import { createStructuredSignInTransport } from "./structured-signin-transport.js";
313
317
  import { ONBOARDING_BACKENDS, ONBOARDING_BROWSER_BACKENDS, readPendingBackendSignIns } from "./backend-signin-pending.js";
314
318
  import { hostFacts, runtimeAccountsCapability, runtimeFacts } from "./cli-registry.js";
315
- import { handleSettingsRequest, switchClassicRoomProfile } from "./settings-api.js";
319
+ import { handleSettingsRequest, switchClassicRoomProfile, switchClassicRoomBackend } from "./settings-api.js";
316
320
  import { setLocale, detectLocale, getLocale, t } from "./locale.js";
317
321
  import { remoteCardAction, remoteCardChoiceLabel, remoteCardOutcomeText, remoteCardPrompt, REMOTE_CARD_TEXT_MAX } from "./remote-card-prompt.js";
318
322
  import { recentChatContext } from "./log-tail.js";
@@ -5751,6 +5755,7 @@ export class FleetManager {
5751
5755
  this.publishTraffic(row, "consumed");
5752
5756
  });
5753
5757
  outbox.on("generation_recovered", () => this.scheduleDeliveryOutboxPump());
5758
+ this.sweepContactAuthorizationOutcomes();
5754
5759
  this.replyObligationTimer = setInterval(() => measureSyncWork("fleet.replyObligationSweep", () => this.sweepReplyObligations()), REPLY_OBLIGATION_SWEEP_MS);
5755
5760
  this.replyObligationTimer.unref?.();
5756
5761
  // #856: the text the target daemon received differs from what was
@@ -5951,6 +5956,7 @@ export class FleetManager {
5951
5956
  return admitted.delivery.deliveryId;
5952
5957
  },
5953
5958
  changed: (instance, ticketId) => {
5959
+ this.sweepContactAuthorizationOutcomes();
5954
5960
  const revision = this.deliveryOutbox.contactAuthorizations.policy(instance).revision;
5955
5961
  const ticket = ticketId ? this.deliveryOutbox.contactAuthorizations.get(ticketId) : undefined;
5956
5962
  if (ticket) {
@@ -5988,13 +5994,18 @@ export class FleetManager {
5988
5994
  throw Error("forbidden");
5989
5995
  if (!this.webChatOwner(name))
5990
5996
  throw Error("not-found");
5991
- const store = service.host.store, policy = store.policy(name, this.contactGeneration(name));
5997
+ const store = service.host.store, generation = this.contactGeneration(name), policy = store.policy(name, generation);
5998
+ const origin = store.origin(name);
5992
5999
  const daemon = this.daemons.get(name);
5993
6000
  const backend = room ? this.classicChannels.getBackendByInstance(name, this.fleetConfig?.defaults?.backend) : this.fleetConfig?.instances[name]?.backend ?? "unknown";
5994
6001
  const nativeGuard = daemon?.classicNativeGuard?.() ?? { state: "not-covered", backend, reason: "Native guard is not loaded in this build", impactComplete: false };
5995
6002
  const removedTools = room ? [...toolsFor(resolveToolSet(this.fleetConfig?.instances[name], name))]
5996
6003
  .filter(tool => !CLASSIC_RESTRICTED_TOOLS.includes(tool)) : [];
5997
- return { instance: name, revision: policy.revision, classicRoom: !!room,
6004
+ return { instance: name, revision: policy.revision,
6005
+ originState: { kind: origin?.kind ?? "none", people: origin?.people ?? [], chain: origin?.chain ?? [],
6006
+ receiptCount: origin?.receiptIds.length ?? 0, revision: store.originRevision(name), generation,
6007
+ canClear: canManage && !!origin, lastCleared: store.lastOriginClear(name, generation) },
6008
+ classicRoom: !!room,
5998
6009
  mode: room?.restrictedMode === true ? "restricted" : "legacy", approvers: service.approvers(name),
5999
6010
  eligibleApprovers: service.host.defaultApprovers(name),
6000
6011
  inheritedApprovers: policy.approvers === undefined,
@@ -6055,6 +6066,24 @@ export class FleetManager {
6055
6066
  this.emitSseEvent("needs", { items: this.needsYouItems() });
6056
6067
  return this.contactPermissions(name, actor);
6057
6068
  }
6069
+ clearContactOrigin(name, raw, actor) {
6070
+ const parsed = ContactOriginClearSchema.safeParse(raw);
6071
+ if (!parsed.success)
6072
+ throw Error("invalid-request");
6073
+ const service = this.contactService();
6074
+ if (!service.canManage(name, actor))
6075
+ throw Error("forbidden");
6076
+ if (!this.webChatOwner(name))
6077
+ throw Error("not-found");
6078
+ service.host.store.clearOrigin(name, parsed.data, actor, () => {
6079
+ if (!service.canManage(name, actor))
6080
+ throw Error("forbidden");
6081
+ return this.contactGeneration(name);
6082
+ });
6083
+ this.emitSseEvent("contact-auth", { instance: name, revision: parsed.data.revision,
6084
+ originRevision: service.host.store.originRevision(name) });
6085
+ return this.contactPermissions(name, actor);
6086
+ }
6058
6087
  contactAuthorization(id, actor) {
6059
6088
  const service = this.contactService(), ticket = service.host.store.get(id);
6060
6089
  if (!ticket)
@@ -6080,6 +6109,20 @@ export class FleetManager {
6080
6109
  decideContactAuthorization(id, decision, actor) {
6081
6110
  return this.contactService().decide(id, decision, actor);
6082
6111
  }
6112
+ /** Status only: no human receipt, approval capability or original correlation is attached. */
6113
+ sweepContactAuthorizationOutcomes() {
6114
+ const outbox = this.deliveryOutbox;
6115
+ if (!outbox?.isOpen || this.shuttingDown)
6116
+ return;
6117
+ try {
6118
+ outbox.contactAuthorizations.notifyOutcomes(ticket => {
6119
+ outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(ticket.state === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
6120
+ });
6121
+ }
6122
+ catch (err) {
6123
+ this.logger.error({ err }, "Contact outcome notice sweep failed; durable state will retry");
6124
+ }
6125
+ }
6083
6126
  contactNeeds(actor) {
6084
6127
  const service = this.contactService();
6085
6128
  const pending = service.host.store.pending()
@@ -6096,20 +6139,55 @@ export class FleetManager {
6096
6139
  && !service.host.store.suggestionDismissed(room.instanceName) && this.contactAdminOf(room.instanceName, actor))
6097
6140
  .map(room => ({ id: `contact-suggest:${room.instanceName}`, type: "contact",
6098
6141
  reason: "contact_restricted_suggestion", instance: room.instanceName,
6099
- since: Date.parse(room.createdAt) || 0, detail: "", contactSuggestion: { instance: room.instanceName } }))];
6142
+ since: service.host.store.suggestionRaisedAt(room.instanceName), detail: "", contactSuggestion: { instance: room.instanceName } }))];
6100
6143
  }
6144
+ /**
6145
+ * The chat's contact items. M-3381 (the user, beta.14): the restricted-mode suggestions are ONE low-key line per world —
6146
+ * "N existing ClassicBot rooms can switch to restricted mode", saying where to act (the dashboard's Needs you, or a
6147
+ * room's Permissions) — not one line per room; each room's age counts from when its suggestion was raised.
6148
+ */
6101
6149
  contactSuggestions() {
6102
6150
  const rooms = this.classicChannels?.getAll().filter(room => room.restrictedMode !== true) ?? [];
6103
6151
  const store = this.contactService().host.store;
6104
6152
  const pending = store.pending().map(ticket => ({ id: `contact:${ticket.id}`, type: "contact",
6105
6153
  reason: "contact_request", instance: ticket.target, owner: this.getAdapterForInstance(ticket.target)?.id,
6106
6154
  since: Date.parse(ticket.createdAt), detail: "", contactTicket: { id: ticket.id, source: ticket.source, target: ticket.target } }));
6107
- return [...pending, ...rooms.filter(room => !store.suggestionDismissed(room.instanceName)).map(room => ({
6108
- id: `contact-suggest:${room.instanceName}`, type: "contact", reason: "contact_restricted_suggestion",
6109
- instance: room.instanceName, owner: this.getAdapterForInstance(room.instanceName)?.id,
6110
- since: Date.parse(room.createdAt) || 0, detail: t("contact.suggest"), contactSuggestion: { instance: room.instanceName },
6155
+ const byWorld = new Map();
6156
+ for (const room of rooms) {
6157
+ if (store.suggestionDismissed(room.instanceName))
6158
+ continue;
6159
+ const owner = this.getAdapterForInstance(room.instanceName)?.id;
6160
+ if (owner === undefined)
6161
+ continue;
6162
+ const raised = store.suggestionRaisedAt(room.instanceName), group = byWorld.get(owner);
6163
+ byWorld.set(owner, { count: (group?.count ?? 0) + 1, since: Math.min(group?.since ?? Infinity, raised) });
6164
+ }
6165
+ return [...pending, ...[...byWorld].map(([owner, group]) => ({
6166
+ id: `contact-suggest:rooms:${owner}`, type: "contact", reason: "contact_restricted_suggestion", instance: "", owner,
6167
+ // Low-key (#4228 review): listed in the chat's Needs you, but never a new-item notification or a DM.
6168
+ since: group.since, detail: "", contactSuggestionCount: group.count, quiet: true,
6111
6169
  }))];
6112
6170
  }
6171
+ /** Identity for reminder visibility/dismissal ONLY. Never a verified contact/action permit. */
6172
+ contactSuggestionActor(req, url) {
6173
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
6174
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
6175
+ return null;
6176
+ const verified = this.contactActor(req, url);
6177
+ if (verified)
6178
+ return verified;
6179
+ const owner = verdict.session.owner, adapter = owner && this.adapters.get(owner.adapterId);
6180
+ if (!owner || !adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6181
+ return null;
6182
+ return { platform: adapter.type, adapterId: owner.adapterId, userId: owner.userId, label: owner.userId };
6183
+ }
6184
+ /** Dismissing a reminder grants no authority: current room-admin membership is still checked below. */
6185
+ acknowledgeContactSuggestionFromWeb(instance, req, url) {
6186
+ const actor = this.contactSuggestionActor(req, url);
6187
+ if (!actor)
6188
+ throw Error("verification-required");
6189
+ this.acknowledgeContactSuggestion(instance, actor);
6190
+ }
6113
6191
  acknowledgeContactSuggestion(instance, actor) {
6114
6192
  if (!this.contactAdminOf(instance, actor) || !this.contactRoom(instance))
6115
6193
  throw Error("forbidden");
@@ -6330,6 +6408,7 @@ export class FleetManager {
6330
6408
  * requesters are no longer told about overdue or expired asks (they can check delivery_status / describe_instance).
6331
6409
  */
6332
6410
  sweepReplyObligations(now = new Date()) {
6411
+ this.sweepContactAuthorizationOutcomes();
6333
6412
  const outbox = this.deliveryOutbox;
6334
6413
  if (!outbox || this.shuttingDown)
6335
6414
  return;
@@ -8179,6 +8258,14 @@ export class FleetManager {
8179
8258
  return;
8180
8259
  this.cancelButtonIdleRetireTimers.delete(name);
8181
8260
  if (this.getInstanceExecutionState(name) === "idle") {
8261
+ // #4270: a pause between tool calls can read as idle mid-turn, and nothing re-shows the bubble when the turn
8262
+ // goes back to working. While the turn is still open (no completion delivered, not cancelled), check again
8263
+ // after another grace instead of retiring. The turn's close, or the 5-minute idle backstop for a turn that
8264
+ // never closes, still retires it.
8265
+ if (this.instanceTurnOpen(name) && this.instanceHasCancelButton(name)) {
8266
+ this.scheduleIdleButtonRetirement(name);
8267
+ return;
8268
+ }
8182
8269
  this.markCancelButtonPublicationForRetirement(name, publication);
8183
8270
  this.retireInstanceButtons(name);
8184
8271
  }
@@ -8186,6 +8273,27 @@ export class FleetManager {
8186
8273
  timer.unref?.();
8187
8274
  this.cancelButtonIdleRetireTimers.set(name, timer);
8188
8275
  }
8276
+ /** #4270: the daemon's turn is still open (turn_started seen, no turn_closed, no completion delivered, not cancelled). */
8277
+ instanceTurnOpen(name) {
8278
+ const daemon = this.daemons.get(name);
8279
+ if (!daemon || typeof daemon.getWorkingStateObservation !== "function")
8280
+ return false;
8281
+ try {
8282
+ const turn = daemon.getWorkingStateObservation().turn;
8283
+ return !!turn && !turn.cancelled && !turn.completionDelivered;
8284
+ }
8285
+ catch {
8286
+ return false;
8287
+ }
8288
+ }
8289
+ instanceHasCancelButton(name) {
8290
+ if (this.cancelButtonPublications.get(name)?.inFlight)
8291
+ return true;
8292
+ for (const entry of this.cancelButtons.values())
8293
+ if (entry.instanceName === name)
8294
+ return true;
8295
+ return false;
8296
+ }
8189
8297
  cacheInstanceProcessStatus(name, status) {
8190
8298
  // #1386: every transition into crashed is a new occurrence (a new "Needs you" item), and every other status ends
8191
8299
  // the previous one — at once, not when the coalesced collector next runs: running then crashed in one IPC chunk is
@@ -10989,6 +11097,8 @@ export class FleetManager {
10989
11097
  gatewayPolicy: () => publicLinkSessionPolicy(this.fleetConfig?.web?.session?.public_link, publicLinkNamedHostname(this.fleetConfig?.web)),
10990
11098
  // A session over the temporary link ends with the link (its TTL, at most 8 h on a quick tunnel).
10991
11099
  exposureEnd: id => this.publicWebLink?.endOf(id) ?? null,
11100
+ // M-3399: a session made over the fixed link carries its identity, to outlive a restart or an update.
11101
+ linkKeyOf: id => this.publicWebLink?.keyOf?.(id) ?? null,
10992
11102
  });
10993
11103
  this.enforceGuestSwitch(); // #1920: guests off while the fleet was down
10994
11104
  }
@@ -11194,9 +11304,16 @@ export class FleetManager {
11194
11304
  reserve: id => this.getTunnelLane().reserve("dashboard", id),
11195
11305
  createGateway: (exposureId, current, open, failed, named) => createPublicWebGateway({ ...named, exposureId, isCurrent: current, isOpen: open, onError: failed,
11196
11306
  dispatch: (req, res) => this.dispatchWebHttp(req, res, this.fleetConfig?.health_port ?? 19280) }),
11197
- revoke: id => {
11307
+ revoke: (id, keep) => {
11198
11308
  this.webLoginCodes?.revokeAudience(id);
11199
11309
  this.webGuestLoginCodes?.revokeAudience(id);
11310
+ // M-3399 (the user: "sign-in should survive an update or restart"): the fixed link closing because the fleet stops
11311
+ // keeps its sessions — and their verified authority — for the same link to take back when it opens again. Sign-in
11312
+ // codes still end; nothing over the link answers until it is open again.
11313
+ if (keep?.keepSessions) {
11314
+ this.logger.info({ exposureId: id }, "Public web link: fixed-link sessions kept across the fleet stop");
11315
+ return;
11316
+ }
11200
11317
  // #2453 (§0.2): the link's sessions end, and the authorizations kept for them go with them (housekeeping: their
11201
11318
  // handles can never match again).
11202
11319
  const ended = new Set(this.webSessions?.list(undefined, r => r.exposureId === id).map(r => r.handle) ?? []);
@@ -11206,6 +11323,21 @@ export class FleetManager {
11206
11323
  if (result && !result.durable)
11207
11324
  this.logger.warn("Public session revocation could not be saved; exposure remains closed");
11208
11325
  },
11326
+ // M-3399: the fixed link open again (auto_open, or a /web): its kept sessions rejoin it; ones kept for another hostname
11327
+ // or token end, with their authorizations.
11328
+ opened: (id, configuration) => {
11329
+ const result = this.webSessions?.adoptLink(configuration, id);
11330
+ if (!result)
11331
+ return;
11332
+ if (result.ended.length) {
11333
+ const ended = new Set(result.ended);
11334
+ this.sessionAuthorizationStore()?.prune(a => !ended.has(a.handle));
11335
+ }
11336
+ if (result.adopted || result.ended.length)
11337
+ this.logger.info({ exposureId: id, adopted: result.adopted, ended: result.ended.length }, "Public web link: kept fixed-link sessions rejoined");
11338
+ if (!result.durable)
11339
+ this.logger.warn("Fixed-link session changes could not be saved");
11340
+ },
11209
11341
  log: (event, exposureId, detail) => this.logger.info({ event, exposureId, ...(detail ? { detail } : {}) }, "Public web link"),
11210
11342
  createPreview: ({ id, expiresAt, binary, protocol, dashboardOrigin, isCurrent }) => {
11211
11343
  if (!publicPreviewWanted(this.fleetConfig?.web))
@@ -15308,7 +15440,7 @@ export class FleetManager {
15308
15440
  }
15309
15441
  return;
15310
15442
  }
15311
- // #1806: /backend — channel admin, as /model. A ClassicBot agent is not switched by it (it says so).
15443
+ // /backend uses the shared staged picker for a ClassicBot room, with the same admin gate as /model.
15312
15444
  if (text === "/backend" || text.startsWith("/backend ") || text.startsWith("/backend@")) {
15313
15445
  if (!this.isModelAdmin(msg.userId, chatId, msg.adapterId)) {
15314
15446
  await msgAdapter?.sendText(chatId, t("permission.denied"));
@@ -22092,6 +22224,10 @@ export class FleetManager {
22092
22224
  return runWebCommand({
22093
22225
  scope: (instance) => this.webCommandScope(instance),
22094
22226
  platform: (instance) => this.commandPlatform(instance),
22227
+ report: (command) => {
22228
+ const lang = this.webPrefs?.read("operator").values.lang;
22229
+ return this.topicCommands.getWebReport(command, lang === "en" || lang === "zh-TW" ? lang : getLocale());
22230
+ },
22095
22231
  ctx: (instance) => this.topicCommands.getCtxText(instance),
22096
22232
  // Board 003648ac: a watch for the paste, armed when the daemon says it was written (raw_paste_written); one
22097
22233
  // for a command that was not handed over is dropped.
@@ -22148,12 +22284,15 @@ export class FleetManager {
22148
22284
  const refusal = this.backendCommandRefusal(instance);
22149
22285
  if (refusal)
22150
22286
  return { error: refusal };
22287
+ const target = this.backendCommandTarget(instance);
22151
22288
  // The cached model lists, as the web's /model; an empty one is discovered once, bounded (moving to a CLI
22152
22289
  // never signed in at startup, or probed before it was installed, must not offer an empty list).
22153
22290
  const wanted = backendArgs(args)[0];
22154
22291
  if (wanted && KNOWN_BACKENDS.includes(wanted))
22155
22292
  await this.ensureModelCatalog(wanted, instance);
22156
22293
  const step = await backendStep({ ...this.backendCommandDeps(instance, { live: false }), models: async (backend) => this.modelCatalogFor(backend, instance) }, instance, backendArgs(args));
22294
+ if (!this.backendTargetIs(instance, target))
22295
+ return { error: t("menu.click_stale") };
22157
22296
  if (step.kind === "refuse")
22158
22297
  return step.noop ? { text: step.text } : { error: step.text };
22159
22298
  if (step.kind === "choose") {
@@ -22174,7 +22313,7 @@ export class FleetManager {
22174
22313
  const token = randomBytes(16).toString("hex");
22175
22314
  this.webBackendTokens.set(token, {
22176
22315
  instance, asked: joinBackendArgs(backendArgs(args)), args: step.args, from: step.from,
22177
- target: this.fleetConfig.instances[instance], deadline: now + CLASSIC_BACKEND_SELECTION_TIMEOUT_MS,
22316
+ target, deadline: now + CLASSIC_BACKEND_SELECTION_TIMEOUT_MS,
22178
22317
  });
22179
22318
  return { confirm: { token, message: step.text } };
22180
22319
  },
@@ -23679,6 +23818,7 @@ export class FleetManager {
23679
23818
  get browserBackendSignIns() {
23680
23819
  return this.browserBackendSignInsInstance ??= new BrowserBackendSignIns({
23681
23820
  dataDir: this.dataDir, lock: this.loginWindow,
23821
+ allowed: backend => backend !== "claude-code" || !claudeSubscriptionSuppressed(this.dataDir, null),
23682
23822
  current: owner => this.browserSignInOwnerCurrent(owner),
23683
23823
  installed: async () => {
23684
23824
  const found = await Promise.all(ONBOARDING_BACKENDS.map(async (backend) => (await this.isCliInstalledOffLoop(backend)) ? backend : null));
@@ -23722,6 +23862,7 @@ export class FleetManager {
23722
23862
  */
23723
23863
  get profileSignIns() {
23724
23864
  return this.profileSignInsInstance ??= new ProfileSignIns({
23865
+ allowed: (backend, profile) => backend !== "claude-code" || !claudeSubscriptionSuppressed(this.dataDir, profile),
23725
23866
  lock: this.loginWindow,
23726
23867
  current: owner => this.browserSignInOwnerCurrent(owner),
23727
23868
  installed: backend => this.isCliInstalledOffLoop(backend),
@@ -23817,7 +23958,8 @@ export class FleetManager {
23817
23958
  signInIdentityGeneration = 0;
23818
23959
  signInIdentitySlots = 0;
23819
23960
  signInIdentityWaiters = [];
23820
- signInIdentity(backend, profile) { return this.signInIdentities.get(`${backend}\0${profile ?? ""}`)?.identity ?? undefined; }
23961
+ signInIdentity(backend, profile) { if (backend === "claude-code" && this.dataDir && claudeSubscriptionSuppressed(this.dataDir, profile ?? null))
23962
+ return undefined; return this.signInIdentities.get(`${backend}\0${profile ?? ""}`)?.identity ?? undefined; }
23821
23963
  /** A sign-in finished (or changed): forget what was read and let no read that was already running put its answer back. */
23822
23964
  forgetSignInIdentities() { this.signInIdentityGeneration++; this.signInIdentities.clear(); this.signInIdentityReads.clear(); }
23823
23965
  /** At most three `claude auth status` at once across the whole host, however many requests ask. */
@@ -23835,6 +23977,8 @@ export class FleetManager {
23835
23977
  }
23836
23978
  /** One `claude auth status` for a sign-in (the default one, or a credential profile's folder). */
23837
23979
  async readSignInIdentity(target) {
23980
+ if (target.backend === "claude-code" && claudeSubscriptionSuppressed(this.dataDir, target.profile ?? null))
23981
+ return undefined;
23838
23982
  let env, launch;
23839
23983
  if (target.profile) {
23840
23984
  const l = credentialProfileLaunch(this.dataDir, target.backend, target.profile);
@@ -23973,8 +24117,31 @@ export class FleetManager {
23973
24117
  this.logger.debug({ err: err.message }, "Computer accounts not read");
23974
24118
  }
23975
24119
  }
23976
- return buildAccountsView({ targets, diskProfiles, agents, classic, fleetDefaults, usage, keepAlive, machines, installShown: this.webHostInstalls.view()?.backend ?? null,
24120
+ const view = buildAccountsView({ targets, diskProfiles, agents, classic, fleetDefaults, usage, keepAlive, machines, installShown: this.webHostInstalls.view()?.backend ?? null,
23977
24121
  versions: new Map(this.backendAvailabilityRows().map(row => [row.backend, row.version ?? null])), claudeInstall: await this.claudeInstallShown() });
24122
+ for (const cli of view.clis)
24123
+ for (const row of cli.rows) {
24124
+ if (row.backend !== "claude-code" || row.scope.kind !== "host")
24125
+ continue;
24126
+ try {
24127
+ const selected = readClaudeCredentialSelection(this.dataDir, row.profile);
24128
+ if (selected)
24129
+ row.credential = selected;
24130
+ }
24131
+ catch {
24132
+ row.credentialUnavailable = true;
24133
+ }
24134
+ if (row.credentialUnavailable || row.credential?.source === "managed") {
24135
+ delete row.identity;
24136
+ delete row.usageGroups;
24137
+ delete row.usageStale;
24138
+ delete row.usageStaleInfo;
24139
+ delete row.keepAlive;
24140
+ delete row.reconnect;
24141
+ row.state = row.credential?.kind || row.credentialUnavailable ? "unknown" : "not_signed_in";
24142
+ }
24143
+ }
24144
+ return view;
23978
24145
  }
23979
24146
  /**
23980
24147
  * M-3307: the install kind as the AI accounts page is told it — paths `~`-abbreviated (Fable note 2 on #4163) — and, for a native install, the npm copy still left on
@@ -24130,8 +24297,11 @@ export class FleetManager {
24130
24297
  if (!isKeepAliveBackend(backend) || isWindowsInstance(config))
24131
24298
  return null;
24132
24299
  let key = this.launchCredentialKey(config, backend);
24133
- for (let renewing = this.keepAliveRenewing.get(key); renewing; renewing = this.keepAliveRenewing.get(key)) {
24134
- await renewing;
24300
+ for (;;) {
24301
+ const waiting = this.claudeCredentialChanges?.get(key) ?? this.keepAliveRenewing.get(key);
24302
+ if (!waiting)
24303
+ break;
24304
+ await waiting;
24135
24305
  assertCurrent();
24136
24306
  key = this.launchCredentialKey(config, backend);
24137
24307
  }
@@ -24212,6 +24382,8 @@ export class FleetManager {
24212
24382
  * sign-in admission reopens after a restart only once it has ended. `release()` only after its CLI has exited.
24213
24383
  */
24214
24384
  acquireKeepAliveRun(backend, profile) {
24385
+ if (backend === "claude-code" && claudeSubscriptionSuppressed(this.dataDir, profile))
24386
+ return "in_use";
24215
24387
  if (this.keepAliveInUse(backend, profile))
24216
24388
  return "in_use";
24217
24389
  const claim = this.loginWindow.tryClaim("keepalive", backend);
@@ -24280,6 +24452,178 @@ export class FleetManager {
24280
24452
  }
24281
24453
  return { agents, classic, fleetDefaults };
24282
24454
  }
24455
+ claudeCredentialChanges = new Map();
24456
+ claudeCredentialConsumers(profile) {
24457
+ const configured = this.accountUses(), rooms = readClassicBindingsStrict(this.dataDir);
24458
+ if (rooms.kind === "unknown")
24459
+ throw new ClaudeCredentialError("unavailable");
24460
+ const live = [];
24461
+ for (const [name, daemon] of this.daemons) {
24462
+ const snapshot = daemon.getConfigSnapshot();
24463
+ if (isWindowsInstance(snapshot))
24464
+ continue;
24465
+ const backend = snapshot.backend ?? this.fleetConfig?.defaults?.backend ?? "claude-code";
24466
+ if (backend !== "claude-code")
24467
+ continue;
24468
+ if (resolveCredentialProfile(snapshot.backend_options?.[backend]) === profile)
24469
+ live.push({ name, epoch: this.lifecycle.epochOf(name), snapshot });
24470
+ }
24471
+ const users = [...new Set([...configured.agents.filter(a => a.backend === "claude-code" && a.profile === profile).map(a => a.name), ...configured.classic.filter(a => a.backend === "claude-code" && a.profile === profile).map(a => a.key), ...live.map(a => a.name)])].sort();
24472
+ return { users, revision: createHash("sha256").update(JSON.stringify([this.settingsGeneration, this.fleetConfig, rooms, live])).digest("hex") };
24473
+ }
24474
+ async changeClaudeCredential(profile, revision, change, actor, confirmation, authorized, ownClaim) {
24475
+ if (profile !== null && !accountFolderExists(this.dataDir, "claude-code", profile))
24476
+ throw new ClaudeCredentialError("profile-unknown");
24477
+ const before = this.claudeCredentialConsumers(profile);
24478
+ if (before.users.length && !confirmation.restart)
24479
+ throw new ClaudeCredentialError("in-use");
24480
+ if (before.users.length && confirmation.consumersRevision !== before.revision)
24481
+ throw new ClaudeCredentialError("conflict");
24482
+ const targets = [...this.daemons].filter(([, d]) => { const snap = d.getConfigSnapshot(); return !isWindowsInstance(snap) && (snap.backend ?? this.fleetConfig?.defaults?.backend ?? "claude-code") === "claude-code" && resolveCredentialProfile(snap.backend_options?.["claude-code"]) === profile; }).sort(([a], [b]) => a.localeCompare(b));
24483
+ const records = targets.map(([name, daemon]) => ({ name, daemon, epoch: this.lifecycle.epochOf(name), stopped: false, retired: false }));
24484
+ const claim = ownClaim ?? this.loginWindow.tryClaim("account", "claude-code");
24485
+ if (!claim || !this.loginWindow.isCurrent(claim) || claim.backend !== "claude-code" || (ownClaim && claim.kind !== "web"))
24486
+ throw new ClaudeCredentialError("in-use");
24487
+ let writerFinished;
24488
+ const writerLife = new Promise(resolve => { writerFinished = resolve; });
24489
+ this.accountWriters.add(writerLife);
24490
+ const key = this.credentialKey("claude-code", profile);
24491
+ let release;
24492
+ const gate = new Promise(r => { release = r; });
24493
+ this.claudeCredentialChanges.set(key, gate);
24494
+ const generation = this.settingsGeneration, configImage = JSON.stringify([this.fleetConfig, readClassicBindingsStrict(this.dataDir)]);
24495
+ let committed = false, released = false;
24496
+ const releaseStarts = () => { if (released)
24497
+ return; released = true; if (this.claudeCredentialChanges.get(key) === gate)
24498
+ this.claudeCredentialChanges.delete(key); release(); };
24499
+ const check = () => {
24500
+ if (!authorized())
24501
+ throw new ClaudeCredentialError("session-changed");
24502
+ if (this.shuttingDown || this.settingsGeneration !== generation || JSON.stringify([this.fleetConfig, readClassicBindingsStrict(this.dataDir)]) !== configImage || !this.loginWindow.isCurrent(claim))
24503
+ throw new ClaudeCredentialError("conflict");
24504
+ for (const record of records)
24505
+ if (this.lifecycle.epochOf(record.name) !== record.epoch || this.daemons.get(record.name) !== (record.stopped ? undefined : record.daemon))
24506
+ throw new ClaudeCredentialError("conflict");
24507
+ const prior = this.claudeCredentialMetadata(profile);
24508
+ if ((prior?.revision ?? 0) !== revision)
24509
+ throw new ClaudeCredentialError("conflict");
24510
+ };
24511
+ const handles = new Map();
24512
+ const locked = async (index) => {
24513
+ if (index < records.length)
24514
+ return this.lifecycle.runTransition(records[index].name, async (handle) => { handles.set(handle.name, handle); return locked(index + 1); });
24515
+ check();
24516
+ if ([...this.credentialLeases.values()].some(lease => lease.key === key && lease.starting) || [...this.credentialOrphans.values()].some(orphan => orphan.key === key)) {
24517
+ this.recheckCredentialOrphans();
24518
+ throw new ClaudeCredentialError("in-use");
24519
+ }
24520
+ if (this.claudeCredentialConsumers(profile).revision !== before.revision)
24521
+ throw new ClaudeCredentialError("conflict");
24522
+ return changeIdleClaudeCredential({
24523
+ assertCurrent: check, releaseStarts, restart: change !== null,
24524
+ commit: () => { check(); const result = this.withClaudeVault(v => v.write(profile, revision, change, actor)); committed = true; return result; },
24525
+ consumers: records.map(record => ({ name: record.name,
24526
+ quiesce: () => record.daemon.quiesceClaudeCredential(),
24527
+ stop: async () => {
24528
+ const stopping = this.stopInstance(record.name, handles.get(record.name));
24529
+ record.epoch++;
24530
+ await stopping;
24531
+ record.stopped = true;
24532
+ record.retired = await record.daemon.claudeCredentialRetired();
24533
+ if (!record.retired) {
24534
+ this.credentialOrphans.set(Symbol(record.name), { key, backend: "claude-code", profile, ended: () => record.daemon.claudeCredentialRetired() });
24535
+ throw new ClaudeCredentialError("unavailable");
24536
+ }
24537
+ },
24538
+ current: () => !this.shuttingDown && (!record.stopped || record.retired) && this.settingsGeneration === generation && this.lifecycle.epochOf(record.name) === record.epoch && this.daemons.get(record.name) === (record.stopped ? undefined : record.daemon),
24539
+ recover: async () => {
24540
+ if (!record.stopped) {
24541
+ const stopping = this.stopInstance(record.name, handles.get(record.name));
24542
+ record.epoch++;
24543
+ await stopping;
24544
+ record.stopped = true;
24545
+ record.retired = await record.daemon.claudeCredentialRetired();
24546
+ if (!record.retired) {
24547
+ this.credentialOrphans.set(Symbol(record.name), { key, backend: "claude-code", profile, ended: () => record.daemon.claudeCredentialRetired() });
24548
+ throw new ClaudeCredentialError("unavailable");
24549
+ }
24550
+ }
24551
+ const current = () => !this.shuttingDown && this.settingsGeneration === generation && this.lifecycle.epochOf(record.name) === record.epoch;
24552
+ const execution = new SettingsExecution({ current, snapshot: () => null });
24553
+ try {
24554
+ execution.assert();
24555
+ const config = this.fleetConfig?.instances[record.name];
24556
+ if (config)
24557
+ await this.startInstance(record.name, config, daemonTopicMode(this.fleetConfig) ?? false, "fleet-topic", false, handles.get(record.name), execution);
24558
+ else {
24559
+ const room = this.classicChannels?.getAll().find(room => room.instanceName === record.name);
24560
+ if (!room)
24561
+ throw new ClaudeCredentialError("conflict");
24562
+ await this.startClassicInstance(record.name, this.classicChannels.getBackendByInstance(record.name, this.fleetConfig?.defaults?.backend), this.classicChannels.getPreTaskCommand(room.channelId, room.adapterId), this.classicChannels.getModel(room.channelId, room.adapterId, this.fleetConfig?.defaults?.model), this.classicChannels.getAutoPauseAfter(room.channelId, room.adapterId, this.fleetConfig?.defaults?.auto_pause_after), handles.get(record.name), execution);
24563
+ }
24564
+ }
24565
+ finally {
24566
+ execution.close();
24567
+ }
24568
+ }
24569
+ }))
24570
+ });
24571
+ };
24572
+ try {
24573
+ return await locked(0);
24574
+ }
24575
+ finally {
24576
+ releaseStarts();
24577
+ if (!ownClaim)
24578
+ this.loginWindow.release(claim);
24579
+ this.accountWriters.delete(writerLife);
24580
+ writerFinished();
24581
+ if (committed) {
24582
+ this.forgetSignInIdentities();
24583
+ this.usageAfterSignIn();
24584
+ broadcastSseEvent(this.sseClients, "backend_login", {}, () => { });
24585
+ }
24586
+ }
24587
+ }
24588
+ claudeSetupTokensInstance = null;
24589
+ claudeSetupTokenOperation(owner, request) {
24590
+ this.claudeSetupTokensInstance ??= new ClaudeSetupTokens({ lock: this.loginWindow,
24591
+ metadata: profile => this.claudeCredentialMetadata(profile),
24592
+ commit: (profile, revision, value, actor, confirmation, current, claim) => this.changeClaudeCredential(profile, revision, { kind: "setup-token", value }, actor, confirmation, () => !this.shuttingDown && current(), claim),
24593
+ });
24594
+ return this.claudeSetupTokensInstance.operation({ ...owner, current: () => !this.shuttingDown && owner.current() }, request);
24595
+ }
24596
+ /** M-3419: private host credential store. No secret is logged or returned by the metadata API. */
24597
+ withClaudeVault(fn) {
24598
+ const vault = new ClaudeCredentialVault(this.dataDir);
24599
+ try {
24600
+ return fn(vault);
24601
+ }
24602
+ finally {
24603
+ vault.close();
24604
+ }
24605
+ }
24606
+ claudeCredentialMetadata(profile) {
24607
+ if (profile !== null && !accountFolderExists(this.dataDir, "claude-code", profile))
24608
+ throw new ClaudeCredentialError("profile-unknown");
24609
+ return readClaudeCredentialSelection(this.dataDir, profile);
24610
+ }
24611
+ auditClaudeCredential(actor, action, outcome) {
24612
+ this.withClaudeVault(vault => vault.audit(actor, null, action, null, null, outcome));
24613
+ }
24614
+ writeClaudeCredential(profile, revision, change, actor) {
24615
+ if (profile !== null && !accountFolderExists(this.dataDir, "claude-code", profile))
24616
+ throw new ClaudeCredentialError("profile-unknown");
24617
+ // This storage slice never changes a credential underneath a current consumer or concurrent sign-in.
24618
+ // The integration slice supplies the explicit idle/restart confirmation before replacing a used profile.
24619
+ const uses = this.accountUses();
24620
+ if ([...uses.agents, ...uses.classic].some(x => x.backend === "claude-code" && x.profile === profile)
24621
+ || (profile !== null && uses.fleetDefaults.get("claude-code") === profile)
24622
+ || this.loginWindow.holderFor("claude-code")
24623
+ || this.keepAliveInUse("claude-code", profile))
24624
+ throw new ClaudeCredentialError("in-use");
24625
+ return this.withClaudeVault(vault => vault.write(profile, revision, change, actor));
24626
+ }
24283
24627
  /** #3212 PR 2: Settings → Accounts → + Add account (accounts-profiles.ts). `by`: the session's label, for the fleet log. */
24284
24628
  addAccountProfile(backend, name, by, machine) {
24285
24629
  // #3190 Part 3c: on a paired computer the profile's folder is made by its Runtime when the first sign-in starts; this only checks what can be checked first.
@@ -24312,6 +24656,23 @@ export class FleetManager {
24312
24656
  return this.machineAccounts.remove(backend, name, confirm, machine.id, machine, by); // #3190 Part 3c: that computer's Runtime deletes its own folder
24313
24657
  const profile = typeof name === "string" ? name : "";
24314
24658
  const shown = validCredentialProfileName(name) ? name : "(invalid)";
24659
+ // A profile name must not be recreated with an old managed secret still attached.
24660
+ const managedRefusal = () => {
24661
+ if (backend === "claude-code" && validCredentialProfileName(name)
24662
+ && existsSync(join(this.dataDir, "credential-vault", "claude.sqlite"))) {
24663
+ try {
24664
+ if (this.claudeCredentialMetadata(name)?.kind)
24665
+ return { ok: false, error: "credential_connected" };
24666
+ }
24667
+ catch {
24668
+ return { ok: false, error: "unsafe" };
24669
+ }
24670
+ }
24671
+ return null;
24672
+ };
24673
+ const managed = managedRefusal();
24674
+ if (managed)
24675
+ return managed;
24315
24676
  // #3321 review ("Cancel sign-in and remove"): the sign-in of exactly this account is ended first — no other account's, and a start whose profile is
24316
24677
  // not known yet is not guessed at — and every Remove check below is then made as usual: what is still signing in refuses (`signing_in`).
24317
24678
  if (opts?.cancelSignIn && validCredentialProfileName(name)) {
@@ -24327,6 +24688,9 @@ export class FleetManager {
24327
24688
  // (run with the folder, once every Remove check has passed) removes that item first. AgEnD never deletes it itself.
24328
24689
  // #3305 review: the logout holds the shared login window (no sign-in or other logout starts meanwhile), and after it
24329
24690
  // every check is made again — who uses it, sign-ins, ClassicBot's settings — on the same folder (its identity).
24691
+ const afterCancel = managedRefusal();
24692
+ if (afterCancel)
24693
+ return afterCancel;
24330
24694
  const signOutDeps = this.accountSignOutDeps ?? ACCOUNT_SIGN_OUT_DEPS;
24331
24695
  let keychainLeft = false;
24332
24696
  let removed;
@@ -24344,6 +24708,9 @@ export class FleetManager {
24344
24708
  if (!this.loginWindow.isCurrent(claim))
24345
24709
  return { ok: false, error: "failed" }; // the fleet is stopping
24346
24710
  keychainLeft = out.keychainLeft === true;
24711
+ const beforeDelete = managedRefusal();
24712
+ if (beforeDelete)
24713
+ return beforeDelete;
24347
24714
  return removeAccountProfile(this.dataDir, this.removalRequest(backend, name, confirm, claim), undefined, { expect: dry.identity });
24348
24715
  });
24349
24716
  if (!step.ok)
@@ -24473,6 +24840,8 @@ export class FleetManager {
24473
24840
  if (machine)
24474
24841
  return this.machineAccounts.signOut(backend, profile, confirm, machine.id, machine, by); // #3190 Part 3c: that computer's Runtime runs the CLI's own logout
24475
24842
  const named = typeof profile === "string" ? profile : null;
24843
+ if (backend === "claude-code" && claudeSubscriptionSuppressed(this.dataDir, named))
24844
+ return { ok: false, error: "unsafe" };
24476
24845
  const shown = named === null ? "(default)" : validCredentialProfileName(named) ? named : "(invalid)";
24477
24846
  // #3305 review P2-3: the logout holds the shared login window from before it runs until its cleanup is done — no
24478
24847
  // sign-in (chat, dashboard, install) and no other logout starts meanwhile; one already running refuses this.
@@ -24597,6 +24966,9 @@ export class FleetManager {
24597
24966
  }
24598
24967
  if (!opts.skipAuthCheck)
24599
24968
  this.recordLoginFlow(wanted, "login", chat.userId);
24969
+ const backend = LOGIN_BACKEND_ALIASES[backendArg.toLowerCase()] ?? backendArg.toLowerCase();
24970
+ if (backend === "claude-code" && claudeSubscriptionSuppressed(this.dataDir, opts.profile ?? null))
24971
+ return t("login.managed_credentials");
24600
24972
  return this.webLogin.start(backendArg, chat, opts);
24601
24973
  }
24602
24974
  /**
@@ -24849,6 +25221,9 @@ export class FleetManager {
24849
25221
  }
24850
25222
  /** The sign-in itself, in the web terminal, for a CLI that is installed. */
24851
25223
  async launchSignIn(backendArg, chat, opts = {}) {
25224
+ const backend = LOGIN_BACKEND_ALIASES[backendArg.toLowerCase()] ?? backendArg.toLowerCase();
25225
+ if (backend === "claude-code" && claudeSubscriptionSuppressed(this.dataDir, opts.profile ?? null))
25226
+ return t("login.managed_credentials");
24852
25227
  return this.webLogin.start(backendArg, chat, opts);
24853
25228
  }
24854
25229
  /** Fleet shutdown: end any web login or install window and wait for its confirmed teardown. */
@@ -24906,6 +25281,7 @@ export class FleetManager {
24906
25281
  // "cancelled" is the detail both legacy onDone handlers keep quiet about —
24907
25282
  // a stopping fleet must not announce "login failed — fleet shutdown".
24908
25283
  await Promise.all([
25284
+ bounded(this.claudeSetupTokensInstance?.close(), "setup-token"),
24909
25285
  bounded(this.browserBackendSignInsInstance?.close().then(confirmed => {
24910
25286
  if (confirmed)
24911
25287
  this.browserBackendSignInsInstance = null;
@@ -28098,7 +28474,8 @@ export class FleetManager {
28098
28474
  resolveInstanceEffort(instanceName) {
28099
28475
  if (isWindowsInstance(this.fleetConfig?.instances[instanceName]))
28100
28476
  return { effort: null, source: "unset" };
28101
- const own = this.fleetConfig?.instances[instanceName]?.effort;
28477
+ const own = this.fleetConfig?.instances[instanceName]?.effort
28478
+ ?? this.contactRoom(instanceName)?.effort;
28102
28479
  if (own)
28103
28480
  return { effort: own, source: "instance" };
28104
28481
  const fallback = this.fleetConfig?.defaults?.effort;
@@ -28337,6 +28714,7 @@ export class FleetManager {
28337
28714
  // ── #1806: /backend — another CLI backend, with its model and effort, in one write and one relaunch ──
28338
28715
  /** The steps' view of this fleet (backend-command.ts). `live`: a missing or stale model list may be probed (not on the web). */
28339
28716
  backendCommandDeps(instanceName, opts) {
28717
+ const classic = this.contactRoom(instanceName);
28340
28718
  return {
28341
28719
  currentBackend: (name) => this.backendNameForInstance(name),
28342
28720
  currentDisplay: (name) => `${this.backendNameForInstance(name)} · ${this.resolveInstanceModel(name).display}`,
@@ -28346,7 +28724,8 @@ export class FleetManager {
28346
28724
  modelKnown: (backend, model) => this.backendModelVerdict(instanceName, backend, model).ok,
28347
28725
  effortLevels: (backend, model) => this.backendEffortLevels(instanceName, backend, model),
28348
28726
  inherited: (key) => {
28349
- const value = getEffectiveInstanceDefaults(this.fleetConfig?.defaults)[key];
28727
+ const value = (key === "model" && classic ? this.classicChannels?.getDefaults().model : undefined)
28728
+ ?? getEffectiveInstanceDefaults(this.fleetConfig?.defaults)[key];
28350
28729
  return typeof value === "string" && value ? value : undefined;
28351
28730
  },
28352
28731
  modelCompatible: (backend, model) => isModelCompatible(backend, model),
@@ -28354,7 +28733,8 @@ export class FleetManager {
28354
28733
  const status = this.getInstanceStatus(name);
28355
28734
  return { running: status === "running", busy: status === "running" && !this.getInstanceIdle(name), status };
28356
28735
  },
28357
- t: (key, ...args) => t(key, ...args),
28736
+ confirmationNotice: () => classic?.restrictedMode === true ? t("classic.restricted_backend_notice") : undefined,
28737
+ t: (key, ...args) => t(classic && key === "backend.default_inherited" ? "backend.default_classic_inherited" : key, ...args),
28358
28738
  };
28359
28739
  }
28360
28740
  /**
@@ -28647,14 +29027,30 @@ export class FleetManager {
28647
29027
  * #1806 review: the instance a `/backend` was asked about is still this config entry — not one deleted and created
28648
29028
  * again under the same name, or replaced by a Settings edit (both put a new object there), stopped or not.
28649
29029
  */
28650
- backendTargetIs(instanceName, target) {
29030
+ backendCommandTarget(instanceName) {
28651
29031
  const instances = this.fleetConfig?.instances;
28652
- return !!target && !!instances && Object.prototype.hasOwnProperty.call(instances, instanceName) && instances[instanceName] === target;
29032
+ const fleet = instances && Object.hasOwn(instances, instanceName) ? instances[instanceName] : undefined;
29033
+ const rooms = (this.classicChannels?.getAll?.() ?? []).filter(room => room.instanceName === instanceName);
29034
+ if (fleet)
29035
+ return rooms.length ? undefined : { value: fleet };
29036
+ if (rooms.length !== 1)
29037
+ return undefined;
29038
+ try {
29039
+ return { value: rooms[0], classicSnapshot: createHash("sha256")
29040
+ .update(readFileSync(join(this.dataDir, "classicBot.yaml"))).update("\0")
29041
+ .update(JSON.stringify(this.fleetConfig?.defaults ?? {})).digest("hex") };
29042
+ }
29043
+ catch {
29044
+ return undefined;
29045
+ }
29046
+ }
29047
+ backendTargetIs(instanceName, target) {
29048
+ const now = this.backendCommandTarget(instanceName);
29049
+ return !!target && now?.value === target.value && now.classicSnapshot === target.classicSnapshot;
28653
29050
  }
28654
- /** `/backend` is for fleet.yaml instances: update_instance_config does not manage a ClassicBot agent. */
29051
+ /** An absent, ambiguous or unreadable room is never a backend-switch target. */
28655
29052
  backendCommandRefusal(instanceName) {
28656
- return this.fleetConfig?.instances && Object.prototype.hasOwnProperty.call(this.fleetConfig.instances, instanceName)
28657
- ? null : t("backend.classic_unsupported", instanceName);
29053
+ return this.backendCommandTarget(instanceName) ? null : t("classic.no_agent");
28658
29054
  }
28659
29055
  /**
28660
29056
  * Apply a confirmed `/backend`: judged again first (a menu lives a minute — the backend may have moved, a CLI been
@@ -28678,6 +29074,15 @@ export class FleetManager {
28678
29074
  return t("menu.click_stale");
28679
29075
  const { plan } = step;
28680
29076
  const shown = planDisplay(deps, plan);
29077
+ const room = this.contactRoom(instanceName);
29078
+ if (room && !Object.hasOwn(this.fleetConfig?.instances ?? {}, instanceName)) {
29079
+ const saved = await switchClassicRoomBackend(this, room, plan, from, stillCurrent);
29080
+ if (!saved.ok)
29081
+ return t("backend.failed", instanceName, plan.backend, saved.error);
29082
+ return this.getInstanceStatus(instanceName) === "running"
29083
+ ? t("backend.switched", instanceName, plan.backend, shown.model, shown.effort)
29084
+ : t("backend.switched_not_running", instanceName, plan.backend, shown.model, shown.effort, this.getInstanceStatus(instanceName));
29085
+ }
28681
29086
  const { value, error } = await new Promise(resolve => {
28682
29087
  applyInstanceConfigPatch(this, instanceName, { backend: plan.backend, model: plan.model, effort: plan.effort }, (value, error) => resolve({ value, error }));
28683
29088
  });
@@ -28765,7 +29170,7 @@ export class FleetManager {
28765
29170
  await pending.respond(text);
28766
29171
  return undefined;
28767
29172
  }
28768
- /** Start `/backend` for a fleet instance from Discord or Telegram; the caller has checked the channel admin. */
29173
+ /** Start the shared `/backend` picker for a Fleet instance or ClassicBot room. */
28769
29174
  async beginBackendCommand(place, args) {
28770
29175
  const refusal = this.backendCommandRefusal(place.instanceName);
28771
29176
  if (refusal) {
@@ -28776,12 +29181,16 @@ export class FleetManager {
28776
29181
  await place.respond(t("backend.usage"));
28777
29182
  return;
28778
29183
  }
28779
- place = { ...place, target: this.fleetConfig.instances[place.instanceName] };
29184
+ place = { ...place, target: this.backendCommandTarget(place.instanceName) };
28780
29185
  const deps = this.backendCommandDeps(place.instanceName, {
28781
29186
  live: true,
28782
29187
  onLiveProbe: () => { void place.respond(t("model.refreshing")).catch(() => { }); },
28783
29188
  });
28784
29189
  const step = await backendStep(deps, place.instanceName, args);
29190
+ if (!this.backendTargetIs(place.instanceName, place.target)) {
29191
+ await place.respond(t("menu.click_stale"));
29192
+ return;
29193
+ }
28785
29194
  if (step.kind === "refuse") {
28786
29195
  await place.respond(step.text);
28787
29196
  return;
@@ -28813,6 +29222,10 @@ export class FleetManager {
28813
29222
  /** Telegram `/backend` in a fleet topic (topic-commands) or a ClassicBot chat; the caller has checked the admin. */
28814
29223
  async runBackendCommand(instanceName, text, userId, channelId, adapter, chatId, threadId, adapterId) {
28815
29224
  const respond = async (reply) => (await adapter.sendText(chatId, reply, { threadId })).messageId;
29225
+ if (!this.isModelAdmin(userId, channelId, adapterId)) {
29226
+ await respond(t("permission.denied"));
29227
+ return;
29228
+ }
28816
29229
  await this.beginBackendCommand({ instanceName, userId, channelId, adapterId, respond, adapter, adapterChatId: chatId, adapterThreadId: threadId }, backendArgs(text.replace(/^\/backend(@\S+)?/, "")));
28817
29230
  }
28818
29231
  /** Consume a `/backend` click: the next step, or on the confirmation the switch itself. True for every backend-select id. */
@@ -28849,6 +29262,10 @@ export class FleetManager {
28849
29262
  return true;
28850
29263
  }
28851
29264
  const next = await backendStep(this.backendCommandDeps(pending.instanceName, { live: true }), pending.instanceName, [...step.args, choice.token]);
29265
+ if (!this.backendTargetIs(pending.instanceName, pending.target)) {
29266
+ await this.endBackendMenu(pending, t("menu.click_stale")).catch(() => { });
29267
+ return true;
29268
+ }
28852
29269
  if (next.kind === "refuse") {
28853
29270
  await this.endBackendMenu(pending, next.text).catch(() => { });
28854
29271
  return true;
@@ -29151,6 +29568,7 @@ export class FleetManager {
29151
29568
  reply_completion_guard: replyCompletionGuard ?? true,
29152
29569
  ...(backend ? { backend } : {}),
29153
29570
  ...(model ? { model } : {}),
29571
+ ...(classicIdentity?.effort ? { effort: classicIdentity.effort } : {}),
29154
29572
  ...(classicIdentity?.displayName ? { display_name: classicIdentity.displayName } : {}),
29155
29573
  ...(classicIdentity?.description ? { description: classicIdentity.description } : {}),
29156
29574
  ...(autoPauseAfter !== undefined ? { auto_pause_after: autoPauseAfter } : {}),
@@ -29387,7 +29805,8 @@ export class FleetManager {
29387
29805
  this.ownerAppControl = null;
29388
29806
  const ownerAppStopped = ownerAppControl?.close();
29389
29807
  this.publicLinkAutoOpen?.stop();
29390
- const publicStopped = this.publicWebLink?.close("fleet shutdown");
29808
+ // M-3399: a stop (a restart, an update) is not a person closing the link: the fixed link's sessions are kept.
29809
+ const publicStopped = this.publicWebLink?.close("fleet shutdown", undefined, { keepNamedSessions: true });
29391
29810
  this.webRemoteAccessState?.close(); // #3008: an unsaved switch gets its last write
29392
29811
  const sharesStopped = this.officeSharesInstance?.close(); // #2636: every Office share ends, and its tunnel
29393
29812
  // #1386: every live "Needs you" message says the fleet stopped (capabilities revoked first) — while the