agent-relay-server 0.73.0 → 0.74.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.
- package/docs/openapi.json +1 -1
- package/package.json +2 -2
- package/public/assets/{MessageBubble-BWdM9UCM.js → MessageBubble-CspI1qqW.js} +2 -2
- package/public/assets/MessageBubble-CspI1qqW.js.map +1 -0
- package/public/assets/{PlanGraphPanel-icESxd82.js → PlanGraphPanel-WjXyWbzZ.js} +2 -2
- package/public/assets/{PlanGraphPanel-icESxd82.js.map → PlanGraphPanel-WjXyWbzZ.js.map} +1 -1
- package/public/assets/{activity-BR9I23hc.js → activity-B9WoIWSe.js} +2 -2
- package/public/assets/{activity-BR9I23hc.js.map → activity-B9WoIWSe.js.map} +1 -1
- package/public/assets/{agent-profiles-BB0V-Tg1.js → agent-profiles-D1X5BBW_.js} +2 -2
- package/public/assets/{agent-profiles-BB0V-Tg1.js.map → agent-profiles-D1X5BBW_.js.map} +1 -1
- package/public/assets/{agents-Clkboz93.js → agents-D7th_n2N.js} +2 -2
- package/public/assets/{agents-Clkboz93.js.map → agents-D7th_n2N.js.map} +1 -1
- package/public/assets/{analytics-DRlHs5ho.js → analytics-e_HOZBPx.js} +2 -2
- package/public/assets/{analytics-DRlHs5ho.js.map → analytics-e_HOZBPx.js.map} +1 -1
- package/public/assets/{automation-DlnH_MPy.js → automation-wOEiCheJ.js} +2 -2
- package/public/assets/{automation-DlnH_MPy.js.map → automation-wOEiCheJ.js.map} +1 -1
- package/public/assets/{branch-state-badge-Dg1qnmF5.js → branch-state-badge-B7T81Oct.js} +2 -2
- package/public/assets/{branch-state-badge-Dg1qnmF5.js.map → branch-state-badge-B7T81Oct.js.map} +1 -1
- package/public/assets/{channels-BVYLrKUL.js → channels-BAD_kIo7.js} +2 -2
- package/public/assets/{channels-BVYLrKUL.js.map → channels-BAD_kIo7.js.map} +1 -1
- package/public/assets/{chat-ml_YzbK4.js → chat-Bj6R0vno.js} +2 -2
- package/public/assets/{chat-ml_YzbK4.js.map → chat-Bj6R0vno.js.map} +1 -1
- package/public/assets/{connectors-BOyk5hC3.js → connectors-Cdjtxly2.js} +2 -2
- package/public/assets/{connectors-BOyk5hC3.js.map → connectors-Cdjtxly2.js.map} +1 -1
- package/public/assets/display-DHgdn4vN.js +3 -0
- package/public/assets/{display-LAWaAboe.js.map → display-DHgdn4vN.js.map} +1 -1
- package/public/assets/{formatted-body-impl-D2F76gPY.js → formatted-body-impl-BXeoUw5r.js} +2 -2
- package/public/assets/{formatted-body-impl-D2F76gPY.js.map → formatted-body-impl-BXeoUw5r.js.map} +1 -1
- package/public/assets/{index-DYmgI4s4.js → index-DNQadbv0.js} +6 -6
- package/public/assets/{index-DYmgI4s4.js.map → index-DNQadbv0.js.map} +1 -1
- package/public/assets/{insights-DylYp2q4.js → insights-n-pd12FP.js} +2 -2
- package/public/assets/{insights-DylYp2q4.js.map → insights-n-pd12FP.js.map} +1 -1
- package/public/assets/{integrations-B9ViWoJy.js → integrations-DzRla8mj.js} +2 -2
- package/public/assets/{integrations-B9ViWoJy.js.map → integrations-DzRla8mj.js.map} +1 -1
- package/public/assets/{maintenance-inyZGLys.js → maintenance-DZI5exUu.js} +2 -2
- package/public/assets/{maintenance-inyZGLys.js.map → maintenance-DZI5exUu.js.map} +1 -1
- package/public/assets/{managed-agents-CEFvMPN-.js → managed-agents-Bh_vowgH.js} +2 -2
- package/public/assets/{managed-agents-CEFvMPN-.js.map → managed-agents-Bh_vowgH.js.map} +1 -1
- package/public/assets/{markdown-preview-impl-CniyG4_g.js → markdown-preview-impl-B-6jdhi0.js} +2 -2
- package/public/assets/{markdown-preview-impl-CniyG4_g.js.map → markdown-preview-impl-B-6jdhi0.js.map} +1 -1
- package/public/assets/{memory-DDYGuRzr.js → memory-B74VVg5K.js} +2 -2
- package/public/assets/{memory-DDYGuRzr.js.map → memory-B74VVg5K.js.map} +1 -1
- package/public/assets/{messages-BMFcsMMa.js → messages-D5n46hEh.js} +2 -2
- package/public/assets/{messages-BMFcsMMa.js.map → messages-D5n46hEh.js.map} +1 -1
- package/public/assets/{orchestrators-D5nL4a52.js → orchestrators-DBryzqq2.js} +2 -2
- package/public/assets/{orchestrators-D5nL4a52.js.map → orchestrators-DBryzqq2.js.map} +1 -1
- package/public/assets/{overview-DywDrPKE.js → overview-0xb4ATEH.js} +2 -2
- package/public/assets/{overview-DywDrPKE.js.map → overview-0xb4ATEH.js.map} +1 -1
- package/public/assets/{pairs-UvIyBk4w.js → pairs-CnKDSHJu.js} +2 -2
- package/public/assets/{pairs-UvIyBk4w.js.map → pairs-CnKDSHJu.js.map} +1 -1
- package/public/assets/{projects-DXBjwPU5.js → projects-DluLrkwe.js} +2 -2
- package/public/assets/{projects-DXBjwPU5.js.map → projects-DluLrkwe.js.map} +1 -1
- package/public/assets/{security-Boe7MEIz.js → security-C2t99jNP.js} +2 -2
- package/public/assets/{security-Boe7MEIz.js.map → security-C2t99jNP.js.map} +1 -1
- package/public/assets/{select-Dh5Q8rJ8.js → select-CCbQiEmS.js} +2 -2
- package/public/assets/{select-Dh5Q8rJ8.js.map → select-CCbQiEmS.js.map} +1 -1
- package/public/assets/{settings-Ch4jMDrE.js → settings-Ucd8p6KS.js} +2 -2
- package/public/assets/{settings-Ch4jMDrE.js.map → settings-Ucd8p6KS.js.map} +1 -1
- package/public/assets/{store-BRvMMH5T.js → store-D1K4_xId.js} +2 -2
- package/public/assets/{store-BRvMMH5T.js.map → store-D1K4_xId.js.map} +1 -1
- package/public/assets/{tasks-DrW8R52c.js → tasks-Bk8clApn.js} +2 -2
- package/public/assets/{tasks-DrW8R52c.js.map → tasks-Bk8clApn.js.map} +1 -1
- package/public/assets/{teams-CJqpAwmO.js → teams-BXkI8tvS.js} +2 -2
- package/public/assets/{teams-CJqpAwmO.js.map → teams-BXkI8tvS.js.map} +1 -1
- package/public/assets/{terminal-viewer-impl-1_7v8GfU.js → terminal-viewer-impl-BL-zWN1C.js} +2 -2
- package/public/assets/{terminal-viewer-impl-1_7v8GfU.js.map → terminal-viewer-impl-BL-zWN1C.js.map} +1 -1
- package/public/assets/{work-queue-BnIi7evb.js → work-queue-DqMKcH5G.js} +2 -2
- package/public/assets/{work-queue-BnIi7evb.js.map → work-queue-DqMKcH5G.js.map} +1 -1
- package/public/assets/{workspaces-u5j6mOlA.js → workspaces-B_nIm6Tw.js} +2 -2
- package/public/assets/{workspaces-u5j6mOlA.js.map → workspaces-B_nIm6Tw.js.map} +1 -1
- package/public/index.html +3 -3
- package/src/context-advisory.ts +2 -2
- package/src/db/continuations.ts +8 -2
- package/src/notification-router.ts +2 -0
- package/src/notification-types.ts +2 -0
- package/src/notify.ts +2 -0
- package/src/self-resume-config.ts +2 -0
- package/src/self-resume.ts +82 -13
- package/src/sse.ts +2 -6
- package/public/assets/MessageBubble-BWdM9UCM.js.map +0 -1
- package/public/assets/display-LAWaAboe.js +0 -3
package/src/self-resume.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { getSelfResumeConfig } from "./config-store";
|
|
|
5
5
|
import {
|
|
6
6
|
archiveContinuationSegment,
|
|
7
7
|
ensureContinuationEnvelope,
|
|
8
|
+
findMessageByIdempotencyKey,
|
|
8
9
|
getAgent,
|
|
9
10
|
getContinuationEnvelope,
|
|
10
11
|
updateContinuationAfterCompact,
|
|
@@ -49,11 +50,14 @@ export function compactAndResume(input: CompactAndResumeInput): CompactAndResume
|
|
|
49
50
|
config,
|
|
50
51
|
now,
|
|
51
52
|
});
|
|
52
|
-
const
|
|
53
|
-
if (
|
|
54
|
-
const command = createCleanStop(agent,
|
|
55
|
-
notifySelfResumeBudgetExhausted(agent, envelope,
|
|
56
|
-
return { ok: false, mode, envelope, command, exhausted: true, reason:
|
|
53
|
+
const budget = selfResumeBudgetStatus(accrueActiveWallClock(envelope, now));
|
|
54
|
+
if (budget.kind === "hard-stop") {
|
|
55
|
+
const command = createCleanStop(agent, budget.reason);
|
|
56
|
+
notifySelfResumeBudgetExhausted(agent, envelope, budget.reason);
|
|
57
|
+
return { ok: false, mode, envelope, command, exhausted: true, reason: budget.reason };
|
|
58
|
+
}
|
|
59
|
+
if (budget.kind === "warning") {
|
|
60
|
+
notifySelfResumeBudgetWarning(agent, envelope, budget.reason);
|
|
57
61
|
}
|
|
58
62
|
|
|
59
63
|
const workingState = input.workingState.trim();
|
|
@@ -156,11 +160,43 @@ function assertResumeSupported(agent: AgentCard, mode: SelfResumeMode): void {
|
|
|
156
160
|
}
|
|
157
161
|
}
|
|
158
162
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
163
|
+
type SelfResumeBudgetStatus =
|
|
164
|
+
| { kind: "within-budget" }
|
|
165
|
+
| { kind: "warning"; reason: string }
|
|
166
|
+
| { kind: "hard-stop"; reason: string };
|
|
167
|
+
|
|
168
|
+
function selfResumeBudgetStatus(envelope: ContinuationEnvelope): SelfResumeBudgetStatus {
|
|
169
|
+
const multiplier = Math.max(1, envelope.budget.hardStopMultiplier || 1);
|
|
170
|
+
if (envelope.generation >= hardLimit(envelope.budget.maxGenerations, multiplier)) return { kind: "hard-stop", reason: "max generations hard stop exhausted" };
|
|
171
|
+
if (activeWallClockMs(envelope) >= hardLimit(envelope.budget.maxWallClockMs, multiplier)) return { kind: "hard-stop", reason: "max active wall clock hard stop exhausted" };
|
|
172
|
+
if (envelope.budget.spent.tokens >= hardLimit(envelope.budget.maxTokens, multiplier)) return { kind: "hard-stop", reason: "max token hard stop exhausted" };
|
|
173
|
+
if (envelope.generation >= envelope.budget.maxGenerations) return { kind: "warning", reason: "max generations exhausted" };
|
|
174
|
+
if (activeWallClockMs(envelope) >= envelope.budget.maxWallClockMs) return { kind: "warning", reason: "max active wall clock exhausted" };
|
|
175
|
+
if (envelope.budget.spent.tokens >= envelope.budget.maxTokens) return { kind: "warning", reason: "max token budget exhausted" };
|
|
176
|
+
return { kind: "within-budget" };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function accrueActiveWallClock(envelope: ContinuationEnvelope, now: number): ContinuationEnvelope {
|
|
180
|
+
const activeDeltaMs = Math.max(0, now - envelope.updatedAt);
|
|
181
|
+
if (activeDeltaMs === 0) return envelope;
|
|
182
|
+
return {
|
|
183
|
+
...envelope,
|
|
184
|
+
budget: {
|
|
185
|
+
...envelope.budget,
|
|
186
|
+
spent: {
|
|
187
|
+
...envelope.budget.spent,
|
|
188
|
+
wallClockMs: Math.max(0, envelope.budget.spent.wallClockMs) + activeDeltaMs,
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function activeWallClockMs(envelope: ContinuationEnvelope): number {
|
|
195
|
+
return Math.max(0, envelope.budget.spent.wallClockMs);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function hardLimit(limit: number, multiplier: number): number {
|
|
199
|
+
return Math.ceil(limit * multiplier);
|
|
164
200
|
}
|
|
165
201
|
|
|
166
202
|
function createNativeCompact(agentId: string, generation: number, continuation: string): Command {
|
|
@@ -214,15 +250,48 @@ function notifySelfResumeBudgetExhausted(agent: AgentCard, envelope: Continuatio
|
|
|
214
250
|
generation: envelope.generation,
|
|
215
251
|
};
|
|
216
252
|
emitRelayEvent({ type: "agent.resume_budget_exhausted", source: "server", subject: agent.id, data: payload });
|
|
217
|
-
|
|
253
|
+
const recipient = agent.spawnedBy ?? "user";
|
|
218
254
|
routeNotification({
|
|
219
255
|
type: "agent.resume_budget_exhausted",
|
|
220
256
|
scope: { agentId: agent.id, parent: agent.spawnedBy },
|
|
221
|
-
recipients: [
|
|
257
|
+
recipients: [recipient],
|
|
222
258
|
message: {
|
|
223
259
|
subject: "Self-resume budget exhausted",
|
|
224
|
-
body:
|
|
260
|
+
body: agent.spawnedBy
|
|
261
|
+
? `Spawned agent \`${agent.id}\` stopped cleanly: ${reason}.`
|
|
262
|
+
: `Agent \`${agent.id}\` stopped cleanly after hitting the self-resume hard backstop: ${reason}.`,
|
|
263
|
+
payload,
|
|
264
|
+
from: agent.id,
|
|
265
|
+
replyExpected: false,
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function notifySelfResumeBudgetWarning(agent: AgentCard, envelope: ContinuationEnvelope, reason: string): void {
|
|
271
|
+
const payload = {
|
|
272
|
+
kind: "agent.resume_budget_warning",
|
|
273
|
+
agentId: agent.id,
|
|
274
|
+
parent: agent.spawnedBy,
|
|
275
|
+
reason,
|
|
276
|
+
generation: envelope.generation,
|
|
277
|
+
hardStopMultiplier: envelope.budget.hardStopMultiplier,
|
|
278
|
+
};
|
|
279
|
+
const idempotencyKey = `self-resume-budget-warning:${agent.id}:${envelope.generation}`;
|
|
280
|
+
if (findMessageByIdempotencyKey(agent.id, idempotencyKey)) return;
|
|
281
|
+
emitRelayEvent({ type: "agent.resume_budget_warning", source: "server", subject: agent.id, data: payload });
|
|
282
|
+
const recipient = agent.spawnedBy ?? "user";
|
|
283
|
+
routeNotification({
|
|
284
|
+
type: "agent.resume_budget_warning",
|
|
285
|
+
scope: { agentId: agent.id, parent: agent.spawnedBy },
|
|
286
|
+
recipients: [recipient],
|
|
287
|
+
message: {
|
|
288
|
+
subject: "Self-resume budget warning",
|
|
289
|
+
body: agent.spawnedBy
|
|
290
|
+
? `Spawned agent \`${agent.id}\` exceeded its self-resume advisory budget (${reason}) and was resumed anyway. Decide whether to continue, adjust budget, or stop and replace it.`
|
|
291
|
+
: `Agent \`${agent.id}\` exceeded its self-resume advisory budget (${reason}) and was resumed anyway. Decide whether to continue, adjust budget, or stop and replace it.`,
|
|
225
292
|
payload,
|
|
293
|
+
idempotencyKey,
|
|
294
|
+
from: agent.id,
|
|
226
295
|
replyExpected: false,
|
|
227
296
|
},
|
|
228
297
|
});
|
package/src/sse.ts
CHANGED
|
@@ -274,14 +274,10 @@ function isInboundChannelMessage(msg: Message): boolean {
|
|
|
274
274
|
return msg.kind === "channel.event" && direction === "inbound" && event?.type === "message.created";
|
|
275
275
|
}
|
|
276
276
|
|
|
277
|
-
function sessionMirrorType(msg: Message): string | undefined {
|
|
278
|
-
const session = isRecord(msg.payload?.session) ? msg.payload.session : undefined;
|
|
279
|
-
return typeof session?.type === "string" ? session.type : undefined;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
277
|
function isBadgeWorthyMessage(msg: Message): boolean {
|
|
283
278
|
if (msg.kind !== "session") return false;
|
|
284
|
-
|
|
279
|
+
const session = isRecord(msg.payload?.session) ? msg.payload.session : undefined;
|
|
280
|
+
return session?.final === true;
|
|
285
281
|
}
|
|
286
282
|
|
|
287
283
|
function notificationForMessage(msg: Message): RelayNotification | undefined {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MessageBubble-BWdM9UCM.js","names":[],"sources":["../../dashboard/src/components/chat/sessionTrace.ts","../../dashboard/src/components/chat/helpers.ts","../../dashboard/src/components/chat/TraceView.tsx","../../dashboard/src/components/chat/hooks/useTtsPlayingKey.ts","../../dashboard/src/components/chat/MessageBubble.tsx"],"sourcesContent":["\nimport { isReactionEventMessage, messageBody, toTimestamp, responseBodyContainsBlock } from '@/lib/display'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\nimport type { ChatHistoryImport, ChatHistoryImportEntry, Message } from '@/types'\n\nexport interface ActivityStep { id: number; kind: 'narration' | 'reasoning' | 'tool'; label?: string; text: string; ts: number; turnId?: string }\nexport type RelayInjectionCategory = 'memory' | 'instructions' | 'tools' | 'comms' | 'knowledge' | 'context'\ninterface RelayInjectionTimelineEvent {\n id: number\n category: RelayInjectionCategory\n summary: string\n detail: Record<string, unknown>\n agentId: string\n timestamp: number\n}\n\nexport type TimelineEntry =\n | { type: 'message'; msg: Message }\n | { type: 'initial-prompt'; msg: Message }\n | { type: 'notice'; msg: Message }\n | { type: 'relay-injection'; event: RelayInjectionTimelineEvent }\n | { type: 'agent-action'; direction: 'spawned-child' | 'spawned-by'; agentId: string; provider?: string; status: 'ready' | 'exited' | 'failed'; reason?: string; timestamp: number }\n | { type: 'activity'; steps: ActivityStep[]; timestamp: number }\n | { type: 'import-boundary'; history: ChatHistoryImport; timestamp: number }\n | { type: 'imported-message'; history: ChatHistoryImport; entry: ChatHistoryImportEntry }\n | { type: 'status'; event: StatusEvent }\n | { type: 'date'; date: string; timestamp: number }\n | { type: 'created'; timestamp: number }\n\nexport const TIMELINE_STATUS_LABELS: Record<string, string> = {\n online: 'came online',\n offline: 'went offline',\n shutdown: 'shut down',\n restarted: 'restarted',\n 'compaction-requested': 'compaction requested',\n compacting: 'compaction started',\n compacted: 'context compacted',\n 'compaction-stalled': 'compaction stalled — may need manual intervention',\n 'clear-requested': 'clear requested',\n 'clearing-context': 'clear started',\n 'context-cleared': 'context cleared',\n 'clear-stalled': 'context clear stalled — may need manual intervention',\n 'shutting-down': 'shutting down',\n}\n\nconst TIMELINE_STATUSES = new Set(Object.keys(TIMELINE_STATUS_LABELS))\nconst STATUS_DEDUPE_WINDOW_MS = 3000\n\n// True event time of a message: occurredAt (set when a Runner backfilled a message it had\n// queued during an outage, #196) falling back to the server receive time. Used for chat\n// timeline ordering + display so a backfilled turn lands where it actually happened in the\n// conversation, not at the bottom. Display-only — DB poll cursors still use created_at.\nfunction messageEventTime(msg: Message): number {\n return new Date(msg.occurredAt ?? msg.createdAt).getTime()\n}\n\n// Narration/reasoning/tool session events are mirrored as `kind:\"session\"` messages\n// but must not become chat bubbles — they render inline in the turn's activity trace.\n// (`narration` = the agent's intermediate spoken text; `reasoning` = its thinking.)\nexport function sessionActivityStep(msg: Message): ActivityStep | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string; turnId?: string } | undefined\n if (!s || (s.type !== 'narration' && s.type !== 'reasoning' && s.type !== 'tool')) return null\n return {\n id: msg.id,\n kind: s.type,\n label: typeof s.label === 'string' ? s.label : undefined,\n text: msg.body,\n ts: messageEventTime(msg),\n turnId: typeof s.turnId === 'string' ? s.turnId : undefined,\n }\n}\n\n// A `notice` session event (e.g. the runner's durable \"context compacted\" marker) renders\n// as a discreet timeline marker, reusing the StatusMarker path. Its `label` carries a\n// timeline-status key (e.g. \"compacted\"); we surface it as a StatusEvent so it dedupes with\n// the ephemeral live timeline-status decoration and survives a reload (the ephemeral one does\n// not). Returns null for non-notice messages or labels we don't render.\nexport function sessionNoticeStatusEvent(msg: Message): StatusEvent | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; label?: string } | undefined\n if (s?.type !== 'notice') return null\n const status = typeof s.label === 'string' && s.label ? s.label : 'compacted'\n return { id: `notice-${msg.id}`, status, timestamp: messageEventTime(msg) }\n}\n\nexport function sessionRelayInjectionEvent(msg: Message): RelayInjectionTimelineEvent | null {\n if (msg.kind !== 'session') return null\n const s = msg.payload?.session as { type?: string; relayInjection?: Record<string, unknown> } | undefined\n if (s?.type !== 'relay-injection') return null\n const raw = s.relayInjection && typeof s.relayInjection === 'object' && !Array.isArray(s.relayInjection) ? s.relayInjection : {}\n const category = typeof raw.category === 'string' && ['memory', 'instructions', 'tools', 'comms', 'knowledge', 'context'].includes(raw.category)\n ? raw.category as RelayInjectionCategory\n : 'context'\n const timestamp = typeof raw.timestamp === 'number' && Number.isFinite(raw.timestamp) ? raw.timestamp : messageEventTime(msg)\n const detail = raw.detail && typeof raw.detail === 'object' && !Array.isArray(raw.detail) ? raw.detail as Record<string, unknown> : {}\n return {\n id: msg.id,\n category,\n summary: typeof raw.summary === 'string' && raw.summary.trim() ? raw.summary : msg.body,\n detail,\n agentId: typeof raw.agentId === 'string' && raw.agentId ? raw.agentId : msg.from,\n timestamp,\n }\n}\n\nfunction stripLeadingResponseBlocks(body: string, blocks: string[]): string {\n let remaining = body.trim()\n for (const raw of blocks) {\n const block = raw.trim()\n if (!block) continue\n if (remaining === block) break\n if (remaining.startsWith(`${block}\\n\\n`)) {\n remaining = remaining.slice(block.length + 2).trimStart()\n }\n }\n return remaining.trim() || body.trim()\n}\n\n// Bus-level system signals (kind:\"system\", from:\"system\") — e.g. branch.landed,\n// agent.context_threshold, workspace.* events. Rendered as notice pills (NoticePill\n// labels/humanizes the kind, #507), NOT chat bubbles or session status markers.\nexport function isBusSignalMessage(msg: Message): boolean {\n return msg.kind === 'system' && msg.from === 'system'\n}\n\n// Spawn lifecycle signals routed to the parent: agent.ready / agent.exited / agent.spawn_failed.\n// These are richer than generic bus signals and get their own agent-action timeline entry.\nconst LIFECYCLE_KINDS = new Set(['agent.ready', 'agent.exited', 'agent.spawn_failed'])\n\nexport function dateKey(ts: number): string {\n const d = new Date(ts)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n}\n\nexport function dedupeStatusEvents(statusEvents: StatusEvent[]): StatusEvent[] {\n const events = statusEvents\n .filter((event) => TIMELINE_STATUSES.has(event.status))\n .slice()\n .sort((a, b) => a.timestamp - b.timestamp)\n const result: StatusEvent[] = []\n for (const event of events) {\n if (result.some((existing) => existing.id === event.id)) continue\n if (result.some((existing) => existing.status === event.status && Math.abs(existing.timestamp - event.timestamp) <= STATUS_DEDUPE_WINDOW_MS)) continue\n result.push(event)\n }\n return result\n}\n\nexport function buildTimeline(\n messages: Message[],\n statusEvents: StatusEvent[],\n createdAt?: string | number | null,\n importedHistory: ChatHistoryImport[] = [],\n options?: { spawnedBy?: { agentId: string; provider?: string } },\n): TimelineEntry[] {\n const raw: Array<{ ts: number; entry: TimelineEntry }> = []\n\n for (const history of importedHistory) {\n const firstImportedAt = history.entries.reduce((min, entry) => Math.min(min, toTimestamp(entry.originalCreatedAt)), Number.POSITIVE_INFINITY)\n const boundaryAt = Number.isFinite(firstImportedAt) ? firstImportedAt - 1 : history.importedAt\n raw.push({ ts: boundaryAt, entry: { type: 'import-boundary', history, timestamp: boundaryAt } })\n for (const entry of history.entries) {\n raw.push({ ts: toTimestamp(entry.originalCreatedAt), entry: { type: 'imported-message', history, entry } })\n }\n }\n\n if (createdAt) {\n const ts = new Date(createdAt as string).getTime()\n if (Number.isFinite(ts)) raw.push({ ts, entry: { type: 'created', timestamp: ts } })\n }\n\n // Synthetic \"spawned by\" lead entry for child agents — derives from the agent's spawnedBy\n // metadata (no inbound system message exists for this direction). Placed at createdAt so it\n // sorts as the first real entry after the created/date markers.\n if (options?.spawnedBy) {\n const ts = createdAt ? new Date(createdAt as string).getTime() : 0\n const spawnedByTs = Number.isFinite(ts) ? ts : 0\n raw.push({ ts: spawnedByTs, entry: { type: 'agent-action', direction: 'spawned-by', agentId: options.spawnedBy.agentId, provider: options.spawnedBy.provider, status: 'ready', timestamp: spawnedByTs } })\n }\n\n // The initial/spawn prompt (#513): the earliest real prompt that kicked off the\n // session — a human prompt, or (for a spawned agent) the first message from the spawn\n // parent. Tagged so it renders with a distinct title instead of as a normal bubble or\n // a folded peer one-liner. Skip session events, bus signals, reactions, and empty bodies.\n const spawnParentId = options?.spawnedBy?.agentId\n let initialPromptId: number | null = null\n let initialPromptTs = Number.POSITIVE_INFINITY\n for (const msg of messages) {\n if (msg.kind === 'session' || isBusSignalMessage(msg) || isReactionEventMessage(msg)) continue\n const fromInitiator = msg.from === HUMAN_AGENT_ID || (spawnParentId !== undefined && msg.from === spawnParentId)\n if (!fromInitiator || !messageBody(msg).trim()) continue\n const ts = messageEventTime(msg)\n if (ts < initialPromptTs) { initialPromptTs = ts; initialPromptId = msg.id }\n }\n\n // A full-capture response stores the turn's narration blocks plus the final\n // answer. Keep the stored message intact, but derive what the response bubble\n // should show: strip leading narration blocks and leave the final visible block.\n // Narration suppression then compares against that visible block only, preserving\n // the live chronological trace after the turn completes.\n const responseBodiesByTurn = new Map<string, string[]>()\n const narrationByTurn = new Map<string, Array<{ id: number; body: string }>>()\n const responseDisplayBodyByMessageId = new Map<number, string>()\n for (const msg of messages) {\n if (msg.kind !== 'session') continue\n const s = msg.payload?.session as { type?: string; turnId?: string } | undefined\n if (s?.type === 'narration' && typeof s.turnId === 'string') {\n const list = narrationByTurn.get(s.turnId) ?? []\n list.push({ id: msg.id, body: msg.body.trim() })\n narrationByTurn.set(s.turnId, list)\n } else if (s?.type === 'response' && typeof s.turnId === 'string') {\n const list = responseBodiesByTurn.get(s.turnId) ?? []\n list.push(msg.body.trim())\n responseBodiesByTurn.set(s.turnId, list)\n }\n }\n const responseDisplayBodiesByTurn = new Map<string, string[]>()\n for (const [turnId, bodies] of responseBodiesByTurn) {\n const narrationBodies = (narrationByTurn.get(turnId) ?? []).map((item) => item.body)\n responseDisplayBodiesByTurn.set(turnId, bodies.map((body) => stripLeadingResponseBlocks(body, narrationBodies)))\n }\n for (const msg of messages) {\n if (msg.kind !== 'session') continue\n const s = msg.payload?.session as { type?: string; turnId?: string } | undefined\n if (s?.type !== 'response' || typeof s.turnId !== 'string') continue\n const displayBody = stripLeadingResponseBlocks(msg.body, (narrationByTurn.get(s.turnId) ?? []).map((item) => item.body))\n if (displayBody && displayBody !== msg.body) responseDisplayBodyByMessageId.set(msg.id, displayBody)\n }\n const suppressedNarrationIds = new Set<number>()\n for (const [turnId, bodies] of responseDisplayBodiesByTurn) {\n const narrations = narrationByTurn.get(turnId) ?? []\n for (const body of bodies) {\n for (let i = narrations.length - 1; i >= 0; i--) {\n const narration = narrations[i]!\n if (suppressedNarrationIds.has(narration.id)) continue\n if (!responseBodyContainsBlock(body, narration.body)) continue\n suppressedNarrationIds.add(narration.id)\n break\n }\n }\n }\n\n // Tracks in-progress agent-action entries by child id so ready→exited coalesces into one entry.\n type RawAgentAction = { ts: number; entry: Extract<TimelineEntry, { type: 'agent-action' }> }\n const agentActionByChild = new Map<string, RawAgentAction>()\n\n const noticeStatusEvents: StatusEvent[] = []\n for (const msg of messages) {\n if (isBusSignalMessage(msg)) {\n const kind = typeof msg.payload?.kind === 'string' ? msg.payload.kind : ''\n if (LIFECYCLE_KINDS.has(kind)) {\n const p = msg.payload as { kind: string; agentId?: string; provider?: string; reason?: string }\n const childId = typeof p.agentId === 'string' ? p.agentId : ''\n const ts = messageEventTime(msg)\n if (!childId) {\n // agent.spawn_failed without a child id (command-level failure): fall through to notice\n raw.push({ ts, entry: { type: 'notice', msg } })\n continue\n }\n const status: 'ready' | 'exited' | 'failed' = kind === 'agent.ready' ? 'ready' : kind === 'agent.exited' ? 'exited' : 'failed'\n const existing = agentActionByChild.get(childId)\n if (existing) {\n // Coalesce: evolve the same entry to the final status in place\n existing.entry.status = status\n if (typeof p.reason === 'string') existing.entry.reason = p.reason\n existing.entry.timestamp = ts\n existing.ts = ts\n } else {\n const item: RawAgentAction = {\n ts,\n entry: {\n type: 'agent-action',\n direction: 'spawned-child',\n agentId: childId,\n provider: typeof p.provider === 'string' ? p.provider : undefined,\n status,\n reason: typeof p.reason === 'string' ? p.reason : undefined,\n timestamp: ts,\n },\n }\n agentActionByChild.set(childId, item)\n raw.push(item)\n }\n continue\n }\n raw.push({ ts: messageEventTime(msg), entry: { type: 'notice', msg } })\n continue\n }\n const notice = sessionNoticeStatusEvent(msg)\n if (notice) {\n noticeStatusEvents.push(notice)\n continue\n }\n const step = sessionActivityStep(msg)\n if (step) {\n if (step.kind === 'narration' && suppressedNarrationIds.has(step.id)) continue\n raw.push({ ts: step.ts, entry: { type: 'activity', steps: [step], timestamp: step.ts } })\n continue\n }\n const relayInjection = sessionRelayInjectionEvent(msg)\n if (relayInjection) {\n raw.push({ ts: relayInjection.timestamp, entry: { type: 'relay-injection', event: relayInjection } })\n continue\n }\n if (msg.kind === 'session') {\n const s = msg.payload?.session as { type?: string; turnId?: string } | undefined\n if (s?.type === 'response' && typeof s.turnId === 'string') {\n const body = responseDisplayBodyByMessageId.get(msg.id)\n if (body && body !== msg.body) {\n raw.push({ ts: messageEventTime(msg), entry: { type: 'message', msg: { ...msg, body } } })\n continue\n }\n }\n }\n const entryType = msg.id === initialPromptId ? 'initial-prompt' : 'message'\n raw.push({ ts: messageEventTime(msg), entry: { type: entryType, msg } })\n }\n for (const event of dedupeStatusEvents([...statusEvents, ...noticeStatusEvents])) {\n raw.push({ ts: event.timestamp, entry: { type: 'status', event } })\n }\n\n const typeOrder = { created: 0, date: 1, 'import-boundary': 2, 'imported-message': 3, 'initial-prompt': 4, message: 4, activity: 4, notice: 4, 'agent-action': 4, 'relay-injection': 4, status: 5 } as const\n raw.sort((a, b) => {\n const dt = a.ts - b.ts\n if (Math.abs(dt) < 3000) return typeOrder[a.entry.type] - typeOrder[b.entry.type] || dt\n return dt\n })\n\n const entries: TimelineEntry[] = []\n let lastDate = ''\n for (const { ts, entry } of raw) {\n if (entry.type === 'created') {\n entries.push(entry)\n continue\n }\n const dk = dateKey(ts)\n if (dk !== lastDate) {\n entries.push({ type: 'date', date: dk, timestamp: ts })\n lastDate = dk\n }\n // Coalesce consecutive activity steps from the same turn into one trace.\n if (entry.type === 'activity') {\n const prev = entries[entries.length - 1]\n if (prev && prev.type === 'activity' && sameActivityTurn(prev, entry)) {\n prev.steps.push(...entry.steps)\n continue\n }\n }\n entries.push(entry)\n }\n\n return entries\n}\n\n// Stable per-entry key — used by Virtuoso for reconciliation AND by chat search to\n// address a match back to its timeline row. Lives here (pure logic) rather than in\n// VirtualTimeline so the search layer can reuse it without pulling in react-virtuoso.\nexport function timelineEntryKey(entry: TimelineEntry): string {\n if (entry.type === 'message') return `msg-${entry.msg.id}`\n if (entry.type === 'initial-prompt') return `initprompt-${entry.msg.id}`\n if (entry.type === 'notice') return `notice-${entry.msg.id}`\n if (entry.type === 'relay-injection') return `relay-injection-${entry.event.id}`\n if (entry.type === 'agent-action') return `agent-action-${entry.direction}-${entry.agentId}`\n // Key by the FIRST step only — stable as the turn streams. Including the last\n // step's id rekeyed the entry on every appended step, so virtuoso treated the\n // in-place-growing turn as a replaced item and lost its resize anchoring: the\n // viewport jumped down by the added height while scrolled up reading history.\n if (entry.type === 'activity') return `act-${entry.steps[0]?.id ?? entry.timestamp}`\n if (entry.type === 'import-boundary') return `import-${entry.history.id}`\n if (entry.type === 'imported-message') return `import-msg-${entry.history.id}-${entry.entry.originalMessageId}-${entry.entry.position}`\n if (entry.type === 'status') return `status-${entry.event.id}`\n if (entry.type === 'date') return `date-${entry.date}`\n return `created-${entry.timestamp}`\n}\n\n// Searchable plain text for an entry — what chat search matches against. Only entries\n// that carry human-readable content contribute; structural rows (date/status/created/\n// agent-action/import-boundary) return '' so they're never search targets.\nexport function timelineEntryText(entry: TimelineEntry): string {\n if (entry.type === 'message' || entry.type === 'initial-prompt' || entry.type === 'notice') {\n const subject = entry.msg.subject ? `${entry.msg.subject} ` : ''\n return subject + messageBody(entry.msg)\n }\n if (entry.type === 'imported-message') return messageBody(entry.entry.message)\n if (entry.type === 'activity') {\n return entry.steps.map((step) => [step.label, step.text].filter(Boolean).join(' ')).join('\\n')\n }\n if (entry.type === 'relay-injection') return `${entry.event.category} ${entry.event.summary}\\n${JSON.stringify(entry.event.detail)}`\n return ''\n}\n\nexport function sameActivityTurn(a: Extract<TimelineEntry, { type: 'activity' }>, b: Extract<TimelineEntry, { type: 'activity' }>): boolean {\n const at = a.steps[a.steps.length - 1]?.turnId\n const bt = b.steps[0]?.turnId\n if (at && bt) return at === bt\n // No turn id on either side: group adjacent steps regardless.\n return !at && !bt\n}\n","\nimport { AlertCircle, Check, CheckCheck, Clock } from 'lucide-react'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport {\n isBadgeWorthy,\n isReactionEventMessage,\n normalizePathForCompare,\n normalizeReactionEmoji,\n pathWithinBase,\n toTimestamp,\n} from '@/lib/display'\nimport { planLookupKey } from '@/store/slices/plans'\nimport type { Agent, AttachmentRef, InboxThread, Message, Orchestrator, Plan } from '@/types'\nimport type { PendingAttachment } from './types'\n\nexport function formatBytes(size: number): string {\n if (size < 1024) return `${size} B`\n if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`\n return `${(size / 1024 / 1024).toFixed(1)} MB`\n}\n\nexport function resolveRelativePath(cwd: string, path: string): string {\n if (path.startsWith('/')) return path\n const parts = `${cwd.replace(/\\/+$/, '')}/${path}`.split('/')\n const stack: string[] = []\n for (const part of parts) {\n if (!part || part === '.') continue\n if (part === '..') stack.pop()\n else stack.push(part)\n }\n return '/' + stack.join('/')\n}\n\nexport function parentPath(path: string): string {\n const trimmed = path.replace(/\\/+$/, '')\n const index = trimmed.lastIndexOf('/')\n return index > 0 ? trimmed.slice(0, index) : '/'\n}\n\nexport function orchestratorForFilePreview(orchestrators: Orchestrator[], path: string): Orchestrator | undefined {\n return orchestrators\n .filter((orch) => orch.status === 'online' && pathWithinBase(path, orch.baseDir))\n .sort((a, b) => normalizePathForCompare(b.baseDir).length - normalizePathForCompare(a.baseDir).length)[0] ||\n orchestrators.find((orch) => orch.status === 'online')\n}\n\nexport function supportsSideFilePreview(): boolean {\n return typeof window !== 'undefined' && window.matchMedia('(min-width: 1280px)').matches\n}\n\nexport function hasActiveTextSelection(): boolean {\n return typeof window !== 'undefined' && Boolean(window.getSelection()?.toString())\n}\n\nexport function messageAttachments(msg: Message): AttachmentRef[] {\n const attachments = msg.payload?.attachments\n if (!Array.isArray(attachments)) return []\n return attachments.filter((item): item is AttachmentRef => Boolean(item && typeof item === 'object' && typeof (item as AttachmentRef).artifactId === 'string'))\n}\n\nexport const QUICK_REACTIONS = ['👍', '❤️', '✅', '👀'] as const\n\nexport function groupedReactions(msg: Message): Array<{ emoji: string; count: number; mine: boolean; actors: string[] }> {\n const groups = new Map<string, { emoji: string; count: number; mine: boolean; actors: string[] }>()\n for (const reaction of msg.reactions || []) {\n const emoji = normalizeReactionEmoji(reaction.emoji)\n const current = groups.get(emoji) ?? { emoji, count: 0, mine: false, actors: [] }\n current.count += 1\n current.mine = current.mine || reaction.actorId === HUMAN_AGENT_ID\n current.actors.push(reaction.actorId)\n groups.set(emoji, current)\n }\n return [...groups.values()].sort((a, b) => b.count - a.count || a.emoji.localeCompare(b.emoji))\n}\n\nexport function isReactionEvent(msg: Message): boolean {\n return isReactionEventMessage(msg)\n}\n\nexport function outboundReceipt(msg: Message, peer: string): { label: string; title: string; tone: 'muted' | 'ok' | 'warn' | 'danger'; icon: typeof Check } {\n const readBy = msg.readBy || []\n const expectedReader = msg.resolvedToAgent || peer || msg.to\n const readByExpected = expectedReader ? readBy.includes(expectedReader) : false\n const readBySomeone = readBy.some((id) => id !== HUMAN_AGENT_ID)\n if (readByExpected || readBySomeone) {\n const reader = readByExpected ? expectedReader : readBy.find((id) => id !== HUMAN_AGENT_ID)\n return { label: 'read', title: reader ? `Read by ${reader}` : 'Read by agent', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'delivered') {\n return { label: 'delivered', title: 'Delivered to agent inbox', tone: 'ok', icon: CheckCheck }\n }\n if (msg.deliveryStatus === 'queued') {\n return { label: 'queued', title: 'Queued until the target agent is available', tone: 'warn', icon: Clock }\n }\n if (msg.deliveryStatus === 'failed' || msg.deliveryStatus === 'dead') {\n const detail = msg.deliveryPoisonReason || msg.deliveryLastError || msg.deliveryStatus\n return { label: msg.deliveryStatus, title: detail, tone: 'danger', icon: AlertCircle }\n }\n return { label: 'sent', title: 'Accepted by Relay', tone: 'muted', icon: Check }\n}\n\nfunction messageActivityTimestamp(msg: Message): number {\n const messageAt = toTimestamp(msg.createdAt)\n return (msg.reactions || []).reduce((latest, reaction) => {\n return Math.max(latest, toTimestamp(reaction.updatedAt || reaction.createdAt))\n }, messageAt)\n}\n\nexport function threadActivityTimestamp(thread: InboxThread | undefined): number {\n if (!thread) return 0\n return thread.messages.reduce((latest, msg) => Math.max(latest, messageActivityTimestamp(msg)), 0)\n}\n\n// Ascending-by-time comparator for the conversations-list sorts (last activity, last seen).\n// Older timestamp sorts first, so 'asc' (the default, SortAsc icon) reads oldest→newest and a\n// conversation whose agent just finished a turn appends at the bottom instead of being yanked\n// to the top on every turn-completion (#541). dir=-1 ('desc') flips it to newest-first.\nexport function compareConversationActivity(ta: number, tb: number, dir: number): number {\n return (ta - tb) * dir\n}\n\n// Time of the agent's last *final response* (`kind:\"session\"`, `type:\"response\"`) — what\n// the conversations list shows instead of a heartbeat/last-seen or any-message activity.\n// 0 when the agent hasn't produced a response yet (caller falls back to thread activity).\nexport function lastFinalResponseTimestamp(thread: InboxThread | undefined): number {\n if (!thread) return 0\n let latest = 0\n for (const msg of thread.messages) {\n if (isBadgeWorthy(msg)) latest = Math.max(latest, toTimestamp(msg.createdAt))\n }\n return latest\n}\n\nexport function chatTimestamp(iso: string | number): string {\n const d = new Date(iso as string)\n return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\nexport function revokePendingAttachmentUrls(items: PendingAttachment[]): void {\n for (const item of items) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)\n}\n\ntype ChatPlanContext = { threadId: string | number; channel?: string } | { teamId: string; channel?: string }\n\nexport function resolveChatPlanContext(\n agent: Agent | null,\n messages: Message[],\n lastMessage: Message | null | undefined,\n plansByThread: Record<string, Plan | null>,\n): ChatPlanContext | null {\n if (agent?.teamId) return { teamId: agent.teamId }\n const ordered = [...messages]\n if (lastMessage && !ordered.some((message) => message.id === lastMessage.id)) ordered.push(lastMessage)\n const threaded = ordered.filter((message) => message.threadId).reverse()\n const knownPlanMessage = threaded.find((message) => Boolean(plansByThread[planLookupKey(message.threadId!, message.channel)]))\n const selected = knownPlanMessage ?? threaded[0]\n if (!selected?.threadId) return null\n return {\n threadId: selected.threadId,\n ...(selected.channel ? { channel: selected.channel } : {}),\n }\n}\n","\nimport { useEffect, useMemo, useState, useSyncExternalStore } from 'react'\nimport type React from 'react'\nimport { AlertCircle, AlertTriangle, ArrowLeft, BookOpen, Brain, ChevronDown, ChevronRight, ChevronUp, Circle, CircleStop, Database, FileText, GitFork, GitMerge, LogOut, PlugZap, Plus, Radio, Sparkles, Terminal, Wrench } from 'lucide-react'\nimport type { LucideIcon } from 'lucide-react'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { displayName, messageBody } from '@/lib/display'\nimport type { ChatHistoryImport, ChatHistoryImportEntry } from '@/types'\nimport { cn } from '@/lib/utils'\nimport { chatTimestamp } from './helpers'\nimport { dateKey, TIMELINE_STATUS_LABELS, type ActivityStep, type RelayInjectionCategory, type TimelineEntry } from './sessionTrace'\nimport type { Message } from '@/types'\nimport type { ChatStatusEvent as StatusEvent } from '@/store'\nimport { useRelayStore } from '@/store'\nimport { AgentTypeIcon } from '@/components/shared/agent-type-icon'\n\nconst TIMELINE_STATUS_COLORS: Record<string, string> = {\n online: 'text-emerald-400',\n offline: 'text-zinc-400',\n shutdown: 'text-zinc-400',\n restarted: 'text-blue-400',\n 'compaction-requested': 'text-zinc-400',\n compacting: 'text-amber-400',\n compacted: 'text-amber-400',\n 'compaction-stalled': 'text-red-400',\n 'clear-requested': 'text-zinc-400',\n 'clearing-context': 'text-amber-400',\n 'context-cleared': 'text-amber-400',\n 'clear-stalled': 'text-red-400',\n 'shutting-down': 'text-zinc-400',\n}\n\nfunction dateSeparatorLabel(dateStr: string): string {\n const today = new Date()\n const [y, m, d] = dateStr.split('-').map(Number)\n const target = new Date(y!, m! - 1, d)\n const todayKey = dateKey(today.getTime())\n if (dateStr === todayKey) return 'Today'\n const yesterday = new Date(today)\n yesterday.setDate(yesterday.getDate() - 1)\n if (dateStr === dateKey(yesterday.getTime())) return 'Yesterday'\n return target.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: target.getFullYear() !== today.getFullYear() ? 'numeric' : undefined })\n}\n\nexport function StatusMarker({ event }: { event: StatusEvent }) {\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n <Circle className={cn('w-2 h-2 fill-current', TIMELINE_STATUS_COLORS[event.status] || 'text-zinc-400')} />\n <span>{TIMELINE_STATUS_LABELS[event.status] || event.status}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(event.timestamp)}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nconst BUS_SIGNAL_ICON: Record<string, LucideIcon> = {\n 'branch.landed': GitMerge,\n 'context.warning': AlertTriangle,\n 'agent.context_threshold': AlertTriangle,\n 'agent.resume_budget_exhausted': AlertTriangle,\n 'agent.rate_limit_resume': PlugZap,\n}\n\n// Explicit overrides for kinds that read better with custom wording; every other bus\n// signal is humanized from its kind (see humanizeSignalKind) so no event renders as a\n// raw dotted identifier and nothing is silently dropped (#507).\nconst BUS_SIGNAL_LABEL: Record<string, string> = {\n 'branch.landed': 'branch landed',\n 'context.warning': 'context warning',\n 'agent.context_threshold': 'context threshold reached',\n}\n\n// Turn an unmapped bus-signal kind into a readable label: drop the leading namespace\n// segment and normalize separators. e.g. `agent.rate_limit_resume` → \"rate limit resume\",\n// `workspace.review-request` → \"review request\". Falls back to \"system signal\" if empty.\nfunction humanizeSignalKind(kind: string): string {\n if (!kind) return 'system signal'\n const withoutNamespace = kind.includes('.') ? kind.slice(kind.indexOf('.') + 1) : kind\n const words = withoutNamespace.replace(/[._-]+/g, ' ').trim()\n return words || 'system signal'\n}\n\n// Inline, clickable agent reference — the ONE place chat resolves an agent id to a\n// label (#522: prefer label everywhere) and links it to that agent's chat (#522: every\n// reference links). Falls back to the raw id only when the agent is unknown and no\n// fallback label was supplied. Reused by NoticePill, AgentActionEntry, and MessageBubble.\nexport function AgentLink({ agentId, fallbackLabel, className }: { agentId: string; fallbackLabel?: string; className?: string }) {\n const agent = useRelayStore((s) => s.agentsById[agentId]) || null\n const openInboxThread = useRelayStore((s) => s.openInboxThread)\n const switchView = useRelayStore((s) => s.switchView)\n const label = agent ? displayName(agent) : (fallbackLabel || agentId)\n return (\n <button\n type=\"button\"\n className={cn('inline-flex max-w-full items-center gap-1 rounded px-1 text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground', className)}\n onClick={(e) => { e.stopPropagation(); openInboxThread(agentId); void switchView('chat') }}\n title={`Open chat for ${label}`}\n >\n <AgentTypeIcon agent={agent} className=\"w-4 h-4 text-[10px]\" />\n <span className=\"max-w-[160px] truncate\">{label}</span>\n </button>\n )\n}\n\n// Branch-landed gets a richer pill than the generic notice: the short merge SHA plus a\n// linked \"by {agent}\" attribution (#509). The payload (src/branch-landed.ts) carries\n// sha (mergedSha), author (ownerAgentId), branch, base — all previously dropped.\nfunction BranchLandedPill({ msg }: { msg: Message }) {\n const payload = (msg.payload ?? {}) as Record<string, unknown>\n const sha = typeof payload.sha === 'string' ? payload.sha : ''\n const shortSha = sha ? sha.slice(0, 7) : ''\n const author = typeof payload.author === 'string' ? payload.author : ''\n const branch = typeof payload.branch === 'string' ? payload.branch : ''\n const base = typeof payload.base === 'string' ? payload.base : ''\n const pushed = payload.pushed\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex max-w-full flex-wrap items-center justify-center gap-x-1.5 gap-y-0.5 rounded-full border border-emerald-500/25 bg-emerald-500/10 px-2.5 py-1 text-xs text-emerald-300/90\">\n <GitMerge className=\"h-3 w-3 shrink-0 text-emerald-400\" />\n <span className=\"text-emerald-300\">branch landed</span>\n {branch && base && (\n <span className=\"font-mono text-emerald-200/70\" title={`${branch} → ${base}`}>\n {branch}<span className=\"opacity-50\"> → </span>{base}\n </span>\n )}\n {shortSha && (\n <span className=\"rounded bg-emerald-500/15 px-1 font-mono text-emerald-200\" title={sha}>{shortSha}</span>\n )}\n {author && (\n <span className=\"inline-flex items-center gap-1 text-emerald-300/80\">\n <span className=\"opacity-70\">by</span>\n <AgentLink agentId={author} className=\"text-emerald-300/90 hover:text-emerald-100\" />\n </span>\n )}\n {pushed === false && <span className=\"text-amber-300/80\" title=\"Local-only land — not pushed to origin\">· local only</span>}\n <span className=\"text-emerald-300/50\">{chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function NoticePill({ msg }: { msg: Message }) {\n const signalKind = typeof msg.payload?.kind === 'string' ? msg.payload.kind : ''\n if (signalKind === 'branch.landed') return <BranchLandedPill msg={msg} />\n const Icon: LucideIcon = BUS_SIGNAL_ICON[signalKind] ?? Radio\n const label = BUS_SIGNAL_LABEL[signalKind] ?? humanizeSignalKind(signalKind)\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground\">\n <Icon className=\"h-3 w-3\" />\n <span>{label}</span>\n <span className=\"text-muted-foreground/60\">{chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nconst AGENT_ACTION_VERB: Record<string, Record<string, string>> = {\n 'spawned-child': { ready: 'spawned', exited: 'spawned · exited', failed: 'spawn failed' },\n 'spawned-by': { ready: 'spawned by', exited: 'spawned by', failed: 'spawned by' },\n}\n\nconst AGENT_ACTION_ICON: Record<string, LucideIcon> = {\n 'spawned-child-ready': Plus,\n 'spawned-child-exited': LogOut,\n 'spawned-child-failed': AlertCircle,\n 'spawned-by-ready': ArrowLeft,\n 'spawned-by-exited': ArrowLeft,\n 'spawned-by-failed': ArrowLeft,\n}\n\nconst AGENT_ACTION_COLOR: Record<string, string> = {\n 'spawned-child-ready': 'text-emerald-400',\n 'spawned-child-exited': 'text-zinc-400',\n 'spawned-child-failed': 'text-red-400',\n 'spawned-by-ready': 'text-blue-400',\n 'spawned-by-exited': 'text-blue-400',\n 'spawned-by-failed': 'text-blue-400',\n}\n\nexport function AgentActionEntry({ entry }: { entry: Extract<TimelineEntry, { type: 'agent-action' }> }) {\n const key = `${entry.direction}-${entry.status}`\n const verb = AGENT_ACTION_VERB[entry.direction]?.[entry.status] ?? entry.direction\n const Icon: LucideIcon = AGENT_ACTION_ICON[key] ?? Radio\n const color = AGENT_ACTION_COLOR[key] ?? 'text-muted-foreground'\n const isError = entry.status === 'failed'\n\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className={cn('flex items-center gap-1.5 rounded-full border bg-muted/30 px-2.5 py-1 text-xs', isError ? 'border-red-500/30' : 'border-border')}>\n <Icon className={cn('h-3 w-3 shrink-0', color)} />\n <span className=\"text-muted-foreground\">{verb}</span>\n <AgentLink agentId={entry.agentId} />\n {entry.reason && isError && (\n <span className=\"text-red-400/80 max-w-[120px] truncate\" title={entry.reason}>— {entry.reason}</span>\n )}\n <span className=\"text-muted-foreground/60 shrink-0\">{chatTimestamp(entry.timestamp)}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nconst RELAY_INJECTION_ICON: Record<RelayInjectionCategory, LucideIcon> = {\n memory: Brain,\n instructions: FileText,\n tools: Wrench,\n comms: Radio,\n knowledge: BookOpen,\n context: Database,\n}\n\nconst RELAY_INJECTION_TONE: Record<RelayInjectionCategory, string> = {\n memory: 'border-emerald-500/25 bg-emerald-500/10 text-emerald-300',\n instructions: 'border-sky-500/25 bg-sky-500/10 text-sky-300',\n tools: 'border-amber-500/25 bg-amber-500/10 text-amber-300',\n comms: 'border-violet-500/25 bg-violet-500/10 text-violet-300',\n knowledge: 'border-cyan-500/25 bg-cyan-500/10 text-cyan-300',\n context: 'border-zinc-500/25 bg-zinc-500/10 text-zinc-300',\n}\n\nfunction detailJson(detail: Record<string, unknown>): string {\n try {\n return JSON.stringify(detail, null, 2)\n } catch {\n return String(detail)\n }\n}\n\nexport function RelayInjectionRow({ entry }: { entry: Extract<TimelineEntry, { type: 'relay-injection' }> }) {\n const [expanded, setExpanded] = useState(false)\n const event = entry.event\n const Icon = RELAY_INJECTION_ICON[event.category] ?? Sparkles\n const tone = RELAY_INJECTION_TONE[event.category] ?? RELAY_INJECTION_TONE.context\n return (\n <div className=\"flex justify-center py-2 my-1\">\n <div className={cn('w-full max-w-[85%] md:max-w-[75%] rounded-lg border px-2.5 py-1.5 text-xs shadow-sm', tone)}>\n <button\n type=\"button\"\n className=\"flex w-full min-w-0 items-center gap-1.5 text-left\"\n onClick={() => setExpanded((value) => !value)}\n >\n <Icon className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"shrink-0 font-medium\">{event.category}</span>\n <span className=\"min-w-0 flex-1 truncate text-foreground/80\">{event.summary}</span>\n <span className=\"shrink-0 text-muted-foreground/60\">{chatTimestamp(event.timestamp)}</span>\n <ChevronRight className={cn('h-3.5 w-3.5 shrink-0 transition-transform', expanded && 'rotate-90')} />\n </button>\n {expanded && (\n <pre className=\"mt-2 max-h-72 overflow-auto rounded-md border border-border/60 bg-background/75 p-2 font-mono text-[11px] leading-relaxed text-muted-foreground whitespace-pre-wrap break-words\">\n {detailJson(event.detail)}\n </pre>\n )}\n </div>\n </div>\n )\n}\n\nexport function BusyIndicator({ blockedLabel, onInterrupt }: { blockedLabel?: string; onInterrupt?: () => void }) {\n if (blockedLabel) {\n return (\n <div className=\"flex justify-start mb-3 animate-in fade-in slide-in-from-bottom-1 duration-150\">\n <div className=\"flex h-9 items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-red-500/30 px-4\">\n <AlertCircle className=\"w-3.5 h-3.5 text-red-400\" />\n <span className=\"text-xs text-red-300\">blocked: {blockedLabel}</span>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"flex justify-start mb-3 animate-in fade-in slide-in-from-bottom-1 duration-150\">\n <div className=\"flex h-9 items-center gap-2 rounded-2xl rounded-bl-sm bg-card ring-1 ring-foreground/10 px-4\">\n <div className=\"flex items-center gap-1\">\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-yellow-400 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]\" />\n </div>\n <span className=\"text-xs text-muted-foreground\">working</span>\n {onInterrupt && (\n <button\n onClick={onInterrupt}\n title=\"Interrupt\"\n className=\"ml-1 flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs text-muted-foreground hover:text-red-300 hover:bg-red-500/10 transition-colors\"\n >\n <CircleStop className=\"w-3.5 h-3.5\" />\n Stop\n </button>\n )}\n </div>\n </div>\n )\n}\n\nconst HIDE_TOOLS_KEY = 'agent-relay:chat-hide-tools'\nconst hideToolsStore = (() => {\n const listeners = new Set<() => void>()\n let value = (() => {\n try {\n return window.localStorage.getItem(HIDE_TOOLS_KEY) === 'on'\n } catch {\n return false\n }\n })()\n const emit = () => listeners.forEach((l) => l())\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n if (e.key !== HIDE_TOOLS_KEY) return\n value = e.newValue === 'on'\n emit()\n })\n }\n return {\n subscribe(cb: () => void) {\n listeners.add(cb)\n return () => listeners.delete(cb)\n },\n get: () => value,\n toggle() {\n value = !value\n try {\n window.localStorage.setItem(HIDE_TOOLS_KEY, value ? 'on' : 'off')\n } catch {}\n emit()\n },\n }\n})()\n\nfunction useHideTools(): [boolean, () => void] {\n const hideTools = useSyncExternalStore(hideToolsStore.subscribe, hideToolsStore.get, () => false)\n return [hideTools, hideToolsStore.toggle]\n}\n\nexport function ActivityTrace({ steps, showReasoning, issueRepo }: { steps: ActivityStep[]; showReasoning: boolean; issueRepo?: string }) {\n const [hideTools, toggleHideTools] = useHideTools()\n const visible = showReasoning ? steps : steps.filter((s) => s.kind !== 'reasoning')\n if (!visible.length) return null\n const toolCount = visible.filter((s) => s.kind === 'tool').length\n return (\n <div className=\"flex justify-start mb-2\">\n <div className=\"max-w-[85%] md:max-w-[75%] min-w-0 space-y-1.5\">\n {visible.map((step) => {\n if (step.kind === 'narration') {\n return (\n <FormattedBody\n key={step.id}\n text={step.text}\n issueRepo={issueRepo}\n className=\"text-sm leading-relaxed break-words text-foreground/90 min-w-0\"\n />\n )\n }\n if (step.kind === 'reasoning') {\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground/80\">\n <Brain className=\"w-3.5 h-3.5 mt-0.5 shrink-0 opacity-70\" />\n <FormattedBody text={step.text} issueRepo={issueRepo} className=\"italic break-words min-w-0\" />\n </div>\n )\n }\n if (hideTools) return null\n return (\n <div key={step.id} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground\">\n <Terminal className=\"w-3 h-3 mt-0.5 shrink-0 opacity-70\" />\n <span className=\"min-w-0 break-words\">\n <span className=\"font-medium\">{step.label || 'tool'}</span>\n {step.text && step.text.trim() && step.text.trim() !== (step.label ?? '').trim() ? <span className=\"opacity-70\"> — {step.text}</span> : null}\n </span>\n </div>\n )\n })}\n {toolCount > 0 && (\n <button\n onClick={toggleHideTools}\n className=\"flex items-center gap-1 text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors text-left\"\n >\n <ChevronRight className={cn('w-3 h-3 shrink-0 transition-transform', !hideTools && 'rotate-90')} />\n <span>{hideTools ? `show ${toolCount} tool step${toolCount === 1 ? '' : 's'}` : 'hide tool steps'}</span>\n </button>\n )}\n </div>\n </div>\n )\n}\n\nexport function DateSeparator({ date }: { date: string }) {\n return (\n <div className=\"flex items-center justify-center gap-3 py-3 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs font-medium text-muted-foreground\">{dateSeparatorLabel(date)}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function CreatedMarker({ timestamp }: { timestamp: number }) {\n const d = new Date(timestamp)\n const label = d.toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' })\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <span className=\"text-xs text-muted-foreground/60\">created {label}</span>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedHistoryMarker({ history }: { history: ChatHistoryImport }) {\n const source = history.sourceAgentLabel || history.sourcePeerId\n const count = history.entries.length\n return (\n <div className=\"flex items-center justify-center gap-2 py-2 my-1\">\n <div className=\"h-px flex-1 bg-border\" />\n <div className=\"flex items-center gap-1.5 rounded-full border border-dashed border-border bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground\">\n <GitFork className=\"h-3 w-3\" />\n <span>forked history from {source}</span>\n <span className=\"text-muted-foreground/60\">{count} {count === 1 ? 'entry' : 'entries'}</span>\n </div>\n <div className=\"h-px flex-1 bg-border\" />\n </div>\n )\n}\n\nexport function ImportedMessageBubble({ entry, sourceLabel, issueRepo }: { entry: ChatHistoryImportEntry; sourceLabel?: string; issueRepo?: string }) {\n const msg = entry.message\n const body = messageBody(msg)\n const isOriginalHuman = entry.originalFrom === HUMAN_AGENT_ID\n return (\n <div className={cn('flex mb-3 opacity-80', isOriginalHuman ? 'justify-end' : 'justify-start')}>\n <div className=\"max-w-[85%] md:max-w-[75%]\">\n <div\n className={cn(\n 'rounded-2xl border border-dashed px-3.5 py-2 text-sm select-text',\n isOriginalHuman\n ? 'border-primary/25 bg-primary/10 text-foreground rounded-br-sm'\n : 'border-border bg-card/70 rounded-bl-sm'\n )}\n >\n <div className={cn('mb-1 text-[10px] uppercase tracking-normal', isOriginalHuman ? 'text-primary/70' : 'text-muted-foreground')}>\n forked history · {isOriginalHuman ? 'you' : (sourceLabel || entry.originalFrom)}\n </div>\n <FormattedBody text={body} rawBody={msg.body} issueRepo={issueRepo} className=\"leading-relaxed\" />\n <p className={cn('mt-1 flex items-center justify-end gap-1.5 text-xs', isOriginalHuman ? 'text-primary/60' : 'text-muted-foreground')}>\n <span className=\"opacity-40\">#{entry.originalMessageId}</span>\n <span>{chatTimestamp(entry.originalCreatedAt)}</span>\n </p>\n </div>\n </div>\n </div>\n )\n}\n\n// The initial/spawn prompt (#513) — the message that kicked off the session — gets a\n// distinct titled panel instead of a plain user bubble, so it reads as the brief at the\n// top of the conversation. data-msg-id is preserved for the scroll/measurement logic.\nexport function InitialPromptBubble({ msg, issueRepo }: { msg: Message; issueRepo?: string }) {\n const body = messageBody(msg)\n const time = chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))\n return (\n <div data-msg-id={msg.id} className=\"mb-3\">\n <div className=\"rounded-xl border border-primary/30 bg-primary/[0.06] px-3.5 py-2.5 shadow-sm\">\n <div className=\"mb-1.5 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-primary/80\">\n <Sparkles className=\"h-3.5 w-3.5\" />\n <span>Initial prompt</span>\n <span className=\"ml-auto text-[10px] font-normal normal-case text-muted-foreground/60\">{time}</span>\n </div>\n <FormattedBody text={body} rawBody={msg.body} issueRepo={issueRepo} className=\"text-sm leading-relaxed text-foreground\" />\n </div>\n </div>\n )\n}\n\n// Pinned \"Last prompt\" reminder. Rendered as a shrink-0 flex sibling ABOVE the timeline in\n// ChatPanel — the SAME mechanism as the chat search bar (ChatSearchBar) — so it stays put\n// above the conversation instead of scrolling away (#545). It previously lived inside the\n// scroll container as a position:sticky child, which broke when the timeline was virtualized\n// (b0ef5c5): a Virtuoso Header item scrolls/unmounts, so sticky no longer pinned it and it was\n// only glimpsed at the very top. `scrollEl` is the Virtuoso scroller (lifted up from\n// VirtualTimeline), used to observe whether the original prompt is on-screen and to scroll to it.\nexport function StickyPromptBanner({ scrollEl, timeline }: { scrollEl: HTMLElement | null; timeline: TimelineEntry[] }) {\n const [hidden, setHidden] = useState(true)\n const [expandedByPrompt, setExpandedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [collapsedByPrompt, setCollapsedByPrompt] = useState<{ id: number; value: boolean } | null>(null)\n const [promptAbove, setPromptAbove] = useState(false)\n\n const lastOutbound = useMemo(() => {\n for (let i = timeline.length - 1; i >= 0; i--) {\n const entry = timeline[i]\n if (!entry || (entry.type !== 'message' && entry.type !== 'initial-prompt')) continue\n if (entry.msg.from === HUMAN_AGENT_ID) {\n return { id: entry.msg.id, body: messageBody(entry.msg) }\n }\n }\n return null\n }, [timeline])\n\n // Auto-hide while the original prompt is on-screen (no reminder needed), show it once the\n // prompt scrolls out of view. The timeline is virtualized, so the prompt row mounts/unmounts\n // as you scroll — re-resolve the target on every scroll and re-attach the observer when the\n // row swaps. When the row is unmounted entirely it's definitely off-screen, so show the banner.\n useEffect(() => {\n if (!lastOutbound || !scrollEl) { setHidden(true); return }\n let observer: IntersectionObserver | null = null\n let observed: Element | null = null\n const sync = () => {\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n if (!target) {\n observer?.disconnect()\n observer = null\n observed = null\n setHidden(false) // prompt row virtualized away → off-screen → show the reminder\n return\n }\n const r = target.getBoundingClientRect()\n const sr = scrollEl.getBoundingClientRect()\n setPromptAbove(r.top < sr.top)\n if (target === observed) return\n observer?.disconnect()\n observed = target\n observer = new IntersectionObserver(\n ([e]) => { if (e) setHidden(e.isIntersecting) },\n { root: scrollEl, threshold: 0 }\n )\n observer.observe(target)\n }\n sync()\n scrollEl.addEventListener('scroll', sync, { passive: true })\n return () => { observer?.disconnect(); scrollEl.removeEventListener('scroll', sync) }\n }, [lastOutbound?.id, scrollEl])\n\n if (hidden || !lastOutbound || !lastOutbound.body.trim()) return null\n\n const expanded = expandedByPrompt?.id === lastOutbound.id ? expandedByPrompt.value : false\n const collapsed = collapsedByPrompt?.id === lastOutbound.id ? collapsedByPrompt.value : false\n\n function scrollToPrompt() {\n if (!scrollEl || !lastOutbound) return\n const target = scrollEl.querySelector(`[data-msg-id=\"${lastOutbound.id}\"]`)\n target?.scrollIntoView({ behavior: 'smooth', block: 'center' })\n }\n\n const arrow = promptAbove ? '↑' : '↓'\n\n if (collapsed) {\n return (\n <div className=\"flex shrink-0 bg-card/45 border-b border-border\">\n <button\n type=\"button\"\n className=\"w-full flex items-center justify-center gap-1.5 py-1 text-[11px] text-primary/60 hover:text-primary transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: false })}\n >\n <span>Your prompt</span>\n <ChevronDown className=\"w-3 h-3\" />\n </button>\n </div>\n )\n }\n\n return (\n <section className=\"flex shrink-0 flex-col border-b border-border bg-card/45 px-3 py-2\">\n <div className=\"flex items-center gap-2 text-[11px] text-muted-foreground mb-0.5\">\n <span className=\"font-medium text-primary/70\">Your prompt</span>\n <button\n type=\"button\"\n className=\"ml-auto hover:text-foreground transition-colors\"\n onClick={scrollToPrompt}\n >\n {arrow} scroll to original\n </button>\n <button\n type=\"button\"\n className=\"hover:text-foreground transition-colors\"\n onClick={() => setCollapsedByPrompt({ id: lastOutbound.id, value: true })}\n title=\"Minimize\"\n >\n <ChevronUp className=\"w-3 h-3\" />\n </button>\n </div>\n <p\n className={cn('text-sm text-foreground leading-snug cursor-pointer', !expanded && 'line-clamp-2')}\n onClick={() => setExpandedByPrompt({ id: lastOutbound.id, value: !expanded })}\n >\n {lastOutbound.body}\n </p>\n </section>\n )\n}\n","\nimport { useSyncExternalStore } from 'react'\nimport { voiceTts } from '@/lib/voice'\n\nexport function useTtsPlayingKey(): string | null {\n return useSyncExternalStore(\n (cb) => voiceTts.subscribe(cb),\n () => voiceTts.getPlayingKey(),\n () => null,\n )\n}\n","\nimport { memo, useEffect, useRef, useState } from 'react'\nimport { AlertCircle, ArrowLeft, ArrowRight, ChevronRight, CircleStop, Download, FileText, Loader2, SmilePlus, Volume2, X, ZoomIn } from 'lucide-react'\nimport { voiceTts } from '@/lib/voice'\nimport { useRelayStore } from '@/store'\nimport { FormattedBody } from '@/components/shared/formatted-body'\nimport { AgentLink } from './TraceView'\nimport { Button } from '@/components/ui/button'\nimport { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'\nimport { apiBlob } from '@/lib/api'\nimport { HUMAN_AGENT_ID } from '@/lib/constants'\nimport { displayTarget, messageBody } from '@/lib/display'\nimport type { AttachmentRef, Message } from '@/types'\nimport { cn } from '@/lib/utils'\nimport type { ReferencedPathInfo } from './types'\nimport {\n chatTimestamp,\n groupedReactions,\n hasActiveTextSelection,\n isReactionEvent,\n messageAttachments,\n outboundReceipt,\n QUICK_REACTIONS,\n resolveRelativePath,\n} from './helpers'\nimport { useTtsPlayingKey } from './hooks/useTtsPlayingKey'\n\nfunction AttachmentPreview({ attachment, outbound }: { attachment: AttachmentRef; outbound: boolean }) {\n const isImage = attachment.kind === 'image'\n const title = attachment.title || attachment.artifactId\n const [objectUrl, setObjectUrl] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [loading, setLoading] = useState(false)\n const [lightboxOpen, setLightboxOpen] = useState(false)\n\n useEffect(() => {\n let cancelled = false\n let url: string | null = null\n\n async function load() {\n setLoading(true)\n setError(null)\n setObjectUrl(null)\n try {\n const blob = await apiBlob(`/artifacts/${encodeURIComponent(attachment.artifactId)}/content`)\n if (cancelled) return\n url = URL.createObjectURL(blob)\n setObjectUrl(url)\n } catch (e) {\n if (!cancelled) setError((e as Error).message)\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n\n void load()\n return () => {\n cancelled = true\n if (url) URL.revokeObjectURL(url)\n }\n }, [attachment.artifactId])\n\n function download() {\n if (!objectUrl) return\n const a = document.createElement('a')\n a.href = objectUrl\n a.download = title\n document.body.appendChild(a)\n a.click()\n a.remove()\n }\n\n if (isImage) {\n return (\n <>\n <button\n type=\"button\"\n onClick={() => objectUrl && setLightboxOpen(true)}\n disabled={!objectUrl}\n className=\"group/img mt-2 block overflow-hidden rounded-md border border-foreground/10 bg-black/10 text-left disabled:cursor-default relative\"\n >\n {objectUrl ? (\n <>\n <img src={objectUrl} alt={title} loading=\"lazy\" className=\"block max-h-72 max-w-full object-contain\" />\n <span className=\"absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/30 transition-colors\">\n <ZoomIn className=\"w-6 h-6 text-white opacity-0 group-hover/img:opacity-100 transition-opacity drop-shadow-md\" />\n </span>\n </>\n ) : (\n <span className={cn('flex min-h-20 items-center gap-2 px-3 py-2 text-xs', error ? 'text-red-400' : 'text-muted-foreground')}>\n {loading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <AlertCircle className=\"h-4 w-4\" />}\n {error || 'Loading image'}\n </span>\n )}\n </button>\n {objectUrl && (\n <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>\n <DialogContent className=\"max-w-[95vw] max-h-[95vh] w-auto p-0 bg-black/95 border-zinc-800 gap-0 overflow-hidden\" showCloseButton={false}>\n <DialogTitle className=\"sr-only\">{title}</DialogTitle>\n <div className=\"relative flex items-center justify-center min-h-[200px]\">\n <img src={objectUrl} alt={title} className=\"max-w-[93vw] max-h-[90vh] object-contain\" />\n <div className=\"absolute top-2 right-2 flex gap-1\">\n <button type=\"button\" onClick={download} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Download\">\n <Download className=\"w-4 h-4\" />\n </button>\n <button type=\"button\" onClick={() => setLightboxOpen(false)} className=\"rounded-md bg-black/60 hover:bg-black/80 p-2 text-white transition-colors\" title=\"Close\">\n <X className=\"w-4 h-4\" />\n </button>\n </div>\n </div>\n </DialogContent>\n </Dialog>\n )}\n </>\n )\n }\n\n return (\n <button\n type=\"button\"\n onClick={download}\n disabled={!objectUrl}\n className={cn(\n 'mt-2 flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-xs transition-colors disabled:cursor-default disabled:opacity-70',\n outbound ? 'border-primary-foreground/20 bg-primary-foreground/10 hover:bg-primary-foreground/15' : 'border-border bg-background hover:bg-muted'\n )}\n >\n {loading ? <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" /> : error ? <AlertCircle className=\"h-4 w-4 shrink-0 text-red-400\" /> : <FileText className=\"h-4 w-4 shrink-0\" />}\n <span className={cn('min-w-0 flex-1 truncate', error && 'text-red-400')}>{error || title}</span>\n <Download className=\"h-3.5 w-3.5 shrink-0\" />\n </button>\n )\n}\n\nfunction AddReaction({ open, onToggle, onReact }: { open: boolean; onToggle: () => void; onReact: (emoji: string) => void }) {\n return (\n <div className=\"relative shrink-0\">\n <button\n type=\"button\"\n title=\"Add reaction\"\n onClick={onToggle}\n className={cn(\n 'inline-flex h-5 w-6 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground',\n open ? 'opacity-100' : 'opacity-0 pointer-events-none md:group-hover/msg:opacity-100 md:group-hover/msg:pointer-events-auto'\n )}\n >\n <SmilePlus className=\"h-3 w-3\" />\n </button>\n {open && (\n <div className=\"absolute bottom-full left-0 z-30 mb-1 flex gap-0.5 rounded-full border border-border bg-popover p-0.5 shadow-md\">\n {QUICK_REACTIONS.map((emoji) => (\n <button\n key={emoji}\n type=\"button\"\n title={`React ${emoji}`}\n onClick={() => onReact(emoji)}\n className=\"inline-flex h-6 w-7 items-center justify-center rounded-full text-xs transition-colors hover:bg-muted\"\n >\n {emoji}\n </button>\n ))}\n </div>\n )}\n </div>\n )\n}\n\n// Inter-agent (peer↔peer) messages render as a compact, foldable one-liner — distinct\n// from the user↔agent bubbles, never persisted-open (#508). The other party is shown via\n// AgentLink (label-preferred + clickable, #522); fan-out targets (broadcast/tag:/cap:/…)\n// fall back to a plain displayTarget label since they don't resolve to one agent.\nfunction PeerMessageLine({ msg, peer }: { msg: Message; peer: string }) {\n const [expanded, setExpanded] = useState(false)\n const agentsById = useRelayStore((s) => s.agentsById)\n const isOutbound = msg.from === peer\n const otherParty = (isOutbound ? msg.to : msg.from) || ''\n // Per-project #NNN linkify (#533/#543): outbound folded lines use the selected\n // peer's repo; inbound inter-agent lines use the originating agent's repo.\n const issueRepo = agentsById[isOutbound ? peer : otherParty]?.issueRepo ?? agentsById[peer]?.issueRepo\n const isSelector = !otherParty || otherParty === 'broadcast' || otherParty.includes(':')\n const body = messageBody(msg)\n const time = chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))\n const DirIcon = isOutbound ? ArrowRight : ArrowLeft\n\n return (\n <div data-msg-id={msg.id} className=\"flex justify-center mb-1.5\">\n <div className=\"w-full max-w-[94%] rounded-md border border-border/50 bg-muted/15 px-2.5 py-1\">\n <div className=\"flex items-center gap-1.5 text-xs cursor-pointer select-none\" onClick={() => setExpanded((v) => !v)}>\n <ChevronRight className={cn('h-3 w-3 shrink-0 text-muted-foreground/60 transition-transform', expanded && 'rotate-90')} />\n <DirIcon className=\"h-3 w-3 shrink-0 text-muted-foreground/70\" />\n <span className=\"shrink-0 text-muted-foreground\">Message {isOutbound ? 'to' : 'from'}</span>\n {isSelector\n ? <span className=\"shrink-0 font-medium text-muted-foreground\">{displayTarget(otherParty, agentsById)}</span>\n : <AgentLink agentId={otherParty} className=\"shrink-0 px-0.5 text-foreground/80\" />}\n {!expanded && <span className=\"min-w-0 flex-1 truncate text-muted-foreground/50\">{body}</span>}\n <span className=\"ml-auto shrink-0 text-muted-foreground/40\">{time}</span>\n </div>\n {expanded && (\n <div className=\"mt-1.5 pl-5\">\n <FormattedBody text={body} rawBody={msg.body} issueRepo={issueRepo} className=\"text-sm leading-relaxed text-foreground/90\" />\n </div>\n )}\n </div>\n </div>\n )\n}\n\nexport const MessageBubble = memo(function MessageBubble({\n msg,\n peer,\n onOpenReferencedPath,\n onPreviewReferencedPath,\n onPreviewReferencedPathEnd,\n}: {\n msg: Message\n peer: string\n onOpenReferencedPath?: (path: string, line?: number, type?: ReferencedPathInfo['type']) => void\n onPreviewReferencedPath?: (path: string, line?: number, anchor?: DOMRect) => void\n onPreviewReferencedPathEnd?: () => void\n}) {\n // Inter-agent (peer↔peer) messages get a folded one-liner instead of a bubble (#508).\n // This early-return precedes all hooks, which is safe here: the timeline keys each\n // MessageBubble by msg id (VirtualTimeline.timelineEntryKey), and from/to are immutable\n // for a given id — so a mounted instance never flips between the two render paths.\n if (msg.from !== HUMAN_AGENT_ID && msg.to !== HUMAN_AGENT_ID) {\n return <PeerMessageLine msg={msg} peer={peer} />\n }\n const isOutbound = msg.from === HUMAN_AGENT_ID\n const reactToMessage = useRelayStore((s) => s.reactToMessage)\n const voiceTtsEnabled = useRelayStore((s) => s.voiceTtsEnabled)\n const ttsPlayingKey = useTtsPlayingKey()\n const peerCwd = useRelayStore((s) => {\n const cwd = s.agentsById[peer]?.meta?.cwd\n return typeof cwd === 'string' ? cwd : ''\n })\n // Per-project #NNN linkify (#533): the peer agent's resolved project repo.\n const peerIssueRepo = useRelayStore((s) => s.agentsById[peer]?.issueRepo)\n const [showQuickReact, setShowQuickReact] = useState(false)\n const bubbleRef = useRef<HTMLDivElement>(null)\n const pointerStartRef = useRef<{ x: number; y: number } | null>(null)\n const suppressBubbleClickRef = useRef(false)\n const body = messageBody(msg)\n const time = chatTimestamp(msg.occurredAt ?? (msg.createdAt as string))\n const attachments = messageAttachments(msg)\n const reactions = groupedReactions(msg)\n const receipt = isOutbound ? outboundReceipt(msg, peer) : null\n const ReceiptIcon = receipt?.icon\n // On-demand TTS: replay any agent response through the same Kokoro/browser\n // pipeline. Only when the speaker is on, and only for inbound non-reaction text.\n const isTtsPlaying = ttsPlayingKey === String(msg.id)\n const showPlayButton = voiceTtsEnabled && !isOutbound && !isReactionEvent(msg) && body.trim().length > 0\n function togglePlay(e: React.MouseEvent) {\n e.stopPropagation()\n if (isTtsPlaying) voiceTts.bargeIn()\n else voiceTts.speak(msg.body, String(msg.id))\n }\n useEffect(() => {\n if (!showQuickReact) return\n function dismiss(e: MouseEvent | TouchEvent) {\n if (hasActiveTextSelection()) return\n if (bubbleRef.current && !bubbleRef.current.contains(e.target as Node)) setShowQuickReact(false)\n }\n document.addEventListener('mousedown', dismiss)\n document.addEventListener('touchstart', dismiss)\n return () => { document.removeEventListener('mousedown', dismiss); document.removeEventListener('touchstart', dismiss) }\n }, [showQuickReact])\n\n function resolvedReferencedPath(path: string): string {\n return resolveRelativePath(peerCwd || '/', path)\n }\n\n function openReferencedPath(path: string, line?: number) {\n const absolute = resolvedReferencedPath(path)\n onOpenReferencedPath?.(absolute, line)\n }\n\n function previewReferencedPath(path: string, line?: number, anchor?: DOMRect) {\n const absolute = resolvedReferencedPath(path)\n onPreviewReferencedPath?.(absolute, line, anchor)\n }\n\n function handleReact(emoji: string) {\n reactToMessage(msg, emoji)\n setShowQuickReact(false)\n }\n\n function handleBubblePointerDown(e: React.PointerEvent<HTMLDivElement>) {\n if (e.button !== 0) return\n pointerStartRef.current = { x: e.clientX, y: e.clientY }\n suppressBubbleClickRef.current = false\n }\n\n function handleBubblePointerMove(e: React.PointerEvent<HTMLDivElement>) {\n const start = pointerStartRef.current\n if (!start) return\n if (Math.abs(e.clientX - start.x) > 3 || Math.abs(e.clientY - start.y) > 3) {\n suppressBubbleClickRef.current = true\n }\n }\n\n function handleBubbleClick(e: React.MouseEvent<HTMLDivElement>) {\n if (isReactionEvent(msg) || isOutbound) return\n const target = e.target as HTMLElement\n if (target.closest('a,button,input,textarea,select,[role=\"button\"]')) return\n if (suppressBubbleClickRef.current || hasActiveTextSelection()) {\n suppressBubbleClickRef.current = false\n return\n }\n setShowQuickReact((v) => !v)\n }\n\n return (\n <div data-msg-id={msg.id} className={cn('group/msg flex mb-3', isOutbound ? 'justify-end' : 'justify-start')}>\n <div ref={bubbleRef} className=\"relative max-w-[85%] md:max-w-[75%]\">\n {showPlayButton && (\n <button\n type=\"button\"\n title={isTtsPlaying ? 'Stop playback' : 'Play aloud'}\n onClick={togglePlay}\n className={cn(\n 'absolute -top-2 -right-2 z-20 inline-flex h-6 w-6 items-center justify-center rounded-full border bg-popover shadow-sm transition',\n isTtsPlaying\n ? 'border-primary/50 text-primary opacity-100'\n // Hide-until-hover only on hover-capable devices; touch screens (iPad)\n // have no hover, so keep the button visible there instead of opacity-0.\n : 'border-border text-muted-foreground opacity-70 hover:bg-muted hover:text-foreground hover:opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover/msg:opacity-100'\n )}\n >\n {isTtsPlaying ? <CircleStop className=\"h-3.5 w-3.5 animate-pulse\" /> : <Volume2 className=\"h-3.5 w-3.5\" />}\n </button>\n )}\n <div\n className={cn(\n 'rounded-2xl px-3.5 py-2 text-sm select-text',\n !isOutbound && !isReactionEvent(msg) && 'cursor-pointer',\n isOutbound\n ? 'bg-primary text-primary-foreground rounded-br-sm'\n : 'bg-card ring-1 ring-foreground/10 rounded-bl-sm'\n )}\n onPointerDown={handleBubblePointerDown}\n onPointerMove={handleBubblePointerMove}\n onClick={handleBubbleClick}\n >\n {msg.subject && (\n <p className={cn('text-xs font-semibold mb-1', isOutbound ? 'text-primary-foreground/70' : 'text-muted-foreground')}>\n {msg.subject}\n </p>\n )}\n <FormattedBody\n text={body}\n rawBody={msg.body}\n issueRepo={peerIssueRepo}\n className=\"leading-relaxed\"\n onOpenPath={openReferencedPath}\n onPreviewPath={previewReferencedPath}\n onPreviewPathEnd={onPreviewReferencedPathEnd}\n resolvePathTitle={(path, line) => `${resolvedReferencedPath(path)}${line ? `:${line}` : ''}`}\n />\n {attachments.map((attachment) => (\n <AttachmentPreview key={`${msg.id}-${attachment.artifactId}-${attachment.role || ''}`} attachment={attachment} outbound={isOutbound} />\n ))}\n <p className={cn('text-xs mt-1 flex items-center gap-1.5', isOutbound ? 'justify-end text-primary-foreground/60' : 'justify-end text-muted-foreground')}>\n <span className=\"opacity-40\">#{msg.id}</span>\n <span>{time}</span>\n {receipt && ReceiptIcon && (\n <span\n className={cn(\n 'inline-flex items-center gap-1',\n receipt.tone === 'ok' && 'text-emerald-300',\n receipt.tone === 'warn' && 'text-amber-200',\n receipt.tone === 'danger' && 'text-red-200'\n )}\n title={receipt.title}\n >\n <ReceiptIcon className=\"h-3 w-3\" />\n {receipt.label}\n </span>\n )}\n </p>\n </div>\n {!isReactionEvent(msg) && reactions.length > 0 && (\n <div className={cn('flex flex-wrap items-center gap-0.5 -mt-1 relative z-10', isOutbound ? 'justify-end pr-2' : 'justify-start pl-2')}>\n {!isOutbound && <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />}\n {reactions.map((reaction) => (\n <button\n key={reaction.emoji}\n type=\"button\"\n title={reaction.actors.join(', ')}\n onClick={() => handleReact(reaction.emoji)}\n className={cn(\n 'inline-flex h-5 items-center gap-0.5 rounded-full border px-1.5 text-[11px] shadow-sm transition-colors',\n reaction.mine\n ? 'border-primary/40 bg-primary/10 text-primary'\n : 'border-border bg-background hover:bg-muted text-foreground'\n )}\n >\n <span>{reaction.emoji}</span>\n {reaction.count > 1 && <span>{reaction.count}</span>}\n </button>\n ))}\n </div>\n )}\n {!isReactionEvent(msg) && !isOutbound && reactions.length === 0 && (\n <div className=\"absolute -bottom-2.5 left-1 z-20\">\n <AddReaction open={showQuickReact} onToggle={() => setShowQuickReact((v) => !v)} onReact={handleReact} />\n </div>\n )}\n </div>\n </div>\n )\n})\n"],"mappings":"qmBA8BA,EAAA,geAgBA,GAAA,IAAA,IAAA,OAAA,KAAA,EAAA,CAAA,CACA,GAAA,IAMA,SAAA,EAAA,EAAA,sDAOA,SAAA,GAAA,EAAA,gRAmBA,SAAA,GAAA,EAAA,8MAQA,SAAA,GAAA,EAAA,+qBAoBA,SAAA,EAAA,EAAA,EAAA,6JAgBA,SAAA,EAAA,EAAA,6CAMA,IAAA,GAAA,IAAA,IAAA,qDAEA,SAAA,EAAA,EAAA,+HAKA,SAAA,GAAA,EAAA,wNAcA,SAAA,GAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA,EAAA,y9GAiNA,SAAA,GAAA,EAAA,+jBAqBA,SAAA,GAAA,EAAA;6GAaA,SAAA,GAAA,EAAA,EAAA,uFC1XA,SAAgB,GAAY,EAAsB,CAGhD,OAFI,EAAO,KAAa,GAAG,EAAK,IAC5B,EAAO,KAAO,KAAa,IAAI,EAAO,MAAM,QAAQ,EAAE,CAAC,KACpD,IAAI,EAAO,KAAO,MAAM,QAAQ,EAAE,CAAC,KAG5C,SAAgB,GAAoB,EAAa,EAAsB,CACrE,GAAI,EAAK,WAAW,IAAI,CAAE,OAAO,EACjC,IAAM,EAAQ,GAAG,EAAI,QAAQ,OAAQ,GAAG,CAAC,GAAG,IAAO,MAAM,IAAI,CACvD,EAAkB,EAAE,CAC1B,IAAK,IAAM,KAAQ,EACb,CAAC,GAAQ,IAAS,MAClB,IAAS,KAAM,EAAM,KAAK,CACzB,E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,EAAA,KAAC,MAAD,CAAK,UAAU,6CACb,EAAA,EAAA,KAAC,GAAD,CAAa,KAAM,EAAgB,aAAgB,EAAmB,GAAM,CAAC,EAAE,CAAE,QAAS,EAAe,CAAA,CACrG,CAAA,CAEJ,GACF,CAAA,EAER"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var e=`user`,t=e,n=5e3,r=new Set([`done`,`failed`,`canceled`]),i=new Set([`open`,`blocked`]),a={online:0,idle:0,busy:2,offline:3},o={idle:0,online:0,busy:2,offline:4},s={from:``,to:``,body:``,channel:``,subject:``,claimable:!1},c={toMode:`agent`,to:``,body:``,channel:``,subject:``,claimable:!1},l={pairId:``,from:``,body:``,subject:``},u={requesterId:``,targetId:``,objective:``},d=[{key:`overview`,label:`Overview`,icon:`LayoutDashboard`},{key:`chat`,label:`Chat`,icon:`MessageCircle`},{key:`agents`,label:`Agents`,icon:`Bot`},{key:`managed`,label:`Managed Agents`,icon:`Workflow`},{key:`teams`,label:`Teams`,icon:`Users`},{key:`profiles`,label:`Agent Profiles`,icon:`UserCog`},{key:`orchestrators`,label:`Orchestrators`,icon:`Server`},{key:`workspaces`,label:`Workspaces`,icon:`GitBranch`},{key:`files`,label:`Files`,icon:`FolderTree`},{key:`channels`,label:`Channels`,icon:`MessagesSquare`},{key:`connectors`,label:`Connectors`,icon:`Plug`},{key:`integrations`,label:`Integrations`,icon:`PlugZap`},{key:`security`,label:`Security`,icon:`Shield`},{key:`memory`,label:`Memory`,icon:`BrainCircuit`},{key:`activity`,label:`Activity`,icon:`Activity`},{key:`pairs`,label:`Pairs`,icon:`Link`},{key:`messages`,label:`Messages`,icon:`Mail`},{key:`work`,label:`Work Queue`,icon:`ListChecks`},{key:`tasks`,label:`Tasks`,icon:`ClipboardList`},{key:`automation`,label:`Automation`,icon:`CalendarClock`},{key:`analytics`,label:`Analytics`,icon:`AreaChart`},{key:`insights`,label:`Insights`,icon:`Lightbulb`},{key:`projects`,label:`Projects`,icon:`Boxes`},{key:`maintenance`,label:`Maintenance`,icon:`Wrench`},{key:`settings`,label:`Settings`,icon:`Settings`}],f={critical:`text-red-400 bg-red-500/10`,warning:`text-yellow-400 bg-yellow-500/10`,info:`text-blue-400 bg-blue-500/10`},p={active:`bg-emerald-500/20 text-emerald-400`,pending:`bg-yellow-500/20 text-yellow-400`,ended:`bg-zinc-500/20 text-zinc-400`,rejected:`bg-red-500/20 text-red-400`,expired:`bg-red-500/20 text-red-400`};function m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ee(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function te(e){return e instanceof Error?e.message:String(e)}var ne=[`cleaned`,`merged`,`abandoned`],h={"admin:*":`system:admin`,"system:write":`system:admin`,"agents:read":`agent:read`,"agents:write":`agent:write`,"messages:read":`message:read`,"messages:write":`message:send`,"tasks:read":`task:read`,"tasks:write":`task:write`,"commands:read":`command:read`,"commands:write":`command:write`,"channels:read":`channel:read`,"channels:write":`channel:write`,"integrations:read":`integration:read`,"integrations:write":`integration:write`,"connectors:read":`integration:read`,"connectors:write":`integration:write`,"events:create":`integration:write`,"tasks:create":`task:write`};function g(e){return h[e]??e}function _(e,t){let n=g(t),r=v(n);if(!r)return!1;if(e?.includes(`*`))return!0;for(let t of e??[]){let e=g(t),i=v(e);if(i&&(e===`system:admin`||e===n||e===`${r.category}:*`||r.category===`settings`&&r.action&&r.namespace&&i.category===`settings`&&i.action===r.action&&i.namespace===void 0))return!0}return!1}function v(e){if(e===`*`)return{category:`*`};let t=e.split(`:`);if(t.some(e=>!e))return null;if(t.length===2){let[e,n]=t;return{category:e,action:n}}if(t.length===3){let[e,n,r]=t;return e!==`settings`||n!==`read`&&n!==`write`||r===`*`?null:{category:e,action:n,namespace:r}}return null}function y(e){let t=typeof e==`number`?e:new Date(e||0).getTime();return Number.isFinite(t)?t:0}var b=[`lifecycle.`,`commands.`,`capabilities.`],x={"+1":`👍`,":+1:":`👍`,thumbsup:`👍`,":thumbsup:":`👍`,"thumbs-up":`👍`,":thumbs-up:":`👍`,thumbs_up:`👍`,":thumbs_up:":`👍`,thumb_up:`👍`,":thumb_up:":`👍`,like:`👍`,":like:":`👍`,heart:`❤️`,":heart:":`❤️`,redheart:`❤️`,red_heart:`❤️`,":red_heart:":`❤️`,check:`✅`,":check:":`✅`,checkmark:`✅`,":checkmark:":`✅`,white_check_mark:`✅`,":white_check_mark:":`✅`,eyes:`👀`,":eyes:":`👀`};function S(e){let t=e.trim();return x[t.toLowerCase()]??t}function re(e){return e.filter(e=>!b.some(t=>e.startsWith(t)))}function ie(e,t=2){if(!e)return``;let n=e.replace(/\/+$/,``).split(`/`);return n.length<=t?e:n.slice(-t).join(`/`)}function C(e){return e.trim().replace(/\\/g,`/`).replace(/\/+$/,``)||`/`}function ae(e,t){if(!e?.trim()||!t?.trim())return!1;let n=C(e),r=C(t);return r===`/`?n.startsWith(`/`):n===`/`?!1:n===r||n.startsWith(r+`/`)}function w(e){return e?.meta?.builtin===!0||e?.id===`user`||e?.id===`system`}function T(e){let t=e?.tags||[],n=e?.capabilities||[],r=typeof e?.meta?.policyName==`string`?e.meta.policyName:``;return e?.kind===`channel`||e?.meta?.kind===`channel`||t.includes(`channel`)||t.some(e=>e.startsWith(`channel:`))||n.includes(`channel`)||n.some(e=>e.startsWith(`channel:`))||t.includes(`telegram`)||n.includes(`telegram`)||r===`telegram-main`}function oe(e){return!!(typeof e?.meta?.automationId==`string`||typeof e?.meta?.automationRunId==`string`||e?.tags?.includes(`automation`))}function E(e){return w(e)||T(e)||oe(e)}function D(e){if(e?.id===`user`)return`user`;if(e?.id===`system`)return`system`;if(T(e))return`channel`;let t=typeof e?.meta?.provider==`string`?e.meta.provider.toLowerCase():void 0;if(t===`codex`)return`codex`;if(t===`claude`)return`claude`;let n=[...e?.tags||[],e?.meta?.client,e?.meta?.runtime,e?.meta?.agentType].filter(e=>typeof e==`string`).map(e=>e.toLowerCase());return n.some(e=>e.includes(`codex`))?`codex`:n.some(e=>e.includes(`claude`))?`claude`:`agent`}function O(e,t){if(!t?.lastSeen||t.status===`offline`||t.id===`user`||t.id===`system`)return!1;let n=t.meta?.transport;if(m(n)&&n.connected===!0)return!1;let r=new Date(t.lastSeen).getTime();return Number.isFinite(r)?e-r>6e4:!1}function k(e,t){if(!e||w(e)||T(e)||t===`resume`)return!1;if(t===`interrupt`)return e.providerCapabilities?.liveSession?.interrupt===!0&&e.status===`busy`;if(D(e)===`claude`&&(t===`restart`||t===`shutdown`||t===`compact`||t===`clearContext`)&&!A(e))return!1;let n=e.providerCapabilities?.lifecycle;if(n){if(t===`restart`)return n.restartHard===!0;if(t===`shutdown`)return n.shutdownHard===!0;if(t===`reconnect`)return n.reconnect===!0}return t===`compact`?e.providerCapabilities?.context?.compact===!0:t===`clearContext`?e.providerCapabilities?.context?.clear===!0:e.meta?.runnerManaged===!0&&(t===`restart`||t===`shutdown`)}function A(e){return typeof e.meta?.tmuxSession==`string`&&e.meta.tmuxSession.trim().length>0}function j(e){return k(e,`restart`)||k(e,`shutdown`)||k(e,`reconnect`)||k(e,`compact`)||k(e,`clearContext`)}function M(e){return!!(e&&!w(e)&&!T(e)&&!j(e)&&(e.status===`offline`||e.status===`stale`))}function N(e,t){if(e.status!==`offline`)return!1;let n=typeof e.meta?.policyName==`string`?e.meta.policyName:``;if(!n)return!1;let r=t.find(e=>e.policy.name===n);return!!(r?.state.agentId&&r.state.agentId!==e.id)}function P(e,t,n=[]){let r=e.filter(e=>!N(e,n));return t?r:r.filter(e=>!E(e))}function F(e){return e?e.label||e.name||e.id.slice(-12):`?`}function I(e,t){if(!e)return`?`;if(e===`broadcast`)return`broadcast`;if(e.startsWith(`tag:`))return`#`+e.slice(4);if(e.startsWith(`cap:`))return e.slice(4);if(e.startsWith(`label:`))return e.slice(6);if(e.startsWith(`team:`)){let n=e.slice(5),r=Object.values(t).find(e=>e.teamId===n);return r?`team:${F(r)}`:`team:${n.slice(-8)}`}let n=t[e];return n?F(n):e.slice(-8)}function L(e){if(!e)return``;let t=e.payload||{},n=t.message;if(n&&typeof n==`object`&&typeof n.text==`string`&&n.text.trim())return n.text;let r=t.interaction;if(r&&typeof r==`object`){let e=typeof r.title==`string`?r.title.trim():``,t=typeof r.description==`string`?r.description.trim():``;if(e&&t)return e+`
|
|
2
|
-
`+t;if(e)return e;if(t)return t}let i=t.reaction;if(i&&typeof i==`object`){let e=typeof i.name==`string`?i.name:``,t=typeof i.emoji==`string`?i.emoji:``,n=typeof i.value==`string`?i.value:``;return[`Reaction`,S(t||e||n)].filter(Boolean).join(`: `)}let a=t.activity;return a&&typeof a==`object`?[typeof a.kind==`string`?a.kind:`activity`,typeof a.state==`string`?a.state:``].filter(Boolean).join(` `):typeof t.text==`string`&&t.text.trim()?t.text:typeof t.message==`string`&&t.message.trim()?t.message:B(e.body||``)??(e.body||``)}function R(e){if(!e?.payload)return!1;let t=e.payload.event;return e.payload.reactionNotification===!0||t?.type===`message.reaction`}function z(e){if(!e)return null;let t=e.trim();if(!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=typeof e.text==`string`?e.text:typeof e.message==`string`?e.message:null;if(!n?.trim())return null;let r=new Set([`text`,`message`]);return{text:n,meta:Object.entries(e).filter(([e,t])=>!r.has(e)&&(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)).map(([e,t])=>[e,String(t)]),raw:e}}catch{return null}}function B(e){return z(e)?.text??null}function V(e){let t=e?.subject||L(e)||``;return t.length>90?t.slice(0,90)+`...`:t}function H(e){return e.from===`user`&&e.to?e.to:e.to===`user`&&e.from?e.from:``}function U(e){return e.to===`user`&&e.from!==`user`}function W(e){if(e.kind!==`session`)return!1;let t=e.payload?.session?.type;return t===`reasoning`||t===`tool`}function G(e){return e.kind===`session`&&e.payload?.session?.type===`response`}function K(e,t){let n=e.trim(),r=t.trim();return r?n===r?!0:n.startsWith(`${r}\n\n`)||n.endsWith(`\n\n${r}`)||n.includes(`\n\n${r}\n\n`):!1}function q(e,t,n){if(!U(n)||!G(n)||(n.readBy||[]).includes(`user`))return!1;let r=Number(e[t]||0);return n.id>(Number.isFinite(r)?r:0)}function se(e){return i.has(e.status)&&!e.claimedBy}function ce(e){return!!(e.claimable&&!e.claimedBy&&!(e.kind===`task`&&Number.isSafeInteger(e.payload?.taskId)))}function le(e,t){return!e||!t?!1:e===`broadcast`||e===t.id?!0:e.startsWith(`tag:`)?(t.tags||[]).includes(e.slice(4)):e.startsWith(`cap:`)?(t.capabilities||[]).includes(e.slice(4)):e.startsWith(`label:`)?t.label===e.slice(6):e.startsWith(`team:`)?t.teamId===e.slice(5):!1}function ue(e,t){return e?t.from===e||t.to===e||t.resolvedToAgent===e:!1}function de(e,t){if(!e||!t)return!1;let n=[t.id,t.type,...t.topicChannels||[]].filter(Boolean);if(e.channel&&n.includes(e.channel))return!0;let r=e.payload?.channel;if(r&&typeof r==`object`){let e=[r.agentId,r.provider,r.accountId].filter(Boolean);if(e.includes(t.id)||e.includes(t.type)||t.accountId&&e.includes(t.accountId))return!0}return!!(t.agentId&&(e.from===t.agentId||e.to===t.agentId))}function J(e){let t=e?.meta?.providerState;return!m(t)||typeof t.state!=`string`?null:{state:t.state,reason:typeof t.reason==`string`?t.reason:void 0,label:typeof t.label==`string`&&t.label?t.label:t.state,recommendedAction:typeof t.recommendedAction==`string`?t.recommendedAction:void 0,source:typeof t.source==`string`?t.source:void 0,raw:t.raw,updatedAt:typeof t.updatedAt==`number`?t.updatedAt:void 0,pendingApproval:fe(t.pendingApproval)}}function fe(e){if(!m(e)||typeof e.id!=`string`)return;let t=Array.isArray(e.choices)?e.choices.filter(m).map(e=>({id:e.id,label:typeof e.label==`string`?e.label:String(e.id||``)})).filter(e=>(e.id===`approve`||e.id===`approve-session`||e.id===`deny`||e.id===`abort`)&&!!e.label):[],n=Array.isArray(e.questions)?e.questions.filter(m).map(e=>({question:typeof e.question==`string`?e.question:``,header:typeof e.header==`string`?e.header:void 0,multiSelect:e.multiSelect===!0,options:Array.isArray(e.options)?e.options.filter(m).map(e=>({label:typeof e.label==`string`?e.label:String(e.label??``),description:typeof e.description==`string`?e.description:void 0})).filter(e=>!!e.label):[]})).filter(e=>!!e.question&&e.options.length>0):void 0;return{id:e.id,provider:typeof e.provider==`string`?e.provider:void 0,kind:typeof e.kind==`string`?e.kind:void 0,title:typeof e.title==`string`&&e.title?e.title:`Permission request`,body:typeof e.body==`string`?e.body:``,choices:t,...n&&n.length?{questions:n}:{}}}function Y(e){let t=J(e);return t?.state===`blocked`?t:null}function pe(e){return!!e?.id}function me(e){return pe(Y(e)?.pendingApproval)}function X(e){let t=e?.meta?.activeSubagents;if(!Array.isArray(t)){let t=typeof e?.meta?.activeSubagentCount==`number`?e.meta.activeSubagentCount:0;return t>0?Array.from({length:t},(e,t)=>({id:`subagent-${t+1}`,label:`Subagent ${t+1}`})):[]}return t.filter(m).map((e,t)=>{let n=typeof e.id==`string`&&e.id?e.id:`subagent-${t+1}`,r=typeof e.role==`string`&&e.role?e.role:void 0;return{id:n,label:typeof e.label==`string`&&e.label?e.label:r||n,role:r,startedAt:typeof e.startedAt==`number`?e.startedAt:void 0}})}function Z(e){let t=e?.meta?.activeWork;if(!Array.isArray(t))return null;let n=t.find(e=>m(e)&&e.kind===`background-script`);return!n||!m(n)?null:typeof n.label==`string`&&n.label?n.label:`background script`}function he(e,t,n,r){let i=typeof t?.meta?.lifecycleAction==`string`?t.meta.lifecycleAction:``,a=O(e,t),o=t?.status!==`offline`&&!t?.ready&&a,s=t?.status!==`offline`&&!t?.ready&&!a,c=n.unread>0&&t?.status!==`busy`,l=Y(t),u=ge(t,n,r);if(t?.status===`offline`)return{label:`offline`,tone:`secondary`,icon:`PlugZap`,stale:!1,reconnecting:!1,badges:u};if(i.startsWith(`finalizing-`))return{label:`wrapping up (${i.slice(11)})`,tone:`warning`,icon:`Hourglass`,stale:a,reconnecting:o,badges:u};if(i===`shutting-down`)return{label:`shutting down`,tone:`warning`,icon:`Power`,stale:a,reconnecting:o,badges:u};if(i===`killing`)return{label:`killing`,tone:`danger`,icon:`Power`,stale:a,reconnecting:o,badges:u};if(i===`restarting`)return{label:`restarting`,tone:`warning`,icon:`RefreshCw`,stale:a,reconnecting:o,badges:u};if(t?.status===`stale`)return{label:`stale`,tone:`danger`,icon:`RefreshCw`,stale:!0,reconnecting:!0,badges:u};if(o)return{label:`reconnecting`,tone:`danger`,icon:`RefreshCw`,stale:a,reconnecting:o,badges:u};if(s)return{label:`online, not ready`,tone:`warning`,icon:`Loader`,stale:a,reconnecting:o,badges:u};if(l)return{label:`blocked: ${l.label}`,tone:`danger`,icon:`AlertCircle`,stale:a,reconnecting:o,badges:u};if(t?.status===`busy`){let e=Array.isArray(t?.meta?.busyReasons)?t.meta.busyReasons:[];return Z(t)&&!e.includes(`provider-turn`)&&!e.includes(`subagent`)?{label:`running background work`,tone:`warning`,icon:`Play`,stale:a,reconnecting:o,badges:u}:{label:`busy in turn`,tone:`warning`,icon:`Play`,stale:a,reconnecting:o,badges:u}}return r?.status===`active`?{label:`paired`,tone:`success`,icon:`Link`,stale:a,reconnecting:o,badges:u}:c?{label:`idle, unread`,tone:`danger`,icon:`Bell`,stale:a,reconnecting:o,badges:u}:{label:t?.status===`idle`?`idle`:`ready`,tone:`success`,icon:`CircleCheck`,stale:a,reconnecting:o,badges:u}}function ge(e,t,n){let r=[],i=Y(e),a=X(e).length;i&&r.push({label:i.reason?`blocked: ${i.reason}`:`blocked`,className:`bg-red-500/20 text-red-400`}),a&&r.push({label:a===1?`1 subagent`:a+` subagents`,className:`bg-cyan-500/20 text-cyan-300`});let o=Z(e);return o&&r.push({label:o,className:`bg-indigo-500/20 text-indigo-300`}),n?.status===`active`&&r.push({label:`paired`,className:`bg-emerald-500/20 text-emerald-400`}),n?.status===`pending`&&r.push({label:`pair invite`,className:`bg-yellow-500/20 text-yellow-400`}),t.needsHumanResponse&&r.push({label:`needs response`,className:`bg-amber-500/20 text-amber-300`}),t.unread&&r.push({label:t.unread+` unread`,className:`bg-red-500/20 text-red-400`}),t.claimableTasks&&r.push({label:t.claimableTasks+` claimable`,className:`bg-orange-500/20 text-orange-400`}),r}function _e(){return{unread:0,needsHumanResponse:!1,pendingPairInvite:!1,claimableTasks:0,total:0,score:0}}function Q(e){return!e||e.status===`offline`?!1:e.targetHealth?.status===`ok`?!0:e.targetHealth?.status===`error`||e.targetHealth?.status===`warning`?!1:e.ready}function ve(e){return e?e.targetHealth?.status===`error`?{label:`target broken`,tone:`danger`,icon:`AlertTriangle`,badges:[]}:e.targetHealth?.status===`warning`?{label:`target warning`,tone:`warning`,icon:`AlertCircle`,badges:[]}:e.status===`offline`?{label:`offline`,tone:`secondary`,icon:`PlugZap`,badges:[]}:e.status===`busy`?{label:`busy`,tone:`warning`,icon:`Activity`,badges:[]}:Q(e)?{label:`ready`,tone:`success`,icon:`CircleCheck`,badges:[]}:{label:`not ready`,tone:`warning`,icon:`Loader`,badges:[]}:{label:`unknown`,tone:`secondary`,icon:`PlugZap`,badges:[]}}function ye(e){let t=e?.runtime||{};return t.status===`error`?{label:`error`,tone:`danger`,icon:`AlertTriangle`,badges:[]}:t.status===`warn`?{label:`warning`,tone:`warning`,icon:`AlertCircle`,badges:[]}:t.running?{label:`running`,tone:`success`,icon:`CircleCheck`,badges:[]}:t.enabled===!1?{label:`disabled`,tone:`secondary`,icon:`Pause`,badges:[]}:t.status===`ok`?{label:`ok`,tone:`success`,icon:`CircleCheck`,badges:[]}:{label:`unknown`,tone:`secondary`,icon:`HelpCircle`,badges:[]}}function be(e){let t=e?.taskStats||{};return(t.waitingTasks||0)>0?{label:`waiting`,tone:`warning`,icon:`AlertCircle`,badges:[]}:(t.openTasks||0)>0?{label:`active`,tone:`info`,icon:`Activity`,badges:[]}:e?.configured?e.observed?{label:`quiet`,tone:`success`,icon:`CircleCheck`,badges:[]}:{label:`configured`,tone:`primary`,icon:`PlugZap`,badges:[]}:{label:`observed only`,tone:`secondary`,icon:`Eye`,badges:[]}}function xe(e){let t=e?.health;return!t||t.status===`ok`?e?.version||e?.package?.version?`compatible`:`unknown version`:t.status===`upgrade-required`?`upgrade required`:t.status===`restart-required`?`restart required`:t.status===`unknown`?`unknown contract`:(t.issues||[]).some(e=>e.code===`protocol-mismatch`)?`protocol mismatch`:(t.issues||[]).some(e=>e.code===`package-drift`)?`package drift`:t.restartRequired?`restart required`:t.status}function Se(e){let t=e?.health?.status;return t===`upgrade-required`?`text-red-400 bg-red-500/10`:t===`warn`||t===`restart-required`?`text-yellow-400 bg-yellow-500/10`:t===`unknown`?`text-zinc-400 bg-zinc-500/10`:`text-emerald-400 bg-emerald-500/10`}function Ce(e,t){if(!t)return``;let n=new Date(t).getTime();if(!Number.isFinite(n))return``;let r=Math.max(0,(e-n)/1e3);return r<60?Math.floor(r)+`s ago`:r<3600?Math.floor(r/60)+`m ago`:r<86400?Math.floor(r/3600)+`h ago`:Math.floor(r/86400)+`d ago`}function $(e){return e?new Date(e).toLocaleString():``}function we(e){return String(e||`export`).replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`export`}function Te(e){return e.filter(e=>e.status!==`ok`).map(e=>{let t={name:e.name,status:e.status,detail:e.detail||e.name,impact:Ee(e),subjects:e.subjects||[],actions:[{label:`Inspect logs`,icon:`FileSearch`,copy:`agent-relay daemon logs`},{label:`Restart daemon`,icon:`RefreshCw`,copy:`agent-relay daemon restart`},{label:`Copy env`,icon:`Copy`,copy:`agent-relay doctor`}]};return e.name===`stale-live-agents`?t.actions.unshift({label:`Run reaper`,icon:`Eraser`,api:`POST`,path:`/system/reap`},{label:`Show stale`,icon:`Filter`,view:`agents`,preset:`offline_stale`}):e.name===`channel-delivery-targets`?t.actions.unshift({label:`Open channels`,icon:`MessagesSquare`,view:`channels`},{label:`Run reaper`,icon:`Eraser`,api:`POST`,path:`/system/reap`}):[`expired-message-claims`,`expired-task-claims`,`offline-claimed-tasks`].includes(e.name)&&t.actions.unshift({label:`Run reaper`,icon:`Eraser`,api:`POST`,path:`/system/reap`},{label:`Open work`,icon:`ListChecks`,view:`work`}),t})}function Ee(e){return{database:`Relay persistence is unavailable; messages, state, and audit writes may fail.`,"stale-live-agents":`Agents may look online even though their heartbeat has stopped.`,"expired-message-claims":`Claimable messages may be stuck until the reaper releases expired claims.`,"expired-task-claims":`Tasks can appear owned by agents that no longer hold a live lease.`,"offline-claimed-tasks":`Offline agents are still shown as owners for active work.`,"channel-delivery-targets":`Inbound channel messages may be accepted but routed to no live delivery agent.`}[e.name]||`Relay health is degraded for this check.`}function De(e){return{success:`text-emerald-400`,warning:`text-yellow-400`,danger:`text-red-400`,info:`text-blue-400`,primary:`text-blue-400`,secondary:`text-zinc-400`}[e]||`text-zinc-400`}function Oe(e,t){return!e||e.status===`offline`?`bg-zinc-500 opacity-50`:typeof e.meta?.lifecycleAction==`string`&&e.meta.lifecycleAction.startsWith(`finalizing-`)?`bg-amber-500 animate-pulse`:e.meta?.lifecycleAction===`shutting-down`||e.meta?.lifecycleAction===`restarting`?`bg-yellow-500 animate-pulse`:e.meta?.lifecycleAction===`killing`||Y(e)?`bg-red-500 animate-pulse`:e.status===`busy`?`bg-yellow-500`:t&&O(t,e)?`bg-red-500 animate-pulse`:e.ready?`bg-emerald-500 shadow-[0_0_6px_theme(colors.emerald.500)]`:`bg-emerald-500 animate-pulse`}function ke(e,t,n){if(typeof document>`u`||typeof URL>`u`||typeof Blob>`u`)return;let r=URL.createObjectURL(new Blob([t],{type:n})),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),URL.revokeObjectURL(r)}export{o as $,V as A,we as B,U as C,L as D,q as E,z as F,De as G,Oe as H,ae as I,_ as J,re as K,Y as L,S as M,Se as N,ue as O,xe as P,ee as Q,J as R,se as S,W as T,Ce as U,ie as V,y as W,te as X,ne as Y,m as Z,H as _,k as a,e as at,G as b,ve as c,d as ct,F as d,a as dt,r as et,I as f,Te as g,$ as h,he as i,l as it,C as j,de as k,ye as l,p as lt,_e as m,M as n,c as nt,D as o,t as ot,ke as p,P as q,me as r,u as rt,Q as s,n as st,X as t,s as tt,le as u,f as ut,be as v,R as w,ce as x,O as y,K as z};
|
|
3
|
-
//# sourceMappingURL=display-LAWaAboe.js.map
|