@segmentstream/agent 0.51.1 → 0.52.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 (91) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +65 -27
  3. package/dist/_chunks/{build-metadata-BDr_toej.mjs → build-metadata-DJ3WHCte.mjs} +1 -1
  4. package/dist/_chunks/{principal-ie0lHCpn.mjs → principal-JoaOmdFL.mjs} +114 -11
  5. package/dist/extension/config.d.ts +37 -1
  6. package/dist/extension/config.mjs +74 -3
  7. package/dist/extension/connections/ontology.mjs +1 -1
  8. package/dist/extension/extension.d.ts +1 -1
  9. package/dist/extension/hooks/authorization.mjs +1 -1
  10. package/dist/extension/instructions/persona.mjs +1 -1
  11. package/dist/extension/instructions/sandbox.mjs +2 -1
  12. package/dist/extension/lib/actor.d.ts +17 -6
  13. package/dist/extension/lib/actor.mjs +1 -1
  14. package/dist/extension/lib/admission.mjs +10 -1
  15. package/dist/extension/lib/agent-task.d.ts +2 -0
  16. package/dist/extension/lib/agent-task.mjs +6 -2
  17. package/dist/extension/lib/agent-tools.d.ts +42 -0
  18. package/dist/extension/lib/agent-tools.mjs +43 -0
  19. package/dist/extension/lib/attachment-tools.mjs +1 -1
  20. package/dist/extension/lib/attachments.mjs +1 -1
  21. package/dist/extension/lib/build-metadata.mjs +1 -1
  22. package/dist/extension/lib/chat-address.mjs +1 -1
  23. package/dist/extension/lib/chat-context.mjs +1 -1
  24. package/dist/extension/lib/chat-recorder.mjs +10 -1
  25. package/dist/extension/lib/confirmations.mjs +1 -1
  26. package/dist/extension/lib/email/channel.mjs +3 -1
  27. package/dist/extension/lib/html-text.d.ts +14 -0
  28. package/dist/extension/lib/html-text.mjs +198 -0
  29. package/dist/extension/lib/identities.d.ts +5 -0
  30. package/dist/extension/lib/identities.mjs +4 -1
  31. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  32. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  33. package/dist/extension/lib/ontology-connection.mjs +1 -1
  34. package/dist/extension/lib/ontology-file-call.mjs +7 -1
  35. package/dist/extension/lib/ontology-tools.mjs +1 -1
  36. package/dist/extension/lib/review/hold.mjs +1 -1
  37. package/dist/extension/lib/review/reply.mjs +1 -1
  38. package/dist/extension/lib/role-skill.mjs +1 -1
  39. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  40. package/dist/extension/lib/sent-files.mjs +1 -1
  41. package/dist/extension/lib/slack/adapter.mjs +3 -1
  42. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  43. package/dist/extension/lib/stored-files.mjs +1 -1
  44. package/dist/extension/lib/telegram/adapter.mjs +2 -2
  45. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  46. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  47. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  48. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  49. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  50. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  51. package/dist/extension/lib/telegram/files.mjs +1 -1
  52. package/dist/extension/lib/telegram/health.mjs +1 -1
  53. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  54. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  55. package/dist/extension/lib/telegram/inbound.mjs +1 -1
  56. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  57. package/dist/extension/lib/telegram/principal.mjs +1 -1
  58. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  59. package/dist/extension/lib/telegram/silent.mjs +1 -1
  60. package/dist/extension/lib/telegram/structured.mjs +1 -1
  61. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  62. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  63. package/dist/extension/lib/web/auth.d.ts +65 -8
  64. package/dist/extension/lib/web/auth.mjs +1 -1
  65. package/dist/extension/lib/web/channel.d.ts +10 -6
  66. package/dist/extension/lib/web/channel.mjs +1 -1
  67. package/dist/extension/lib/web-fetch.d.ts +60 -0
  68. package/dist/extension/lib/web-fetch.mjs +244 -0
  69. package/dist/extension/lib/whatsapp/adapter.mjs +3 -1
  70. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  71. package/dist/extension/lib/workspace-source.mjs +1 -1
  72. package/dist/extension/model.mjs +1 -1
  73. package/dist/extension/tools/attachments_discard.mjs +1 -1
  74. package/dist/extension/tools/attachments_list.mjs +1 -1
  75. package/dist/extension/tools/attachments_promote.mjs +3 -1
  76. package/dist/extension/tools/attachments_read.mjs +1 -1
  77. package/dist/extension/tools/attachments_send.mjs +1 -1
  78. package/dist/extension/tools/attachments_stage.d.ts +2 -2
  79. package/dist/extension/tools/attachments_stage.mjs +7 -2
  80. package/dist/extension/tools/attachments_table.mjs +1 -1
  81. package/dist/extension/tools/ontology_call_file.d.ts +1 -0
  82. package/dist/extension/tools/ontology_call_file.mjs +2 -1
  83. package/dist/extension/tools/questions_ask.d.ts +1 -3
  84. package/dist/extension/tools/questions_ask.mjs +3 -3
  85. package/dist/extension/tools/sandbox.mjs +5 -1
  86. package/dist/extension/tools/web_fetch.d.ts +2 -0
  87. package/dist/extension/tools/web_fetch.mjs +73 -0
  88. package/dist/extension/tools/workspace_source.mjs +4 -2
  89. package/dist/tools/index.d.ts +1 -0
  90. package/dist/tools/index.mjs +2 -1
  91. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.52.1
