orchajs 0.24.0 → 0.26.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.
Files changed (78) hide show
  1. package/README.md +50 -3
  2. package/dist/amarsia/analytics.js +12 -0
  3. package/dist/amarsia/inference.d.ts +6 -0
  4. package/dist/amarsia/inference.js +377 -0
  5. package/dist/browser.js +5 -0
  6. package/dist/cli-agents-template.d.ts +1 -1
  7. package/dist/cli-agents-template.js +44 -11
  8. package/dist/cli.js +22 -9
  9. package/dist/compiler/build-project.js +57 -14
  10. package/dist/compiler/node-esm-banner.d.ts +2 -0
  11. package/dist/compiler/node-esm-banner.js +5 -0
  12. package/dist/orcha.js +5 -0
  13. package/dist/playground/server.js +3 -0
  14. package/dist/project-loader.js +4 -2
  15. package/dist/providers/anthropic.js +67 -58
  16. package/dist/providers/bedrock.js +14 -8
  17. package/dist/providers/deepseek.js +9 -2
  18. package/dist/providers/google-gemini.js +20 -15
  19. package/dist/providers/openai.js +6 -0
  20. package/dist/providers/types.d.ts +5 -0
  21. package/dist/react-native.js +5 -0
  22. package/dist/runtime/agent.d.ts +3 -3
  23. package/dist/runtime/agent.js +278 -45
  24. package/dist/runtime/compiler-hook.d.ts +4 -0
  25. package/dist/runtime/compiler-hook.js +9 -0
  26. package/dist/runtime/create-orcha.d.ts +19 -0
  27. package/dist/runtime/create-orcha.js +109 -12
  28. package/dist/runtime/optional-features.d.ts +19 -0
  29. package/dist/runtime/optional-features.js +22 -0
  30. package/dist/runtime/platform-browser.js +16 -3
  31. package/dist/runtime/platform-node.js +16 -2
  32. package/dist/runtime/platform-react-native.js +16 -3
  33. package/dist/runtime/session-events.js +19 -0
  34. package/dist/storage/browser-indexeddb.d.ts +3 -0
  35. package/dist/storage/browser-indexeddb.js +72 -8
  36. package/dist/storage/cloud-outbox.d.ts +30 -0
  37. package/dist/storage/cloud-outbox.js +628 -0
  38. package/dist/storage/cloud.d.ts +1 -0
  39. package/dist/storage/cloud.js +1 -0
  40. package/dist/storage/node-jsonl.d.ts +3 -0
  41. package/dist/storage/node-jsonl.js +273 -4
  42. package/dist/storage/node-sqlite.d.ts +3 -0
  43. package/dist/storage/node-sqlite.js +66 -17
  44. package/dist/storage/react-native-jsonl.d.ts +3 -0
  45. package/dist/storage/react-native-jsonl.js +223 -0
  46. package/dist/testing.js +3 -0
  47. package/dist/types.d.ts +25 -4
  48. package/dist-cjs/amarsia/analytics.js +12 -0
  49. package/dist-cjs/amarsia/inference.js +372 -0
  50. package/dist-cjs/browser.js +5 -0
  51. package/dist-cjs/cli-agents-template.js +44 -11
  52. package/dist-cjs/compiler/build-project.js +68 -4
  53. package/dist-cjs/compiler/node-esm-banner.js +32 -0
  54. package/dist-cjs/orcha.js +5 -0
  55. package/dist-cjs/playground/server.js +1 -0
  56. package/dist-cjs/project-loader.js +7 -5
  57. package/dist-cjs/providers/anthropic.js +65 -60
  58. package/dist-cjs/providers/bedrock.js +17 -9
  59. package/dist-cjs/providers/deepseek.js +10 -2
  60. package/dist-cjs/providers/google-gemini.js +27 -20
  61. package/dist-cjs/providers/openai.js +8 -0
  62. package/dist-cjs/react-native.js +5 -0
  63. package/dist-cjs/runtime/agent.js +311 -61
  64. package/dist-cjs/runtime/compiler-hook.js +11 -0
  65. package/dist-cjs/runtime/create-orcha.js +117 -12
  66. package/dist-cjs/runtime/optional-features.js +58 -0
  67. package/dist-cjs/runtime/platform-browser.js +16 -3
  68. package/dist-cjs/runtime/platform-node.js +16 -2
  69. package/dist-cjs/runtime/platform-react-native.js +18 -3
  70. package/dist-cjs/runtime/session-events.js +14 -0
  71. package/dist-cjs/storage/browser-indexeddb.js +73 -8
  72. package/dist-cjs/storage/cloud-outbox.js +646 -0
  73. package/dist-cjs/storage/cloud.js +29 -0
  74. package/dist-cjs/storage/node-jsonl.js +246 -3
  75. package/dist-cjs/storage/node-sqlite.js +70 -19
  76. package/dist-cjs/storage/react-native-jsonl.js +207 -0
  77. package/dist-cjs/testing.js +1 -0
  78. package/package.json +1 -1
