@aithos/sdk 0.1.0-alpha.53 → 0.1.0-alpha.54

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.
@@ -90,6 +90,89 @@ export interface InvokeBedrockResult {
90
90
  */
91
91
  readonly sponsoredRemainingForUser?: number;
92
92
  }
93
+ /** A decrypted ethos section in the working-set. */
94
+ export interface WorkingSetSection {
95
+ readonly id: string;
96
+ readonly title: string;
97
+ readonly body: string;
98
+ }
99
+ /**
100
+ * Client-decrypted data the agentic loop may read server-side. Built in the
101
+ * browser (where the keys live) from exactly the zones / collections the
102
+ * mandate grants — the proxy never holds a standing decryption key
103
+ * (see PLATFORM-COMPUTE-AGENTIC-MCP.md §4). Use {@link ComputeNamespace}
104
+ * with a `mcp` reference + this working-set.
105
+ */
106
+ export interface ComputeWorkingSet {
107
+ /** Decrypted ethos sections, per zone. Only granted zones appear. */
108
+ readonly ethos?: {
109
+ readonly public?: readonly WorkingSetSection[];
110
+ readonly circle?: readonly WorkingSetSection[];
111
+ readonly self?: readonly WorkingSetSection[];
112
+ };
113
+ /** Decrypted structured data, per collection name. */
114
+ readonly data?: Record<string, readonly Record<string, unknown>[]>;
115
+ }
116
+ /** A tool invocation the loop performed (trace for UI / debugging). */
117
+ export interface ConverseToolCall {
118
+ readonly name: string;
119
+ readonly ok: boolean;
120
+ readonly turn: number;
121
+ }
122
+ export type ConverseStopReason = "end_turn" | "max_tokens" | "stop_sequence" | "max_iterations" | "budget_exhausted";
123
+ export interface RunConversationArgs {
124
+ /** Mandate id — optional for owner sessions, required for delegate sessions. */
125
+ readonly mandateId?: string;
126
+ /** Claude model id (text or vision). */
127
+ readonly model: string;
128
+ /** Initial conversation. The loop's internal tool turns are server-side. */
129
+ readonly messages: readonly ComputeMessage[];
130
+ /** Optional system prompt. */
131
+ readonly system?: string;
132
+ /**
133
+ * MCP tools to expose to the model. v1 only supports the Aithos server.
134
+ * Omit `tools` to expose the full Aithos catalogue; pass a subset to narrow.
135
+ */
136
+ readonly mcp?: {
137
+ readonly server: "aithos";
138
+ readonly tools?: readonly string[];
139
+ };
140
+ /**
141
+ * Client-decrypted working-set the tools read from. Build it with
142
+ * {@link ComputeNamespace.buildWorkingSet}. Required for any tool that
143
+ * touches private (circle/self) or structured data.
144
+ */
145
+ readonly workingSet?: ComputeWorkingSet;
146
+ /** Cap on Bedrock turns. Server clamps to its own hard cap. Default 6. */
147
+ readonly maxIterations?: number;
148
+ /** Per-turn output token cap. */
149
+ readonly maxTokens?: number;
150
+ readonly temperature?: number;
151
+ /** Idempotency key for the WHOLE conversation (generated if omitted). */
152
+ readonly idempotencyKey?: string;
153
+ readonly signal?: AbortSignal;
154
+ }
155
+ export interface RunConversationResult {
156
+ /** Final assistant text. */
157
+ readonly content: string;
158
+ readonly stopReason: ConverseStopReason;
159
+ /** Number of Bedrock turns performed (each was a billed call). */
160
+ readonly iterations: number;
161
+ /** Token usage summed over all turns. */
162
+ readonly usage: {
163
+ readonly inputTokens: number;
164
+ readonly outputTokens: number;
165
+ };
166
+ /** Trace of the tool calls the loop made. */
167
+ readonly toolCalls: readonly ConverseToolCall[];
168
+ /** Total microcredits debited for the whole conversation. */
169
+ readonly creditsCharged: number;
170
+ readonly walletBalance: number;
171
+ readonly auditId: string;
172
+ readonly fundedBy?: "sponsored" | "grant" | "purchase";
173
+ readonly receiptId?: string;
174
+ readonly sponsoredBy?: string;
175
+ }
93
176
  /**
94
177
  * Stable cross-provider image model ids supported by the Aithos compute
95
178
  * proxy. New models can be added on the server side without an SDK
@@ -399,6 +482,21 @@ export declare class ComputeNamespace {
399
482
  * `mandate_revoked`, `insufficient_credits`, …).
400
483
  */
