@segmentstream/agent 0.42.1 → 0.44.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 (130) hide show
  1. package/CHANGELOG.md +1033 -0
  2. package/README.md +25 -24
  3. package/dist/_chunks/{build-metadata-BPEZ5XVM.mjs → build-metadata-BnufKOxq.mjs} +1 -1
  4. package/dist/_chunks/{inbound-request-DgQB4g1J.mjs → inbound-request-CK0QqEOP.mjs} +36 -1
  5. package/dist/_chunks/{principal-BIX7T6Hh.mjs → principal-BXvelsZk.mjs} +5 -5
  6. package/dist/extension/channels/telegram.mjs +1 -1
  7. package/dist/extension/channels/whatsapp.mjs +1 -1
  8. package/dist/extension/config.d.ts +26 -18
  9. package/dist/extension/config.mjs +65 -12
  10. package/dist/extension/conventions.d.ts +1 -1
  11. package/dist/extension/conventions.mjs +22 -19
  12. package/dist/extension/extension.d.ts +2 -2
  13. package/dist/extension/extension.mjs +3 -3
  14. package/dist/extension/hooks/authorization.mjs +1 -1
  15. package/dist/extension/hooks/{conversations.mjs → chat-recorder.mjs} +4 -4
  16. package/dist/extension/hooks/sandbox.d.ts +2 -2
  17. package/dist/extension/instructions/{conversations.mjs → chat-context.mjs} +2 -2
  18. package/dist/extension/instructions/persona.mjs +1 -1
  19. package/dist/extension/instructions/sandbox.mjs +2 -2
  20. package/dist/extension/instructions.md +10 -10
  21. package/dist/extension/lib/actor.mjs +1 -1
  22. package/dist/extension/lib/attachment-tools.d.ts +1 -1
  23. package/dist/extension/lib/attachment-tools.mjs +7 -7
  24. package/dist/extension/lib/attachments.d.ts +9 -4
  25. package/dist/extension/lib/attachments.mjs +9 -7
  26. package/dist/extension/lib/build-metadata.mjs +1 -1
  27. package/dist/extension/lib/chat-address.d.ts +33 -0
  28. package/dist/extension/lib/{conversation.mjs → chat-address.mjs} +13 -12
  29. package/dist/extension/lib/{conversations.d.ts → chat-archive.d.ts} +12 -12
  30. package/dist/extension/lib/{conversations.mjs → chat-archive.mjs} +9 -9
  31. package/dist/extension/lib/chat-context.d.ts +5 -5
  32. package/dist/extension/lib/chat-context.mjs +7 -7
  33. package/dist/extension/lib/{conversation-runtime.d.ts → chat-recorder.d.ts} +3 -3
  34. package/dist/extension/lib/{conversation-runtime.mjs → chat-recorder.mjs} +13 -13
  35. package/dist/extension/lib/confirmations.d.ts +3 -3
  36. package/dist/extension/lib/confirmations.mjs +8 -8
  37. package/dist/extension/lib/group-routing/addressing.d.ts +1 -1
  38. package/dist/extension/lib/group-routing/addressing.mjs +2 -2
  39. package/dist/extension/lib/group-routing/burst.mjs +2 -2
  40. package/dist/extension/lib/group-routing/{conversation-prompt.d.ts → chat-prompt.d.ts} +2 -2
  41. package/dist/extension/lib/group-routing/{conversation-prompt.mjs → chat-prompt.mjs} +3 -3
  42. package/dist/extension/lib/group-routing/{conversation-router.d.ts → chat-router.d.ts} +6 -6
  43. package/dist/extension/lib/group-routing/{conversation-router.mjs → chat-router.mjs} +9 -9
  44. package/dist/extension/lib/group-routing/engagement.mjs +2 -2
  45. package/dist/extension/lib/group-routing/messages.d.ts +1 -1
  46. package/dist/extension/lib/group-routing/policy.d.ts +6 -6
  47. package/dist/extension/lib/group-routing/policy.mjs +16 -16
  48. package/dist/extension/lib/group-routing/replay.mjs +36 -9
  49. package/dist/extension/lib/group-routing/router.d.ts +3 -3
  50. package/dist/extension/lib/group-routing/router.mjs +16 -16
  51. package/dist/extension/lib/group-routing/routing-context.d.ts +2 -2
  52. package/dist/extension/lib/group-routing/routing-context.mjs +2 -2
  53. package/dist/extension/lib/group-routing/signals.d.ts +3 -3
  54. package/dist/extension/lib/group-routing/signals.mjs +5 -5
  55. package/dist/extension/lib/model-service-alert.d.ts +2 -2
  56. package/dist/extension/lib/model-service-alert.mjs +2 -2
  57. package/dist/extension/lib/ontology-connection.mjs +1 -1
  58. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  59. package/dist/extension/lib/ontology-tools.mjs +1 -1
  60. package/dist/extension/lib/review/hold.d.ts +7 -7
  61. package/dist/extension/lib/review/hold.mjs +12 -12
  62. package/dist/extension/lib/review/judge.d.ts +9 -9
  63. package/dist/extension/lib/review/judge.mjs +12 -12
  64. package/dist/extension/lib/review/reply.d.ts +13 -13
  65. package/dist/extension/lib/review/reply.mjs +20 -20
  66. package/dist/extension/lib/role-skill.mjs +1 -1
  67. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  68. package/dist/extension/lib/sent-files.mjs +3 -2
  69. package/dist/extension/lib/slack/adapter.mjs +2 -2
  70. package/dist/extension/lib/slack/attachments-send.d.ts +2 -2
  71. package/dist/extension/lib/slack/attachments-send.mjs +6 -6
  72. package/dist/extension/lib/slack/files.mjs +4 -4
  73. package/dist/extension/lib/stored-files.mjs +1 -1
  74. package/dist/extension/lib/telegram/adapter.d.ts +4 -3
  75. package/dist/extension/lib/telegram/adapter.mjs +35 -15
  76. package/dist/extension/lib/telegram/app-links.d.ts +39 -0
  77. package/dist/extension/lib/telegram/app-links.mjs +53 -0
  78. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  79. package/dist/extension/lib/telegram/attachments-send.mjs +2 -2
  80. package/dist/extension/lib/telegram/callbacks.mjs +2 -2
  81. package/dist/extension/lib/telegram/{conversations.d.ts → chat-archive.d.ts} +7 -7
  82. package/dist/extension/lib/telegram/{conversations.mjs → chat-archive.mjs} +11 -11
  83. package/dist/extension/lib/telegram/confirmation-text.mjs +1 -0
  84. package/dist/extension/lib/telegram/confirmations.d.ts +2 -2
  85. package/dist/extension/lib/telegram/confirmations.mjs +4 -4
  86. package/dist/extension/lib/telegram/customer-text.d.ts +2 -1
  87. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  88. package/dist/extension/lib/telegram/delivery-diagnostics.d.ts +3 -3
  89. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +2 -2
  90. package/dist/extension/lib/telegram/files.d.ts +1 -1
  91. package/dist/extension/lib/telegram/files.mjs +9 -9
  92. package/dist/extension/lib/telegram/health.mjs +1 -1
  93. package/dist/extension/lib/telegram/images.mjs +1 -1
  94. package/dist/extension/lib/telegram/inbound-request.d.ts +1 -1
  95. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  96. package/dist/extension/lib/telegram/inbound.d.ts +3 -3
  97. package/dist/extension/lib/telegram/inbound.mjs +37 -37
  98. package/dist/extension/lib/telegram/lifecycle.mjs +4 -4
  99. package/dist/extension/lib/telegram/media-policy.mjs +1 -1
  100. package/dist/extension/lib/telegram/principal.d.ts +2 -2
  101. package/dist/extension/lib/telegram/principal.mjs +1 -1
  102. package/dist/extension/lib/telegram/router.mjs +2 -2
  103. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  104. package/dist/extension/lib/telegram/sessions.d.ts +1 -1
  105. package/dist/extension/lib/telegram/signals.mjs +1 -1
  106. package/dist/extension/lib/telegram/silent.d.ts +2 -2
  107. package/dist/extension/lib/telegram/silent.mjs +1 -1
  108. package/dist/extension/lib/telegram/structured.mjs +1 -1
  109. package/dist/extension/lib/telegram/turn-errors.d.ts +2 -2
  110. package/dist/extension/lib/telegram/turn-errors.mjs +3 -3
  111. package/dist/extension/lib/telegram/voice.d.ts +1 -1
  112. package/dist/extension/lib/telegram/voice.mjs +1 -1
  113. package/dist/extension/lib/whatsapp/adapter.d.ts +2 -2
  114. package/dist/extension/lib/whatsapp/adapter.mjs +4 -2
  115. package/dist/extension/lib/whatsapp/links.d.ts +12 -0
  116. package/dist/extension/lib/whatsapp/links.mjs +34 -0
  117. package/dist/extension/lib/workflow-serializable.d.ts +1 -1
  118. package/dist/extension/model.mjs +1 -1
  119. package/dist/extension/personas.d.ts +1 -1
  120. package/dist/extension/review.d.ts +23 -20
  121. package/dist/extension/review.mjs +21 -34
  122. package/dist/extension/tools/attachments_promote.mjs +1 -1
  123. package/dist/extension/tools/attachments_send.mjs +3 -3
  124. package/dist/extension/tools/no_reply.d.ts +1 -1
  125. package/dist/extension/tools/questions_ask.mjs +4 -4
  126. package/dist/extension/tools/sandbox.mjs +2 -2
  127. package/package.json +3 -2
  128. package/dist/extension/lib/conversation.d.ts +0 -33
  129. /package/dist/extension/hooks/{conversations.d.ts → chat-recorder.d.ts} +0 -0
  130. /package/dist/extension/instructions/{conversations.d.ts → chat-context.d.ts} +0 -0
