@segmentstream/agent 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.48.0
4
+
5
+ The agent's limits for people who signed up now apply to the web. Each message a member sends from
6
+ the browser starts a turn that the ontology counts against `limits` when `signUp` created them, by
7
+ email too, on the same counters as their turns on a messenger. Invited and paired members are never
8
+ counted. A turn beyond the limits is refused before it reaches the model with `429 rate_limited` and
9
+ `Retry-After`, and `useAgent()` reports it, like every refusal of the agent's routes, as a
10
+ `SegmentStreamApiError` with its code. The counts use the `limits` the agent last sent with a
11
+ messenger's turn, or the platform's defaults.
12
+
13
+ The agent token introspection (`POST /api/ontology/agent/tokens/introspect`) accepts `turn: true`
14
+ and then answers `limited: { scope, retry_after_seconds }` for a turn beyond the limits.
15
+
16
+ Action required: upgrade the ontology SDK together with the agent SDK. With an ontology SDK released
17
+ before this one, the agent asks again without the turn and web turns stay uncounted until
18
+ 2027-02-15; after that date they fail.
19
+
20
+ Pins @segmentstream/ontology 0.102.0.
21
+
3
22
  ## 0.47.0
4
23
 
5
24
  A member signed in to the workspace app can talk to the agent from the browser, as themselves and
package/README.md CHANGED
@@ -7,6 +7,9 @@ calls go through the workspace's connection, unknown senders pair with a member
7
7
  messages become text, and group chats are answered only when the agent is addressed or asked for
8
8
  something it does.
9
9
 
10
+ Guides named by path below, such as `docs/ontology.md`, are in every workspace project;
11
+ `segmentstream sync` keeps them current.
12
+
10
13
  The package is built against one eve version, `1.0.1`, and the workspace's `agent/` pins the
11
14
  same one. eve and the package move together.
12
15
 
@@ -149,7 +152,7 @@ text is missing. Guidance for the group decision model lives the same way in
149
152
  Skills stay eve's, in `agent/agent/skills/`. A module there that exports
150
153
  `forRoles(["accountant", "founder"], { description, content })` is a skill only those roles get:
151
154
  it is an eve dynamic skill, listed and loadable only in sessions started by a person holding one
