actorctl 0.1.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.
@@ -0,0 +1,831 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // ../../src/platform/cloudflare/user-worker.ts
20
+ import { ConfigProvider, Layer as Layer10 } from "effect";
21
+
22
+ // ../../src/platform/cloudflare/analytics.ts
23
+ import { Effect as Effect2, Layer } from "effect";
24
+
25
+ // ../../src/services/analytics.ts
26
+ import { Context, Data } from "effect";
27
+ var AnalyticsError = class extends Data.TaggedError("AnalyticsError") {
28
+ };
29
+ var Analytics = class extends Context.Service()("tardigrade-cloud/Analytics") {
30
+ };
31
+
32
+ // ../../src/platform/cloudflare/analytics.ts
33
+ var cloudflareAnalytics = (accountId, binding) => Layer.succeed(Analytics, Analytics.of({
34
+ accountId,
35
+ query: (sql, parameters = []) => Effect2.tryPromise({
36
+ try: () => binding.query(sql, parameters),
37
+ catch: () => new AnalyticsError({ operation: "query", message: "Analytics query failed." })
38
+ }),
39
+ execute: (sql, parameters = []) => Effect2.tryPromise({
40
+ try: () => binding.execute(sql, parameters),
41
+ catch: () => new AnalyticsError({ operation: "execute", message: "Analytics write failed." })
42
+ })
43
+ }));
44
+
45
+ // ../../src/services/container.ts
46
+ import { Context as Context2, Effect as Effect3, Layer as Layer2 } from "effect";
47
+ var ContainerService = class extends Context2.Service()("tardigrade-cloud/ContainerService") {
48
+ };
49
+ var boundContainerService = (binding, thread) => Layer2.succeed(ContainerService, {
50
+ execute: (taskId, command, timeoutMs) => Effect3.tryPromise(async () => {
51
+ if (!binding) throw new Error("Container service is unavailable");
52
+ if (thread !== `task-${taskId}`) throw new Error("Command task must match the agent thread");
53
+ return binding.execute(taskId, command, timeoutMs);
54
+ })
55
+ });
56
+
57
+ // ../../src/platform/cloudflare/inference.ts
58
+ import { Effect as Effect5, Layer as Layer3 } from "effect";
59
+
60
+ // ../../src/services/ai-gateway.ts
61
+ import { Context as Context3, Data as Data2 } from "effect";
62
+ var AiGatewayError = class extends Data2.TaggedError("AiGatewayError") {
63
+ };
64
+ var AiGateway = class extends Context3.Service()("tardigrade-cloud/AiGateway") {
65
+ };
66
+
67
+ // ../../src/platform/cloudflare/inference.ts
68
+ var boundAiGateway = (accountId, binding) => Layer3.succeed(AiGateway, AiGateway.of({
69
+ accountId,
70
+ complete: (request) => Effect5.tryPromise({
71
+ try: () => binding.complete(request),
72
+ catch: () => new AiGatewayError({ reason: "unavailable", message: "Inference service unavailable." })
73
+ }).pipe(Effect5.flatMap((result) => result.ok ? Effect5.succeed(result.value) : Effect5.fail(new AiGatewayError(result.error))))
74
+ }));
75
+
76
+ // ../../src/platform/cloudflare/runtime.ts
77
+ import { Effect as Effect17 } from "effect";
78
+
79
+ // ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteClient.js
80
+ var SqliteClient_exports = {};
81
+ __export(SqliteClient_exports, {
82
+ SqliteClient: () => SqliteClient,
83
+ TypeId: () => TypeId,
84
+ layer: () => layer2,
85
+ layerConfig: () => layerConfig,
86
+ make: () => make4
87
+ });
88
+ import * as Cause from "effect/Cause";
89
+ import * as Config from "effect/Config";
90
+ import * as Context4 from "effect/Context";
91
+ import * as Effect6 from "effect/Effect";
92
+ import * as Exit from "effect/Exit";
93
+ import * as Fiber from "effect/Fiber";
94
+ import { identity } from "effect/Function";
95
+ import * as Layer4 from "effect/Layer";
96
+ import * as Rec from "effect/Record";
97
+ import * as Scope from "effect/Scope";
98
+ import * as Semaphore from "effect/Semaphore";
99
+ import * as Stream from "effect/Stream";
100
+ import * as Reactivity from "effect/unstable/reactivity/Reactivity";
101
+ import * as Client from "effect/unstable/sql/SqlClient";
102
+ import { classifySqliteError, SqlError, UnknownError } from "effect/unstable/sql/SqlError";
103
+ import * as Statement from "effect/unstable/sql/Statement";
104
+ var ATTR_DB_SYSTEM_NAME = "db.system.name";
105
+ var classifyError = (cause, message, operation) => classifySqliteError(cause, {
106
+ message,
107
+ operation
108
+ });
109
+ var TypeId = "~@effect/sql-sqlite-do/SqliteClient";
110
+ var SqliteClient = /* @__PURE__ */ Context4.Service("@effect/sql-sqlite-do/SqliteClient");
111
+ var SqliteTransaction = /* @__PURE__ */ Context4.Service("@effect/sql-sqlite-do/SqliteClient/SqliteTransaction");
112
+ var unsupportedTransaction = (message, operation) => new SqlError({
113
+ reason: new UnknownError({
114
+ cause: new Error(message),
115
+ message,
116
+ operation
117
+ })
118
+ });
119
+ var makeUnsupportedWithTransaction = (message) => (_effect) => Effect6.fail(unsupportedTransaction(message, "transaction"));
120
+ var makeStorageBackedWithTransaction = (storage, connection, semaphore) => (effect) => Effect6.withFiber((fiber) => {
121
+ const services = fiber.context;
122
+ const connOption = Context4.getOption(services, SqliteTransaction);
123
+ if (connOption._tag === "Some") {
124
+ return Effect6.fail(unsupportedTransaction("Nested transactions are not supported by Cloudflare Durable Object SQLite storage", "transaction"));
125
+ }
126
+ const effectWithTxn = Effect6.provideContext(effect, Context4.add(services, SqliteTransaction, [connection, 0]));
127
+ return semaphore.withPermits(1)(Effect6.callback((resume) => {
128
+ let interrupted = false;
129
+ const promise2 = storage.transaction((txn) => new Promise((resolve) => {
130
+ if (interrupted) return resolve();
131
+ resume(Effect6.onExit(effectWithTxn, (exit) => {
132
+ if (Exit.isFailure(exit)) {
133
+ txn.rollback();
134
+ }
135
+ resolve();
136
+ return Effect6.promise(() => promise2);
137
+ }));
138
+ })).catch((cause) => resume(Effect6.fail(new SqlError({
139
+ reason: classifyError(cause, "Failed transaction", "transaction")
140
+ }))));
141
+ return Effect6.suspend(() => {
142
+ interrupted = true;
143
+ return Effect6.promise(() => promise2);
144
+ });
145
+ }));
146
+ });
147
+ var make4 = (options) => Effect6.gen(function* () {
148
+ const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
149
+ const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : void 0;
150
+ const db = options.storage?.sql ?? options.db;
151
+ if (db === void 0) {
152
+ return yield* Effect6.die("SqliteClient.make requires either a Durable Object storage or sql storage");
153
+ }
154
+ const sqlStorage = db;
155
+ const makeConnection = Effect6.gen(function* () {
156
+ function* runIterator(sql, params = []) {
157
+ const cursor = sqlStorage.exec(sql, ...params);
158
+ const columns = cursor.columnNames;
159
+ for (const result of cursor.raw()) {
160
+ const obj = {};
161
+ for (let i = 0; i < columns.length; i++) {
162
+ const value = result[i];
163
+ Rec.assignProperty(obj, columns[i], value instanceof ArrayBuffer ? new Uint8Array(value) : value);
164
+ }
165
+ yield obj;
166
+ }
167
+ }
168
+ const runStatement = (sql, params = []) => Effect6.try({
169
+ try: () => Array.from(runIterator(sql, params)),
170
+ catch: (cause) => new SqlError({
171
+ reason: classifyError(cause, "Failed to execute statement", "execute")
172
+ })
173
+ });
174
+ const runValues = (sql, params = []) => Effect6.try({
175
+ try: () => Array.from(sqlStorage.exec(sql, ...params).raw(), (row) => {
176
+ for (let i = 0; i < row.length; i++) {
177
+ const value = row[i];
178
+ if (value instanceof ArrayBuffer) {
179
+ row[i] = new Uint8Array(value);
180
+ }
181
+ }
182
+ return row;
183
+ }),
184
+ catch: (cause) => new SqlError({
185
+ reason: classifyError(cause, "Failed to execute statement", "execute")
186
+ })
187
+ });
188
+ return identity({
189
+ execute(sql, params, transformRows2) {
190
+ return transformRows2 ? Effect6.map(runStatement(sql, params), transformRows2) : runStatement(sql, params);
191
+ },
192
+ executeRaw(sql, params) {
193
+ return runStatement(sql, params);
194
+ },
195
+ executeValues(sql, params) {
196
+ return runValues(sql, params);
197
+ },
198
+ executeValuesUnprepared(sql, params) {
199
+ return runValues(sql, params);
200
+ },
201
+ executeUnprepared(sql, params, transformRows2) {
202
+ return transformRows2 ? Effect6.map(runStatement(sql, params), transformRows2) : runStatement(sql, params);
203
+ },
204
+ executeStream(sql, params, transformRows2) {
205
+ return Stream.suspend(() => {
206
+ const iterator = runIterator(sql, params);
207
+ return Stream.fromIteratorSucceed(iterator, 128);
208
+ }).pipe(Stream.catchCauseFilter(Cause.findDefect, (defect) => Stream.fail(new SqlError({
209
+ reason: classifyError(defect, "Failed to execute statement", "execute")
210
+ }))), transformRows2 ? Stream.mapArray((chunk) => transformRows2(chunk)) : identity);
211
+ }
212
+ });
213
+ });
214
+ const semaphore = yield* Semaphore.make(1);
215
+ const connection = yield* makeConnection;
216
+ const acquirer = semaphore.withPermits(1)(Effect6.succeed(connection));
217
+ const transactionAcquirer = Effect6.uninterruptibleMask((restore) => {
218
+ const fiber = Fiber.getCurrent();
219
+ const scope = Context4.getUnsafe(fiber.context, Scope.Scope);
220
+ return Effect6.as(Effect6.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), connection);
221
+ });
222
+ const client = yield* Client.make({
223
+ acquirer,
224
+ compiler,
225
+ transactionAcquirer,
226
+ transactionService: SqliteTransaction,
227
+ spanAttributes: [...options.spanAttributes ? Object.entries(options.spanAttributes) : [], [ATTR_DB_SYSTEM_NAME, "sqlite"]],
228
+ transformRows
229
+ });
230
+ return Object.assign(client, {
231
+ [TypeId]: TypeId,
232
+ config: options,
233
+ withTransaction: options.storage ? makeStorageBackedWithTransaction(options.storage, connection, semaphore) : makeUnsupportedWithTransaction("Transactions require Durable Object storage; pass ctx.storage as the storage option")
234
+ });
235
+ });
236
+ var layerConfig = (config) => Layer4.effectContext(Config.unwrap(config).pipe(Effect6.flatMap(make4), Effect6.map((client) => Context4.make(SqliteClient, client).pipe(Context4.add(Client.SqlClient, client))))).pipe(Layer4.provide(Reactivity.layer));
237
+ var layer2 = (config) => Layer4.effectContext(Effect6.map(make4(config), (client) => Context4.make(SqliteClient, client).pipe(Context4.add(Client.SqlClient, client)))).pipe(Layer4.provide(Reactivity.layer));
238
+
239
+ // ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteMigrator.js
240
+ var SqliteMigrator_exports = {};
241
+ __export(SqliteMigrator_exports, {
242
+ layer: () => layer3,
243
+ run: () => run
244
+ });
245
+ __reExport(SqliteMigrator_exports, Migrator_star);
246
+ import * as Layer5 from "effect/Layer";
247
+ import * as Migrator from "effect/unstable/sql/Migrator";
248
+ import * as Migrator_star from "effect/unstable/sql/Migrator";
249
+ var run = /* @__PURE__ */ Migrator.make({});
250
+ var layer3 = (options) => Layer5.effectDiscard(run(options));
251
+
252
+ // ../../src/platform/cloudflare/runtime.ts
253
+ import { cloudflareHandler } from "tardie/experimental/cloudflare";
254
+
255
+ // ../../src/platform/exporting-host.ts
256
+ import { Context as Context7, Effect as Effect11, Fiber as Fiber2, Layer as Layer8, ManagedRuntime, Queue, Semaphore as Semaphore3, Schema as Schema2 } from "effect";
257
+ import { SqlClient as SqlClient3 } from "effect/unstable/sql";
258
+ import { createThreadHost, InvalidMessage, MessageConflict } from "tardie/experimental";
259
+ import { sqlJournal } from "tardie/experimental/cloudflare";
260
+
261
+ // ../../src/services/event-exporter.ts
262
+ import { Context as Context5, Data as Data3 } from "effect";
263
+ var ExportError = class extends Data3.TaggedError("ExportError") {
264
+ };
265
+ var EventExporter = class extends Context5.Service()("tardigrade-cloud/EventExporter") {
266
+ };
267
+
268
+ // ../../src/platform/export-source.ts
269
+ import { Effect as Effect8 } from "effect";
270
+ import { SqlClient as SqlClient2 } from "effect/unstable/sql";
271
+ var journalExportSource = (options) => Effect8.gen(function* () {
272
+ if (!options.journal || !options.cursorKey) return yield* new ExportError({ operation: "config", message: "Journal and destination cursor key are required." });
273
+ const sql = yield* SqlClient2.SqlClient;
274
+ const error = (operation) => () => new ExportError({ operation, message: `Journal export ${operation} failed.` });
275
+ yield* sql`CREATE TABLE IF NOT EXISTS event_export_cursors (id TEXT PRIMARY KEY, position INTEGER NOT NULL CHECK (position >= 0))`.pipe(Effect8.mapError(error("cursor")));
276
+ yield* sql`INSERT INTO event_export_cursors (id, position) VALUES (${options.cursorKey}, 0) ON CONFLICT (id) DO NOTHING`.pipe(Effect8.mapError(error("cursor")));
277
+ const cursor = Effect8.gen(function* () {
278
+ const rows = yield* sql`SELECT position FROM event_export_cursors WHERE id = ${options.cursorKey}`.pipe(Effect8.mapError(error("cursor")));
279
+ if (!rows[0]) return yield* new ExportError({ operation: "cursor", message: "Export cursor is missing." });
280
+ return rows[0].position;
281
+ });
282
+ return {
283
+ cursor,
284
+ read: (from, limit) => sql`SELECT seq AS position, event AS payload FROM experimental_events WHERE actor = ${options.journal} AND seq >= ${from} ORDER BY seq LIMIT ${limit}`.pipe(Effect8.mapError(error("read"))),
285
+ advance: (expected, next) => Effect8.gen(function* () {
286
+ if (!Number.isSafeInteger(expected) || !Number.isSafeInteger(next) || expected < 0 || next <= expected) {
287
+ return yield* new ExportError({ operation: "cursor", message: "Invalid cursor advancement." });
288
+ }
289
+ const rows = yield* sql`UPDATE event_export_cursors SET position = ${next} WHERE id = ${options.cursorKey} AND position = ${expected} RETURNING position`.pipe(Effect8.mapError(error("cursor")));
290
+ if (rows.length !== 1) return yield* new ExportError({ operation: "cursor", message: "Export cursor changed concurrently; retry the flush." });
291
+ })
292
+ };
293
+ });
294
+
295
+ // ../../src/platform/exporter.ts
296
+ import { Effect as Effect9, Layer as Layer6, Semaphore as Semaphore2 } from "effect";
297
+ var DEFAULT_EXPORT_BATCH_SIZE = 100;
298
+ var eventExporter = (options) => Layer6.effect(EventExporter, Effect9.gen(function* () {
299
+ const analytics = yield* Analytics;
300
+ const batchSize = options.batchSize ?? DEFAULT_EXPORT_BATCH_SIZE;
301
+ if (![options.accountId, options.actor, options.sourceId].every(Boolean) || analytics.accountId !== options.accountId) {
302
+ return yield* new ExportError({ operation: "config", message: "Exporter identity must match the analytics account." });
303
+ }
304
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize >= Number.MAX_SAFE_INTEGER) {
305
+ return yield* new ExportError({ operation: "config", message: "Export batch size must be a positive safe integer below Number.MAX_SAFE_INTEGER." });
306
+ }
307
+ const writeError = () => new ExportError({ operation: "write", message: "Analytics event export failed." });
308
+ yield* analytics.execute(`CREATE TABLE IF NOT EXISTS actor_events (
309
+ account_id VARCHAR NOT NULL, actor VARCHAR NOT NULL, source_id VARCHAR NOT NULL,
310
+ position BIGINT NOT NULL, payload JSON NOT NULL,
311
+ PRIMARY KEY (account_id, source_id, position)
312
+ )`).pipe(Effect9.mapError(writeError));
313
+ const lock = yield* Semaphore2.make(1);
314
+ return EventExporter.of({
315
+ flush: () => lock.withPermits(1)(Effect9.gen(function* () {
316
+ const cursor = yield* options.source.cursor;
317
+ if (!Number.isSafeInteger(cursor) || cursor < 0) return yield* new ExportError({ operation: "cursor", message: "Invalid export cursor." });
318
+ const rows = yield* options.source.read(cursor, batchSize + 1);
319
+ if (rows.length > batchSize + 1 || rows.some((row, index) => row.position !== cursor + index || !Number.isSafeInteger(row.position))) {
320
+ return yield* new ExportError({ operation: "read", message: "Journal export page has a gap or exceeds the requested limit." });
321
+ }
322
+ const batch = rows.slice(0, batchSize);
323
+ if (batch.length === 0) return { exported: 0, cursor, hasMore: false, batchSize };
324
+ const next = cursor + batch.length;
325
+ if (!Number.isSafeInteger(next)) return yield* new ExportError({ operation: "cursor", message: "Export cursor exceeds the safe integer range." });
326
+ const parameters = batch.flatMap((row) => [options.accountId, options.actor, options.sourceId, row.position, row.payload]);
327
+ const values = batch.map((_, index) => `(${Array.from({ length: 5 }, (_2, field) => `$${index * 5 + field + 1}`).join(", ")})`).join(", ");
328
+ yield* analytics.execute(
329
+ `INSERT INTO actor_events (account_id, actor, source_id, position, payload) VALUES ${values} ON CONFLICT (account_id, source_id, position) DO NOTHING`,
330
+ parameters
331
+ ).pipe(Effect9.mapError(writeError));
332
+ yield* options.source.advance(cursor, next);
333
+ return { exported: batch.length, cursor: next, hasMore: rows.length > batchSize, batchSize };
334
+ }))
335
+ });
336
+ }));
337
+ var sqlEventExporter = (options) => Layer6.unwrap(Effect9.gen(function* () {
338
+ if (!options.destinationId) return yield* new ExportError({ operation: "config", message: "Analytics destination identity is required." });
339
+ const source = yield* journalExportSource({
340
+ journal: options.journal,
341
+ cursorKey: JSON.stringify([options.accountId, options.sourceId, options.destinationId])
342
+ });
343
+ return eventExporter({ ...options, source });
344
+ }));
345
+
346
+ // ../../src/platform/actor-mcp.ts
347
+ import { Context as Context6, Effect as Effect10, Layer as Layer7, Schema } from "effect";
348
+ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
349
+ import { HttpRouter } from "effect/unstable/http";
350
+ var ACTOR_MCP_PROTOCOLS = [McpProtocol.v2025_11_25, McpProtocol.v2025_06_18];
351
+ var identity2 = { thread: Schema.NonEmptyString, id: Schema.NonEmptyString };
352
+ var receipt = Schema.Struct({ id: Schema.String, position: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))) });
353
+ function actorMcp(host, instance, options = {}) {
354
+ const path = `/v1/actors/${encodeURIComponent(instance)}/mcp`;
355
+ let app;
356
+ const open = () => app ??= Effect10.runPromise(host.describe(instance)).then((contracts) => {
357
+ const register = Layer7.effectDiscard(Effect10.gen(function* () {
358
+ const server = yield* McpServer.McpServer;
359
+ const add2 = (name, description, input, output, run2) => server.addTool({
360
+ tool: new McpSchema.Tool({ name, description, inputSchema: Tool.getJsonSchemaFromSchema(input), outputSchema: Tool.getJsonSchemaFromSchema(output) }),
361
+ annotations: Context6.empty(),
362
+ handle: (payload) => Schema.decodeUnknownEffect(Schema.toType(input), { onExcessProperty: "error" })(payload).pipe(
363
+ Effect10.mapError((error) => new McpSchema.InvalidParams({ message: error.message })),
364
+ Effect10.flatMap((value) => run2(value).pipe(
365
+ Effect10.map((result) => new McpSchema.CallToolResult({ content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result })),
366
+ Effect10.catch((error) => Effect10.succeed(new McpSchema.CallToolResult({ isError: true, content: [{ type: "text", text: error.message }] })))
367
+ ))
368
+ )
369
+ });
370
+ const thread = (name) => host.getThread({ instance, thread: name }).pipe(Effect10.flatMap((value) => value ? Effect10.succeed(value) : Effect10.fail(new Error("Unknown thread"))));
371
+ for (const [name, method] of Object.entries(contracts)) {
372
+ yield* add2(
373
+ `invoke_${name}`,
374
+ `Accept ${name}. Returns a durable call receipt; use call_get for the final result. Reuse id and input on retries.`,
375
+ Schema.Struct({ ...identity2, input: method.inputSchema }),
376
+ receipt,
377
+ (input) => thread(input.thread).pipe(Effect10.flatMap((current) => current.invoke(name, input.input, { id: input.id })))
378
+ );
379
+ }
380
+ yield* add2(
381
+ "call_get",
382
+ "Read a call's current status and final result.",
383
+ Schema.Struct(identity2),
384
+ 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) }),
385
+ (input) => thread(input.thread).pipe(Effect10.flatMap((current) => current.call(input.id)), Effect10.flatMap((value) => value ? Effect10.succeed(value) : Effect10.fail(new Error("Unknown call"))))
386
+ );
387
+ yield* add2(
388
+ "call_cancel",
389
+ "Request cancellation of an accepted call. Returns acceptance, not cancellation completion.",
390
+ Schema.Struct({ ...identity2, reason: Schema.String }),
391
+ receipt,
392
+ (input) => thread(input.thread).pipe(Effect10.flatMap((current) => current.call(input.id).pipe(Effect10.flatMap((call) => call ? current.cancel(call.method, input.id, input.reason) : Effect10.fail(new Error("Unknown call"))))))
393
+ );
394
+ })).pipe(Layer7.provide(McpServer.layerHttp({ name: host.actor, version: "1.0.0", path, protocols: ACTOR_MCP_PROTOCOLS, ...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {} })));
395
+ return HttpRouter.toWebHandler(register, { disableLogger: true });
396
+ }).catch((error) => {
397
+ app = void 0;
398
+ throw error;
399
+ });
400
+ return {
401
+ request: async (request) => new URL(request.url).pathname === path ? (await open()).handler(request) : void 0,
402
+ close: async () => {
403
+ if (app) await (await app).dispose();
404
+ }
405
+ };
406
+ }
407
+
408
+ // ../../src/platform/exporting-host.ts
409
+ import { Tool as Tool2 } from "effect/unstable/ai";
410
+ var DEFAULT_EXPORT_FLUSH_TIMEOUT_MS = 3e4;
411
+ var isThreadEventJournal = (value, actor, account) => {
412
+ try {
413
+ const parts = JSON.parse(value);
414
+ return Array.isArray(parts) && parts.length === 5 && parts.every((part) => typeof part === "string") && parts[0] === actor && parts[1] === account && parts[2] === "thread" && parts[4] === "events";
415
+ } catch {
416
+ return false;
417
+ }
418
+ };
419
+ async function createSqlExportingHost(options) {
420
+ if (!options.accountId || !options.destinationId) throw new Error("Account and analytics destination are required.");
421
+ const flushTimeoutMs = options.flushTimeoutMs ?? DEFAULT_EXPORT_FLUSH_TIMEOUT_MS;
422
+ if (!Number.isSafeInteger(flushTimeoutMs) || flushTimeoutMs < 1) throw new Error("Export flush timeout must be positive integer milliseconds.");
423
+ const runtime = ManagedRuntime.make(options.sql);
424
+ const connections = /* @__PURE__ */ new Set();
425
+ try {
426
+ const state = await runtime.runPromise(Effect11.gen(function* () {
427
+ const sql = yield* SqlClient3.SqlClient;
428
+ 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)`;
429
+ yield* sql`INSERT INTO event_export_identity VALUES (1, ${options.accountId}, ${options.actor.actorName}, ${crypto.randomUUID()}) ON CONFLICT (id) DO NOTHING`;
430
+ const rows = yield* sql`SELECT account, actor, generation FROM event_export_identity WHERE id = 1`;
431
+ const identity3 = rows[0];
432
+ 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."));
433
+ const signals = yield* Queue.make({ capacity: 1, strategy: "sliding" });
434
+ const lock = yield* Semaphore3.make(1);
435
+ return { sql, identity: identity3, signals, lock };
436
+ }));
437
+ let closed = false;
438
+ const signal = () => {
439
+ if (!closed) Queue.offerUnsafe(state.signals, void 0);
440
+ };
441
+ const journal = (parts, exportEvents = false) => {
442
+ const key = JSON.stringify(parts);
443
+ const opened = sqlJournal({ actor: key, layer: Layer8.succeed(SqlClient3.SqlClient, state.sql) });
444
+ connections.add(opened.close);
445
+ const afterCommit = Effect11.gen(function* () {
446
+ if (options.sync) yield* Effect11.tryPromise(() => options.sync());
447
+ if (exportEvents) signal();
448
+ });
449
+ return {
450
+ ...opened,
451
+ append: (...args) => opened.append(...args).pipe(Effect11.andThen(afterCommit)),
452
+ appendWithCheckpoint: (...args) => opened.appendWithCheckpoint(...args).pipe(Effect11.andThen(afterCommit))
453
+ };
454
+ };
455
+ const checkAccount = (instance) => {
456
+ if (instance !== options.accountId) throw new Error("Actor instance does not match its account.");
457
+ };
458
+ const storage = {
459
+ supervisor: (actor, instance) => {
460
+ checkAccount(instance);
461
+ return journal([actor, instance, "supervisor"]);
462
+ },
463
+ thread: (coordinate) => {
464
+ checkAccount(coordinate.instance);
465
+ return journal([coordinate.actor, coordinate.instance, "thread", coordinate.thread, "events"], true);
466
+ },
467
+ close: Effect11.gen(function* () {
468
+ for (const close of connections) yield* close;
469
+ connections.clear();
470
+ })
471
+ };
472
+ const allocations = Semaphore3.makeUnsafe(1);
473
+ const host = createThreadHost({ ...options, services: (coordinate, current) => options.services(coordinate, current).pipe(Layer8.provideMerge(Layer8.succeed(SqlClient3.SqlClient, state.sql))), storage, actorContext: options.actorContext ?? ((context) => context) });
474
+ const bootstrap = sqlJournal({ actor: "bootstrap", layer: Layer8.succeed(SqlClient3.SqlClient, state.sql) });
475
+ await Effect11.runPromise(bootstrap.read);
476
+ await Effect11.runPromise(bootstrap.close);
477
+ const flush = state.lock.withPermits(1)(Effect11.scoped(Effect11.gen(function* () {
478
+ const rows = yield* state.sql`SELECT DISTINCT actor FROM experimental_events ORDER BY actor`;
479
+ const journals = rows.filter((row) => isThreadEventJournal(row.actor, options.actor.actorName, options.accountId));
480
+ const results = [];
481
+ if (journals.length === 0) return results;
482
+ const analytics = Context7.get(yield* Layer8.build(options.analytics), Analytics);
483
+ for (const row of journals) {
484
+ const result = yield* Effect11.gen(function* () {
485
+ return yield* (yield* EventExporter).flush();
486
+ }).pipe(Effect11.provide(sqlEventExporter({
487
+ accountId: options.accountId,
488
+ actor: options.actor.actorName,
489
+ sourceId: JSON.stringify([state.identity.generation, row.actor]),
490
+ destinationId: options.destinationId,
491
+ journal: row.actor,
492
+ ...options.batchSize === void 0 ? {} : { batchSize: options.batchSize }
493
+ }).pipe(Layer8.provide(Layer8.succeed(Analytics, analytics)))));
494
+ results.push(result);
495
+ }
496
+ return results;
497
+ })).pipe(Effect11.timeout(flushTimeoutMs)));
498
+ const worker = runtime.runFork(Effect11.forever(Effect11.gen(function* () {
499
+ yield* Queue.take(state.signals);
500
+ yield* flush.pipe(
501
+ Effect11.tap((results) => Effect11.sync(() => {
502
+ if (results.some((result) => result.hasMore)) signal();
503
+ })),
504
+ 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 }))
505
+ );
506
+ })));
507
+ signal();
508
+ const mcp = actorMcp(host, options.accountId, options.mcp);
509
+ let closing;
510
+ return {
511
+ ...host,
512
+ mcpRequest: mcp.request,
513
+ allocationRequest: async (request) => {
514
+ const parts = new URL(request.url).pathname.split("/");
515
+ if (request.method !== "POST" || parts.length !== 5 || parts[1] !== "v1" || parts[2] !== "actors" || parts[4] !== "threads") return void 0;
516
+ const input = await request.json().catch(() => void 0);
517
+ const schema = Schema2.Struct({ name: Schema2.optionalKey(Schema2.NonEmptyString), parent: Schema2.optionalKey(Schema2.NonEmptyString) });
518
+ const work = allocations.withPermit(Effect11.gen(function* () {
519
+ const body = yield* Schema2.decodeUnknownEffect(schema)(input).pipe(Effect11.mapError(InvalidMessage.from));
520
+ const instance = decodeURIComponent(parts[3]);
521
+ if (body.name && (yield* host.getThread({ instance, thread: body.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
522
+ const name = body.name === void 0 ? {} : { name: body.name };
523
+ const thread = yield* body.parent === void 0 ? host.allocateRootThread({ instance, ...name }) : host.allocateChildThread({ parent: { actor: host.actor, instance, thread: body.parent }, ...name });
524
+ return Response.json(thread.coordinate);
525
+ }));
526
+ return Effect11.runPromise(work.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : 500 })))));
527
+ },
528
+ methodRequest: async (request) => {
529
+ const parts = new URL(request.url).pathname.split("/");
530
+ if (parts[1] !== "v1" || parts[2] !== "actors" || decodeURIComponent(parts[3] ?? "") !== options.accountId) return void 0;
531
+ if (request.method === "GET" && parts.length === 5 && parts[4] === "methods") {
532
+ const contracts = await Effect11.runPromise(host.describe(options.accountId));
533
+ return Response.json({ items: Object.entries(contracts).map(([name, method]) => ({
534
+ name,
535
+ inputSchema: Tool2.getJsonSchemaFromSchema(method.inputSchema),
536
+ outputSchema: Tool2.getJsonSchemaFromSchema(method.outputSchema),
537
+ cancellable: method.onCancel !== void 0
538
+ })) });
539
+ }
540
+ if (parts[4] === "threads" && parts[6] === "calls" && (request.method === "GET" && parts.length === 8 || request.method === "POST" && parts.length === 9 && parts[8] === "cancel")) {
541
+ const work2 = Effect11.gen(function* () {
542
+ const thread = yield* host.getThread({ instance: options.accountId, thread: decodeURIComponent(parts[5]) });
543
+ if (!thread) return new Response(null, { status: 404 });
544
+ const id2 = decodeURIComponent(parts[7]);
545
+ const call = yield* thread.call(id2);
546
+ if (!call) return new Response(null, { status: 404 });
547
+ if (request.method === "GET") return Response.json(call);
548
+ const input2 = yield* Effect11.tryPromise(() => request.json()).pipe(Effect11.mapError(InvalidMessage.from));
549
+ const body = yield* Schema2.decodeUnknownEffect(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(input2).pipe(Effect11.mapError(InvalidMessage.from));
550
+ const receipt2 = yield* thread.cancel(call.method, id2, body.reason);
551
+ return Response.json(receipt2, { status: 202 });
552
+ });
553
+ return Effect11.runPromise(work2.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : error instanceof MessageConflict ? 409 : 500 })))));
554
+ }
555
+ if (request.method !== "POST" || parts.length !== 8 || parts[4] !== "threads" || parts[6] !== "methods") return void 0;
556
+ const id = request.headers.get("idempotency-key");
557
+ if (!id?.trim()) return Response.json({ error: "Idempotency-Key is required" }, { status: 400 });
558
+ const input = await request.json().catch(() => void 0);
559
+ const work = Effect11.gen(function* () {
560
+ const thread = yield* host.getThread({ instance: decodeURIComponent(parts[3]), thread: decodeURIComponent(parts[5]) });
561
+ const method = decodeURIComponent(parts[7]);
562
+ if (!thread || !Object.hasOwn(thread.methods, method)) return new Response(null, { status: 404 });
563
+ const body = yield* Schema2.decodeUnknownEffect(Schema2.Json)(input).pipe(Effect11.mapError(InvalidMessage.from));
564
+ const receipt2 = yield* thread.invoke(method, body, { id });
565
+ return Response.json(receipt2, { status: 202 });
566
+ });
567
+ return Effect11.runPromise(work.pipe(Effect11.catch((error) => Effect11.succeed(Response.json({ error: error.message }, { status: error instanceof MessageConflict ? 409 : error instanceof InvalidMessage ? 400 : 500 })))));
568
+ },
569
+ flushEvents: () => {
570
+ if (closed) return Promise.reject(new Error("Actor host is closed."));
571
+ return runtime.runPromise(flush);
572
+ },
573
+ close: () => closing ??= (async () => {
574
+ closed = true;
575
+ try {
576
+ try {
577
+ await mcp.close();
578
+ } finally {
579
+ await Effect11.runPromise(host.close);
580
+ }
581
+ } finally {
582
+ await Effect11.runPromise(Fiber2.interrupt(worker));
583
+ await runtime.dispose();
584
+ }
585
+ })()
586
+ };
587
+ } catch (error) {
588
+ for (const close of connections) await Effect11.runPromise(close);
589
+ await runtime.dispose();
590
+ throw error;
591
+ }
592
+ }
593
+
594
+ // ../../src/events-query.ts
595
+ var MAX_EVENT_PAGE_SIZE = 1e3;
596
+ var MAX_EVENT_TYPES = 32;
597
+ var sequence = (value) => {
598
+ if (value === null) return void 0;
599
+ const parsed = Number(value);
600
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : Number.NaN;
601
+ };
602
+ var parseEventsQuery = (params, pageSize) => {
603
+ const after = sequence(params.get("after")) ?? 0;
604
+ const before = sequence(params.get("before"));
605
+ const limit = sequence(params.get("limit")) ?? pageSize;
606
+ const order = params.get("order") ?? "asc";
607
+ const types = (params.get("type") ?? "").split(",").map((type) => type.trim()).filter(Boolean);
608
+ if (Number.isNaN(after) || Number.isNaN(before) || Number.isNaN(limit) || limit < 1 || limit > MAX_EVENT_PAGE_SIZE) return void 0;
609
+ if (order !== "asc" && order !== "desc" || types.length > MAX_EVENT_TYPES) return void 0;
610
+ return { after, ...before === void 0 ? {} : { before }, limit, types, order };
611
+ };
612
+ var eventsStatement = (journal, query) => {
613
+ const clauses = ["actor = ?", "seq >= ?"];
614
+ const parameters = [journal, query.after];
615
+ if (query.before !== void 0) {
616
+ clauses.push("seq < ?");
617
+ parameters.push(query.before);
618
+ }
619
+ if (query.types.length) {
620
+ clauses.push(`json_extract(event, '$.event.type') IN (${query.types.map(() => "?").join(", ")})`);
621
+ parameters.push(...query.types);
622
+ }
623
+ parameters.push(query.limit);
624
+ return { sql: `SELECT seq, event FROM experimental_events WHERE ${clauses.join(" AND ")} ORDER BY seq ${query.order === "desc" ? "DESC" : "ASC"} LIMIT ?`, parameters };
625
+ };
626
+ var eventsPage = (rows, query) => ({
627
+ items: rows.map((row) => ({ ...JSON.parse(row.event), seq: row.seq })),
628
+ cursor: query.order === "desc" ? rows.length ? rows[rows.length - 1].seq : query.before ?? 0 : rows.length ? rows[rows.length - 1].seq + 1 : query.after
629
+ });
630
+
631
+ // ../../src/platform/cloudflare/router.ts
632
+ import { Effect as Effect16, Layer as Layer9 } from "effect";
633
+
634
+ // ../../src/services/actor-router.ts
635
+ import { Context as Context8, Data as Data4 } from "effect";
636
+ var ActorRouterError = class extends Data4.TaggedError("ActorRouterError") {
637
+ };
638
+ var ActorRouter = class extends Context8.Service()("tardigrade-cloud/ActorRouter") {
639
+ };
640
+
641
+ // ../../src/services/actor-runtime.ts
642
+ import { Context as Context9, Data as Data5 } from "effect";
643
+ var ActorRuntimeError = class extends Data5.TaggedError("ActorRuntimeError") {
644
+ };
645
+ var ActorRuntime = class extends Context9.Service()("tardigrade-cloud/ActorRuntime") {
646
+ };
647
+
648
+ // ../../src/services/metadata-store.ts
649
+ import { Context as Context10, Data as Data6, Schema as Schema3 } from "effect";
650
+ var Actor = Schema3.Struct({
651
+ name: Schema3.NonEmptyString,
652
+ description: Schema3.String
653
+ }).annotate({ identifier: "Actor" });
654
+ var Version = Schema3.Struct({
655
+ id: Schema3.NonEmptyString,
656
+ actor: Schema3.NonEmptyString,
657
+ digest: Schema3.NonEmptyString
658
+ }).annotate({ identifier: "Version" });
659
+ var Deployment = Schema3.Struct({
660
+ id: Schema3.NonEmptyString,
661
+ version: Schema3.NonEmptyString
662
+ }).annotate({ identifier: "Deployment" });
663
+ var VersionRecord = Schema3.Struct({
664
+ ...Version.fields,
665
+ artifactDigest: Schema3.String.check(Schema3.isPattern(/^sha256:[a-f0-9]{64}$/))
666
+ }).annotate({ identifier: "VersionRecord" });
667
+ var MetadataStoreError = class extends Data6.TaggedError("MetadataStoreError") {
668
+ };
669
+ var MetadataStore = class extends Context10.Service()("tardigrade-cloud/MetadataStore") {
670
+ };
671
+
672
+ // ../../src/platform/router.ts
673
+ import { Effect as Effect15, Option as Option2 } from "effect";
674
+
675
+ // ../../src/platform/cloudflare/router.ts
676
+ var actorObjectName = (address) => JSON.stringify([address.accountId, address.actorName]);
677
+
678
+ // ../../src/platform/cloudflare/runtime.ts
679
+ var createCloudflareExportingHost = (options) => createSqlExportingHost({ ...options, sql: SqliteClient_exports.layer({ storage: options.storage }), sync: () => options.storage.sync() });
680
+ var DEFAULT_EVENT_PAGE_SIZE = 100;
681
+ var READY_PATH = "/__tardigrade/ready";
682
+ var cloudflareActorObject = (options) => class {
683
+ constructor(ctx, env) {
684
+ this.ctx = ctx;
685
+ this.env = env;
686
+ }
687
+ ctx;
688
+ env;
689
+ active;
690
+ pending = Promise.resolve();
691
+ fetch(request) {
692
+ const run2 = this.pending.then(() => this.handle(request));
693
+ this.pending = run2.catch(() => {
694
+ });
695
+ return run2;
696
+ }
697
+ async handle(request) {
698
+ const accountId = request.headers.get("x-tardigrade-account");
699
+ const actorName = request.headers.get("x-tardigrade-actor");
700
+ const deploymentId = request.headers.get("x-tardigrade-deployment");
701
+ const versionId = request.headers.get("x-tardigrade-version");
702
+ const artifactDigest = request.headers.get("x-tardigrade-artifact");
703
+ if (!accountId || !actorName || !deploymentId || !versionId || !artifactDigest || request.headers.get("x-tardigrade-instance") !== accountId) return new Response("Missing routing identity", { status: 400 });
704
+ const deployment = { accountId, actorName, deploymentId, versionId, artifactDigest };
705
+ if (this.ctx.id.name !== actorObjectName(deployment)) return new Response("Object identity mismatch", { status: 403 });
706
+ const parts = new URL(request.url).pathname.split("/");
707
+ const ready = request.method === "GET" && new URL(request.url).pathname === READY_PATH;
708
+ try {
709
+ if (!ready && (parts[1] !== "v1" || parts[2] !== "actors" || decodeURIComponent(parts[3] ?? "") !== accountId)) return new Response("Account route mismatch", { status: 403 });
710
+ } catch {
711
+ return new Response("Invalid path", { status: 400 });
712
+ }
713
+ const key = JSON.stringify(deployment);
714
+ if (this.active?.deployment !== key) {
715
+ if (this.active) {
716
+ const previous = this.active;
717
+ this.active = void 0;
718
+ try {
719
+ await previous.app.dispose();
720
+ } finally {
721
+ await previous.host.close();
722
+ }
723
+ }
724
+ const loaded = await options.load(deployment, this.env);
725
+ if (loaded.actor.actorName !== actorName) return new Response("Loaded actor mismatch", { status: 409 });
726
+ const host = await createCloudflareExportingHost({ ...loaded, accountId, storage: this.ctx.storage });
727
+ this.active = { deployment: key, host, app: cloudflareHandler(host) };
728
+ }
729
+ if (ready) return new Response(null, { status: 204 });
730
+ const url = new URL(request.url);
731
+ const pageSize = options.eventPageSize ?? DEFAULT_EVENT_PAGE_SIZE;
732
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1) throw new Error("Event page size must be a positive integer.");
733
+ if (request.method === "GET" && parts.length === 7 && parts[6] === "events") {
734
+ const thread = decodeURIComponent(parts[5]);
735
+ if (!await Effect17.runPromise(this.active.host.getThread({ instance: accountId, thread }))) return new Response(null, { status: 404 });
736
+ const query = parseEventsQuery(url.searchParams, pageSize);
737
+ if (!query) return new Response(null, { status: 400 });
738
+ const statement = eventsStatement(JSON.stringify([actorName, accountId, "thread", thread, "events"]), query);
739
+ return Response.json(eventsPage([...this.ctx.storage.sql.exec(statement.sql, ...statement.parameters)], query));
740
+ }
741
+ if (request.method === "GET" && parts.length === 5 && parts[4] === "threads") {
742
+ const cursor = Number(url.searchParams.get("cursor") ?? 0);
743
+ if (!Number.isSafeInteger(cursor) || cursor < 0) return new Response(null, { status: 400 });
744
+ const store = await Effect17.runPromise(this.active.host.supervisorStore(accountId));
745
+ const threads = store.threads.get().filter((thread) => thread.status === "registered");
746
+ 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) } : {} });
747
+ }
748
+ if (request.method === "POST" && parts.length === 5 && parts[4] === "threads") {
749
+ const input = await request.clone().json().catch(() => null);
750
+ 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 });
751
+ }
752
+ 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);
753
+ }
754
+ };
755
+
756
+ // ../../src/platform/cloudflare/user-worker.ts
757
+ var secrets = (value) => {
758
+ if (value === void 0) return {};
759
+ const parsed = JSON.parse(value);
760
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || Object.values(parsed).some((item) => typeof item !== "string")) {
761
+ throw new Error("Actor secrets must be a JSON object of strings.");
762
+ }
763
+ return parsed;
764
+ };
765
+ var createActorWorker = (actor, DurableObject, services, actorContext) => {
766
+ const Handler = cloudflareActorObject({
767
+ load: async (deployment, env) => ({
768
+ actor,
769
+ ...actorContext ? { actorContext } : {},
770
+ services: (coordinate, runtime) => {
771
+ const platform = Layer10.mergeAll(
772
+ ConfigProvider.layer(ConfigProvider.fromUnknown(secrets(env.SECRETS))),
773
+ boundAiGateway(deployment.accountId, env.INFERENCE),
774
+ boundContainerService(env.WORKSPACE, coordinate.thread)
775
+ );
776
+ return services ? services(runtime, coordinate).pipe(Layer10.provideMerge(platform)) : platform;
777
+ },
778
+ analytics: cloudflareAnalytics(deployment.accountId, env.ANALYTICS),
779
+ destinationId: "aurora",
780
+ ...env.EXPORT_BATCH_SIZE === void 0 ? {} : { batchSize: Number(env.EXPORT_BATCH_SIZE) },
781
+ ...env.EXPORT_FLUSH_TIMEOUT_MS === void 0 ? {} : { flushTimeoutMs: Number(env.EXPORT_FLUSH_TIMEOUT_MS) }
782
+ })
783
+ });
784
+ return class Actor extends DurableObject {
785
+ handler;
786
+ accountId;
787
+ actorName;
788
+ constructor(ctx, env) {
789
+ super(ctx, env);
790
+ this.accountId = env.ACCOUNT_ID;
791
+ this.actorName = env.ACTOR_NAME;
792
+ this.handler = new Handler(ctx, env);
793
+ }
794
+ fetch(request) {
795
+ if (request.headers.get("x-tardigrade-account") !== this.accountId || request.headers.get("x-tardigrade-actor") !== this.actorName) {
796
+ return Promise.resolve(new Response("Actor identity mismatch", { status: 403 }));
797
+ }
798
+ return this.handler.fetch(request);
799
+ }
800
+ };
801
+ };
802
+ var actorWorkerFetch = (actor) => (request, env) => {
803
+ if (actor.actorName !== env.ACTOR_NAME || !env.ACCOUNT_ID || !env.DEPLOYMENT_ID || !env.VERSION_ID || !env.ARTIFACT_DIGEST || !env.TARDIGRADE_CLOUD) {
804
+ return Promise.resolve(new Response("Worker deployment identity mismatch", { status: 403 }));
805
+ }
806
+ const expected = {
807
+ "x-tardigrade-account": env.ACCOUNT_ID,
808
+ "x-tardigrade-instance": env.ACCOUNT_ID,
809
+ "x-tardigrade-actor": env.ACTOR_NAME,
810
+ "x-tardigrade-deployment": env.DEPLOYMENT_ID,
811
+ "x-tardigrade-version": env.VERSION_ID,
812
+ "x-tardigrade-artifact": env.ARTIFACT_DIGEST
813
+ };
814
+ for (const [key, value] of Object.entries(expected)) {
815
+ if (request.headers.get(key) !== value) return Promise.resolve(new Response("Worker routing identity mismatch", { status: 403 }));
816
+ }
817
+ const ready = request.method === "GET" && new URL(request.url).pathname === READY_PATH;
818
+ const parts = new URL(request.url).pathname.split("/");
819
+ try {
820
+ if (!ready && (parts[1] !== "v1" || parts[2] !== "actors" || decodeURIComponent(parts[3] ?? "") !== env.ACCOUNT_ID || !["threads", "methods", "mcp"].includes(parts[4] ?? ""))) {
821
+ return Promise.resolve(new Response("Worker account route mismatch", { status: 403 }));
822
+ }
823
+ } catch {
824
+ return Promise.resolve(new Response("Invalid worker route", { status: 400 }));
825
+ }
826
+ return env.TARDIGRADE_CLOUD.getByName(JSON.stringify([env.ACCOUNT_ID, env.ACTOR_NAME])).fetch(request);
827
+ };
828
+ export {
829
+ actorWorkerFetch,
830
+ createActorWorker
831
+ };