@songsid/agend 2.4.0-beta.17 → 2.4.0-beta.18

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 (112) hide show
  1. package/dist/backend/claude-code.js +6 -2
  2. package/dist/backend/claude-code.js.map +1 -1
  3. package/dist/backend/claude-transcript-errors.d.ts +4 -0
  4. package/dist/backend/claude-transcript-errors.js +5 -1
  5. package/dist/backend/claude-transcript-errors.js.map +1 -1
  6. package/dist/build-provenance.json +1 -1
  7. package/dist/cli-audited.js +6 -5
  8. package/dist/cli-audited.js.map +1 -1
  9. package/dist/daemon.d.ts +8 -0
  10. package/dist/daemon.js +62 -13
  11. package/dist/daemon.js.map +1 -1
  12. package/dist/fleet-context.d.ts +1 -0
  13. package/dist/fleet-manager.d.ts +15 -1
  14. package/dist/fleet-manager.js +96 -9
  15. package/dist/fleet-manager.js.map +1 -1
  16. package/dist/fleet-windows-runtime.d.ts +1 -1
  17. package/dist/fleet-windows-runtime.js +1 -1
  18. package/dist/fleet-windows-runtime.js.map +1 -1
  19. package/dist/fleet-yaml-stringify.d.ts +3 -0
  20. package/dist/fleet-yaml-stringify.js +79 -0
  21. package/dist/fleet-yaml-stringify.js.map +1 -0
  22. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +10 -2
  23. package/dist/host-monitoring-alert-policy.d.ts +71 -0
  24. package/dist/host-monitoring-alert-policy.js +150 -0
  25. package/dist/host-monitoring-alert-policy.js.map +1 -0
  26. package/dist/host-monitoring-alert-resources.d.ts +11 -0
  27. package/dist/host-monitoring-alert-resources.js +16 -0
  28. package/dist/host-monitoring-alert-resources.js.map +1 -0
  29. package/dist/host-monitoring-alert-settings.d.ts +14 -0
  30. package/dist/host-monitoring-alert-settings.js +63 -0
  31. package/dist/host-monitoring-alert-settings.js.map +1 -0
  32. package/dist/host-monitoring-alert-store.d.ts +49 -0
  33. package/dist/host-monitoring-alert-store.js +228 -0
  34. package/dist/host-monitoring-alert-store.js.map +1 -0
  35. package/dist/host-monitoring-alert-text.d.ts +7 -0
  36. package/dist/host-monitoring-alert-text.js +10 -0
  37. package/dist/host-monitoring-alert-text.js.map +1 -0
  38. package/dist/host-monitoring-alerts.d.ts +76 -0
  39. package/dist/host-monitoring-alerts.js +261 -0
  40. package/dist/host-monitoring-alerts.js.map +1 -0
  41. package/dist/host-monitoring-footprint-policy.d.ts +45 -0
  42. package/dist/host-monitoring-footprint-policy.js +150 -0
  43. package/dist/host-monitoring-footprint-policy.js.map +1 -0
  44. package/dist/host-monitoring-footprint.d.ts +42 -0
  45. package/dist/host-monitoring-footprint.js +169 -0
  46. package/dist/host-monitoring-footprint.js.map +1 -0
  47. package/dist/host-monitoring-history-policy.d.ts +2 -0
  48. package/dist/host-monitoring-history-policy.js +16 -2
  49. package/dist/host-monitoring-history-policy.js.map +1 -1
  50. package/dist/host-monitoring-history-store.js +8 -6
  51. package/dist/host-monitoring-history-store.js.map +1 -1
  52. package/dist/host-monitoring-history-worker.js +19 -3
  53. package/dist/host-monitoring-history-worker.js.map +1 -1
  54. package/dist/host-monitoring-history.d.ts +9 -0
  55. package/dist/host-monitoring-history.js +45 -9
  56. package/dist/host-monitoring-history.js.map +1 -1
  57. package/dist/host-monitoring-process-identity.d.ts +8 -0
  58. package/dist/host-monitoring-process-identity.js +81 -0
  59. package/dist/host-monitoring-process-identity.js.map +1 -0
  60. package/dist/host-monitoring-runtime.d.ts +8 -0
  61. package/dist/host-monitoring-runtime.js +18 -3
  62. package/dist/host-monitoring-runtime.js.map +1 -1
  63. package/dist/host-monitoring.d.ts +2 -0
  64. package/dist/host-monitoring.js.map +1 -1
  65. package/dist/instance-lifecycle.js +2 -2
  66. package/dist/instance-lifecycle.js.map +1 -1
  67. package/dist/needs-you-hub.d.ts +1 -0
  68. package/dist/needs-you-hub.js +1 -0
  69. package/dist/needs-you-hub.js.map +1 -1
  70. package/dist/needs-you.d.ts +3 -2
  71. package/dist/needs-you.js +1 -0
  72. package/dist/needs-you.js.map +1 -1
  73. package/dist/public-web-gateway.js +7 -1
  74. package/dist/public-web-gateway.js.map +1 -1
  75. package/dist/runtime-cli-install.js +9 -9
  76. package/dist/runtime-cli-install.js.map +1 -1
  77. package/dist/settings-api.d.ts +2 -0
  78. package/dist/settings-api.js +56 -0
  79. package/dist/settings-api.js.map +1 -1
  80. package/dist/settings-baseline.js +5 -4
  81. package/dist/settings-baseline.js.map +1 -1
  82. package/dist/settings-effect.d.ts +2 -0
  83. package/dist/settings-effect.js +20 -1
  84. package/dist/settings-effect.js.map +1 -1
  85. package/dist/topic-commands.js +4 -0
  86. package/dist/topic-commands.js.map +1 -1
  87. package/dist/ui/chat-store.js +21 -4
  88. package/dist/ui/host-alerts.js +23 -0
  89. package/dist/ui/host-footprint.js +17 -0
  90. package/dist/ui/host-health.js +17 -12
  91. package/dist/ui/host-time.js +5 -0
  92. package/dist/ui/panel-chat.js +2 -0
  93. package/dist/ui/panel-needs.js +27 -16
  94. package/dist/ui/panel-settings.js +1 -0
  95. package/dist/ui/settings-host-alerts.js +22 -0
  96. package/dist/ui/settings-host-monitoring.js +8 -7
  97. package/dist/ui/shared/app-i18n.js +2 -2
  98. package/dist/ui/shared/app.css +50 -9
  99. package/dist/ui/shared/chat-render.js +24 -9
  100. package/dist/ui/shared/chat-strings.js +2 -2
  101. package/dist/ui/shared/chat-thread.js +3 -1
  102. package/dist/web-api.d.ts +2 -1
  103. package/dist/web-api.js +197 -6
  104. package/dist/web-api.js.map +1 -1
  105. package/dist/web-chat-history.d.ts +40 -1
  106. package/dist/web-chat-history.js +131 -9
  107. package/dist/web-chat-history.js.map +1 -1
  108. package/dist/web-guest-access.js +4 -4
  109. package/dist/web-guest-access.js.map +1 -1
  110. package/dist/web-upload.d.ts +1 -1
  111. package/dist/web-upload.js.map +1 -1
  112. package/package.json +1 -1