4
+
5
+ Pins @segmentstream/ontology 0.108.0.
6
+
7
+ ## 0.52.0
8
+
9
+ The web channel admits guests: a website's visitor whose agent token the ontology issued for a
10
+ website its `guest` names talks to the agent as a guest, in their own chat `guest:<id>`. The
11
+ session principal carries `kind: "guest"`, the role `guest` alone, no member, and `agentTools`,
12
+ the agent tools `guest.permissions` grant, never the sandbox; personas, models and skills choose by
13
+ role as for anyone, so `personas.byRole.guest` works. A guest who holds `agent_tool:web` gets
14
+ `segmentstream__web_fetch` for the domains `web.domains` lists, as anyone does. The agent acts for
15
+ the guest at the ontology as `guest:<id>` with their token's grant. Attachments, the workspace's
16
+ code and `questions_ask` are never offered to a guest, nor is `chat_post_message`, and an action
17
+ that needs a confirmation is refused for them. Their chat is archived under `web` with no member
18
+ taking part.
19
+
20
+ `limits.guest` in `agent/segmentstream.json` sets each guest's turns a day, `turnsPerDay` (at
21
+ most 20), and every guest's together, `workspaceTurnsPerDay` (at most 1000). `webChannel({ config })`
22
+ takes `agent/segmentstream.json` and sends its `limits` with each web turn, so the web's turns, a
23
+ member's or a guest's, count against the workspace's own limits; messenger turns send all but the
24
+ guest limits. The ontology answers a turn beyond them `429 rate_limited`, as before.
25
+
26
+ Action required: in `agent/agent/channels/eve.ts`, import `../../segmentstream.json` and pass it
27
+ as `webChannel({ config })`, as the starter does, so that the ontology counts the web's turns
28
+ against your `limits`; without it they count against the limits a messenger's turn last sent.
29
+
30
+ The roles decide who gets the agent's own tools. The sandbox tools (`segmentstream__bash`,
31
+ `segmentstream__read_file`, `segmentstream__write_file`), `segmentstream__attachments_stage`,
32
+ `segmentstream__ontology_call_file`, `segmentstream__workspace_source` and promoting a sandbox file
33
+ by `path` need `"sandbox": true` and a caller who holds `agent_tool:sandbox`; the sandbox's system
34
+ instruction follows them. Every call checks the grant again. The ontology names the tools a caller
35
+ holds in its answers, and each channel carries them on the session principal as `agentTools`, next
36
+ to `roles`.
37
+
38
+ `"web": { "domains": ["example.com"] }` in `agent/segmentstream.json` gives callers who hold
39
+ `agent_tool:web` `segmentstream__web_fetch`: it reads `https://` pages of those domains and their
40
+ subdomains, at most 50 bare lower-case domains, and checks every redirect the same way. It never
41
+ connects to an address that is not public, reads at most 5 MiB within 60 seconds and answers at most
42
+ 50,000 characters, HTML as Markdown or text. No web search: the runtime's search cannot be held to
43
+ the listed domains.
44
+
45
+ Action required: grant `agent_tool:sandbox` (and `agent_tool:web` with `web`) in the ontology's
46
+ roles; see the ontology SDK's notes. An ontology SDK released before agent tool permissions names no
47
+ `agent_tools`, and the agent then gives every caller the sandbox, as before, until 2027-02-15;
48
+ upgrade the ontology SDK and deploy it before then.
49
+
50
+ Pins @segmentstream/ontology 0.107.0.
51
+
3
52
  ## 0.51.1
4
53
 
5
54
  Pins @segmentstream/ontology 0.106.3.
package/README.md CHANGED
@@ -52,11 +52,13 @@ agent/
52
52
  └── segmentstream.ts # mounts this package with segmentstream.json
53
53
  ```
54
54
 
55
- **`agent/agent/channels/eve.ts`** exports `webChannel()` from `@segmentstream/agent/web`: the agent's
56
- HTTP channel, where a member signed in to the app talks to the agent from the browser as themselves,
57
- with the agent token the ontology issues. The runtime reads this channel only from that file, whose
58
- name it fixes, so an extension cannot provide it; without the file, the agent admits no members
59
- from the browser.
55
+ **`agent/agent/channels/eve.ts`** exports `webChannel({ config })` from `@segmentstream/agent/web`,
56
+ with `config` imported from `../../segmentstream.json`: the agent's HTTP channel, where a member
57
+ signed in to the app talks to the agent from the browser as themselves, and a guest of a website
58
+ the ontology's `guest` names talks to it as a guest, each with the agent token the ontology issues.
59
+ The channel sends the ontology the `limits` of `config` with each turn, `limits.guest` included.
60
+ The runtime reads this channel only from that file, whose name it fixes, so an extension cannot
61
+ provide it; without the file, the agent admits nobody from the browser.
60
62
 
61
63
  **`agent/agent/extensions/segmentstream.ts`** mounts the extension. The file name is the mount's namespace, so
62
64
  every contribution is named `segmentstream__…`:
@@ -118,22 +120,23 @@ See [Sandbox](#sandbox).
118
120
  }
119
121
  ```
120
122
 