package/README.md CHANGED
@@ -114,6 +114,7 @@ See [Sandbox](#sandbox).
114
114
  | `channels.telegram.policy` | `"smart"` | Classifies unaddressed group messages and captionless uploads; `mention` observes unaddressed messages without decoding or inference |
115
115
  | `channels.telegram.linkPreviews` | `external` | Suppress own-workspace previews and preview the first external link; opt into `all` for native previews or `none` to disable them. Caller options take precedence. |
116
116
  | `channels.telegram.additionalOwnOrigins` | `[]` | Additional exact HTTP(S) workspace origins, including local ports; no paths or credentials. |
117
+ | `channels.telegram.appLinks` | `"web"` | `"miniApp"` opens links to the app's own pages in the bot's Main Mini App (`t.me/<bot>?startapp=…`) as messages are delivered; see `docs/agent.md` |
117
118
  | `channels.telegram.interimMessages` | `false` | `true` delivers the text the model writes before calling tools as its own message, like a reply; see [Telegram answer delivery](#telegram-answer-delivery) |
118
119
  | `models.stt` | `"spacexai/grok-stt"` | The AI Gateway transcription model for voice messages; `false` leaves them untranscribed |
119
120
  | `models.imageDescription` | `google/gemini-2.5-flash-lite` | Image evidence for group routing even with native vision; `false` disables descriptions |
@@ -121,7 +122,7 @@ See [Sandbox](#sandbox).
121
122
  | `ontology.connection` | `true` | Whether the agent reaches the ontology over MCP |
122
123
  | `sandbox` | `false` | `true` adds `bash`, `read_file` and `write_file` in the agent's sandbox without network; see [Sandbox](#sandbox) |
123
124
  | `personas` | none | `{ "byRole": { role: persona }, "default": persona }`: who the agent is to the person; see [Personas and skills by role](#personas-and-skills-by-role) |
124
- | `conversations` | none | `{ "byRole": { role: { "review": … } }, "default": { "review": … } }`: who sends replies; see [Reply review](#reply-review) |
125
+ | `review` | none | `{ "byRole": { role: { "mode": … } }, "default": { "mode": … } }`: who sends replies; see [Reply review](#reply-review) |
125
126
 
126
127
  An unknown field or an invalid value fails the mount with `SegmentStreamAgentConfigError`, naming
127
128
  each path. `manifestOf(config)` returns the normalized configuration, defaults applied, for the
@@ -130,8 +131,8 @@ platform's deployment manifest.
130
131
  ## Personas and skills by role
131
132
 
132
133
  The shared instructions (`agent/agent/instructions.md`) reach everyone the agent talks to. A
133
- persona, `agent/personas/<name>.md`, says who the agent is to the person in a conversation: one
134
- per conversation, the first `personas.byRole` entry whose role the person who started it holds,
134
+ persona, `agent/personas/<name>.md`, says who the agent is to the person in a session: one
135
+ per session, the first `personas.byRole` entry whose role the person who started it holds,
135
136
  else `personas.default`. The SDK reads each text when the agent is built and the platform puts it
136
137
  inline when it deploys, so the mount stays `segmentstream(config)`; the build fails when a named
137
138
  text is missing. Guidance for the group decision model lives the same way in
@@ -145,11 +146,11 @@ in the workspace agent guide.
145
146
 
146
147
  ## Reply review
147
148
 
148
- `conversations` says, per role of the person the agent replies to, who sends its replies on
149
+ `review` says, per role of the person the agent replies to, who sends its replies on
149
150
  Telegram and WhatsApp: `{ "review": { "mode": "never" } }` (the agent, the default),
150
151
  `{ "mode": "always" }` (a member reviews every reply) or
151
152
  `{ "mode": "whenUnsure", "minConfidence": 0.9 }` (the decision model judges each reply in its
152
- conversation, with the criteria in `agent/review/<role>.md`, and the agent sends those it is sure
153
+ chat, with the criteria in `agent/review/<role>.md`, and the agent sends those it is sure
153
154
  enough of). A held reply becomes an `agent_review` record of the ontology, which a member
154
155
  approves, edits or rejects. See [reply review](../../docs/agent.md#reply-review) in the workspace
155
156
  agent guide.
@@ -261,7 +262,7 @@ continue using GET lookup. Starter templates and pins remain unchanged in this s
261
262
  | `segmentstream__bash`, `_read_file`, `_write_file` | `tools` | With `"sandbox": true`: eve's file tools, only in the sandbox `@segmentstream/agent/sandbox` opened. |
262
263
  | `segmentstream__attachments_stage` | `tools` | With `"sandbox": true`: copies a chat attachment or a stored record's file, read as the member, into the sandbox. |
263
264
  | platform rules | `instructions` | Changes go through actions; `*_find` and `list_metrics` say what fields and metrics mean; `discover` ranks by meaning where listed; when to call `no_reply`; attachments |
264
- | chat context | `hooks`, `instructions` | Adds the chat messages a Telegram session has not seen, once, ahead of the turn; see [Durable conversations](#durable-conversations). |
265
+ | chat context | `hooks`, `instructions` | Adds the chat messages a Telegram session has not seen, once, ahead of the turn; see [Durable chats](#durable-chats). |
265
266
  | sandbox rules | `instructions` | With `"sandbox": true`: working copies, file contents as data, no network. |
266
267
  | sandbox cleanup | `hooks` | Deletes the session's sandbox when its history is cleared. |
267
268
 
@@ -373,7 +374,7 @@ The SDK adds no text to the prompt.
373
374
  - **The secret.** The route hands the secret to the session in the channel's adapter state; the
374
375
  session's first event moves it into the session's durable task state, and it is forgotten once
375
376
  the outcome is reported. It is never in the principal, the model's context, tool arguments or
376
- results, the session's events, logs or the conversation archive.
377
+ results, the session's events, logs or the chat archive.
377
378
  - **No person is present.** Ontology actions the workflow's role permits run without confirmation
378
379
  cards. Attachments, member files, chat history and `chat_post_message` are not offered. A
379
380
  question from `questions_ask`, an approval a tool asks a person for, eve's own questions or a
@@ -387,7 +388,7 @@ The SDK adds no text to the prompt.
387
388
  or when the ontology refuses the secret, the session ends: eve has no command for a session to
388
389
  retire itself, so it asks its own deployment's `POST /eve/segmentstream/v1/tasks/end`, which ends
389
390
  only the session that still owns the task's address.
390
- - **Logs.** The conversation archive keeps a task's events under provider `task` and the task's id,
391
+ - **Logs.** The chat archive keeps a task's events under provider `task` and the task's id,
391
392
  with no member taking part, so `segmentstream agent logs --chat <task id>` shows them.
392
393
 
393
394
  ### Telegram
@@ -414,14 +415,14 @@ The SDK adds no text to the prompt.
414
415
  `chatId`, `chatType` and `username`.
415
416
  - **Routing.** Private chats and messages explicitly addressed to the bot retain direct admission.
416
417
  Other group messages, including captionless attachments, go through one `decide` question with
417
- the agent's purpose, recent conversation, open questions and confirmation state. The legacy
418
+ the agent's purpose, recent chat, open questions and confirmation state. The legacy
418
419
  `mention` policy observes unaddressed messages without paid work. Attachments never force a turn.
419
420
  Human reply edges and other recipients are untrusted context for inference. Failed decisions
420
- observe, except within a conversation-policy `defer` band. Recent context comes from the
421
- conversation archive: observed and answered messages, delivered replies and confirmation cards;
421
+ observe, except within a chat-policy `defer` band. Recent context comes from the
422
+ chat archive: observed and answered messages, delivered replies and confirmation cards;
422
423
  retries add nothing. Decision events retain the reason, short audit note, model and latency, plus
423
424
  probabilities when available.
424
- - **Conversation addressing.** Opt in with `groups.smart.engagement.policy: "conversation"`.
425
+ - **Chat addressing.** Opt in with `groups.smart.engagement.policy: "chat"`.
425
426
  Code decides only explicit cases: a bot mention, command, agent vocative or reply to the agent
426
427
  goes to the agent; a reply to, tag of, or leading/trailing name of a person goes to that person.
427
428
  Every other message goes to the decision model with the chat's last `smart.context.messages`
@@ -481,7 +482,7 @@ The SDK adds no text to the prompt.
481
482
  no turn and drops the old chat from the memo. The `<chat>` block carries at most 1000
482
483
  characters of `whenToUse`.
483
484
  - **Cross-chat drafts.** The agent uses `chat_post_message` through its existing ontology
484
- connection, from a Telegram, Slack or WhatsApp conversation, into a Telegram chat or, when the
485
+ connection, from a Telegram, Slack or WhatsApp chat, into a Telegram chat or, when the
485
486
  ontology declares `chat.slack`, a Slack channel or a member's Slack DM, or, when it declares
486
487
  `chat.whatsapp`, another member's WhatsApp chat with the workspace's number (only inside Meta's
487
488
  24-hour customer-service window). The Slack channel reports
@@ -500,7 +501,7 @@ The SDK adds no text to the prompt.
500
501
  routes now serve only the inbound webhook and authenticated health; old instruction relay calls
501
502
  fail instead of starting an agent turn.
502
503
  - **Silence.** When the model calls `segmentstream__no_reply` (eve's `no_reply`), the turn ends
503
- without a message; the call and its reason are recorded in the session and the conversation
504
+ without a message; the call and its reason are recorded in the session and the chat
504
505
  archive like any tool call. Empty and whitespace-only final text also send nothing. The turn
505
506
  stays in the session. Archive decisions distinguish empty text and whitespace, retaining finish
506
507
  reason and character count without logging raw output. Model reply decisions do not prove
@@ -609,7 +610,7 @@ larger Telegram limits do not bypass it. Downloads are bounded even if storage u
609
610
  Exact chat posting accepts text only through the ontology's `chat_post_message`.
610
611
  There are no `document_ids` relay arguments, `AgentMessage` transport or
611
612
  `<agent_request>` turns. Stored file tools keep their member authorization in the
612
- current conversation; group purpose and document restrictions still apply.
613
+ current chat; group purpose and document restrictions still apply.
613
614
 
614
615
  ## Telegram answer delivery
615
616
 
@@ -653,7 +654,7 @@ Building the package needs Node.js 24, as eve does: `pnpm run build` runs `eve e
653
654
  which writes the agent-shaped `dist/extension` tree, its declarations and eve's compatibility
654
655
  manifest.
655
656
 
656
- SDK-authored tool results and conversation archive events normalize runtime values to JSON
657
+ SDK-authored tool results and chat archive events normalize runtime values to JSON
657
658
  before returning or encoding them. Exact decimal/bigint strings and binary byte views are
658
659
  preserved; conversion diagnostics identify the boundary and value path without logging payloads.
659
660
  Maps use entry arrays so distinct key types and object keys retain every entry. Native brand and
@@ -685,7 +686,7 @@ a provider token.
685
686
 
686
687
  Apache-2.0
687
688
 
688
- ## Durable conversations
689
+ ## Durable chats
689
690
 
690
691
  Production Telegram webhooks archive every receivable message in the platform database,
691
692
  including automated posts and unanswered messages. The extension also records replies,
@@ -713,7 +714,7 @@ applies bounded credential and file-byte redaction, and ingestion preserves the
713
714
  Deploy backend migration 0043/API before upgrading to agent SDK 0.6.10.
714
715
  `segmentstream agent logs` and its `show`/`call` commands read this content
715
716
  with a human Cloud session; all members with workspace access can read DMs too.
716
- Runtime/model/MCP conversation readers never receive these new fields. Telegram delivery diagnostics
717
+ Runtime/model/MCP chat readers never receive these new fields. Telegram delivery diagnostics
717
718
  retain their correlation reference, operation and redacted error in the same archive before the
718
719
  channel callback returns, so a notice remains diagnosable after runtime logs expire.
719
720
 
@@ -722,7 +723,7 @@ Platform REST reads, the workspace ontology's
722
723
  `chat_history` and `chat_search`, and the member REST facade enforce workspace/group
723
724
  permissions and DM participant/admin scope. Deploy the backend migration/API and upgrade the
724
725
  ontology SDK along with this extension. See the repository's
725
- [conversation storage guide](../../docs/agent-conversation-storage.md) for APIs, retention,
726
+ [chat storage guide](../../docs/agent-chat-storage.md) for APIs, retention,
726
727
  eve's existing storage, and Telegram's delivery limits.
727
728
 
728
729
  ### Exact chat posting protocol
@@ -745,11 +746,11 @@ The target/attribution are resolved again immediately before executing the froze
745
746
 
746
747
  The SDK constructs model-hidden `_segmentstream` metadata for approved runtime posts.
747
748
  It contains `version: 1`, `session_id` and `call_id`. A consumed, unexpired chat approval additionally
748
- supplies `operation_id`, the source conversation and `expected: { chat_id, digest }`. A Telegram
749
+ supplies `operation_id`, the source chat and `expected: { chat_id, digest }`. A Telegram
749
750
  source carries its chat, topic and message references. A Slack or WhatsApp source carries only
750
751
  `{ provider, chat_id, thread_id, kind, peer? }`: `kind` is `private` for a member's own direct
751
- conversation, whose `peer` is the member's id on the provider. The ontology refuses a source on a
752
- channel other than the member's verified pairing, and a post into the conversation it came from,
752
+ chat, whose `peer` is the member's id on the provider. The ontology refuses a source on a
753
+ channel other than the member's verified pairing, and a post into the chat it came from,
753
754
  including a private destination naming the same person. An ontology without this source form
754
755
  refuses a Slack or WhatsApp source before sending.
755
756
  The operation ID is `hq:` plus SHA-256 of the JSON array `[session_id, call_id]`; it stays stable
@@ -789,7 +790,7 @@ the unreachable run. The smart gate still decides whether to reply; observing a
789
790
  creates no session and sends no failure notice. Every deployment, independent request and
790
791
  cold start selects the same successor, and Eve hands it over between deployments like any
791
792
  healthy session. If the successor's own deployment is deleted later, the next successor
792
- follows the same rule, up to four in a row. Archived conversation context remains
793
+ follows the same rule, up to four in a row. Archived chat context remains
793
794
  available, but the inaccessible session's model history and pending inputs cannot migrate.
794
795
  `segmentstream history squash` deletes earlier deployments and so ends the sessions
795
796
  they own; each affected address continues once at its successor.
@@ -809,7 +810,7 @@ retrying, and temporary-outage copy that asks the member to wait before retrying
809
810
  Unknown model failures retain the ordinary notice; raw provider messages and hints
810
811
  never become user-facing text. Session recovery failures use the same classification.
811
812
 
812
- The conversation recorder also writes a `model_service_alert` decision for recognized
813
+ The chat recorder also writes a `model_service_alert` decision for recognized
813
814
  model service failures on every channel it can archive, including private HTTP sessions.
814
815
  This durable operator alert contains only the safe category, failure code, retry policy
815
816
  and ordinary event coordinates. A workspace-wide archive event key limits it to one
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- var version = "0.42.1";
7
+ var version = "0.44.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -12,6 +12,7 @@ import { confirmationEntities } from "../extension/lib/telegram/confirmation-tex
12
12
  import { plainTelegramText, splitTelegramText, telegramMarkdown } from "../extension/lib/telegram/format.mjs";
13
13
  import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
14
14
  import { retainDeliveryDiagnostic } from "../extension/lib/telegram/delivery-diagnostics.mjs";
15
+ import { miniAppLinks } from "../extension/lib/telegram/app-links.mjs";
15
16
  import { randomBytes, randomUUID } from "node:crypto";
16
17
  import { AsyncLocalStorage } from "node:async_hooks";
17
18
  import { telegramPreviewOptions, telegramTextLinks } from "@segmentstream/ontology/telegram";
@@ -119,7 +120,28 @@ var TelegramDeliveryError = class extends Error {
119
120
  this.messageIds = messageIds;
120
121
  }
121
122
  };
122
- function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}) {
123
+ function isFields(value) {
124
+ return typeof value === "object" && value !== null;
125
+ }
126
+ function records(value) {
127
+ return Array.isArray(value) ? value.filter(isFields) : [];
128
+ }
129
+ function linkDestinations(body) {
130
+ const markup = body.reply_markup;
131
+ return [
132
+ ...records(body.entities),
133
+ ...records(body.caption_entities),
134
+ ...records(body.media).flatMap((item) => records(item.caption_entities)),
135
+ ...Array.isArray(markup?.inline_keyboard) ? markup.inline_keyboard.flatMap(records) : []
136
+ ].flatMap((item) => typeof item.url === "string" ? [item.url] : []);
137
+ }
138
+ function withAppLinks(items, links) {
139
+ return links.size === 0 || !Array.isArray(items) ? items : items.map((item) => isFields(item) && typeof item.url === "string" && links.has(item.url) ? {
140
+ ...item,
141
+ url: links.get(item.url)
142
+ } : item);
143
+ }
144
+ function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}, appLinks) {
123
145
  const methods = new Set([
124
146
  "sendMessage",
125
147
  "editMessageText",
@@ -135,6 +157,10 @@ function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}) {
135
157
  if (!methods.has(url.split("/").at(-1) ?? "") || typeof init?.body !== "string") return fetchImpl(input, init);
136
158
  const body = JSON.parse(init.body);
137
159
  let textBlocked = false;
160
+ const fixed = ["text", "caption"].some((field) => {
161
+ const value = body[field];
162
+ return typeof value === "string" && (isExactChatPostCard(value) || confirmationEntities(value) !== void 0);
163
+ });
138
164
  for (const field of ["text", "caption"]) {
139
165
  if (typeof body[field] === "string" && isExactChatPostCard(body[field])) body.parse_mode = "MarkdownV2";
140
166
  if (typeof body[field] === "string" && !isExactChatPostCard(body[field])) {
@@ -179,6 +205,14 @@ function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}) {
179
205
  if (rows.length === 0 && markup.inline_keyboard.length > 0) delete body.reply_markup;
180
206
  else markup.inline_keyboard = rows;
181
207
  }
208
+ const links = appLinks === void 0 || fixed ? new Map() : await miniAppLinks(appLinks, linkDestinations(body));
209
+ if (links.size > 0) {
210
+ if (Array.isArray(markup?.inline_keyboard) && body.reply_markup !== void 0) markup.inline_keyboard = markup.inline_keyboard.map((row) => withAppLinks(row, links));
211
+ if (Array.isArray(body.media)) body.media = body.media.map((item) => isFields(item) && item.caption_entities !== void 0 ? {
212
+ ...item,
213
+ caption_entities: withAppLinks(item.caption_entities, links)
214
+ } : item);
215
+ }
182
216
  const send = async () => {
183
217
  const parts = url.endsWith("/sendMessage") && typeof body.text === "string" && !isExactChatPostCard(body.text) ? splitTelegramText({
184
218
  text: body.text,
@@ -195,6 +229,7 @@ function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}) {
195
229
  delete payload.disable_web_page_preview;
196
230
  Object.assign(payload, previewOptions);
197
231
  }
232
+ for (const field of ["entities", "caption_entities"]) if (payload[field] !== void 0) payload[field] = withAppLinks(payload[field], links);
198
233
  return await fetchImpl(input, {
199
234
  ...init,
200
235
  body: JSON.stringify(payload)
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { n as currentInboundRequest } from "./inbound-request-DgQB4g1J.mjs";
7
+ import { n as currentInboundRequest } from "./inbound-request-CK0QqEOP.mjs";
8
8
  import "../extension/lib/agent-task.mjs";
9
9
  import { randomUUID } from "node:crypto";
10
10
  function telegramRuntimeSource(message, files, callbackQueryId) {
@@ -94,8 +94,8 @@ function telegramPrincipal(input) {
94
94
  if (message.from.username !== void 0) attributes.username = message.from.username;
95
95
  const locale = member.locale ?? message.from.languageCode;
96
96
  if (locale !== void 0) attributes.locale = locale;
97
- const language = input.conversationLanguage ?? conversationLanguage([message.text || message.caption]);
98
- if (language !== void 0) attributes.conversationLanguage = language;
97
+ const language = input.chatLanguage ?? chatLanguage([message.text || message.caption]);
98
+ if (language !== void 0) attributes.chatLanguage = language;
99
99
  return {
100
100
  authenticator: TELEGRAM_AUTHENTICATOR,
101
101
  issuer: "telegram",
@@ -105,7 +105,7 @@ function telegramPrincipal(input) {
105
105
  attributes
106
106
  };
107
107
  }
108
- function conversationLanguage(texts) {
108
+ function chatLanguage(texts) {
109
109
  for (const text of texts) {
110
110
  if (/[\u0430-\u044f\u0451]/iu.test(text)) return "ru";
111
111
  if ((text.match(/\b[a-z]+\b/gi)?.length ?? 0) >= 3) return "en";
@@ -125,4 +125,4 @@ function identityProviderOf(principal) {
125
125
  const provider = principal?.attributes.identityProvider;
126
126
  return typeof provider === "string" && provider !== "" ? provider : void 0;
127
127
  }
128
- export { rolesOf as a, compatibleRuntimeEnvelope as c, telegramRuntimeSource as d, memberIdOf as i, principalRuntimeSource as l, conversationLanguage as n, telegramPrincipal as o, identityProviderOf as r, RUNTIME_SOURCE_PROTOCOL as s, TELEGRAM_AUTHENTICATOR as t, runtimeEnvelope as u };
128
+ export { rolesOf as a, compatibleRuntimeEnvelope as c, telegramRuntimeSource as d, memberIdOf as i, principalRuntimeSource as l, chatLanguage as n, telegramPrincipal as o, identityProviderOf as r, RUNTIME_SOURCE_PROTOCOL as s, TELEGRAM_AUTHENTICATOR as t, runtimeEnvelope as u };
@@ -16,7 +16,7 @@ var telegram_default = segmentstreamTelegram({
16
16
  admission: () => segmentstream.config,
17
17
  decide: (options) => decide(options),
18
18
  review: {
19
- settings: () => segmentstream.config.conversations,
19
+ settings: () => segmentstream.config.review,
20
20
  decide: (options) => decide(options)
21
21
  }
22
22
  });
@@ -11,7 +11,7 @@ var whatsapp_default = segmentstreamWhatsApp({
11
11
  settings: () => segmentstream.config.channels.whatsapp,
12
12
  admission: () => segmentstream.config,
13
13
  review: {
14
- settings: () => segmentstream.config.conversations,
14
+ settings: () => segmentstream.config.review,
15
15
  decide: (options) => decide(options),
16
16
  model: () => segmentstream.config.models.decision
17
17
  }
@@ -4,8 +4,9 @@ import { type StructuredInbound } from "./lib/telegram/structured-settings.js";
4
4
  import type { WorkspaceActionHook } from "./lib/telegram/workspace-action.js";
5
5
  import { type TelegramTexts } from "./lib/telegram/texts.js";
6
6
  import type { AttachmentLifecycle } from "./lib/telegram/lifecycle.js";
7
+ import { type TelegramAppLinks } from "./lib/telegram/app-links.js";
7
8
  import { type PersonaSettings } from "./personas.js";
8
- import { type ConversationsSettings, type ReviewMode } from "./review.js";
9
+ import { type ReviewSettings, type ReviewMode } from "./review.js";
9
10
  import { type TelegramLinkPreviews } from "@segmentstream/ontology/telegram";
10
11
  export declare const TELEGRAM_POLICIES: readonly ["mention", "smart"];
11
12
  /**
@@ -79,6 +80,11 @@ export interface SegmentStreamAgentConfigInput {
79
80
  readonly linkPreviews?: string;
80
81
  /** Additional exact HTTP(S) origins belonging to this workspace. */
81
82
  readonly additionalOwnOrigins?: readonly string[];
83
+ /**
84
+ * How links to the workspace's own app open: `web` (default) leaves them as written,
85
+ * `miniApp` opens their pages in the bot's Main Mini App.
86
+ */
87
+ readonly appLinks?: string;
82
88
  /**
83
89
  * Whether text the model writes before it calls tools reaches the chat as its own message,
84
90
  * like a reply. Off when absent: only final replies are delivered.
@@ -179,21 +185,19 @@ export interface SegmentStreamAgentConfigInput {
179
185
  * that staff would send the reply as written (`whenUnsure`). The criteria of a `whenUnsure`
180
186
  * review are `agent/review/<role>.md` (`default.md`), which the SDK and the platform put inline.
181
187
  */
182
- readonly conversations?: {
183
- readonly byRole?: Readonly<Record<string, ConversationInput>>;
184
- readonly default?: ConversationInput;
185
- };
186
- }
187
- /** One entry of {@link SegmentStreamAgentConfigInput.conversations}. */
188
- export interface ConversationInput {
189
- readonly review: {
190
- readonly mode: Exclude<ReviewMode, "whenUnsure">;
191
- } | {
192
- readonly mode: "whenUnsure";
193
- readonly minConfidence: number;
194
- readonly criteria?: string;
188
+ readonly review?: {
189
+ readonly byRole?: Readonly<Record<string, ReviewInput>>;
190
+ readonly default?: ReviewInput;
195
191
  };
196
192
  }
193
+ /** One entry of {@link SegmentStreamAgentConfigInput.review}. */
194
+ export type ReviewInput = {
195
+ readonly mode: Exclude<ReviewMode, "whenUnsure">;
196
+ } | {
197
+ readonly mode: "whenUnsure";
198
+ readonly minConfidence: number;
199
+ readonly criteria?: string;
200
+ };
197
201
  export interface TelegramSettings {
198
202
  readonly groups?: {
199
203
  readonly replyEdgeIsAddress?: boolean;
@@ -206,6 +210,8 @@ export interface TelegramSettings {
206
210
  readonly policy: TelegramPolicy;
207
211
  readonly linkPreviews?: TelegramLinkPreviews;
208
212
  readonly additionalOwnOrigins?: readonly string[];
213
+ /** `miniApp` when links to the app open in the Mini App; validation sets it only then. */
214
+ readonly appLinks?: Exclude<TelegramAppLinks, "web">;
209
215
  /** Whether interim messages are on; validation sets it only when they are. */
210
216
  readonly interimMessages?: boolean;
211
217
  readonly attachmentLifecycle?: AttachmentLifecycle;
@@ -260,7 +266,7 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
260
266
  /** The personas, with their texts once read; absent when `segmentstream.json` declares none. */
261
267
  readonly personas?: PersonaSettings;
262
268
  /** Who sends replies; absent when `segmentstream.json` declares none, and the agent sends them. */
263
- readonly conversations?: ConversationsSettings;
269
+ readonly review?: ReviewSettings;
264
270
  }
265
271
  /** One validation failure, in Standard Schema's issue shape. */
266
272
  export interface ConfigIssue {
@@ -270,9 +276,11 @@ export interface ConfigIssue {
270
276
  /** A setting `agent/segmentstream.json` sets that configures nothing: accepted, and ignored. */
271
277
  export type ConfigWarning = ConfigIssue;
272
278
  /**
273
- * Every setting the configuration sets that configures nothing, for the deploy output and the
274
- * console, so the builder learns of it where they work: retired session and group keys, and the
275
- * older policies' thresholds where the conversation policy applies. The agent also logs them.
279
+ * Every setting the configuration sets that the builder should change, for the deploy output and
280
+ * the console, so the builder learns of it where they work: retired session and group keys and the
281
+ * older policies' thresholds where the chat policy applies, which configure nothing, and
282
+ * deprecated settings, which still apply until replaced. Each message says which and what to do.
283
+ * The agent also logs them.
276
284
  */
277
285
  export declare function configWarnings(value: unknown): ReadonlyArray<ConfigWarning>;
278
286
  type Validation = {
@@ -9,11 +9,12 @@ import { localizedText as localizedText$1 } from "./lib/admission.mjs";
9
9
  import { STRUCTURED_KINDS } from "./lib/telegram/structured-settings.mjs";
10
10
  import { TELEGRAM_TEXT_KEYS } from "./lib/telegram/texts.mjs";
11
11
  import { isTechnicalText } from "./lib/customer-text-safety.mjs";
12
+ import { TELEGRAM_APP_LINKS } from "./lib/telegram/app-links.mjs";
12
13
  import { inlineConventionFiles } from "./conventions.mjs";
13
14
  import { personaSettings } from "./personas.mjs";
14
- import { conversationsSettings } from "./review.mjs";
15
+ import { earlierReviewInput, reviewSettings } from "./review.mjs";
15
16
  import { readFileSync, realpathSync } from "node:fs";
16
- import { expandGroupFiles, groupPolicyIssues } from "@segmentstream/ontology/groups";
17
+ import { currentGroupPolicyInput, expandGroupFiles, groupPolicyIssues } from "@segmentstream/ontology/groups";
17
18
  import { TELEGRAM_LINK_PREVIEWS, isHttpOrigin } from "@segmentstream/ontology/telegram";
18
19
  const CONNECTION_KEY = /^[a-z][a-z0-9_]{0,63}$/;
19
20
  const TELEGRAM_POLICIES = ["mention", "smart"];
@@ -46,7 +47,7 @@ const IGNORED_SESSION_KEYS = [
46
47
  "timezone",
47
48
  "idleResetHours"
48
49
  ];
49
- const INAPPLICABLE_THRESHOLD = "applies only to the legacy and engaged policies; the conversation policy reads thresholds.reply and thresholds.defer, so remove it";
50
+ const INAPPLICABLE_THRESHOLD = "applies only to the legacy and engaged policies; the chat policy reads thresholds.reply and thresholds.defer, so remove it";
50
51
  function configWarnings(value) {
51
52
  const root = value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
52
53
  return [
@@ -56,12 +57,17 @@ function configWarnings(value) {
56
57
  })),
57
58
  ...ignoredGroupSettings(root?.groups, ["groups"]).map((path) => ({
58
59
  path: path.split("."),
59
- message: "no longer configures anything: group routing reads the chat's recent messages and has no conversation timers, so remove it"
60
+ message: "no longer configures anything: group routing reads the chat's recent messages and has no chat timers, so remove it"
60
61
  })),
61
- ...inapplicableGroupThresholds(root?.groups).map((path) => ({
62
+ ...inapplicableGroupThresholds(currentGroupPolicyInput(root?.groups)).map((path) => ({
62
63
  path: ["groups", ...path],
63
64
  message: INAPPLICABLE_THRESHOLD
64
65
  })),
66
+ ...earlierRoutingNames(root?.groups),
67
+ ...root?.conversations === void 0 ? [] : [{
68
+ path: ["conversations"],
69
+ message: "is now review, with each role's mode and minConfidence directly under it: write \"review\": { \"byRole\": { \"<role>\": { \"mode\": ... } }, \"default\": { ... } }"
70
+ }],
65
71
  ...isRecord(root?.groups) && isRecord(root.groups.smart) && root.groups.smart.instructions !== void 0 ? [{
66
72
  path: [
67
73
  "groups",
@@ -72,6 +78,40 @@ function configWarnings(value) {
72
78
  }] : []
73
79
  ];
74
80
  }
81
+ function earlierRoutingNames(groups) {
82
+ if (!isRecord(groups)) return [];
83
+ return [
84
+ [["groups", "smart"], groups.smart],
85
+ ...isRecord(groups.chats) ? Object.entries(groups.chats).map(([key, chat]) => [[
86
+ "groups",
87
+ "chats",
88
+ key,
89
+ "smart"
90
+ ], isRecord(chat) ? chat.smart : void 0]) : [],
91
+ [[
92
+ "groups",
93
+ "observability",
94
+ "shadow"
95
+ ], isRecord(groups.observability) ? groups.observability.shadow : void 0]
96
+ ].flatMap(([path, smart]) => {
97
+ const engagement = isRecord(smart) && isRecord(smart.engagement) ? smart.engagement : {};
98
+ return [...engagement.policy === "conversation" ? [{
99
+ path: [
100
+ ...path,
101
+ "engagement",
102
+ "policy"
103
+ ],
104
+ message: "is now \"chat\"; write \"chat\""
105
+ }] : [], ...engagement.conversationMinutes === void 0 ? [] : [{
106
+ path: [
107
+ ...path,
108
+ "engagement",
109
+ "conversationMinutes"
110
+ ],
111
+ message: "is now engagementMinutes; rename it"
112
+ }]];
113
+ });
114
+ }
75
115
  var SegmentStreamAgentConfigError = class extends Error {
76
116
  issues;
77
117
  name = "SegmentStreamAgentConfigError";
@@ -148,6 +188,7 @@ function telegramSettings(value, issues) {
148
188
  "groups",
149
189
  "linkPreviews",
150
190
  "additionalOwnOrigins",
191
+ "appLinks",
151
192
  "interimMessages",
152
193
  "attachmentLifecycle",
153
194
  "menuButton",
@@ -195,6 +236,11 @@ function telegramSettings(value, issues) {
195
236
  message: "must be an array of HTTP(S) origins without paths, credentials, queries or fragments",
196
237
  path: [...path, "additionalOwnOrigins"]
197
238
  });
239
+ const appLinks = telegram.appLinks === void 0 ? "web" : telegram.appLinks;
240
+ if (!TELEGRAM_APP_LINKS.some((mode) => mode === appLinks)) issues.push({
241
+ message: "must be \"web\" or \"miniApp\"",
242
+ path: [...path, "appLinks"]
243
+ });
198
244
  const interimMessages = telegram.interimMessages === void 0 ? false : telegram.interimMessages;
199
245
  if (typeof interimMessages !== "boolean") issues.push({
200
246
  message: "must be true or false",
@@ -269,6 +315,7 @@ function telegramSettings(value, issues) {
269
315
  } },
270
316
  linkPreviews,
271
317
  additionalOwnOrigins,
318
+ ...appLinks === "miniApp" ? { appLinks: "miniApp" } : {},
272
319
  ...interimMessages === true ? { interimMessages: true } : {},
273
320
  ...menuText === void 0 ? {} : { menuButton: { text: menuText } },
274
321
  ...lifecycle === void 0 ? {} : { attachmentLifecycle: {
@@ -596,6 +643,7 @@ function validateConfig(input, options = {}) {
596
643
  "replies",
597
644
  "texts",
598
645
  "personas",
646
+ "review",
599
647
  "conversations"
600
648
  ],
601
649
  issues
@@ -641,21 +689,22 @@ function validateConfig(input, options = {}) {
641
689
  const telegram = telegramSettings(channels?.telegram, issues);
642
690
  const whatsapp = whatsappSettings(channels?.whatsapp, issues);
643
691
  const slack = slackSettings(channels?.slack, issues);
644
- for (const issue of groupPolicyIssues(root?.groups)) issues.push({
692
+ const authoredGroupsInput = currentGroupPolicyInput(root?.groups);
693
+ for (const issue of groupPolicyIssues(authoredGroupsInput)) issues.push({
645
694
  ...issue,
646
695
  path: ["groups", ...issue.path]
647
696
  });
648
- const ignoredGroups = ignoredGroupSettings(root?.groups, ["groups"]);
697
+ const ignoredGroups = ignoredGroupSettings(authoredGroupsInput, ["groups"]);
649
698
  if (ignoredGroups.length > 0 && !ignoredGroupSettingsReported) {
650
699
  ignoredGroupSettingsReported = true;
651
- console.warn(`[segmentstream] agent/segmentstream.json: ${ignoredGroups.join(", ")} no longer configure anything and are ignored. Group routing has no conversation timers: the classifier reads the chat's last groups.smart.context.messages messages, however old; remove these keys.`);
700
+ console.warn(`[segmentstream] agent/segmentstream.json: ${ignoredGroups.join(", ")} no longer configure anything and are ignored. Group routing has no chat timers: the classifier reads the chat's last groups.smart.context.messages messages, however old; remove these keys.`);
652
701
  }
653
- const inapplicable = inapplicableGroupThresholds(root?.groups);
702
+ const inapplicable = inapplicableGroupThresholds(authoredGroupsInput);
654
703
  if (inapplicable.length > 0 && !inapplicableThresholdsReported) {
655
704
  inapplicableThresholdsReported = true;
656
705
  console.warn(`[segmentstream] agent/segmentstream.json: ${inapplicable.map((path) => ["groups", ...path].join(".")).join(", ")} ${INAPPLICABLE_THRESHOLD}.`);
657
706
  }
658
- let authoredGroups = root?.groups;
707
+ let authoredGroups = authoredGroupsInput;
659
708
  if (authoredGroups !== void 0 && groupPolicyIssues(authoredGroups).length === 0) try {
660
709
  authoredGroups = expandGroupFiles(authoredGroups, (path) => {
661
710
  const root = realpathSync(process.cwd());
@@ -778,7 +827,11 @@ function validateConfig(input, options = {}) {
778
827
  path: ["sandbox"]
779
828
  });
780
829
  const personas = personaSettings(root?.personas, issues, options.texts === "required");
781
- const conversations = conversationsSettings(root?.conversations, issues);
830
+ if (root?.review !== void 0 && root.conversations !== void 0) issues.push({
831
+ path: ["conversations"],
832
+ message: "is the earlier name of review; keep review"
833
+ });
834
+ const review = reviewSettings(root?.review ?? earlierReviewInput(root?.conversations), issues);
782
835
  if (issues.length > 0) return { issues };
783
836
  return { value: {
784
837
  groups,
@@ -805,7 +858,7 @@ function validateConfig(input, options = {}) {
805
858
  replies,
806
859
  texts,
807
860
  ...personas === null ? {} : { personas },
808
- ...conversations === void 0 ? {} : { conversations }
861
+ ...review === void 0 ? {} : { review }
809
862
  } };
810
863
  }
811
864
  function readAgentFile(path) {
@@ -6,7 +6,7 @@
6
6
  * - `agent/groups/instructions.md`: guidance the group decision model reads after the platform's
7
7
  * rules;
8
8
  * - `agent/review/<role>.md` (`default.md` for `default`): what staff check a reply for, which the
9
- * decision model reads for a conversation whose review is `whenUnsure`.
9
+ * decision model reads for a role whose review is `whenUnsure`.
10
10
  *
11
11
  * The SDK reads them when the agent is built; the platform reads them from the deployment's
12
12
  * archive and puts them inline in `segmentstream.json` before it builds, so the running agent,