401
484
  invokeBedrock(args: InvokeBedrockArgs): Promise<InvokeBedrockResult>;
485
+ /**
486
+ * Run an agentic conversation: a multi-turn Bedrock tool-calling loop that
487
+ * runs server-side in a single POST and is billed once for the cumulative
488
+ * token usage. Tools come from the Aithos MCP (declared via `mcp`); the
489
+ * model reads private user data from the client-decrypted `workingSet`.
490
+ *
491
+ * The loop, tool dispatch, and billing all happen on the proxy — the SDK
492
+ * makes ONE signed request and gets the final answer. Same signer paths as
493
+ * {@link invokeBedrock} (owner direct or delegate-under-mandate).
494
+ *
495
+ * @throws {AithosSDKError} `sdk_no_signer`, `sdk_no_delegate_for_mandate`,
496
+ * `network`, `http`, `empty`, or any proxy code (`quota_exceeded`,
497
+ * `mandate_revoked`, `insufficient_credits`, …).
498
+ */
499
+ runConversation(args: RunConversationArgs): Promise<RunConversationResult>;
402
500
  /**
403
501
  * Multimodal Bedrock invoke — image + text → text response.
404
502
  * Default model: `claude-sonnet-4-6` (vision-capable, reliable JSON).
@@ -101,6 +101,53 @@ export class ComputeNamespace {
101
101
  signal: args.signal,
102
102
  });
103
103
  }
104
+ /**
105
+ * Run an agentic conversation: a multi-turn Bedrock tool-calling loop that
106
+ * runs server-side in a single POST and is billed once for the cumulative
107
+ * token usage. Tools come from the Aithos MCP (declared via `mcp`); the
108
+ * model reads private user data from the client-decrypted `workingSet`.
109
+ *
110
+ * The loop, tool dispatch, and billing all happen on the proxy — the SDK
111
+ * makes ONE signed request and gets the final answer. Same signer paths as
112
+ * {@link invokeBedrock} (owner direct or delegate-under-mandate).
113
+ *
114
+ * @throws {AithosSDKError} `sdk_no_signer`, `sdk_no_delegate_for_mandate`,
115
+ * `network`, `http`, `empty`, or any proxy code (`quota_exceeded`,
116
+ * `mandate_revoked`, `insufficient_credits`, …).
117
+ */
118
+ async runConversation(args) {
119
+ const { endpoints, fetch: fetchImpl } = this.#deps;
120
+ const choice = this.#resolveSigner(args.mandateId);
121
+ const url = computeInvokeUrl(endpoints);
122
+ const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();
123
+ const params = {
124
+ app_did: this.#deps.appDid,
125
+ mandate_id: this.#resolveMandateIdForWire(args.mandateId, choice),
126
+ model: args.model,
127
+ messages: args.messages,
128
+ idempotency_key: idempotencyKey,
129
+ };
130
+ if (args.system !== undefined)
131
+ params.system = args.system;
132
+ if (args.mcp !== undefined)
133
+ params.mcp = args.mcp;
134
+ if (args.workingSet !== undefined)
135
+ params.working_set = args.workingSet;
136
+ if (args.maxTokens !== undefined)
137
+ params.max_tokens = args.maxTokens;
138
+ if (args.maxIterations !== undefined)
139
+ params.max_iterations = args.maxIterations;
140
+ if (args.temperature !== undefined)
141
+ params.temperature = args.temperature;
142
+ return await this.#signAndPost({
143
+ url,
144
+ method: "aithos.compute_converse",
145
+ params,
146
+ choice,
147
+ fetchImpl,
148
+ signal: args.signal,
149
+ });
150
+ }
104
151
  /**
105
152
  * Multimodal Bedrock invoke — image + text → text response.
106
153
  * Default model: `claude-sonnet-4-6` (vision-capable, reliable JSON).
@@ -5,7 +5,7 @@ export { AithosSDKError } from "./types.js";
5
5
  export { AithosRpcError } from "@aithos/protocol-client";
6
6
  export type { AithosSdkEndpoints } from "./endpoints.js";
7
7
  export { DEFAULT_SDK_ENDPOINTS } from "./endpoints.js";
8
- export type { ComputeMessage, ImageAspectRatio, ImageModelId, InvokeBedrockArgs, InvokeBedrockResult, InvokeBedrockVisionArgs, InvokeBedrockVisionResult, InvokeImageArgs, InvokeImageImage, InvokeImageResult, InvokeSegmentationArgs, InvokeSegmentationResult, SegmentPolygon, StopReason, TranscribeModelId, TranscribeProgressState, TranscribeSegment, TranscribeWord, InvokeTranscribeArgs, InvokeTranscribeResult, PrepareTranscribeArgs, PrepareTranscribeResult, StartTranscribeArgs, StartTranscribeResult, TranscribeStatusResult, TranscribeJobSummary, } from "./compute.js";
8
+ export type { ComputeMessage, ImageAspectRatio, ImageModelId, InvokeBedrockArgs, InvokeBedrockResult, InvokeBedrockVisionArgs, InvokeBedrockVisionResult, InvokeImageArgs, InvokeImageImage, InvokeImageResult, InvokeSegmentationArgs, InvokeSegmentationResult, SegmentPolygon, StopReason, RunConversationArgs, RunConversationResult, ComputeWorkingSet, WorkingSetSection, ConverseToolCall, ConverseStopReason, TranscribeModelId, TranscribeProgressState, TranscribeSegment, TranscribeWord, InvokeTranscribeArgs, InvokeTranscribeResult, PrepareTranscribeArgs, PrepareTranscribeResult, StartTranscribeArgs, StartTranscribeResult, TranscribeStatusResult, TranscribeJobSummary, } from "./compute.js";
9
9
  export { ComputeNamespace } from "./compute.js";
10
10
  export type { LocalPendingEntry, LocalPendingStatus, TranscribeDraftMeta, TranscribeDraftRecord, } from "./transcribe-resilience.js";
11
11
  export { LocalPendingTranscribeTracker, TranscribeDraftStore, TranscribeDraftUnavailableError, } from "./transcribe-resilience.js";
package/dist/src/sdk.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import type { AithosAuth } from "./auth.js";
2
2
  import { AppsNamespace } from "./apps.js";
3
- import { ComputeNamespace } from "./compute.js";
3
+ import { ComputeNamespace, type ComputeWorkingSet } from "./compute.js";
4
4
  import { type AithosSdkEndpoints } from "./endpoints.js";
5
- import { EthosNamespace } from "./ethos.js";
5
+ import { EthosNamespace, type ZoneName } from "./ethos.js";
6
6
  import { MandatesNamespace } from "./mandates.js";
7
7
  import { WalletNamespace } from "./wallet.js";
8
8
  import { WebNamespace } from "./web.js";
@@ -57,5 +57,29 @@ export declare class AithosSDK {
57
57
  constructor(config: AithosSDKConfig);
58
58
  /** DID of the currently signed-in owner, or null if no owner is loaded. */