121
- | Field | Default | Meaning |
122
- | ---------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
123
- | `channels.telegram.connection` | none | The Connect key whose credential is the bot token. Without `channels.telegram`, no Telegram. |
124
- | `channels.telegram.policy` | `"smart"` | Classifies unaddressed group messages and captionless uploads; `mention` observes unaddressed messages without decoding or inference |
125
- | `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. |
126
- | `channels.telegram.additionalOwnOrigins` | `[]` | Additional exact HTTP(S) workspace origins, including local ports; no paths or credentials. |
127
- | `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` |
128
- | `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) |
129
- | `models.stt` | `"spacexai/grok-stt"` | The AI Gateway transcription model for voice messages; `false` leaves them untranscribed |
130
- | `models.imageDescription` | `google/gemini-2.5-flash-lite` | Image evidence for group routing even with native vision; `false` disables descriptions |
131
- | `models.decision` | `"typesafe-ai/jev-1.14.0"` | The AI Gateway decision model of the inbound router |
132
- | `ontology.connection` | `true` | Whether the agent reaches the ontology over MCP |
133
- | `sandbox` | `false` | `true` adds `bash`, `read_file` and `write_file` in the agent's sandbox without network; see [Sandbox](#sandbox) |
134
- | `workspaceSource` | `false` | `true`, with `"sandbox": true`, gives members `segmentstream__workspace_source`, a read-only copy of the deployed code in the sandbox; see [Sandbox](#sandbox) |
135
- | `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) |
136
- | `review` | none | `{ "byRole": { role: { "mode": … } }, "default": { "mode": … } }`: who sends replies; see [Reply review](#reply-review) |
123
+ | Field | Default | Meaning |
124
+ | ---------------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
125
+ | `channels.telegram.connection` | none | The Connect key whose credential is the bot token. Without `channels.telegram`, no Telegram. |
126
+ | `channels.telegram.policy` | `"smart"` | Classifies unaddressed group messages and captionless uploads; `mention` observes unaddressed messages without decoding or inference |
127
+ | `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. |
128
+ | `channels.telegram.additionalOwnOrigins` | `[]` | Additional exact HTTP(S) workspace origins, including local ports; no paths or credentials. |
129
+ | `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` |
130
+ | `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) |
131
+ | `models.stt` | `"spacexai/grok-stt"` | The AI Gateway transcription model for voice messages; `false` leaves them untranscribed |
132
+ | `models.imageDescription` | `google/gemini-2.5-flash-lite` | Image evidence for group routing even with native vision; `false` disables descriptions |
133
+ | `models.decision` | `"typesafe-ai/jev-1.14.0"` | The AI Gateway decision model of the inbound router |
134
+ | `ontology.connection` | `true` | Whether the agent reaches the ontology over MCP |
135
+ | `sandbox` | `false` | `true` adds `bash`, `read_file` and `write_file` in the agent's sandbox without network, for callers who hold `agent_tool:sandbox`; see [Sandbox](#sandbox) |
136
+ | `workspaceSource` | `false` | `true`, with `"sandbox": true`, gives members `segmentstream__workspace_source`, a read-only copy of the deployed code in the sandbox; see [Sandbox](#sandbox) |
137
+ | `web` | none | `{ "domains": ["example.com"] }`: `segmentstream__web_fetch` reads `https://` pages of those domains and their subdomains, for callers who hold `agent_tool:web`; see [Who gets which tool](#who-gets-which-tool) |
138
+ | `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) |
139
+ | `review` | none | `{ "byRole": { role: { "mode": … } }, "default": { "mode": … } }`: who sends replies; see [Reply review](#reply-review) |
137
140
 
138
141
  An unknown field or an invalid value fails the mount with `SegmentStreamAgentConfigError`, naming
139
142
  each path. `manifestOf(config)` returns the normalized configuration, defaults applied, for the
@@ -217,7 +220,9 @@ optional fallback for any missing scope-specific limit reply. Without either rep
217
220
  stop processing. `groupPairingRequired` and `refused` may override existing pairing/refusal copy.
218
221
 
219
222
  Omitted limit fields use platform ceilings: 6 turns/minute and 80/day per sender, 30 new users/hour,
220
- and 3000 workspace turns/day. Overrides must be positive integers at or below each ceiling.
223
+ and 3000 workspace turns/day; for a website's guests, `limits.guest`, 20 turns/day per guest and
224
+ 1000 guest turns/day for the workspace, counted apart. Overrides must be positive integers at or
225
+ below each ceiling. The web channel sends the limits of the `config` it is given with each turn.
221
226
  The trusted runtime submits these effective limits; the ontology clamps and persists them for other
222
227
  admission paths. Only self-registered users with exactly the member role consume sender/workspace
223
228
  turn quotas, keyed by user id across identities. Paired-only users and holders of named roles
@@ -271,15 +276,47 @@ continue using GET lookup. Starter templates and pins remain unchanged in this s
271
276
  | `segmentstream__attachments_list`, `_read`, `_promote`, `_discard` | `tools` | The member's temporary attachments in this chat: list, read, keep through an action, drop. |
272
277
  | `segmentstream__attachments_send` | `tools` | Sends readable stored ontology files into the current Telegram chat and topic. |
273
278
  | `segmentstream__no_reply` | `tools` | Eve's `no_reply`: ends the turn without a message and keeps the model's reason in the session and the archive. |
274
- | `segmentstream__bash`, `_read_file`, `_write_file` | `tools` | With `"sandbox": true`: eve's file tools, only in the sandbox `@segmentstream/agent/sandbox` opened. |
275
- | `segmentstream__attachments_stage` | `tools` | With `"sandbox": true`: copies a chat attachment or a stored record's file, read as the member, into the sandbox. |
276
- | `segmentstream__workspace_source` | `tools` | With `"workspaceSource": true`: copies the deployed commit's code, read as the member, into `/workspace/source`, read-only. |
279
+ | `segmentstream__bash`, `_read_file`, `_write_file` | `tools` | With `"sandbox": true`, for `agent_tool:sandbox`: eve's file tools, only in the sandbox `@segmentstream/agent/sandbox` opened. |
280
+ | `segmentstream__attachments_stage` | `tools` | With `"sandbox": true`, for `agent_tool:sandbox`: copies a chat attachment or a stored record's file, read as the member, into the sandbox. |
281
+ | `segmentstream__ontology_call_file` | `tools` | With `"sandbox": true`, for `agent_tool:sandbox`: calls an ontology tool with the JSON object in a sandbox file, or saves a read's result there. |
282
+ | `segmentstream__workspace_source` | `tools` | With `"workspaceSource": true`, for members with `agent_tool:sandbox`: copies the deployed commit's code, read as the member, into `/workspace/source`, read-only. |
283
+ | `segmentstream__web_fetch` | `tools` | With `web.domains`, for `agent_tool:web`: reads one `https://` page of those domains, every redirect checked, as Markdown, text or HTML. |
277
284
  | 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 |
278
285
  | chat context | `hooks`, `instructions` | Adds the chat messages a Telegram session has not seen, once, ahead of the turn; see [Durable chats](#durable-chats). |
279
- | sandbox rules | `instructions` | With `"sandbox": true`: working copies, file contents as data, no network; with `"workspaceSource": true`, where to read the workspace's code. |
286
+ | sandbox rules | `instructions` | With `"sandbox": true`, for `agent_tool:sandbox`: working copies, file contents as data, no network; with `"workspaceSource": true`, where to read the workspace's code. |
280
287
  | sandbox cleanup | `hooks` | Deletes the session's sandbox when its history is cleared. |
281
288
  | workspace source guard | `hooks` | Removes the copy of the workspace's code when anyone but the member who copied it takes a turn. |
282
289
 
290
+ ### Who gets which tool
291
+
292
+ The configuration says which tools the agent has; the ontology's roles say who gets them. The
293
+ agent's own tools are the ontology's permissions `agent_tool:sandbox` (the sandbox tools above,
294
+ `ontology_call_file`, `attachments_stage`, `workspace_source` and `attachments_promote` with
295
+ `path`) and `agent_tool:web` (`web_fetch`); no wildcard grants them. Every answer in which the
296
+ ontology names whom the agent acts for, identity lookup and admission, agent token introspection
297
+ and the current task, carries `agent_tools`: the tools that caller's current roles grant. Each
298
+ channel stamps them on the session principal as the attribute `agentTools` (`string[]`), next to
299
+ `roles`. A tool is offered, and each call runs, only while the current principal holds its tool; a
300
+ principal without `agentTools` holds none. eve's own `local-dev` principal on an `eve dev` host
301
+ holds every one.
302
+
303
+ An ontology SDK that predates agent tool permissions answers no `agent_tools`; the SDK reads that as
304
+ `["sandbox"]`, what every caller had before, until 2027-02-15. An ontology whose roles name no
305
+ `agent_tool` permission answers `["sandbox"]` for everyone too, with a `check` warning.
306
+
307
+ A website's guest (the ontology's `guest`) holds the tools `guest.permissions` grant: at most
308
+ `agent_tool:web`, never the sandbox, which the SDK drops from a guest's answer whatever it says.
309
+ Their principal carries `kind: "guest"`, `guestId`, `roles: ["guest"]` and `agentTools`, no
310
+ `memberId`; the tools only a member has (attachments, `questions_ask`, `workspace_source`, chat
311
+ posts) are never offered to them.
312
+
313
+ `segmentstream__web_fetch` follows each redirect itself, since eve's `web_fetch` gives no hook to
314
+ check a hop's host: every URL is `https://` on the default port, on a listed domain or its
315
+ subdomain, and connects only when every address of its host is public. It reads text only, at
316
+ most 5 MiB within 60 seconds, and answers at most 50,000 characters, HTML converted to Markdown or
317
+ text. There is no web search tool: eve's provider-run search cannot be held to the listed
318
+ domains.
319
+
283
320
  ### Sandbox
284
321
 
285
322
  `@segmentstream/agent/sandbox` exports `environment`, a Vercel Sandbox environment, and a default
@@ -324,7 +361,8 @@ stored file staged again is granted again but not transferred while that path ho
324
361
  SHA-256. No URL, header or credential enters the sandbox. `segmentstream__read_file` keeps eve's model output,
325
362
  so PNG, JPEG, GIF and WebP images up to 3 MiB and PDFs up to 20 MiB reach the model as files.
326
363
 
327
- `segmentstream__workspace_source`, offered to members with `"workspaceSource": true`, copies the
364
+ `segmentstream__workspace_source`, offered to members with `"workspaceSource": true` who hold
365
+ `agent_tool:sandbox`, copies the
328
366
  commit production runs into `/workspace/source` for a member who holds `workspace_source:read`.
329
367
  The runtime reads `/api/ontology/agent/source` page by page as the member with its own token, refuses pages that name different commits (starting once more
330
368
  when production moves meanwhile) and archives with entries other than files and directories or
@@ -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.51.1";
7
+ var version = "0.52.1";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { telegramText, withTelegramTexts } from "../extension/lib/telegram/texts.mjs";
8
8
  import { isTechnicalText } from "../extension/lib/customer-text-safety.mjs";
9
9
  import { miniAppLinks, originalLinkPreview, withMiniAppLinks } from "../extension/lib/telegram/app-links.mjs";
10
+ import { admissionLimitsOf } from "../extension/config.mjs";
10
11
  import { appOrigin } from "../extension/lib/environment.mjs";
11
12
  import { redactDiagnostic } from "../extension/lib/diagnostics.mjs";
12
13
  import { redactTelegramDiagnostic } from "../extension/lib/telegram/diagnostic-redaction.mjs";
@@ -18,6 +19,7 @@ import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
18
19
  import { runtimeToken, tokenExpiry } from "../extension/lib/runtime-token.mjs";
19
20
  import { retainDeliveryDiagnostic } from "../extension/lib/telegram/delivery-diagnostics.mjs";
20
21
  import { MAXIMUM_DOWNLOAD_BYTES } from "../extension/lib/connection-proxy.mjs";
22
+ import { AGENT_TOOLS_ATTRIBUTE, SANDBOX_TOOL, agentToolsAnswer, agentToolsAttribute } from "../extension/lib/agent-tools.mjs";
21
23
  import { AGENT_TASK_HEADER, agentTaskIdOf, taskSecret } from "../extension/lib/agent-task.mjs";
22
24
  import { promptFits, withButtonDecision } from "../extension/lib/confirmation-buttons.mjs";
23
25
  import { CHAT_POST_ENVELOPE, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost } from "../extension/lib/chat-post-confirmation.mjs";
@@ -402,6 +404,9 @@ const WEB_AUTHENTICATOR = "segmentstream-web";
402
404
  const WEB_PROVIDER = "web";
403
405
  const AGENT_GRANT_HEADER = "X-SegmentStream-Agent-Grant";
404
406
  const WEB_GRANT_ATTRIBUTE = "webGrant";
407
+ const KIND_ATTRIBUTE = "kind";
408
+ const GUEST_ID_ATTRIBUTE = "guestId";
409
+ const GUEST_ROLE = "guest";
405
410
  const ACCESS_TOKEN_PREFIX = "sso_";
406
411
  const INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
407
412
  const INTROSPECTION_TIMEOUT_MS = 5e3;
@@ -434,22 +439,40 @@ var TurnLimitedError = class extends ForbiddenError {
434
439
  function strings(value) {
435
440
  return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
436
441
  }
442
+ function limitedOf(value) {
443
+ const limited = value;
444
+ return typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
445
+ scope: typeof limited.scope === "string" ? limited.scope : "",
446
+ retryAfterSeconds: limited.retry_after_seconds
447
+ } } : {};
448
+ }
437
449
  function webMemberOf(body) {
438
450
  if (typeof body !== "object" || body === null) return;
439
451
  const answer = body;
440
452
  const roles = strings(answer.roles);
441
- if (answer.active !== true || typeof answer.member_id !== "string" || typeof answer.grant_id !== "string" || answer.chat !== `member:${answer.member_id}` || roles === void 0) return;
442
- const limited = answer.limited;
453
+ if (answer.active !== true || typeof answer.grant_id !== "string" || roles === void 0) return;
454
+ if (answer.member_id === void 0 && typeof answer.guest_id === "string") {
455
+ const agentTools = (strings(answer.agent_tools) ?? []).filter((tool) => tool !== SANDBOX_TOOL);
456
+ return answer.guest_id === answer.grant_id && answer.chat === `guest:${answer.guest_id}` && roles.length === 1 && roles[0] === "guest" ? {
457
+ kind: "guest",
458
+ guestId: answer.guest_id,
459
+ grant: answer.grant_id,
460
+ chat: answer.chat,
461
+ roles,
462
+ agentTools,
463
+ ...limitedOf(answer.limited)
464
+ } : void 0;
465
+ }
466
+ const agentTools = agentToolsAnswer(answer.agent_tools);
467
+ if (typeof answer.member_id !== "string" || answer.chat !== `member:${answer.member_id}` || agentTools === void 0) return;
443
468
  return {
444
469
  memberId: answer.member_id,
445
470
  grant: answer.grant_id,
446
471
  chat: answer.chat,
447
472
  roles,
473
+ agentTools,
448
474
  ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
449
- ...typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
450
- scope: typeof limited.scope === "string" ? limited.scope : "",
451
- retryAfterSeconds: limited.retry_after_seconds
452
- } } : {}
475
+ ...limitedOf(answer.limited)
453
476
  };
