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
@@ -26,6 +26,9 @@ module.exports = __toCommonJS(node_jsonl_exports);
26
26
  var import_fs = require("fs");
27
27
  var import_promises = require("fs/promises");
28
28
  var import_path = require("path");
29
+ var import_readline = require("readline");
30
+ const acknowledgementWrites = /* @__PURE__ */ new Map();
31
+ const TAIL_INDEX_STRIDE = 100;
29
32
  class NodeJsonlSessionStore {
30
33
  directory;
31
34
  #legacyDirectory;
@@ -35,6 +38,8 @@ class NodeJsonlSessionStore {
35
38
  #watchers = [];
36
39
  #watchTimers = /* @__PURE__ */ new Map();
37
40
  #observedSequences = /* @__PURE__ */ new Map();
41
+ #tailIndexes = /* @__PURE__ */ new Map();
42
+ #tailIndexLoads = /* @__PURE__ */ new Map();
38
43
  constructor(directory = ".orcha/sessions", projectRoot = process.cwd(), agent) {
39
44
  this.#legacyDirectory = (0, import_path.resolve)(projectRoot, directory);
40
45
  this.directory = (0, import_path.resolve)(
@@ -68,6 +73,42 @@ class NodeJsonlSessionStore {
68
73
  }
69
74
  });
70
75
  }
76
+ async readAfterSequence(sessionId, afterSequence, limit) {
77
+ validateTailArguments(afterSequence, limit);
78
+ const path = await this.#readSessionPath(sessionId);
79
+ if (!path) return [];
80
+ const index = await this.#getTailIndex(path, sessionId);
81
+ const start = checkpointOffset(index.checkpoints, afterSequence + 1);
82
+ const events = [];
83
+ const lines = (0, import_readline.createInterface)({
84
+ input: (0, import_fs.createReadStream)(path, { encoding: "utf8", start }),
85
+ crlfDelay: Infinity
86
+ });
87
+ let lineNumber = 0;
88
+ try {
89
+ for await (const line of lines) {
90
+ lineNumber += 1;
91
+ if (!line) continue;
92
+ let event;
93
+ try {
94
+ event = JSON.parse(line);
95
+ } catch (error) {
96
+ throw new Error(
97
+ `Corrupt JSONL event in session "${sessionId}" at line ${lineNumber}.`,
98
+ { cause: error }
99
+ );
100
+ }
101
+ if (event.sequence > afterSequence) events.push(event);
102
+ if (events.length >= limit) break;
103
+ }
104
+ return events;
105
+ } catch (error) {
106
+ if (isMissingFileError(error)) return [];
107
+ throw error;
108
+ } finally {
109
+ lines.close();
110
+ }
111
+ }
71
112
  async append(sessionId, events) {
72
113
  if (events.length === 0) {
73
114
  return;
@@ -76,9 +117,19 @@ class NodeJsonlSessionStore {
76
117
  const write = previous.then(async () => {
77
118
  const path = await this.#writeSessionPath(sessionId);
78
119
  await (0, import_promises.mkdir)((0, import_path.dirname)(path), { recursive: true });
79
- const lines = `${events.map((event) => JSON.stringify(event)).join("\n")}
80
- `;
81
- await (0, import_promises.appendFile)(path, lines, "utf8");
120
+ const startOffset = await fileSize(path);
121
+ const serialized = events.map((event) => `${JSON.stringify(event)}
122
+ `);
123
+ await (0, import_promises.appendFile)(path, serialized.join(""), "utf8");
124
+ const checkpoints = [];
125
+ let offset = startOffset;
126
+ for (const [index, event] of events.entries()) {
127
+ if ((event.sequence - 1) % TAIL_INDEX_STRIDE === 0) {
128
+ checkpoints.push({ sequence: event.sequence, offset });
129
+ }
130
+ offset += Buffer.byteLength(serialized[index], "utf8");
131
+ }
132
+ await this.#recordTailIndex(path, startOffset, offset, checkpoints);
82
133
  this.#notify(sessionId, events);
83
134
  });
84
135
  this.#queues.set(sessionId, write);
@@ -111,6 +162,41 @@ class NodeJsonlSessionStore {
111
162
  }
112
163
  return [...sessionIds].sort();
113
164
  }
165
+ async getCloudAcknowledgement(sessionId) {
166
+ const path = await this.#cloudAcknowledgementPath(sessionId);
167
+ if (!path) return 0;
168
+ try {
169
+ const value = Number(await (0, import_promises.readFile)(path, "utf8"));
170
+ return Number.isInteger(value) && value >= 0 ? value : 0;
171
+ } catch (error) {
172
+ if (isMissingFileError(error)) return 0;
173
+ throw error;
174
+ }
175
+ }
176
+ async setCloudAcknowledgement(sessionId, sequence) {
177
+ if (!Number.isInteger(sequence) || sequence < 0) {
178
+ throw new Error("Invalid cloud acknowledgement sequence.");
179
+ }
180
+ const sessionPath = await this.#writeSessionPath(sessionId);
181
+ const path = `${sessionPath}.cloud-ack`;
182
+ const previous = acknowledgementWrites.get(path) ?? Promise.resolve();
183
+ const write = previous.then(async () => {
184
+ const current = await this.getCloudAcknowledgement(sessionId);
185
+ if (sequence <= current) return;
186
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
187
+ await (0, import_promises.mkdir)((0, import_path.dirname)(path), { recursive: true });
188
+ await (0, import_promises.writeFile)(temporary, String(sequence), "utf8");
189
+ await (0, import_promises.rename)(temporary, path);
190
+ });
191
+ acknowledgementWrites.set(path, write);
192
+ try {
193
+ await write;
194
+ } finally {
195
+ if (acknowledgementWrites.get(path) === write) {
196
+ acknowledgementWrites.delete(path);
197
+ }
198
+ }
199
+ }
114
200
  async describeLocation(sessionId) {
115
201
  return await this.#readSessionPath(sessionId) ?? this.#sessionPath(this.directory, sessionId);
116
202
  }
@@ -237,6 +323,95 @@ class NodeJsonlSessionStore {
237
323
  async #writeSessionPath(sessionId) {
238
324
  return await this.#readSessionPath(sessionId) ?? this.#sessionPath(this.directory, sessionId);
239
325
  }
326
+ async #cloudAcknowledgementPath(sessionId) {
327
+ const current = `${this.#sessionPath(this.directory, sessionId)}.cloud-ack`;
328
+ if (await pathExists(current)) return current;
329
+ const legacy = `${this.#sessionPath(this.#legacyDirectory, sessionId)}.cloud-ack`;
330
+ return await pathExists(legacy) ? legacy : void 0;
331
+ }
332
+ async #getTailIndex(path, sessionId) {
333
+ const size = await fileSize(path);
334
+ const cached = this.#tailIndexes.get(path);
335
+ if (cached?.indexedSize === size) return cached;
336
+ const loading = this.#tailIndexLoads.get(path);
337
+ if (loading) return loading;
338
+ const load = this.#loadTailIndex(path, sessionId, size);
339
+ this.#tailIndexLoads.set(path, load);
340
+ try {
341
+ const index = await load;
342
+ this.#tailIndexes.set(path, index);
343
+ return index;
344
+ } finally {
345
+ if (this.#tailIndexLoads.get(path) === load) {
346
+ this.#tailIndexLoads.delete(path);
347
+ }
348
+ }
349
+ }
350
+ async #loadTailIndex(path, sessionId, size) {
351
+ try {
352
+ const source = await (0, import_promises.readFile)(tailIndexPath(path), "utf8");
353
+ const parsed = parseTailIndex(source);
354
+ if (parsed.indexedSize === size && (size === 0 || parsed.checkpoints[0]?.sequence === 1)) {
355
+ return parsed;
356
+ }
357
+ } catch (error) {
358
+ if (!isMissingFileError(error)) {
359
+ this.#tailIndexes.delete(path);
360
+ }
361
+ }
362
+ return this.#rebuildTailIndex(path, sessionId);
363
+ }
364
+ async #rebuildTailIndex(path, sessionId) {
365
+ const source = await (0, import_promises.readFile)(path);
366
+ const checkpoints = [];
367
+ let lineStart = 0;
368
+ let lineNumber = 0;
369
+ for (let cursor = 0; cursor <= source.length; cursor += 1) {
370
+ if (cursor < source.length && source[cursor] !== 10) continue;
371
+ const end = cursor > lineStart && source[cursor - 1] === 13 ? cursor - 1 : cursor;
372
+ if (end > lineStart) {
373
+ lineNumber += 1;
374
+ let event;
375
+ try {
376
+ event = JSON.parse(
377
+ source.subarray(lineStart, end).toString("utf8")
378
+ );
379
+ } catch (error) {
380
+ throw new Error(
381
+ `Corrupt JSONL event in session "${sessionId}" at line ${lineNumber}.`,
382
+ { cause: error }
383
+ );
384
+ }
385
+ if ((event.sequence - 1) % TAIL_INDEX_STRIDE === 0) {
386
+ checkpoints.push({ sequence: event.sequence, offset: lineStart });
387
+ }
388
+ }
389
+ lineStart = cursor + 1;
390
+ }
391
+ const index = { checkpoints, indexedSize: source.length };
392
+ await persistTailIndex(path, index);
393
+ return index;
394
+ }
395
+ async #recordTailIndex(path, previousSize, indexedSize, checkpoints) {
396
+ const cached = this.#tailIndexes.get(path);
397
+ if (cached?.indexedSize === previousSize) {
398
+ cached.checkpoints.push(...checkpoints);
399
+ cached.indexedSize = indexedSize;
400
+ } else {
401
+ this.#tailIndexes.delete(path);
402
+ }
403
+ try {
404
+ await (0, import_promises.appendFile)(
405
+ tailIndexPath(path),
406
+ `${checkpoints.map(({ sequence, offset }) => `${sequence} ${offset}
407
+ `).join("")}size ${indexedSize}
408
+ `,
409
+ "utf8"
410
+ );
411
+ } catch {
412
+ this.#tailIndexes.delete(path);
413
+ }
414
+ }
240
415
  #sessionPath(directory, sessionId) {