59
59
  get userDid(): string | null;
60
+ /**
61
+ * Build the client-decrypted working-set for an agentic conversation.
62
+ *
63
+ * Reads the requested ethos zones for `did` through {@link EthosNamespace}
64
+ * (which decrypts client-side using the active owner/delegate keys) and
65
+ * packages them into the {@link ComputeWorkingSet} shape that
66
+ * `sdk.compute.runConversation({ workingSet })` consumes.
67
+ *
68
+ * Only zones the session can actually read are included: a zone the
69
+ * mandate does not grant (or whose delegate wrap is missing) throws
70
+ * `ethos_zone_unreadable` / `ethos_anonymous_private_zone` on read and is
71
+ * silently skipped — so the working-set is naturally bounded by what the
72
+ * caller is authorized to see. The proxy never holds a decryption key;
73
+ * this is where the plaintext is produced (see PLATFORM-COMPUTE-AGENTIC-MCP.md §4).
74
+ *
75
+ * Structured (gamma) data collections are not loaded here in v1 — attach
76
+ * them to the returned object's `data` field yourself if needed.
77
+ *
78
+ * @param did Subject DID whose ethos to read (usually the signed-in owner).
79
+ * @param opts.zones Zones to attempt. Defaults to all three.
80
+ */
81
+ buildWorkingSet(did: string, opts?: {
82
+ readonly zones?: readonly ZoneName[];
83
+ }): Promise<ComputeWorkingSet>;
60
84
  }
