samva 0.46.1 → 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/AGENTS.md +13 -7
- package/README.md +106 -8
- package/dist/agent/index.d.ts +57 -0
- package/dist/agent/index.js +53 -0
- package/dist/agent/runtime.d.ts +3 -0
- package/dist/agent/runtime.js +95 -0
- package/dist/agent/test.d.ts +31 -0
- package/dist/agent/test.js +66 -0
- package/dist/agent/types.d.ts +150 -0
- package/dist/client/sdk.gen.d.ts +50 -165
- package/dist/client/sdk.gen.js +1339 -1614
- package/dist/client/types.gen.d.ts +461 -989
- package/dist/effect/agents.d.ts +340 -8
- package/dist/effect/agents.js +4 -2
- package/dist/effect/api-keys.d.ts +2 -0
- package/dist/effect/campaigns.d.ts +160 -160
- package/dist/effect/contacts.d.ts +8 -0
- package/dist/effect/contacts.js +5 -1
- package/dist/effect/descriptors/agents.d.ts +12 -2
- package/dist/effect/descriptors/agents.js +12 -2
- package/dist/effect/descriptors/contacts.d.ts +20 -0
- package/dist/effect/descriptors/contacts.js +20 -0
- package/dist/effect/generated/accounts.d.ts +10 -0
- package/dist/effect/generated/accounts.js +1 -0
- package/dist/effect/generated/agents.d.ts +2967 -690
- package/dist/effect/generated/agents.js +54 -13
- package/dist/effect/generated/api-keys.d.ts +15 -0
- package/dist/effect/generated/api-keys.js +2 -0
- package/dist/effect/generated/contacts.d.ts +859 -1
- package/dist/effect/generated/contacts.js +62 -3
- package/dist/effect/generated/index.d.ts +1 -5
- package/dist/effect/generated/journeys.d.ts +351 -111
- package/dist/effect/generated/journeys.js +3 -1
- package/dist/effect/generated/mailboxes.d.ts +93 -95
- package/dist/effect/generated/mailboxes.js +21 -25
- package/dist/effect/generated/shared.d.ts +459 -139
- package/dist/effect/generated/shared.js +84 -39
- package/dist/effect/generated/template-registrations.d.ts +19 -4
- package/dist/effect/generated/template-registrations.js +8 -7
- package/dist/effect/generated/templates.d.ts +76 -11
- package/dist/effect/generated/templates.js +25 -12
- package/dist/effect/generated-metadata.d.ts +18 -84
- package/dist/effect/generated-metadata.js +362 -415
- package/dist/effect/index.d.ts +0 -2
- package/dist/effect/index.js +1 -3
- package/dist/effect/internal/client.js +1 -1
- package/dist/effect/internal/operation.js +4 -1
- package/dist/effect/journeys.d.ts +26 -2
- package/dist/effect/mailboxes.d.ts +41 -41
- package/dist/effect/scheduled-messages.d.ts +350 -350
- package/dist/effect/templates.d.ts +9 -0
- package/dist/effect/topics.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/promises/client.d.ts +1 -5
- package/dist/promises/client.js +3 -7
- package/dist/promises/types.gen.d.ts +1 -1
- package/dist/service-map.d.ts +18 -75
- package/package.json +10 -22
- package/dist/effect/descriptors/extension-installations.d.ts +0 -90
- package/dist/effect/descriptors/extension-installations.js +0 -90
- package/dist/effect/descriptors/extensions.d.ts +0 -50
- package/dist/effect/descriptors/extensions.js +0 -50
- package/dist/effect/extension-installations.d.ts +0 -132
- package/dist/effect/extension-installations.js +0 -29
- package/dist/effect/extensions.d.ts +0 -102
- package/dist/effect/extensions.js +0 -21
- package/dist/effect/generated/extension-installations.d.ts +0 -2761
- package/dist/effect/generated/extension-installations.js +0 -405
- package/dist/effect/generated/extensions.d.ts +0 -1037
- package/dist/effect/generated/extensions.js +0 -214
- package/dist/mailbox/dispatch.d.ts +0 -10
- package/dist/mailbox/dispatch.js +0 -66
- package/dist/mailbox/index.d.ts +0 -17
- package/dist/mailbox/index.js +0 -30
- package/dist/mailbox/test.d.ts +0 -25
- package/dist/mailbox/test.js +0 -181
- package/dist/mailbox/types.d.ts +0 -221
- package/dist/mailbox/webhook.d.ts +0 -10
- package/dist/mailbox/webhook.js +0 -41
package/AGENTS.md
CHANGED
|
@@ -37,8 +37,7 @@ organization, mailbox, or API key's decision rules. Policy writes require a pers
|
|
|
37
37
|
unset. Replacement requires the observed `ifVersion`; `deletePolicy({ kind, id, ifVersion })`
|
|
38
38
|
clears the configuration. Both return the next snapshot, and clear keeps the counter. On
|
|
39
39
|
`ConflictError` (`409`), reload and review before editing again; never automatically retry stale
|
|
40
|
-
full configuration with a newer version. Agent definitions
|
|
41
|
-
their own `policy`.
|
|
40
|
+
full configuration with a newer version. Agent definitions carry their own `policy`.
|
|
42
41
|
Read an action with `mailboxes.getAction` or read its decision in `mailboxes.getNeedsYou` before
|
|
43
42
|
reviewing it. Both `approveAction` and `denyAction` require the observed decision's positive
|
|
44
43
|
`reviewRound`. A stale round returns `409`; refresh the action and review its new decision before
|
|
@@ -68,11 +67,6 @@ client and call level. `contacts.startImport` retries only `mode: "new"`; a resu
|
|
|
68
67
|
a generation fence and must be followed by `getImportJob` after an ambiguous response. Promise cursor lists expose lazy `.pages(params)` and `.items(params)`
|
|
69
68
|
async iterators. `orgSlug` selects an organization when paired with `authToken`.
|
|
70
69
|
|
|
71
|
-
Mailbox extensions import `samva/mailbox`, `samva/mailbox/test`, or `samva/mailbox/webhook`.
|
|
72
|
-
Handlers receive the normal client and use flat calls such as
|
|
73
|
-
`ctx.samva.mailboxes.reply({ id, messageId, text })`. Keep sends in stable order so dispatch
|
|
74
|
-
reuses deterministic event keys.
|
|
75
|
-
|
|
76
70
|
Use `client.newsletters` for newsletter management and `client.newsletters.domains` for custom archive domains. Effect entrypoints are `samva/effect/newsletters`, `samva/effect/newsletter-issues`, and `samva/effect/newsletter-domains`. A newsletter’s `topicId` names its consent and campaign audience.
|
|
77
71
|
|
|
78
72
|
`client.newsletters.domains.list({ id, cursor, limit })` returns a hostname-ordered page with
|
|
@@ -88,3 +82,15 @@ for a `projectId`. Create accepts an optional `slug`; update exports the project
|
|
|
88
82
|
at the same link. Rename changes the slug and breaks the old link. Delete removes the link;
|
|
89
83
|
existing guest copies remain independent. Get returns the link, canonicalPath, view/open counts and update time,
|
|
90
84
|
or `null` when the project has no share link.
|
|
85
|
+
|
|
86
|
+
Hosted agent modules import `defineAgent`, `defineTool`, and `AgentContext` from `samva/agent`;
|
|
87
|
+
offline evals import `defineEval`, `runAgent`, and `runEval` from `samva/agent/test`. These
|
|
88
|
+
entrypoints use the optional `effect` peer for tool input schemas. Register tools, Markdown skills,
|
|
89
|
+
events, and schedules explicitly in the entry module. `defineAgent` derives their manifest
|
|
90
|
+
descriptors; do not maintain a second tool list. `defineTool` decodes unknown input before calling
|
|
91
|
+
`execute`. Every tool declares `replay: "safe" | "unsafe"`; optional tool approval combines with
|
|
92
|
+
policy floors, and stricter requirements win. Keep each call's authority in its supplied `ctx`,
|
|
93
|
+
never in globals shared by a warm module. Event calls expose `eventId`, `eventType`, and
|
|
94
|
+
`attempt` in `ctx.capability.trigger`. SDK idempotent writes derive stable keys from the agent,
|
|
95
|
+
event, operation, and call ordinal; preserve write order across retries, or supply an explicit
|
|
96
|
+
`idempotencyKey`. Eval assertions reject `runEval` on failure.
|
package/README.md
CHANGED
|
@@ -4,6 +4,103 @@ Samva is email and WhatsApp for AI agents, and the API developers build on. An a
|
|
|
4
4
|
|
|
5
5
|
TypeScript SDK for Samva's public customer API.
|
|
6
6
|
|
|
7
|
+
## Author a hosted agent
|
|
8
|
+
|
|
9
|
+
Import `defineAgent` and `defineTool` from `samva/agent`, and install the optional `effect` peer
|
|
10
|
+
for tool input schemas. An entry module registers its tools, event handlers, schedules, and
|
|
11
|
+
Markdown skills explicitly. `samva agents init` scaffolds a project; `samva agents build` produces
|
|
12
|
+
one self-contained ES module, and `samva agents publish` publishes an immutable version.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Schema } from "effect";
|
|
16
|
+
import { defineAgent, defineTool } from "samva/agent";
|
|
17
|
+
|
|
18
|
+
const instructions = "Help customers manage their appointments.";
|
|
19
|
+
const reschedule = "# Reschedule\nAsk for the appointment id.";
|
|
20
|
+
|
|
21
|
+
export default defineAgent({
|
|
22
|
+
manifest: {
|
|
23
|
+
name: "Front desk",
|
|
24
|
+
version: "1.0.0",
|
|
25
|
+
endpointIds: [],
|
|
26
|
+
integrations: [],
|
|
27
|
+
eventTriggers: [],
|
|
28
|
+
policy: { presets: [], rules: [] },
|
|
29
|
+
model: "standard",
|
|
30
|
+
reasoning: "auto",
|
|
31
|
+
workingHours: null,
|
|
32
|
+
takeoverTimeoutMinutes: 30,
|
|
33
|
+
},
|
|
34
|
+
instructions,
|
|
35
|
+
skills: { reschedule },
|
|
36
|
+
tools: {
|
|
37
|
+
appointment: defineTool({
|
|
38
|
+
description: "Look up an appointment",
|
|
39
|
+
input: Schema.Struct({ id: Schema.String }),
|
|
40
|
+
replay: "safe",
|
|
41
|
+
async execute(input, ctx) {
|
|
42
|
+
return await ctx.connections.call("intg_yourintegration", "get_appointment", input);
|
|
43
|
+
},
|
|
44
|
+
}),
|
|
45
|
+
},
|
|
46
|
+
events: {
|
|
47
|
+
"appointment.confirmed"(event, ctx) {
|
|
48
|
+
ctx.log(event.type);
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
schedules: {
|
|
52
|
+
"0 9 * * *"(ctx) {
|
|
53
|
+
ctx.log("Daily check");
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`defineTool` validates input before calling `execute`, and infers its input type from the Effect
|
|
60
|
+
schema. Declare `replay: "safe"` only when repeating a call is safe; otherwise use `"unsafe"`.
|
|
61
|
+
A tool's optional `approval` (`"run"`, `"model"`, `"person"`, or `"never"`) sets a floor combined
|
|
62
|
+
with Samva's decision rules: stricter requirements win. Each call receives a fresh `ctx` with its
|
|
63
|
+
capability identity, the Samva client, integration calls, memory, and logging. Keep authority in
|
|
64
|
+
that context rather than module globals. Instructions can also be a function of `ctx`; `knowledge`
|
|
65
|
+
can supply static business facts separately. Markdown skills are registered by name and loaded
|
|
66
|
+
when needed. In a project, import instructions and skills from `.md` files as text; the CLI
|
|
67
|
+
bundles those imports into the module.
|
|
68
|
+
|
|
69
|
+
For a conversation call, `ctx.capability.trigger.target` provides the admitted `mailboxId`,
|
|
70
|
+
`threadId`, and `messageId` for scoped mailbox reads and replies, or `null` when there is no
|
|
71
|
+
mailbox target. Include this field when constructing a fake conversation context for an eval.
|
|
72
|
+
|
|
73
|
+
Eval files are ordinary TypeScript modules. Import `defineEval`, `runAgent`, and `runEval` from
|
|
74
|
+
`samva/agent/test`. Supply a fake `AgentContext`; the helper runs the registered tool or handler
|
|
75
|
+
without a server and preserves input validation:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import type { AgentContext, AgentDefinition } from "samva/agent";
|
|
79
|
+
import { defineEval, runAgent, runEval } from "samva/agent/test";
|
|
80
|
+
|
|
81
|
+
declare const agent: AgentDefinition;
|
|
82
|
+
declare const ctx: AgentContext;
|
|
83
|
+
|
|
84
|
+
const evaluation = defineEval({
|
|
85
|
+
name: "appointment lookup",
|
|
86
|
+
async run(definition, context) {
|
|
87
|
+
const local = runAgent(definition, context);
|
|
88
|
+
await local.tool("appointment", { id: "appointment-1" });
|
|
89
|
+
await local.event({
|
|
90
|
+
id: "event-1",
|
|
91
|
+
type: "appointment.confirmed",
|
|
92
|
+
timestamp: "2026-01-01T00:00:00.000Z",
|
|
93
|
+
data: { appointmentId: "appointment-1" },
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
await runEval(agent, evaluation, ctx);
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Assertions thrown by an eval reject `runEval`. The runner also exposes `schedule(cron)`,
|
|
102
|
+
`instructions()`, and `skill(name)`; missing registrations fail explicitly.
|
|
103
|
+
|
|
7
104
|
## Give an agent a mailbox
|
|
8
105
|
|
|
9
106
|
Create a mailbox, send from it, and read what comes back. A hosted `samva.email` address needs no DNS setup.
|
|
@@ -256,8 +353,6 @@ The Promise client exposes:
|
|
|
256
353
|
- `customFields`
|
|
257
354
|
- `email`
|
|
258
355
|
- `events`
|
|
259
|
-
- `extensionInstallations`
|
|
260
|
-
- `extensions`
|
|
261
356
|
- `feedback`
|
|
262
357
|
- `integrationCatalog`
|
|
263
358
|
- `integrations`
|
|
@@ -562,7 +657,7 @@ is the frozen public email snapshot; inspect the action type before using send-s
|
|
|
562
657
|
Preserve the original key and body after a timeout. Replaying them reads the same action's current
|
|
563
658
|
phase, and changing the body under that key is a conflict. `getAction` reads progress. A permitted
|
|
564
659
|
person can `cancelAction` before acceptance or `retryAction` when `retryEligible` is true; Retry
|
|
565
|
-
continues the original action and never extends `executeUntil`. API keys
|
|
660
|
+
continues the original action and never extends `executeUntil`. API keys cannot
|
|
566
661
|
cancel or Retry. `approveAction` returns an action with `202` while the send is pending; accepted,
|
|
567
662
|
completed, and `notSent` replays return `200`. Non-send approvals execute synchronously and return
|
|
568
663
|
`200`, as does `denyAction`.
|
|
@@ -675,9 +770,12 @@ const input = {
|
|
|
675
770
|
const response = await samva.email.send(input);
|
|
676
771
|
```
|
|
677
772
|
|
|
678
|
-
##
|
|
773
|
+
## Agent event handlers
|
|
679
774
|
|
|
680
|
-
Import `
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
775
|
+
Import `defineAgent` from `samva/agent` and register handlers in `events`. Samva invokes each
|
|
776
|
+
matching handler with the event envelope and a fresh `ctx`; use `ctx.samva` for API calls.
|
|
777
|
+
Mailbox and contact events use the same module. Offline evals use `runAgent` from
|
|
778
|
+
`samva/agent/test`, with an explicitly supplied context. The event trigger includes its id,
|
|
779
|
+
type, and attempt number. Event SDK calls receive deterministic idempotency keys per agent,
|
|
780
|
+
event, operation, and call ordinal; keep writes in stable order across retries. An explicit
|
|
781
|
+
`idempotencyKey` overrides the generated key.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import type { AgentModuleTool } from "../client/types.gen.js";
|
|
3
|
+
import type { AgentContext, AgentDefinition, AgentEventHandler, AgentInstructions, AgentManifest, AgentScheduleHandler, AgentTool } from "./types.js";
|
|
4
|
+
export * from "./types.js";
|
|
5
|
+
/** Input is decoded before execute runs, in the host and in offline evals alike. */
|
|
6
|
+
export declare function defineTool<const S extends Schema.ConstraintDecoder<unknown>, Output>(definition: {
|
|
7
|
+
readonly description: string;
|
|
8
|
+
readonly input: S;
|
|
9
|
+
readonly approval?: AgentModuleTool["approval"];
|
|
10
|
+
readonly replay: AgentModuleTool["replay"];
|
|
11
|
+
readonly execute: (input: S["Type"], ctx: AgentContext) => Output;
|
|
12
|
+
}): {
|
|
13
|
+
input: S;
|
|
14
|
+
descriptor: {
|
|
15
|
+
readonly description: string;
|
|
16
|
+
readonly input: {
|
|
17
|
+
readonly [x: string]: string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | /*elided*/ any | {
|
|
18
|
+
readonly [x: string]: string | number | boolean | /*elided*/ any | /*elided*/ any | null;
|
|
19
|
+
} | null)[] | {
|
|
20
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
21
|
+
} | null)[] | {
|
|
22
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
23
|
+
} | null)[] | {
|
|
24
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
25
|
+
} | null)[] | {
|
|
26
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
27
|
+
} | null)[] | {
|
|
28
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
29
|
+
} | null)[] | {
|
|
30
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
31
|
+
} | null)[] | {
|
|
32
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
33
|
+
} | null)[] | {
|
|
34
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
35
|
+
} | null)[] | {
|
|
36
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
37
|
+
} | null)[] | {
|
|
38
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
39
|
+
} | null)[] | {
|
|
40
|
+
readonly [x: string]: string | number | boolean | any | any | null;
|
|
41
|
+
} | null;
|
|
42
|
+
};
|
|
43
|
+
readonly approval?: import("../index.js").PolicyRequirement | undefined;
|
|
44
|
+
readonly replay: "safe" | "unsafe";
|
|
45
|
+
};
|
|
46
|
+
execute(input: unknown, ctx: AgentContext): Promise<Awaited<Output>>;
|
|
47
|
+
};
|
|
48
|
+
export declare function defineAgent<const Tools extends Readonly<Record<string, AgentTool>> = Record<never, never>>(definition: {
|
|
49
|
+
readonly manifest: AgentManifest;
|
|
50
|
+
readonly instructions: AgentInstructions;
|
|
51
|
+
readonly knowledge?: string;
|
|
52
|
+
readonly skills?: Readonly<Record<string, string>>;
|
|
53
|
+
readonly tools?: Tools;
|
|
54
|
+
readonly events?: Readonly<Record<string, AgentEventHandler>>;
|
|
55
|
+
readonly schedules?: Readonly<Record<string, AgentScheduleHandler>>;
|
|
56
|
+
readonly workflows?: ReadonlyArray<string>;
|
|
57
|
+
}): AgentDefinition<Tools>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { invokeAgent } from "./runtime.js";
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
// src/agent/index.ts
|
|
4
|
+
/** Input is decoded before execute runs, in the host and in offline evals alike. */
|
|
5
|
+
function defineTool(definition) {
|
|
6
|
+
const document = Schema.toJsonSchemaDocument(definition.input);
|
|
7
|
+
const jsonObject = Schema.Record(Schema.String, Schema.Json);
|
|
8
|
+
const inputSchema = Schema.decodeUnknownSync(jsonObject)(document.schema);
|
|
9
|
+
const descriptor = {
|
|
10
|
+
description: definition.description,
|
|
11
|
+
input: {
|
|
12
|
+
...inputSchema,
|
|
13
|
+
...Object.keys(document.definitions).length > 0 ? { $defs: Schema.decodeUnknownSync(jsonObject)(document.definitions) } : {}
|
|
14
|
+
},
|
|
15
|
+
...definition.approval === void 0 ? {} : { approval: definition.approval },
|
|
16
|
+
replay: definition.replay
|
|
17
|
+
};
|
|
18
|
+
return {
|
|
19
|
+
input: definition.input,
|
|
20
|
+
descriptor,
|
|
21
|
+
async execute(input, ctx) {
|
|
22
|
+
const decoded = await Schema.decodeUnknownPromise(definition.input)(input);
|
|
23
|
+
return await definition.execute(decoded, ctx);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function defineAgent(definition) {
|
|
28
|
+
const skills = definition.skills ?? {};
|
|
29
|
+
const tools = definition.tools ?? {};
|
|
30
|
+
const events = definition.events ?? {};
|
|
31
|
+
const schedules = definition.schedules ?? {};
|
|
32
|
+
const agent = {
|
|
33
|
+
__samvaAgentRuntime: (operation, capability, authority) => invokeAgent(agent, operation, capability, authority),
|
|
34
|
+
manifest: {
|
|
35
|
+
...definition.manifest,
|
|
36
|
+
tools: Object.fromEntries(Object.entries(tools).map(([name, tool]) => [name, tool.descriptor])),
|
|
37
|
+
skills: Object.keys(skills).sort(),
|
|
38
|
+
events: Object.keys(events).sort(),
|
|
39
|
+
schedules: Object.keys(schedules).sort()
|
|
40
|
+
},
|
|
41
|
+
instructions: definition.instructions,
|
|
42
|
+
knowledge: definition.knowledge ?? "",
|
|
43
|
+
skills,
|
|
44
|
+
tools,
|
|
45
|
+
events,
|
|
46
|
+
schedules,
|
|
47
|
+
workflows: definition.workflows ?? []
|
|
48
|
+
};
|
|
49
|
+
return agent;
|
|
50
|
+
}
|
|
51
|
+
export { defineAgent, defineTool };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { AgentCallCapability, AgentDefinition, AgentModuleAuthority, AgentModuleOperation } from "./types.js";
|
|
2
|
+
/** The SDK transport carries no credential: only the supplied call-local RPC stub can reach Samva. */
|
|
3
|
+
export declare function invokeAgent(agent: AgentDefinition, operation: AgentModuleOperation, capability: AgentCallCapability, authority: AgentModuleAuthority): Promise<unknown>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { clientWithIdempotency, createBoundClient } from "../promises/client.js";
|
|
2
|
+
// src/agent/runtime.ts
|
|
3
|
+
/** The SDK transport carries no credential: only the supplied call-local RPC stub can reach Samva. */
|
|
4
|
+
async function invokeAgent(agent, operation, capability, authority) {
|
|
5
|
+
const pendingLogs = [];
|
|
6
|
+
const client = createBoundClient({
|
|
7
|
+
baseUrl: "https://api.samva.dev",
|
|
8
|
+
maxRetries: 0,
|
|
9
|
+
fetch: async (input, init) => {
|
|
10
|
+
const request = new Request(input, init);
|
|
11
|
+
const url = new URL(request.url);
|
|
12
|
+
if (url.origin !== "https://api.samva.dev") throw new Error("Agent Samva calls must target the Samva API");
|
|
13
|
+
const headers = new Headers(request.headers);
|
|
14
|
+
headers.delete("authorization");
|
|
15
|
+
headers.delete("x-api-key");
|
|
16
|
+
headers.delete("cookie");
|
|
17
|
+
const result = await authority.samva({
|
|
18
|
+
method: request.method,
|
|
19
|
+
path: `${url.pathname}${url.search}`,
|
|
20
|
+
headers: Object.fromEntries(headers),
|
|
21
|
+
body: request.body === null ? null : await request.text()
|
|
22
|
+
});
|
|
23
|
+
return new Response(result.status === 204 || result.status === 205 ? null : result.body, {
|
|
24
|
+
status: result.status,
|
|
25
|
+
headers: result.headers
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
const counts = /* @__PURE__ */ new Map();
|
|
30
|
+
const samva = operation.kind === "event" ? clientWithIdempotency(client, (method) => {
|
|
31
|
+
const count = (counts.get(method) ?? 0) + 1;
|
|
32
|
+
counts.set(method, count);
|
|
33
|
+
return `${capability.agentId}:${operation.event.id}:${method}:${count}`;
|
|
34
|
+
}) : client;
|
|
35
|
+
const state = (call) => authority.state ? authority.state(call) : Promise.reject(/* @__PURE__ */ new Error("Agent module state is unavailable"));
|
|
36
|
+
const ctx = {
|
|
37
|
+
capability,
|
|
38
|
+
samva,
|
|
39
|
+
connections: { call: (integrationId, tool, input) => authority.connection(integrationId, tool, input) },
|
|
40
|
+
workflows: { start: (input) => authority.startWorkflow ? authority.startWorkflow(input) : Promise.reject(/* @__PURE__ */ new Error("Agent workflows are unavailable")) },
|
|
41
|
+
state: {
|
|
42
|
+
agent: { call: (name, input) => state({
|
|
43
|
+
scope: "agent",
|
|
44
|
+
operation: name,
|
|
45
|
+
input
|
|
46
|
+
}) },
|
|
47
|
+
conversation: { call: (name, input) => state({
|
|
48
|
+
scope: "conversation",
|
|
49
|
+
operation: name,
|
|
50
|
+
input
|
|
51
|
+
}) }
|
|
52
|
+
},
|
|
53
|
+
memory: {
|
|
54
|
+
search: (query) => authority.searchMemory(query),
|
|
55
|
+
remember: (content) => authority.remember(content)
|
|
56
|
+
},
|
|
57
|
+
log(...values) {
|
|
58
|
+
pendingLogs.push(authority.log(values));
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
switch (operation.kind) {
|
|
63
|
+
case "instructions": return typeof agent.instructions === "string" ? agent.instructions : await agent.instructions(ctx);
|
|
64
|
+
case "knowledge": return agent.knowledge;
|
|
65
|
+
case "list-skills": return Object.keys(agent.skills).sort();
|
|
66
|
+
case "load-skill": {
|
|
67
|
+
const skill = agent.skills[operation.name];
|
|
68
|
+
if (skill === void 0) throw new Error(`Unknown agent skill: ${operation.name}`);
|
|
69
|
+
return skill;
|
|
70
|
+
}
|
|
71
|
+
case "schedule": {
|
|
72
|
+
if (capability.trigger.kind !== "schedule" || capability.trigger.cron !== operation.cron || capability.trigger.scheduledAt !== operation.scheduledAt) throw new Error("The agent schedule does not match its call capability");
|
|
73
|
+
const handler = agent.schedules[operation.cron];
|
|
74
|
+
if (handler === void 0) throw new Error("Unknown agent schedule");
|
|
75
|
+
return await handler(ctx) ?? null;
|
|
76
|
+
}
|
|
77
|
+
case "event": {
|
|
78
|
+
if (capability.trigger.kind !== "event" || capability.trigger.eventId !== operation.event.id || capability.trigger.eventType !== operation.event.type || capability.trigger.attempt !== operation.attempt) throw new Error("The agent event does not match its call capability");
|
|
79
|
+
const handler = agent.events[operation.event.type];
|
|
80
|
+
if (handler === void 0) throw new Error(`Unknown agent event handler: ${operation.event.type}`);
|
|
81
|
+
return await handler(operation.event, ctx) ?? null;
|
|
82
|
+
}
|
|
83
|
+
case "tool": {
|
|
84
|
+
const tool = agent.tools[operation.name];
|
|
85
|
+
if (tool === void 0) throw new Error(`Unknown agent tool: ${operation.name}`);
|
|
86
|
+
return await tool.execute(operation.input, ctx);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
await Promise.all(pendingLogs);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export { invokeAgent };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { AgentContext, AgentDefinition, AgentEvent, AgentTool } from "./types.js";
|
|
2
|
+
export interface AgentTestRunner<Tools extends Readonly<Record<string, AgentTool>>> {
|
|
3
|
+
tool<Name extends keyof Tools & string>(name: Name, input: Tools[Name]["input"]["Encoded"]): ReturnType<Tools[Name]["execute"]>;
|
|
4
|
+
event(event: AgentEvent): Promise<unknown>;
|
|
5
|
+
schedule(cron: string): Promise<unknown>;
|
|
6
|
+
instructions(): Promise<string>;
|
|
7
|
+
skill(name: string): string;
|
|
8
|
+
}
|
|
9
|
+
/** Run the same registered handlers and validated tools with explicitly supplied fake authority. */
|
|
10
|
+
export declare function runAgent<Tools extends Readonly<Record<string, AgentTool>>>(agent: AgentDefinition<Tools>, ctx: AgentContext): AgentTestRunner<Tools>;
|
|
11
|
+
export interface AgentEval<Agent extends AgentDefinition = AgentDefinition> {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
run(agent: Agent, ctx: AgentContext): void | Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** Eval files are ordinary modules: define assertions in run and invoke them with runEval. */
|
|
16
|
+
export declare function defineEval<Agent extends AgentDefinition>(evaluation: AgentEval<Agent>): AgentEval<Agent>;
|
|
17
|
+
/** A failed assertion rejects instead of turning an unsuccessful evaluation into a pass. */
|
|
18
|
+
export declare function runEval<Agent extends AgentDefinition>(agent: Agent, evaluation: AgentEval<Agent>, ctx: AgentContext): Promise<{
|
|
19
|
+
name: string;
|
|
20
|
+
passed: boolean;
|
|
21
|
+
}>;
|
|
22
|
+
export interface RecordedCall {
|
|
23
|
+
method: string;
|
|
24
|
+
path: string;
|
|
25
|
+
body: unknown;
|
|
26
|
+
idempotencyKey: string | null;
|
|
27
|
+
}
|
|
28
|
+
/** Canned responses are keyed by `METHOD /path`. */
|
|
29
|
+
export declare function createTestClient(responses?: Record<string, unknown>): import("../index.js").SamvaClient & {
|
|
30
|
+
calls: RecordedCall[];
|
|
31
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createBoundClient } from "../promises/client.js";
|
|
2
|
+
// src/agent/test.ts
|
|
3
|
+
function runAgent(agent, ctx) {
|
|
4
|
+
return {
|
|
5
|
+
async tool(name, input) {
|
|
6
|
+
const tool = agent.tools[name];
|
|
7
|
+
if (!tool) throw new Error(`Unknown agent tool: ${name}`);
|
|
8
|
+
return await tool.execute(input, ctx);
|
|
9
|
+
},
|
|
10
|
+
async event(event) {
|
|
11
|
+
const handler = agent.events[event.type];
|
|
12
|
+
if (!handler) throw new Error(`Unknown agent event handler: ${event.type}`);
|
|
13
|
+
return await handler(event, ctx);
|
|
14
|
+
},
|
|
15
|
+
async schedule(cron) {
|
|
16
|
+
const handler = agent.schedules[cron];
|
|
17
|
+
if (!handler) throw new Error(`Unknown agent schedule: ${cron}`);
|
|
18
|
+
return await handler(ctx);
|
|
19
|
+
},
|
|
20
|
+
async instructions() {
|
|
21
|
+
return typeof agent.instructions === "function" ? await agent.instructions(ctx) : agent.instructions;
|
|
22
|
+
},
|
|
23
|
+
skill(name) {
|
|
24
|
+
const markdown = agent.skills[name];
|
|
25
|
+
if (markdown === void 0) throw new Error(`Unknown agent skill: ${name}`);
|
|
26
|
+
return markdown;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Eval files are ordinary modules: define assertions in run and invoke them with runEval. */
|
|
31
|
+
function defineEval(evaluation) {
|
|
32
|
+
return evaluation;
|
|
33
|
+
}
|
|
34
|
+
/** A failed assertion rejects instead of turning an unsuccessful evaluation into a pass. */
|
|
35
|
+
async function runEval(agent, evaluation, ctx) {
|
|
36
|
+
await evaluation.run(agent, ctx);
|
|
37
|
+
return {
|
|
38
|
+
name: evaluation.name,
|
|
39
|
+
passed: true
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** Canned responses are keyed by `METHOD /path`. */
|
|
43
|
+
function createTestClient(responses = {}) {
|
|
44
|
+
const calls = [];
|
|
45
|
+
const client = createBoundClient({
|
|
46
|
+
baseUrl: "https://api.samva.dev",
|
|
47
|
+
async fetch(input, init) {
|
|
48
|
+
const request = new Request(input, init);
|
|
49
|
+
const url = new URL(request.url);
|
|
50
|
+
const path = url.pathname + url.search;
|
|
51
|
+
const text = await request.text();
|
|
52
|
+
calls.push({
|
|
53
|
+
method: request.method,
|
|
54
|
+
path,
|
|
55
|
+
body: text ? JSON.parse(text) : void 0,
|
|
56
|
+
idempotencyKey: request.headers.get("idempotency-key")
|
|
57
|
+
});
|
|
58
|
+
const response = responses[`${request.method} ${path}`];
|
|
59
|
+
return Response.json(response ?? {});
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
return Object.assign(client, { calls });
|
|
63
|
+
}
|
|
64
|
+
export { createTestClient, defineEval, runAgent, runEval };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=test.js.map
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { Schema } from "effect";
|
|
2
|
+
import type { AgentModuleManifest, AgentModuleTool } from "../client/types.gen.js";
|
|
3
|
+
import type { SamvaClient } from "../promises/client.js";
|
|
4
|
+
export type { AgentModuleManifest, AgentModuleTool } from "../client/types.gen.js";
|
|
5
|
+
type DeepReadonly<T> = T extends readonly (infer A)[] ? readonly DeepReadonly<A>[] : T extends object ? {
|
|
6
|
+
readonly [K in keyof T]: DeepReadonly<T[K]>;
|
|
7
|
+
} : T;
|
|
8
|
+
/** Handler and tool descriptors are derived by defineAgent from the registered code. */
|
|
9
|
+
export type AgentManifest = DeepReadonly<Omit<AgentModuleManifest, "tools" | "skills" | "events" | "schedules">>;
|
|
10
|
+
/** The host supplies a fresh capability for every invocation; it is never an environment binding. */
|
|
11
|
+
export interface AgentCallCapability {
|
|
12
|
+
readonly callId: string;
|
|
13
|
+
readonly organizationId: string;
|
|
14
|
+
readonly agentId: string;
|
|
15
|
+
readonly versionId: string;
|
|
16
|
+
readonly bundleSha256: string;
|
|
17
|
+
/** Unix milliseconds. */
|
|
18
|
+
readonly expiresAt: number;
|
|
19
|
+
readonly trigger: {
|
|
20
|
+
readonly kind: "conversation";
|
|
21
|
+
readonly conversationId: string;
|
|
22
|
+
readonly counterpart: {
|
|
23
|
+
readonly kind: "contact";
|
|
24
|
+
readonly contactId: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: "correspondent";
|
|
27
|
+
readonly correspondentId: string;
|
|
28
|
+
};
|
|
29
|
+
readonly admissionId: string;
|
|
30
|
+
/** The admitted mailbox target. The host still checks every SDK request against it. */
|
|
31
|
+
readonly target: {
|
|
32
|
+
readonly mailboxId: string;
|
|
33
|
+
readonly threadId: string;
|
|
34
|
+
readonly messageId: string;
|
|
35
|
+
} | null;
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: "event";
|
|
38
|
+
readonly eventId: string;
|
|
39
|
+
readonly eventType: string;
|
|
40
|
+
readonly attempt: number;
|
|
41
|
+
} | {
|
|
42
|
+
readonly kind: "schedule";
|
|
43
|
+
readonly cron: string;
|
|
44
|
+
readonly scheduledAt: number;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export interface AgentMemoryMatch {
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly content: string;
|
|
50
|
+
}
|
|
51
|
+
export interface AgentContext {
|
|
52
|
+
readonly capability: AgentCallCapability;
|
|
53
|
+
readonly samva: SamvaClient;
|
|
54
|
+
readonly connections: {
|
|
55
|
+
call(integrationId: string, tool: string, input: Readonly<Record<string, unknown>>): Promise<unknown>;
|
|
56
|
+
};
|
|
57
|
+
readonly workflows?: {
|
|
58
|
+
start(input: AgentWorkflowStart): Promise<string>;
|
|
59
|
+
};
|
|
60
|
+
readonly state?: {
|
|
61
|
+
readonly agent: AgentState;
|
|
62
|
+
readonly conversation: AgentState;
|
|
63
|
+
};
|
|
64
|
+
readonly memory: {
|
|
65
|
+
search(query: string): Promise<ReadonlyArray<AgentMemoryMatch>>;
|
|
66
|
+
remember(content: string): Promise<void>;
|
|
67
|
+
};
|
|
68
|
+
log(...values: ReadonlyArray<unknown>): void;
|
|
69
|
+
}
|
|
70
|
+
export interface AgentWorkflowStart {
|
|
71
|
+
readonly exportName: string;
|
|
72
|
+
readonly idempotencyKey: string;
|
|
73
|
+
readonly input: Schema.Json;
|
|
74
|
+
}
|
|
75
|
+
export interface AgentState {
|
|
76
|
+
call(operation: string, input: Schema.Json): Promise<Schema.Json>;
|
|
77
|
+
}
|
|
78
|
+
export interface AgentStateCall {
|
|
79
|
+
readonly scope: "agent" | "conversation";
|
|
80
|
+
readonly operation: string;
|
|
81
|
+
readonly input: Schema.Json;
|
|
82
|
+
}
|
|
83
|
+
export interface AgentEvent<Data = unknown> {
|
|
84
|
+
readonly id: string;
|
|
85
|
+
readonly type: string;
|
|
86
|
+
readonly timestamp: string;
|
|
87
|
+
readonly data: Data;
|
|
88
|
+
}
|
|
89
|
+
export type AgentEventHandler = (event: AgentEvent, ctx: AgentContext) => unknown | Promise<unknown>;
|
|
90
|
+
export type AgentScheduleHandler = (ctx: AgentContext) => unknown | Promise<unknown>;
|
|
91
|
+
export type AgentInstructions = string | ((ctx: AgentContext) => string | Promise<string>);
|
|
92
|
+
export interface AgentTool {
|
|
93
|
+
readonly input: Schema.ConstraintDecoder<unknown>;
|
|
94
|
+
readonly descriptor: DeepReadonly<AgentModuleTool>;
|
|
95
|
+
execute(input: unknown, ctx: AgentContext): Promise<unknown>;
|
|
96
|
+
}
|
|
97
|
+
export interface AgentDefinition<Tools extends Readonly<Record<string, AgentTool>> = Readonly<Record<string, AgentTool>>> {
|
|
98
|
+
readonly manifest: DeepReadonly<AgentModuleManifest>;
|
|
99
|
+
__samvaAgentRuntime(operation: AgentModuleOperation, capability: AgentCallCapability, authority: AgentModuleAuthority): Promise<unknown>;
|
|
100
|
+
readonly instructions: AgentInstructions;
|
|
101
|
+
readonly knowledge: string;
|
|
102
|
+
readonly skills: Readonly<Record<string, string>>;
|
|
103
|
+
readonly tools: Tools;
|
|
104
|
+
readonly events: Readonly<Record<string, AgentEventHandler>>;
|
|
105
|
+
readonly schedules: Readonly<Record<string, AgentScheduleHandler>>;
|
|
106
|
+
readonly workflows?: ReadonlyArray<string>;
|
|
107
|
+
}
|
|
108
|
+
/** The host calls one operation with one call-local authority over Workers RPC. */
|
|
109
|
+
export type AgentModuleOperation = {
|
|
110
|
+
readonly kind: "instructions";
|
|
111
|
+
} | {
|
|
112
|
+
readonly kind: "knowledge";
|
|
113
|
+
} | {
|
|
114
|
+
readonly kind: "list-skills";
|
|
115
|
+
} | {
|
|
116
|
+
readonly kind: "load-skill";
|
|
117
|
+
readonly name: string;
|
|
118
|
+
} | {
|
|
119
|
+
readonly kind: "tool";
|
|
120
|
+
readonly name: string;
|
|
121
|
+
readonly input: unknown;
|
|
122
|
+
} | {
|
|
123
|
+
readonly kind: "event";
|
|
124
|
+
readonly event: AgentEvent;
|
|
125
|
+
readonly attempt: number;
|
|
126
|
+
} | {
|
|
127
|
+
readonly kind: "schedule";
|
|
128
|
+
readonly cron: string;
|
|
129
|
+
readonly scheduledAt: number;
|
|
130
|
+
};
|
|
131
|
+
export interface AgentModuleRequest {
|
|
132
|
+
readonly method: string;
|
|
133
|
+
readonly path: string;
|
|
134
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
135
|
+
readonly body: string | null;
|
|
136
|
+
}
|
|
137
|
+
export interface AgentModuleResponse {
|
|
138
|
+
readonly status: number;
|
|
139
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
140
|
+
readonly body: string;
|
|
141
|
+
}
|
|
142
|
+
export interface AgentModuleAuthority {
|
|
143
|
+
samva(request: AgentModuleRequest): Promise<AgentModuleResponse>;
|
|
144
|
+
connection(integrationId: string, tool: string, input: Readonly<Record<string, unknown>>): Promise<unknown>;
|
|
145
|
+
searchMemory(query: string): Promise<ReadonlyArray<AgentMemoryMatch>>;
|
|
146
|
+
remember(content: string): Promise<void>;
|
|
147
|
+
log(values: ReadonlyArray<unknown>): Promise<void>;
|
|
148
|
+
state?(call: AgentStateCall): Promise<Schema.Json>;
|
|
149
|
+
startWorkflow?(input: AgentWorkflowStart): Promise<string>;
|
|
150
|
+
}
|