cortena-ui 1.4.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +7 -0
  3. package/README.md +235 -3
  4. package/dist/a2ui/views.js +2 -2
  5. package/dist/agent-chat/a2ui-block.d.ts +60 -0
  6. package/dist/agent-chat/a2ui-block.js +69 -0
  7. package/dist/agent-chat/a2ui-block.js.map +1 -0
  8. package/dist/agent-chat/agui-client.d.ts +40 -0
  9. package/dist/agent-chat/agui-client.js +251 -0
  10. package/dist/agent-chat/agui-client.js.map +1 -0
  11. package/dist/agent-chat/bridge.d.ts +109 -0
  12. package/dist/agent-chat/bridge.js +353 -0
  13. package/dist/agent-chat/bridge.js.map +1 -0
  14. package/dist/agent-chat/session.d.ts +79 -0
  15. package/dist/agent-chat/session.js +391 -0
  16. package/dist/agent-chat/session.js.map +1 -0
  17. package/dist/agent-chat/step-label.d.ts +99 -0
  18. package/dist/agent-chat/step-label.js +116 -0
  19. package/dist/agent-chat/step-label.js.map +1 -0
  20. package/dist/agent-chat/store.d.ts +102 -0
  21. package/dist/agent-chat/store.js +876 -0
  22. package/dist/agent-chat/store.js.map +1 -0
  23. package/dist/agent-chat/types.d.ts +277 -0
  24. package/dist/agent-chat/types.js +17 -0
  25. package/dist/agent-chat/types.js.map +1 -0
  26. package/dist/agent-chat.d.ts +11 -0
  27. package/dist/agent-chat.js +11 -0
  28. package/dist/components/admin-permissions/admin-permissions.d.ts +66 -0
  29. package/dist/components/admin-permissions/admin-permissions.js +101 -0
  30. package/dist/components/admin-permissions/admin-permissions.js.map +1 -0
  31. package/dist/components/admin-permissions/context.d.ts +70 -0
  32. package/dist/components/admin-permissions/context.js +258 -0
  33. package/dist/components/admin-permissions/context.js.map +1 -0
  34. package/dist/components/admin-permissions/index.d.ts +10 -0
  35. package/dist/components/admin-permissions/licence.d.ts +15 -0
  36. package/dist/components/admin-permissions/licence.js +78 -0
  37. package/dist/components/admin-permissions/licence.js.map +1 -0
  38. package/dist/components/admin-permissions/matrix.d.ts +20 -0
  39. package/dist/components/admin-permissions/matrix.js +191 -0
  40. package/dist/components/admin-permissions/matrix.js.map +1 -0
  41. package/dist/components/admin-permissions/members.d.ts +18 -0
  42. package/dist/components/admin-permissions/members.js +185 -0
  43. package/dist/components/admin-permissions/members.js.map +1 -0
  44. package/dist/components/admin-permissions/role-assignment.d.ts +35 -0
  45. package/dist/components/admin-permissions/role-assignment.js +174 -0
  46. package/dist/components/admin-permissions/role-assignment.js.map +1 -0
  47. package/dist/components/admin-permissions/roles.d.ts +25 -0
  48. package/dist/components/admin-permissions/roles.js +168 -0
  49. package/dist/components/admin-permissions/roles.js.map +1 -0
  50. package/dist/components/admin-permissions/types.d.ts +152 -0
  51. package/dist/components/admin-permissions/types.js +63 -0
  52. package/dist/components/admin-permissions/types.js.map +1 -0
  53. package/dist/components/agent-chat-popup.d.ts +29 -0
  54. package/dist/components/agent-chat-popup.js +188 -0
  55. package/dist/components/agent-chat-popup.js.map +1 -0
  56. package/dist/components/agent-chat.d.ts +163 -0
  57. package/dist/components/agent-chat.js +673 -0
  58. package/dist/components/agent-chat.js.map +1 -0
  59. package/dist/components/app-shell.d.ts +126 -0
  60. package/dist/components/app-shell.js +297 -0
  61. package/dist/components/app-shell.js.map +1 -0
  62. package/dist/components/badge.d.ts +1 -1
  63. package/dist/components/button-link.js +1 -1
  64. package/dist/components/button.d.ts +1 -1
  65. package/dist/components/checkbox.d.ts +1 -1
  66. package/dist/components/combobox.d.ts +1 -1
  67. package/dist/components/combobox.js +1 -1
  68. package/dist/components/consent-screen.d.ts +65 -0
  69. package/dist/components/consent-screen.js +123 -0
  70. package/dist/components/consent-screen.js.map +1 -0
  71. package/dist/components/data-table/data-table.d.ts +15 -1
  72. package/dist/components/data-table/data-table.js +18 -4
  73. package/dist/components/data-table/data-table.js.map +1 -1
  74. package/dist/components/data-table/index.d.ts +4 -4
  75. package/dist/components/data-table/parts.d.ts +27 -3
  76. package/dist/components/data-table/parts.js +175 -55
  77. package/dist/components/data-table/parts.js.map +1 -1
  78. package/dist/components/data-table/types.d.ts +61 -0
  79. package/dist/components/data-table/use-data-table.js +91 -6
  80. package/dist/components/data-table/use-data-table.js.map +1 -1
  81. package/dist/components/data-table/use-server-source.js +119 -28
  82. package/dist/components/data-table/use-server-source.js.map +1 -1
  83. package/dist/components/help-panel.d.ts +131 -0
  84. package/dist/components/help-panel.js +545 -0
  85. package/dist/components/help-panel.js.map +1 -0
  86. package/dist/components/login-screen.d.ts +127 -0
  87. package/dist/components/login-screen.js +339 -0
  88. package/dist/components/login-screen.js.map +1 -0
  89. package/dist/components/session-guard.d.ts +268 -0
  90. package/dist/components/session-guard.js +632 -0
  91. package/dist/components/session-guard.js.map +1 -0
  92. package/dist/components/toast.d.ts +1 -1
  93. package/dist/core.d.ts +5 -1
  94. package/dist/core.js +11 -7
  95. package/dist/data-table.d.ts +13 -4
  96. package/dist/data-table.js +10 -2
  97. package/dist/hooks/use-cortena-theme.js +49 -3
  98. package/dist/hooks/use-cortena-theme.js.map +1 -1
  99. package/dist/index.d.ts +17 -4
  100. package/dist/index.js +21 -8
  101. package/dist/markdown.d.ts +2 -1
  102. package/dist/markdown.js +2 -1
  103. package/package.json +18 -5
  104. package/src/agent-chat/a2ui-block.ts +118 -0
  105. package/src/agent-chat/agui-client.ts +405 -0
  106. package/src/agent-chat/bridge.ts +445 -0
  107. package/src/agent-chat/session.ts +549 -0
  108. package/src/agent-chat/step-label.ts +177 -0
  109. package/src/agent-chat/store.ts +1234 -0
  110. package/src/agent-chat/types.ts +308 -0
  111. package/src/components/admin-permissions/admin-permissions.tsx +130 -0
  112. package/src/components/admin-permissions/context.tsx +376 -0
  113. package/src/components/admin-permissions/index.tsx +32 -0
  114. package/src/components/admin-permissions/licence.tsx +84 -0
  115. package/src/components/admin-permissions/matrix.tsx +257 -0
  116. package/src/components/admin-permissions/members.tsx +204 -0
  117. package/src/components/admin-permissions/role-assignment.tsx +239 -0
  118. package/src/components/admin-permissions/roles.tsx +169 -0
  119. package/src/components/admin-permissions/types.ts +231 -0
  120. package/src/components/agent-chat-popup.tsx +289 -0
  121. package/src/components/agent-chat.tsx +1006 -0
  122. package/src/components/app-shell.tsx +502 -0
  123. package/src/components/consent-screen.tsx +239 -0
  124. package/src/components/data-table/data-table.tsx +36 -0
  125. package/src/components/data-table/index.tsx +6 -1
  126. package/src/components/data-table/parts.tsx +223 -47
  127. package/src/components/data-table/types.ts +68 -0
  128. package/src/components/data-table/use-data-table.ts +152 -4
  129. package/src/components/data-table/use-server-source.ts +150 -12
  130. package/src/components/help-panel.tsx +765 -0
  131. package/src/components/login-screen.tsx +479 -0
  132. package/src/components/session-guard.tsx +1071 -0
  133. package/src/entries/agent-chat.ts +137 -0
  134. package/src/entries/core.ts +8 -0
  135. package/src/entries/data-table.ts +41 -0
  136. package/src/entries/markdown.ts +25 -0
  137. package/src/hooks/use-cortena-theme.ts +63 -4
  138. package/src/index.ts +6 -0