241
416
  if (!/^[A-Za-z0-9_:-]+$/.test(sessionId)) {
242
417
  throw new Error("Invalid session ID.");
@@ -267,9 +442,77 @@ async function pathExists(path) {
267
442
  throw error;
268
443
  }
269
444
  }
445
+ async function fileSize(path) {
446
+ try {
447
+ return (await (0, import_promises.stat)(path)).size;
448
+ } catch (error) {
449
+ if (isMissingFileError(error)) return 0;
450
+ throw error;
451
+ }
452
+ }
453
+ function tailIndexPath(path) {
454
+ return `${path}.tail-index`;
455
+ }
456
+ function parseTailIndex(source) {
457
+ const checkpoints = [];
458
+ let indexedSize = -1;
459
+ for (const line of source.split("\n")) {
460
+ if (!line) continue;
461
+ const [left, right] = line.split(" ");
462
+ const value = Number(right);
463
+ if (!Number.isSafeInteger(value) || value < 0) {
464
+ throw new Error("Invalid JSONL tail index.");
465
+ }
466
+ if (left === "size") {
467
+ indexedSize = value;
468
+ continue;
469
+ }
470
+ const sequence = Number(left);
471
+ const previous = checkpoints.at(-1);
472
+ if (!Number.isSafeInteger(sequence) || sequence <= 0 || previous !== void 0 && (sequence <= previous.sequence || value <= previous.offset)) {
473
+ throw new Error("Invalid JSONL tail index.");
474
+ }
475
+ checkpoints.push({ sequence, offset: value });
476
+ }
477
+ if (indexedSize < 0) throw new Error("Incomplete JSONL tail index.");
478
+ return { checkpoints, indexedSize };
479
+ }
480
+ async function persistTailIndex(path, index) {
481
+ const destination = tailIndexPath(path);
482
+ const temporary = `${destination}.${process.pid}.${Date.now()}.tmp`;
483
+ const source = `${index.checkpoints.map(({ sequence, offset }) => `${sequence} ${offset}
484
+ `).join("")}size ${index.indexedSize}
485
+ `;
486
+ try {
487
+ await (0, import_promises.writeFile)(temporary, source, "utf8");
488
+ await (0, import_promises.rename)(temporary, destination);
489
+ } catch {
490
+ }
491
+ }
492
+ function checkpointOffset(checkpoints, targetSequence) {
493
+ let low = 0;
494
+ let high = checkpoints.length - 1;
495
+ let offset = 0;
496
+ while (low <= high) {
497
+ const middle = Math.floor((low + high) / 2);
498
+ const checkpoint = checkpoints[middle];
499
+ if (checkpoint.sequence <= targetSequence) {
500
+ offset = checkpoint.offset;
501
+ low = middle + 1;
502
+ } else {
503
+ high = middle - 1;
504
+ }
505
+ }
506
+ return offset;
507
+ }
270
508
  function isMissingFileError(error) {
271
509
  return error instanceof Error && "code" in error && error.code === "ENOENT";
272
510
  }