152
- of the roles. See [personas and skills by role](../../docs/agent.md#personas-and-skills-by-role)
155
+ of the roles. See personas and skills by role (`docs/agent.md#personas-and-skills-by-role`)
153
156
  in the workspace agent guide.
154
157
 
155
158
  ## Reply review
@@ -160,7 +163,7 @@ Telegram and WhatsApp: `{ "review": { "mode": "never" } }` (the agent, the defau
160
163
  `{ "mode": "whenUnsure", "minConfidence": 0.9 }` (the decision model judges each reply in its
161
164
  chat, with the criteria in `agent/review/<role>.md`, and the agent sends those it is sure
162
165
  enough of). A held reply becomes an `agent_review` record of the ontology, which a member
163
- approves, edits or rejects. See [reply review](../../docs/agent.md#reply-review) in the workspace
166
+ approves, edits or rejects. See reply review (`docs/agent.md#reply-review`) in the workspace
164
167
  agent guide.
165
168
 
166
169
  ## Channel admission and first contact
@@ -321,9 +324,8 @@ SHA-256. No URL, header or credential enters the sandbox. `segmentstream__read_f
321
324
  so PNG, JPEG, GIF and WebP images up to 3 MiB and PDFs up to 20 MiB reach the model as files.
322
325
 
323
326
  `segmentstream__workspace_source`, offered to members with `"workspaceSource": true`, copies the
324
- commit production runs into `/workspace/source` for a member who holds `workspace_source:read`
325
- (see `docs/workspace-source-spec.md`). The runtime reads `/api/ontology/agent/source` page by page
326
- as the member with its own token, refuses pages that name different commits (starting once more
327
+ commit production runs into `/workspace/source` for a member who holds `workspace_source:read`.
328
+ 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
327
329
  when production moves meanwhile) and archives with entries other than files and directories or
328
330
  paths outside their root, extracts them into `/workspace/source.tmp`, swaps that in read-only and
329
331
  writes `/workspace/.segmentstream/source.json` with the member, the commit, the turn and the counts.
@@ -381,7 +383,7 @@ client with a member, and it negotiates neither chat posting nor the chat's runt
381
383
 
382
384
  A workflow hands the workspace's agent a prompt with `agentTask` from
383
385
  `@segmentstream/ontology/workflows` and waits for its answer
384
- ([the specification](../../docs/agent-tasks-spec.md)). The task runs in an ordinary session of the
386
+ (see `docs/ontology.md#agent-tasks`). The task runs in an ordinary session of the
385
387
  same agent: its instructions, model choice from the principal's roles, tools, guides and sandbox.
386
388
  The SDK adds no text to the prompt.
387
389
 
@@ -457,7 +459,7 @@ The SDK adds no text to the prompt.
457
459
  steers their running turn, and other members' messages queue behind it. Turn cancellations use
458
460
  `texts.notice.cancelled` with a symbol fallback; an unconfigured failure notice never consists
459
461
  only of a reference. Diagnostics remain in operator logs.
460
- See [group configuration](../../docs/agent.md#groups).
462
+ See group configuration (`docs/agent.md#groups`).
461
463
  - **Voice.** Voice messages, audio files and video notes are downloaded through the connection and
462
464
  transcribed with `models.stt` through AI Gateway before the turn.
463
465
  The transcript becomes the message, with a note such as `[voice message, 12 s]` in
@@ -744,9 +746,7 @@ Archive metadata and message text retain the workspace policy (365 days by defau
744
746
  Platform REST reads, the workspace ontology's
745
747
  `chat_history` and `chat_search`, and the member REST facade enforce workspace/group
746
748
  permissions and DM participant/admin scope. Deploy the backend migration/API and upgrade the
747
- ontology SDK along with this extension. See the repository's
748
- [chat storage guide](../../docs/agent-chat-storage.md) for APIs, retention,
749
- eve's existing storage, and Telegram's delivery limits.
749
+ ontology SDK along with this extension.
750
750
 
751
751
  ### Exact chat posting protocol
752
752
 
@@ -801,7 +801,7 @@ An older archive returning only `{stored:true}` cannot authorize a send.
801
801
  Rollback
802
802
  disables posting while preserving archive claims and deduplication tombstones;
803
803
  it never restores relay or retries uncertain deliveries.
804
- See [migration and verification](../../docs/agent-chat-delivery-migration.md).
804
+ See migration and verification (`docs/agent-chat-delivery-migration.md`).
805
805
 
806
806
  ### Deleted session deployments
807
807
 
@@ -841,7 +841,6 @@ The first insert also emits `[segmentstream] model service alert` in runtime log
841
841
  Per-turn diagnostics remain available; alerting failures do not replace the original
842
842
  error. Read alerts with `segmentstream agent logs --query model_service_alert --all`.
843
843
  This does not submit member feedback or send an operator chat message.
844
- See [the incident and verification procedure](../../docs/telegram-session-recovery.md).
845
844
 
846
845
  ### Opt-in attachment lifecycle
847
846
 
@@ -949,10 +948,10 @@ data schemas; workspaces opt in only after their hook accepts the additional fie
949
948
  Runtime health reports native approvals and attachment-lifecycle presence behind its existing
950
949
  runtime authentication; source pins and public health alone are not adoption proof.
951
950
 
952
- Telegram 0.13.0 requires workspace-authored pairing and confirmation text. See [workspace Telegram text](../../docs/agent.md#workspace-telegram-text) for keys, limits, neutral fallbacks and unsupported Eve buttons.
951
+ Telegram 0.13.0 requires workspace-authored pairing and confirmation text. See workspace Telegram text (`docs/agent.md#workspace-telegram-text`) for keys, limits, neutral fallbacks and unsupported Eve buttons.
953
952
 
954
- Workspace [callback actions](../../docs/agent.md#workspace-callback-actions) and
955
- [structured Telegram input](../../docs/agent.md#structured-telegram-input) are separate opt-in
953
+ Workspace callback actions (`docs/agent.md#workspace-callback-actions`) and
954
+ structured Telegram input (`docs/agent.md#structured-telegram-input`) are separate opt-in
956
955
  mappings. They require the ontology runtime-source capability and dispatch only a currently
957
956
  permitted routine action as the verified member. The workspace owns callback tokens, presentation
958
957
  and business idempotency.
@@ -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.47.0";
7
+ var version = "0.48.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -4,4 +4,4 @@ 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
- export { t as agentBuild } from "../../_chunks/build-metadata-5S6uTvyu.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-DjhDPTy-.mjs";
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-5S6uTvyu.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DjhDPTy-.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -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 { t as agentBuild } from "../../../_chunks/build-metadata-5S6uTvyu.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DjhDPTy-.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { d as telegramRuntimeSource, l as principalRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-Dzs8hUDB.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-5S6uTvyu.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-DjhDPTy-.mjs";
9
9
  import { n as currentInboundRequest } from "../../../_chunks/inbound-request-B3RhCuOw.mjs";
10
10
  import { object } from "../confirmation-description.mjs";
11
11
  import { needsConfirmation } from "../confirmations.mjs";
@@ -1,5 +1,5 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
- import { type AuthFn } from "eve/channels/auth";
2
+ import { ForbiddenError, type AuthFn } from "eve/channels/auth";
3
3
  import { type Environment } from "../environment.js";
4
4
  import { type RuntimeToken } from "../runtime-token.js";
5
5
  /**
@@ -29,12 +29,33 @@ export interface WebMember {
29
29
  readonly chat: string;
30
30
  readonly roles: ReadonlyArray<string>;
31
31
  readonly name?: string;
32
+ /**
33
+ * For a turn the member starts: the agent's limit for people who signed up that it exceeds, and
34
+ * when the next turn may run. Members invited or paired are never limited.
35
+ */
36
+ readonly limited?: {
37
+ readonly scope: string;
38
+ readonly retryAfterSeconds: number;
39
+ };
32
40
  }
33
41
  /**
34
42
  * Asks whom a token stands for, for the origin the member reached the agent on: the member, or
35
- * `undefined` when it stands for nobody. Throws when the ontology cannot answer.
43
+ * `undefined` when it stands for nobody. With `turn`, the member is starting a turn, which the
44
+ * ontology counts against the agent's limits. Throws when the ontology cannot answer.
36
45
  */
37
- export type WebIntrospection = (token: string, origin: string) => Promise<WebMember | undefined>;
46
+ export type WebIntrospection = (token: string, origin: string, turn?: boolean) => Promise<WebMember | undefined>;
47
+ /** The code of the answer to a turn the agent's limits refuse, as the ontology's own refusals. */
48
+ export declare const TURN_LIMITED_CODE = "rate_limited";
49
+ /**
50
+ * A turn the agent's limits for people who signed up refuse: answered `429 rate_limited` with
51
+ * `Retry-After`, before the turn reaches the model. The answer carries no words: the app's chat
52
+ * reports it by its code in the workspace's own.
53
+ */
54
+ export declare class TurnLimitedError extends ForbiddenError {
55
+ readonly retryAfterSeconds: number;
56
+ readonly response: Response;
57
+ constructor(retryAfterSeconds: number);
58
+ }
38
59
  /** The member an introspection answer names, when it is active and names their own chat. */
39
60
  export declare function webMemberOf(body: unknown): WebMember | undefined;
40
61
  /** The ontology's introspection, called with the deployment's runtime token. */
@@ -55,6 +76,8 @@ export interface WebAuthOptions {
55
76
  * The route authenticator for the agent's own HTTP channel: a request with an agent token runs as
56
77
  * the member it stands for, and any other request goes on to the next authenticator. An answer to
57
78
  * one of the agent's confirmations through its own buttons is stamped with its decision, as a click
58
- * on a Telegram card is, so that only a click, never a typed message, decides a confirmation.
79
+ * on a Telegram card is, so that only a click, never a typed message, decides a confirmation. A
80
+ * message starts a turn, which counts against the agent's limits for people who signed up, as their
81
+ * turns on a messenger do; one beyond them is refused with {@link TurnLimitedError}.
59
82
  */
60
83
  export declare function webAuth(options?: WebAuthOptions): AuthFn<Request>;
@@ -9,7 +9,7 @@ import { withChatAddress } from "../chat-address.mjs";
9
9
  import { appOrigin } from "../environment.mjs";
10
10
  import { runtimeToken } from "../runtime-token.mjs";
11
11
  import { createHash } from "node:crypto";
12
- import { UnauthenticatedError } from "eve/channels/auth";
12
+ import { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";
13
13
  const WEB_AUTHENTICATOR = "segmentstream-web";
14
14
  const WEB_PROVIDER = "web";
15
15
  const AGENT_GRANT_HEADER = "X-SegmentStream-Agent-Grant";
@@ -19,6 +19,30 @@ const INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
19
19
  const INTROSPECTION_TIMEOUT_MS = 5e3;
20
20
  const ANSWER_TTL_MS = 6e4;
21
21
  const ANSWER_LIMIT = 1e3;
22
+ const TURN_LIMITED_CODE = "rate_limited";
23
+ var TurnLimitedError = class extends ForbiddenError {
24
+ retryAfterSeconds;
25
+ response;
26
+ constructor(retryAfterSeconds) {
27
+ super({
28
+ code: TURN_LIMITED_CODE,
29
+ message: TURN_LIMITED_CODE
30
+ });
31
+ this.retryAfterSeconds = retryAfterSeconds;
32
+ this.name = "TurnLimitedError";
33
+ this.response = Response.json({
34
+ code: TURN_LIMITED_CODE,
35
+ ok: false,
36
+ retry_after_seconds: retryAfterSeconds
37
+ }, {
38
+ status: 429,
39
+ headers: {
40
+ "cache-control": "no-store",
41
+ "retry-after": String(retryAfterSeconds)
42
+ }
43
+ });
44
+ }
45
+ };
22
46
  function strings(value) {
23
47
  return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
24
48
  }
@@ -27,28 +51,39 @@ function webMemberOf(body) {
27
51
  const answer = body;
28
52
  const roles = strings(answer.roles);
29
53
  if (answer.active !== true || typeof answer.member_id !== "string" || typeof answer.grant_id !== "string" || answer.chat !== `member:${answer.member_id}` || roles === void 0) return;
54
+ const limited = answer.limited;
30
55
  return {
31
56
  memberId: answer.member_id,
32
57
  grant: answer.grant_id,
33
58
  chat: answer.chat,
34
59
  roles,
35
- ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {}
60
+ ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
61
+ ...typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
62
+ scope: typeof limited.scope === "string" ? limited.scope : "",
63
+ retryAfterSeconds: limited.retry_after_seconds
64
+ } } : {}
36
65
  };
37
66
  }
38
67
  function ontologyIntrospection(options = {}) {
39
- return async (token, origin) => {
40
- const response = await (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${INTROSPECTION_PATH}`, {
68
+ return async (token, origin, turn) => {
69
+ const ask = async (body) => (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${INTROSPECTION_PATH}`, {
41
70
  method: "POST",
42
71
  headers: {
43
72
  authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
44
73
  "content-type": "application/json"
45
74
  },
46
- body: JSON.stringify({
47
- token,
48
- origin
49
- }),
75
+ body: JSON.stringify(body),
50
76
  signal: AbortSignal.timeout(INTROSPECTION_TIMEOUT_MS)
51
77
  });
78
+ let response = await ask({
79
+ token,
80
+ origin,
81
+ ...turn === true ? { turn: true } : {}
82
+ });
83
+ if (turn === true && response.status === 400) response = await ask({
84
+ token,
85
+ origin
86
+ });
52
87
  if (!response.ok) throw new Error(`The ontology could not say whom an agent token stands for (${response.status}).`);
53
88
  return webMemberOf(await response.json());
54
89
  };
@@ -84,25 +119,32 @@ function bearerOf(request) {
84
119
  const header = request.headers.get("authorization") ?? "";
85
120
  return /^Bearer\s+(.+)$/iu.exec(header.trim())?.[1];
86
121
  }
87
- async function answersOf(request) {
88
- if (request.method !== "POST") return [];
122
+ async function bodyOf(request) {
123
+ if (request.method !== "POST") return;
89
124
  try {
90
125
  const body = await request.clone().json();
91
- const answers = typeof body === "object" && body !== null ? body.answers : [];
92
- return Array.isArray(answers) ? answers.filter((answer) => typeof answer === "object" && answer !== null && typeof answer.interactionId === "string") : [];
126
+ return typeof body === "object" && body !== null ? body : void 0;
93
127
  } catch {
94
- return [];
128
+ return;
95
129
  }
96
130
  }
131
+ function answersOf(body) {
132
+ const answers = body?.answers;
133
+ return Array.isArray(answers) ? answers.filter((answer) => typeof answer === "object" && answer !== null && typeof answer.interactionId === "string") : [];
134
+ }
135
+ function startsTurn(body) {
136
+ return body?.message !== void 0 && body.message !== null;
137
+ }
97
138
  function answerCache(introspect) {
98
139
  const answers = new Map();
99
- return async (token, origin) => {
140
+ return async (token, origin, turn) => {
141
+ if (turn === true) return introspect(token, origin, true);
100
142
  const key = createHash("sha256").update(`${origin} ${token}`).digest("hex");
101
143
  const now = Date.now();
102
144
  const kept = answers.get(key);
103
145
  if (kept !== void 0 && kept.until > now) return kept.member;
104
146
  answers.delete(key);
105
- const member = await introspect(token, origin);
147
+ const member = await introspect(token, origin, false);
106
148
  if (member !== void 0) {
107
149
  if (answers.size >= ANSWER_LIMIT) answers.delete(answers.keys().next().value);
108
150
  answers.set(key, {
@@ -119,12 +161,14 @@ function webAuth(options = {}) {
119
161
  const token = bearerOf(request);
120
162
  if (token === void 0 || !token.startsWith("sso_")) return null;
121
163
  introspect ??= answerCache(options.introspect ?? ontologyIntrospection());
122
- const member = await introspect(token, new URL(request.url).origin);
164
+ const body = await bodyOf(request);
165
+ const member = await introspect(token, new URL(request.url).origin, startsTurn(body));
123
166
  if (member === void 0) throw new UnauthenticatedError({
124
167
  code: "agent_token_invalid",
125
168
  message: "The agent token is invalid or expired."
126
169
  });
127
- return withButtonDecision(webPrincipal(member), await answersOf(request));
170
+ if (member.limited !== void 0) throw new TurnLimitedError(member.limited.retryAfterSeconds);
171
+ return withButtonDecision(webPrincipal(member), answersOf(body));
128
172
  };
129
173
  }
130
- export { ACCESS_TOKEN_PREFIX, AGENT_GRANT_HEADER, INTROSPECTION_PATH, WEB_AUTHENTICATOR, WEB_GRANT_ATTRIBUTE, WEB_PROVIDER, ontologyIntrospection, webAuth, webGrantOf, webMemberOf, webPrincipal };
174
+ export { ACCESS_TOKEN_PREFIX, AGENT_GRANT_HEADER, INTROSPECTION_PATH, TURN_LIMITED_CODE, TurnLimitedError, WEB_AUTHENTICATOR, WEB_GRANT_ATTRIBUTE, WEB_PROVIDER, ontologyIntrospection, webAuth, webGrantOf, webMemberOf, webPrincipal };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -80,7 +80,7 @@
80
80
  "@chat-adapter/state-memory": "4.42.0",
81
81
  "@chat-adapter/telegram": "4.41.0",
82
82
  "@chat-adapter/whatsapp": "4.42.0",
83
- "@segmentstream/ontology": "0.101.0",
83
+ "@segmentstream/ontology": "0.102.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",