@@ -0,0 +1,391 @@
1
+ "use client";
2
+ import { truncate } from "./step-label.js";
3
+ //#region src/agent-chat/session.ts
4
+ /**
5
+ * Sessions, history and the filter chain.
6
+ *
7
+ * Ported from `cortena-shared/src/stores/use-chat.ts` and
8
+ * `cortenaweb/components/chat/message-bubble.tsx` (Cortena monorepo).
9
+ * `cortena-shared` is not published, so the rules the two transports share
10
+ * live here; keep them in step.
11
+ *
12
+ * The one deliberate difference is where the current session key is kept.
13
+ * cortenaweb puts it in `localStorage`, which is shared by every tab of an
14
+ * origin, so a second window adopted the first window's session: it inherited
15
+ * a stream that was not its own and both windows then showed the same content.
16
+ * Sessions here are **per window** — the key lives in `sessionStorage`, under a
17
+ * name scoped to the extension — so opening the extension twice starts two
18
+ * sessions. Both stay listed and either window can resume either one; two
19
+ * windows on one session may both send, and cortenacore serialises the runs.
20
+ */
21
+ /**
22
+ * A new session key, minted client-side.
23
+ *
24
+ * `agent:<agentId>:new-<Date.now()>-<random36>`. cortenacore reads the
25
+ * `agent:<id>:` prefix to bind the session to that agent's template, and the
26
+ * key is the AG-UI `threadId` verbatim, prefix included. Minting it rather than
27
+ * asking for one is what lets the first message go out immediately.
28
+ */
29
+ function mintSessionKey(agentId) {
30
+ return `agent:${agentId}:new-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
31
+ }
32
+ /** Was this key minted locally for a chat that had no session yet? */
33
+ function isProvisionalSessionKey(key) {
34
+ return /(^|:)new-\d+-[a-z0-9]+$/.test(key);
35
+ }
36
+ /** Does this session belong to this agent? `sessions.list` is filtered by it. */
37
+ function isSessionOfAgent(key, agentId) {
38
+ return key.startsWith(`agent:${agentId}:`);
39
+ }
40
+ /** The `sessionStorage` name the current key is kept under, per extension. */
41
+ function sessionStorageKey(scope) {
42
+ return `cortena.agent-chat.${scope}.session`;
43
+ }
44
+ /** The `sessionStorage` name the open/collapsed state is kept under. */
45
+ function viewStorageKey(scope) {
46
+ return `cortena.agent-chat.${scope}.view`;
47
+ }
48
+ /** The `sessionStorage` name this window's progress steps are kept under. */
49
+ function stepsStorageKey(scope) {
50
+ return `cortena.agent-chat.${scope}.steps`;
51
+ }
52
+ /**
53
+ * `sessionStorage`, or nothing.
54
+ *
55
+ * Absent during SSR and refused outright when a browser blocks storage for the
56
+ * origin, and neither is a reason for the chat not to work: without it a window
57
+ * simply forgets its session on reload.
58
+ */
59
+ function windowSessionStorage() {
60
+ try {
61
+ return typeof window === "undefined" ? null : window.sessionStorage;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ function readStoredSessionKey(scope) {
67
+ try {
68
+ return windowSessionStorage()?.getItem(sessionStorageKey(scope)) ?? null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+ function writeStoredSessionKey(scope, key) {
74
+ try {
75
+ const storage = windowSessionStorage();
76
+ if (!storage) return;
77
+ if (key === null) storage.removeItem(sessionStorageKey(scope));
78
+ else storage.setItem(sessionStorageKey(scope), key);
79
+ } catch {}
80
+ }
81
+ /** Most steps kept, in memory and in `sessionStorage`. A turn that long is a runaway loop. */
82
+ const STEP_LIMIT = 50;
83
+ /**
84
+ * Most bytes the steps slot may occupy.
85
+ *
86
+ * `sessionStorage` is a few megabytes for the whole origin, shared with
87
+ * everything else the host keeps there, and a step count alone does not bound
88
+ * the size: fifty steps whose labels are all near the limit, with a failure
89
+ * message on each, is a slot nobody budgeted for. Over the cap the OLDEST are
90
+ * dropped, one at a time, because the recent ones are the ones a reload has to
91
+ * bring back.
92
+ */
93
+ const STEP_BYTE_LIMIT = 65536;
94
+ /**
95
+ * The steps of the current turn, and the session they belong to.
96
+ *
97
+ * They go in the per-window store beside the session key, for the same reason
98
+ * the key does: a tab is reloaded mid-run, or a host remounts the surface on a
99
+ * route change, and both threw the whole strip away. (Collapsing the pop-up is
100
+ * NOT one of them — the panel is `hidden`, not unmounted, and the run streams
101
+ * into it either way.) Messages come back from `chat.history`; steps do not
102
+ * exist on the server, so this is the only place they can come back from.
103
+ *
104
+ * Scoped to a session key, and checked on read: resuming a different session
105
+ * must not inherit the last one's steps.
106
+ */
107
+ function readStoredSteps(scope, sessionKey) {
108
+ try {
109
+ const raw = windowSessionStorage()?.getItem(stepsStorageKey(scope));
110
+ if (!raw) return [];
111
+ const parsed = JSON.parse(raw);
112
+ if (parsed?.sessionKey !== sessionKey || !Array.isArray(parsed.steps)) return [];
113
+ return parsed.steps.filter((step) => typeof step?.id === "string" && typeof step?.label === "string").map(restoreStep).slice(-50);
114
+ } catch {
115
+ return [];
116
+ }
117
+ }
118
+ /** Every status a step may legitimately come back with. */
119
+ const STEP_STATUSES = /* @__PURE__ */ new Set([
120
+ "running",
121
+ "done",
122
+ "error",
123
+ "stopped",
124
+ "paused"
125
+ ]);
126
+ /**
127
+ * A step as it comes back from storage.
128
+ *
129
+ * The important cases are `running` and `paused`. Neither is true any more:
130
+ * the run that owned the call ended when the surface went away — a reload, a
131
+ * remount on a route change; a collapsed pop-up only HIDES the strip and never
132
+ * reaches this path — and no result will arrive for it now, so a restored
133
+ * spinner spins until the user gives up and reloads again, which restores it.
134
+ *
135
+ * It comes back `stopped`, with no message. Neutral is the honest reading:
136
+ * nothing failed, the work simply did not continue, and "Interrupted." drawn in
137
+ * the failure colour told the user their call had broken when the page had.
138
+ *
139
+ * An unrecognised status is treated the same way. Nothing else writes this
140
+ * slot today, but it is per-origin `sessionStorage` and this is the only place
141
+ * that decides what a strip is allowed to render.
142
+ */
143
+ function restoreStep(step) {
144
+ if (STEP_STATUSES.has(step.status) && step.status !== "running" && step.status !== "paused") return step;
145
+ const restored = {
146
+ ...step,
147
+ status: "stopped",
148
+ endedAt: step.endedAt ?? Date.now()
149
+ };
150
+ delete restored.errorMessage;
151
+ return restored;
152
+ }
153
+ /**
154
+ * The fields of a step that are safe to keep, and the only ones kept.
155
+ *
156
+ * `args` is deliberately absent. A tool call's arguments are the user's data —
157
+ * what they searched for, whose record they opened, the body of what they
158
+ * wrote — and `sessionStorage` is readable by every script on the origin,
159
+ * survives the run, and is the sort of thing that ends up in a support bundle.
160
+ * Nothing on screen needs them after the run: the LABEL is already derived
161
+ * from them, and the label is what a restored strip shows.
162
+ */
163
+ function storedStep(step) {
164
+ return {
165
+ id: truncate(step.id, 80),
166
+ toolName: truncate(step.toolName, 80),
167
+ label: step.label,
168
+ status: step.status,
169
+ startedAt: step.startedAt,
170
+ ...step.endedAt === void 0 ? {} : { endedAt: step.endedAt },
171
+ ...step.errorMessage === void 0 ? {} : { errorMessage: step.errorMessage }
172
+ };
173
+ }
174
+ /** The slot's contents, projected and trimmed to fit the byte cap. */
175
+ function serialiseSteps(sessionKey, steps) {
176
+ let kept = steps.slice(-50).map(storedStep);
177
+ let json = JSON.stringify({
178
+ sessionKey,
179
+ steps: kept
180
+ });
181
+ while (kept.length > 1 && json.length > STEP_BYTE_LIMIT) {
182
+ kept = kept.slice(1);
183
+ json = JSON.stringify({
184
+ sessionKey,
185
+ steps: kept
186
+ });
187
+ }
188
+ return json;
189
+ }
190
+ function writeStoredSteps(scope, sessionKey, steps) {
191
+ try {
192
+ const storage = windowSessionStorage();
193
+ if (!storage) return;
194
+ if (!sessionKey || steps.length === 0) {
195
+ storage.removeItem(stepsStorageKey(scope));
196
+ return;
197
+ }
198
+ storage.setItem(stepsStorageKey(scope), serialiseSteps(sessionKey, steps));
199
+ } catch {}
200
+ }
201
+ function generateId() {
202
+ return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
203
+ }
204
+ function isToolRelatedMessage(msg) {
205
+ const role = typeof msg.role === "string" ? msg.role.toLowerCase() : "";
206
+ if (role === "tool" || role === "toolresult" || role === "tool_result") return true;
207
+ const content = msg.content;
208
+ if (Array.isArray(content) && content.length > 0) {
209
+ const toolTypes = /* @__PURE__ */ new Set([
210
+ "tool_use",
211
+ "tool_call",
212
+ "tool_result",
213
+ "toolresult",
214
+ "server_tool_use"
215
+ ]);
216
+ const hasText = content.some((c) => c.type === "text" || c.type === "thinking");
217
+ if (content.some((c) => toolTypes.has(c.type)) && !hasText) return true;
218
+ }
219
+ return false;
220
+ }
221
+ /**
222
+ * Strip `System: [timestamp] …` lines and `[System Message]` prefixes the
223
+ * runtime prepends to a user turn as agent context. They are not user text.
224
+ */
225
+ function stripSystemPrefixes(text) {
226
+ return text.split("\n").filter((line) => !/^System:\s*\[/.test(line) && !line.startsWith("[System Message]")).join("\n").replace(/^\n+/, "");
227
+ }
228
+ /** Lift `<thinking>…</thinking>` out of plain text. */
229
+ function separateThinking(text) {
230
+ const match = text.match(/<thinking>([\s\S]*?)<\/thinking>/);
231
+ if (!match?.[1]) return { mainText: text };
232
+ const thinkingText = match[1].trim();
233
+ const mainText = text.replace(/<thinking>[\s\S]*?<\/thinking>\s*/, "").trim();
234
+ return {
235
+ ...thinkingText ? { thinkingText } : {},
236
+ mainText
237
+ };
238
+ }
239
+ function parseOneHistoryMessage(raw) {
240
+ const msg = raw;
241
+ const content = msg.content;
242
+ let text = Array.isArray(content) ? content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("") : typeof msg.content === "string" ? msg.content : typeof msg.text === "string" ? msg.text : "";
243
+ const isToolMessage = isToolRelatedMessage(msg);
244
+ const role = msg.role === "user" ? "user" : "assistant";
245
+ if (role === "user") text = stripSystemPrefixes(text);
246
+ let thinkingText = "";
247
+ if (typeof msg.thinking === "string" && msg.thinking.trim()) thinkingText = msg.thinking.trim();
248
+ else if (Array.isArray(content)) thinkingText = content.filter((c) => c.type === "thinking").map((c) => c.thinking ?? c.text ?? "").filter(Boolean).join("\n\n");
249
+ if (!thinkingText) {
250
+ const { thinkingText: tagThinking, mainText } = separateThinking(text);
251
+ if (tagThinking) return {
252
+ id: typeof msg.id === "string" ? msg.id : generateId(),
253
+ role,
254
+ text: mainText,
255
+ timestamp: msg.timestamp ?? Date.now(),
256
+ thinkingText: tagThinking,
257
+ ...isToolMessage ? { isToolMessage } : {}
258
+ };
259
+ }
260
+ return {
261
+ id: typeof msg.id === "string" ? msg.id : generateId(),
262
+ role,
263
+ text,
264
+ timestamp: msg.timestamp ?? Date.now(),
265
+ ...thinkingText ? { thinkingText } : {},
266
+ ...isToolMessage ? { isToolMessage } : {}
267
+ };
268
+ }
269
+ /**
270
+ * Merge an agent turn — assistant messages plus tool call and result messages —
271
+ * into one visible message. Everything except the final substantive response is
272
+ * folded into the chain of thought. Only a genuine user message breaks the turn.
273
+ */
274
+ function mergeConsecutiveAssistantMessages(messages) {
275
+ const result = [];
276
+ let run = [];
277
+ const flush = () => {
278
+ const first = run[0];
279
+ if (!first) return;
280
+ if (run.length === 1) {
281
+ result.push(first);
282
+ run = [];
283
+ return;
284
+ }
285
+ let visibleIdx = run.length - 1;
286
+ while (visibleIdx > 0 && !(run[visibleIdx]?.text ?? "").trim()) visibleIdx--;
287
+ const visible = run[visibleIdx] ?? first;
288
+ const cot = [];
289
+ for (let i = 0; i < run.length; i++) {
290
+ const entry = run[i];
291
+ if (!entry) continue;
292
+ if (i === visibleIdx) {
293
+ if (visible.thinkingText) cot.push(visible.thinkingText);
294
+ continue;
295
+ }
296
+ if (entry.thinkingText) cot.push(entry.thinkingText);
297
+ if (entry.text.trim()) cot.push(entry.text.trim());
298
+ }
299
+ const combined = cot.filter(Boolean).join("\n\n");
300
+ result.push({
301
+ ...visible,
302
+ ...combined ? { thinkingText: combined } : {}
303
+ });
304
+ run = [];
305
+ };
306
+ for (const msg of messages) if (msg.role === "user" && !msg.isToolMessage && msg.text.trim().length > 0) {
307
+ flush();
308
+ result.push(msg);
309
+ } else run.push(msg);
310
+ flush();
311
+ return result;
312
+ }
313
+ /** Raw transcript records to the messages the list renders. */
314
+ function parseHistoryMessages(raw) {
315
+ return mergeConsecutiveAssistantMessages(raw.map(parseOneHistoryMessage));
316
+ }
317
+ /**
318
+ * The history shrink guard.
319
+ *
320
+ * A history load must not shrink the session already on screen. The first
321
+ * message of a new chat loads history while the turn is still in flight and the
322
+ * user's message has not been persisted yet; replacing wholesale threw that
323
+ * message away, and the reply survived, so the symptom was a conversation with
324
+ * the answer but not the question.
325
+ *
326
+ * Only the same session, and only against losing messages: a longer or equal
327
+ * history still replaces, so an edit, a deletion made elsewhere and a compaction
328
+ * all land normally.
329
+ */
330
+ function wouldShrinkHistory(params) {
331
+ return params.currentSessionKey === params.loadedSessionKey && params.loadedCount < params.currentCount;
332
+ }
333
+ /** A JSON blob a tool or an extension API returned, echoed as a message. */
334
+ function isToolResult(text) {
335
+ const trimmed = text.trim();
336
+ if (!(trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("{") && trimmed.endsWith("}"))) return false;
337
+ try {
338
+ const parsed = JSON.parse(trimmed);
339
+ return typeof parsed === "object" && parsed !== null;
340
+ } catch {
341
+ return false;
342
+ }
343
+ }
344
+ /** Raw skill-file content the model echoed instead of acting on. */
345
+ function isSkillContent(text) {
346
+ const trimmed = text.trim();
347
+ return /^name:\s*\S+.*\bdescription:.*\btype:\s*skill\b/i.test(trimmed) || /^---\s*\n[\s\S]*?\btype:\s*skill\b[\s\S]*?\n---/m.test(trimmed);
348
+ }
349
+ /** Runtime diagnostics: token counters, a leaked api-key hint. */
350
+ function isAgentDiagnostics(text) {
351
+ const trimmed = text.trim();
352
+ return /Tokens:\s*\d+.*Cache:.*Context:/s.test(trimmed) || /\bapi-key\s+sk-/.test(trimmed);
353
+ }
354
+ /** Tool execution output that leaked into history as its own message. */
355
+ function isToolOutput(text) {
356
+ const trimmed = text.trim();
357
+ if (!trimmed) return false;
358
+ if (/^Tool\s+\S+\s+not found$/i.test(trimmed)) return true;
359
+ if (trimmed === "(no output)") return true;
360
+ if (/^total\s+\d+\s+[d-][rwx-]{9}/.test(trimmed)) return true;
361
+ if (/^[d-][rwx-]{9}[@+]?\s+\d+\s+\S+\s+\S+/.test(trimmed)) return true;
362
+ if (/(?:^|\n)[A-Z_]{2,}=\S/m.test(trimmed)) {
363
+ if (/\b(?:PATH|PWD|HOME|USER|INIT_CWD|PNPM_|NODE_|npm_|CORTENA_|CORTENACORE_|CORTENABOT_)/m.test(trimmed)) return true;
364
+ if ((trimmed.match(/(?:^|\n)[A-Z_]{3,}=\S/gm) ?? []).length >= 3) return true;
365
+ }
366
+ return false;
367
+ }
368
+ /**
369
+ * Should this message be hidden?
370
+ *
371
+ * The same chain cortenaweb's bubble applies, in the same order. It exists
372
+ * because tool plumbing leaks into a transcript in several recognisable shapes,
373
+ * and a chat that renders them reads as broken. Tool detail is not lost: it is
374
+ * in the tool strip and in the chain of thought.
375
+ *
376
+ * A reply that is only UI the agent drew has no text at all, so an A2UI block
377
+ * counts as content — without that, the surface the user asked for is filtered
378
+ * away and nothing appears.
379
+ */
380
+ function isHiddenMessage(message) {
381
+ if (message.isError) return false;
382
+ if (message.isToolMessage) return true;
383
+ if (message.role === "assistant" && !message.text.trim() && !message.thinkingText && !message.a2ui?.length) return true;
384
+ if (message.role === "user") return !message.text.trim() && !message.attachments?.length;
385
+ const text = message.text;
386
+ return isToolResult(text) || isSkillContent(text) || isAgentDiagnostics(text) || isToolOutput(text);
387
+ }
388
+ //#endregion
389
+ export { STEP_LIMIT, isHiddenMessage, isProvisionalSessionKey, isSessionOfAgent, mintSessionKey, parseHistoryMessages, readStoredSessionKey, readStoredSteps, separateThinking, serialiseSteps, sessionStorageKey, stepsStorageKey, viewStorageKey, windowSessionStorage, wouldShrinkHistory, writeStoredSessionKey, writeStoredSteps };
390
+
391
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../src/agent-chat/session.ts"],"sourcesContent":["/**\n * Sessions, history and the filter chain.\n *\n * Ported from `cortena-shared/src/stores/use-chat.ts` and\n * `cortenaweb/components/chat/message-bubble.tsx` (Cortena monorepo).\n * `cortena-shared` is not published, so the rules the two transports share\n * live here; keep them in step.\n *\n * The one deliberate difference is where the current session key is kept.\n * cortenaweb puts it in `localStorage`, which is shared by every tab of an\n * origin, so a second window adopted the first window's session: it inherited\n * a stream that was not its own and both windows then showed the same content.\n * Sessions here are **per window** — the key lives in `sessionStorage`, under a\n * name scoped to the extension — so opening the extension twice starts two\n * sessions. Both stay listed and either window can resume either one; two\n * windows on one session may both send, and cortenacore serialises the runs.\n */\n\nimport { truncate } from \"./step-label\";\nimport type { AgentChatMessage, AgentChatStep } from \"./types\";\n\n/* ── minting and remembering a key ───────────────────────────────────────── */\n\n/**\n * A new session key, minted client-side.\n *\n * `agent:<agentId>:new-<Date.now()>-<random36>`. cortenacore reads the\n * `agent:<id>:` prefix to bind the session to that agent's template, and the\n * key is the AG-UI `threadId` verbatim, prefix included. Minting it rather than\n * asking for one is what lets the first message go out immediately.\n */\nexport function mintSessionKey(agentId: string): string {\n return `agent:${agentId}:new-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n}\n\n/** Was this key minted locally for a chat that had no session yet? */\nexport function isProvisionalSessionKey(key: string): boolean {\n return /(^|:)new-\\d+-[a-z0-9]+$/.test(key);\n}\n\n/** Does this session belong to this agent? `sessions.list` is filtered by it. */\nexport function isSessionOfAgent(key: string, agentId: string): boolean {\n return key.startsWith(`agent:${agentId}:`);\n}\n\n/** The `sessionStorage` name the current key is kept under, per extension. */\nexport function sessionStorageKey(scope: string): string {\n return `cortena.agent-chat.${scope}.session`;\n}\n\n/** The `sessionStorage` name the open/collapsed state is kept under. */\nexport function viewStorageKey(scope: string): string {\n return `cortena.agent-chat.${scope}.view`;\n}\n\n/** The `sessionStorage` name this window's progress steps are kept under. */\nexport function stepsStorageKey(scope: string): string {\n return `cortena.agent-chat.${scope}.steps`;\n}\n\n/**\n * `sessionStorage`, or nothing.\n *\n * Absent during SSR and refused outright when a browser blocks storage for the\n * origin, and neither is a reason for the chat not to work: without it a window\n * simply forgets its session on reload.\n */\nexport function windowSessionStorage(): Storage | null {\n try {\n return typeof window === \"undefined\" ? null : window.sessionStorage;\n } catch {\n return null;\n }\n}\n\nexport function readStoredSessionKey(scope: string): string | null {\n try {\n return windowSessionStorage()?.getItem(sessionStorageKey(scope)) ?? null;\n } catch {\n return null;\n }\n}\n\nexport function writeStoredSessionKey(scope: string, key: string | null): void {\n try {\n const storage = windowSessionStorage();\n if (!storage) {\n return;\n }\n if (key === null) {\n storage.removeItem(sessionStorageKey(scope));\n } else {\n storage.setItem(sessionStorageKey(scope), key);\n }\n } catch {\n // A blocked storage is not a reason to lose the run in flight.\n }\n}\n\n/* ── the progress steps of the turn ──────────────────────────────────────── */\n\n/** Most steps kept, in memory and in `sessionStorage`. A turn that long is a runaway loop. */\nexport const STEP_LIMIT = 50;\n\n/**\n * Most bytes the steps slot may occupy.\n *\n * `sessionStorage` is a few megabytes for the whole origin, shared with\n * everything else the host keeps there, and a step count alone does not bound\n * the size: fifty steps whose labels are all near the limit, with a failure\n * message on each, is a slot nobody budgeted for. Over the cap the OLDEST are\n * dropped, one at a time, because the recent ones are the ones a reload has to\n * bring back.\n */\nconst STEP_BYTE_LIMIT = 64 * 1024;\n\n/** Longest tool call id or tool name kept, in storage and on `data-tool`. */\nexport const STORED_TEXT_LIMIT = 80;\n\n/**\n * The steps of the current turn, and the session they belong to.\n *\n * They go in the per-window store beside the session key, for the same reason\n * the key does: a tab is reloaded mid-run, or a host remounts the surface on a\n * route change, and both threw the whole strip away. (Collapsing the pop-up is\n * NOT one of them — the panel is `hidden`, not unmounted, and the run streams\n * into it either way.) Messages come back from `chat.history`; steps do not\n * exist on the server, so this is the only place they can come back from.\n *\n * Scoped to a session key, and checked on read: resuming a different session\n * must not inherit the last one's steps.\n */\nexport function readStoredSteps(scope: string, sessionKey: string): AgentChatStep[] {\n try {\n const raw = windowSessionStorage()?.getItem(stepsStorageKey(scope));\n if (!raw) {\n return [];\n }\n const parsed = JSON.parse(raw) as { sessionKey?: unknown; steps?: unknown };\n if (parsed?.sessionKey !== sessionKey || !Array.isArray(parsed.steps)) {\n return [];\n }\n return (parsed.steps as AgentChatStep[])\n .filter((step) => typeof step?.id === \"string\" && typeof step?.label === \"string\")\n .map(restoreStep)\n .slice(-STEP_LIMIT);\n } catch {\n // Storage refused, or somebody else wrote the slot. Neither is worth a\n // broken chat; the strip simply starts empty.\n return [];\n }\n}\n\n/** Every status a step may legitimately come back with. */\nconst STEP_STATUSES: ReadonlySet<string> = new Set([\n \"running\",\n \"done\",\n \"error\",\n \"stopped\",\n \"paused\",\n]);\n\n/**\n * A step as it comes back from storage.\n *\n * The important cases are `running` and `paused`. Neither is true any more:\n * the run that owned the call ended when the surface went away — a reload, a\n * remount on a route change; a collapsed pop-up only HIDES the strip and never\n * reaches this path — and no result will arrive for it now, so a restored\n * spinner spins until the user gives up and reloads again, which restores it.\n *\n * It comes back `stopped`, with no message. Neutral is the honest reading:\n * nothing failed, the work simply did not continue, and \"Interrupted.\" drawn in\n * the failure colour told the user their call had broken when the page had.\n *\n * An unrecognised status is treated the same way. Nothing else writes this\n * slot today, but it is per-origin `sessionStorage` and this is the only place\n * that decides what a strip is allowed to render.\n */\nfunction restoreStep(step: AgentChatStep): AgentChatStep {\n const known = STEP_STATUSES.has(step.status);\n if (known && step.status !== \"running\" && step.status !== \"paused\") {\n return step;\n }\n const restored: AgentChatStep = {\n ...step,\n status: \"stopped\",\n endedAt: step.endedAt ?? Date.now(),\n };\n delete restored.errorMessage;\n return restored;\n}\n\n/**\n * The fields of a step that are safe to keep, and the only ones kept.\n *\n * `args` is deliberately absent. A tool call's arguments are the user's data —\n * what they searched for, whose record they opened, the body of what they\n * wrote — and `sessionStorage` is readable by every script on the origin,\n * survives the run, and is the sort of thing that ends up in a support bundle.\n * Nothing on screen needs them after the run: the LABEL is already derived\n * from them, and the label is what a restored strip shows.\n */\nfunction storedStep(step: AgentChatStep): AgentChatStep {\n return {\n // Bounded, both of them. Neither is written by this package: the id is the\n // producer's `toolCallId` and the name is whatever the model called, so a\n // single call carrying 9 kB of either filled the byte cap on its own and\n // pushed every real step out of the slot.\n id: truncate(step.id, STORED_TEXT_LIMIT),\n toolName: truncate(step.toolName, STORED_TEXT_LIMIT),\n label: step.label,\n status: step.status,\n startedAt: step.startedAt,\n ...(step.endedAt === undefined ? {} : { endedAt: step.endedAt }),\n ...(step.errorMessage === undefined ? {} : { errorMessage: step.errorMessage }),\n };\n}\n\n/** The slot's contents, projected and trimmed to fit the byte cap. */\nexport function serialiseSteps(sessionKey: string, steps: readonly AgentChatStep[]): string {\n let kept = steps.slice(-STEP_LIMIT).map(storedStep);\n let json = JSON.stringify({ sessionKey, steps: kept });\n while (kept.length > 1 && json.length > STEP_BYTE_LIMIT) {\n kept = kept.slice(1);\n json = JSON.stringify({ sessionKey, steps: kept });\n }\n return json;\n}\n\nexport function writeStoredSteps(\n scope: string,\n sessionKey: string | null,\n steps: readonly AgentChatStep[],\n): void {\n try {\n const storage = windowSessionStorage();\n if (!storage) {\n return;\n }\n if (!sessionKey || steps.length === 0) {\n storage.removeItem(stepsStorageKey(scope));\n return;\n }\n storage.setItem(stepsStorageKey(scope), serialiseSteps(sessionKey, steps));\n } catch {\n // Blocked, or over quota. The run in flight is not worth losing over it.\n }\n}\n\n/* ── history ─────────────────────────────────────────────────────────────── */\n\nfunction generateId(): string {\n return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction isToolRelatedMessage(msg: Record<string, unknown>): boolean {\n const role = typeof msg.role === \"string\" ? msg.role.toLowerCase() : \"\";\n if (role === \"tool\" || role === \"toolresult\" || role === \"tool_result\") {\n return true;\n }\n const content = msg.content as Array<{ type: string }> | undefined;\n if (Array.isArray(content) && content.length > 0) {\n const toolTypes = new Set([\n \"tool_use\",\n \"tool_call\",\n \"tool_result\",\n \"toolresult\",\n \"server_tool_use\",\n ]);\n const hasText = content.some((c) => c.type === \"text\" || c.type === \"thinking\");\n const hasToolBlocks = content.some((c) => toolTypes.has(c.type));\n if (hasToolBlocks && !hasText) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Strip `System: [timestamp] …` lines and `[System Message]` prefixes the\n * runtime prepends to a user turn as agent context. They are not user text.\n */\nfunction stripSystemPrefixes(text: string): string {\n return text\n .split(\"\\n\")\n .filter((line) => !/^System:\\s*\\[/.test(line) && !line.startsWith(\"[System Message]\"))\n .join(\"\\n\")\n .replace(/^\\n+/, \"\");\n}\n\n/** Lift `<thinking>…</thinking>` out of plain text. */\nexport function separateThinking(text: string): { thinkingText?: string; mainText: string } {\n const match = text.match(/<thinking>([\\s\\S]*?)<\\/thinking>/);\n if (!match?.[1]) {\n return { mainText: text };\n }\n const thinkingText = match[1].trim();\n const mainText = text.replace(/<thinking>[\\s\\S]*?<\\/thinking>\\s*/, \"\").trim();\n return { ...(thinkingText ? { thinkingText } : {}), mainText };\n}\n\nfunction parseOneHistoryMessage(raw: unknown): AgentChatMessage {\n const msg = raw as Record<string, unknown>;\n const content = msg.content as\n | Array<{ type: string; text?: string; thinking?: string; a2ui?: unknown }>\n | undefined;\n let text = Array.isArray(content)\n ? content\n .filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text!)\n .join(\"\")\n : typeof msg.content === \"string\"\n ? msg.content\n : typeof msg.text === \"string\"\n ? msg.text\n : \"\";\n\n const isToolMessage = isToolRelatedMessage(msg);\n const role = ((msg.role as string) === \"user\" ? \"user\" : \"assistant\") as \"user\" | \"assistant\";\n if (role === \"user\") {\n text = stripSystemPrefixes(text);\n }\n\n let thinkingText = \"\";\n if (typeof msg.thinking === \"string\" && msg.thinking.trim()) {\n thinkingText = msg.thinking.trim();\n } else if (Array.isArray(content)) {\n thinkingText = content\n .filter((c) => c.type === \"thinking\")\n .map((c) => c.thinking ?? c.text ?? \"\")\n .filter(Boolean)\n .join(\"\\n\\n\");\n }\n if (!thinkingText) {\n const { thinkingText: tagThinking, mainText } = separateThinking(text);\n if (tagThinking) {\n return {\n id: typeof msg.id === \"string\" ? msg.id : generateId(),\n role,\n text: mainText,\n timestamp: (msg.timestamp as number) ?? Date.now(),\n thinkingText: tagThinking,\n ...(isToolMessage ? { isToolMessage } : {}),\n };\n }\n }\n\n return {\n id: typeof msg.id === \"string\" ? msg.id : generateId(),\n role,\n text,\n timestamp: (msg.timestamp as number) ?? Date.now(),\n ...(thinkingText ? { thinkingText } : {}),\n ...(isToolMessage ? { isToolMessage } : {}),\n };\n}\n\n/**\n * Merge an agent turn — assistant messages plus tool call and result messages —\n * into one visible message. Everything except the final substantive response is\n * folded into the chain of thought. Only a genuine user message breaks the turn.\n */\nfunction mergeConsecutiveAssistantMessages(messages: AgentChatMessage[]): AgentChatMessage[] {\n const result: AgentChatMessage[] = [];\n let run: AgentChatMessage[] = [];\n\n const flush = () => {\n const first = run[0];\n if (!first) {\n return;\n }\n if (run.length === 1) {\n result.push(first);\n run = [];\n return;\n }\n let visibleIdx = run.length - 1;\n while (visibleIdx > 0 && !(run[visibleIdx]?.text ?? \"\").trim()) {\n visibleIdx--;\n }\n const visible = run[visibleIdx] ?? first;\n const cot: string[] = [];\n for (let i = 0; i < run.length; i++) {\n const entry = run[i];\n if (!entry) {\n continue;\n }\n if (i === visibleIdx) {\n if (visible.thinkingText) {\n cot.push(visible.thinkingText);\n }\n continue;\n }\n if (entry.thinkingText) {\n cot.push(entry.thinkingText);\n }\n if (entry.text.trim()) {\n cot.push(entry.text.trim());\n }\n }\n const combined = cot.filter(Boolean).join(\"\\n\\n\");\n result.push({ ...visible, ...(combined ? { thinkingText: combined } : {}) });\n run = [];\n };\n\n for (const msg of messages) {\n const isRealUser = msg.role === \"user\" && !msg.isToolMessage && msg.text.trim().length > 0;\n if (isRealUser) {\n flush();\n result.push(msg);\n } else {\n run.push(msg);\n }\n }\n flush();\n return result;\n}\n\n/** Raw transcript records to the messages the list renders. */\nexport function parseHistoryMessages(raw: readonly unknown[]): AgentChatMessage[] {\n return mergeConsecutiveAssistantMessages(raw.map(parseOneHistoryMessage));\n}\n\n/**\n * The history shrink guard.\n *\n * A history load must not shrink the session already on screen. The first\n * message of a new chat loads history while the turn is still in flight and the\n * user's message has not been persisted yet; replacing wholesale threw that\n * message away, and the reply survived, so the symptom was a conversation with\n * the answer but not the question.\n *\n * Only the same session, and only against losing messages: a longer or equal\n * history still replaces, so an edit, a deletion made elsewhere and a compaction\n * all land normally.\n */\nexport function wouldShrinkHistory(params: {\n currentSessionKey: string | null;\n loadedSessionKey: string;\n currentCount: number;\n loadedCount: number;\n}): boolean {\n return (\n params.currentSessionKey === params.loadedSessionKey &&\n params.loadedCount < params.currentCount\n );\n}\n\n/* ── the filter chain ────────────────────────────────────────────────────── */\n\n/** A JSON blob a tool or an extension API returned, echoed as a message. */\nfunction isToolResult(text: string): boolean {\n const trimmed = text.trim();\n const wrapped =\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"));\n if (!wrapped) {\n return false;\n }\n try {\n const parsed = JSON.parse(trimmed);\n return typeof parsed === \"object\" && parsed !== null;\n } catch {\n return false;\n }\n}\n\n/** Raw skill-file content the model echoed instead of acting on. */\nfunction isSkillContent(text: string): boolean {\n const trimmed = text.trim();\n return (\n /^name:\\s*\\S+.*\\bdescription:.*\\btype:\\s*skill\\b/i.test(trimmed) ||\n /^---\\s*\\n[\\s\\S]*?\\btype:\\s*skill\\b[\\s\\S]*?\\n---/m.test(trimmed)\n );\n}\n\n/** Runtime diagnostics: token counters, a leaked api-key hint. */\nfunction isAgentDiagnostics(text: string): boolean {\n const trimmed = text.trim();\n return /Tokens:\\s*\\d+.*Cache:.*Context:/s.test(trimmed) || /\\bapi-key\\s+sk-/.test(trimmed);\n}\n\n/** Tool execution output that leaked into history as its own message. */\nfunction isToolOutput(text: string): boolean {\n const trimmed = text.trim();\n if (!trimmed) {\n return false;\n }\n if (/^Tool\\s+\\S+\\s+not found$/i.test(trimmed)) {\n return true;\n }\n if (trimmed === \"(no output)\") {\n return true;\n }\n if (/^total\\s+\\d+\\s+[d-][rwx-]{9}/.test(trimmed)) {\n return true;\n }\n if (/^[d-][rwx-]{9}[@+]?\\s+\\d+\\s+\\S+\\s+\\S+/.test(trimmed)) {\n return true;\n }\n if (/(?:^|\\n)[A-Z_]{2,}=\\S/m.test(trimmed)) {\n if (\n /\\b(?:PATH|PWD|HOME|USER|INIT_CWD|PNPM_|NODE_|npm_|CORTENA_|CORTENACORE_|CORTENABOT_)/m.test(\n trimmed,\n )\n ) {\n return true;\n }\n if ((trimmed.match(/(?:^|\\n)[A-Z_]{3,}=\\S/gm) ?? []).length >= 3) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Should this message be hidden?\n *\n * The same chain cortenaweb's bubble applies, in the same order. It exists\n * because tool plumbing leaks into a transcript in several recognisable shapes,\n * and a chat that renders them reads as broken. Tool detail is not lost: it is\n * in the tool strip and in the chain of thought.\n *\n * A reply that is only UI the agent drew has no text at all, so an A2UI block\n * counts as content — without that, the surface the user asked for is filtered\n * away and nothing appears.\n */\nexport function isHiddenMessage(message: AgentChatMessage): boolean {\n if (message.isError) {\n return false;\n }\n if (message.isToolMessage) {\n return true;\n }\n if (\n message.role === \"assistant\" &&\n !message.text.trim() &&\n !message.thinkingText &&\n !message.a2ui?.length\n ) {\n return true;\n }\n if (message.role === \"user\") {\n return !message.text.trim() && !message.attachments?.length;\n }\n const text = message.text;\n return isToolResult(text) || isSkillContent(text) || isAgentDiagnostics(text) || isToolOutput(text);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eAAe,SAAyB;CACtD,OAAO,SAAS,QAAQ,OAAO,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;AACpF;;AAGA,SAAgB,wBAAwB,KAAsB;CAC5D,OAAO,0BAA0B,KAAK,GAAG;AAC3C;;AAGA,SAAgB,iBAAiB,KAAa,SAA0B;CACtE,OAAO,IAAI,WAAW,SAAS,QAAQ,EAAE;AAC3C;;AAGA,SAAgB,kBAAkB,OAAuB;CACvD,OAAO,sBAAsB,MAAM;AACrC;;AAGA,SAAgB,eAAe,OAAuB;CACpD,OAAO,sBAAsB,MAAM;AACrC;;AAGA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,sBAAsB,MAAM;AACrC;;;;;;;;AASA,SAAgB,uBAAuC;CACrD,IAAI;EACF,OAAO,OAAO,WAAW,cAAc,OAAO,OAAO;CACvD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,qBAAqB,OAA8B;CACjE,IAAI;EACF,OAAO,qBAAqB,CAAC,EAAE,QAAQ,kBAAkB,KAAK,CAAC,KAAK;CACtE,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,sBAAsB,OAAe,KAA0B;CAC7E,IAAI;EACF,MAAM,UAAU,qBAAqB;EACrC,IAAI,CAAC,SACH;EAEF,IAAI,QAAQ,MACV,QAAQ,WAAW,kBAAkB,KAAK,CAAC;OAE3C,QAAQ,QAAQ,kBAAkB,KAAK,GAAG,GAAG;CAEjD,QAAQ,CAER;AACF;;AAKA,MAAa,aAAa;;;;;;;;;;;AAY1B,MAAM,kBAAkB;;;;;;;;;;;;;;AAkBxB,SAAgB,gBAAgB,OAAe,YAAqC;CAClF,IAAI;EACF,MAAM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BAAyB,KAAK,CAAC,EAAA,CAAG,UAAU,GAC7D,OAAO;CAEX;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,SAAoC;CAClE,IAAI,QAAQ,SACV,OAAO;CAET,IAAI,QAAQ,eACV,OAAO;CAET,IACE,QAAQ,SAAS,eACjB,CAAC,QAAQ,KAAK,KAAK,KACnB,CAAC,QAAQ,gBACT,CAAC,QAAQ,MAAM,QAEf,OAAO;CAET,IAAI,QAAQ,SAAS,QACnB,OAAO,CAAC,QAAQ,KAAK,KAAK,KAAK,CAAC,QAAQ,aAAa;CAEvD,MAAM,OAAO,QAAQ;CACrB,OAAO,aAAa,IAAI,KAAK,eAAe,IAAI,KAAK,mBAAmB,IAAI,KAAK,aAAa,IAAI;AACpG"}
@@ -0,0 +1,99 @@
1
+ "use client";
2
+ //#region src/agent-chat/step-label.d.ts
3
+ /**
4
+ * The wording map: one plain sentence per tool call (SKILLS-9).
5
+ *
6
+ * A run is a sequence of tool calls, and what the user sees of it today is a
7
+ * tool name and a JSON blob. `engram_describe {"id":"tasks.task.list"}` is an
8
+ * accurate description of nothing anybody asked for. This module turns the
9
+ * three native tools — `engram_search`, `engram_describe`, `broker_invoke` —
10
+ * into sentences a person can read while they wait.
11
+ *
12
+ * It is a pure function of the tool name and the arguments, in its own module,
13
+ * for two reasons. It is the part most likely to be edited by someone who is
14
+ * not editing the store, and it is the part worth testing exhaustively: the
15
+ * store's job is start/end pairing, and the wording's job is being readable.
16
+ *
17
+ * Deliberately NOT here: anything that needs the result. The client cannot know
18
+ * whether a `broker_invoke` is a read or a write before the reply comes back —
19
+ * only the catalogue knows, and the model only carries `confirmed` once the
20
+ * user has said yes — so an unconfirmed invoke is worded "Fetching …", which is
21
+ * true of a read and harmless of a write that has not happened yet. The one
22
+ * result-dependent wording, a 409 `confirmation_required`, is
23
+ * `confirmationRequiredLabel` and the store applies it when the envelope
24
+ * arrives.
25
+ */
26
+ /**
27
+ * Which end of the step the label is for.
28
+ *
29
+ * Nearly every sentence reads the same either way, because it describes the
30
+ * step rather than claiming an outcome — "Reading skill: alerts" is as true of
31
+ * a finished read as of one in flight, and rewriting it on completion makes the
32
+ * strip jump under the reader's eye for no gain. The exception is the confirmed
33
+ * write, where "Doing: tasks task create" and "Done: tasks task create" are
34
+ * genuinely different facts and the user needs the second one.
35
+ */
36
+ export type AgentStepPhase = "running" | "done";
37
+ /**
38
+ * An id as words: `tasks.task.list` -> "tasks task list".
39
+ *
40
+ * Deterministic and dumb on purpose. A cleverer mapping — reordering to "list
41
+ * tasks", pluralising, looking up a display name — needs a table that has to be
42
+ * maintained for every capability in every extension, and a table that is one
43
+ * release out of date reads worse than the id did.
44
+ */
45
+ export declare function humaniseId(id: string): string;
46
+ /**
47
+ * One line of it, sanitised and bounded, with the ellipsis inside the limit.
48
+ *
49
+ * Everything interpolated into a label goes through this, including the ones
50
+ * that look safe: a tool name, an operation id, a server's `message`. All three
51
+ * arrive from outside — a catalogue entry, a broker reply — and none is worth
52
+ * trusting with the length of a line or with the direction of it. Control and
53
+ * format characters are stripped BEFORE the length check, so a run of
54
+ * invisibles cannot eat the budget and a U+202E cannot flip the rest of the
55
+ * strip right-to-left. Newlines have already become spaces by then, so the
56
+ * strip does not silently join two words.
57
+ */
58
+ export declare function truncate(text: string, limit?: number): string;
59
+ /**
60
+ * The line for a call nothing better can be said about yet.
61
+ *
62
+ * Its own function because two other places have to RECOGNISE it: the store
63
+ * re-words a step that finished on this line if its arguments turn up late, and
64
+ * the strip holds it out of the live region rather than announcing
65
+ * "Working: broker_invoke" to a screen reader a moment before the real sentence
66
+ * replaces it.
67
+ */
68
+ export declare function genericLabel(toolName: string): string;
69
+ /** Is this label the fallback rather than something the arguments produced? */
70
+ export declare function isGenericLabel(toolName: string, label: string): boolean;
71
+ /**
72
+ * The line shown for one tool call.
73
+ *
74
+ * | tool | label |
75
+ * | --- | --- |
76
+ * | `engram_search` | Looking for a way to \<intent\> |
77
+ * | `engram_describe`, `skill.*` | Reading skill: \<title, or the topic\> |
78
+ * | `engram_describe`, anything else | Checking how to \<id as words\> |
79
+ * | `broker_invoke`, `confirmed: true` | Doing: \<operation\> / Done: \<operation\> |
80
+ * | `broker_invoke`, otherwise | Fetching \<operation\> |
81
+ * | anything else | Working: \<tool name\> |
82
+ *
83
+ * The key argument missing falls through to the last row rather than inventing
84
+ * a sentence about nothing: arguments arrive in a second event
85
+ * (`TOOL_CALL_ARGS`), so "no arguments yet" is a state every call passes
86
+ * through, and the generic line is what it should read as until they land.
87
+ */
88
+ export declare function stepLabel(toolName: string, args: Record<string, unknown> | undefined, phase: AgentStepPhase): string;
89
+ /**
90
+ * The label for a call the broker refused pending a yes.
91
+ *
92
+ * A 409 `confirmation_required` is not a failure — it is the broker doing its
93
+ * job on a write the user has not approved — so the step keeps its tick and
94
+ * changes its words. Drawn as an error it reads as "the agent broke"; drawn as
95
+ * "Fetching …", completed, it reads as though the write went through.
96
+ */
97
+ export declare function confirmationRequiredLabel(args: Record<string, unknown> | undefined): string;
98
+ //#endregion
99
+ //# sourceMappingURL=step-label.d.ts.map
@@ -0,0 +1,116 @@
1
+ "use client";
2
+ //#region src/agent-chat/step-label.ts
3
+ /** Longest intent or title carried into a label, ellipsis included. */
4
+ const TEXT_LIMIT = 80;
5
+ /**
6
+ * An id as words: `tasks.task.list` -> "tasks task list".
7
+ *
8
+ * Deterministic and dumb on purpose. A cleverer mapping — reordering to "list
9
+ * tasks", pluralising, looking up a display name — needs a table that has to be
10
+ * maintained for every capability in every extension, and a table that is one
11
+ * release out of date reads worse than the id did.
12
+ */
13
+ function humaniseId(id) {
14
+ return id.split(/[.\-_]+/).filter(Boolean).join(" ").toLowerCase();
15
+ }
16
+ /** The topic of a skill id: `skill.platform.using-extensions` -> "using extensions". */
17
+ function skillTopic(id) {
18
+ const parts = id.split(".").filter(Boolean);
19
+ const last = parts[parts.length - 1];
20
+ return last ? humaniseId(last) : humaniseId(id);
21
+ }
22
+ /**
23
+ * One line of it, sanitised and bounded, with the ellipsis inside the limit.
24
+ *
25
+ * Everything interpolated into a label goes through this, including the ones
26
+ * that look safe: a tool name, an operation id, a server's `message`. All three
27
+ * arrive from outside — a catalogue entry, a broker reply — and none is worth
28
+ * trusting with the length of a line or with the direction of it. Control and
29
+ * format characters are stripped BEFORE the length check, so a run of
30
+ * invisibles cannot eat the budget and a U+202E cannot flip the rest of the
31
+ * strip right-to-left. Newlines have already become spaces by then, so the
32
+ * strip does not silently join two words.
33
+ */
34
+ function truncate(text, limit = TEXT_LIMIT) {
35
+ const collapsed = text.replace(/\s+/g, " ").trim().replace(/[\p{Cf}\p{Cc}]/gu, "");
36
+ return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}…`;
37
+ }
38
+ /**
39
+ * The line for a call nothing better can be said about yet.
40
+ *
41
+ * Its own function because two other places have to RECOGNISE it: the store
42
+ * re-words a step that finished on this line if its arguments turn up late, and
43
+ * the strip holds it out of the live region rather than announcing
44
+ * "Working: broker_invoke" to a screen reader a moment before the real sentence
45
+ * replaces it.
46
+ */
47
+ function genericLabel(toolName) {
48
+ return `Working: ${truncate(toolName)}`;
49
+ }
50
+ /** Is this label the fallback rather than something the arguments produced? */
51
+ function isGenericLabel(toolName, label) {
52
+ return label === genericLabel(toolName);
53
+ }
54
+ function readString(args, key) {
55
+ const value = args?.[key];
56
+ return typeof value === "string" && value.trim() ? value : "";
57
+ }
58
+ /**
59
+ * The line shown for one tool call.
60
+ *
61
+ * | tool | label |
62
+ * | --- | --- |
63
+ * | `engram_search` | Looking for a way to \<intent\> |
64
+ * | `engram_describe`, `skill.*` | Reading skill: \<title, or the topic\> |
65
+ * | `engram_describe`, anything else | Checking how to \<id as words\> |
66
+ * | `broker_invoke`, `confirmed: true` | Doing: \<operation\> / Done: \<operation\> |
67
+ * | `broker_invoke`, otherwise | Fetching \<operation\> |
68
+ * | anything else | Working: \<tool name\> |
69
+ *
70
+ * The key argument missing falls through to the last row rather than inventing
71
+ * a sentence about nothing: arguments arrive in a second event
72
+ * (`TOOL_CALL_ARGS`), so "no arguments yet" is a state every call passes
73
+ * through, and the generic line is what it should read as until they land.
74
+ */
75
+ function stepLabel(toolName, args, phase) {
76
+ switch (toolName) {
77
+ case "engram_search": {
78
+ const intent = readString(args, "intent");
79
+ if (intent) return `Looking for a way to ${truncate(intent)}`;
80
+ break;
81
+ }
82
+ case "engram_describe": {
83
+ const id = readString(args, "id");
84
+ if (!id) break;
85
+ if (id.startsWith("skill.")) {
86
+ const title = readString(args, "title");
87
+ return `Reading skill: ${truncate(title ? title : skillTopic(id))}`;
88
+ }
89
+ return `Checking how to ${truncate(humaniseId(id))}`;
90
+ }
91
+ case "broker_invoke": {
92
+ const operation = readString(args, "operation");
93
+ if (!operation) break;
94
+ const label = truncate(humaniseId(operation));
95
+ if (args?.confirmed === true) return phase === "done" ? `Done: ${label}` : `Doing: ${label}`;
96
+ return `Fetching ${label}`;
97
+ }
98
+ }
99
+ return genericLabel(toolName);
100
+ }
101
+ /**
102
+ * The label for a call the broker refused pending a yes.
103
+ *
104
+ * A 409 `confirmation_required` is not a failure — it is the broker doing its
105
+ * job on a write the user has not approved — so the step keeps its tick and
106
+ * changes its words. Drawn as an error it reads as "the agent broke"; drawn as
107
+ * "Fetching …", completed, it reads as though the write went through.
108
+ */
109
+ function confirmationRequiredLabel(args) {
110
+ const operation = readString(args, "operation");
111
+ return `Needs your confirmation: ${operation ? truncate(humaniseId(operation)) : "that action"}`;
112
+ }
113
+ //#endregion
114
+ export { confirmationRequiredLabel, genericLabel, humaniseId, isGenericLabel, stepLabel, truncate };
115
+
116
+ //# sourceMappingURL=step-label.js.map