511
+ function validateTailArguments(afterSequence, limit) {
512
+ if (!Number.isInteger(afterSequence) || afterSequence < 0 || !Number.isInteger(limit) || limit <= 0) {
513
+ throw new Error("Invalid session event tail range.");
514
+ }
515
+ }
273
516
  // Annotate the CommonJS export names for ESM import in node:
274
517
  0 && (module.exports = {
275
518
  NodeJsonlSessionStore,
@@ -49,24 +49,24 @@ class NodeSqliteSessionStore {
49
49
  where agent_name = ? and session_id = ?
50
50
  order by sequence asc
51
51
  `).all(this.agentName, sessionId);
52
- return rows.map((row) => {
53
- let data;
54
- try {
55
- data = JSON.parse(row.data);
56
- } catch (error) {
57
- throw new Error(
58
- `Corrupt SQLite event in session "${sessionId}" at sequence ${row.sequence}.`,
59
- { cause: error }
60
- );
61
- }
62
- return {
63
- sequence: row.sequence,
64
- type: row.type,
65
- timestamp: row.timestamp,
66
- ...row.run === null ? {} : { run: row.run },
67
- data
68
- };
69
- });
52
+ return rows.map((row) => eventFromRow(row, sessionId));
53
+ }
54
+ async readAfterSequence(sessionId, afterSequence, limit) {
55
+ validateSessionId(sessionId);
56
+ validateTailArguments(afterSequence, limit);
57
+ const rows = this.#database.prepare(`
58
+ select sequence, run, type, timestamp, data
59
+ from session_events
60
+ where agent_name = ? and session_id = ? and sequence > ?
61
+ order by sequence asc
62
+ limit ?
63
+ `).all(
64
+ this.agentName,
65
+ sessionId,
66
+ afterSequence,
67
+ limit
68
+ );
69
+ return rows.map((row) => eventFromRow(row, sessionId));
70
70
  }
71
71
  async append(sessionId, events) {
72
72
  validateSessionId(sessionId);
@@ -111,6 +111,27 @@ class NodeSqliteSessionStore {
111
111
  `).all(this.agentName);
112
112
  return rows.map((row) => row.session_id);
113
113
  }
114
+ async getCloudAcknowledgement(sessionId) {
115
+ validateSessionId(sessionId);
116
+ const rows = this.#database.prepare(`
117
+ select sequence
118
+ from cloud_acknowledgements
119
+ where agent_name = ? and session_id = ?
120
+ `).all(this.agentName, sessionId);
121
+ return rows[0]?.sequence ?? 0;
122
+ }
123
+ async setCloudAcknowledgement(sessionId, sequence) {
124
+ validateSessionId(sessionId);
125
+ if (!Number.isInteger(sequence) || sequence < 0) {
126
+ throw new Error("Invalid cloud acknowledgement sequence.");
127
+ }
128
+ this.#database.prepare(`
129
+ insert into cloud_acknowledgements (agent_name, session_id, sequence)
130
+ values (?, ?, ?)
131
+ on conflict(agent_name, session_id) do update set sequence = excluded.sequence
132
+ where excluded.sequence > cloud_acknowledgements.sequence
133
+ `).run(this.agentName, sessionId, sequence);
134
+ }
114
135
  subscribe(sessionId, listener) {
115
136
  validateSessionId(sessionId);
116
137
  const listeners = this.#listeners.get(sessionId) ?? /* @__PURE__ */ new Set();
@@ -164,7 +185,14 @@ function openDatabase(path) {
164
185
  primary key (agent_name, session_id, sequence)
165
186
  );
166
187
 
167
- pragma user_version = 1;
188
+ create table if not exists cloud_acknowledgements (
189
+ agent_name text not null,
190
+ session_id text not null,
191
+ sequence integer not null,
192
+ primary key (agent_name, session_id)
193
+ );
194
+
195
+ pragma user_version = 2;
168
196
  `);
169
197
  databases.set(path, database);
170
198
  return database;
@@ -185,6 +213,29 @@ function validateSessionId(sessionId) {
185
213
  throw new Error("Invalid session ID.");
186
214
  }
187
215
  }
