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
@@ -1,5 +1,8 @@
1
1
  import AsyncStorage from "@react-native-async-storage/async-storage";
2
2
  const writes = new Map();
3
+ const tailIndexes = new Map();
4
+ const TAIL_CHUNK_SIZE = 100;
5
+ let tailChunkGeneration = 0;
3
6
  export class ReactNativeJsonlSessionStore {
4
7
  #namespace;
5
8
  #listeners = new Map();
@@ -17,6 +20,33 @@ export class ReactNativeJsonlSessionStore {
17
20
  .filter(Boolean)
18
21
  .map((line) => JSON.parse(line));
19
22
  }
23
+ async readAfterSequence(sessionId, afterSequence, limit) {
24
+ if (!Number.isInteger(afterSequence) ||
25
+ afterSequence < 0 ||
26
+ !Number.isInteger(limit) ||
27
+ limit <= 0) {
28
+ throw new Error("Invalid session event tail range.");
29
+ }
30
+ await writes.get(this.#key(sessionId))?.catch(() => undefined);
31
+ const index = await this.#ensureTailIndex(sessionId);
32
+ const relevant = index.chunks.filter((chunk) => chunk.lastSequence > afterSequence);
33
+ const events = [];
34
+ for (const chunk of relevant) {
35
+ const contents = await AsyncStorage.getItem(chunk.key);
36
+ if (contents === null) {
37
+ tailIndexes.delete(this.#tailIndexKey(sessionId));
38
+ return this.#readTailFromCanonical(sessionId, afterSequence, limit);
39
+ }
40
+ const parsed = parseEvents(contents).slice(0, chunk.count);
41
+ for (const event of parsed) {
42
+ if (event.sequence > afterSequence)
43
+ events.push(event);
44
+ if (events.length === limit)
45
+ return events;
46
+ }
47
+ }
48
+ return events;
49
+ }
20
50
  async append(sessionId, events) {
21
51
  if (events.length === 0) {
22
52
  return;
@@ -24,9 +54,20 @@ export class ReactNativeJsonlSessionStore {
24
54
  const key = this.#key(sessionId);
25
55
  const previous = writes.get(key) ?? Promise.resolve();
26
56
  const write = previous.then(async () => {
57
+ const index = await this.#ensureTailIndex(sessionId);
58
+ await AsyncStorage.setItem(this.#tailPendingKey(sessionId), "1");
27
59
  const existing = await AsyncStorage.getItem(key);
28
60
  const appended = events.map((event) => JSON.stringify(event)).join("\n");
29
61
  await AsyncStorage.setItem(key, `${existing ? `${existing.replace(/\n*$/, "")}\n` : ""}${appended}\n`);
62
+ try {
63
+ await this.#appendTailIndex(sessionId, index, events);
64
+ await AsyncStorage.removeItem(this.#tailPendingKey(sessionId));
65
+ }
66
+ catch {
67
+ tailIndexes.delete(this.#tailIndexKey(sessionId));
68
+ // Canonical JSONL is already durable. A pending marker makes the
69
+ // auxiliary index rebuild on the next tail read.
70
+ }
30
71
  });
31
72
  writes.set(key, write);
32
73
  try {
@@ -47,6 +88,31 @@ export class ReactNativeJsonlSessionStore {
47
88
  .map((key) => key.slice(prefix.length))
48
89
  .sort();
49
90
  }
91
+ async getCloudAcknowledgement(sessionId) {
92
+ const value = Number(await AsyncStorage.getItem(this.#acknowledgementKey(sessionId)));
93
+ return Number.isInteger(value) && value >= 0 ? value : 0;
94
+ }
95
+ async setCloudAcknowledgement(sessionId, sequence) {
96
+ if (!Number.isInteger(sequence) || sequence < 0) {
97
+ throw new Error("Invalid cloud acknowledgement sequence.");
98
+ }
99
+ const key = this.#acknowledgementKey(sessionId);
100
+ const previous = writes.get(key) ?? Promise.resolve();
101
+ const write = previous.then(async () => {
102
+ const current = Number(await AsyncStorage.getItem(key));
103
+ if (!Number.isInteger(current) || current < sequence) {
104
+ await AsyncStorage.setItem(key, String(sequence));
105
+ }
106
+ });
107
+ writes.set(key, write);
108
+ try {
109
+ await write;
110
+ }
111
+ finally {
112
+ if (writes.get(key) === write)
113
+ writes.delete(key);
114
+ }
115
+ }
50
116
  subscribe(sessionId, listener) {
51
117
  const listeners = this.#listeners.get(sessionId) ?? new Set();
52
118
  listeners.add(listener);
@@ -68,4 +134,161 @@ export class ReactNativeJsonlSessionStore {
68
134
  #key(sessionId) {
69
135
  return `@orchajs:${this.#namespace}:${sessionId}`;
70
136
  }
137
+ #acknowledgementKey(sessionId) {
138
+ return `@orchajs-cloud-ack:${this.#namespace}:${sessionId}`;
139
+ }
140
+ #tailIndexKey(sessionId) {
141
+ return `@orchajs-tail-index:${this.#namespace}:${sessionId}`;
142
+ }
143
+ #tailPendingKey(sessionId) {
144
+ return `@orchajs-tail-pending:${this.#namespace}:${sessionId}`;
145
+ }
146
+ #tailChunkKey(sessionId) {
147
+ tailChunkGeneration += 1;
148
+ return `@orchajs-tail-chunk:${this.#namespace}:${sessionId}:${Date.now()}:${tailChunkGeneration}`;
149
+ }
150
+ async #ensureTailIndex(sessionId) {
151
+ const indexKey = this.#tailIndexKey(sessionId);
152
+ const pending = await AsyncStorage.getItem(this.#tailPendingKey(sessionId));
153
+ if (!pending) {
154
+ const cached = tailIndexes.get(indexKey);
155
+ if (cached)
156
+ return cached;
157
+ const stored = await AsyncStorage.getItem(indexKey);
158
+ if (stored) {
159
+ try {
160
+ const parsed = parseTailIndex(stored);
161
+ tailIndexes.set(indexKey, parsed);
162
+ return parsed;
163
+ }
164
+ catch {
165
+ // Rebuild invalid auxiliary data from canonical JSONL.
166
+ }
167
+ }
168
+ }
169
+ return this.#rebuildTailIndex(sessionId);
170
+ }
171
+ async #rebuildTailIndex(sessionId) {
172
+ const events = await this.read(sessionId);
173
+ const chunks = [];
174
+ const writes = [];
175
+ for (let start = 0; start < events.length; start += TAIL_CHUNK_SIZE) {
176
+ const chunkEvents = events.slice(start, start + TAIL_CHUNK_SIZE);
177
+ const key = this.#tailChunkKey(sessionId);
178
+ writes.push([key, serializeEvents(chunkEvents)]);
179
+ chunks.push(tailChunk(key, chunkEvents));
180
+ }
181
+ const index = {
182
+ version: 1,
183
+ eventCount: events.length,
184
+ chunks,
185
+ };
186
+ writes.push([this.#tailIndexKey(sessionId), JSON.stringify(index)]);
187
+ if (writes.length > 0)
188
+ await AsyncStorage.multiSet(writes);
189
+ await AsyncStorage.removeItem(this.#tailPendingKey(sessionId));
190
+ tailIndexes.set(this.#tailIndexKey(sessionId), index);
191
+ return index;
192
+ }
193
+ async #appendTailIndex(sessionId, current, events) {
194
+ const chunks = [...current.chunks];
195
+ const replacements = [];
196
+ const obsolete = [];
197
+ let remaining = [...events];
198
+ const last = chunks.at(-1);
199
+ if (last && last.count < TAIL_CHUNK_SIZE) {
200
+ const stored = await AsyncStorage.getItem(last.key);
201
+ if (stored === null)
202
+ throw new Error("Missing tail index chunk.");
203
+ const retained = parseEvents(stored).slice(0, last.count);
204
+ const added = remaining.splice(0, TAIL_CHUNK_SIZE - retained.length);
205
+ const combined = [...retained, ...added];
206
+ const key = this.#tailChunkKey(sessionId);
207
+ replacements.push([key, serializeEvents(combined)]);
208
+ chunks[chunks.length - 1] = tailChunk(key, combined);
209
+ obsolete.push(last.key);
210
+ }
211
+ while (remaining.length > 0) {
212
+ const chunkEvents = remaining.splice(0, TAIL_CHUNK_SIZE);
213
+ const key = this.#tailChunkKey(sessionId);
214
+ replacements.push([key, serializeEvents(chunkEvents)]);
215
+ chunks.push(tailChunk(key, chunkEvents));
216
+ }
217
+ const index = {
218
+ version: 1,
219
+ eventCount: current.eventCount + events.length,
220
+ chunks,
221
+ };
222
+ replacements.push([
223
+ this.#tailIndexKey(sessionId),
224
+ JSON.stringify(index),
225
+ ]);
226
+ await AsyncStorage.multiSet(replacements);
227
+ tailIndexes.set(this.#tailIndexKey(sessionId), index);
228
+ await Promise.all(obsolete.map((key) => AsyncStorage.removeItem(key)));
229
+ }
230
+ async #readTailFromCanonical(sessionId, afterSequence, limit) {
231
+ const index = await this.#rebuildTailIndex(sessionId);
232
+ const events = [];
233
+ for (const chunk of index.chunks) {
234
+ if (chunk.lastSequence <= afterSequence)
235
+ continue;
236
+ const contents = await AsyncStorage.getItem(chunk.key);
237
+ if (!contents)
238
+ continue;
239
+ for (const event of parseEvents(contents).slice(0, chunk.count)) {
240
+ if (event.sequence > afterSequence)
241
+ events.push(event);
242
+ if (events.length === limit)
243
+ return events;
244
+ }
245
+ }
246
+ return events;
247
+ }
248
+ }
249
+ function tailChunk(key, events) {
250
+ return {
251
+ key,
252
+ firstSequence: events[0].sequence,
253
+ lastSequence: events.at(-1).sequence,
254
+ count: events.length,
255
+ };
256
+ }
257
+ function serializeEvents(events) {
258
+ return `${events.map((event) => JSON.stringify(event)).join("\n")}\n`;
259
+ }
260
+ function parseEvents(contents) {
261
+ return contents
262
+ .split("\n")
263
+ .filter(Boolean)
264
+ .map((line) => JSON.parse(line));
265
+ }
266
+ function parseTailIndex(contents) {
267
+ const value = JSON.parse(contents);
268
+ if (value.version !== 1 ||
269
+ !Number.isInteger(value.eventCount) ||
270
+ (value.eventCount ?? -1) < 0 ||
271
+ !Array.isArray(value.chunks)) {
272
+ throw new Error("Invalid React Native tail index.");
273
+ }
274
+ let count = 0;
275
+ let previousSequence = 0;
276
+ for (const chunk of value.chunks) {
277
+ if (typeof chunk?.key !== "string" ||
278
+ !Number.isInteger(chunk.firstSequence) ||
279
+ !Number.isInteger(chunk.lastSequence) ||
280
+ !Number.isInteger(chunk.count) ||
281
+ chunk.count <= 0 ||
282
+ chunk.count > TAIL_CHUNK_SIZE ||
283
+ chunk.firstSequence <= previousSequence ||
284
+ chunk.lastSequence < chunk.firstSequence) {
285
+ throw new Error("Invalid React Native tail index.");
286
+ }
287
+ count += chunk.count;
288
+ previousSequence = chunk.lastSequence;
289
+ }
290
+ if (count !== value.eventCount) {
291
+ throw new Error("Invalid React Native tail index.");
292
+ }
293
+ return value;
71
294
  }
package/dist/testing.js CHANGED
@@ -347,6 +347,9 @@ async function runTestCase(agent, store, testCase, suiteId, projectRoot, warning
347
347
  toolResults.push({
348
348
  callId: call.callId,
349
349
  output: response.output,
350
+ ...(response.contents !== undefined
351
+ ? { contents: response.contents }
352
+ : {}),
350
353
  ...(response.isError === true ? { isError: true } : {}),
351
354
  });
352
355
  }
package/dist/types.d.ts CHANGED
@@ -46,7 +46,7 @@ export interface ProjectConfiguration {
46
46
  credentials?: Record<string, string | undefined>;
47
47
  };
48
48
  storage?: {
49
- strategy?: "node-jsonl" | "sqlite" | "indexeddb" | "react-native";
49
+ strategy?: "node-jsonl" | "sqlite" | "indexeddb" | "react-native" | "cloud";
50
50
  directory?: string;
51
51
  };
52
52
  }
@@ -61,13 +61,14 @@ export type AgentRegistration = string | {
61
61
  subagents?: Record<string, SubagentRegistration>;
62
62
  };
63
63
  export interface OrchaInitConfiguration {
64
- providers: ProviderInitConfigurations;
64
+ providers?: ProviderInitConfigurations;
65
65
  agents: Record<string, AgentRegistration>;
66
66
  /** Precompiled registry used by browser, React Native, and custom runtimes. */
67
67
  bundle?: CompiledBundle;
68
68
  amarsia?: {
69
69
  key: string;
70
70
  endpoint?: string;
71
+ inference?: boolean;
71
72
  };
72
73
  actions?: LocalActionRuntimeConfiguration;
73
74
  mcp?: ProjectConfiguration["mcp"];
@@ -388,12 +389,13 @@ export interface ClientToolCall {
388
389
  export interface ToolResult {
389
390
  callId: string;
390
391
  output: unknown;
392
+ contents?: AgentContentInput;
391
393
  isError?: boolean;
392
394
  }
393
395
  export interface ToolResumeInput {
394
396
  toolResults: ToolResult[];
395
397
  }
396
- export type ResumeInput = string | AgentContinueInput | ToolResumeInput;
398
+ export type ResumeInput = AgentContentInput | AgentContinueInput | ToolResumeInput;
397
399
  export type SessionEventType = "session.created" | "session.updated" | "run.started" | "message.created" | "action.requested" | "action.completed" | "action.failed" | "client_action.requested" | "client_action.resolved" | "skill.requested" | "skill.loaded" | "skill.failed" | "evaluation.requested" | "evaluation.completed" | "evaluation.failed" | "subagent.initiated" | "subagent.resumed" | "subagent.completed" | "subagent.paused" | "subagent.failed" | "run.paused" | "run.completed" | "run.failed" | "session.paused" | "session.resumed" | "test.warning" | "test.completed";
398
400
  export interface SessionEvent<TData = Record<string, unknown>> {
399
401
  sequence: number;
@@ -404,8 +406,26 @@ export interface SessionEvent<TData = Record<string, unknown>> {
404
406
  }
405
407
  export interface SessionStore {
406
408
  read(sessionId: string): Promise<SessionEvent[]>;
409
+ /** Reads a bounded contiguous local tail without materializing prior events. */
410
+ readAfterSequence?(sessionId: string, afterSequence: number, limit: number): Promise<SessionEvent[]>;
407
411
  append(sessionId: string, events: SessionEvent[]): Promise<void>;
408
412
  listSessionIds(): Promise<string[]>;
413
+ /** Durable cloud delivery checkpoint owned by the local store. */
414
+ getCloudAcknowledgement?(sessionId: string): Promise<number>;
415
+ /** Advances the durable cloud delivery checkpoint for a session. */
416
+ setCloudAcknowledgement?(sessionId: string, sequence: number): Promise<void>;
417
+ /** Number of sessions with local events not yet acknowledged by cloud. */
418
+ readonly cloudStoragePendingCount?: number | undefined;
419
+ /** Most recent background cloud delivery error. */
420
+ readonly cloudStorageLastError?: Error | undefined;
421
+ /** Explicitly reconciles a warm local session with cloud storage. */
422
+ refreshCloudSession?(sessionId: string): Promise<void>;
423
+ flushCloudStorage?(options?: {
424
+ timeoutMs?: number;
425
+ }): Promise<void>;
426
+ closeCloudStorage?(options?: {
427
+ timeoutMs?: number;
428
+ }): Promise<void>;
409
429
  subscribe?(sessionId: string, listener: (events: SessionEvent[]) => void): () => void;
410
430
  subscribeAll?(listener: (sessionId: string, events: SessionEvent[]) => void): () => void;
411
431
  describeLocation?(sessionId: string): Promise<string>;
@@ -487,7 +507,7 @@ export interface SessionUpdate {
487
507
  }
488
508
  export interface AgentRuntime {
489
509
  readonly clientTools: CompiledActionManifest[];
490
- run(input: AgentInput | string): Execution;
510
+ run(input: AgentInput | AgentContentInput): Execution;
491
511
  resume(sessionId: string, input?: ResumeInput): Execution;
492
512
  pause(sessionId: string): Promise<SessionSnapshot>;
493
513
  subagentHistory(childSessionId: string, options?: PaginationOptions): Promise<SessionHistory>;
@@ -500,6 +520,7 @@ export interface AgentRuntime {
500
520
  }
501
521
  export interface AgentTestActionResponse {
502
522
  output: unknown;
523
+ contents?: AgentContentInput;
503
524
  isError?: boolean;
504
525
  }
505
526
  export interface AgentTestActionConfiguration {
@@ -212,8 +212,20 @@ function withAmarsiaTelemetry(options) {
212
212
  const projections = /* @__PURE__ */ new Map();
213
213
  const pending = /* @__PURE__ */ new Map();
214
214
  return {
215
+ get cloudStoragePendingCount() {
216
+ return store.cloudStoragePendingCount;
217
+ },
218
+ get cloudStorageLastError() {
219
+ return store.cloudStorageLastError;
220
+ },
215
221
  read: (sessionId) => store.read(sessionId),
222
+ readAfterSequence: store.readAfterSequence?.bind(store),
216
223
  listSessionIds: () => store.listSessionIds(),
224
+ getCloudAcknowledgement: store.getCloudAcknowledgement?.bind(store),
225
+ setCloudAcknowledgement: store.setCloudAcknowledgement?.bind(store),
226
+ refreshCloudSession: store.refreshCloudSession?.bind(store),
227
+ flushCloudStorage: store.flushCloudStorage?.bind(store),
228
+ closeCloudStorage: store.closeCloudStorage?.bind(store),
217
229
  describeLocation: store.describeLocation?.bind(store),
218
230
  subscribe: store.subscribe?.bind(store),
219
231
  subscribeAll: store.subscribeAll?.bind(store),