@@ -3,3 +3,7 @@ export type RegistryCompiler = (configuration: OrchaInitConfiguration, projectRo
3
3
  /** @internal Installed by Node development tooling, never by runtime bundles. */
4
4
  export declare function setRegistryCompiler(compiler: RegistryCompiler): void;
5
5
  export declare function getRegistryCompiler(): RegistryCompiler | undefined;
6
+ /** @internal Prevents registry evaluation from starting runtime resources. */
7
+ export declare function setRegistryCompilationActive(active: boolean): void;
8
+ /** @internal True only while development tooling evaluates a registry. */
9
+ export declare function isRegistryCompilationActive(): boolean;
@@ -1,4 +1,5 @@
1
1
  let registryCompiler;
2
+ let registryCompilationActive = false;
2
3
  /** @internal Installed by Node development tooling, never by runtime bundles. */
3
4
  export function setRegistryCompiler(compiler) {
4
5
  registryCompiler = compiler;
@@ -6,3 +7,11 @@ export function setRegistryCompiler(compiler) {
6
7
  export function getRegistryCompiler() {
7
8
  return registryCompiler;
8
9
  }
10
+ /** @internal Prevents registry evaluation from starting runtime resources. */
11
+ export function setRegistryCompilationActive(active) {
12
+ registryCompilationActive = active;
13
+ }
14
+ /** @internal True only while development tooling evaluates a registry. */
15
+ export function isRegistryCompilationActive() {
16
+ return registryCompilationActive;
17
+ }
@@ -4,12 +4,31 @@ import type { AgentRuntime, CompiledBundle, OrchaInitConfiguration } from "../ty
4
4
  export interface Orcha {
5
5
  init(configuration: OrchaInitConfiguration): OrchaClient;
6
6
  isInitialized(): boolean;
7
+ /** Number of sessions whose local tail is waiting for cloud acknowledgement. */
8
+ readonly cloudStoragePendingCount: number;
9
+ /** Most recent background cloud storage error, if any. */
10
+ readonly cloudStorageLastError: Error | undefined;
11
+ /** Waits for cloud outboxes to drain, up to the supplied timeout. */
12
+ flushCloudStorage(options?: number | {
13
+ timeoutMs?: number;
14
+ }): Promise<void>;
15
+ /**
16
+ * Closes background runtime resources and makes a best-effort backup flush.
17
+ * Use flushCloudStorage() first when remote delivery must be enforced.
18
+ */
19
+ close(options?: {
20
+ timeoutMs?: number;
21
+ }): Promise<void>;
7
22
  /** Flushes queued Amarsia telemetry without blocking normal agent runs. */
8
23
  flushTelemetry(options?: {
9
24
  timeoutMs?: number;
10
25
  }): Promise<void>;
11
26
  /** @internal Used by the development compiler. */
12
27
  getCompiledBundle(): CompiledBundle;
28
+ /** @internal Used to omit direct providers from inferred builds. */
29
+ isInferenceEnabled(): boolean;
30
+ /** @internal Used to include cloud storage only when selected. */
31
+ isCloudStorageEnabled(): boolean;
13
32
  }
14
33
  export type OrchaClient = Orcha & Record<string, AgentRuntime>;
15
34
  export type BundleResolver = (configuration: OrchaInitConfiguration) => CompiledBundle;
@@ -1,11 +1,17 @@
1
1
  import { RuntimeAgent } from "./agent.js";
2
2
  import { AmarsiaTelemetryClient, withAmarsiaTelemetry, } from "../amarsia/analytics.js";
3
+ import { isRegistryCompilationActive } from "./compiler-hook.js";
3
4
  import { setOrchaRuntimeContext } from "./context.js";
5
+ import { createInferenceGenerator } from "./optional-features.js";
4
6
  class OrchaRuntimeCore {
5
7
  #agents = new Map();
6
8
  #bundle;
9
+ #inferenceEnabled = false;
10
+ #cloudStorageEnabled = false;
7
11
  #client;
8
12
  #telemetry;
13
+ #stores = new Set();
14
+ #closing;
9
15
  #activeSessions = new Set();
10
16
  #sessionControls = new Map();
11
17
  #resolveBundle;
@@ -20,16 +26,22 @@ class OrchaRuntimeCore {
20
26
  this.#client = client;
21
27
  }
22
28
  init(configuration) {
23
- if (this.#telemetry) {
24
- void this.#telemetry.close();
25
- }
26
- for (const agent of this.#agents.values()) {
27
- if (agent instanceof RuntimeAgent) {
28
- void agent._close();
29
- }
29
+ if (this.#bundle || this.#closing) {
30
+ throw new Error("Orcha is already initialized. Await orcha.close() before initializing it again.");
30
31
  }
31
32
  const projectRoot = this.#platform.projectRoot(configuration);
32
33
  const bundle = configuration.bundle ?? this.#resolveBundle(configuration);
34
+ const inferenceEnabled = configuration.amarsia?.inference === true;
35
+ if (isRegistryCompilationActive()) {
36
+ this.#bundle = bundle;
37
+ this.#inferenceEnabled = inferenceEnabled;
38
+ this.#cloudStorageEnabled =
39
+ configuration.storage?.strategy === "cloud";
40
+ return this.#client;
41
+ }
42
+ if (inferenceEnabled && !configuration.amarsia?.key.trim()) {
43
+ throw new Error("Amarsia inference requires a non-empty amarsia.key.");
44
+ }
33
45
  if (configuration.amarsia?.key && this.#platform.syncProject) {
34
46
  this.#platform.syncProject({
35
47
  configuration,
@@ -38,7 +50,7 @@ class OrchaRuntimeCore {
38
50
  });
39
51
  }
40
52
  const runtimeConfiguration = {
41
- providers: Object.fromEntries(Object.entries(configuration.providers).map(([name, provider]) => [
53
+ providers: Object.fromEntries(Object.entries(configuration.providers ?? {}).map(([name, provider]) => [
42
54
  name,
43
55
  typeof provider === "string" ? { apiKey: provider } : provider,
44
56
  ])),
@@ -49,6 +61,16 @@ class OrchaRuntimeCore {
49
61
  mcp: configuration.mcp,
50
62
  storage: configuration.storage,
51
63
  };
64
+ if (inferenceEnabled) {
65
+ for (const provider of compiledProviderNames(bundle)) {
66
+ const providers = runtimeConfiguration.providers;
67
+ providers[provider] ??= { apiKey: "" };
68
+ }
69
+ }
70
+ const inferenceGenerator = inferenceEnabled
71
+ ? createInferenceGenerator(configuration.amarsia)
72
+ : undefined;
73
+ const generateProviderResponse = inferenceGenerator ?? this.#generateProviderResponse;
52
74
  if (bundle.actionRuntime &&
53
75
  runtimeConfiguration.actions?.runtime !== bundle.actionRuntime) {
54
76
  throw new Error(`Production bundle expects local action runtime "${bundle.actionRuntime}".`);
@@ -64,9 +86,11 @@ class OrchaRuntimeCore {
64
86
  this.#telemetry = telemetry;
65
87
  const createRuntimeStore = (manifest) => {
66
88
  const store = createStore(manifest);
67
- return telemetry
89
+ const runtimeStore = telemetry
68
90
  ? withAmarsiaTelemetry({ store, manifest, client: telemetry })
69
91
  : store;
92
+ this.#stores.add(runtimeStore);
93
+ return runtimeStore;
70
94
  };
71
95
  const agents = new Map();
72
96
  for (const [name, manifest] of Object.entries(bundle.agents)) {
@@ -78,7 +102,7 @@ class OrchaRuntimeCore {
78
102
  store: createRuntimeStore(subagentManifest),
79
103
  activeSessions: this.#activeSessions,
80
104
  sessionControls: this.#sessionControls,
81
- generateProviderResponse: this.#generateProviderResponse,
105
+ generateProviderResponse,
82
106
  delegatedOnly: true,
83
107
  projectRoot,
84
108
  randomUUID: this.#platform.randomUUID,
@@ -90,26 +114,80 @@ class OrchaRuntimeCore {
90
114
  store: createRuntimeStore(manifest),
91
115
  activeSessions: this.#activeSessions,
92
116
  sessionControls: this.#sessionControls,
93
- generateProviderResponse: this.#generateProviderResponse,
117
+ generateProviderResponse,
94
118
  subagents,
95
119
  projectRoot,
96
120
  randomUUID: this.#platform.randomUUID,
97
121
  }));
98
122
  }
99
123
  this.#bundle = bundle;
124
+ this.#inferenceEnabled = inferenceEnabled;
125
+ this.#cloudStorageEnabled =
126
+ configuration.storage?.strategy === "cloud";
100
127
  this.#agents = agents;
101
128
  setOrchaRuntimeContext(this.#client, {
102
129
  projectRoot,
103
130
  registrations: { ...configuration.agents },
104
131
  bundle,
105
132
  configuration: runtimeConfiguration,
106
- generateProviderResponse: this.#generateProviderResponse,
133
+ generateProviderResponse,
107
134
  });
108
135
  return this.#client;
109
136
  }
110
137
  isInitialized() {
111
138
  return this.#bundle !== undefined;
112
139
  }
140
+ get cloudStoragePendingCount() {
141
+ let pending = 0;
142
+ for (const store of this.#stores) {
143
+ pending += store.cloudStoragePendingCount ?? 0;
144
+ }
145
+ return pending;
146
+ }
147
+ get cloudStorageLastError() {
148
+ let error;
149
+ for (const store of this.#stores) {
150
+ error = store.cloudStorageLastError ?? error;
151
+ }
152
+ return error;
153
+ }
154
+ async flushCloudStorage(options = {}) {
155
+ const normalized = typeof options === "number" ? { timeoutMs: options } : options;
156
+ await Promise.all([...this.#stores].map((store) => store.flushCloudStorage?.(normalized)));
157
+ }
158
+ async close(options = {}) {
159
+ if (this.#closing)
160
+ return this.#closing;
161
+ const close = (async () => {
162
+ const backupOperations = [
163
+ this.#telemetry?.close(options),
164
+ ...[...this.#stores].map((store) => store.closeCloudStorage?.(options)),
165
+ ].filter((operation) => operation !== undefined);
166
+ const resourceOperations = [
167
+ ...[...this.#agents.values()].flatMap((agent) => agent instanceof RuntimeAgent ? [agent._close()] : []),
168
+ ];
169
+ const [, resourceResults] = await Promise.all([
170
+ Promise.allSettled(backupOperations),
171
+ Promise.allSettled(resourceOperations),
172
+ ]);
173
+ const failure = resourceResults.find((result) => result.status === "rejected");
174
+ this.#stores.clear();
175
+ this.#agents.clear();
176
+ this.#telemetry = undefined;
177
+ this.#bundle = undefined;
178
+ this.#inferenceEnabled = false;
179
+ this.#cloudStorageEnabled = false;
180
+ if (failure)
181
+ throw failure.reason;
182
+ })();
183
+ this.#closing = close;
184
+ try {
185
+ await close;
186
+ }
187
+ finally {
188
+ this.#closing = undefined;
189
+ }
190
+ }
113
191
  async flushTelemetry(options) {
114
192
  await this.#telemetry?.drain(options);
115
193
  }
@@ -119,10 +197,29 @@ class OrchaRuntimeCore {
119
197
  }
120
198
  return this.#bundle;
121
199
  }
200
+ isInferenceEnabled() {
201
+ return this.#inferenceEnabled;
202
+ }
203
+ isCloudStorageEnabled() {
204
+ return this.#cloudStorageEnabled;
205
+ }
122
206
  agent(name) {
123
207
  return this.#agents.get(name);
124
208
  }
125
209
  }
210
+ function compiledProviderNames(bundle) {
211
+ const names = new Set();
212
+ const visit = (manifest) => {
213
+ names.add(manifest.provider);
214
+ for (const evaluation of Object.values(manifest.evaluations ?? {})) {
215
+ if (evaluation.enabled !== false)
216
+ names.add(evaluation.provider);
217
+ }
218
+ Object.values(manifest.subagents ?? {}).forEach(visit);
219
+ };
220
+ Object.values(bundle.agents).forEach(visit);
221
+ return names;
222
+ }
126
223
  export function createOrcha(resolveBundle, generateProviderResponse, platform) {
127
224
  const core = new OrchaRuntimeCore(resolveBundle, generateProviderResponse, platform);
128
225
  const client = new Proxy(core, {
@@ -0,0 +1,19 @@
1
+ import type { ProviderResponseGenerator } from "../providers/types.js";
2
+ import type { SessionStore } from "../types.js";
3
+ export interface CloudSessionStoreFactoryOptions {
4
+ local: SessionStore;
5
+ key: string;
6
+ endpoint?: string;
7
+ agentName: string;
8
+ }
9
+ export type CloudSessionStoreFactory = (options: CloudSessionStoreFactoryOptions) => SessionStore;
10
+ export type InferenceGeneratorFactory = (configuration: {
11
+ key: string;
12
+ endpoint?: string;
13
+ }) => ProviderResponseGenerator;
14
+ /** @internal Registers the optional inference implementation. */
15
+ export declare function setInferenceGeneratorFactory(factory: InferenceGeneratorFactory): void;
16
+ /** @internal Registers the optional cloud storage implementation. */
17
+ export declare function setCloudSessionStoreFactory(factory: CloudSessionStoreFactory): void;
18
+ export declare function createInferenceGenerator(configuration: Parameters<InferenceGeneratorFactory>[0]): ProviderResponseGenerator;
19
+ export declare function createCloudSessionStore(options: CloudSessionStoreFactoryOptions): SessionStore;
@@ -0,0 +1,22 @@
1
+ let inferenceGeneratorFactory;
2
+ let cloudSessionStoreFactory;
3
+ /** @internal Registers the optional inference implementation. */
4
+ export function setInferenceGeneratorFactory(factory) {
5
+ inferenceGeneratorFactory = factory;
6
+ }
7
+ /** @internal Registers the optional cloud storage implementation. */
8
+ export function setCloudSessionStoreFactory(factory) {
9
+ cloudSessionStoreFactory = factory;
10
+ }
11
+ export function createInferenceGenerator(configuration) {
12
+ if (!inferenceGeneratorFactory) {
13
+ throw new Error("Amarsia inference was not included in this Orcha runtime.");
14
+ }
15
+ return inferenceGeneratorFactory(configuration);
16
+ }
17
+ export function createCloudSessionStore(options) {
18
+ if (!cloudSessionStoreFactory) {
19
+ throw new Error("Cloud session storage was not included in this Orcha runtime.");
20
+ }
21
+ return cloudSessionStoreFactory(options);
22
+ }
@@ -1,4 +1,5 @@
1
1
  import { BrowserIndexedDbSessionStore } from "../storage/browser-indexeddb.js";
2
+ import { createCloudSessionStore } from "./optional-features.js";
2
3
  import { portableRandomUUID } from "./random-id.js";
3
4
  export const browserRuntimePlatform = {
4
5
  randomUUID: portableRandomUUID,
@@ -7,9 +8,21 @@ export const browserRuntimePlatform = {
7
8
  },
8
9
  createSessionStore({ configuration, manifest }) {
9
10
  const strategy = configuration.storage?.strategy ?? "indexeddb";
10
- if (strategy !== "indexeddb") {
11
- throw new Error(`Browser runtimes require storage strategy "indexeddb", received "${strategy}".`);
11
+ if (strategy !== "indexeddb" && strategy !== "cloud") {
12
+ throw new Error(`Browser runtimes require storage strategy "indexeddb" or "cloud", received "${strategy}".`);
12
13
  }
13
- return new BrowserIndexedDbSessionStore(manifest.key ?? manifest.name, configuration.storage?.directory ?? "orchajs");
14
+ const local = new BrowserIndexedDbSessionStore(manifest.key ?? manifest.name, configuration.storage?.directory ?? "orchajs");
15
+ if (strategy !== "cloud") {
16
+ return local;
17
+ }
18
+ if (!configuration.amarsia?.key) {
19
+ throw new Error('Storage strategy "cloud" requires amarsia.key.');
20
+ }
21
+ return createCloudSessionStore({
22
+ local,
23
+ key: configuration.amarsia.key,
24
+ endpoint: configuration.amarsia.endpoint,
25
+ agentName: manifest.key ?? manifest.name,
26
+ });
14
27
  },
15
28
  };
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { resolve } from "node:path";
3
3
  import { syncAmarsiaProject } from "../amarsia/sync.js";
4
4
  import { createSessionStore } from "../storage/create-store.js";
5
+ import { createCloudSessionStore } from "./optional-features.js";
5
6
  export const nodeRuntimePlatform = {
6
7
  randomUUID,
7
8
  projectRoot(configuration) {
@@ -10,12 +11,25 @@ export const nodeRuntimePlatform = {
10
11
  process.cwd());
11
12
  },
12
13
  createSessionStore({ configuration, projectRoot, manifest }) {
13
- return createSessionStore({
14
- strategy: configuration.storage?.strategy,
14
+ const strategy = configuration.storage?.strategy;
15
+ const local = createSessionStore({
16
+ strategy: strategy === "cloud" ? "node-jsonl" : strategy,
15
17
  directory: configuration.storage?.directory,
16
18
  projectRoot,
17
19
  agentName: manifest.key ?? manifest.name,
18
20
  });
21
+ if (strategy !== "cloud") {
22
+ return local;
23
+ }
24
+ if (!configuration.amarsia?.key) {
25
+ throw new Error('Storage strategy "cloud" requires amarsia.key.');
26
+ }
27
+ return createCloudSessionStore({
28
+ local,
29
+ key: configuration.amarsia.key,
30
+ endpoint: configuration.amarsia.endpoint,
31
+ agentName: manifest.key ?? manifest.name,
32
+ });
19
33
  },
20
34
  syncProject({ configuration, bundle, projectRoot }) {
21
35
  if (!configuration.amarsia?.key) {
@@ -1,4 +1,5 @@
1
1
  import { ReactNativeJsonlSessionStore } from "../storage/react-native-jsonl.js";
2
+ import { createCloudSessionStore } from "./optional-features.js";
2
3
  import { portableRandomUUID } from "./random-id.js";
3
4
  export const reactNativeRuntimePlatform = {
4
5
  randomUUID: portableRandomUUID,
@@ -7,9 +8,21 @@ export const reactNativeRuntimePlatform = {
7
8
  },
8
9
  createSessionStore({ configuration, manifest }) {
9
10
  const strategy = configuration.storage?.strategy ?? "react-native";
10
- if (strategy !== "react-native") {
11
- throw new Error(`React Native requires storage strategy "react-native", received "${strategy}".`);
11
+ if (strategy !== "react-native" && strategy !== "cloud") {
12
+ throw new Error(`React Native requires storage strategy "react-native" or "cloud", received "${strategy}".`);
12
13
  }
13
- return new ReactNativeJsonlSessionStore(manifest.key ?? manifest.name);
14
+ const local = new ReactNativeJsonlSessionStore(manifest.key ?? manifest.name);
15
+ if (strategy !== "cloud") {
16
+ return local;
17
+ }
18
+ if (!configuration.amarsia?.key) {
19
+ throw new Error('Storage strategy "cloud" requires amarsia.key.');
20
+ }
21
+ return createCloudSessionStore({
22
+ local,
23
+ key: configuration.amarsia.key,
24
+ endpoint: configuration.amarsia.endpoint,
25
+ agentName: manifest.key ?? manifest.name,
26
+ });
14
27
  },
15
28
  };
@@ -158,9 +158,13 @@ export function normalizePersistedToolResults(value) {
158
158
  return undefined;
159
159
  }
160
160
  if (typeof item.callId === "string" && "output" in item) {
161
+ const contents = Array.isArray(item.contents)
162
+ ? item.contents.filter(isPersistedMessageContent)
163
+ : undefined;
161
164
  results.push({
162
165
  callId: item.callId,
163
166
  output: item.output,
167
+ ...(contents && contents.length > 0 ? { contents } : {}),
164
168
  ...(item.isError === true ? { isError: true } : {}),
165
169
  });
166
170
  continue;
@@ -184,6 +188,21 @@ export function normalizePersistedToolResults(value) {
184
188
  }
185
189
  return results;
186
190
  }
191
+ function isPersistedMessageContent(value) {
192
+ if (!isRecord(value) || typeof value.type !== "string") {
193
+ return false;
194
+ }
195
+ if (value.type === "text") {
196
+ return typeof value.text === "string";
197
+ }
198
+ if (value.type === "file") {
199
+ return (typeof value.mimeType === "string" &&
200
+ typeof value.filePath === "string");
201
+ }
202
+ return (["image", "video", "audio", "url"].includes(value.type) &&
203
+ typeof value.mimeType === "string" &&
204
+ typeof value.fileUri === "string");
205
+ }
187
206
  function isRecord(value) {
188
207
  return typeof value === "object" && value !== null && !Array.isArray(value);
189
208
  }
@@ -3,8 +3,11 @@ export declare class BrowserIndexedDbSessionStore implements SessionStore {
3
3
  #private;
4
4
  constructor(namespace: string, databaseName?: string);
5
5
  read(sessionId: string): Promise<SessionEvent[]>;
6
+ readAfterSequence(sessionId: string, afterSequence: number, limit: number): Promise<SessionEvent[]>;
6
7
  append(sessionId: string, events: SessionEvent[]): Promise<void>;
7
8
  listSessionIds(): Promise<string[]>;
9
+ getCloudAcknowledgement(sessionId: string): Promise<number>;
10
+ setCloudAcknowledgement(sessionId: string, sequence: number): Promise<void>;
8
11
  subscribe(sessionId: string, listener: (events: SessionEvent[]) => void): () => void;
9
12
  subscribeAll(listener: (sessionId: string, events: SessionEvent[]) => void): () => void;
10
13
  describeLocation(sessionId: string): Promise<string>;
@@ -1,5 +1,7 @@
1
- const DATABASE_VERSION = 1;
1
+ const DATABASE_VERSION = 3;
2
2
  const EVENT_STORE = "events";
3
+ const CLOUD_ACK_STORE = "cloud-acknowledgements";
4
+ const SESSION_SEQUENCE_INDEX = "session-sequence";
3
5
  export class BrowserIndexedDbSessionStore {
4
6
  #databaseName;
5
7
  #namespace;
@@ -19,6 +21,17 @@ export class BrowserIndexedDbSessionStore {
19
21
  .sort((left, right) => left.sequence - right.sequence)
20
22
  .map((record) => record.event);
21
23
  }
24
+ async readAfterSequence(sessionId, afterSequence, limit) {
25
+ validateTailArguments(afterSequence, limit);
26
+ const database = await this.#open();
27
+ const transaction = database.transaction(EVENT_STORE, "readonly");
28
+ const index = transaction
29
+ .objectStore(EVENT_STORE)
30
+ .index(SESSION_SEQUENCE_INDEX);
31
+ const records = await request(index.getAll(IDBKeyRange.bound([this.#namespace, sessionId, afterSequence], [this.#namespace, sessionId, Number.MAX_SAFE_INTEGER], true), limit));
32
+ await transactionComplete(transaction);
33
+ return records.map((record) => record.event);
34
+ }
22
35
  async append(sessionId, events) {
23
36
  if (events.length === 0) {
24
37
  return;
@@ -47,6 +60,33 @@ export class BrowserIndexedDbSessionStore {
47
60
  await transactionComplete(transaction);
48
61
  return [...new Set(records.map((record) => record.sessionId))].sort();
49
62
  }
63
+ async getCloudAcknowledgement(sessionId) {
64
+ const database = await this.#open();
65
+ const transaction = database.transaction(CLOUD_ACK_STORE, "readonly");
66
+ const value = await request(transaction.objectStore(CLOUD_ACK_STORE).get(acknowledgementId(this.#namespace, sessionId)));
67
+ await transactionComplete(transaction);
68
+ return typeof value === "number" &&
69
+ Number.isInteger(value) &&
70
+ value >= 0
71
+ ? value
72
+ : 0;
73
+ }
74
+ async setCloudAcknowledgement(sessionId, sequence) {
75
+ if (!Number.isInteger(sequence) || sequence < 0) {
76
+ throw new Error("Invalid cloud acknowledgement sequence.");
77
+ }
78
+ const database = await this.#open();
79
+ const transaction = database.transaction(CLOUD_ACK_STORE, "readwrite");
80
+ const store = transaction.objectStore(CLOUD_ACK_STORE);
81
+ const id = acknowledgementId(this.#namespace, sessionId);
82
+ const current = await request(store.get(id));
83
+ if (typeof current !== "number" ||
84
+ !Number.isInteger(current) ||
85
+ current < sequence) {
86
+ store.put(sequence, id);
87
+ }
88
+ await transactionComplete(transaction);
89
+ }
50
90
  subscribe(sessionId, listener) {
51
91
  const listeners = this.#listeners.get(sessionId) ?? new Set();
52
92
  listeners.add(listener);
@@ -73,14 +113,27 @@ export class BrowserIndexedDbSessionStore {
73
113
  const openRequest = indexedDB.open(this.#databaseName, DATABASE_VERSION);
74
114
  openRequest.onupgradeneeded = () => {
75
115
  const database = openRequest.result;
76
- if (database.objectStoreNames.contains(EVENT_STORE)) {
77
- return;
116
+ let eventStore;
117
+ if (!database.objectStoreNames.contains(EVENT_STORE)) {
118
+ eventStore = database.createObjectStore(EVENT_STORE, {
119
+ keyPath: "id",
120
+ });
121
+ eventStore.createIndex("session", ["namespace", "sessionId"]);
122
+ eventStore.createIndex("namespace", "namespace");
123
+ }
124
+ else {
125
+ eventStore = openRequest.transaction.objectStore(EVENT_STORE);
126
+ }
127
+ if (!eventStore.indexNames.contains(SESSION_SEQUENCE_INDEX)) {
128
+ eventStore.createIndex(SESSION_SEQUENCE_INDEX, [
129
+ "namespace",
130
+ "sessionId",
131
+ "sequence",
132
+ ]);
133
+ }
134
+ if (!database.objectStoreNames.contains(CLOUD_ACK_STORE)) {
135
+ database.createObjectStore(CLOUD_ACK_STORE);
78
136
  }
79
- const store = database.createObjectStore(EVENT_STORE, {
80
- keyPath: "id",
81
- });
82
- store.createIndex("session", ["namespace", "sessionId"]);
83
- store.createIndex("namespace", "namespace");
84
137
  };
85
138
  openRequest.onsuccess = () => resolve(openRequest.result);
86
139
  openRequest.onerror = () => reject(openRequest.error);
@@ -88,6 +141,9 @@ export class BrowserIndexedDbSessionStore {
88
141
  });
89
142
  }
90
143
  }
144
+ function acknowledgementId(namespace, sessionId) {
145
+ return `${namespace}\u0000${sessionId}`;
146
+ }
91
147
  function eventId(namespace, sessionId, sequence) {
92
148
  return `${namespace}\u0000${sessionId}\u0000${sequence
93
149
  .toString()
@@ -106,3 +162,11 @@ function transactionComplete(transaction) {
106
162
  transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction aborted."));
107
163
  });
108
164
  }
165
+ function validateTailArguments(afterSequence, limit) {
166
+ if (!Number.isInteger(afterSequence) ||
167
+ afterSequence < 0 ||
168
+ !Number.isInteger(limit) ||
169
+ limit <= 0) {
170
+ throw new Error("Invalid session event tail range.");
171
+ }
172
+ }
@@ -0,0 +1,30 @@
1
+ import type { SessionEvent, SessionStore } from "../types.js";
2
+ export interface CloudSessionStoreOptions {
3
+ local: SessionStore;
4
+ key: string;
5
+ endpoint?: string;
6
+ agentName: string;
7
+ }
8
+ /**
9
+ * A durable local-first outbox. Local appends never wait for cloud I/O; the
10
+ * persisted acknowledgement lets a new process recover unsent session tails.
11
+ */
12
+ export declare class CloudSessionStore implements SessionStore {
13
+ #private;
14
+ constructor(options: CloudSessionStoreOptions);
15
+ get cloudStoragePendingCount(): number;
16
+ get cloudStorageLastError(): Error | undefined;
17
+ read(sessionId: string): Promise<SessionEvent[]>;
18
+ append(sessionId: string, events: SessionEvent[]): Promise<void>;
19
+ refreshCloudSession(sessionId: string): Promise<void>;
20
+ listSessionIds(): Promise<string[]>;
21
+ subscribe(sessionId: string, listener: (events: SessionEvent[]) => void): () => void;
22
+ subscribeAll(listener: (sessionId: string, events: SessionEvent[]) => void): () => void;
23
+ describeLocation(sessionId: string): Promise<string>;
24
+ flushCloudStorage(options?: {
25
+ timeoutMs?: number;
26
+ }): Promise<void>;
27
+ closeCloudStorage(options?: {
28
+ timeoutMs?: number;
29
+ }): Promise<void>;
30
+ }