216
+ function validateTailArguments(afterSequence, limit) {
217
+ if (!Number.isInteger(afterSequence) || afterSequence < 0 || !Number.isInteger(limit) || limit <= 0) {
218
+ throw new Error("Invalid session event tail range.");
219
+ }
220
+ }
221
+ function eventFromRow(row, sessionId) {
222
+ let data;
223
+ try {
224
+ data = JSON.parse(row.data);
225
+ } catch (error) {
226
+ throw new Error(
227
+ `Corrupt SQLite event in session "${sessionId}" at sequence ${row.sequence}.`,
228
+ { cause: error }
229
+ );
230
+ }
231
+ return {
232
+ sequence: row.sequence,
233
+ type: row.type,
234
+ timestamp: row.timestamp,
235
+ ...row.run === null ? {} : { run: row.run },
236
+ data
237
+ };
238
+ }
188
239
  function safelyNotify(notify) {
189
240
  try {
190
241
  notify();
@@ -34,6 +34,9 @@ __export(react_native_jsonl_exports, {
34
34
  module.exports = __toCommonJS(react_native_jsonl_exports);
35
35
  var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"), 1);
36
36
  const writes = /* @__PURE__ */ new Map();
37
+ const tailIndexes = /* @__PURE__ */ new Map();
38
+ const TAIL_CHUNK_SIZE = 100;
39
+ let tailChunkGeneration = 0;
37
40
  class ReactNativeJsonlSessionStore {
38
41
  #namespace;
39
42
  #listeners = /* @__PURE__ */ new Map();
@@ -48,6 +51,34 @@ class ReactNativeJsonlSessionStore {
48
51
  }
49
52
  return contents.split("\n").filter(Boolean).map((line) => JSON.parse(line));
50
53
  }
54
+ async readAfterSequence(sessionId, afterSequence, limit) {
55
+ if (!Number.isInteger(afterSequence) || afterSequence < 0 || !Number.isInteger(limit) || limit <= 0) {
56
+ throw new Error("Invalid session event tail range.");
57
+ }
58
+ await writes.get(this.#key(sessionId))?.catch(() => void 0);
59
+ const index = await this.#ensureTailIndex(sessionId);
60
+ const relevant = index.chunks.filter(
61
+ (chunk) => chunk.lastSequence > afterSequence
62
+ );
63
+ const events = [];
64
+ for (const chunk of relevant) {
65
+ const contents = await import_async_storage.default.getItem(chunk.key);
66
+ if (contents === null) {
67
+ tailIndexes.delete(this.#tailIndexKey(sessionId));
68
+ return this.#readTailFromCanonical(
69
+ sessionId,
70
+ afterSequence,
71
+ limit
72
+ );
73
+ }
74
+ const parsed = parseEvents(contents).slice(0, chunk.count);
75
+ for (const event of parsed) {
76
+ if (event.sequence > afterSequence) events.push(event);
77
+ if (events.length === limit) return events;
78
+ }
79
+ }
80
+ return events;
81
+ }
51
82
  async append(sessionId, events) {
52
83
  if (events.length === 0) {
53
84
  return;
@@ -55,6 +86,8 @@ class ReactNativeJsonlSessionStore {
55
86
  const key = this.#key(sessionId);
56
87
  const previous = writes.get(key) ?? Promise.resolve();
57
88
  const write = previous.then(async () => {
89
+ const index = await this.#ensureTailIndex(sessionId);
90
+ await import_async_storage.default.setItem(this.#tailPendingKey(sessionId), "1");
58
91
  const existing = await import_async_storage.default.getItem(key);
59
92
  const appended = events.map((event) => JSON.stringify(event)).join("\n");
60
93
  await import_async_storage.default.setItem(
@@ -63,6 +96,12 @@ class ReactNativeJsonlSessionStore {
63
96
  ` : ""}${appended}
64
97
  `
65
98
  );
99
+ try {
100
+ await this.#appendTailIndex(sessionId, index, events);
101
+ await import_async_storage.default.removeItem(this.#tailPendingKey(sessionId));
102
+ } catch {
103
+ tailIndexes.delete(this.#tailIndexKey(sessionId));
104
+ }
66
105
  });
67
106
  writes.set(key, write);
68
107
  try {
@@ -79,6 +118,31 @@ class ReactNativeJsonlSessionStore {
79
118
  const prefix = `@orchajs:${this.#namespace}:`;
80
119
  return (await import_async_storage.default.getAllKeys()).filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length)).sort();
81
120
  }
121
+ async getCloudAcknowledgement(sessionId) {
122
+ const value = Number(
123
+ await import_async_storage.default.getItem(this.#acknowledgementKey(sessionId))
124
+ );
125
+ return Number.isInteger(value) && value >= 0 ? value : 0;
126
+ }
127
+ async setCloudAcknowledgement(sessionId, sequence) {
128
+ if (!Number.isInteger(sequence) || sequence < 0) {
129
+ throw new Error("Invalid cloud acknowledgement sequence.");
130
+ }
131
+ const key = this.#acknowledgementKey(sessionId);
132
+ const previous = writes.get(key) ?? Promise.resolve();
133
+ const write = previous.then(async () => {
134
+ const current = Number(await import_async_storage.default.getItem(key));
135
+ if (!Number.isInteger(current) || current < sequence) {
136
+ await import_async_storage.default.setItem(key, String(sequence));
137
+ }
138
+ });
139
+ writes.set(key, write);
140
+ try {
141
+ await write;
142
+ } finally {
143
+ if (writes.get(key) === write) writes.delete(key);
144
+ }
145
+ }
82
146
  subscribe(sessionId, listener) {
83
147
  const listeners = this.#listeners.get(sessionId) ?? /* @__PURE__ */ new Set();
84
148
  listeners.add(listener);
@@ -100,6 +164,149 @@ class ReactNativeJsonlSessionStore {
100
164
  #key(sessionId) {
101
165
  return `@orchajs:${this.#namespace}:${sessionId}`;
102
166
  }
167
+ #acknowledgementKey(sessionId) {
168
+ return `@orchajs-cloud-ack:${this.#namespace}:${sessionId}`;
169
+ }
170
+ #tailIndexKey(sessionId) {
171
+ return `@orchajs-tail-index:${this.#namespace}:${sessionId}`;
172
+ }
173
+ #tailPendingKey(sessionId) {
174
+ return `@orchajs-tail-pending:${this.#namespace}:${sessionId}`;
175
+ }
176
+ #tailChunkKey(sessionId) {
177
+ tailChunkGeneration += 1;
178
+ return `@orchajs-tail-chunk:${this.#namespace}:${sessionId}:${Date.now()}:${tailChunkGeneration}`;
179
+ }
180
+ async #ensureTailIndex(sessionId) {
181
+ const indexKey = this.#tailIndexKey(sessionId);
182
+ const pending = await import_async_storage.default.getItem(
183
+ this.#tailPendingKey(sessionId)
184
+ );
185
+ if (!pending) {
186
+ const cached = tailIndexes.get(indexKey);
187
+ if (cached) return cached;
188
+ const stored = await import_async_storage.default.getItem(indexKey);
189
+ if (stored) {
190
+ try {
191
+ const parsed = parseTailIndex(stored);
192
+ tailIndexes.set(indexKey, parsed);
193
+ return parsed;
194
+ } catch {
195
+ }
196
+ }
197
+ }
198
+ return this.#rebuildTailIndex(sessionId);
199
+ }
200
+ async #rebuildTailIndex(sessionId) {
201
+ const events = await this.read(sessionId);
202
+ const chunks = [];
203
+ const writes2 = [];
204
+ for (let start = 0; start < events.length; start += TAIL_CHUNK_SIZE) {
205
+ const chunkEvents = events.slice(start, start + TAIL_CHUNK_SIZE);
206
+ const key = this.#tailChunkKey(sessionId);
207
+ writes2.push([key, serializeEvents(chunkEvents)]);
208
+ chunks.push(tailChunk(key, chunkEvents));
209
+ }
210
+ const index = {
211
+ version: 1,
212
+ eventCount: events.length,
213
+ chunks
214
+ };
215
+ writes2.push([this.#tailIndexKey(sessionId), JSON.stringify(index)]);
216
+ if (writes2.length > 0) await import_async_storage.default.multiSet(writes2);
217
+ await import_async_storage.default.removeItem(this.#tailPendingKey(sessionId));
218
+ tailIndexes.set(this.#tailIndexKey(sessionId), index);
219
+ return index;
220
+ }
221
+ async #appendTailIndex(sessionId, current, events) {
222
+ const chunks = [...current.chunks];
223
+ const replacements = [];
224
+ const obsolete = [];
225
+ let remaining = [...events];
226
+ const last = chunks.at(-1);
227
+ if (last && last.count < TAIL_CHUNK_SIZE) {
228
+ const stored = await import_async_storage.default.getItem(last.key);
229
+ if (stored === null) throw new Error("Missing tail index chunk.");
230
+ const retained = parseEvents(stored).slice(0, last.count);
231
+ const added = remaining.splice(
232
+ 0,
233
+ TAIL_CHUNK_SIZE - retained.length
234
+ );
235
+ const combined = [...retained, ...added];
236
+ const key = this.#tailChunkKey(sessionId);
237
+ replacements.push([key, serializeEvents(combined)]);
238
+ chunks[chunks.length - 1] = tailChunk(key, combined);
239
+ obsolete.push(last.key);
240
+ }
241
+ while (remaining.length > 0) {
242
+ const chunkEvents = remaining.splice(0, TAIL_CHUNK_SIZE);
243
+ const key = this.#tailChunkKey(sessionId);
244
+ replacements.push([key, serializeEvents(chunkEvents)]);
245
+ chunks.push(tailChunk(key, chunkEvents));
246
+ }
247
+ const index = {
248
+ version: 1,
249
+ eventCount: current.eventCount + events.length,
250
+ chunks
251
+ };
252
+ replacements.push([
253
+ this.#tailIndexKey(sessionId),
254
+ JSON.stringify(index)
255
+ ]);
256
+ await import_async_storage.default.multiSet(replacements);
257
+ tailIndexes.set(this.#tailIndexKey(sessionId), index);
258
+ await Promise.all(
259
+ obsolete.map((key) => import_async_storage.default.removeItem(key))
260
+ );
261
+ }
262
+ async #readTailFromCanonical(sessionId, afterSequence, limit) {
263
+ const index = await this.#rebuildTailIndex(sessionId);
264
+ const events = [];
265
+ for (const chunk of index.chunks) {
266
+ if (chunk.lastSequence <= afterSequence) continue;
267
+ const contents = await import_async_storage.default.getItem(chunk.key);
268
+ if (!contents) continue;
269
+ for (const event of parseEvents(contents).slice(0, chunk.count)) {
270
+ if (event.sequence > afterSequence) events.push(event);
271
+ if (events.length === limit) return events;
272
+ }
273
+ }
274
+ return events;
275
+ }
276
+ }
277
+ function tailChunk(key, events) {
278
+ return {
279
+ key,
280
+ firstSequence: events[0].sequence,
281
+ lastSequence: events.at(-1).sequence,
282
+ count: events.length
283
+ };
284
+ }
285
+ function serializeEvents(events) {
286
+ return `${events.map((event) => JSON.stringify(event)).join("\n")}
287
+ `;
288
+ }
289
+ function parseEvents(contents) {
290
+ return contents.split("\n").filter(Boolean).map((line) => JSON.parse(line));
291
+ }
292
+ function parseTailIndex(contents) {
293
+ const value = JSON.parse(contents);
294
+ if (value.version !== 1 || !Number.isInteger(value.eventCount) || (value.eventCount ?? -1) < 0 || !Array.isArray(value.chunks)) {
295
+ throw new Error("Invalid React Native tail index.");
296
+ }
297
+ let count = 0;
298
+ let previousSequence = 0;
299
+ for (const chunk of value.chunks) {
300
+ if (typeof chunk?.key !== "string" || !Number.isInteger(chunk.firstSequence) || !Number.isInteger(chunk.lastSequence) || !Number.isInteger(chunk.count) || chunk.count <= 0 || chunk.count > TAIL_CHUNK_SIZE || chunk.firstSequence <= previousSequence || chunk.lastSequence < chunk.firstSequence) {
301
+ throw new Error("Invalid React Native tail index.");
302
+ }
303
+ count += chunk.count;
304
+ previousSequence = chunk.lastSequence;
305
+ }
306
+ if (count !== value.eventCount) {
307
+ throw new Error("Invalid React Native tail index.");
308
+ }
309
+ return value;
103
310
  }
104
311
  // Annotate the CommonJS export names for ESM import in node:
105
312
  0 && (module.exports = {
@@ -453,6 +453,7 @@ async function runTestCase(agent, store, testCase, suiteId, projectRoot, warning
453
453
  toolResults.push({
454
454
  callId: call.callId,
455
455
  output: response.output,
456
+ ...response.contents !== void 0 ? { contents: response.contents } : {},
456
457
  ...response.isError === true ? { isError: true } : {}
457
458
  });
458
459
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orchajs",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "description": "A filesystem-convention, stateful agent framework for JavaScript.",
5
5
  "license": "MIT",
6
6
  "repository": {