61
85
  //# sourceMappingURL=sdk.d.ts.map
package/dist/src/sdk.js CHANGED
@@ -1,10 +1,11 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Copyright 2026 Mathieu Colla
3
3
  import { AppsNamespace } from "./apps.js";
4
- import { ComputeNamespace } from "./compute.js";
4
+ import { ComputeNamespace, } from "./compute.js";
5
5
  import { resolveEndpoints } from "./endpoints.js";
6
6
  import { EthosNamespace } from "./ethos.js";
7
7
  import { MandatesNamespace } from "./mandates.js";
8
+ import { AithosSDKError } from "./types.js";
8
9
  import { WalletNamespace } from "./wallet.js";
9
10
  import { WebNamespace } from "./web.js";
10
11
  export class AithosSDK {
@@ -80,5 +81,48 @@ export class AithosSDK {
80
81
  get userDid() {
81
82
  return this.auth.getOwnerInfo()?.did ?? null;
82
83
  }
84
+ /**
85
+ * Build the client-decrypted working-set for an agentic conversation.
86
+ *
87
+ * Reads the requested ethos zones for `did` through {@link EthosNamespace}
88
+ * (which decrypts client-side using the active owner/delegate keys) and
89
+ * packages them into the {@link ComputeWorkingSet} shape that
90
+ * `sdk.compute.runConversation({ workingSet })` consumes.
91
+ *
92
+ * Only zones the session can actually read are included: a zone the
93
+ * mandate does not grant (or whose delegate wrap is missing) throws
94
+ * `ethos_zone_unreadable` / `ethos_anonymous_private_zone` on read and is
95
+ * silently skipped — so the working-set is naturally bounded by what the
96
+ * caller is authorized to see. The proxy never holds a decryption key;
97
+ * this is where the plaintext is produced (see PLATFORM-COMPUTE-AGENTIC-MCP.md §4).
98
+ *
99
+ * Structured (gamma) data collections are not loaded here in v1 — attach
100
+ * them to the returned object's `data` field yourself if needed.
101
+ *
102
+ * @param did Subject DID whose ethos to read (usually the signed-in owner).
103
+ * @param opts.zones Zones to attempt. Defaults to all three.
104
+ */
105
+ async buildWorkingSet(did, opts) {
106
+ const zones = opts?.zones ?? ["public", "circle", "self"];
107
+ const client = await this.ethos.of(did);
108
+ const ethos = {};
109
+ for (const zone of zones) {
110
+ try {
111
+ const sections = await client.zone(zone).sections();
112
+ ethos[zone] = sections.map((s) => ({
113
+ id: s.id,
114
+ title: s.title,
115
+ body: s.body,
116
+ }));
117
+ }
118
+ catch (e) {
119
+ // Zone not granted / not decryptable for this session → skip it.
120
+ if (e instanceof AithosSDKError)
121
+ continue;
122
+ throw e;
123
+ }
124
+ }
125
+ return { ethos };
126
+ }
83
127
  }
84
128
  //# sourceMappingURL=sdk.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=converse.test.d.ts.map
@@ -0,0 +1,162 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Mathieu Colla
3
+ // Unit tests for sdk.compute.runConversation with a mock fetch.
4
+ //
5
+ // Mirrors compute.test.ts: a real BrowserIdentity drives the actual
6
+ // envelope-signing path, and we assert on the JSON-RPC body posted to
7
+ // the compute proxy (method name + camelCase→snake_case param mapping).
8
+ import { strict as assert } from "node:assert";
9
+ import { describe, it } from "node:test";
10
+ import { createBrowserIdentity } from "@aithos/protocol-client";
11
+ import { AithosAuth, AithosSDK, AithosSDKError, memoryKeyStore, noopStore, } from "../src/index.js";
12
+ import { serializeRecoveryFile } from "../src/internal/recovery-file.js";
13
+ const APP_DID = "did:aithos:app:test";
14
+ async function makeSdk(fetchImpl) {
15
+ const id = createBrowserIdentity("test-handle", "Test User");
16
+ const auth = new AithosAuth({
17
+ authBaseUrl: "https://auth.test",
18
+ fetch: (() => {
19
+ throw new Error("auth not used in converse tests");
20
+ }),
21
+ sessionStore: noopStore(),
22
+ keyStore: memoryKeyStore(),
23
+ });
24
+ const { text } = serializeRecoveryFile(id);
25
+ await auth.signInWithRecovery({ file: text });
26
+ return new AithosSDK({
27
+ auth,
28
+ appDid: APP_DID,
29
+ endpoints: { compute: "https://compute.example.test" },
30
+ fetch: fetchImpl,
31
+ });
32
+ }
33
+ const HAPPY_RESULT = {
34
+ content: "Voici le résumé.",
35
+ stopReason: "end_turn",
36
+ iterations: 2,
37
+ usage: { inputTokens: 420, outputTokens: 95 },
38
+ toolCalls: [{ name: "ethos_read_section", ok: true, turn: 1 }],
39
+ creditsCharged: 130,
40
+ walletBalance: 99_870,
41
+ auditId: "audit-cv-1",
42
+ fundedBy: "purchase",
43
+ };
44
+ describe("compute.runConversation — happy path + param mapping", () => {
45
+ it("posts aithos.compute_converse with mapped params and parses the result", async () => {
46
+ let capturedUrl;
47
+ let capturedInit;
48
+ const fakeFetch = async (input, init) => {
49
+ capturedUrl = typeof input === "string" ? input : input.toString();
50
+ capturedInit = init;
51
+ return new Response(JSON.stringify({ result: HAPPY_RESULT }), {
52
+ status: 200,
53
+ headers: { "content-type": "application/json" },
54
+ });
55
+ };
56
+ const sdk = await makeSdk(fakeFetch);
57
+ const out = await sdk.compute.runConversation({
58
+ mandateId: "mandate:abc",
59
+ model: "claude-sonnet-4-6",
60
+ system: "Tu agis dans la voix de l'utilisateur.",
61
+ messages: [{ role: "user", content: "Résume mon ethos." }],
62
+ mcp: { server: "aithos", tools: ["ethos_list_sections", "ethos_read_section"] },
63
+ workingSet: {
64
+ ethos: { public: [{ id: "p1", title: "Bio", body: "..." }] },
65
+ },
66
+ maxIterations: 5,
67
+ maxTokens: 800,
68
+ temperature: 0.4,
69
+ });
70
+ assert.deepEqual(out, HAPPY_RESULT);
71
+ assert.equal(capturedUrl, "https://compute.example.test/v1/invoke");
72
+ assert.equal(capturedInit?.method, "POST");
73
+ const body = JSON.parse(capturedInit?.body);
74
+ assert.equal(body.jsonrpc, "2.0");
75
+ assert.equal(body.method, "aithos.compute_converse");
76
+ assert.equal(body.params.app_did, APP_DID);
77
+ assert.equal(body.params.mandate_id, "mandate:abc");
78
+ assert.equal(body.params.model, "claude-sonnet-4-6");
79
+ assert.equal(body.params.system, "Tu agis dans la voix de l'utilisateur.");
80
+ // camelCase → snake_case mapping on the wire.
81
+ assert.equal(body.params.max_iterations, 5);
82
+ assert.equal(body.params.max_tokens, 800);
83
+ assert.equal(body.params.temperature, 0.4);
84
+ assert.ok(body.params.working_set, "working_set must be on the wire");
85
+ assert.deepEqual(body.params.mcp, {
86
+ server: "aithos",
87
+ tools: ["ethos_list_sections", "ethos_read_section"],
88
+ });
89
+ assert.match(body.params.idempotency_key, /^[0-9a-f]{32}$/);
90
+ assert.ok(body.params._envelope, "request must carry a signed envelope");
91
+ // SDK-only camelCase keys must NOT leak onto the wire.
92
+ assert.equal(body.params.maxIterations, undefined);
93
+ assert.equal(body.params.workingSet, undefined);
94
+ });
95
+ it("omits optional fields when not provided", async () => {
96
+ let capturedInit;
97
+ const fakeFetch = async (_input, init) => {
98
+ capturedInit = init;
99
+ return new Response(JSON.stringify({ result: HAPPY_RESULT }), {
100
+ status: 200,
101
+ headers: { "content-type": "application/json" },
102
+ });
103
+ };
104
+ const sdk = await makeSdk(fakeFetch);
105
+ await sdk.compute.runConversation({
106
+ mandateId: "mandate:abc",
107
+ model: "claude-haiku-4-5",
108
+ messages: [{ role: "user", content: "Salut" }],
109
+ });
110
+ const body = JSON.parse(capturedInit?.body);
111
+ assert.equal(body.params.system, undefined);
112
+ assert.equal(body.params.mcp, undefined);
113
+ assert.equal(body.params.working_set, undefined);
114
+ assert.equal(body.params.max_iterations, undefined);
115
+ assert.equal(body.params.max_tokens, undefined);
116
+ });
117
+ });
118
+ describe("compute.runConversation — errors", () => {
119
+ it("maps a JSON-RPC error to AithosSDKError with the proxy code", async () => {
120
+ const fakeFetch = async () => new Response(JSON.stringify({
121
+ error: { code: -32071, message: "insufficient credits" },
122
+ }), { status: 200, headers: { "content-type": "application/json" } });
123
+ const sdk = await makeSdk(fakeFetch);
124
+ await assert.rejects(() => sdk.compute.runConversation({
125
+ mandateId: "mandate:abc",
126
+ model: "claude-sonnet-4-6",
127
+ messages: [{ role: "user", content: "Hi" }],
128
+ }), (err) => {
129
+ assert.ok(err instanceof AithosSDKError);
130
+ assert.equal(err.code, "-32071");
131
+ return true;
132
+ });
133
+ });
134
+ it("throws sdk_no_signer when no owner and no mandate", async () => {
135
+ // Build an SDK with no signed-in owner.
136
+ const auth = new AithosAuth({
137
+ authBaseUrl: "https://auth.test",
138
+ fetch: (() => {
139
+ throw new Error("unused");
140
+ }),
141
+ sessionStore: noopStore(),
142
+ keyStore: memoryKeyStore(),
143
+ });
144
+ const sdk = new AithosSDK({
145
+ auth,
146
+ appDid: APP_DID,
147
+ endpoints: { compute: "https://compute.example.test" },
148
+ fetch: (() => {
149
+ throw new Error("fetch must not be reached");
150
+ }),
151
+ });
152
+ await assert.rejects(() => sdk.compute.runConversation({
153
+ model: "claude-sonnet-4-6",
154
+ messages: [{ role: "user", content: "Hi" }],
155
+ }), (err) => {
156
+ assert.ok(err instanceof AithosSDKError);
157
+ assert.equal(err.code, "sdk_no_signer");
158
+ return true;
159
+ });
160
+ });
161
+ });
162
+ //# sourceMappingURL=converse.test.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithos/sdk",
3
- "version": "0.1.0-alpha.53",
3
+ "version": "0.1.0-alpha.54",
4
4
  "description": "Aithos SDK — high-level TypeScript developer kit for building agentic apps on the Aithos protocol. Wraps @aithos/protocol-client and exposes the Aithos compute proxy and wallet (Stripe top-up) endpoints.",
5
5
  "keywords": [
6
6
  "aithos",