@segmentstream/agent 0.72.2 → 0.72.3

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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.72.3
4
+
5
+ Group routing's log names the route a message took. Each message logs one
6
+ `[segmentstream] telegram route` line for the live policy, a failure included, with the outcome
7
+ of `groups.observability.shadow` beside it as `shadow: { route, reason }`. The shadow policy no
8
+ longer logs a route of its own, which could read as the live one; a shadow failure is logged
9
+ with `shadow: true` and its cause. Chat-policy failures now log on that line, with the route
10
+ taken and the cause, instead of a separate `chat routing failed` line.
11
+
12
+ Routing's read of a chat's recent messages from the archive now gives up after 8 seconds rather
13
+ than the archive's 15, leaving the decision model and the turn their time. A read that runs out
14
+ routes as a failed decision model does.
15
+
3
16
  ## 0.72.2
4
17
 
5
18
  Pins @segmentstream/ontology 0.148.0.
@@ -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.72.2";
7
+ var version = "0.72.3";
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-BqO3Ozio.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CssbWQOM.mjs";
@@ -69,16 +69,15 @@ export interface ChatArchive {
69
69
  readonly from?: string;
70
70
  readonly senderId?: string;
71
71
  readonly messageId?: string;
72
+ /** Ends the read sooner than the archive's own timeout: the caller's budget for it. */
73
+ readonly signal?: AbortSignal;
72
74
  }): Promise<ChatPage>;
73
75
  /**
74
76
  * The channel's replies still to deliver, in every chat of `provider`, newest first: reply
75
- * operations (`operationId` `reply:<key>`) whose newest state is `requested`. Archives that
77
+ * operations (`operationId` `reply:<key>`) whose newest state is `requested`, of those requested
78
+ * no later than `requestedBefore` (an ISO time), the ones due for another attempt. Archives that
76
79
  * predate it have none.
77
80
  */
