@letta-ai/letta-code 0.34.72 → 0.34.73-app-server.1

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 (151) hide show
  1. package/dist/mcp-client.js +2 -2
  2. package/dist/mcp-client.js.map +1 -1
  3. package/dist/mcp-oauth.js +2 -2
  4. package/dist/mcp-oauth.js.map +1 -1
  5. package/dist/schedules.js +19 -5
  6. package/dist/schedules.js.map +5 -4
  7. package/dist/types/agent/message.d.ts.map +1 -1
  8. package/dist/types/agent/modify.d.ts.map +1 -1
  9. package/dist/types/agent/preloaded-skills.d.ts +4 -1
  10. package/dist/types/agent/preloaded-skills.d.ts.map +1 -1
  11. package/dist/types/agent/shared-memory-skills.d.ts.map +1 -1
  12. package/dist/types/agent/subagents/parent-transcript.d.ts.map +1 -1
  13. package/dist/types/backend/api/agents.d.ts +1 -0
  14. package/dist/types/backend/api/agents.d.ts.map +1 -1
  15. package/dist/types/cli/helpers/conversation-title.d.ts.map +1 -1
  16. package/dist/types/constants.d.ts +5 -0
  17. package/dist/types/constants.d.ts.map +1 -1
  18. package/dist/types/cron/scheduled-task-prompt.d.ts +2 -0
  19. package/dist/types/cron/scheduled-task-prompt.d.ts.map +1 -1
  20. package/dist/types/experiments/manager.d.ts.map +1 -1
  21. package/dist/types/experiments/types.d.ts +2 -1
  22. package/dist/types/experiments/types.d.ts.map +1 -1
  23. package/dist/types/headless-super-run-wait.d.ts.map +1 -1
  24. package/dist/types/helpers/usable-directory.d.ts +2 -2
  25. package/dist/types/helpers/usable-directory.d.ts.map +1 -1
  26. package/dist/types/helpers/working-directory.d.ts +1 -0
  27. package/dist/types/helpers/working-directory.d.ts.map +1 -1
  28. package/dist/types/mods/context.d.ts +1 -0
  29. package/dist/types/mods/context.d.ts.map +1 -1
  30. package/dist/types/permissions/loader.d.ts.map +1 -1
  31. package/dist/types/queue/turn-queue-runtime.d.ts +0 -4
  32. package/dist/types/queue/turn-queue-runtime.d.ts.map +1 -1
  33. package/dist/types/telemetry/index.d.ts +1 -22
  34. package/dist/types/telemetry/index.d.ts.map +1 -1
  35. package/dist/types/tools/external-tool-background.d.ts.map +1 -1
  36. package/dist/types/tools/impl/foreground-sleep.d.ts.map +1 -1
  37. package/dist/types/tools/impl/kill-bash.d.ts +1 -1
  38. package/dist/types/tools/impl/kill-bash.d.ts.map +1 -1
  39. package/dist/types/tools/impl/monitor-script.d.ts +1 -0
  40. package/dist/types/tools/impl/monitor-script.d.ts.map +1 -1
  41. package/dist/types/tools/impl/monitor.d.ts +1 -0
  42. package/dist/types/tools/impl/monitor.d.ts.map +1 -1
  43. package/dist/types/tools/impl/skill.d.ts.map +1 -1
  44. package/dist/types/tools/impl/watch-pr-cloud.d.ts +1 -0
  45. package/dist/types/tools/impl/watch-pr-cloud.d.ts.map +1 -1
  46. package/dist/types/tools/impl/watch-pr.d.ts +1 -0
  47. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  48. package/dist/types/tools/manager.d.ts +3 -5
  49. package/dist/types/tools/manager.d.ts.map +1 -1
  50. package/dist/types/tools/script-tool-scope.d.ts.map +1 -1
  51. package/dist/types/tools/workflow/sdk-spawner.d.ts.map +1 -1
  52. package/dist/types/types/agent-picker.d.ts +55 -0
  53. package/dist/types/types/agent-picker.d.ts.map +1 -0
  54. package/dist/types/types/background-process-protocol.d.ts +4 -0
  55. package/dist/types/types/background-process-protocol.d.ts.map +1 -1
  56. package/dist/types/types/list-memory-command.d.ts +9 -0
  57. package/dist/types/types/list-memory-command.d.ts.map +1 -0
  58. package/dist/types/types/protocol_v2.d.ts +8 -24
  59. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  60. package/dist/types/utils/task-notifications.d.ts +2 -0
  61. package/dist/types/utils/task-notifications.d.ts.map +1 -1
  62. package/dist/types/websocket/listener/background-process-snapshot.d.ts +1 -0
  63. package/dist/types/websocket/listener/background-process-snapshot.d.ts.map +1 -1
  64. package/dist/types/websocket/listener/cwd.d.ts.map +1 -1
  65. package/dist/types/websocket/listener/listener-constants.d.ts.map +1 -1
  66. package/dist/types/websocket/listener/protocol-outbound.d.ts +0 -1
  67. package/dist/types/websocket/listener/protocol-outbound.d.ts.map +1 -1
  68. package/dist/types/websocket/listener/types.d.ts +1 -0
  69. package/dist/types/websocket/listener/types.d.ts.map +1 -1
  70. package/letta.js +241422 -234880
  71. package/npm-shrinkwrap.json +52 -11
  72. package/package.json +2 -35
  73. package/scripts/isolated-unit-tests.json +0 -5
  74. package/scripts/source-file-size-baseline.json +9 -16
  75. package/scripts/unit-test-impact.test.cjs +2 -2
  76. package/dist/channels-public.js +0 -1964
  77. package/dist/channels-public.js.map +0 -20
  78. package/dist/channels-slack.js +0 -1784
  79. package/dist/channels-slack.js.map +0 -27
  80. package/dist/gateway-core.js +0 -3067
  81. package/dist/gateway-core.js.map +0 -19
  82. package/dist/types/channels/command-runtime-executor.d.ts +0 -125
  83. package/dist/types/channels/command-runtime-executor.d.ts.map +0 -1
  84. package/dist/types/channels/command-surface.d.ts +0 -42
  85. package/dist/types/channels/command-surface.d.ts.map +0 -1
  86. package/dist/types/channels/control-request-coordinator.d.ts +0 -42
  87. package/dist/types/channels/control-request-coordinator.d.ts.map +0 -1
  88. package/dist/types/channels/core-stream.d.ts +0 -35
  89. package/dist/types/channels/core-stream.d.ts.map +0 -1
  90. package/dist/types/channels/gateway-core.d.ts +0 -88
  91. package/dist/types/channels/gateway-core.d.ts.map +0 -1
  92. package/dist/types/channels/gateway-sources.d.ts +0 -6
  93. package/dist/types/channels/gateway-sources.d.ts.map +0 -1
  94. package/dist/types/channels/interactive.d.ts +0 -13
  95. package/dist/types/channels/interactive.d.ts.map +0 -1
  96. package/dist/types/channels/lifecycle-error.d.ts +0 -25
  97. package/dist/types/channels/lifecycle-error.d.ts.map +0 -1
  98. package/dist/types/channels/message-channel-executor.d.ts +0 -48
  99. package/dist/types/channels/message-channel-executor.d.ts.map +0 -1
  100. package/dist/types/channels/message-channel-formatting.d.ts +0 -6
  101. package/dist/types/channels/message-channel-formatting.d.ts.map +0 -1
  102. package/dist/types/channels/message-channel-idempotency.d.ts +0 -8
  103. package/dist/types/channels/message-channel-idempotency.d.ts.map +0 -1
  104. package/dist/types/channels/message-channel-tool-definition.d.ts +0 -37
  105. package/dist/types/channels/message-channel-tool-definition.d.ts.map +0 -1
  106. package/dist/types/channels/message-channel-types.d.ts +0 -46
  107. package/dist/types/channels/message-channel-types.d.ts.map +0 -1
  108. package/dist/types/channels/processor.d.ts +0 -27
  109. package/dist/types/channels/processor.d.ts.map +0 -1
  110. package/dist/types/channels/progress-builder.d.ts +0 -7
  111. package/dist/types/channels/progress-builder.d.ts.map +0 -1
  112. package/dist/types/channels/progress-formatting.d.ts +0 -27
  113. package/dist/types/channels/progress-formatting.d.ts.map +0 -1
  114. package/dist/types/channels/route-thread-key.d.ts +0 -4
  115. package/dist/types/channels/route-thread-key.d.ts.map +0 -1
  116. package/dist/types/channels/slack/attachment-primitives.d.ts +0 -55
  117. package/dist/types/channels/slack/attachment-primitives.d.ts.map +0 -1
  118. package/dist/types/channels/slack/bot-policy.d.ts +0 -25
  119. package/dist/types/channels/slack/bot-policy.d.ts.map +0 -1
  120. package/dist/types/channels/slack/ingress-policy.d.ts +0 -108
  121. package/dist/types/channels/slack/ingress-policy.d.ts.map +0 -1
  122. package/dist/types/channels/slack/internal-types.d.ts +0 -168
  123. package/dist/types/channels/slack/internal-types.d.ts.map +0 -1
  124. package/dist/types/channels/slack/message-action-contract.d.ts +0 -11
  125. package/dist/types/channels/slack/message-action-contract.d.ts.map +0 -1
  126. package/dist/types/channels/slack/model-picker-blocks.d.ts +0 -5
  127. package/dist/types/channels/slack/model-picker-blocks.d.ts.map +0 -1
  128. package/dist/types/channels/slack/presentation.d.ts +0 -18
  129. package/dist/types/channels/slack/presentation.d.ts.map +0 -1
  130. package/dist/types/channels/slack/progress.d.ts +0 -7
  131. package/dist/types/channels/slack/progress.d.ts.map +0 -1
  132. package/dist/types/channels/slack/public-utils.d.ts +0 -10
  133. package/dist/types/channels/slack/public-utils.d.ts.map +0 -1
  134. package/dist/types/channels/slack/sender.d.ts +0 -39
  135. package/dist/types/channels/slack/sender.d.ts.map +0 -1
  136. package/dist/types/channels/slack/status-controller.d.ts +0 -37
  137. package/dist/types/channels/slack/status-controller.d.ts.map +0 -1
  138. package/dist/types/channels/slack/user-mentions.d.ts +0 -10
  139. package/dist/types/channels/slack/user-mentions.d.ts.map +0 -1
  140. package/dist/types/channels/slack/utils.d.ts +0 -37
  141. package/dist/types/channels/slack/utils.d.ts.map +0 -1
  142. package/dist/types/channels/xml.d.ts +0 -6
  143. package/dist/types/channels/xml.d.ts.map +0 -1
  144. package/dist/types/channels-public.d.ts +0 -17
  145. package/dist/types/channels-public.d.ts.map +0 -1
  146. package/dist/types/channels-slack.d.ts +0 -17
  147. package/dist/types/channels-slack.d.ts.map +0 -1
  148. package/dist/types/gateway-core.d.ts +0 -12
  149. package/dist/types/gateway-core.d.ts.map +0 -1
  150. package/dist/types/websocket/listener/constants.d.ts +0 -26
  151. package/dist/types/websocket/listener/constants.d.ts.map +0 -1