@@ -196,6 +196,7 @@ export function createThread(list, scroller, opts) {
196
196
  if (x.role === "status") return statusHtml(x, time);
197
197
  const u = opts.isUser(x);
198
198
  // renderMarkdown escapes the whole text before it adds any tag of its own (chat-render.js).
199
+ const resend = opts.canResend?.(x) ? `<div data-trust="thread-control" class="msg-resend"><span class="muted">${escAttr(tr("chat.tick_failed"))} ·</span><button type="button" class="btn btn-sm" data-act="resend" data-arg="${escAttr(msgKey(x))}" ${x.resending ? "disabled" : ""}>${escAttr(tr(x.resending ? "chat.resending" : "chat.resend"))}</button></div>` : "";
199
200
  const ticks = u && x.delivery ? R().deliveryHtml(x.delivery, TICKS()) : "";
200
201
  const tools = u ? "" : `<div data-trust="thread-control" class="msg-tools"><button type="button" class="chip-btn icon-only" data-act="copyMsg" data-arg="${escAttr(msgKey(x))}" title="${escAttr(tr("chat.copyMessage"))}" aria-label="${escAttr(tr("chat.copyMessage"))}">${COPY}</button></div>`;
201
202
  const buttons = x.role === "agent" ? replyButtonsHtml(x.buttons) : "";
@@ -213,7 +214,7 @@ export function createThread(list, scroller, opts) {
213
214
  // M-3339: a contact request's badge (聯絡申請 #R… / 已准轉交 #R…) — escaped HTML from the Fleet chat's hook; a Hub passes none.
214
215
  const contact = typeof opts.contactBadge === "function" && x.contactTicket ? String(opts.contactBadge(x) || "") : "";
215
216
  // M-3092 (Hub rooms): another person's message, a bubble on the left (`msg-person`); the fleet never sets x.person.
216
- return `<div class="msg ${u ? "user" : "agent"}${x.person ? " msg-person" : ""}" data-key="${escAttr(key)}" tabindex="-1">${act}<div class="meta"><span class="sender"${badge}>${escAttr(x.sender)}</span>${time}${ticks}${contact}</div>${quoteHtml(x.replyTo)}<div class="body">${clicked ? clickHtml(x.click) : `<div class="md">${renderedMarkdown(x.text, x.role === "agent", opts.emojis, opts.mentions, opts.mentionLabels?.())}</div>`}${R().attachmentsHtml(x.attachments, { htmlCards: x.role === "agent", goneTitle: tr(x.archived ? "chat.attNotKeptTitle" : "chat.attGone"), goneLabel: tr(x.archived ? "chat.attNotKept" : "chat.attUnavailable"), inlinePreviews: !PUBLIC_LINK(), textPreviews: true })}${buttons}</div>${Array.isArray(x.reactionBar) ? reactBarHtml(x, key, reactable) : R().reactionsHtml(x.reactions, tr("chat.reactedBy", x.instance || ""))}${tools}</div>`;
217
+ return `<div class="msg ${u ? "user" : "agent"}${x.person ? " msg-person" : ""}" data-key="${escAttr(key)}" tabindex="-1">${act}<div class="meta"><span class="sender"${badge}>${escAttr(x.sender)}</span>${time}${ticks}${contact}</div>${quoteHtml(x.replyTo)}<div class="body">${clicked ? clickHtml(x.click) : `<div class="md">${renderedMarkdown(x.text, x.role === "agent", opts.emojis, opts.mentions, opts.mentionLabels?.())}</div>`}${R().attachmentsHtml(x.attachments, { htmlCards: x.role === "agent", goneTitle: tr(x.archived ? "chat.attNotKeptTitle" : "chat.attGone"), goneLabel: tr(x.archived ? "chat.attNotKept" : "chat.attUnavailable"), inlinePreviews: !PUBLIC_LINK(), textPreviews: true })}${buttons}</div>${Array.isArray(x.reactionBar) ? reactBarHtml(x, key, reactable) : R().reactionsHtml(x.reactions, tr("chat.reactedBy", x.instance || ""))}${tools}${resend}</div>`;
217
218
  }
218
219
  /** M-3127: a room's words for its reaction controls (opts.reactText(key)), English when the page gives none. */
219
220
  function reactText(k, ...a) {
@@ -1062,6 +1063,7 @@ export function createThread(list, scroller, opts) {
1062
1063
  else if (act === "reactAdd") { closePicker(true); reactFrom(el, true); } // a quick pick: mine added
1063
1064
  else if (act === "reactToggle") reactFrom(el, el.getAttribute("aria-pressed") !== "true"); // a chip: mine on or off
1064
1065
  else if (act === "jumpQuote") void jumpTo(el.dataset.arg);
1066
+ else if (act === "resend") opts.resendMessage?.(el.dataset.arg);
1065
1067
  else if (act === "retryOut") opts.retryOutgoing?.(el.dataset.arg); // a failed send, again
1066
1068
  else if (act === "putBackOut") opts.putBackOutgoing?.(el.dataset.arg); // back in the composer, to change it
1067
1069
  else if (act === "deleteOut") opts.deleteOutgoing?.(el.dataset.arg);
package/dist/web-api.d.ts CHANGED
@@ -60,7 +60,8 @@ export type AccountWriteResult = {
60
60
  };
61
61
  export interface WebApiContext extends ClaudeCredentialApi {
62
62
  hostHistoryQuery?(range: unknown, series: unknown): Promise<import('./host-monitoring-history.js').HostHistoryResult>;
63
- hostHealthSnapshot?(): import("./host-monitoring.js").HostHealthSnapshot;
63
+ hostHealthSnapshot?(agentOffset?: number): import("./host-monitoring.js").HostHealthSnapshot;
64
+ hostAlertAction?(key: string, revision: number, actor: string, snoozeMs?: number): Promise<boolean>;
64
65
  clearContactOrigin?: ContactApiHost["clearContactOrigin"];
65
66
  contactPermissions?: ContactApiHost["contactPermissions"];
66
67
  writeContactPermissions?: ContactApiHost["writeContactPermissions"];
package/dist/web-api.js CHANGED
@@ -43,7 +43,7 @@ import { MAX_COMMAND_ARGS } from "./web-commands.js";
43
43
  import { ROUTE_WORKER_CSP, ROUTE_WORKER_PATH, sendPanelHtml } from "./web-host-guard.js";
44
44
  import { libavoidFile } from "./web-libavoid.js";
45
45
  import { shellRoute } from "./web-shell-routes.js";
46
- import { createReadStream, createWriteStream, existsSync, readFileSync } from "node:fs";
46
+ import { createReadStream, createWriteStream, existsSync, readFileSync, closeSync } from "node:fs";
47
47
  import { servedAssets } from "./auth-api.js";
48
48
  import { assetIntact, assetsUnchanged, assetVersion, assetVersionMark, answerStaleAsset, buildModuleGraph, staticClosure, versionShell, IMMUTABLE_PRIVATE } from "./web-asset-version.js";
49
49
  import { join, dirname } from "node:path";
@@ -223,6 +223,9 @@ const safeInstanceSegment = (name) => /^[^\\/\x00]+$/.test(name) && name !== "."
223
223
  const streamGuests = new WeakMap();
224
224
  const streamContactProjection = new WeakMap();
225
225
  function contactNeedsFor(req, url, ctx, base) {
226
+ const auth = evaluateWebRequest(req, url, ctx.webToken ?? null, ctx.webSessions, { touch: false });
227
+ const admin = auth.kind === 'allow' && auth.via === 'session' && auth.session.tier === 'admin';
228
+ base = admin ? base : base.filter(item => !item || typeof item !== 'object' || item.type !== 'host');
226
229
  const ordinary = base.filter(item => !item || typeof item !== "object" || item.type !== "contact");
227
230
  const actor = ctx.contactActor?.(req, url);
228
231
  if (actor && ctx.contactNeeds)
@@ -2661,6 +2664,39 @@ export function handleWebRequest(req, res, url, ctx) {
2661
2664
  json(res, 503, { error: "history_unavailable" }); });
2662
2665
  return true;
2663
2666
  }
2667
+ if (path === '/ui/host-alert-action') {
2668
+ res.setHeader('Cache-Control', 'private, no-store');
2669
+ const auth = () => evaluateWebRequest(req, url, ctx.webToken ?? null, ctx.webSessions, { touch: false });
2670
+ const who = auth();
2671
+ if (who.kind !== 'allow' || who.via !== 'session' || who.session.tier !== 'admin') {
2672
+ json(res, 403, { error: 'admin_session_required' });
2673
+ return true;
2674
+ }
2675
+ if (method !== 'POST' || url.search) {
2676
+ json(res, 400, { error: 'invalid_host_alert_action' });
2677
+ return true;
2678
+ }
2679
+ void readBoundedWebBody(req, 2048).then(async (bytes) => {
2680
+ const current = () => { const value = auth(); return value.kind === 'allow' && value.via === 'session' && value.session.tier === 'admin' && value.session.idHash === who.session.idHash; };
2681
+ if (!current())
2682
+ return json(res, 403, { error: 'admin_session_required' });
2683
+ let input;
2684
+ try {
2685
+ input = JSON.parse(bytes.toString('utf8'));
2686
+ }
2687
+ catch {
2688
+ return json(res, 400, { error: 'invalid_host_alert_action' });
2689
+ }
2690
+ if (!input || Array.isArray(input) || Object.keys(input).some(k => !['key', 'revision', 'snoozeMs'].includes(k)) || typeof input.key !== 'string' || !/^[a-zA-Z0-9:_-]{1,128}$/.test(input.key) || !Number.isSafeInteger(input.revision) || input.revision < 1 || (input.snoozeMs !== undefined && (!Number.isSafeInteger(input.snoozeMs) || input.snoozeMs < 60000 || input.snoozeMs > 86400000)))
2691
+ return json(res, 400, { error: 'invalid_host_alert_action' });
2692
+ const ok = await ctx.hostAlertAction?.(input.key, input.revision, 'web:' + who.session.idHash, input.snoozeMs);
2693
+ if (!current())
2694
+ return json(res, 403, { error: 'admin_session_required' });
2695
+ json(res, ok ? 200 : 409, { ok: !!ok, ...(!ok ? { error: 'host_alert_stale' } : {}) });
2696
+ }).catch(() => { if (!res.headersSent)
2697
+ json(res, 503, { error: 'host_alert_unavailable' }); });
2698
+ return true;
2699
+ }
2664
2700
  if (path === "/ui/host-health") {
2665
2701
  res.setHeader("Cache-Control", "private, no-store");
2666
2702
  const who = evaluateWebRequest(req, url, ctx.webToken ?? null, ctx.webSessions, { touch: false });
@@ -2668,7 +2704,7 @@ export function handleWebRequest(req, res, url, ctx) {
2668
2704
  json(res, 403, { error: "admin_session_required" });
2669
2705
  return true;
2670
2706
  }
2671
- if (method !== "GET" || url.search) {
2707
+ if (method !== "GET" || [...url.searchParams.keys()].some(k => k !== "agentOffset") || url.searchParams.getAll("agentOffset").length > 1 || !/^(?:0|50|100)$/.test(url.searchParams.get("agentOffset") ?? "0")) {
2672
2708
  json(res, 400, { error: "invalid_host_health_request" });
2673
2709
  return true;
2674
2710
  }
@@ -2676,7 +2712,7 @@ export function handleWebRequest(req, res, url, ctx) {
2676
2712
  json(res, 503, { error: "host_monitoring_unavailable" });
2677
2713
  return true;
2678
2714
  }
2679
- json(res, 200, ctx.hostHealthSnapshot());
2715
+ json(res, 200, ctx.hostHealthSnapshot(Number(url.searchParams.get("agentOffset") ?? 0)));
2680
2716
  return true;
2681
2717
  }
2682
2718
  // Auth check for all /ui routes. Defence in depth behind the fleet-manager
@@ -3110,7 +3146,7 @@ export function handleWebRequest(req, res, url, ctx) {
3110
3146
  streamGuests.set(res, guest);
3111
3147
  guest.streamOpened?.();
3112
3148
  }
3113
- if (!guest && ctx.contactActor)
3149
+ if (!guest)
3114
3150
  streamContactProjection.set(res, (event, value) => {
3115
3151
  if (event === "needs")
3116
3152
  return { items: contactNeedsFor(req, url, ctx, (value && typeof value === "object" && Array.isArray(value.items)) ? value.items : []) };
@@ -3230,7 +3266,7 @@ export function handleWebRequest(req, res, url, ctx) {
3230
3266
  // #2848: the chat has messages, none of them a guest's to see (all between agents, or kept before they were marked):
3231
3267
  // said, so its empty chat is explained rather than blank. Only that there are some — never how many, or what.
3232
3268
  const allHidden = !!guest && messages.length === 0 && (ctx.webChatHistory?.list(instance, 1).length ?? 0) > 0;
3233
- json(res, 200, { messages, boot: ctx.webChatHistory?.boot ?? null, lastId: ctx.webChatHistory?.lastId ?? 0, ...(allHidden ? { allHidden: true } : {}) });
3269
+ json(res, 200, { messages, resendOwner: webPersonOf(req, url, ctx)?.voterKey ?? null, boot: ctx.webChatHistory?.boot ?? null, lastId: ctx.webChatHistory?.lastId ?? 0, ...(allHidden ? { allHidden: true } : {}) });
3234
3270
  return true;
3235
3271
  }
3236
3272
  // ── M-3272: scrolling back past the 500-message window (the archive, web-chat-archive.ts) ──
@@ -3561,6 +3597,11 @@ export function handleWebRequest(req, res, url, ctx) {
3561
3597
  return true;
3562
3598
  }
3563
3599
  // ── Send message ───────────────────────────────────────
3600
+ if (method === "POST" && path === "/ui/resend") {
3601
+ void handleResendMessage(req, res, ctx).catch(() => { if (!res.destroyed && !res.headersSent)
3602
+ json(res, 503, { error: "Resend unavailable" }); });
3603
+ return true;
3604
+ }
3564
3605
  if (method === "POST" && path === "/ui/send") {
3565
3606
  handleSendMessage(req, res, ctx);
3566
3607
  return true;
@@ -5952,6 +5993,156 @@ function webSendDedupeOf(ctx) {
5952
5993
  webSendDedupes.set(ctx, d = new WebSendDedupe());
5953
5994
  return d;
5954
5995
  }
5996
+ /** Resend only retained server content, with one new attempt on the same bubble. */
5997
+ async function handleResendMessage(req, res, ctx) {
5998
+ const url = new URL(req.url ?? "/", "http://localhost"), arrival = webAuthorityOf(req, url, ctx);
5999
+ let raw;
6000
+ try {
6001
+ raw = JSON.parse((await readBoundedWebBody(req, 8192)).toString("utf8"));
6002
+ }
6003
+ catch {
6004
+ json(res, 400, { error: "Invalid resend request" });
6005
+ return;
6006
+ }
6007
+ if (!permitWebContinuation(req, res, ctx))
6008
+ return;
6009
+ const parsed = z.object({ instance: z.string().min(1).max(128), boot: z.string().regex(/^[0-9a-f]{1,32}$/),
6010
+ id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), attempt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) }).strict().safeParse(raw);
6011
+ if (!parsed.success) {
6012
+ json(res, 400, { error: "Invalid resend request" });
6013
+ return;
6014
+ }
6015
+ const { instance, boot, id, attempt } = parsed.data, history = ctx.webChatHistory;
6016
+ const person = webPersonOf(req, url, ctx), guest = guestRequestOf(req), refused = guestChatRefusal(guest, instance);
6017
+ if (!person) {
6018
+ json(res, 401, { error: WEB_TOKEN_INVALID_MESSAGE });
6019
+ return;
6020
+ }
6021
+ if (refused) {
6022
+ json(res, refused.status, { error: refused.error });
6023
+ return;
6024
+ }
6025
+ const native = isWindowsInstance(ctx.fleetConfig?.instances[instance]);
6026
+ if (native && !nativeCliAuthorization(req, url, ctx)) {
6027
+ json(res, 403, { error: "Windows runtime requires an administrator on the local dashboard" });
6028
+ return;
6029
+ }
6030
+ const row = history?.find(instance, boot, id);
6031
+ if (!row || row.role !== "user" || row.retry?.owner !== person.voterKey || (guest && !guestSeesMessage(row, guest, guest.scope()))) {
6032
+ json(res, 404, { error: "Message is not available to resend" });
6033
+ return;
6034
+ }
6035
+ if (native && row.attachments?.length) {
6036
+ json(res, 400, { error: "Attachments are not supported by this runtime yet" });
6037
+ return;
6038
+ }
6039
+ if (guest && guestCommandText(row.text)) {
6040
+ json(res, 403, { error: "guest_no_commands" });
6041
+ return;
6042
+ }
6043
+ if (gatewayRequestContext(req) && row.text.startsWith("/raw ") && !adminAdmissionOf(req, url, ctx)) {
6044
+ json(res, 403, { error: t("web.raw_public_refused") });
6045
+ return;
6046
+ }
6047
+ const registered = registeredChatInstance(ctx, instance);
6048
+ if (!registered && !ctx.instanceIpcClients.has(instance)) {
6049
+ json(res, 404, { error: "Instance not found" });
6050
+ return;
6051
+ }
6052
+ const admission = admissionOf(req, url, ctx);
6053
+ const authorityCurrent = () => admission !== null && admissionOf(req, url, ctx) === admission
6054
+ && webPersonOf(req, url, ctx)?.voterKey === person.voterKey
6055
+ && (!guest || (guest.current() && !guestChatRefusal(guest, instance)))
6056
+ && (native ? isWindowsInstance(ctx.fleetConfig?.instances[instance]) && nativeCliAuthorization(req, url, ctx)
6057
+ : registered ? registeredChatInstance(ctx, instance) : ctx.instanceIpcClients.has(instance));
6058
+ const stillCurrent = () => !res.destroyed && authorityCurrent();
6059
+ const update = () => ctx.emitSseEvent("delivery", { instance, boot: row.boot, id: row.id, messageId: row.messageId, delivery: row.delivery, retry: row.retry });
6060
+ if (row.retry.attempt === attempt + 1 && row.delivery !== "failed") {
6061
+ json(res, 200, { sent: true, repeated: true, message: row });
6062
+ return;
6063
+ }
6064
+ if (row.delivery !== "failed" || row.retry.attempt !== attempt) {
6065
+ json(res, 409, { error: "This delivery changed; refresh and try again" });
6066
+ return;
6067
+ }
6068
+ const quoted = row.replyTo ? history.find(instance, row.replyTo.boot, row.replyTo.id) : undefined;
6069
+ if (row.replyTo && (!quoted || (guest && !guestSeesMessage(quoted, guest, guest.scope())))) {
6070
+ json(res, 409, { error: t("web.reply_gone"), reason: "reply_gone" });
6071
+ return;
6072
+ }
6073
+ const files = [];
6074
+ const limits = uploadLimits(ctx.fleetConfig?.web, { publicLink: gatewayRequestContext(req) !== undefined });
6075
+ let totalBytes = 0;
6076
+ if ((row.attachments?.length ?? 0) > limits.maxFiles) {
6077
+ json(res, 409, { error: "The attachments exceed the current file limit", reason: "attachment_gone" });
6078
+ return;
6079
+ }
6080
+ for (const attachment of row.attachments ?? []) {
6081
+ const opened = "id" in attachment ? ctx.webFiles?.open(attachment.id) : null;
6082
+ if (!opened) {
6083
+ json(res, 409, { error: "An attached file is no longer available", reason: "attachment_gone" });
6084
+ return;
6085
+ }
6086
+ try {
6087
+ if (opened.file.instance !== instance) {
6088
+ json(res, 409, { error: "An attached file is no longer available", reason: "attachment_gone" });
6089
+ return;
6090
+ }
6091
+ totalBytes += opened.file.size;
6092
+ if (opened.file.size > limits.maxFileBytes || totalBytes > limits.maxTotalBytes) {
6093
+ json(res, 409, { error: "The attachments exceed the current file limit", reason: "attachment_gone" });
6094
+ return;
6095
+ }
6096
+ files.push({ kind: opened.file.kind, name: opened.file.name, path: opened.file.realPath });
6097
+ }
6098
+ finally {
6099
+ closeSync(opened.fd);
6100
+ }
6101
+ }
6102
+ if (!stillCurrent()) {
6103
+ json(res, 403, { error: "The session or instance changed" });
6104
+ return;
6105
+ }
6106
+ const { authority } = confirmAfterBody(arrival, webAuthorityOf(req, url, ctx, instance));
6107
+ const nativeRequestId = isNativeExecInstance(ctx.fleetConfig?.instances[instance]) ? randomUUID() : undefined;
6108
+ const nativeJournalIds = nativeRequestId ? new Set((ctx.nativeInstanceRuntime?.().get(instance)?.turns ?? []).map(turn => `native:${turn.id}:user`)) : undefined;
6109
+ const messageId = nativeRequestId ? `native:${nativeRequestId}:user` : newWebMessageId(), claimed = history.beginResend(instance, boot, id, attempt, person.voterKey, messageId, nativeJournalIds);
6110
+ if (claimed.kind === "refused") {
6111
+ json(res, 409, { error: "This delivery changed; refresh and try again" });
6112
+ return;
6113
+ }
6114
+ if (claimed.kind === "already") {
6115
+ json(res, 200, { sent: true, repeated: true, message: claimed.message });
6116
+ return;
6117
+ }
6118
+ update();
6119
+ const delivery = attachmentDelivery(row.text, files);
6120
+ const adapter = ctx.getAdapterForInstance ? ctx.getAdapterForInstance(instance) : ctx.adapter;
6121
+ const payload = { type: "fleet_inbound", content: delivery.text, ...(nativeRequestId ? { requestId: nativeRequestId } : {}), targetSession: instance, meta: {
6122
+ chat_id: ctx.getGroupIdForInstance?.(instance) ?? String(ctx.fleetConfig?.channel?.group_id ?? ""),
6123
+ thread_id: String(ctx.fleetConfig?.instances[instance]?.topic_id ?? ""), message_id: messageId,
6124
+ user: person.name, user_id: person.userId, source: "web", ts: new Date().toISOString(), adapter_id: adapter?.id,
6125
+ ...(guest ? { web_guest: "1" } : {}), ...delivery.meta, ...(quoted ? { reply_to_text: webChatReplyText(quoted) } : {}),
6126
+ } };
6127
+ let handedOff = false;
6128
+ try {
6129
+ const delivered = ctx.deliverHumanToInstance ? await ctx.deliverHumanToInstance(instance, payload, webHumanOrigin(false, authority), row.text, { stillCurrent, ...(native ? { authorityCurrent } : {}) })
6130
+ : await ctx.deliverToInstance(instance, payload, { stillCurrent, ...(native ? { authorityCurrent } : {}) });
6131
+ if (delivered === false)
6132
+ throw new Error("delivery changed");
6133
+ handedOff = true;
6134
+ if (!res.destroyed)
6135
+ json(res, 200, { sent: true, message: row });
6136
+ }
6137
+ catch (error) {
6138
+ if (handedOff)
6139
+ return; // a lost HTTP answer does not make the accepted pane handoff fail
6140
+ history.setDelivery(instance, messageId, "failed");
6141
+ update();
6142
+ ctx.logger.error({ instance, err: error }, "Web resend handoff failed");
6143
+ json(res, 503, { ...webDeliveryFailure(error), message: row });
6144
+ }
6145
+ }
5955
6146
  function handleSendMessage(req, res, ctx) {
5956
6147
  const arrival = webAuthorityOf(req, new URL(req.url ?? "/", "http://localhost"), ctx); // #1939 §3: again after the body
5957
6148
  let body = "";
@@ -6220,7 +6411,7 @@ function handleSendMessage(req, res, ctx) {
6220
6411
  ctx.lastInboundUser.set(instance, person.name);
6221
6412
  ctx.eventLog?.logActivity("message", person.name, (message || `[${files.length} file(s)]`).slice(0, 200), instance);
6222
6413
  // #1920: the account that wrote it (a guest sees its own); channel-visible once its copy was sent (above).
6223
- ctx.emitSseEvent("message", { instance, sender: person.name, role: "user", text: message, ts, attachments: files.map(publicAttachment), messageId, ...(person.bound ? { from: person.voterKey } : {}),
6414
+ ctx.emitSseEvent("message", { instance, sender: person.name, role: "user", retryOwner: person.voterKey, text: message, ts, attachments: files.map(publicAttachment), messageId, ...(person.bound ? { from: person.voterKey } : {}),
6224
6415
  ...(quoted ? { replyTo: webChatReplyRef(quoted) } : {}), ...(clientId ? { clientId } : {}) });
6225
6416
  json(res, 200, { sent: true, messageId });
6226
6417
  }