78
- /**
79
- * A channel's replies still `requested`, newest first, of those requested no later than
80
- * `requestedBefore` (an ISO time): the ones due for another attempt.
81
- */
82
81
  pendingReplies?(input: {
83
82
  readonly provider: string;
84
83
  readonly limit: number;
@@ -119,7 +119,7 @@ function chatArchive(input = {}) {
119
119
  const environment = input.environment ?? process.env;
120
120
  const token = input.token ?? runtimeToken;
121
121
  const fetchImpl = input.fetch ?? fetch;
122
- async function call(path, body) {
122
+ async function call(path, body, signal) {
123
123
  const env = proxyEnvironment(environment);
124
124
  const identity = await token();
125
125
  const base = `${env.segmentstreamUrl}/api/internal/v1/workspaces/${encodeURIComponent(env.workspaceId)}`;
@@ -132,7 +132,7 @@ function chatArchive(input = {}) {
132
132
  "x-segmentstream-runtime-identity": identity
133
133
  },
134
134
  body: JSON.stringify(workflowValue(body, { boundary: "chat archive" })),
135
- signal: AbortSignal.timeout(15e3)
135
+ signal: signal === void 0 ? AbortSignal.timeout(15e3) : AbortSignal.any([signal, AbortSignal.timeout(15e3)])
136
136
  });
137
137
  if (!response.ok) throw new Error(`Chat archive ${path} failed (${response.status}); request ${response.headers.get("x-request-id") ?? "unknown"}.`);
138
138
  return response.json();
@@ -141,7 +141,7 @@ function chatArchive(input = {}) {
141
141
  append: async (event) => {
142
142
  return (await call("events", event)).stored;
143
143
  },
144
- context: async ({ includeDecisions, participantId, ...search }) => await call("search", {
144
+ context: async ({ includeDecisions, participantId, signal, ...search }) => await call("search", {
145
145
  search,
146
146
  context: !includeDecisions,
147
147
  reader: {
@@ -149,7 +149,7 @@ function chatArchive(input = {}) {
149
149
  groups: includeDecisions === true,
150
150
  admin: false
151
151
  }
152
- }),
152
+ }, signal),
153
153
  lastChat: async ({ provider, senderId, participantId }) => {
154
154
  return (await call("search", {
155
155
  search: {
@@ -99,7 +99,12 @@ export declare function decisionRouter(input: {
99
99
  */
100
100
  export declare function routeMessage(input: {
101
101
  readonly groups?: GroupPolicy;
102
- readonly metrics?: boolean;
102
+ /**
103
+ * An evaluation that only observes, the shadow of `observability.shadow`: it records no routing
104
+ * metric, and it logs no route of its own, only a failure with its cause. The live route's log
105
+ * and archived decision carry its outcome.
106
+ */
107
+ readonly shadow?: boolean;
103
108
  readonly signals?: GroupMessageSignals;
104
109
  readonly pendingQuestionAt?: string;
105
110
  readonly chatId: string;
@@ -253,7 +253,7 @@ async function routeMessage(input) {
253
253
  }
254
254
  },
255
255
  beforeDecide: void 0,
256
- metrics: false,
256
+ shadow: true,
257
257
  question: async () => question ?? input.question(),
258
258
  record: (decision) => {
259
259
  shadow = { ...decision };
@@ -266,7 +266,8 @@ async function routeMessage(input) {
266
266
  })();
267
267
  return shadowRun;
268
268
  };
269
- const complete = async (route, reason, note, logReason = reason, diagnostics, uncertain = false) => {
269
+ const complete = async (route, reason, note, options = {}) => {
270
+ const { diagnostics, uncertain = false, error } = options;
270
271
  if (reason !== "admission_refused") await evaluateShadow();
271
272
  payload = {
272
273
  ...payload,
@@ -276,7 +277,7 @@ async function routeMessage(input) {
276
277
  ...uncertain ? { uncertain } : {}
277
278
  }
278
279
  };
279
- if (input.metrics !== false) recordRoutingMetric(signals?.provider ?? "unknown", route, reason, diagnostics?.latencyMs);
280
+ if (input.shadow !== true) recordRoutingMetric(signals?.provider ?? "unknown", route, reason, diagnostics?.latencyMs);
280
281
  input.record?.({
281
282
  route,
282
283
  ...uncertain ? { uncertain: true } : {},
@@ -290,11 +291,22 @@ async function routeMessage(input) {
290
291
  } },
291
292
  ...diagnostics === void 0 ? {} : { diagnostics }
292
293
  });
293
- if (reason !== "decision_model_failed" && reason !== "decision_model_timeout") console.info("[segmentstream] telegram route", {
294
+ const logged = {
294
295
  route,
295
- reason: logReason,
296
- ...diagnostics
296
+ reason: options.logReason ?? reason,
297
+ ...diagnostics,
298
+ ...shadow === void 0 ? {} : { shadow: {
299
+ route: shadow.route,
300
+ reason: shadow.reason
301
+ } }
302
+ };
303
+ if (error !== void 0) console.error("[segmentstream] telegram route", {
304
+ ...logged,
305
+ ...input.shadow === true ? { shadow: true } : {},
306
+ note,
307
+ error
297
308
  });
309
+ else if (input.shadow !== true) console.info("[segmentstream] telegram route", logged);
298
310
  return route;
299
311
  };
300
312
  if (groups.smart.engagement.policy === "chat" && signals !== void 0 && signals.chat.kind !== "direct") {
@@ -336,15 +348,24 @@ async function routeMessage(input) {
336
348
  ...payload,
337
349
  ...typeof result === "string" ? {} : result.router
338
350
  };
339
- return outcome === "uncertain" ? complete("reply", "decision_model_uncertain", "The decision model was not sure the message is for the agent; the agent decides.", "decision-model", diagnostics, true) : complete(outcome, `decision_model_${outcome}`, "Addressee read from the chat's recent messages.", "decision-model", diagnostics);
351
+ return outcome === "uncertain" ? complete("reply", "decision_model_uncertain", "The decision model was not sure the message is for the agent; the agent decides.", {
352
+ logReason: "decision-model",
353
+ diagnostics,
354
+ uncertain: true
355
+ }) : complete(outcome, `decision_model_${outcome}`, "Addressee read from the chat's recent messages.", {
356
+ logReason: "decision-model",
357
+ diagnostics
358
+ });
340
359
  } catch (error) {
341
- console.error("[segmentstream] chat routing failed", { error });
342
360
  const timeout = error instanceof Error && error.name === "TimeoutError";
343
361
  if (thresholds.defer !== void 0 && thresholds.defer < thresholds.reply) {
344
- if (!admitted && input.beforeDecide && !await input.beforeDecide().catch(() => false)) return complete("observe", "admission_refused", "Admission refused before the turn.");
345
- return complete("reply", timeout ? "decision_model_timeout_uncertain" : "decision_model_failed_uncertain", "Chat routing unavailable; the agent decides.", void 0, void 0, true);
362
+ if (!admitted && input.beforeDecide && !await input.beforeDecide().catch(() => false)) return complete("observe", "admission_refused", "Admission refused before the turn.", { error });
363
+ return complete("reply", timeout ? "decision_model_timeout_uncertain" : "decision_model_failed_uncertain", "Chat routing unavailable; the agent decides.", {
364
+ uncertain: true,
365
+ error
366
+ });
346
367
  }
347
- return complete("observe", timeout ? "decision_model_timeout" : "decision_model_failed", "Chat routing unavailable; observe fallback.");
368
+ return complete("observe", timeout ? "decision_model_timeout" : "decision_model_failed", "Chat routing unavailable; observe fallback.", { error });
348
369
  }
349
370
  }
350
371
  if (addressed !== void 0 && addressed !== "pending-question" && addressed !== "reply-to-bot") return complete("reply", addressed, `Bot addressed directly: ${addressed}.`);
@@ -422,17 +443,16 @@ async function routeMessage(input) {
422
443
  category: thread ? "humanThread" : engagement?.strength === "explicit" ? "engaged" : "neutral"
423
444
  }
424
445
  };
425
- return complete(route, below ? "decision_model_below_threshold" : `decision_model_${route}`, `Smart model selected ${route}; reply target: ${question.audience?.replyTo?.kind ?? "none"}; tagged recipients: ${question.audience?.mentions.length ?? 0}.`, "decision-model", typeof result === "string" ? void 0 : result.diagnostics);
446
+ return complete(route, below ? "decision_model_below_threshold" : `decision_model_${route}`, `Smart model selected ${route}; reply target: ${question.audience?.replyTo?.kind ?? "none"}; tagged recipients: ${question.audience?.mentions.length ?? 0}.`, {
447
+ logReason: "decision-model",
448
+ ...typeof result === "string" ? {} : { diagnostics: result.diagnostics }
449
+ });
426
450
  } catch (error) {
427
451
  const timeout = error instanceof Error && error.name === "TimeoutError";
428
- const note = timeout ? "Routing timed out; observe fallback." : "Routing failed; observe fallback.";
429
- console.error("[segmentstream] telegram route", {
430
- route: "observe",
431
- reason: timeout ? "decision-timeout" : "decision-failure",
432
- note,
452
+ return complete("observe", timeout ? "decision_model_timeout" : "decision_model_failed", timeout ? "Routing timed out; observe fallback." : "Routing failed; observe fallback.", {
453
+ logReason: timeout ? "decision-timeout" : "decision-failure",
433
454
  error
434
455
  });
435
- return complete("observe", timeout ? "decision_model_timeout" : "decision_model_failed", note);
436
456
  }
437
457
  }
438
458
  export { FOLLOW_UP_WINDOW_MS, decisionRouter, routeMessage, routingEvidence };
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-BqO3Ozio.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CssbWQOM.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -48,6 +48,7 @@ import { downloadTelegramFile } from "./voice.mjs";
48
48
  import { telegramWebhookVerifier } from "./webhook.mjs";
49
49
  import { telegramPreviewEnvironment } from "@segmentstream/ontology/telegram";
50
50
  import { telegramChannel } from "eve/channels/telegram";
51
+ const ROUTING_READ_TIMEOUT_MS = 8e3;
51
52
  const LEGACY_DEFERRED_CALLBACK = "ss-confirm:d:";
52
53
  async function typing(_event, ctx) {
53
54
  await ctx.channel.telegram.startTyping();
@@ -232,7 +233,8 @@ function segmentstreamTelegram(options) {
232
233
  chatId,
233
234
  threadId: threadId ?? null,
234
235
  limit: 200,
235
- includeDecisions: true
236
+ includeDecisions: true,
237
+ signal: AbortSignal.timeout(ROUTING_READ_TIMEOUT_MS)
236
238
  })).events, 100),
237
239
  signalSettings: settings().groups,
238
240
  ...settings().inbound === void 0 ? {} : { structured: {
@@ -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-BqO3Ozio.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CssbWQOM.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 { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-Cw1NtCkj.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-BqO3Ozio.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CssbWQOM.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.72.2",
3
+ "version": "0.72.3",
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",