@segmentstream/agent 0.38.3 → 0.39.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/README.md CHANGED
@@ -120,25 +120,51 @@ See [Sandbox](#sandbox).
120
120
  | `models.decision` | `"typesafe-ai/jev-1.14.0"` | The AI Gateway decision model of the inbound router |
121
121
  | `ontology.connection` | `true` | Whether the agent reaches the ontology over MCP |
122
122
  | `sandbox` | `false` | `true` adds `bash`, `read_file` and `write_file` in the agent's sandbox without network; see [Sandbox](#sandbox) |
123
+ | `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) |
123
124
 
124
125
  An unknown field or an invalid value fails the mount with `SegmentStreamAgentConfigError`, naming
125
126
  each path. `manifestOf(config)` returns the normalized configuration, defaults applied, for the
126
127
  platform's deployment manifest.
127
128
 
129
+ ## Personas and skills by role
130
+
131
+ The shared instructions (`agent/agent/instructions.md`) reach everyone the agent talks to. A
132
+ persona, `agent/personas/<name>.md`, says who the agent is to the person in a conversation: one
133
+ per conversation, the first `personas.byRole` entry whose role the person who started it holds,
134
+ else `personas.default`. eve reads no folder at runtime, so the mount imports each persona text
135
+ with `?raw` and passes it under `files`; the build fails when a named text is missing:
136
+
137
+ ```ts
138
+ /// <reference types="@segmentstream/agent/raw" />
139
+ import { segmentstream } from "@segmentstream/agent/extension";
140
+
141
+ import config from "../../segmentstream.json";
142
+ import seller from "../../personas/seller.md?raw";
143
+
144
+ export default segmentstream({ ...config, files: { "personas/seller.md": seller } });
145
+ ```
146
+
147
+ Skills stay eve's, in `agent/agent/skills/`. A module there that exports
148
+ `forRoles(["accountant", "founder"], { description, content })` is a skill only those roles get:
149
+ it is an eve dynamic skill, listed and loadable only in sessions started by a person holding one
150
+ of the roles. See [personas and skills by role](../../docs/agent.md#personas-and-skills-by-role)
151
+ in the workspace agent guide.
152
+
128
153
  ## Channel admission and first contact
129
154
 
130
155
  The platform and SDK provide admission, identity resolution, onboarding execution, notice tracking
131
- and durable limits. Workspace apps own channel policy, member grants, onboarding actions, notice
132
- content and lower limit values. No channel defaults to open, and no notice or limit reply text
133
- ships as a default. Existing invited-channel pairing and refusal replies remain unchanged.
134
-
135
- Admission belongs in the ontology's `signIn.channels`; each unlisted provider stays invited,
136
- independently of email `signIn.policy`. Opening a channel is an explicit workspace opt-in.
137
- For an intentionally open provider, declare safe named `member.permissions`. Wildcards and
138
- generated create/update/delete grants are rejected. Shared named reads need review; move staff
139
- reads into a named role. Actions handling a member's own records enforce ownership with
140
- `principal.id`. Groups never register users. Closing a channel stops new registrations;
141
- block or deactivate an existing member to stop their access.
156
+ and durable limits. Workspace apps own where sign-up is open, the roles it grants, onboarding
157
+ actions, notice content and lower limit values. No channel defaults to open, and no notice or limit
158
+ reply text ships as a default. Existing invited-channel pairing and refusal replies remain unchanged.
159
+
160
+ Admission belongs in the ontology's `signUp`: a stranger's first private message on a listed
161
+ channel makes them a user holding the roles `signUp` names; every other channel admits only
162
+ invited or paired people. Opening a channel is an explicit workspace opt-in, and `check` refuses
163
+ sign-up roles with wildcards or unscoped generated writes. Actions handling a person's own
164
+ records enforce ownership with `principal.id`. Groups never register users. Closing a channel
165
+ stops new registrations; block or deactivate an existing user to stop their access. The earlier
166
+ `signIn.channels.<provider>: "open"`, which gives strangers `member`, remains as a deprecated
167
+ alias.
142
168
 
143
169
  Configure app-owned text and lower limits in `agent/segmentstream.json`. These placeholders
144
170
  represent text authored by the workspace, not SDK defaults:
@@ -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.38.3";
7
+ var version = "0.39.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -4,6 +4,7 @@ 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 PersonaSettings } from "./personas.js";
7
8
  import { type TelegramLinkPreviews } from "@segmentstream/ontology/telegram";
8
9
  export declare const TELEGRAM_POLICIES: readonly ["mention", "smart"];
9
10
  /**
@@ -159,6 +160,20 @@ export interface SegmentStreamAgentConfigInput {
159
160
  */
160
161
  readonly idleResetHours?: unknown;
161
162
  };
163
+ /**
164
+ * What the agent is to the person in a session: a persona per role, the first role the person
165
+ * who started the session holds winning in the order written, and a `default` for everyone else.
166
+ * Each persona's text is `agent/personas/<name>.md`.
167
+ */
168
+ readonly personas?: {
169
+ readonly byRole?: Readonly<Record<string, string>>;
170
+ readonly default?: string;
171
+ };
172
+ /**
173
+ * The persona texts, by path beside `segmentstream.json`. Only the mount passes them, imported
174
+ * with `?raw`, because eve reads no directory at runtime.
175
+ */
176
+ readonly files?: Readonly<Record<string, string>>;
162
177
  }
163
178
  export interface TelegramSettings {
164
179
  readonly groups?: {
@@ -223,6 +238,10 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
223
238
  /** Whether the sandbox file tools are on; see {@link SegmentStreamAgentConfigInput.sandbox}. */
224
239
  readonly sandbox: boolean;
225
240
  readonly sessions: SessionSettings;
241
+ /** The personas; absent when `segmentstream.json` declares none. */
242
+ readonly personas?: PersonaSettings;
243
+ /** The persona texts the mount passes; absent when validating the JSON alone. */
244
+ readonly files?: Readonly<Record<string, string>>;
226
245
  }
227
246
  /** One validation failure, in Standard Schema's issue shape. */
228
247
  export interface ConfigIssue {
@@ -274,6 +293,11 @@ export declare function isLegacyAgentArchive(version: string | undefined): boole
274
293
  /** Validates the authored configuration and applies the defaults. */
275
294
  export declare function validateConfig(input: unknown, options?: {
276
295
  readonly archiveSdkVersion?: string;
296
+ /**
297
+ * Whether the mount is validating: it passes the persona texts as `files`. The platform
298
+ * validates `segmentstream.json` alone and reads the texts from the archive.
299
+ */
300
+ readonly mount?: boolean;
277
301
  }): Validation;
278
302
  /**
279
303
  * The Standard Schema eve validates the mount with. `types` exists only for type inference, as the
@@ -9,6 +9,7 @@ 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 { bundledFiles, personaSettings } from "./personas.mjs";
12
13
  import { readFileSync, realpathSync } from "node:fs";
13
14
  import { expandGroupFiles, groupPolicyIssues } from "@segmentstream/ontology/groups";
14
15
  import { TELEGRAM_LINK_PREVIEWS, isHttpOrigin } from "@segmentstream/ontology/telegram";
@@ -583,7 +584,9 @@ function validateConfig(input, options = {}) {
583
584
  "firstContact",
584
585
  "limits",
585
586
  "replies",
586
- "texts"
587
+ "texts",
588
+ "personas",
589
+ "files"
587
590
  ],
588
591
  issues
589
592
  });
@@ -764,6 +767,16 @@ function validateConfig(input, options = {}) {
764
767
  message: "must be true or false",
765
768
  path: ["sandbox"]
766
769
  });
770
+ const personas = personaSettings(root?.personas, issues);
771
+ const files = options.mount === true ? bundledFiles({
772
+ value: root?.files,
773
+ personas,
774
+ issues
775
+ }) : void 0;
776
+ if (options.mount !== true && root?.files !== void 0) issues.push({
777
+ message: "is passed by agent/agent/extensions/segmentstream.ts, not set in segmentstream.json",
778
+ path: ["files"]
779
+ });
767
780
  if (issues.length > 0) return { issues };
768
781
  return { value: {
769
782
  groups,
@@ -788,13 +801,15 @@ function validateConfig(input, options = {}) {
788
801
  firstContact,
789
802
  limits,
790
803
  replies,
791
- texts
804
+ texts,
805
+ ...personas === null ? {} : { personas },
806
+ ...files === void 0 || Object.keys(files).length === 0 ? {} : { files }
792
807
  } };
793
808
  }
794
809
  const configSchema = { "~standard": {
795
810
  version: 1,
796
811
  vendor: "segmentstream",
797
- validate: (input) => validateConfig(input),
812
+ validate: (input) => validateConfig(input, { mount: true }),
798
813
  types: void 0
799
814
  } };
800
815
  function manifestOf(config) {
@@ -22,6 +22,7 @@ export declare const segmentstream: import("eve/extension").ExtensionHandle<{
22
22
  export default segmentstream;
23
23
  export { DEFAULT_DECISION_MODEL, DEFAULT_STT_MODEL, DEFAULT_ADMISSION_LIMITS, SegmentStreamAgentConfigError, manifestOf, type ChatModelChoice, type AdmissionLimits, type AdmissionLimitsInput, type AdmissionSettings, type AdmissionReplies, type FirstContactSettings, type LocalizedText, type SegmentStreamAgentConfig, type SegmentStreamAgentConfigInput, type SessionScope, type SessionSettings, type TelegramPolicy, type TelegramSettings, } from "./config.js";
24
24
  export { chooseModel, model, type DynamicModel, type ModelChoice } from "./model.js";
25
+ export { forRoles } from "./lib/role-skill.js";
25
26
  export { groupPolicy, effectiveGroupPolicy, DEFAULT_GROUP_POLICY, type GroupPolicy, type GroupPolicyInput, type SmartPolicyInput, type ChatOverrideInput, } from "./lib/group-routing/policy.js";
26
27
  export { addressingReason as groupAddressingReason, conversationKey, type GroupMessageSignals, type AgentMessageSignals, type GroupChannelAdapter, } from "./lib/group-routing/signals.js";
27
28
  export { routeMessage as routeGroupMessage, decisionRouter as groupDecisionRouter, } from "./lib/group-routing/router.js";
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { DEFAULT_ADMISSION_LIMITS, DEFAULT_DECISION_MODEL, DEFAULT_STT_MODEL, SegmentStreamAgentConfigError, configSchema, manifestOf } from "./config.mjs";
8
8
  import { chooseModel, model } from "./model.mjs";
9
+ import { forRoles } from "./lib/role-skill.mjs";
9
10
  import { DEFAULT_GROUP_POLICY, effectiveGroupPolicy, groupPolicy } from "./lib/group-routing/policy.mjs";
10
11
  import { addressingReason, conversationKey } from "./lib/group-routing/signals.mjs";
11
12
  import { decisionRouter, routeMessage } from "./lib/group-routing/router.mjs";
@@ -20,4 +21,4 @@ const segmentstream = Object.assign(extension, {
20
21
  model,
21
22
  manifestOf
22
23
  });
23
- export { DEFAULT_ADMISSION_LIMITS, DEFAULT_DECISION_MODEL, DEFAULT_GROUP_POLICY, DEFAULT_STT_MODEL, SegmentStreamAgentConfigError, archivedRoutingMessages, chooseModel, conversationKey, segmentstream as default, segmentstream, effectiveGroupPolicy, addressingReason as groupAddressingReason, agentMessage as groupAgentMessage, conversationAddressing as groupConversationAddressing, decisionRouter as groupDecisionRouter, groupPolicy, manifestOf, model, replayRouterPayload, routeMessage as routeGroupMessage, routingBurst };
24
+ export { DEFAULT_ADMISSION_LIMITS, DEFAULT_DECISION_MODEL, DEFAULT_GROUP_POLICY, DEFAULT_STT_MODEL, SegmentStreamAgentConfigError, archivedRoutingMessages, chooseModel, conversationKey, segmentstream as default, segmentstream, effectiveGroupPolicy, forRoles, addressingReason as groupAddressingReason, agentMessage as groupAgentMessage, conversationAddressing as groupConversationAddressing, decisionRouter as groupDecisionRouter, groupPolicy, manifestOf, model, replayRouterPayload, routeMessage as routeGroupMessage, routingBurst };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The persona of the session: a system instruction after the workspace's own, chosen from the
3
+ * roles of the person who started the session (the workflow's user for a workflow task), so it
4
+ * stays the same for the whole session and keeps the prompt prefix cached. Nothing without
5
+ * `personas` in `agent/segmentstream.json`, or when no role matches and there is no `default`.
6
+ */
7
+ declare const _default: import("eve").DynamicSentinel<import("eve/instructions").DynamicInstructionsResult, import("eve").DynamicContext>;
8
+ export default _default;
@@ -0,0 +1,21 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import segmentstream from "../extension.mjs";
8
+ import { a as rolesOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
9
+ import { personaFile, personaFor } from "../personas.mjs";
10
+ import { defineDynamic, defineInstructions } from "eve/instructions";
11
+ var persona_default = defineDynamic((context) => {
12
+ const { personas, files } = segmentstream.config;
13
+ if (personas === void 0) return null;
14
+ const persona = personaFor(personas, rolesOf(context.session.auth.initiator ?? context.session.auth.current));
15
+ const content = persona === void 0 ? void 0 : files?.[personaFile(persona)];
16
+ return content === void 0 ? null : defineInstructions({
17
+ role: "system",
18
+ content
19
+ });
20
+ });
21
+ export { persona_default as default };
@@ -1,7 +1,10 @@
1
1
  # SegmentStream platform
2
2
 
3
- You are the workspace's agent on SegmentStream. Every conversation runs as the member who is
4
- talking to you, and you act with exactly their permissions.
3
+ You are the workspace's agent on SegmentStream. Every conversation runs as the person who is
4
+ talking to you, called the member below whether they were invited or signed up themselves, and
5
+ you act with exactly their permissions. When the workspace declares personas, a persona
6
+ instruction says who you are to this person; it refines the workspace's instructions, and neither
7
+ overrides these platform rules.
5
8
 
6
9
  The company's records live in the ontology MCP connection `segmentstream__ontology`.
7
10
  Use Eve's `eve__search` to find its operation tools and `eve__tool` to inspect/call them.
@@ -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-CvNkh4kp.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CwWzry8P.mjs";
@@ -0,0 +1,21 @@
1
+ import { type SkillDefinition } from "eve/skills";
2
+ /**
3
+ * A skill only the listed roles get, as the default export of a module in `agent/agent/skills/`:
4
+ *
5
+ * ```ts
6
+ * // agent/agent/skills/accounting.ts
7
+ * import { forRoles } from "@segmentstream/agent";
8
+ *
9
+ * export default forRoles(["accountant", "founder"], {
10
+ * description: "Post journals and reconcile accounts. Use when …",
11
+ * content: `…`,
12
+ * });
13
+ * ```
14
+ *
15
+ * eve gives a static skill to every session, so this one is an eve dynamic skill: a session
16
+ * started by a person holding any of the roles lists and loads it under the module's name; any
17
+ * other session neither sees its name nor can load it. The roles are those of the person who
18
+ * started the session (the workflow's user for a workflow task), so a session keeps its skills.
19
+ * Write the roles as a list of strings: the platform reads that list to show who gets the skill.
20
+ */
21
+ export declare function forRoles(roles: ReadonlyArray<string>, skill: SkillDefinition): import("eve").DynamicSentinel<import("eve/skills").DynamicSkillResult, import("eve").DynamicContext>;
@@ -0,0 +1,14 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { a as rolesOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
8
+ import { defineDynamic, defineSkill } from "eve/skills";
9
+ function forRoles(roles, skill) {
10
+ if (!Array.isArray(roles) || roles.length === 0 || !roles.every((role) => typeof role === "string" && role.trim() !== "")) throw new TypeError("forRoles() needs at least one role name; a skill for everyone is an ordinary skill file.");
11
+ const definition = defineSkill(skill);
12
+ return defineDynamic((context) => rolesOf(context.session.auth.initiator ?? context.session.auth.current).some((role) => roles.includes(role)) ? definition : null);
13
+ }
14
+ export { forRoles };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What the platform reads from the skill files of `agent/agent/skills/` to show them, without
3
+ * running them: a Markdown skill's description, and the roles a `forRoles([...])` module lists.
4
+ * eve remains what decides; these readers only describe.
5
+ */
6
+ /**
7
+ * A Markdown skill's description as eve reads it: the frontmatter's `description`, or else the
8
+ * first line of the body that is not a code fence, without its leading Markdown marker.
9
+ * `undefined` when there is neither.
10
+ */
11
+ export declare function skillDescription(text: string): string | undefined;
12
+ /**
13
+ * How a skill module limits who gets it: the roles of a `forRoles([...])` call written as a list
14
+ * of strings; `"code"` when it decides in some other way, such as roles computed in code or its
15
+ * own `defineDynamic`; `undefined` for a static skill everyone gets.
16
+ */
17
+ export declare function skillModuleRoles(source: string): ReadonlyArray<string> | "code" | undefined;
18
+ /** The `description` a skill module writes as one string literal, when it does. */
19
+ export declare function skillModuleDescription(source: string): string | undefined;
@@ -0,0 +1,39 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ function skillDescription(text) {
8
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
9
+ const described = match === null ? void 0 : frontmatterDescription(match[1] ?? "");
10
+ if (described !== void 0) return described;
11
+ return (match === null ? text : text.slice(match[0].length)).split(/\r?\n/u).map((candidate) => candidate.trim()).find((candidate) => candidate !== "" && !candidate.startsWith("```"))?.replace(/^[#>*-]+\s*/u, "").trim() || void 0;
12
+ }
13
+ function frontmatterDescription(frontmatter) {
14
+ const lines = frontmatter.split(/\r?\n/u);
15
+ const index = lines.findIndex((line) => /^description:/u.test(line));
16
+ if (index === -1) return;
17
+ const value = lines[index].slice(12).trim();
18
+ if (/^[>|][+-]?$/u.test(value)) {
19
+ const block = [];
20
+ for (const line of lines.slice(index + 1)) {
21
+ if (line.trim() !== "" && !/^\s/u.test(line)) break;
22
+ block.push(line.trim());
23
+ }
24
+ return block.join(value.startsWith(">") ? " " : "\n").trim() || void 0;
25
+ }
26
+ return (/^(["'])(.*)\1$/u.exec(value)?.[2] ?? value).trim() || void 0;
27
+ }
28
+ function skillModuleRoles(source) {
29
+ const call = /\bforRoles\s*\(\s*\[([^\]]*)\]/u.exec(source);
30
+ if (call !== null) {
31
+ const roles = (call[1] ?? "").split(",").map((item) => item.trim()).filter((item) => item !== "").map((item) => /^(["'`])([^"'`]+)\1$/u.exec(item)?.[2]);
32
+ return roles.length > 0 && roles.every((role) => role !== void 0) ? roles : "code";
33
+ }
34
+ return /\bforRoles\s*\(|\bdefineDynamic\s*\(/u.test(source) ? "code" : void 0;
35
+ }
36
+ function skillModuleDescription(source) {
37
+ return (/\bdescription\s*:\s*(["'`])((?:(?!\1)[^\\]|\\.)*)\1/u.exec(source)?.[2])?.replace(/\\(.)/gu, "$1").trim() || void 0;
38
+ }
39
+ export { skillDescription, skillModuleDescription, skillModuleRoles };
@@ -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-CvNkh4kp.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CwWzry8P.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-CvNkh4kp.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CwWzry8P.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-BIX7T6Hh.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-CvNkh4kp.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CwWzry8P.mjs";
9
9
  import { n as currentInboundRequest } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
10
10
  import { object } from "../confirmation-description.mjs";
11
11
  import { needsConfirmation } from "../confirmations.mjs";
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Personas: what the agent is to the person in a conversation. `agent/segmentstream.json` says
3
+ * which roles get which persona; each text is `agent/personas/<name>.md` beside it, which the
4
+ * mount (`agent/agent/extensions/segmentstream.ts`) imports and passes as `files`, since eve reads
5
+ * no directory at runtime. Selection reads only the roles of the person who started the session,
6
+ * so a session keeps one persona.
7
+ */
8
+ /** The directory beside `segmentstream.json` that holds the persona texts. */
9
+ export declare const PERSONAS_DIRECTORY = "personas";
10
+ export interface PersonaSettings {
11
+ /** A persona per role; the first role the person holds wins, in the order written. */
12
+ readonly byRole: Readonly<Record<string, string>>;
13
+ /** The persona of anyone no role matches, including a person who holds no roles. */
14
+ readonly default?: string;
15
+ }
16
+ /** One validation failure, in Standard Schema's issue shape. */
17
+ interface Issue {
18
+ readonly message: string;
19
+ readonly path: ReadonlyArray<string>;
20
+ }
21
+ /** The path of a persona's text, relative to the directory of `segmentstream.json`. */
22
+ export declare function personaFile(name: string): string;
23
+ /** The personas the settings name, in selection order: `byRole`'s, then the default. */
24
+ export declare function personaNames(settings: PersonaSettings | null): ReadonlyArray<string>;
25
+ /** The persona for a person with `roles`: the first `byRole` entry they hold, or the default. */
26
+ export declare function personaFor(settings: PersonaSettings | null, roles: ReadonlyArray<string>): string | undefined;
27
+ /** Validates `personas` of `agent/segmentstream.json`; `null` when absent. */
28
+ export declare function personaSettings(value: unknown, issues: Issue[]): PersonaSettings | null;
29
+ /**
30
+ * Validates the mount's `files`: every persona the settings name has its text, and nothing else
31
+ * is passed. JSON never carries `files`; only the mount adds them.
32
+ */
33
+ export declare function bundledFiles(input: {
34
+ readonly value: unknown;
35
+ readonly personas: PersonaSettings | null;
36
+ readonly issues: Issue[];
37
+ }): Readonly<Record<string, string>>;
38
+ export {};
@@ -0,0 +1,114 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ const PERSONAS_DIRECTORY = "personas";
8
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
9
+ const MAXIMUM_NAME_LENGTH = 64;
10
+ const NAME_RULE = "must be lowercase letters, digits and single hyphens, at most 64 characters";
11
+ function personaFile(name) {
12
+ return `${PERSONAS_DIRECTORY}/${name}.md`;
13
+ }
14
+ function personaNames(settings) {
15
+ if (settings === null) return [];
16
+ return [...new Set([...Object.values(settings.byRole), ...settings.default === void 0 ? [] : [settings.default]])];
17
+ }
18
+ function personaFor(settings, roles) {
19
+ if (settings === null) return;
20
+ for (const [role, persona] of Object.entries(settings.byRole)) if (roles.includes(role)) return persona;
21
+ return settings.default;
22
+ }
23
+ function isRecord(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function validName(value) {
27
+ return typeof value === "string" && value.length <= MAXIMUM_NAME_LENGTH && NAME.test(value);
28
+ }
29
+ function role(value) {
30
+ return typeof value === "string" && value.trim() !== "" && value.trim() === value;
31
+ }
32
+ function personaSettings(value, issues) {
33
+ const path = ["personas"];
34
+ if (value === void 0) return null;
35
+ if (!isRecord(value)) {
36
+ issues.push({
37
+ message: "must be an object",
38
+ path
39
+ });
40
+ return null;
41
+ }
42
+ for (const key of Object.keys(value)) if (key !== "byRole" && key !== "default") issues.push({
43
+ message: "is not a known setting",
44
+ path: [...path, key]
45
+ });
46
+ const byRole = {};
47
+ if (value.byRole !== void 0) {
48
+ if (!isRecord(value.byRole)) issues.push({
49
+ message: "must be an object of role to persona",
50
+ path: [...path, "byRole"]
51
+ });
52
+ else for (const [name, persona] of Object.entries(value.byRole)) if (!role(name)) issues.push({
53
+ message: "must be a role name",
54
+ path: [
55
+ ...path,
56
+ "byRole",
57
+ name
58
+ ]
59
+ });
60
+ else if (!validName(persona)) issues.push({
61
+ message: `names a persona that ${NAME_RULE}`,
62
+ path: [
63
+ ...path,
64
+ "byRole",
65
+ name
66
+ ]
67
+ });
68
+ else byRole[name] = persona;
69
+ }
70
+ if (value.default !== void 0 && !validName(value.default)) issues.push({
71
+ message: `names a persona that ${NAME_RULE}`,
72
+ path: [...path, "default"]
73
+ });
74
+ if (value.default === void 0 && Object.keys(byRole).length === 0) issues.push({
75
+ message: "needs byRole, default or both",
76
+ path
77
+ });
78
+ return {
79
+ byRole,
80
+ ...typeof value.default === "string" && validName(value.default) ? { default: value.default } : {}
81
+ };
82
+ }
83
+ function bundledFiles(input) {
84
+ const { issues } = input;
85
+ const path = ["files"];
86
+ const files = {};
87
+ if (input.value !== void 0 && !isRecord(input.value)) {
88
+ issues.push({
89
+ message: "must be an object of path to text",
90
+ path
91
+ });
92
+ return files;
93
+ }
94
+ for (const [file, content] of Object.entries(input.value ?? {})) if (typeof content !== "string") issues.push({
95
+ message: "must be the file's text, imported with ?raw",
96
+ path: [...path, file]
97
+ });
98
+ else files[file] = content;
99
+ const expected = new Set(personaNames(input.personas).map(personaFile));
100
+ for (const file of expected) if (files[file] === void 0) issues.push({
101
+ message: `is missing: import agent/${file} with ?raw in agent/agent/extensions/segmentstream.ts and pass it under files["${file}"]`,
102
+ path: [...path, file]
103
+ });
104
+ else if (files[file].trim() === "") issues.push({
105
+ message: "is empty",
106
+ path: [...path, file]
107
+ });
108
+ for (const file of Object.keys(files)) if (!expected.has(file)) issues.push({
109
+ message: "is not a persona that segmentstream.json names",
110
+ path: [...path, file]
111
+ });
112
+ return files;
113
+ }
114
+ export { PERSONAS_DIRECTORY, bundledFiles, personaFile, personaFor, personaNames, personaSettings };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.38.3",
3
+ "version": "0.39.0",
4
4
  "description": "Mount a SegmentStream workspace's agent on eve: the ontology as tools, acting as the member who writes, and Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -31,6 +31,9 @@
31
31
  "types": "./dist/extension/extension.d.ts",
32
32
  "default": "./dist/extension/extension.mjs"
33
33
  },
34
+ "./raw": {
35
+ "types": "./raw.d.ts"
36
+ },
34
37
  "./sandbox": {
35
38
  "types": "./dist/extension/lib/sandbox.d.ts",
36
39
  "default": "./dist/extension/lib/sandbox.mjs"
@@ -56,6 +59,7 @@
56
59
  },
57
60
  "files": [
58
61
  "dist",
62
+ "raw.d.ts",
59
63
  "README.md",
60
64
  "LICENSE",
61
65
  "NOTICE"
package/raw.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Text imports for the persona files the mount passes as `files`: eve embeds a
3
+ * file imported with `?raw` as its UTF-8 text. Reference it from the mount with
4
+ * `/// <reference types="@segmentstream/agent/raw" />`.
5
+ */
6
+ declare module "*.md?raw" {
7
+ const text: string;
8
+ export default text;
9
+ }