@@ -1,1964 +0,0 @@
1
- // src/channels/command-surface.ts
2
- var DEFAULT_EXTRA_COMMANDS_LABEL = "Host commands";
3
- var DEFAULT_CHANNEL_DISPLAY_NAMES = {
4
- custom: "Custom",
5
- discord: "Discord",
6
- signal: "Signal",
7
- slack: "Slack",
8
- telegram: "Telegram",
9
- whatsapp: "WhatsApp"
10
- };
11
- function defaultChannelDisplayName(channelId) {
12
- return DEFAULT_CHANNEL_DISPLAY_NAMES[channelId] ?? channelId;
13
- }
14
- var CHANNEL_SLASH_COMMANDS = [
15
- {
16
- name: "help",
17
- kind: "direct",
18
- summary: "Show channel usage guidance."
19
- },
20
- {
21
- name: "status",
22
- kind: "direct",
23
- summary: "Show this chat's channel connection status."
24
- },
25
- {
26
- name: "whoami",
27
- kind: "direct",
28
- summary: "Show your access tier and runnable commands here."
29
- },
30
- {
31
- name: "pause",
32
- kind: "direct",
33
- summary: "Pause agent routing for this chat."
34
- },
35
- {
36
- name: "resume",
37
- kind: "direct",
38
- summary: "Resume agent routing for this chat."
39
- },
40
- {
41
- name: "cancel",
42
- kind: "agent-scoped",
43
- summary: "Cancel the in-progress agent turn for this chat."
44
- },
45
- {
46
- name: "chat",
47
- kind: "direct",
48
- summary: "Show the Letta web chat link for this channel route."
49
- },
50
- {
51
- name: "feedback",
52
- kind: "direct",
53
- summary: "Send feedback about Letta Code from this routed chat."
54
- },
55
- {
56
- name: "model",
57
- kind: "agent-scoped",
58
- summary: "Show, list, or switch the model for this chat's routed conversation."
59
- },
60
- {
61
- name: "reflection",
62
- aliases: ["reflect"],
63
- kind: "agent-scoped",
64
- summary: "Start a memory reflection pass for this conversation."
65
- },
66
- {
67
- name: "reload",
68
- kind: "agent-scoped",
69
- summary: "Reload settings, local mods, and agent secrets."
70
- }
71
- ];
72
- var SLACK_MENTION_COMMAND_NAMES = [
73
- "help",
74
- "detach",
75
- "model",
76
- "new",
77
- "reload"
78
- ];
79
- function copyDefinition(definition) {
80
- return {
81
- ...definition,
82
- aliases: definition.aliases ? [...definition.aliases] : undefined
83
- };
84
- }
85
- function dedupedExtraCommands(options) {
86
- const extras = options?.extraCommands;
87
- if (!extras || extras.length === 0) {
88
- return [];
89
- }
90
- const takenNames = new Set(SLACK_MENTION_COMMAND_NAMES);
91
- for (const definition of CHANNEL_SLASH_COMMANDS) {
92
- takenNames.add(definition.name.toLowerCase());
93
- for (const alias of definition.aliases ?? []) {
94
- takenNames.add(alias.toLowerCase());
95
- }
96
- }
97
- const surviving = [];
98
- for (const extra of extras) {
99
- const nameKey = extra.name.toLowerCase();
100
- if (takenNames.has(nameKey)) {
101
- continue;
102
- }
103
- takenNames.add(nameKey);
104
- const aliases = (extra.aliases ?? []).filter((alias) => {
105
- const aliasKey = alias.toLowerCase();
106
- if (takenNames.has(aliasKey)) {
107
- return false;
108
- }
109
- takenNames.add(aliasKey);
110
- return true;
111
- });
112
- surviving.push({
113
- ...extra,
114
- aliases: aliases.length > 0 ? aliases : undefined
115
- });
116
- }
117
- return surviving;
118
- }
119
- function listChannelSlashCommands(options) {
120
- return [
121
- ...CHANNEL_SLASH_COMMANDS.map(copyDefinition),
122
- ...dedupedExtraCommands(options)
123
- ];
124
- }
125
- function parseSingleLineChannelCommand(text, prefix) {
126
- const trimmed = text.trim();
127
- const escapedPrefix = prefix === "/" ? "\\/" : "!";
128
- const match = trimmed.match(new RegExp(`^${escapedPrefix}([A-Za-z][\\w-]*)(?:@[A-Za-z0-9_]+)?(?:[^\\S\\r\\n]+(.*))?$`));
129
- if (!match) {
130
- return null;
131
- }
132
- const [, name, args] = match;
133
- if (!name) {
134
- return null;
135
- }
136
- return {
137
- name: name.toLowerCase(),
138
- args: args?.trim() ?? "",
139
- raw: trimmed
140
- };
141
- }
142
- function parseAnySingleLineChannelCommand(text) {
143
- return parseSingleLineChannelCommand(text, "/") ?? parseSingleLineChannelCommand(text, "!");
144
- }
145
- function parseChannelCommand(text, prefix) {
146
- const lines = text.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
147
- const [firstLine, ...remainingLines] = lines;
148
- if (!firstLine) {
149
- return null;
150
- }
151
- const firstCommand = parseSingleLineChannelCommand(firstLine, prefix);
152
- if (!firstCommand) {
153
- return null;
154
- }
155
- const laterCommand = remainingLines.find((line) => Boolean(parseAnySingleLineChannelCommand(line)));
156
- if (laterCommand) {
157
- return firstCommand;
158
- }
159
- const continuationArgs = remainingLines.join(`
160
- `).trim();
161
- if (!continuationArgs) {
162
- return firstCommand;
163
- }
164
- return {
165
- ...firstCommand,
166
- args: [firstCommand.args, continuationArgs].filter((part) => part.length > 0).join(`
167
- `)
168
- };
169
- }
170
- function parseChannelSlashCommand(text) {
171
- return parseChannelCommand(text, "/");
172
- }
173
- function parseChannelBangCommand(text) {
174
- return parseChannelCommand(text, "!");
175
- }
176
- function supportedCommandsText(prefix = "/", options) {
177
- return listChannelSlashCommands(options).map((definition) => `${prefix}${definition.name}`).join(", ");
178
- }
179
- var SLACK_MENTION_SLASH_COMMAND_EXAMPLES = [
180
- "@agent /help",
181
- "@agent /status",
182
- "@agent /whoami",
183
- "@agent /model",
184
- "@agent /model list",
185
- "@agent /model <handle-or-id>",
186
- "@agent /cancel",
187
- "@agent /chat",
188
- "@agent /feedback <message>",
189
- "@agent /reflection",
190
- "@agent /detach",
191
- "@agent /new",
192
- "@agent /reload"
193
- ];
194
- function supportedSlackMentionSlashCommandsText(options) {
195
- const extras = dedupedExtraCommands(options).map((definition) => `@agent /${definition.name}`);
196
- return [...SLACK_MENTION_SLASH_COMMAND_EXAMPLES, ...extras].join(", ");
197
- }
198
- function supportedBangCommandsText() {
199
- return SLACK_MENTION_COMMAND_NAMES.map((name) => `!${name}`).join(", ");
200
- }
201
- function buildChannelHelpMessage(channelId, resolveDisplayName = defaultChannelDisplayName, options) {
202
- const displayName = resolveDisplayName(channelId);
203
- const extras = dedupedExtraCommands(options);
204
- const extrasLabel = options?.extraCommandsLabel ?? DEFAULT_EXTRA_COMMANDS_LABEL;
205
- if (channelId === "slack") {
206
- const extraLines = extras.length > 0 ? [
207
- `${extrasLabel}:`,
208
- ...extras.map((definition) => `@agent /${definition.name} - ${definition.summary}`)
209
- ] : [];
210
- return [
211
- `${displayName} is connected to Letta Code.`,
212
- "Talk by mentioning the app in a channel thread. Once a thread is routed, normal replies continue the same agent conversation until detached.",
213
- "Control commands start immediately after the mention:",
214
- "@agent /model - show this thread's current model",
215
- "@agent /model list - show available models",
216
- "@agent /model <handle-or-id> - switch this thread's model",
217
- "@agent /status - show route and listener status",
218
- "@agent /cancel - cancel the current turn",
219
- "@agent /chat - show the web chat link",
220
- "@agent /feedback <message> - send feedback to the Letta team from this routed thread",
221
- "@agent /reflection - start a memory reflection pass",
222
- "@agent /detach - stop replying in this thread until mentioned again",
223
- "@agent /new - start a fresh conversation for this thread",
224
- "@agent /reload - reload settings, local mods, and agent secrets",
225
- ...extraLines,
226
- `Legacy bang aliases still work after a mention: ${supportedBangCommandsText()}.`,
227
- "If this chat is not connected yet, send a normal message and follow the pairing instructions."
228
- ].join(`
229
- `);
230
- }
231
- const extraParagraphs = extras.length > 0 ? [
232
- `${extrasLabel} here: ${extras.map((definition) => `/${definition.name}`).join(", ")}.`
233
- ] : [];
234
- return [
235
- `${displayName} is connected to Letta Code.`,
236
- "Send a normal message here and the connected agent will reply in this chat.",
237
- `Supported slash commands here: ${supportedCommandsText()}.`,
238
- ...extraParagraphs,
239
- "If this chat is not connected yet, send any non-command message and follow the pairing instructions."
240
- ].join(`
241
-
242
- `);
243
- }
244
- function buildUnsupportedChannelCommandMessage(channelId, command, resolveDisplayName = defaultChannelDisplayName, options) {
245
- const displayName = resolveDisplayName(channelId);
246
- const isBang = command.raw.startsWith("!");
247
- const commandKind = isBang ? "bang" : "slash";
248
- const supportedCommands = isBang ? supportedBangCommandsText() : channelId === "slack" ? supportedSlackMentionSlashCommandsText(options) : supportedCommandsText("/", options);
249
- const supportedLabel = channelId === "slack" && !isBang ? "Slack mention commands" : `${commandKind} commands`;
250
- return [
251
- `${displayName} received ${command.raw}, but that ${commandKind} command is not supported in channels yet.`,
252
- `Supported ${supportedLabel}: ${supportedCommands}.`,
253
- `Send normal messages without a leading ${isBang ? "bang" : "slash"} command to talk to the connected agent.`
254
- ].join(`
255
-
256
- `);
257
- }
258
-
259
- // src/channels/command-runtime-executor.ts
260
- var DEFAULT_CHANNEL_MODEL_LIST_LIMIT = 8;
261
- function getModelEntryRank(entry) {
262
- if (entry.isDefault)
263
- return 0;
264
- if (entry.isFeatured)
265
- return 1;
266
- const effort = entry.updateArgs?.reasoning_effort;
267
- if (effort === "medium")
268
- return 2;
269
- if (effort === "high")
270
- return 3;
271
- return 4;
272
- }
273
- function preferModelEntry(current, candidate) {
274
- return getModelEntryRank(candidate) < getModelEntryRank(current) ? candidate : current;
275
- }
276
- function buildModelEntriesByHandle(entries) {
277
- const byHandle = new Map;
278
- for (const entry of entries) {
279
- const current = byHandle.get(entry.handle);
280
- byHandle.set(entry.handle, current ? preferModelEntry(current, entry) : entry);
281
- }
282
- return byHandle;
283
- }
284
- function makeUnknownModelEntry(handle) {
285
- return {
286
- id: handle,
287
- handle,
288
- label: handle,
289
- description: ""
290
- };
291
- }
292
- function resolveModelHandles(params) {
293
- const { handles, byHandle, availableHandles } = params;
294
- const seen = new Set;
295
- const resolved = [];
296
- for (const handle of handles) {
297
- if (!handle || seen.has(handle))
298
- continue;
299
- seen.add(handle);
300
- if (availableHandles && !availableHandles.has(handle))
301
- continue;
302
- resolved.push(byHandle.get(handle) ?? makeUnknownModelEntry(handle));
303
- }
304
- return resolved;
305
- }
306
- function getFallbackModelEntries(byHandle) {
307
- const preferred = Array.from(byHandle.values()).filter((entry) => entry.isDefault || entry.isFeatured);
308
- return preferred.length > 0 ? preferred : Array.from(byHandle.values());
309
- }
310
- function modelCommandPrefix(channelId) {
311
- return channelId === "slack" ? "@agent /model" : "/model";
312
- }
313
- function buildChannelModelNotFoundText(channelId) {
314
- return `Model not found. Use ${modelCommandPrefix(channelId)} list to see available models.`;
315
- }
316
- function buildChannelCurrentModelMessage(channelId, params, displayNameResolver = defaultChannelDisplayName) {
317
- const displayName = displayNameResolver(channelId);
318
- const scope = params.scope === "agent" ? "agent" : "conversation";
319
- const handleText = params.modelHandle && params.modelHandle !== params.modelLabel ? ` (${params.modelHandle})` : "";
320
- const switchCommand = modelCommandPrefix(channelId);
321
- return [
322
- `${displayName} current ${scope} model: ${params.modelLabel}${handleText}.`,
323
- `Use ${switchCommand} list to see available models, or ${switchCommand} <handle-or-id> to switch.`
324
- ].join(`
325
- `);
326
- }
327
- function formatChannelModelEntry(channelId, entry) {
328
- const selector = entry.id || entry.handle;
329
- const handleText = entry.handle === entry.label ? "" : ` — ${entry.handle}`;
330
- return `• ${entry.label}${handleText} (${modelCommandPrefix(channelId)} ${selector})`;
331
- }
332
- function appendModelEntrySection(lines, channelId, title, entries, limit) {
333
- if (entries.length === 0)
334
- return;
335
- lines.push("", `${title}:`);
336
- for (const entry of entries.slice(0, limit)) {
337
- lines.push(formatChannelModelEntry(channelId, entry));
338
- }
339
- const remaining = entries.length - limit;
340
- if (remaining > 0) {
341
- lines.push(`…and ${remaining} more.`);
342
- }
343
- }
344
- function buildChannelModelListMessage(channelId, params, displayNameResolver = defaultChannelDisplayName) {
345
- const displayName = displayNameResolver(channelId);
346
- const limit = params.limit ?? DEFAULT_CHANNEL_MODEL_LIST_LIMIT;
347
- const entries = params.entries;
348
- const byHandle = buildModelEntriesByHandle(entries);
349
- const availableHandleList = Array.isArray(params.availableHandles) ? params.availableHandles : null;
350
- const availableSet = availableHandleList ? new Set(availableHandleList) : null;
351
- const recentEntries = resolveModelHandles({
352
- handles: params.recentHandles ?? [],
353
- byHandle,
354
- availableHandles: availableSet
355
- });
356
- const availableEntries = availableHandleList ? resolveModelHandles({ handles: availableHandleList, byHandle }) : getFallbackModelEntries(byHandle);
357
- const lines = [`${displayName} model selector`];
358
- if (params.availableHandles === null) {
359
- lines.push("Availability lookup failed; showing built-in recommended models.");
360
- } else if (params.availableHandles === undefined) {
361
- lines.push("Available model data was not returned; showing built-in recommended models.");
362
- }
363
- appendModelEntrySection(lines, channelId, "Recent models", recentEntries, limit);
364
- appendModelEntrySection(lines, channelId, "Available models", availableEntries, limit);
365
- if (availableEntries.length === 0) {
366
- lines.push("", "No available models were reported. Use /connect in Letta Code to configure a provider, then try again.");
367
- }
368
- lines.push("");
369
- if (channelId === "slack") {
370
- lines.push("Mention the app with @agent /model <handle-or-id> to switch this thread's routed model. Use @agent /model to show the current model. Legacy !model still works after a mention.");
371
- } else {
372
- lines.push("Use /model <handle-or-id> to switch this chat's routed model, or /model to show the current model.");
373
- }
374
- return lines.join(`
375
- `);
376
- }
377
- function buildChannelModelListUnavailableMessage(channelId, error, displayNameResolver = defaultChannelDisplayName) {
378
- const displayName = displayNameResolver(channelId);
379
- return `${displayName} could not load the model list: ${error}`;
380
- }
381
- function buildChannelCurrentModelUnavailableMessage(channelId, error, displayNameResolver = defaultChannelDisplayName) {
382
- const displayName = displayNameResolver(channelId);
383
- return `${displayName} could not load the current model: ${error}`;
384
- }
385
- function buildChannelModelUpdatedMessage(channelId, params, displayNameResolver = defaultChannelDisplayName) {
386
- const displayName = displayNameResolver(channelId);
387
- const scope = params.appliedTo === "agent" ? "agent" : "conversation";
388
- const handleText = params.modelHandle === params.modelLabel ? "" : ` (${params.modelHandle})`;
389
- return `${displayName} updated this ${scope}'s model to ${params.modelLabel}${handleText}.`;
390
- }
391
- function buildChannelModelUpdateFailedMessage(channelId, identifier, error, displayNameResolver = defaultChannelDisplayName) {
392
- const displayName = displayNameResolver(channelId);
393
- return `${displayName} could not switch this chat's routed model to ${identifier}: ${error}`;
394
- }
395
- function buildChannelCancelAcceptedMessage(channelId, displayNameResolver = defaultChannelDisplayName) {
396
- const displayName = displayNameResolver(channelId);
397
- return `${displayName} cancelled the in-progress agent turn for this chat.`;
398
- }
399
- function buildChannelCancelNoActiveTurnMessage(channelId, displayNameResolver = defaultChannelDisplayName) {
400
- const displayName = displayNameResolver(channelId);
401
- return `${displayName} received /cancel, but there is no in-progress agent turn to cancel for this chat.`;
402
- }
403
- function parseChannelModelCommand(args) {
404
- const modelIdentifier = args.trim();
405
- if (!modelIdentifier) {
406
- return { kind: "current" };
407
- }
408
- if (modelIdentifier.toLowerCase() === "list") {
409
- return { kind: "list" };
410
- }
411
- return { kind: "update", modelIdentifier };
412
- }
413
- async function runChannelModelListCommand(params) {
414
- const displayNameResolver = params.channelDisplayName ?? defaultChannelDisplayName;
415
- const result = await params.client.listModels();
416
- return {
417
- handled: true,
418
- text: result.success ? buildChannelModelListMessage(params.channelId, {
419
- entries: result.entries,
420
- availableHandles: result.availableHandles,
421
- recentHandles: params.recentHandles
422
- }, displayNameResolver) : buildChannelModelListUnavailableMessage(params.channelId, result.error ?? "Failed to list models", displayNameResolver)
423
- };
424
- }
425
- async function runChannelModelUpdateCommand(params) {
426
- const displayNameResolver = params.channelDisplayName ?? defaultChannelDisplayName;
427
- const result = await params.client.updateModel({
428
- runtime: params.runtime,
429
- modelIdentifier: params.modelIdentifier
430
- });
431
- if (!result.success) {
432
- return {
433
- handled: true,
434
- success: false,
435
- text: buildChannelModelUpdateFailedMessage(params.channelId, params.modelIdentifier, result.error ?? "Failed to update model", displayNameResolver)
436
- };
437
- }
438
- const appliedHandle = result.modelHandle ?? params.modelIdentifier;
439
- return {
440
- handled: true,
441
- success: true,
442
- modelHandle: appliedHandle,
443
- text: buildChannelModelUpdatedMessage(params.channelId, {
444
- modelLabel: params.resolveModelLabel?.(appliedHandle) ?? params.modelIdentifier,
445
- modelHandle: appliedHandle,
446
- appliedTo: result.appliedTo
447
- }, displayNameResolver)
448
- };
449
- }
450
- async function runChannelCancelCommand(params) {
451
- const response = await params.client.abortMessage({
452
- runtime: params.runtime,
453
- runId: null
454
- });
455
- const cancelled = response.success && response.aborted;
456
- if (params.channelId === undefined) {
457
- return { handled: true, cancelled };
458
- }
459
- const displayNameResolver = params.channelDisplayName ?? defaultChannelDisplayName;
460
- return {
461
- handled: true,
462
- cancelled,
463
- text: cancelled ? buildChannelCancelAcceptedMessage(params.channelId, displayNameResolver) : buildChannelCancelNoActiveTurnMessage(params.channelId, displayNameResolver)
464
- };
465
- }
466
- async function runChannelExecuteCommand(params) {
467
- const trimmedArgs = params.args?.trim();
468
- const response = await params.client.executeCommand({
469
- runtime: params.runtime,
470
- commandId: params.commandId,
471
- ...trimmedArgs ? { args: trimmedArgs } : {}
472
- });
473
- return { handled: true, text: response.output };
474
- }
475
- function runChannelReflectionCommand(params) {
476
- return runChannelExecuteCommand({ ...params, commandId: "reflect" });
477
- }
478
- function runChannelReloadCommand(params) {
479
- return runChannelExecuteCommand({ ...params, commandId: "reload" });
480
- }
481
- // src/channels/core-stream.ts
482
- var LETTA_STREAM_NO_ASSISTANT_MESSAGE_ERROR = "No assistant message received in stream";
483
-
484
- class LettaStreamCoreError extends Error {
485
- errorType;
486
- detail;
487
- runId;
488
- constructor(params) {
489
- super(params.message);
490
- this.name = "LettaStreamCoreError";
491
- this.errorType = params.errorType;
492
- this.detail = params.detail;
493
- this.runId = params.runId;
494
- }
495
- }
496
-
497
- class LettaStreamNoAssistantMessageError extends Error {
498
- constructor() {
499
- super(LETTA_STREAM_NO_ASSISTANT_MESSAGE_ERROR);
500
- this.name = "LettaStreamNoAssistantMessageError";
501
- }
502
- }
503
- function normalizeErrorLine(value) {
504
- const trimmed = value?.trim();
505
- return trimmed ? trimmed : undefined;
506
- }
507
- function formatLettaStreamCoreErrorForChannel(error, options = {}) {
508
- const message = normalizeErrorLine(error.message) ?? "Core failed to generate a response.";
509
- const detail = normalizeErrorLine(error.detail);
510
- if (options.includeDetail === false || !detail || detail === message) {
511
- return message;
512
- }
513
- return `${message}
514
- ${detail}`;
515
- }
516
- function isRecord(value) {
517
- return value !== null && typeof value === "object";
518
- }
519
- function isOptionalString(value) {
520
- return typeof value === "undefined" || typeof value === "string";
521
- }
522
- function isLettaSseTextContentPart(value) {
523
- if (!isRecord(value)) {
524
- return false;
525
- }
526
- return value.type === "text" && typeof value.text === "string" && isOptionalString(value.signature);
527
- }
528
- function isLettaSseAssistantMessage(value) {
529
- if (!isRecord(value) || value.message_type !== "assistant_message") {
530
- return false;
531
- }
532
- const content = value.content;
533
- return typeof content === "undefined" || typeof content === "string" || Array.isArray(content) && content.every(isLettaSseTextContentPart);
534
- }
535
- function isLettaSseErrorMessage(value) {
536
- if (!isRecord(value) || value.message_type !== "error_message") {
537
- return false;
538
- }
539
- return isOptionalString(value.error_type) && isOptionalString(value.message) && isOptionalString(value.detail) && isOptionalString(value.run_id);
540
- }
541
- function isLettaSseStopReasonMessage(value) {
542
- if (!isRecord(value) || value.message_type !== "stop_reason") {
543
- return false;
544
- }
545
- return isOptionalString(value.stop_reason);
546
- }
547
- function coreErrorFromMessage(message) {
548
- return new LettaStreamCoreError({
549
- errorType: message.error_type,
550
- message: message.message ?? "Core failed to generate a response.",
551
- detail: message.detail,
552
- runId: message.run_id
553
- });
554
- }
555
- function collectAssistantContent(message) {
556
- if (typeof message.content === "string") {
557
- return [message.content];
558
- }
559
- if (Array.isArray(message.content)) {
560
- return message.content.map((part) => part.text);
561
- }
562
- return [];
563
- }
564
- async function collectLettaSseAssistantText(body, options = {}) {
565
- const reader = body.getReader();
566
- const decoder = new TextDecoder;
567
- let buffer = "";
568
- const assistantMessages = [];
569
- let stopReason;
570
- async function processData(data) {
571
- if (data === "[DONE]") {
572
- return;
573
- }
574
- const parsed = JSON.parse(data);
575
- await options.onDelta?.(parsed);
576
- const progressUpdates = options.progressBuilder?.buildUpdates(parsed) ?? [];
577
- for (const update of progressUpdates) {
578
- await options.onProgressUpdate?.(update);
579
- }
580
- if (isLettaSseErrorMessage(parsed)) {
581
- throw coreErrorFromMessage(parsed);
582
- }
583
- if (isLettaSseAssistantMessage(parsed)) {
584
- assistantMessages.push(...collectAssistantContent(parsed));
585
- return;
586
- }
587
- if (isLettaSseStopReasonMessage(parsed)) {
588
- stopReason = parsed.stop_reason;
589
- }
590
- }
591
- async function processLine(line) {
592
- if (!line.trim() || !line.startsWith("data: ")) {
593
- return;
594
- }
595
- await processData(line.slice(6));
596
- }
597
- try {
598
- while (true) {
599
- const { done, value } = await reader.read();
600
- if (done) {
601
- break;
602
- }
603
- buffer += decoder.decode(value, { stream: true });
604
- const lines = buffer.split(`
605
- `);
606
- buffer = lines.pop() ?? "";
607
- for (const line of lines) {
608
- await processLine(line);
609
- }
610
- }
611
- const flushed = decoder.decode();
612
- if (flushed) {
613
- buffer += flushed;
614
- }
615
- if (buffer) {
616
- await processLine(buffer);
617
- }
618
- } finally {
619
- reader.releaseLock();
620
- }
621
- const text = assistantMessages.join(" ").trim();
622
- if (!text) {
623
- throw new LettaStreamNoAssistantMessageError;
624
- }
625
- return {
626
- text,
627
- chunkCount: assistantMessages.length,
628
- stopReason
629
- };
630
- }
631
- // src/utils/conversation-busy-error.ts
632
- var CONVERSATION_BUSY_ERROR_PATTERNS = [
633
- /another request is (?:currently )?(?:being )?processed/i,
634
- /currently being processed for this conversation/i,
635
- /busy with another active run/i,
636
- /already processing for this conversation/i,
637
- /turn still running/i
638
- ];
639
- var CONVERSATION_BUSY_TITLE = "Turn still running";
640
- function isConversationBusyErrorText(errorText) {
641
- if (!errorText)
642
- return false;
643
- return CONVERSATION_BUSY_ERROR_PATTERNS.some((pattern) => pattern.test(errorText));
644
- }
645
- function buildConversationBusyErrorBody(automaticRetry) {
646
- return automaticRetry ? "Another request is already processing for this conversation. I’ll wait for it to finish and retry automatically." : "Another request is already processing for this conversation. Please wait for it to finish, then try again.";
647
- }
648
-
649
- // src/channels/lifecycle-error.ts
650
- var RAW_LOOP_ERROR_PATTERN = /^Unexpected stop reason:\s*error$/i;
651
- var APP_CHAT_URL_PATTERN = /https:\/\/app\.letta\.com\/chat\/\S+/i;
652
- var ESCAPE_CHARACTER = String.fromCharCode(27);
653
- var OSC8_PREFIX = `${ESCAPE_CHARACTER}]8;;`;
654
- var OSC8_TERMINATOR = `${ESCAPE_CHARACTER}\\`;
655
- var APPROVAL_PENDING_ERROR_PATTERNS = [
656
- /waiting for approval/i,
657
- /pending request before continuing/i,
658
- /approve or deny the pending request/i
659
- ];
660
- var DATABASE_LOCK_TIMEOUT_PATTERN = /\bcancel(?:l)?ing statement due to lock timeout\b/i;
661
- var POSTGRES_LOCK_NOT_AVAILABLE_CODE_PATTERN = /\b55P03\b/i;
662
- var POSTGRES_LOCK_NOT_AVAILABLE_SQLSTATE_PATTERN = /\b(?:sqlstate|pgcode)\s*[:=]?\s*["']?55P03\b/i;
663
- var POSTGRES_LOCK_NOT_AVAILABLE_CONTEXT_PATTERN = /\b(?:postgres(?:ql)?|psycopg|sqlalchemy|lock[_ -]?not[_ -]?available|lock timeout)\b/i;
664
- var RUN_ID_PATTERNS = [
665
- /"run_id"\s*:\s*"([^"\\]+)"/i,
666
- /\brun[_\s-]?id\b["']?\s*[:=]\s*["']?([A-Za-z0-9_-]+)/i,
667
- /\(run:\s*([A-Za-z0-9_-]+)\)/i
668
- ];
669
- var CHANNEL_LIFECYCLE_FALLBACK_ERROR_MESSAGE = "Something went wrong while processing that message. Please try again.";
670
- var CHANNEL_LIFECYCLE_APPROVAL_PENDING_MESSAGE = "The agent is still waiting on a tool approval from an earlier turn. Please approve or deny that pending request, then send your message again.";
671
- var CHANNEL_LIFECYCLE_TRANSIENT_ERROR_MESSAGE = "A temporary error interrupted this turn. Please try again.";
672
- var CHANNEL_LIFECYCLE_CONVERSATION_BUSY_TITLE = CONVERSATION_BUSY_TITLE;
673
- function stripTrailingRunIdPunctuation(runId) {
674
- return runId.replace(/[)"'.,;]+$/g, "");
675
- }
676
- function extractChannelLifecycleRunId(errorText) {
677
- if (!errorText)
678
- return;
679
- for (const pattern of RUN_ID_PATTERNS) {
680
- const match = errorText.match(pattern);
681
- const runId = match?.[1]?.trim();
682
- if (runId) {
683
- return stripTrailingRunIdPunctuation(runId);
684
- }
685
- }
686
- return;
687
- }
688
- function stripOsc8TerminalLinks(errorText) {
689
- let output = "";
690
- let cursor = 0;
691
- while (cursor < errorText.length) {
692
- const linkStart = errorText.indexOf(OSC8_PREFIX, cursor);
693
- if (linkStart === -1) {
694
- output += errorText.slice(cursor);
695
- break;
696
- }
697
- const labelStart = errorText.indexOf(OSC8_TERMINATOR, linkStart + OSC8_PREFIX.length);
698
- if (labelStart === -1) {
699
- output += errorText.slice(cursor);
700
- break;
701
- }
702
- const closeStart = errorText.indexOf(OSC8_PREFIX, labelStart + OSC8_TERMINATOR.length);
703
- if (closeStart === -1) {
704
- output += errorText.slice(cursor);
705
- break;
706
- }
707
- const closeEnd = errorText.indexOf(OSC8_TERMINATOR, closeStart + OSC8_PREFIX.length);
708
- if (closeEnd === -1) {
709
- output += errorText.slice(cursor);
710
- break;
711
- }
712
- output += errorText.slice(cursor, linkStart);
713
- output += errorText.slice(labelStart + OSC8_TERMINATOR.length, closeStart);
714
- cursor = closeEnd + OSC8_TERMINATOR.length;
715
- }
716
- return output;
717
- }
718
- function sanitizeChannelLifecycleErrorText(errorText) {
719
- if (!errorText)
720
- return "";
721
- const withoutTerminalLinks = stripOsc8TerminalLinks(errorText);
722
- return withoutTerminalLinks.split(`
723
- `).filter((line) => {
724
- const trimmed = line.trim();
725
- if (/^View agent:/i.test(trimmed))
726
- return false;
727
- if (APP_CHAT_URL_PATTERN.test(trimmed))
728
- return false;
729
- return true;
730
- }).join(`
731
- `).replace(/[ \t]+\n/g, `
732
- `).trim();
733
- }
734
- function truncateLifecycleMessage(text, maxLength) {
735
- if (text.length <= maxLength)
736
- return text;
737
- return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
738
- }
739
- function isDatabaseLockErrorText(errorText) {
740
- return DATABASE_LOCK_TIMEOUT_PATTERN.test(errorText) || POSTGRES_LOCK_NOT_AVAILABLE_SQLSTATE_PATTERN.test(errorText) || POSTGRES_LOCK_NOT_AVAILABLE_CODE_PATTERN.test(errorText) && POSTGRES_LOCK_NOT_AVAILABLE_CONTEXT_PATTERN.test(errorText);
741
- }
742
- function getChannelLifecycleErrorDisplay(errorText, options = {}) {
743
- const normalized = sanitizeChannelLifecycleErrorText(errorText);
744
- const optionsRunId = options.runId?.trim();
745
- const runId = optionsRunId || extractChannelLifecycleRunId(errorText);
746
- if (!normalized || RAW_LOOP_ERROR_PATTERN.test(normalized)) {
747
- return {
748
- kind: "generic",
749
- title: "Turn failed",
750
- body: CHANNEL_LIFECYCLE_FALLBACK_ERROR_MESSAGE,
751
- runId
752
- };
753
- }
754
- if (isDatabaseLockErrorText(normalized)) {
755
- return {
756
- kind: "database_lock_timeout",
757
- title: "Turn failed",
758
- body: CHANNEL_LIFECYCLE_TRANSIENT_ERROR_MESSAGE,
759
- runId
760
- };
761
- }
762
- if (isConversationBusyErrorText(normalized)) {
763
- return {
764
- kind: "conversation_busy",
765
- title: CHANNEL_LIFECYCLE_CONVERSATION_BUSY_TITLE,
766
- body: buildConversationBusyErrorBody(options.automaticRetry ?? false),
767
- runId
768
- };
769
- }
770
- if (APPROVAL_PENDING_ERROR_PATTERNS.some((pattern) => pattern.test(normalized))) {
771
- return {
772
- kind: "approval_pending",
773
- title: "Turn failed",
774
- body: CHANNEL_LIFECYCLE_APPROVAL_PENDING_MESSAGE,
775
- runId
776
- };
777
- }
778
- return {
779
- kind: "generic",
780
- title: "Turn failed",
781
- body: normalized,
782
- runId
783
- };
784
- }
785
- function normalizeChannelLifecycleErrorMessage(errorText, options = {}) {
786
- return getChannelLifecycleErrorDisplay(errorText, options).body;
787
- }
788
- function formatChannelLifecycleErrorMessage(errorText, options = {}) {
789
- const display = getChannelLifecycleErrorDisplay(errorText, options);
790
- const maxLength = options.maxLength ?? Number.POSITIVE_INFINITY;
791
- const body = truncateLifecycleMessage(display.body, maxLength);
792
- if (display.kind === "conversation_busy") {
793
- const lines2 = [display.title, body];
794
- if (display.runId) {
795
- lines2.push("", `Run ID: ${display.runId}`);
796
- }
797
- return lines2.join(`
798
- `);
799
- }
800
- if (display.kind === "database_lock_timeout") {
801
- const lines2 = [`${display.title}:`, body];
802
- if (display.runId) {
803
- lines2.push("", `Run ID: ${display.runId}`);
804
- }
805
- return lines2.join(`
806
- `);
807
- }
808
- if (options.codeBlock) {
809
- const escaped = body.replace(/```/g, "``​`");
810
- const lines2 = [`${display.title}:`, "```", escaped, "```"];
811
- if (display.runId) {
812
- lines2.push("", `Run ID: ${display.runId}`);
813
- }
814
- return lines2.join(`
815
- `);
816
- }
817
- const lines = [`${display.title}:`, body];
818
- if (display.runId) {
819
- lines.push("", `Run ID: ${display.runId}`);
820
- }
821
- return lines.join(`
822
- `);
823
- }
824
- // src/constants.ts
825
- var SYSTEM_REMINDER_TAG = "system-reminder";
826
- var SYSTEM_REMINDER_OPEN = `<${SYSTEM_REMINDER_TAG}>`;
827
- var SYSTEM_REMINDER_CLOSE = `</${SYSTEM_REMINDER_TAG}>`;
828
- var SYSTEM_ALERT_TAG = "system-alert";
829
- var SYSTEM_ALERT_OPEN = `<${SYSTEM_ALERT_TAG}>`;
830
- var SYSTEM_ALERT_CLOSE = `</${SYSTEM_ALERT_TAG}>`;
831
- var ELAPSED_DISPLAY_THRESHOLD_MS = 60 * 1000;
832
-
833
- // src/channels/xml.ts
834
- function escapeXmlText(text) {
835
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
836
- }
837
- function escapeXmlAttribute(text) {
838
- return escapeXmlText(text).replace(/"/g, "&quot;").replace(/'/g, "&apos;");
839
- }
840
- function sanitizeMentionDisplayName(mention) {
841
- const name = mention.displayName.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, " ").replace(/\s+/gu, " ").trim().slice(0, 80).trim();
842
- return name || mention.userId;
843
- }
844
- function buildTextWithUserMentions(text, mentions) {
845
- if (!mentions || mentions.length === 0)
846
- return escapeXmlText(text);
847
- let cursor = 0;
848
- const parts = [];
849
- for (const mention of mentions) {
850
- if (!Number.isInteger(mention.start) || !Number.isInteger(mention.end) || mention.start < cursor || mention.end <= mention.start || mention.end > text.length || !mention.userId.trim()) {
851
- return escapeXmlText(text);
852
- }
853
- parts.push(escapeXmlText(text.slice(cursor, mention.start)));
854
- const displayName = sanitizeMentionDisplayName(mention);
855
- parts.push(`<mention id="${escapeXmlAttribute(mention.userId)}">@${escapeXmlText(displayName)}</mention>`);
856
- cursor = mention.end;
857
- }
858
- parts.push(escapeXmlText(text.slice(cursor)));
859
- return parts.join("");
860
- }
861
- function formatMebibytes(bytes) {
862
- const mebibytes = bytes / (1024 * 1024);
863
- const rounded = mebibytes >= 100 ? Math.round(mebibytes).toString() : mebibytes.toFixed(1);
864
- return `${rounded.replace(/\.0$/, "")} MiB`;
865
- }
866
- function buildAttachmentXml(attachment, context) {
867
- const attrs = [`kind="${escapeXmlAttribute(attachment.kind)}"`];
868
- if (attachment.localPath) {
869
- attrs.push(`local_path="${escapeXmlAttribute(attachment.localPath)}"`);
870
- } else {
871
- attrs.push('download_status="not_downloaded"');
872
- }
873
- if (attachment.id) {
874
- attrs.push(`attachment_id="${escapeXmlAttribute(attachment.id)}"`);
875
- }
876
- if (attachment.name) {
877
- attrs.push(`name="${escapeXmlAttribute(attachment.name)}"`);
878
- }
879
- if (attachment.mimeType) {
880
- attrs.push(`mime_type="${escapeXmlAttribute(attachment.mimeType)}"`);
881
- }
882
- if (typeof attachment.sizeBytes === "number") {
883
- attrs.push(`size_bytes="${attachment.sizeBytes}"`);
884
- }
885
- const sourceMessageId = attachment.sourceMessageId ?? context.messageId;
886
- if (!attachment.localPath && sourceMessageId) {
887
- attrs.push(`source_message_id="${escapeXmlAttribute(sourceMessageId)}"`);
888
- }
889
- if (!attachment.localPath && attachment.sourceThreadId) {
890
- attrs.push(`source_thread_id="${escapeXmlAttribute(attachment.sourceThreadId)}"`);
891
- }
892
- if (attachment.downloadReason) {
893
- attrs.push(`download_reason="${escapeXmlAttribute(attachment.downloadReason)}"`);
894
- }
895
- if (typeof attachment.autoDownloadLimitBytes === "number") {
896
- attrs.push(`auto_download_limit_bytes="${attachment.autoDownloadLimitBytes}"`);
897
- }
898
- const children = [];
899
- if (attachment.transcription) {
900
- children.push(`<attempted_transcription>${escapeXmlText(attachment.transcription)}</attempted_transcription>`);
901
- }
902
- if (attachment.transcriptionError) {
903
- children.push(`<attempted_transcription_error>${escapeXmlText(attachment.transcriptionError)}</attempted_transcription_error>`);
904
- }
905
- if (!attachment.localPath && context.channel === "slack" && attachment.id && sourceMessageId) {
906
- const accountArg = context.accountId ? `, accountId="${escapeXmlAttribute(context.accountId)}"` : "";
907
- const threadArg = attachment.sourceThreadId ? `, threadId="${escapeXmlAttribute(attachment.sourceThreadId)}"` : "";
908
- const action = `MessageChannel with action="download-file", channel="slack", chat_id="${escapeXmlAttribute(context.chatId)}"${accountArg}${threadArg}, attachmentId="${escapeXmlAttribute(attachment.id)}", and messageId="${escapeXmlAttribute(sourceMessageId)}"`;
909
- if (attachment.downloadReason === "exceeds_auto_download_limit") {
910
- const sizeNote = typeof attachment.sizeBytes === "number" ? `This file is ${formatMebibytes(attachment.sizeBytes)}${typeof attachment.autoDownloadLimitBytes === "number" ? `, above the ${formatMebibytes(attachment.autoDownloadLimitBytes)} automatic download limit` : ""}. ` : "";
911
- children.push(`<download-instruction>${sizeNote}Call ${action}. The tool downloads the file into the same Slack inbound attachment directory and returns its local_path. Large downloads continue in the background instead of blocking; a task notification delivers the local_path when they finish. Do not ask the sender to reattach it.</download-instruction>`);
912
- } else {
913
- children.push(`<download-retry>Automatic download did not complete. Call ${action} to retry. The action may return a precise error if Slack still cannot provide the file.</download-retry>`);
914
- }
915
- }
916
- if (children.length > 0) {
917
- return `<attachment ${attrs.join(" ")}>
918
- ${children.join(`
919
- `)}
920
- </attachment>`;
921
- }
922
- return `<attachment ${attrs.join(" ")} />`;
923
- }
924
- function buildReactionXml(msg) {
925
- if (!msg.reaction) {
926
- return null;
927
- }
928
- const attrs = [
929
- `action="${escapeXmlAttribute(msg.reaction.action)}"`,
930
- `emoji="${escapeXmlAttribute(msg.reaction.emoji)}"`,
931
- `target_message_id="${escapeXmlAttribute(msg.reaction.targetMessageId)}"`
932
- ];
933
- if (msg.reaction.targetSenderId) {
934
- attrs.push(`target_sender_id="${escapeXmlAttribute(msg.reaction.targetSenderId)}"`);
935
- }
936
- return `<reaction ${attrs.join(" ")} />`;
937
- }
938
- function buildReplyContextXml(msg) {
939
- const replyContext = msg.replyContext;
940
- if (!replyContext) {
941
- return null;
942
- }
943
- const attrs = [];
944
- if (replyContext.messageId) {
945
- attrs.push(`message_id="${escapeXmlAttribute(replyContext.messageId)}"`);
946
- }
947
- if (replyContext.senderId) {
948
- attrs.push(`sender_id="${escapeXmlAttribute(replyContext.senderId)}"`);
949
- }
950
- if (replyContext.senderName) {
951
- attrs.push(`sender_name="${escapeXmlAttribute(replyContext.senderName)}"`);
952
- }
953
- const attrString = attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
954
- if (replyContext.text?.trim()) {
955
- const text = buildTextWithUserMentions(replyContext.text, replyContext.userMentions);
956
- return `<reply-context${attrString}>
957
- ${text}
958
- </reply-context>`;
959
- }
960
- return `<reply-context${attrString} />`;
961
- }
962
- function buildThreadContextEntryXml(tagName, entry, context) {
963
- const attrs = [];
964
- if (entry.senderId) {
965
- attrs.push(`sender_id="${escapeXmlAttribute(entry.senderId)}"`);
966
- }
967
- if (entry.senderName) {
968
- attrs.push(`sender_name="${escapeXmlAttribute(entry.senderName)}"`);
969
- }
970
- if (entry.messageId) {
971
- attrs.push(`message_id="${escapeXmlAttribute(entry.messageId)}"`);
972
- }
973
- const attrString = attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
974
- const body = [
975
- ...entry.text ? [buildTextWithUserMentions(entry.text, entry.userMentions)] : [],
976
- ...(entry.attachments ?? []).map((attachment) => buildAttachmentXml(attachment, {
977
- ...context,
978
- messageId: entry.messageId
979
- }))
980
- ].join(`
981
- `);
982
- return `<${tagName}${attrString}>
983
- ${body}
984
- </${tagName}>`;
985
- }
986
- function buildThreadContextXml(msg) {
987
- const threadContext = msg.threadContext;
988
- if (!threadContext) {
989
- return null;
990
- }
991
- const parts = [];
992
- if (threadContext.starter) {
993
- parts.push(buildThreadContextEntryXml("thread-starter", threadContext.starter, {
994
- channel: msg.channel,
995
- accountId: msg.accountId,
996
- chatId: msg.chatId
997
- }));
998
- }
999
- const historyEntries = threadContext.history ?? [];
1000
- if (historyEntries.length > 0) {
1001
- parts.push([
1002
- "<thread-history>",
1003
- ...historyEntries.map((entry) => buildThreadContextEntryXml("thread-message", entry, {
1004
- channel: msg.channel,
1005
- accountId: msg.accountId,
1006
- chatId: msg.chatId
1007
- })),
1008
- "</thread-history>"
1009
- ].join(`
1010
- `));
1011
- }
1012
- if (parts.length === 0) {
1013
- return null;
1014
- }
1015
- const attrs = threadContext.label ? ` label="${escapeXmlAttribute(threadContext.label)}"` : "";
1016
- return [`<thread-context${attrs}>`, ...parts, "</thread-context>"].join(`
1017
- `);
1018
- }
1019
- function buildChannelNotificationXml(msg) {
1020
- const attrs = [
1021
- `source="${escapeXmlAttribute(msg.channel)}"`,
1022
- `chat_id="${escapeXmlAttribute(msg.chatId)}"`,
1023
- `sender_id="${escapeXmlAttribute(msg.senderId)}"`
1024
- ];
1025
- if (msg.accountId) {
1026
- attrs.push(`account_id="${escapeXmlAttribute(msg.accountId)}"`);
1027
- }
1028
- if (msg.senderName) {
1029
- attrs.push(`sender_name="${escapeXmlAttribute(msg.senderName)}"`);
1030
- }
1031
- if (msg.messageId) {
1032
- attrs.push(`message_id="${escapeXmlAttribute(msg.messageId)}"`);
1033
- }
1034
- if (msg.threadId) {
1035
- attrs.push(`thread_id="${escapeXmlAttribute(msg.threadId)}"`);
1036
- }
1037
- if (msg.routedBy) {
1038
- attrs.push(`routed_by="${escapeXmlAttribute(msg.routedBy)}"`);
1039
- }
1040
- const attrString = attrs.join(" ");
1041
- const escapedText = msg.text ? buildTextWithUserMentions(msg.text, msg.userMentions) : "";
1042
- const reactionXml = buildReactionXml(msg);
1043
- const replyContextXml = buildReplyContextXml(msg);
1044
- const threadContextXml = buildThreadContextXml(msg);
1045
- const attachmentXml = (msg.attachments ?? []).map((attachment) => buildAttachmentXml(attachment, {
1046
- channel: msg.channel,
1047
- accountId: msg.accountId,
1048
- chatId: msg.chatId,
1049
- messageId: msg.messageId
1050
- }));
1051
- const body = [
1052
- threadContextXml,
1053
- replyContextXml,
1054
- reactionXml,
1055
- ...attachmentXml,
1056
- escapedText
1057
- ].filter(Boolean).join(`
1058
- `);
1059
- return `<channel-notification ${attrString}>
1060
- ${body}
1061
- </channel-notification>`;
1062
- }
1063
-
1064
- // src/channels/processor.ts
1065
- function buildChannelTurnSource(params) {
1066
- const { message, route } = params;
1067
- return {
1068
- channel: message.channel,
1069
- accountId: message.accountId ?? route.accountId,
1070
- chatId: message.chatId,
1071
- chatType: message.chatType ?? route.chatType,
1072
- senderId: message.senderId,
1073
- senderTeamId: message.senderTeamId,
1074
- messageId: message.messageId,
1075
- threadId: message.threadId ?? route.threadId ?? null,
1076
- agentId: route.agentId,
1077
- conversationId: route.conversationId
1078
- };
1079
- }
1080
- function formatInboundChannelMessageForAgent(params) {
1081
- return buildChannelNotificationXml(params.message);
1082
- }
1083
- function formatLegacyBatchedSender(message) {
1084
- const senderName = message.senderName?.trim();
1085
- const senderId = message.senderId?.trim() ?? "unknown";
1086
- if (senderName && senderName !== senderId) {
1087
- return `${senderName}:${senderId}`;
1088
- }
1089
- return senderId;
1090
- }
1091
- function formatBatchedChannelMessagesForAgent(params) {
1092
- const { messages } = params;
1093
- if (messages.length === 0) {
1094
- return "";
1095
- }
1096
- const firstMessage = messages[0];
1097
- if (messages.length === 1 && firstMessage) {
1098
- return firstMessage.text;
1099
- }
1100
- if (messages.every((message) => message.channelTurnSource)) {
1101
- const formatted2 = messages.map((message) => message.text).join(`
1102
- `);
1103
- return `--- Batched Channel Messages (${messages.length}) ---
1104
- ${formatted2}
1105
- --- End Batched Channel Messages ---`;
1106
- }
1107
- const formatted = messages.map((message) => {
1108
- const timestamp = message.timestamp ?? "unknown";
1109
- return `[user@${formatLegacyBatchedSender(message)}]<${timestamp}>:${message.text}`;
1110
- }).join(`
1111
- `);
1112
- return `--- Batched Messages (${messages.length}) ---
1113
- ${formatted}
1114
- --- End Batched Messages ---`;
1115
- }
1116
- function buildOutboundChannelMessageFromTurnSource(params) {
1117
- const { turnSource } = params;
1118
- return {
1119
- channel: turnSource.channel,
1120
- accountId: turnSource.accountId,
1121
- chatId: turnSource.chatId,
1122
- threadId: turnSource.threadId,
1123
- text: params.text,
1124
- agentId: turnSource.agentId,
1125
- conversationId: turnSource.conversationId
1126
- };
1127
- }
1128
- // src/channels/progress-formatting.ts
1129
- var MAX_PROGRESS_TEXT_LENGTH = 140;
1130
- var MAX_PROGRESS_DETAILS_LENGTH = 180;
1131
- var MAX_SHELL_PROGRESS_DETAILS_LENGTH = 64;
1132
- var MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH = 180;
1133
- var ESCAPE_CODE = String.fromCharCode(27);
1134
- var ANSI_ESCAPE_RE = new RegExp(`${ESCAPE_CODE}\\[[0-9;?]*[ -/]*[@-~]`, "g");
1135
- var SECRET_ASSIGNMENT_RE = /\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|API[_-]?KEY|ACCESS[_-]?KEY)[A-Z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
1136
- var SECRET_JSON_RE = /(["']?(?:token|secret|password|api[_-]?key|access[_-]?key)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|\S+)/gi;
1137
- function isTaskTool(name) {
1138
- return name === "Task" || name === "task" || name === "Agent" || name === "agent";
1139
- }
1140
- function isShellTool(name) {
1141
- const normalized = name.toLowerCase();
1142
- return normalized === "bash" || normalized === "exec_command";
1143
- }
1144
- function isWebSearchTool(name) {
1145
- const normalized = name.toLowerCase();
1146
- return normalized === "web_search" || normalized === "websearch";
1147
- }
1148
- function isSearchTool(name) {
1149
- return name.toLowerCase() === "grep";
1150
- }
1151
- function isGlobTool(name) {
1152
- return name.toLowerCase() === "glob";
1153
- }
1154
- function isFileReadTool(name) {
1155
- return name.toLowerCase() === "read";
1156
- }
1157
- function isFileWriteTool(name) {
1158
- const normalized = name.toLowerCase();
1159
- return normalized === "write";
1160
- }
1161
- function isFileEditTool(name) {
1162
- const normalized = name.toLowerCase();
1163
- return normalized === "edit" || normalized === "applypatch";
1164
- }
1165
- function getPathBaseName(filePath) {
1166
- return filePath.split(/[\\/]/).filter(Boolean).pop() ?? filePath;
1167
- }
1168
- function asRecord(value) {
1169
- return value && typeof value === "object" ? value : null;
1170
- }
1171
- function firstNonEmptyString(...values) {
1172
- for (const value of values) {
1173
- if (typeof value === "string" && value.trim().length > 0) {
1174
- return value;
1175
- }
1176
- }
1177
- return;
1178
- }
1179
- function truncateChannelProgressText(value, maxLength, marker = "...") {
1180
- if (value.length <= maxLength) {
1181
- return value;
1182
- }
1183
- if (maxLength <= marker.length) {
1184
- return marker.slice(0, Math.max(0, maxLength));
1185
- }
1186
- return `${value.slice(0, maxLength - marker.length).trimEnd()}${marker}`;
1187
- }
1188
- function replaceControlCharacters(value) {
1189
- let result = "";
1190
- for (let index = 0;index < value.length; index += 1) {
1191
- const character = value[index] ?? "";
1192
- const code = character.charCodeAt(0);
1193
- result += code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127 ? " " : character;
1194
- }
1195
- return result;
1196
- }
1197
- function sanitizeChannelProgressCore(value) {
1198
- const raw = typeof value === "string" ? value : String(value ?? "");
1199
- const redacted = raw.replace(ANSI_ESCAPE_RE, "").replace(SECRET_ASSIGNMENT_RE, "$1=[redacted]").replace(SECRET_JSON_RE, "$1[redacted]");
1200
- return replaceControlCharacters(redacted).replace(/[\r\n\t]+/g, " ").replace(/@(?=channel|here|everyone|[A-Za-z0-9._-]+)/gi, "@​").replace(/\s+/g, " ").trim();
1201
- }
1202
- function sanitizeChannelProgressText(value, maxLength = MAX_PROGRESS_TEXT_LENGTH) {
1203
- return truncateChannelProgressText(sanitizeChannelProgressCore(value), maxLength);
1204
- }
1205
- function sanitizeChannelProgressIdentifier(value, fallback) {
1206
- const text = sanitizeChannelProgressText(value, 64);
1207
- if (!text) {
1208
- return fallback;
1209
- }
1210
- const cleaned = text.replace(/[^A-Za-z0-9_.:/ -]/g, "").trim();
1211
- return cleaned || fallback;
1212
- }
1213
- function summarizeShellCommand(command) {
1214
- const normalized = sanitizeChannelProgressText(command, 1e4);
1215
- if (!normalized) {
1216
- return "";
1217
- }
1218
- const segments = normalized.split(/\s*;\s*/).map((segment) => segment.trim()).filter(Boolean);
1219
- const firstTwoSegments = segments.slice(0, 2).join("; ");
1220
- const previewSource = firstTwoSegments.length > 0 && firstTwoSegments.length <= 70 ? firstTwoSegments : segments[0] ?? normalized;
1221
- const withoutPipeline = previewSource.split(/\s*\|\s*/)[0] ?? previewSource;
1222
- return sanitizeChannelProgressText(withoutPipeline.trim() || normalized, MAX_SHELL_PROGRESS_DETAILS_LENGTH);
1223
- }
1224
- function getSkillNameFromArguments(parsedArguments) {
1225
- return firstNonEmptyString(parsedArguments.skill, parsedArguments.skillName);
1226
- }
1227
- function getFragmentedSkillName(summary) {
1228
- const skillMatch = summary.argumentsText?.match(/"(?:skill|skillName)"\s*:\s*"([^"]+)"/);
1229
- return skillMatch?.[1];
1230
- }
1231
- function resolveSkillDescription(skillName, options) {
1232
- const lookup = options?.skillDescriptionsByName;
1233
- if (!skillName || !lookup) {
1234
- return;
1235
- }
1236
- if ("get" in lookup && typeof lookup.get === "function") {
1237
- return firstNonEmptyString(lookup.get(skillName));
1238
- }
1239
- return firstNonEmptyString(lookup[skillName]);
1240
- }
1241
- function formatSkillProgressTitleFromName(skillName) {
1242
- const sanitized = sanitizeChannelProgressText(skillName, MAX_PROGRESS_DETAILS_LENGTH);
1243
- return sanitized ? `Skill: ${sanitized}` : undefined;
1244
- }
1245
- function formatShellProgressDetailsFromArguments(parsedArguments) {
1246
- const description = firstNonEmptyString(parsedArguments.description);
1247
- if (description) {
1248
- return sanitizeChannelProgressText(description, MAX_PROGRESS_DETAILS_LENGTH) || undefined;
1249
- }
1250
- const commandPreview = firstNonEmptyString(parsedArguments.command, parsedArguments.cmd);
1251
- return summarizeShellCommand(commandPreview ?? "") || undefined;
1252
- }
1253
- function formatFragmentedShellProgressDetails(summary) {
1254
- const descriptionMatch = summary.argumentsText?.match(/"description"\s*:\s*"([^"]+)"/);
1255
- if (descriptionMatch?.[1]) {
1256
- return sanitizeChannelProgressText(descriptionMatch[1], MAX_PROGRESS_DETAILS_LENGTH) || undefined;
1257
- }
1258
- return;
1259
- }
1260
- function formatSubagentProgressDetailsFromArguments(parsedArguments) {
1261
- const preview = firstNonEmptyString(parsedArguments.prompt, parsedArguments.description, parsedArguments.subject);
1262
- const sanitized = sanitizeChannelProgressText(preview, MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH);
1263
- return sanitized || undefined;
1264
- }
1265
- function formatFragmentedSubagentProgressDetails(summary) {
1266
- const previewMatch = summary.argumentsText?.match(/"(?:prompt|description|subject)"\s*:\s*"([^"]+)"/);
1267
- if (!previewMatch?.[1]) {
1268
- return;
1269
- }
1270
- const sanitized = sanitizeChannelProgressText(previewMatch[1], MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH);
1271
- return sanitized || undefined;
1272
- }
1273
- function parseToolArguments(value) {
1274
- if (!value) {
1275
- return null;
1276
- }
1277
- try {
1278
- return asRecord(JSON.parse(value));
1279
- } catch {
1280
- return null;
1281
- }
1282
- }
1283
- function isFetchWebpageToolName(name) {
1284
- return name === "fetch_webpage" || name === "FetchWebpage" || name === "fetchWebpage";
1285
- }
1286
- function isSkillToolName(name) {
1287
- if (!name) {
1288
- return false;
1289
- }
1290
- const normalized = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : name;
1291
- return normalized === "Skill" || normalized === "skill";
1292
- }
1293
- function isFilePathToolName(name) {
1294
- return isFileReadTool(name) || isFileWriteTool(name) || isFileEditTool(name);
1295
- }
1296
- function getFileToolKind(name) {
1297
- if (isFileReadTool(name)) {
1298
- return "read";
1299
- }
1300
- if (isFileWriteTool(name)) {
1301
- return "write";
1302
- }
1303
- if (isFileEditTool(name)) {
1304
- return "update";
1305
- }
1306
- return null;
1307
- }
1308
- function countProgressLines(value) {
1309
- return value ? value.split(`
1310
- `).length : 0;
1311
- }
1312
- function formatLineChangeSummary(summary) {
1313
- if (!summary) {
1314
- return "";
1315
- }
1316
- const parts = [];
1317
- if (summary.additions !== undefined) {
1318
- parts.push(`+${summary.additions}`);
1319
- }
1320
- if (summary.deletions !== undefined) {
1321
- parts.push(`-${summary.deletions}`);
1322
- }
1323
- return parts.length > 0 ? ` ${parts.join(" ")}` : "";
1324
- }
1325
- function extractFilePathFromArguments(parsedArguments) {
1326
- return firstNonEmptyString(parsedArguments.file_path, parsedArguments.filePath, parsedArguments.path);
1327
- }
1328
- function formatProgressFileName(filePath) {
1329
- if (!filePath) {
1330
- return;
1331
- }
1332
- const fileName = getPathBaseName(filePath) || filePath;
1333
- return sanitizeChannelProgressText(fileName, MAX_PROGRESS_DETAILS_LENGTH) || undefined;
1334
- }
1335
- function getEditLineChangeSummary(parsedArguments) {
1336
- const oldString = firstNonEmptyString(parsedArguments.old_string);
1337
- const newString = firstNonEmptyString(parsedArguments.new_string);
1338
- if (oldString === undefined || newString === undefined) {
1339
- return null;
1340
- }
1341
- return {
1342
- additions: countProgressLines(newString),
1343
- deletions: countProgressLines(oldString)
1344
- };
1345
- }
1346
- function getWriteLineChangeSummary(parsedArguments) {
1347
- const content = firstNonEmptyString(parsedArguments.content);
1348
- if (content === undefined) {
1349
- return null;
1350
- }
1351
- return {
1352
- additions: countProgressLines(content)
1353
- };
1354
- }
1355
- function getFileLineChangeSummary(name, parsedArguments) {
1356
- if (isFileWriteTool(name)) {
1357
- return getWriteLineChangeSummary(parsedArguments);
1358
- }
1359
- if (isFileEditTool(name)) {
1360
- return getEditLineChangeSummary(parsedArguments);
1361
- }
1362
- return null;
1363
- }
1364
- function getFileToolVerb(kind, status) {
1365
- if (status === "error") {
1366
- if (kind === "read") {
1367
- return "Tried to read";
1368
- }
1369
- if (kind === "write") {
1370
- return "Tried to write";
1371
- }
1372
- return "Tried to update";
1373
- }
1374
- if (status === "started") {
1375
- if (kind === "read") {
1376
- return "Reading";
1377
- }
1378
- if (kind === "write") {
1379
- return "Writing";
1380
- }
1381
- return "Updating";
1382
- }
1383
- if (kind === "read") {
1384
- return "Read";
1385
- }
1386
- if (kind === "write") {
1387
- return "Wrote";
1388
- }
1389
- return "Updated";
1390
- }
1391
- function formatFileToolProgressTitle(name, parsedArguments, status) {
1392
- const kind = getFileToolKind(name);
1393
- if (!kind) {
1394
- return;
1395
- }
1396
- const fileName = formatProgressFileName(extractFilePathFromArguments(parsedArguments));
1397
- if (!fileName) {
1398
- return;
1399
- }
1400
- const stats = status === "completed" ? formatLineChangeSummary(getFileLineChangeSummary(name, parsedArguments)) : "";
1401
- return `${getFileToolVerb(kind, status)} ${fileName}${stats}`;
1402
- }
1403
- function formatFragmentedFileToolProgressTitle(summary, status) {
1404
- if (!summary.name || !summary.argumentsText) {
1405
- return;
1406
- }
1407
- const kind = getFileToolKind(summary.name);
1408
- if (!kind) {
1409
- return;
1410
- }
1411
- const filePathMatch = summary.argumentsText.match(/"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/);
1412
- const fileName = formatProgressFileName(filePathMatch?.[1]);
1413
- if (!fileName) {
1414
- return;
1415
- }
1416
- return `${getFileToolVerb(kind, status)} ${fileName}`;
1417
- }
1418
- function formatToolProgressTitle(summary, status) {
1419
- if (!summary.name || !summary.argumentsText) {
1420
- return;
1421
- }
1422
- const parsedArguments = parseToolArguments(summary.argumentsText);
1423
- if (parsedArguments) {
1424
- if (isSkillToolName(summary.name)) {
1425
- return formatSkillProgressTitleFromName(getSkillNameFromArguments(parsedArguments));
1426
- }
1427
- if (isFilePathToolName(summary.name)) {
1428
- return formatFileToolProgressTitle(summary.name, parsedArguments, status);
1429
- }
1430
- return;
1431
- }
1432
- if (isSkillToolName(summary.name)) {
1433
- return formatSkillProgressTitleFromName(getFragmentedSkillName(summary));
1434
- }
1435
- if (isFilePathToolName(summary.name)) {
1436
- return formatFragmentedFileToolProgressTitle(summary, status);
1437
- }
1438
- return;
1439
- }
1440
- function formatSkillProgressDetailsFromArguments(parsedArguments, options) {
1441
- const skillName = getSkillNameFromArguments(parsedArguments);
1442
- const detail = resolveSkillDescription(skillName, options) ?? skillName;
1443
- const sanitized = sanitizeChannelProgressText(detail, MAX_PROGRESS_DETAILS_LENGTH);
1444
- return sanitized || undefined;
1445
- }
1446
- function formatFragmentedSkillProgressDetails(summary, options) {
1447
- const skillName = getFragmentedSkillName(summary);
1448
- const detail = resolveSkillDescription(skillName, options) ?? skillName;
1449
- const sanitized = sanitizeChannelProgressText(detail, MAX_PROGRESS_DETAILS_LENGTH);
1450
- return sanitized || undefined;
1451
- }
1452
- function formatToolProgressDetails(summary, options) {
1453
- if (!summary.name || !summary.argumentsText) {
1454
- return;
1455
- }
1456
- const parsedArguments = parseToolArguments(summary.argumentsText);
1457
- if (parsedArguments) {
1458
- if (isWebSearchTool(summary.name)) {
1459
- const query = firstNonEmptyString(parsedArguments.query);
1460
- const sanitized = sanitizeChannelProgressText(query, MAX_PROGRESS_DETAILS_LENGTH);
1461
- return sanitized || undefined;
1462
- }
1463
- if (isFetchWebpageToolName(summary.name)) {
1464
- const url = firstNonEmptyString(parsedArguments.url);
1465
- const sanitized = sanitizeChannelProgressText(url, MAX_PROGRESS_DETAILS_LENGTH);
1466
- return sanitized || undefined;
1467
- }
1468
- if (isSkillToolName(summary.name)) {
1469
- return formatSkillProgressDetailsFromArguments(parsedArguments, options);
1470
- }
1471
- if (isTaskTool(summary.name)) {
1472
- return formatSubagentProgressDetailsFromArguments(parsedArguments);
1473
- }
1474
- if (isShellTool(summary.name)) {
1475
- return formatShellProgressDetailsFromArguments(parsedArguments);
1476
- }
1477
- if (isFilePathToolName(summary.name)) {
1478
- const filePath = firstNonEmptyString(parsedArguments.file_path, parsedArguments.filePath, parsedArguments.path);
1479
- const sanitized = sanitizeChannelProgressText(filePath, MAX_PROGRESS_DETAILS_LENGTH);
1480
- return sanitized || undefined;
1481
- }
1482
- if (isGlobTool(summary.name) || isSearchTool(summary.name)) {
1483
- const pattern = firstNonEmptyString(parsedArguments.pattern);
1484
- const sanitized = sanitizeChannelProgressText(pattern, MAX_PROGRESS_DETAILS_LENGTH);
1485
- return sanitized || undefined;
1486
- }
1487
- return;
1488
- }
1489
- if (isShellTool(summary.name)) {
1490
- return formatFragmentedShellProgressDetails(summary);
1491
- }
1492
- if (isSkillToolName(summary.name)) {
1493
- return formatFragmentedSkillProgressDetails(summary, options);
1494
- }
1495
- if (isTaskTool(summary.name)) {
1496
- return formatFragmentedSubagentProgressDetails(summary);
1497
- }
1498
- if (isFilePathToolName(summary.name)) {
1499
- const filePathMatch = summary.argumentsText.match(/"file_path"\s*:\s*"([^"]+)"/);
1500
- if (filePathMatch?.[1]) {
1501
- const sanitized = sanitizeChannelProgressText(filePathMatch[1], MAX_PROGRESS_DETAILS_LENGTH);
1502
- return sanitized || undefined;
1503
- }
1504
- }
1505
- return;
1506
- }
1507
-
1508
- // src/channels/progress-builder.ts
1509
- function getMessageType(delta) {
1510
- return firstNonEmptyString(delta.message_type, delta.messageType) ?? null;
1511
- }
1512
- function getRunId(delta) {
1513
- return firstNonEmptyString(delta.run_id, delta.runId);
1514
- }
1515
- function withRunId(update, runId) {
1516
- return {
1517
- ...update,
1518
- ...runId ? { runId } : {}
1519
- };
1520
- }
1521
- function getCommandId(delta) {
1522
- const command = firstNonEmptyString(delta.command_id, delta.commandId);
1523
- return sanitizeChannelProgressIdentifier(command, "command");
1524
- }
1525
- function getSlashCommand(delta) {
1526
- const commandId = firstNonEmptyString(delta.command_id, delta.commandId);
1527
- const command = commandId ? `/${commandId.replace(/^\/+/, "")}` : "command";
1528
- return sanitizeChannelProgressIdentifier(command, "command");
1529
- }
1530
- function getToolStatus(delta) {
1531
- const status = firstNonEmptyString(delta.status)?.toLowerCase();
1532
- return status === "error" || status === "failed" ? "error" : "completed";
1533
- }
1534
- function stringifyProgressValue(value) {
1535
- if (typeof value === "string") {
1536
- return value;
1537
- }
1538
- if (value === undefined || value === null) {
1539
- return;
1540
- }
1541
- try {
1542
- return JSON.stringify(value);
1543
- } catch {
1544
- return String(value);
1545
- }
1546
- }
1547
- function formatToolErrorDetails(record) {
1548
- const toolReturn = record.tool_return ?? record.toolReturn;
1549
- const toolReturnRecord = asRecord(toolReturn);
1550
- const preview = firstNonEmptyString(record.stderr, record.error, record.message, toolReturnRecord?.stderr, toolReturnRecord?.error, toolReturnRecord?.message, toolReturnRecord?.output, stringifyProgressValue(toolReturn));
1551
- const sanitized = sanitizeChannelProgressText(preview, MAX_PROGRESS_DETAILS_LENGTH);
1552
- return sanitized || undefined;
1553
- }
1554
- function toolNameForMessage(summary) {
1555
- return summary?.name ? `: ${summary.name}` : "";
1556
- }
1557
- function createChannelTurnProgressBuilder(options = {}) {
1558
- const argumentsByToolCallId = new Map;
1559
- const namesByToolCallId = new Map;
1560
- const batchesByStep = new Map;
1561
- const batchesByToolCallId = new Map;
1562
- function addToolBatchTitles(delta, updates) {
1563
- const record = asRecord(delta);
1564
- if (!record)
1565
- return updates;
1566
- const messageType = getMessageType(record);
1567
- const isToolRequest = messageType === "tool_call_message" || messageType === "approval_request_message";
1568
- const stepKey = isToolRequest ? firstNonEmptyString(record.step_id, record.id) : undefined;
1569
- let requestBatch = stepKey ? batchesByStep.get(stepKey) : undefined;
1570
- if (stepKey && !requestBatch) {
1571
- requestBatch = { title: null };
1572
- batchesByStep.set(stepKey, requestBatch);
1573
- }
1574
- return updates.map((update) => {
1575
- if (update.kind !== "tool")
1576
- return update;
1577
- const batch = (update.toolCallId ? batchesByToolCallId.get(update.toolCallId) : undefined) ?? requestBatch;
1578
- if (!batch)
1579
- return update;
1580
- if (update.toolCallId)
1581
- batchesByToolCallId.set(update.toolCallId, batch);
1582
- if (batch.title === null && update.state === "started") {
1583
- batch.title = firstNonEmptyString(update.toolTitle, update.toolDetails) ?? null;
1584
- }
1585
- return { ...update, toolBatchTitle: batch.title };
1586
- });
1587
- }
1588
- function extractToolCallSummary(value) {
1589
- const record = asRecord(value);
1590
- if (!record) {
1591
- return null;
1592
- }
1593
- const id = firstNonEmptyString(record.tool_call_id);
1594
- const cacheId = id ? sanitizeChannelProgressIdentifier(id, "tool-call") : undefined;
1595
- const extractedName = firstNonEmptyString(record.name);
1596
- if (cacheId && extractedName) {
1597
- namesByToolCallId.set(cacheId, extractedName);
1598
- }
1599
- const resolvedName = extractedName ?? (cacheId ? namesByToolCallId.get(cacheId) : undefined);
1600
- const rawArguments = typeof record.arguments === "string" && record.arguments.length > 0 ? record.arguments : asRecord(record.arguments) ? JSON.stringify(record.arguments) : undefined;
1601
- let argumentsText;
1602
- if (cacheId && rawArguments !== undefined) {
1603
- const existing = argumentsByToolCallId.get(cacheId);
1604
- if (parseToolArguments(rawArguments)) {
1605
- argumentsByToolCallId.set(cacheId, rawArguments);
1606
- argumentsText = rawArguments;
1607
- } else if (existing) {
1608
- if (parseToolArguments(existing)) {
1609
- argumentsText = existing;
1610
- } else {
1611
- const accumulated = existing + rawArguments;
1612
- argumentsByToolCallId.set(cacheId, accumulated);
1613
- argumentsText = accumulated;
1614
- }
1615
- } else {
1616
- argumentsByToolCallId.set(cacheId, rawArguments);
1617
- argumentsText = rawArguments;
1618
- }
1619
- } else if (!id && rawArguments !== undefined) {
1620
- argumentsText = rawArguments;
1621
- }
1622
- if (!id && !resolvedName) {
1623
- return null;
1624
- }
1625
- return {
1626
- ...cacheId ? { id: cacheId } : {},
1627
- ...resolvedName ? { name: sanitizeChannelProgressIdentifier(resolvedName, "tool") } : {},
1628
- ...argumentsText ? { argumentsText } : {}
1629
- };
1630
- }
1631
- function extractClientToolSummary(record) {
1632
- const id = firstNonEmptyString(record.tool_call_id, record.toolCallId);
1633
- const cacheId = id ? sanitizeChannelProgressIdentifier(id, "tool-call") : undefined;
1634
- const extractedName = firstNonEmptyString(record.tool_name, record.toolName, record.name);
1635
- if (cacheId && extractedName) {
1636
- namesByToolCallId.set(cacheId, extractedName);
1637
- }
1638
- const resolvedName = extractedName ?? (cacheId ? namesByToolCallId.get(cacheId) : undefined);
1639
- const rawArguments = firstNonEmptyString(record.tool_args, record.toolArgs, record.arguments);
1640
- if (cacheId && rawArguments) {
1641
- argumentsByToolCallId.set(cacheId, rawArguments);
1642
- }
1643
- const argumentsText = rawArguments ?? (cacheId ? argumentsByToolCallId.get(cacheId) : undefined);
1644
- if (!cacheId && !resolvedName) {
1645
- return null;
1646
- }
1647
- return {
1648
- ...cacheId ? { id: cacheId } : {},
1649
- ...resolvedName ? { name: sanitizeChannelProgressIdentifier(resolvedName, "tool") } : {},
1650
- ...argumentsText ? { argumentsText } : {}
1651
- };
1652
- }
1653
- function extractToolCalls(delta) {
1654
- const candidates = Array.isArray(delta.tool_calls) ? delta.tool_calls : delta.tool_calls ? [delta.tool_calls] : delta.tool_call ? [delta.tool_call] : [];
1655
- const summaries = [];
1656
- const seen = new Set;
1657
- for (const candidate of candidates) {
1658
- const summary = extractToolCallSummary(candidate);
1659
- if (!summary) {
1660
- continue;
1661
- }
1662
- const key = `${summary.id ?? ""}:${summary.name ?? ""}`;
1663
- if (seen.has(key)) {
1664
- continue;
1665
- }
1666
- seen.add(key);
1667
- summaries.push(summary);
1668
- }
1669
- return summaries;
1670
- }
1671
- function extractToolReturns(delta) {
1672
- const candidates = Array.isArray(delta.tool_returns) ? delta.tool_returns : [delta];
1673
- const summaries = [];
1674
- const seen = new Set;
1675
- for (const candidate of candidates) {
1676
- const record = asRecord(candidate);
1677
- if (!record) {
1678
- continue;
1679
- }
1680
- const summary = extractToolCallSummary(record);
1681
- if (!summary) {
1682
- continue;
1683
- }
1684
- const key = `${summary.id ?? ""}:${summary.name ?? ""}`;
1685
- if (seen.has(key)) {
1686
- continue;
1687
- }
1688
- seen.add(key);
1689
- const status = getToolStatus(record);
1690
- summaries.push({
1691
- summary,
1692
- status,
1693
- ...status === "error" ? { errorDetails: formatToolErrorDetails(record) } : {}
1694
- });
1695
- }
1696
- return summaries;
1697
- }
1698
- function buildToolCallUpdates(record, runId) {
1699
- const tools = extractToolCalls(record);
1700
- const updates = [];
1701
- for (const tool of tools) {
1702
- const toolDetails = formatToolProgressDetails(tool, options);
1703
- const toolTitle = formatToolProgressTitle(tool, "started");
1704
- updates.push(withRunId({
1705
- kind: "tool",
1706
- state: "started",
1707
- message: `Preparing tool${toolNameForMessage(tool)}`,
1708
- ...tool.id ? { toolCallId: tool.id } : {},
1709
- ...tool.name ? { toolName: tool.name } : {},
1710
- ...toolDetails ? { toolDetails } : {},
1711
- ...toolTitle ? { toolTitle } : {}
1712
- }, runId));
1713
- }
1714
- return updates;
1715
- }
1716
- function buildUpdates(delta) {
1717
- const record = asRecord(delta);
1718
- if (!record) {
1719
- return [];
1720
- }
1721
- const messageType = getMessageType(record);
1722
- const runId = getRunId(record);
1723
- switch (messageType) {
1724
- case "reasoning_message":
1725
- return [
1726
- withRunId({
1727
- kind: "thinking",
1728
- state: "updated",
1729
- message: "Thinking"
1730
- }, runId)
1731
- ];
1732
- case "assistant_message":
1733
- return [
1734
- withRunId({
1735
- kind: "responding",
1736
- state: "updated",
1737
- message: "Writing reply"
1738
- }, runId)
1739
- ];
1740
- case "approval_request_message":
1741
- return buildToolCallUpdates(record, runId);
1742
- case "tool_call_message": {
1743
- const updates = buildToolCallUpdates(record, runId);
1744
- if (updates.length === 0) {
1745
- return [
1746
- withRunId({
1747
- kind: "tool",
1748
- state: "started",
1749
- message: "Preparing tool call"
1750
- }, runId)
1751
- ];
1752
- }
1753
- return updates;
1754
- }
1755
- case "tool_return_message": {
1756
- const toolReturns = extractToolReturns(record);
1757
- const updates = [];
1758
- for (const { summary, status, errorDetails } of toolReturns) {
1759
- const accumulatedArgs = summary.id ? argumentsByToolCallId.get(summary.id) : undefined;
1760
- if (summary.id) {
1761
- argumentsByToolCallId.delete(summary.id);
1762
- namesByToolCallId.delete(summary.id);
1763
- }
1764
- const toolWithAccumulatedArgs = accumulatedArgs ? { ...summary, argumentsText: accumulatedArgs } : summary;
1765
- const toolDetails = formatToolProgressDetails(toolWithAccumulatedArgs, options);
1766
- const toolTitle = formatToolProgressTitle(toolWithAccumulatedArgs, status);
1767
- updates.push(withRunId({
1768
- kind: "tool",
1769
- state: status,
1770
- message: status === "error" ? "Tool failed" : "Tool finished",
1771
- ...summary.id ? { toolCallId: summary.id } : {},
1772
- ...summary.name ? { toolName: summary.name } : {},
1773
- ...toolDetails ? { toolDetails } : {},
1774
- ...status === "error" && errorDetails ? { errorDetails } : {},
1775
- ...toolTitle ? { toolTitle } : {}
1776
- }, runId));
1777
- }
1778
- return updates;
1779
- }
1780
- case "client_tool_start": {
1781
- const tool = extractClientToolSummary(record);
1782
- const toolDetails = tool ? formatToolProgressDetails(tool, options) : undefined;
1783
- const toolTitle = tool ? formatToolProgressTitle(tool, "started") : undefined;
1784
- return [
1785
- withRunId({
1786
- kind: "tool",
1787
- state: "started",
1788
- message: "Running tool",
1789
- ...tool?.id ? { toolCallId: tool.id } : {},
1790
- ...tool?.name ? { toolName: tool.name } : {},
1791
- ...toolDetails ? { toolDetails } : {},
1792
- ...toolTitle ? { toolTitle } : {}
1793
- }, runId)
1794
- ];
1795
- }
1796
- case "client_tool_end": {
1797
- const state = getToolStatus(record);
1798
- const tool = extractClientToolSummary(record);
1799
- const accumulatedArgs = tool?.id ? argumentsByToolCallId.get(tool.id) : undefined;
1800
- if (tool?.id) {
1801
- argumentsByToolCallId.delete(tool.id);
1802
- namesByToolCallId.delete(tool.id);
1803
- }
1804
- const toolWithAccumulatedArgs = tool && accumulatedArgs ? { ...tool, argumentsText: accumulatedArgs } : tool;
1805
- const toolDetails = toolWithAccumulatedArgs ? formatToolProgressDetails(toolWithAccumulatedArgs, options) : undefined;
1806
- const errorDetails = state === "error" ? formatToolErrorDetails(record) : undefined;
1807
- const toolTitle = toolWithAccumulatedArgs ? formatToolProgressTitle(toolWithAccumulatedArgs, state) : undefined;
1808
- return [
1809
- withRunId({
1810
- kind: "tool",
1811
- state,
1812
- message: state === "error" ? "Tool failed" : "Tool finished",
1813
- ...tool?.id ? { toolCallId: tool.id } : {},
1814
- ...tool?.name ? { toolName: tool.name } : {},
1815
- ...toolDetails ? { toolDetails } : {},
1816
- ...errorDetails ? { errorDetails } : {},
1817
- ...toolTitle ? { toolTitle } : {}
1818
- }, runId)
1819
- ];
1820
- }
1821
- case "slash_command_start": {
1822
- const command = getSlashCommand(record);
1823
- return [
1824
- withRunId({
1825
- kind: "command",
1826
- state: "started",
1827
- message: `Running ${command}`,
1828
- command
1829
- }, runId)
1830
- ];
1831
- }
1832
- case "slash_command_end": {
1833
- const command = getSlashCommand(record);
1834
- const success = record.success !== false;
1835
- return [
1836
- withRunId({
1837
- kind: "command",
1838
- state: success ? "completed" : "error",
1839
- message: success ? `${command} finished` : `${command} failed`,
1840
- command
1841
- }, runId)
1842
- ];
1843
- }
1844
- case "command_start": {
1845
- const command = getCommandId(record);
1846
- return [
1847
- withRunId({
1848
- kind: "command",
1849
- state: "started",
1850
- message: "Running command",
1851
- command
1852
- }, runId)
1853
- ];
1854
- }
1855
- case "command_end": {
1856
- const command = getCommandId(record);
1857
- const success = record.success !== false;
1858
- return [
1859
- withRunId({
1860
- kind: "command",
1861
- state: success ? "completed" : "error",
1862
- message: success ? "Command finished" : "Command failed",
1863
- command
1864
- }, runId)
1865
- ];
1866
- }
1867
- case "status": {
1868
- const message = sanitizeChannelProgressText(record.message);
1869
- if (!message) {
1870
- return [];
1871
- }
1872
- return [
1873
- withRunId({
1874
- kind: "status",
1875
- state: "updated",
1876
- message
1877
- }, runId)
1878
- ];
1879
- }
1880
- case "retry": {
1881
- const attempt = Number(record.attempt);
1882
- const maxAttempts = Number(record.max_attempts ?? record.maxAttempts);
1883
- const suffix = Number.isFinite(attempt) && Number.isFinite(maxAttempts) ? ` (${attempt}/${maxAttempts})` : "";
1884
- return [
1885
- withRunId({
1886
- kind: "retry",
1887
- state: "updated",
1888
- message: `Retrying request${suffix}`
1889
- }, runId)
1890
- ];
1891
- }
1892
- case "loop_error":
1893
- return [
1894
- withRunId({
1895
- kind: "error",
1896
- state: "error",
1897
- message: "Encountered an error"
1898
- }, runId)
1899
- ];
1900
- default:
1901
- return [];
1902
- }
1903
- }
1904
- return {
1905
- buildUpdates: (delta) => addToolBatchTitles(delta, buildUpdates(delta))
1906
- };
1907
- }
1908
- // src/channels/route-thread-key.ts
1909
- var CHANNEL_ROOT_THREAD_KEY = "__root__";
1910
- function resolveChannelRouteThreadKey(threadId) {
1911
- const trimmed = threadId?.trim();
1912
- return trimmed && trimmed.length > 0 ? trimmed : CHANNEL_ROOT_THREAD_KEY;
1913
- }
1914
- function channelRouteThreadIdFromKey(threadKey) {
1915
- const trimmed = threadKey?.trim();
1916
- if (!trimmed || trimmed === CHANNEL_ROOT_THREAD_KEY)
1917
- return null;
1918
- return trimmed;
1919
- }
1920
- export {
1921
- sanitizeChannelLifecycleErrorText,
1922
- runChannelReloadCommand,
1923
- runChannelReflectionCommand,
1924
- runChannelModelUpdateCommand,
1925
- runChannelModelListCommand,
1926
- runChannelCancelCommand,
1927
- resolveChannelRouteThreadKey,
1928
- parseChannelSlashCommand,
1929
- parseChannelModelCommand,
1930
- parseChannelBangCommand,
1931
- normalizeChannelLifecycleErrorMessage,
1932
- listChannelSlashCommands,
1933
- getChannelLifecycleErrorDisplay,
1934
- formatLettaStreamCoreErrorForChannel,
1935
- formatInboundChannelMessageForAgent,
1936
- formatChannelLifecycleErrorMessage,
1937
- formatBatchedChannelMessagesForAgent,
1938
- extractChannelLifecycleRunId,
1939
- escapeXmlText,
1940
- defaultChannelDisplayName,
1941
- createChannelTurnProgressBuilder,
1942
- collectLettaSseAssistantText,
1943
- channelRouteThreadIdFromKey,
1944
- buildUnsupportedChannelCommandMessage,
1945
- buildOutboundChannelMessageFromTurnSource,
1946
- buildChannelTurnSource,
1947
- buildChannelModelUpdatedMessage,
1948
- buildChannelModelUpdateFailedMessage,
1949
- buildChannelModelNotFoundText,
1950
- buildChannelModelListUnavailableMessage,
1951
- buildChannelModelListMessage,
1952
- buildChannelHelpMessage,
1953
- buildChannelCurrentModelUnavailableMessage,
1954
- buildChannelCurrentModelMessage,
1955
- buildChannelCancelNoActiveTurnMessage,
1956
- buildChannelCancelAcceptedMessage,
1957
- LettaStreamNoAssistantMessageError,
1958
- LettaStreamCoreError,
1959
- LETTA_STREAM_NO_ASSISTANT_MESSAGE_ERROR,
1960
- CHANNEL_ROOT_THREAD_KEY,
1961
- CHANNEL_LIFECYCLE_FALLBACK_ERROR_MESSAGE
1962
- };
1963
-
1964
- //# debugId=1C6C78F0606CFC2E64756E2164756E21