454
477
  }
455
478
  function ontologyIntrospection(options = {}) {
@@ -466,7 +489,13 @@ function ontologyIntrospection(options = {}) {
466
489
  let response = await ask({
467
490
  token,
468
491
  origin,
469
- ...turn === true ? { turn: true } : {}
492
+ ...turn === true ? { turn: true } : {},
493
+ ...turn === true && options.limits !== void 0 ? { limits: options.limits } : {}
494
+ });
495
+ if (turn === true && options.limits !== void 0 && response.status === 400) response = await ask({
496
+ token,
497
+ origin,
498
+ turn: true
470
499
  });
471
500
  if (turn === true && response.status === 400) response = await ask({
472
501
  token,
@@ -476,7 +505,35 @@ function ontologyIntrospection(options = {}) {
476
505
  return webMemberOf(await response.json());
477
506
  };
478
507
  }
508
+ function guestPrincipal(guest) {
509
+ const chat = {
510
+ provider: "web",
511
+ chatId: guest.chat,
512
+ threadId: "",
513
+ kind: "private",
514
+ peer: guest.guestId
515
+ };
516
+ return withChatAddress({
517
+ authenticator: WEB_AUTHENTICATOR,
518
+ principalId: `web:guest:${guest.guestId}`,
519
+ principalType: "user",
520
+ subject: `guest:${guest.guestId}`,
521
+ attributes: {
522
+ [KIND_ATTRIBUTE]: GUEST_ROLE,
523
+ [GUEST_ID_ATTRIBUTE]: guest.guestId,
524
+ identityProvider: "web",
525
+ roles: guest.roles,
526
+ [WEB_GRANT_ATTRIBUTE]: guest.grant,
527
+ [AGENT_TOOLS_ATTRIBUTE]: guest.agentTools
528
+ }
529
+ }, chat);
530
+ }
531
+ function guestIdOf(principal) {
532
+ const guestId = principal?.attributes[GUEST_ID_ATTRIBUTE];
533
+ return principal?.authenticator === "segmentstream-web" && principal.attributes["kind"] === "guest" && typeof guestId === "string" && guestId !== "" ? guestId : void 0;
534
+ }
479
535
  function webPrincipal(member) {
536
+ if (member.kind === "guest") return guestPrincipal(member);
480
537
  const chat = {
481
538
  provider: "web",
482
539
  chatId: member.chat,
@@ -488,6 +545,7 @@ function webPrincipal(member) {
488
545
  memberId: member.memberId,
489
546
  identityProvider: "web",
490
547
  roles: member.roles,
548
+ ...agentToolsAttribute(member.agentTools),
491
549
  [WEB_GRANT_ATTRIBUTE]: member.grant
492
550
  };
493
551
  if (member.name !== void 0) attributes.memberName = member.name;
@@ -545,10 +603,11 @@ function answerCache(introspect) {
545
603
  }
546
604
  function webAuth(options = {}) {
547
605
  let introspect;
606
+ const limits = options.config === void 0 ? void 0 : admissionLimitsOf(options.config.limits);
548
607
  return async (request) => {
549
608
  const token = bearerOf(request);
550
609
  if (token === void 0 || !token.startsWith("sso_")) return null;
551
- introspect ??= answerCache(options.introspect ?? ontologyIntrospection());
610
+ introspect ??= answerCache(options.introspect ?? ontologyIntrospection(limits === void 0 ? {} : { limits }));
552
611
  const body = await bodyOf(request);
553
612
  const member = await introspect(token, new URL(request.url).origin, startsTurn(body));
554
613
  if (member === void 0) throw new UnauthenticatedError({
@@ -572,11 +631,23 @@ function actorOf(principal) {
572
631
  kind: "task",
573
632
  taskId
574
633
  };
634
+ const guestId = guestIdOf(principal);
635
+ if (guestId !== void 0) return {
636
+ kind: "guest",
637
+ guestId
638
+ };
575
639
  const memberId = memberIdOf(principal);
576
640
  return memberId === void 0 ? void 0 : member(memberId);
577
641
  }
578
642
  function actorKey(actor) {
579
- return actor.kind === "member" ? `member:${actor.memberId}` : `task:${actor.taskId}`;
643
+ switch (actor.kind) {
644
+ case "member": return `member:${actor.memberId}`;
645
+ case "guest": return `guest:${actor.guestId}`;
646
+ case "task": return `task:${actor.taskId}`;
647
+ }
648
+ }
649
+ function isGuestSession(principal) {
650
+ return guestIdOf(principal) !== void 0;
580
651
  }
581
652
  var ActorRequiredError = class extends Error {
582
653
  name = "ActorRequiredError";
@@ -588,6 +659,15 @@ function actorHeaders(input) {
588
659
  if (secret === void 0) throw new ActorRequiredError("The task is no longer live in this session.");
589
660
  return { [AGENT_TASK_HEADER]: secret };
590
661
  }
662
+ if (actor.kind === "guest") {
663
+ const grant = guestIdOf(input.principal) === actor.guestId ? webGrantOf(input.principal) : void 0;
664
+ if (grant === void 0) throw new ActorRequiredError("The guest's web session carries no agent token grant.");
665
+ return {
666
+ [ACT_AS_HEADER]: `guest:${actor.guestId}`,
667
+ "X-SegmentStream-Identity-Provider": "web",
668
+ [AGENT_GRANT_HEADER]: grant
669
+ };
670
+ }
591
671
  const provider = memberIdOf(input.principal) === actor.memberId ? identityProviderOf(input.principal) : void 0;
592
672
  const grant = provider === "web" ? webGrantOf(input.principal) : void 0;
593
673
  if (provider === "web" && grant === void 0) throw new ActorRequiredError("The web session carries no agent token grant.");
@@ -598,7 +678,13 @@ function actorHeaders(input) {
598
678
  };
599
679
  }
600
680
  function memberTool(tool) {
601
- return defineDynamic$1((context) => actorOf(context.session.auth.current)?.kind === "task" ? null : tool);
681
+ return defineDynamic$1((context) => {
682
+ const kind = actorOf(context.session.auth.current)?.kind;
683
+ return kind === "task" || kind === "guest" ? null : tool;
684
+ });
685
+ }
686
+ function notForGuests(tool) {
687
+ return defineDynamic$1((context) => isGuestSession(context.session?.auth?.current) ? null : tool);
602
688
  }
603
689
  const CONFIRMATION_TTL_MS = 6e5;
604
690
  function needsConfirmation(labels) {
@@ -650,6 +736,17 @@ function actionApproval(options) {
650
736
  }
651
737
  return "approved";
652
738
  }
739
+ if (actor?.kind === "guest") {
740
+ if (isChatPost(ctx.toolName)) return denied("Chat posting is unavailable to a guest.");
741
+ let annotations = connectionHints(ctx);
742
+ if (annotations === void 0) try {
743
+ annotations = await options.labels(actor, ctx.toolName, ctx.toolInput ?? {});
744
+ } catch (error) {
745
+ console.warn("The ontology action permission check failed.", error);
746
+ return denied("The action is unavailable or the guests' permissions do not allow it.");
747
+ }
748
+ return needsConfirmation(annotations) ? denied("This action needs a confirmation, which a guest cannot give.") : "approved";
749
+ }
653
750
  const memberId = actor?.memberId;
654
751
  if (memberId === void 0) return denied("A paired member is required.");
655
752
  const present = (run) => options.texts === void 0 ? run() : withTelegramTexts(options.texts(), run, () => confirmationLocale(ctx.session.auth.current));
@@ -1181,6 +1278,11 @@ function ontologyConnection(input) {
1181
1278
  instanceKey: `${origin}/mcp#task:${actor.taskId}`,
1182
1279
  tools: { block: [CHAT_POST_TOOL] }
1183
1280
  });
1281
+ if (actor.kind === "guest") return defineMcpClientConnection({
1282
+ ...common,
1283
+ instanceKey: `${origin}/mcp#guest:${actor.guestId}:web`,
1284
+ tools: { block: [CHAT_POST_TOOL] }
1285
+ });
1184
1286
  const memberId = actor.memberId;
1185
1287
  const web = input.principal?.authenticator === WEB_AUTHENTICATOR;
1186
1288
  const chatPosting = input.chatPosting === true && !web;
@@ -1811,6 +1913,7 @@ function telegramPrincipal(input) {
1811
1913
  segmentstreamRuntimeSource: JSON.stringify(telegramRuntimeSource(message, currentInboundRequest()?.files, input.callbackQueryId)),
1812
1914
  identityProvider: "telegram",
1813
1915
  roles: member.roles,
1916
+ ...agentToolsAttribute(member.agentTools),
1814
1917
  chatId: message.chat.id,
1815
1918
  chatType: message.chat.type
1816
1919
  };
@@ -1850,4 +1953,4 @@ function identityProviderOf(principal) {
1850
1953
  const provider = principal?.attributes.identityProvider;
1851
1954
  return typeof provider === "string" && provider !== "" ? provider : void 0;
1852
1955
  }
1853
- export { WEB_GRANT_ATTRIBUTE as $, OntologyToolRejected as A, ACT_AS_HEADER as B, attachmentUrl as C, principalRuntimeSource as Ct, ontologyConnection as D, actAsHeaders as E, CONFIRMATION_TTL_MS as F, member as G, actorHeaders as H, actionApproval as I, AGENT_GRANT_HEADER as J, memberTool as K, confirmations as L, ontologyToolLabels as M, ontologyTools as N, OntologyActionNotPermitted as O, promotionTarget as P, WEB_AUTHENTICATOR as Q, inputHash as R, agentAttachments as S, compatibleRuntimeEnvelope as St, parseAttachmentUrl as T, telegramRuntimeSource as Tt, actorKey as U, ActorRequiredError as V, actorOf as W, TURN_LIMITED_CODE as X, INTROSPECTION_PATH as Y, TurnLimitedError as Z, AttachmentError as _, formattingRefused as _t, rolesOf as a, webPrincipal as at, MAXIMUM_ATTACHMENT_BYTES as b, withDeliveryLocale as bt, currentInboundRequest as c, isSameChat as ct, prepareInboundMedia as d, currentLocale as dt, WEB_PROVIDER as et, attachmentsContext as f, currentThreadId as ft, ATTACHMENT_URL_PROTOCOL as g, failureText as gt, ATTACHMENT_TTL_HOURS as h, customerText as ht, memberIdOf as i, webMemberOf as it, actionToolName as j, OntologyFileUnavailable as k, runInboundRequest as l, withChatAddress as lt, turnContent as m, customerMessage as mt, chatLanguage as n, webAuth as nt, telegramPrincipal as o, CHAT_ATTRIBUTE as ot, storeFiles as p, customerCopy as pt, ACCESS_TOKEN_PREFIX as q, identityProviderOf as r, webGrantOf as rt, InboundRequest as s, chatAddressOf as st, TELEGRAM_AUTHENTICATOR as t, ontologyIntrospection as tt, withReplacedText as u, TelegramDeliveryError as ut, CHAT_HEADER as v, reportTelegramError as vt, fetchStoredAttachment as w, runtimeEnvelope as wt, SESSION_HEADER as x, RUNTIME_SOURCE_PROTOCOL as xt, EARLIER_CHAT_HEADER as y, safeTelegramFetch as yt, needsConfirmation as z };
1956
+ export { INTROSPECTION_PATH as $, OntologyToolRejected as A, principalRuntimeSource as At, ACT_AS_HEADER as B, attachmentUrl as C, failureText as Ct, ontologyConnection as D, withDeliveryLocale as Dt, actAsHeaders as E, safeTelegramFetch as Et, CONFIRMATION_TTL_MS as F, isGuestSession as G, actorHeaders as H, actionApproval as I, notForGuests as J, member as K, confirmations as L, ontologyToolLabels as M, telegramRuntimeSource as Mt, ontologyTools as N, OntologyActionNotPermitted as O, RUNTIME_SOURCE_PROTOCOL as Ot, promotionTarget as P, GUEST_ROLE as Q, inputHash as R, agentAttachments as S, customerText as St, parseAttachmentUrl as T, reportTelegramError as Tt, actorKey as U, ActorRequiredError as V, actorOf as W, AGENT_GRANT_HEADER as X, ACCESS_TOKEN_PREFIX as Y, GUEST_ID_ATTRIBUTE as Z, AttachmentError as _, TelegramDeliveryError as _t, rolesOf as a, WEB_PROVIDER as at, MAXIMUM_ATTACHMENT_BYTES as b, customerCopy as bt, currentInboundRequest as c, ontologyIntrospection as ct, prepareInboundMedia as d, webMemberOf as dt, KIND_ATTRIBUTE as et, attachmentsContext as f, webPrincipal as ft, ATTACHMENT_URL_PROTOCOL as g, withChatAddress as gt, ATTACHMENT_TTL_HOURS as h, isSameChat as ht, memberIdOf as i, WEB_GRANT_ATTRIBUTE as it, actionToolName as j, runtimeEnvelope as jt, OntologyFileUnavailable as k, compatibleRuntimeEnvelope as kt, runInboundRequest as l, webAuth as lt, turnContent as m, chatAddressOf as mt, chatLanguage as n, TurnLimitedError as nt, telegramPrincipal as o, guestIdOf as ot, storeFiles as p, CHAT_ATTRIBUTE as pt, memberTool as q, identityProviderOf as r, WEB_AUTHENTICATOR as rt, InboundRequest as s, guestPrincipal as st, TELEGRAM_AUTHENTICATOR as t, TURN_LIMITED_CODE as tt, withReplacedText as u, webGrantOf as ut, CHAT_HEADER as v, currentLocale as vt, fetchStoredAttachment as w, formattingRefused as wt, SESSION_HEADER as x, customerMessage as xt, EARLIER_CHAT_HEADER as y, currentThreadId as yt, needsConfirmation as z };
@@ -29,6 +29,10 @@ export declare const DEFAULT_ADMISSION_LIMITS: {
29
29
  };
30
30
  readonly newUsersPerHour: 30;
31
31
  readonly workspaceTurnsPerDay: 3000;
32
+ readonly guest: {
33
+ readonly turnsPerDay: 20;
34
+ readonly workspaceTurnsPerDay: 1000;
35
+ };
32
36
  };
33
37
  export interface AdmissionLimits {
34
38
  readonly perSender: {
@@ -37,9 +41,18 @@ export interface AdmissionLimits {
37
41
  };
38
42
  readonly newUsersPerHour: number;
39
43
  readonly workspaceTurnsPerDay: number;
44
+ /**
45
+ * Guests' turns, which the ontology counts apart from those of people who signed up: per guest
46
+ * and for every guest together, each day. The agent's web channel sends them.
47
+ */
48
+ readonly guest: {
49
+ readonly turnsPerDay: number;
50
+ readonly workspaceTurnsPerDay: number;
51
+ };
40
52
  }
41
- export type AdmissionLimitsInput = Partial<Omit<AdmissionLimits, "perSender">> & {
53
+ export type AdmissionLimitsInput = Partial<Omit<AdmissionLimits, "perSender" | "guest">> & {
42
54
  readonly perSender?: Partial<AdmissionLimits["perSender"]>;
55
+ readonly guest?: Partial<AdmissionLimits["guest"]>;
43
56
  };
44
57
  export type LocalizedText = Readonly<Record<string, string>>;
45
58
  export interface FirstContactSettings {
@@ -159,6 +172,12 @@ export interface SegmentStreamAgentConfigInput {
159
172
  * deployed code into the sandbox, read as the member. Requires `sandbox`. Off when absent.
160
173
  */
161
174
  readonly workspaceSource?: boolean;
175
+ /**
176
+ * The web the agent may read: `segmentstream__web_fetch` fetches `https://` pages of these
177
+ * domains, each also covering its subdomains, for callers who hold `agent_tool:web`. No web
178
+ * tool when absent.
179
+ */
180
+ readonly web?: WebSettings;
162
181
  /** @deprecated Retained only to read old workspace configs; it no longer selects behavior. */
163
182
  readonly confirmations?: {
164
183
  /** Legacy `deferred` is accepted and ignored. Remove this setting when upgrading. */
@@ -285,6 +304,8 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
285
304
  * {@link SegmentStreamAgentConfigInput.workspaceSource}.
286
305
  */
287
306
  readonly workspaceSource?: boolean;
307
+ /** The domains the web tools reach; absent without web tools. See {@link WebSettings}. */
308
+ readonly web?: WebSettings;
288
309
  readonly sessions: SessionSettings;
289
310
  /** The personas, with their texts once read; absent when `segmentstream.json` declares none. */
290
311
  readonly personas?: PersonaSettings;
@@ -356,11 +377,26 @@ export interface EmailSettings {
356
377
  readonly topic: string;
357
378
  } | null;
358
379
  }
380
+ /**
381
+ * The web the agent may read. `domains` are bare lower-case host names, such as `example.com`;
382
+ * each covers itself and its subdomains. Only `https://` pages of them are fetched, and every
383
+ * redirect must stay on them.
384
+ */
385
+ export interface WebSettings {
386
+ readonly domains: ReadonlyArray<string>;
387
+ }
388
+ /** The most domains `web.domains` lists. */
389
+ export declare const MAXIMUM_WEB_DOMAINS = 50;
359
390
  /**
360
391
  * The chat model choice `agent.ts` passes to `segmentstream.model()`, validated like `models.chat`
361
392
  * of `agent/segmentstream.json`, where it normally comes from.
362
393
  */
363
394
  export declare function chatModelChoiceOf(value: unknown): ChatModelChoice;
395
+ /**
396
+ * `limits` of `agent/segmentstream.json`, validated, with the platform's ceilings for what it leaves
397
+ * out: what the web channel sends with each turn. Throws {@link SegmentStreamAgentConfigError}.
398
+ */
399
+ export declare function admissionLimitsOf(value: unknown): AdmissionLimits;
364
400
  /** Exact historical pins retain the pre-0.13 presentation contract at the archive boundary. */
365
401
  export declare function isLegacyAgentArchive(version: string | undefined): boolean;
366
402
  /** Validates the authored configuration and applies the defaults. */