actorctl 0.1.2 → 0.2.0-rc.3

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.
@@ -62,9 +62,9 @@ var boundAiGateway = (accountId, binding) => Layer2.succeed(AiGateway, AiGateway
62
62
  }));
63
63
 
64
64
  // ../../src/platform/cloudflare/runtime.ts
65
- import { Effect as Effect16 } from "effect";
65
+ import { Effect as Effect17 } from "effect";
66
66
 
67
- // ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteClient.js
67
+ // ../../node_modules/.bun/@effect+sql-sqlite-do@4.1.2+edf248c88a527e3e/node_modules/@effect/sql-sqlite-do/dist/SqliteClient.js
68
68
  var SqliteClient_exports = {};
69
69
  __export(SqliteClient_exports, {
70
70
  SqliteClient: () => SqliteClient,
@@ -78,17 +78,16 @@ import * as Config from "effect/Config";
78
78
  import * as Context3 from "effect/Context";
79
79
  import * as Effect5 from "effect/Effect";
80
80
  import * as Exit from "effect/Exit";
81
- import * as Fiber from "effect/Fiber";
82
81
  import { identity } from "effect/Function";
83
82
  import * as Layer3 from "effect/Layer";
83
+ import * as Reactivity from "effect/reactivity/Reactivity";
84
84
  import * as Rec from "effect/Record";
85
- import * as Scope from "effect/Scope";
85
+ import * as Scheduler from "effect/Scheduler";
86
86
  import * as Semaphore from "effect/Semaphore";
87
+ import * as Client from "effect/sql/SqlClient";
88
+ import { classifySqliteError, SqlError, UnknownError } from "effect/sql/SqlError";
89
+ import * as Statement from "effect/sql/Statement";
87
90
  import * as Stream from "effect/Stream";
88
- import * as Reactivity from "effect/unstable/reactivity/Reactivity";
89
- import * as Client from "effect/unstable/sql/SqlClient";
90
- import { classifySqliteError, SqlError, UnknownError } from "effect/unstable/sql/SqlError";
91
- import * as Statement from "effect/unstable/sql/Statement";
92
91
  var ATTR_DB_SYSTEM_NAME = "db.system.name";
93
92
  var classifyError = (cause, message, operation) => classifySqliteError(cause, {
94
93
  message,
@@ -105,33 +104,55 @@ var unsupportedTransaction = (message, operation) => new SqlError({
105
104
  })
106
105
  });
107
106
  var makeUnsupportedWithTransaction = (message) => (_effect) => Effect5.fail(unsupportedTransaction(message, "transaction"));
108
- var makeStorageBackedWithTransaction = (storage, connection, semaphore) => (effect) => Effect5.withFiber((fiber) => {
109
- const services = fiber.context;
110
- const connOption = Context3.getOption(services, SqliteTransaction);
111
- if (connOption._tag === "Some") {
112
- return Effect5.fail(unsupportedTransaction("Nested transactions are not supported by Cloudflare Durable Object SQLite storage", "transaction"));
113
- }
114
- const effectWithTxn = Effect5.provideContext(effect, Context3.add(services, SqliteTransaction, [connection, 0]));
115
- return semaphore.withPermits(1)(Effect5.callback((resume) => {
116
- let interrupted = false;
117
- const promise2 = storage.transaction((txn) => new Promise((resolve) => {
118
- if (interrupted) return resolve();
119
- resume(Effect5.onExit(effectWithTxn, (exit) => {
120
- if (Exit.isFailure(exit)) {
121
- txn.rollback();
122
- }
123
- resolve();
124
- return Effect5.promise(() => promise2);
107
+ var makeStorageBackedWithTransaction = (storage, connection, acquirer, spanAttributes) => {
108
+ const levels = [];
109
+ const open = (id) => Effect5.callback((resume) => {
110
+ const done = storage.transaction((txn) => new Promise((resolve) => {
111
+ resume(Effect5.sync(() => {
112
+ levels[id] = {
113
+ txn,
114
+ resolve,
115
+ done
116
+ };
125
117
  }));
126
- })).catch((cause) => resume(Effect5.fail(new SqlError({
127
- reason: classifyError(cause, "Failed transaction", "transaction")
128
- }))));
129
- return Effect5.suspend(() => {
130
- interrupted = true;
131
- return Effect5.promise(() => promise2);
118
+ })).then(() => Exit.void, (cause) => {
119
+ const exit = Exit.fail(new SqlError({
120
+ reason: classifyError(cause, "Failed transaction", "transaction")
121
+ }));
122
+ resume(exit);
123
+ return exit;
132
124
  });
133
- }));
134
- });
125
+ });
126
+ const close = (id) => Effect5.suspend(() => {
127
+ const level = levels[id];
128
+ levels.length = id;
129
+ level.resolve();
130
+ return Effect5.flatten(Effect5.promise(() => level.done));
131
+ });
132
+ const rollback = (id) => Effect5.sync(() => levels[id].txn.rollback());
133
+ const withTransaction = Client.makeWithTransaction({
134
+ transactionService: SqliteTransaction,
135
+ spanAttributes,
136
+ acquireConnection: (restore) => restore(acquirer),
137
+ begin: () => open(0),
138
+ savepoint: (_, id) => open(id),
139
+ releaseSavepoint: (_, id) => close(id),
140
+ commit: () => close(0),
141
+ rollback: () => Effect5.andThen(rollback(0), close(0)),
142
+ // `releaseSavepoint` runs next and closes the level.
143
+ rollbackSavepoint: (_, id) => rollback(id)
144
+ });
145
+ return (effect) => Effect5.withFiber((fiber) => {
146
+ const conn = Context3.getOrUndefined(fiber.context, SqliteTransaction);
147
+ if (conn !== void 0 && conn[0] !== connection) {
148
+ return Effect5.fail(unsupportedTransaction("Transactions cannot use a connection from a different SQLite client", "transaction"));
149
+ }
150
+ return withTransaction(effect);
151
+ }).pipe(
152
+ // The storage transaction closes the input gate, blocking dispatcher tasks until it completes.
153
+ Effect5.provideService(Scheduler.PreventSchedulerYield, true)
154
+ );
155
+ };
135
156
  var make4 = (options) => Effect5.gen(function* () {
136
157
  const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
137
158
  const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : void 0;
@@ -201,50 +222,53 @@ var make4 = (options) => Effect5.gen(function* () {
201
222
  });
202
223
  const semaphore = yield* Semaphore.make(1);
203
224
  const connection = yield* makeConnection;
204
- const acquirer = semaphore.withPermits(1)(Effect5.succeed(connection));
205
- const transactionAcquirer = Effect5.uninterruptibleMask((restore) => {
206
- const fiber = Fiber.getCurrent();
207
- const scope = Context3.getUnsafe(fiber.context, Scope.Scope);
208
- return Effect5.as(Effect5.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), connection);
209
- });
225
+ const acquirer = Effect5.as(Effect5.acquireRelease(semaphore.take(1), () => semaphore.release(1), {
226
+ interruptible: true
227
+ }), connection);
228
+ const spanAttributes = [...options.spanAttributes ? Object.entries(options.spanAttributes) : [], [ATTR_DB_SYSTEM_NAME, "sqlite"]];
210
229
  const client = yield* Client.make({
230
+ driver: "sqlite-do",
211
231
  acquirer,
232
+ borrower: (f) => semaphore.withPermit(f(connection)),
212
233
  compiler,
213
- transactionAcquirer,
214
234
  transactionService: SqliteTransaction,
215
- spanAttributes: [...options.spanAttributes ? Object.entries(options.spanAttributes) : [], [ATTR_DB_SYSTEM_NAME, "sqlite"]],
235
+ spanAttributes,
216
236
  transformRows
217
237
  });
218
238
  return Object.assign(client, {
219
239
  [TypeId]: TypeId,
220
240
  config: options,
221
- withTransaction: options.storage ? makeStorageBackedWithTransaction(options.storage, connection, semaphore) : makeUnsupportedWithTransaction("Transactions require Durable Object storage; pass ctx.storage as the storage option")
241
+ withTransaction: options.storage ? makeStorageBackedWithTransaction(options.storage, connection, acquirer, spanAttributes) : makeUnsupportedWithTransaction("Transactions require Durable Object storage; pass ctx.storage as the storage option")
222
242
  });
223
243
  });
224
244
  var layerConfig = (config) => Layer3.effectContext(Config.unwrap(config).pipe(Effect5.flatMap(make4), Effect5.map((client) => Context3.make(SqliteClient, client).pipe(Context3.add(Client.SqlClient, client))))).pipe(Layer3.provide(Reactivity.layer));
225
245
  var layer2 = (config) => Layer3.effectContext(Effect5.map(make4(config), (client) => Context3.make(SqliteClient, client).pipe(Context3.add(Client.SqlClient, client)))).pipe(Layer3.provide(Reactivity.layer));
226
246
 
227
- // ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteMigrator.js
247
+ // ../../node_modules/.bun/@effect+sql-sqlite-do@4.1.2+edf248c88a527e3e/node_modules/@effect/sql-sqlite-do/dist/SqliteMigrator.js
228
248
  var SqliteMigrator_exports = {};
229
249
  __export(SqliteMigrator_exports, {
250
+ fromFileSystem: () => fromFileSystem,
230
251
  layer: () => layer3,
231
252
  run: () => run
232
253
  });
233
254
  __reExport(SqliteMigrator_exports, Migrator_star);
234
255
  import * as Layer4 from "effect/Layer";
235
- import * as Migrator from "effect/unstable/sql/Migrator";
236
- import * as Migrator_star from "effect/unstable/sql/Migrator";
256
+ import * as Migrator from "effect/sql/Migrator";
257
+ import * as Migrator_star from "effect/sql/Migrator";
258
+ import {
259
+ fromFileSystem
260
+ } from "effect/sql/MigratorFileSystem";
237
261
  var run = /* @__PURE__ */ Migrator.make({});
238
262
  var layer3 = (options) => Layer4.effectDiscard(run(options));
239
263
 
240
264
  // ../../src/platform/cloudflare/runtime.ts
241
- import { cloudflareHandler } from "tardie/experimental/cloudflare";
265
+ import { HttpRouter as HttpRouter2 } from "effect/http";
266
+ import { hostRoutes } from "tardie/platform/http";
242
267
 
243
268
  // ../../src/platform/exporting-host.ts
244
- import { Context as Context6, Effect as Effect10, Fiber as Fiber2, Layer as Layer7, ManagedRuntime, Queue, Semaphore as Semaphore3, Schema as Schema2 } from "effect";
245
- import { SqlClient as SqlClient3 } from "effect/unstable/sql";
246
- import { createThreadHost, InvalidMessage, MessageConflict } from "tardie/experimental";
247
- import { sqlJournal } from "tardie/experimental/cloudflare";
269
+ import { Context as Context6, Effect as Effect11, Fiber, Layer as Layer7, ManagedRuntime, Queue, Semaphore as Semaphore3, Schema as Schema3 } from "effect";
270
+ import { SqlClient as SqlClient3 } from "effect/sql";
271
+ import { createThreadHost, InitialState, InvalidMessage as InvalidMessage2, MessageConflict as MessageConflict2 } from "tardie/core";
248
272
 
249
273
  // ../../src/services/event-exporter.ts
250
274
  import { Context as Context4, Data as Data3 } from "effect";
@@ -255,7 +279,7 @@ var EventExporter = class extends Context4.Service()("tardigrade-cloud/EventExpo
255
279
 
256
280
  // ../../src/platform/export-source.ts
257
281
  import { Effect as Effect7 } from "effect";
258
- import { SqlClient as SqlClient2 } from "effect/unstable/sql";
282
+ import { SqlClient as SqlClient2 } from "effect/sql";
259
283
  var journalExportSource = (options) => Effect7.gen(function* () {
260
284
  if (!options.journal || !options.cursorKey) return yield* new ExportError({ operation: "config", message: "Journal and destination cursor key are required." });
261
285
  const sql = yield* SqlClient2.SqlClient;
@@ -333,15 +357,15 @@ var sqlEventExporter = (options) => Layer5.unwrap(Effect8.gen(function* () {
333
357
 
334
358
  // ../../src/platform/actor-mcp.ts
335
359
  import { Context as Context5, Effect as Effect9, Layer as Layer6, Schema } from "effect";
336
- import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
337
- import { HttpRouter } from "effect/unstable/http";
360
+ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/ai";
361
+ import { HttpRouter } from "effect/http";
338
362
  var ACTOR_MCP_PROTOCOLS = [McpProtocol.v2025_11_25, McpProtocol.v2025_06_18];
339
363
  var identity2 = { thread: Schema.NonEmptyString, id: Schema.NonEmptyString };
340
364
  var receipt = Schema.Struct({ id: Schema.String, position: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))) });
341
365
  function actorMcp(host, instance, options = {}) {
342
366
  const path = `/v1/actors/${encodeURIComponent(instance)}/mcp`;
343
367
  let app;
344
- const open = () => app ??= Effect9.runPromise(host.describe(instance)).then((contracts) => {
368
+ const open = () => app ??= Effect9.runPromise(host.methodContracts({ instance })).then((contracts) => {
345
369
  const register = Layer6.effectDiscard(Effect9.gen(function* () {
346
370
  const server = yield* McpServer.McpServer;
347
371
  const add2 = (name, description, input, output, run2) => server.addTool({
@@ -370,14 +394,22 @@ function actorMcp(host, instance, options = {}) {
370
394
  "Read a call's current status and final result.",
371
395
  Schema.Struct(identity2),
372
396
  Schema.Struct({ id: Schema.String, method: Schema.String, status: Schema.String, output: Schema.optionalKey(Schema.Json), error: Schema.optionalKey(Schema.String), reason: Schema.optionalKey(Schema.String) }),
373
- (input) => thread(input.thread).pipe(Effect9.flatMap((current) => current.call(input.id)), Effect9.flatMap((value) => value ? Effect9.succeed(value) : Effect9.fail(new Error("Unknown call"))))
397
+ (input) => thread(input.thread).pipe(Effect9.flatMap((current) => Effect9.gen(function* () {
398
+ const records = yield* current.records();
399
+ const invocation = records.find((record) => record.message?.id === input.id)?.message?.invocation;
400
+ return invocation ? { id: input.id, method: invocation.method, ...yield* current.methodState(invocation.method, input.id) } : void 0;
401
+ })), Effect9.flatMap((value) => value ? Effect9.succeed(value) : Effect9.fail(new Error("Unknown call"))))
374
402
  );
375
403
  yield* add2(
376
404
  "call_cancel",
377
405
  "Request cancellation of an accepted call. Returns acceptance, not cancellation completion.",
378
406
  Schema.Struct({ ...identity2, reason: Schema.String }),
379
407
  receipt,
380
- (input) => thread(input.thread).pipe(Effect9.flatMap((current) => current.call(input.id).pipe(Effect9.flatMap((call) => call ? current.cancel(call.method, input.id, input.reason) : Effect9.fail(new Error("Unknown call"))))))
408
+ (input) => thread(input.thread).pipe(Effect9.flatMap((current) => Effect9.gen(function* () {
409
+ const records = yield* current.records();
410
+ const invocation = records.find((record) => record.message?.id === input.id)?.message?.invocation;
411
+ return invocation ? { id: input.id, method: invocation.method, ...yield* current.methodState(invocation.method, input.id) } : void 0;
412
+ }).pipe(Effect9.flatMap((call) => call ? current.cancel(call.method, input.id, input.reason) : Effect9.fail(new Error("Unknown call"))))))
381
413
  );
382
414
  })).pipe(Layer6.provide(McpServer.layerHttp({ name: host.actor, version: "1.0.0", path, protocols: ACTOR_MCP_PROTOCOLS, ...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {} })));
383
415
  return HttpRouter.toWebHandler(register, { disableLogger: true });
@@ -393,8 +425,95 @@ function actorMcp(host, instance, options = {}) {
393
425
  };
394
426
  }
395
427
 
428
+ // src/worker/webhooks.ts
429
+ import { Effect as Effect10, Schema as Schema2 } from "effect";
430
+ import { InvalidMessage, MessageConflict } from "tardie/core";
431
+ var REPLY_TO_HEADER = "x-tardigrade-reply-to";
432
+ var WEBHOOK_TRANSPORT = "tardigrade.webhook";
433
+ var REPLY_ACCEPTED = "accepted";
434
+ var CallMetadata = Schema2.Record(Schema2.String, Schema2.String.check(Schema2.isMaxLength(512))).check(
435
+ Schema2.makeFilter((value) => Object.keys(value).length <= 16 && Object.keys(value).every((key) => key.length <= 64) || "Metadata accepts at most 16 pairs with keys up to 64 characters.")
436
+ );
437
+ var ReplyAddress = Schema2.Struct({
438
+ webhook: Schema2.NonEmptyString,
439
+ account: Schema2.NonEmptyString,
440
+ actor: Schema2.NonEmptyString,
441
+ thread: Schema2.NonEmptyString,
442
+ method: Schema2.NonEmptyString,
443
+ id: Schema2.NonEmptyString,
444
+ metadata: CallMetadata,
445
+ url: Schema2.String
446
+ });
447
+ var webhookTransport = (binding) => ({
448
+ deliver: (address, body, metadata) => Effect10.tryPromise({
449
+ try: async () => {
450
+ const reply = Schema2.decodeUnknownSync(ReplyAddress, { onExcessProperty: "error" })(address);
451
+ if (!binding) throw new Error("WEBHOOKS binding is required");
452
+ if (metadata.inReplyTo !== reply.id) throw new Error("Webhook reply identifies a different invocation");
453
+ await binding.enqueueReply(reply, body, metadata.inReplyTo);
454
+ return { id: metadata.id };
455
+ },
456
+ catch: (cause) => cause instanceof Error ? cause : new Error(String(cause))
457
+ })
458
+ });
459
+ async function receiveWebhookRequest(request, options) {
460
+ try {
461
+ const path = new URL(request.url).pathname;
462
+ const invoke = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/methods\/([^/]+)$/.exec(path);
463
+ if (request.method === "POST" && invoke && request.headers.has(REPLY_TO_HEADER)) {
464
+ const instance = decodeURIComponent(invoke[1]), thread = decodeURIComponent(invoke[2]), method = decodeURIComponent(invoke[3]);
465
+ const id = request.headers.get("idempotency-key");
466
+ let address;
467
+ try {
468
+ address = Schema2.decodeUnknownSync(ReplyAddress, { onExcessProperty: "error" })(JSON.parse(request.headers.get(REPLY_TO_HEADER)));
469
+ if (!id?.trim() || address.id !== id || address.account !== instance || address.actor !== options.actor || address.thread !== thread || address.method !== method) throw new Error("Reply identity mismatch");
470
+ } catch {
471
+ return Response.json({ code: "invalid_message", message: "Invalid webhook reply address" }, { status: 400 });
472
+ }
473
+ const input = await request.json();
474
+ const receipt2 = await options.receive({ target: { actor: options.actor, instance, thread }, body: { method, input }, message: { id, from: { transport: WEBHOOK_TRANSPORT, address } } });
475
+ return Response.json(receipt2, { status: 202, headers: { [REPLY_TO_HEADER]: REPLY_ACCEPTED } });
476
+ }
477
+ const generic = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/calls\/([^/]+)(\/cancel)?$/.exec(path);
478
+ if (generic && (request.method === "GET" && !generic[4] || request.method === "POST" && generic[4])) {
479
+ const instance = decodeURIComponent(generic[1]), thread = decodeURIComponent(generic[2]), id = decodeURIComponent(generic[3]);
480
+ const call = await options.lookup(instance, thread, id);
481
+ if (!call) return new Response(null, { status: 404 });
482
+ if (request.method === "GET") return Response.json({ id, method: call.method, ...call.state });
483
+ let reason;
484
+ try {
485
+ reason = Schema2.decodeUnknownSync(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(await request.json()).reason;
486
+ } catch {
487
+ return Response.json({ code: "invalid_message", message: "A cancellation reason is required" }, { status: 400 });
488
+ }
489
+ await options.receive({ target: { actor: options.actor, instance, thread }, body: { method: call.method, cancel: { id, reason } }, message: { id: JSON.stringify(["cancel", call.method, id]), from: call.from } });
490
+ return Response.json({ id }, { status: 202 });
491
+ }
492
+ const cancel = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/methods\/([^/]+)\/calls\/([^/]+)\/cancellation$/.exec(path);
493
+ if (request.method === "PUT" && cancel) {
494
+ const instance = decodeURIComponent(cancel[1]), thread = decodeURIComponent(cancel[2]), method = decodeURIComponent(cancel[3]), id = decodeURIComponent(cancel[4]);
495
+ const call = await options.lookup(instance, thread, id), from = call?.from;
496
+ if (call?.method !== method || !from || !("transport" in from) || from.transport !== WEBHOOK_TRANSPORT) return void 0;
497
+ let reason;
498
+ try {
499
+ reason = Schema2.decodeUnknownSync(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(await request.json()).reason;
500
+ } catch {
501
+ return Response.json({ code: "invalid_message", message: "A cancellation reason is required" }, { status: 400 });
502
+ }
503
+ await options.receive({ target: { actor: options.actor, instance, thread }, body: { method, cancel: { id, reason } }, message: { id: JSON.stringify(["cancel", method, id]), from } });
504
+ return Response.json({ id, method, thread, status: "requested" }, { status: 202 });
505
+ }
506
+ return void 0;
507
+ } catch (error) {
508
+ if (error instanceof InvalidMessage || error instanceof SyntaxError || error instanceof MessageConflict) {
509
+ return Response.json({ code: error instanceof MessageConflict ? "conflict" : "invalid_message", message: error.message }, { status: error instanceof MessageConflict ? 409 : 400 });
510
+ }
511
+ throw error;
512
+ }
513
+ }
514
+
396
515
  // ../../src/platform/exporting-host.ts
397
- import { Tool as Tool2 } from "effect/unstable/ai";
516
+ import { Tool as Tool2 } from "effect/ai";
398
517
  var DEFAULT_EXPORT_FLUSH_TIMEOUT_MS = 3e4;
399
518
  var isThreadEventJournal = (value, actor, account) => {
400
519
  try {
@@ -411,13 +530,13 @@ async function createSqlExportingHost(options) {
411
530
  const runtime = ManagedRuntime.make(options.sql);
412
531
  const connections = /* @__PURE__ */ new Set();
413
532
  try {
414
- const state = await runtime.runPromise(Effect10.gen(function* () {
533
+ const state = await runtime.runPromise(Effect11.gen(function* () {
415
534
  const sql = yield* SqlClient3.SqlClient;
416
535
  yield* sql`CREATE TABLE IF NOT EXISTS event_export_identity (id INTEGER PRIMARY KEY CHECK (id = 1), account TEXT NOT NULL, actor TEXT NOT NULL, generation TEXT NOT NULL)`;
417
536
  yield* sql`INSERT INTO event_export_identity VALUES (1, ${options.accountId}, ${options.actor.actorName}, ${crypto.randomUUID()}) ON CONFLICT (id) DO NOTHING`;
418
537
  const rows = yield* sql`SELECT account, actor, generation FROM event_export_identity WHERE id = 1`;
419
538
  const identity3 = rows[0];
420
- if (identity3.account !== options.accountId || identity3.actor !== options.actor.actorName) return yield* Effect10.fail(new Error("Journal database belongs to a different account or actor."));
539
+ if (identity3.account !== options.accountId || identity3.actor !== options.actor.actorName) return yield* Effect11.fail(new Error("Journal database belongs to a different account or actor."));
421
540
  const signals = yield* Queue.make({ capacity: 1, strategy: "sliding" });
422
541
  const lock = yield* Semaphore3.make(1);
423
542
  return { sql, identity: identity3, signals, lock };
@@ -428,17 +547,17 @@ async function createSqlExportingHost(options) {
428
547
  };
429
548
  const journal = (parts, exportEvents = false) => {
430
549
  const key = JSON.stringify(parts);
431
- const opened = sqlJournal({ actor: key, layer: Layer7.succeed(SqlClient3.SqlClient, state.sql) });
432
- connections.add(opened.close);
433
- const afterCommit = Effect10.gen(function* () {
434
- if (options.sync) yield* Effect10.tryPromise(() => options.sync());
435
- if (exportEvents) signal();
550
+ const opened = options.journalFactory({
551
+ actor: key,
552
+ layer: Layer7.succeed(SqlClient3.SqlClient, state.sql),
553
+ ...options.transaction ? { transaction: options.transaction } : {},
554
+ flush: Effect11.gen(function* () {
555
+ if (options.sync) yield* Effect11.tryPromise({ try: () => options.sync(), catch: (error) => error instanceof Error ? error : new Error(String(error)) });
556
+ if (exportEvents) signal();
557
+ })
436
558
  });
437
- return {
438
- ...opened,
439
- append: (...args) => opened.append(...args).pipe(Effect10.andThen(afterCommit)),
440
- appendWithCheckpoint: (...args) => opened.appendWithCheckpoint(...args).pipe(Effect10.andThen(afterCommit))
441
- };
559
+ connections.add(opened.close);
560
+ return opened;
442
561
  };
443
562
  const checkAccount = (instance) => {
444
563
  if (instance !== options.accountId) throw new Error("Actor instance does not match its account.");
@@ -452,26 +571,26 @@ async function createSqlExportingHost(options) {
452
571
  checkAccount(coordinate.instance);
453
572
  return journal([coordinate.actor, coordinate.instance, "thread", coordinate.thread, "events"], true);
454
573
  },
455
- close: Effect10.gen(function* () {
574
+ close: Effect11.gen(function* () {
456
575
  for (const close of connections) yield* close;
457
576
  connections.clear();
458
577
  })
459
578
  };
460
579
  const allocations = Semaphore3.makeUnsafe(1);
461
580
  const host = createThreadHost({ ...options, services: (coordinate, current) => options.services(coordinate, current).pipe(Layer7.provideMerge(Layer7.succeed(SqlClient3.SqlClient, state.sql))), storage, actorContext: options.actorContext ?? ((context) => context) });
462
- const bootstrap = sqlJournal({ actor: "bootstrap", layer: Layer7.succeed(SqlClient3.SqlClient, state.sql) });
463
- await Effect10.runPromise(bootstrap.read);
464
- await Effect10.runPromise(bootstrap.close);
465
- const flush = state.lock.withPermits(1)(Effect10.scoped(Effect10.gen(function* () {
581
+ const bootstrap = options.journalFactory({ actor: "bootstrap", layer: Layer7.succeed(SqlClient3.SqlClient, state.sql), ...options.transaction ? { transaction: options.transaction } : {} });
582
+ bootstrap.read();
583
+ await Effect11.runPromise(bootstrap.close);
584
+ const flush = state.lock.withPermits(1)(Effect11.scoped(Effect11.gen(function* () {
466
585
  const rows = yield* state.sql`SELECT DISTINCT actor FROM experimental_events ORDER BY actor`;
467
586
  const journals = rows.filter((row) => isThreadEventJournal(row.actor, options.actor.actorName, options.accountId));
468
587
  const results = [];
469
588
  if (journals.length === 0) return results;
470
589
  const analytics = Context6.get(yield* Layer7.build(options.analytics), Analytics);
471
590
  for (const row of journals) {
472
- const result = yield* Effect10.gen(function* () {
591
+ const result = yield* Effect11.gen(function* () {
473
592
  return yield* (yield* EventExporter).flush();
474
- }).pipe(Effect10.provide(sqlEventExporter({
593
+ }).pipe(Effect11.provide(sqlEventExporter({
475
594
  accountId: options.accountId,
476
595
  actor: options.actor.actorName,
477
596
  sourceId: JSON.stringify([state.identity.generation, row.actor]),
@@ -482,14 +601,14 @@ async function createSqlExportingHost(options) {
482
601
  results.push(result);
483
602
  }
484
603
  return results;
485
- })).pipe(Effect10.timeout(flushTimeoutMs)));
486
- const worker = runtime.runFork(Effect10.forever(Effect10.gen(function* () {
604
+ })).pipe(Effect11.timeout(flushTimeoutMs)));
605
+ const worker = runtime.runFork(Effect11.forever(Effect11.gen(function* () {
487
606
  yield* Queue.take(state.signals);
488
607
  yield* flush.pipe(
489
- Effect10.tap((results) => Effect10.sync(() => {
608
+ Effect11.tap((results) => Effect11.sync(() => {
490
609
  if (results.some((result) => result.hasMore)) signal();
491
610
  })),
492
- Effect10.catch((error) => Effect10.logWarning("Actor analytics export failed; the cursor is retained for the next flush.", { operation: error instanceof ExportError ? error.operation : "connection", flushTimeoutMs }))
611
+ Effect11.catch((error) => Effect11.logWarning("Actor analytics export failed; the cursor is retained for the next flush.", { operation: error instanceof ExportError ? error.operation : "connection", flushTimeoutMs }))
493
612
  );
494
613
  })));
495
614
  signal();
@@ -502,22 +621,23 @@ async function createSqlExportingHost(options) {
502
621
  const parts = new URL(request.url).pathname.split("/");
503
622
  if (request.method !== "POST" || parts.length !== 5 || parts[1] !== "v1" || parts[2] !== "actors" || parts[4] !== "threads") return void 0;
504
623
  const input = await request.json().catch(() => void 0);
505
- const schema = Schema2.Struct({ name: Schema2.optionalKey(Schema2.NonEmptyString), parent: Schema2.optionalKey(Schema2.NonEmptyString) });
506
- const work = allocations.withPermit(Effect10.gen(function* () {
507
- const body = yield* Schema2.decodeUnknownEffect(schema)(input).pipe(Effect10.mapError(InvalidMessage.from));
624
+ const schema = Schema3.Struct({ name: Schema3.optionalKey(Schema3.NonEmptyString), parent: Schema3.optionalKey(Schema3.NonEmptyString), initialState: Schema3.optionalKey(InitialState) });
625
+ const work = allocations.withPermit(Effect11.gen(function* () {
626
+ const body = yield* Schema3.decodeUnknownEffect(schema)(input).pipe(Effect11.mapError(InvalidMessage2.from));
508
627
  const instance = decodeURIComponent(parts[3]);
509
628
  if (body.name && (yield* host.getThread({ instance, thread: body.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
510
629
  const name = body.name === void 0 ? {} : { name: body.name };
511
- const thread = yield* body.parent === void 0 ? host.allocateRootThread({ instance, ...name }) : host.allocateChildThread({ parent: { actor: host.actor, instance, thread: body.parent }, ...name });
630
+ const seed = body.initialState === void 0 ? {} : { initialState: body.initialState };
631
+ const thread = yield* body.parent === void 0 ? host.allocateRootThread({ instance, ...name, ...seed }) : host.allocateChildThread({ parent: { actor: host.actor, instance, thread: body.parent }, ...name, ...seed });
512
632
  return Response.json(thread.coordinate);
513
633
  }));
514
- return Effect10.runPromise(work.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : 500 })))));
634
+ return Effect11.runPromise(work.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage2 ? 400 : 500 })))));
515
635
  },
516
636
  methodRequest: async (request) => {
517
637
  const parts = new URL(request.url).pathname.split("/");
518
638
  if (parts[1] !== "v1" || parts[2] !== "actors" || decodeURIComponent(parts[3] ?? "") !== options.accountId) return void 0;
519
639
  if (request.method === "GET" && parts.length === 5 && parts[4] === "methods") {
520
- const contracts = await Effect10.runPromise(host.describe(options.accountId));
640
+ const contracts = await Effect11.runPromise(host.methodContracts({ instance: options.accountId }));
521
641
  return Response.json({ items: Object.entries(contracts).map(([name, method]) => ({
522
642
  name,
523
643
  inputSchema: Tool2.getJsonSchemaFromSchema(method.inputSchema),
@@ -526,33 +646,51 @@ async function createSqlExportingHost(options) {
526
646
  })) });
527
647
  }
528
648
  if (parts[4] === "threads" && parts[6] === "calls" && (request.method === "GET" && parts.length === 8 || request.method === "POST" && parts.length === 9 && parts[8] === "cancel")) {
529
- const work2 = Effect10.gen(function* () {
649
+ const work2 = Effect11.gen(function* () {
530
650
  const thread = yield* host.getThread({ instance: options.accountId, thread: decodeURIComponent(parts[5]) });
531
651
  if (!thread) return new Response(null, { status: 404 });
532
652
  const id2 = decodeURIComponent(parts[7]);
533
- const call = yield* thread.call(id2);
653
+ const records = yield* thread.records();
654
+ const invocation = records.find((record) => record.message?.id === id2)?.message?.invocation;
655
+ const call = invocation ? { id: id2, method: invocation.method, ...yield* thread.methodState(invocation.method, id2) } : void 0;
534
656
  if (!call) return new Response(null, { status: 404 });
535
657
  if (request.method === "GET") return Response.json(call);
536
- const input2 = yield* Effect10.tryPromise(() => request.json()).pipe(Effect10.mapError(InvalidMessage.from));
537
- const body = yield* Schema2.decodeUnknownEffect(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(input2).pipe(Effect10.mapError(InvalidMessage.from));
538
- const receipt2 = yield* thread.cancel(call.method, id2, body.reason);
658
+ const input2 = yield* Effect11.tryPromise(() => request.json()).pipe(Effect11.mapError(InvalidMessage2.from));
659
+ const body = yield* Schema3.decodeUnknownEffect(Schema3.Struct({ reason: Schema3.String }), { onExcessProperty: "error" })(input2).pipe(Effect11.mapError(InvalidMessage2.from));
660
+ const original = records.find((record) => record.message?.id === id2)?.message;
661
+ const receipt2 = original?.from && "transport" in original.from && original.from.transport === WEBHOOK_TRANSPORT ? yield* host.receive({ target: thread.coordinate, body: { method: call.method, cancel: { id: id2, reason: body.reason } }, message: { id: JSON.stringify(["cancel", call.method, id2]), from: original.from } }) : yield* thread.cancel(call.method, id2, body.reason);
539
662
  return Response.json(receipt2, { status: 202 });
540
663
  });
541
- return Effect10.runPromise(work2.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : error instanceof MessageConflict ? 409 : 500 })))));
664
+ return Effect11.runPromise(work2.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage2 ? 400 : error instanceof MessageConflict2 ? 409 : 500 })))));
665
+ }
666
+ if (request.method === "POST" && parts.length === 8 && parts[4] === "threads" && parts[6] === "methods" && request.headers.has("x-tardigrade-reply-to")) {
667
+ const thread = await Effect11.runPromise(host.getThread({ instance: options.accountId, thread: decodeURIComponent(parts[5]) }));
668
+ if (!thread || !Object.hasOwn(thread.methods, decodeURIComponent(parts[7]))) return new Response(null, { status: 404 });
542
669
  }
670
+ const webhook = await receiveWebhookRequest(request.clone(), {
671
+ actor: host.actor,
672
+ receive: (packet) => Effect11.runPromise(host.receive(packet)),
673
+ lookup: async (instance, thread, id2) => {
674
+ const handle = await Effect11.runPromise(host.getThread({ instance, thread }));
675
+ if (!handle) return void 0;
676
+ const message = (await Effect11.runPromise(handle.records())).find((record) => record.message?.id === id2 && record.message.invocation)?.message;
677
+ return message?.invocation ? { method: message.invocation.method, from: message.from, state: await Effect11.runPromise(handle.methodState(message.invocation.method, id2)) } : void 0;
678
+ }
679
+ }).catch((error) => Response.json({ error: error.message }, { status: error instanceof MessageConflict2 ? 409 : error instanceof InvalidMessage2 || error instanceof SyntaxError ? 400 : 500 }));
680
+ if (webhook) return webhook;
543
681
  if (request.method !== "POST" || parts.length !== 8 || parts[4] !== "threads" || parts[6] !== "methods") return void 0;
544
682
  const id = request.headers.get("idempotency-key");
545
683
  if (!id?.trim()) return Response.json({ error: "Idempotency-Key is required" }, { status: 400 });
546
684
  const input = await request.json().catch(() => void 0);
547
- const work = Effect10.gen(function* () {
685
+ const work = Effect11.gen(function* () {
548
686
  const thread = yield* host.getThread({ instance: decodeURIComponent(parts[3]), thread: decodeURIComponent(parts[5]) });
549
687
  const method = decodeURIComponent(parts[7]);
550
688
  if (!thread || !Object.hasOwn(thread.methods, method)) return new Response(null, { status: 404 });
551
- const body = yield* Schema2.decodeUnknownEffect(Schema2.Json)(input).pipe(Effect10.mapError(InvalidMessage.from));
689
+ const body = yield* Schema3.decodeUnknownEffect(Schema3.Json)(input).pipe(Effect11.mapError(InvalidMessage2.from));
552
690
  const receipt2 = yield* thread.invoke(method, body, { id });
553
691
  return Response.json(receipt2, { status: 202 });
554
692
  });
555
- return Effect10.runPromise(work.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof MessageConflict ? 409 : error instanceof InvalidMessage ? 400 : 500 })))));
693
+ return Effect11.runPromise(work.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof MessageConflict2 ? 409 : error instanceof InvalidMessage2 ? 400 : 500 })))));
556
694
  },
557
695
  flushEvents: () => {
558
696
  if (closed) return Promise.reject(new Error("Actor host is closed."));
@@ -564,16 +702,16 @@ async function createSqlExportingHost(options) {
564
702
  try {
565
703
  await mcp.close();
566
704
  } finally {
567
- await Effect10.runPromise(host.close);
705
+ await Effect11.runPromise(host.close);
568
706
  }
569
707
  } finally {
570
- await Effect10.runPromise(Fiber2.interrupt(worker));
708
+ await Effect11.runPromise(Fiber.interrupt(worker));
571
709
  await runtime.dispose();
572
710
  }
573
711
  })()
574
712
  };
575
713
  } catch (error) {
576
- for (const close of connections) await Effect10.runPromise(close);
714
+ for (const close of connections) await Effect11.runPromise(close);
577
715
  await runtime.dispose();
578
716
  throw error;
579
717
  }
@@ -617,7 +755,7 @@ var eventsPage = (rows, query) => ({
617
755
  });
618
756
 
619
757
  // ../../src/platform/cloudflare/router.ts
620
- import { Effect as Effect15, Layer as Layer8 } from "effect";
758
+ import { Effect as Effect16, Layer as Layer8 } from "effect";
621
759
 
622
760
  // ../../src/services/actor-router.ts
623
761
  import { Context as Context7, Data as Data4 } from "effect";
@@ -634,23 +772,23 @@ var ActorRuntime = class extends Context8.Service()("tardigrade-cloud/ActorRunti
634
772
  };
635
773
 
636
774
  // ../../src/services/metadata-store.ts
637
- import { Context as Context9, Data as Data6, Schema as Schema3 } from "effect";
638
- var Actor = Schema3.Struct({
639
- name: Schema3.NonEmptyString,
640
- description: Schema3.String
775
+ import { Context as Context9, Data as Data6, Schema as Schema4 } from "effect";
776
+ var Actor = Schema4.Struct({
777
+ name: Schema4.NonEmptyString,
778
+ description: Schema4.String
641
779
  }).annotate({ identifier: "Actor" });
642
- var Version = Schema3.Struct({
643
- id: Schema3.NonEmptyString,
644
- actor: Schema3.NonEmptyString,
645
- digest: Schema3.NonEmptyString
780
+ var Version = Schema4.Struct({
781
+ id: Schema4.NonEmptyString,
782
+ actor: Schema4.NonEmptyString,
783
+ digest: Schema4.NonEmptyString
646
784
  }).annotate({ identifier: "Version" });
647
- var Deployment = Schema3.Struct({
648
- id: Schema3.NonEmptyString,
649
- version: Schema3.NonEmptyString
785
+ var Deployment = Schema4.Struct({
786
+ id: Schema4.NonEmptyString,
787
+ version: Schema4.NonEmptyString
650
788
  }).annotate({ identifier: "Deployment" });
651
- var VersionRecord = Schema3.Struct({
789
+ var VersionRecord = Schema4.Struct({
652
790
  ...Version.fields,
653
- artifactDigest: Schema3.String.check(Schema3.isPattern(/^sha256:[a-f0-9]{64}$/))
791
+ artifactDigest: Schema4.String.check(Schema4.isPattern(/^sha256:[a-f0-9]{64}$/))
654
792
  }).annotate({ identifier: "VersionRecord" });
655
793
  var MetadataStoreError = class extends Data6.TaggedError("MetadataStoreError") {
656
794
  };
@@ -658,13 +796,14 @@ var MetadataStore = class extends Context9.Service()("tardigrade-cloud/MetadataS
658
796
  };
659
797
 
660
798
  // ../../src/platform/router.ts
661
- import { Effect as Effect14, Option as Option2 } from "effect";
799
+ import { Effect as Effect15, Option as Option2 } from "effect";
662
800
 
663
801
  // ../../src/platform/cloudflare/router.ts
664
802
  var actorObjectName = (address) => JSON.stringify([address.accountId, address.actorName]);
665
803
 
666
804
  // ../../src/platform/cloudflare/runtime.ts
667
- var createCloudflareExportingHost = (options) => createSqlExportingHost({ ...options, sql: SqliteClient_exports.layer({ storage: options.storage }), sync: () => options.storage.sync() });
805
+ var createCloudflareExportingHost = (options) => import("tardie/platform/journal").then(({ sqlJournal }) => createSqlExportingHost({ ...options, journalFactory: sqlJournal, sql: SqliteClient_exports.layer({ storage: options.storage }), transaction: (work) => options.storage.transactionSync(work), sync: () => options.storage.sync() }));
806
+ var cloudflareHandler = (host) => HttpRouter2.toWebHandler(hostRoutes(host), { disableLogger: true });
668
807
  var DEFAULT_EVENT_PAGE_SIZE = 100;
669
808
  var READY_PATH = "/__tardigrade/ready";
670
809
  var cloudflareActorObject = (options) => class {
@@ -720,7 +859,7 @@ var cloudflareActorObject = (options) => class {
720
859
  if (!Number.isSafeInteger(pageSize) || pageSize < 1) throw new Error("Event page size must be a positive integer.");
721
860
  if (request.method === "GET" && parts.length === 7 && parts[6] === "events") {
722
861
  const thread = decodeURIComponent(parts[5]);
723
- if (!await Effect16.runPromise(this.active.host.getThread({ instance: accountId, thread }))) return new Response(null, { status: 404 });
862
+ if (!await Effect17.runPromise(this.active.host.getThread({ instance: accountId, thread }))) return new Response(null, { status: 404 });
724
863
  const query = parseEventsQuery(url.searchParams, pageSize);
725
864
  if (!query) return new Response(null, { status: 400 });
726
865
  const statement = eventsStatement(JSON.stringify([actorName, accountId, "thread", thread, "events"]), query);
@@ -729,13 +868,13 @@ var cloudflareActorObject = (options) => class {
729
868
  if (request.method === "GET" && parts.length === 5 && parts[4] === "threads") {
730
869
  const cursor = Number(url.searchParams.get("cursor") ?? 0);
731
870
  if (!Number.isSafeInteger(cursor) || cursor < 0) return new Response(null, { status: 400 });
732
- const store = await Effect16.runPromise(this.active.host.supervisorStore(accountId));
871
+ const store = await Effect17.runPromise(this.active.host.supervisorStore(accountId));
733
872
  const threads = store.threads.get().filter((thread) => thread.status === "registered");
734
873
  return Response.json({ items: threads.slice(cursor, cursor + pageSize).map((thread) => ({ id: thread.coordinate.thread, ...thread.parent ? { parent: thread.parent } : {} })), ...cursor + pageSize < threads.length ? { cursor: String(cursor + pageSize) } : {} });
735
874
  }
736
875
  if (request.method === "POST" && parts.length === 5 && parts[4] === "threads") {
737
876
  const input = await request.clone().json().catch(() => null);
738
- if (typeof input?.name === "string" && await Effect16.runPromise(this.active.host.getThread({ instance: accountId, thread: input.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
877
+ if (typeof input?.name === "string" && await Effect17.runPromise(this.active.host.getThread({ instance: accountId, thread: input.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
739
878
  }
740
879
  return await this.active.host.allocationRequest(request.clone()) ?? await this.active.host.methodRequest(request.clone()) ?? await this.active.host.mcpRequest(request.clone()) ?? this.active.app.handler(request);
741
880
  }
@@ -754,6 +893,7 @@ var createActorWorker = (actor, DurableObject, services, actorContext) => {
754
893
  const Handler = cloudflareActorObject({
755
894
  load: async (deployment, env) => ({
756
895
  actor,
896
+ transports: { [WEBHOOK_TRANSPORT]: webhookTransport(env.WEBHOOKS) },
757
897
  ...actorContext ? { actorContext } : {},
758
898
  services: (coordinate, runtime) => {
759
899
  const platform = Layer9.mergeAll(