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.
- package/dist/actorctl.js +14755 -25132
- package/dist/user-worker.js +257 -117
- package/dist/worker/export.ts +10 -4
- package/dist/worker/models.ts +201 -0
- package/dist/worker/webhooks.ts +86 -0
- package/package.json +10 -10
package/dist/worker/export.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Event export
|
|
1
|
+
// Event export from Tardie journals to Tardigrade Cloud analytics.
|
|
2
2
|
// It copies committed thread journal rows from Durable Object SQLite into Aurora's actor_events table through the
|
|
3
3
|
// ANALYTICS binding, keeping the source_id and cursor scheme of the platform's built-in exporter so the API, the
|
|
4
4
|
// events view, and SQL read both kinds of actor the same way.
|
|
@@ -20,6 +20,7 @@ export interface EventExporterOptions {
|
|
|
20
20
|
readonly analytics: AnalyticsBinding | undefined
|
|
21
21
|
readonly accountId: string | undefined
|
|
22
22
|
readonly actorName: string | undefined
|
|
23
|
+
readonly thread?: string
|
|
23
24
|
readonly batchSize?: number
|
|
24
25
|
}
|
|
25
26
|
|
|
@@ -61,15 +62,20 @@ export function eventExporter(options: EventExporterOptions) {
|
|
|
61
62
|
rows("CREATE TABLE IF NOT EXISTS event_export_cursors (id TEXT PRIMARY KEY, position INTEGER NOT NULL CHECK (position >= 0))")
|
|
62
63
|
const prefix = JSON.stringify([actorName, accountId, "thread"]).slice(0, -1) + ","
|
|
63
64
|
const journals = rows<{ actor: string }>("SELECT DISTINCT actor FROM experimental_events WHERE substr(actor, 1, ?) = ? ORDER BY actor", prefix.length, prefix)
|
|
64
|
-
.map(row => row.actor).filter(
|
|
65
|
+
.map(row => ({ storageKey: row.actor, sourceKey: row.actor })).filter(row => row.storageKey.endsWith(',"events"]'))
|
|
66
|
+
// Native 0.44 thread objects each own a journal named "events". Preserve the
|
|
67
|
+
// analytics source naming used by actorctl while reading that per-thread journal.
|
|
68
|
+
if (options.thread && rows("SELECT 1 FROM experimental_events WHERE actor = ? LIMIT 1", "events").length) {
|
|
69
|
+
journals.push({ storageKey: "events", sourceKey: JSON.stringify([actorName, accountId, "thread", options.thread, "events"]) })
|
|
70
|
+
}
|
|
65
71
|
let batches = 0
|
|
66
72
|
for (const journal of journals) {
|
|
67
|
-
const sourceId = JSON.stringify([current, journal])
|
|
73
|
+
const sourceId = JSON.stringify([current, journal.sourceKey])
|
|
68
74
|
const cursorKey = JSON.stringify([accountId, sourceId, DESTINATION])
|
|
69
75
|
rows("INSERT INTO event_export_cursors (id, position) VALUES (?, 0) ON CONFLICT (id) DO NOTHING", cursorKey)
|
|
70
76
|
while (batches < MAX_BATCHES_PER_FLUSH) {
|
|
71
77
|
const cursor = rows<{ position: number }>("SELECT position FROM event_export_cursors WHERE id = ?", cursorKey)[0]!.position
|
|
72
|
-
const batch = rows<{ seq: number; event: string }>("SELECT seq, event FROM experimental_events WHERE actor = ? AND seq >= ? ORDER BY seq LIMIT ?", journal, cursor, batchSize)
|
|
78
|
+
const batch = rows<{ seq: number; event: string }>("SELECT seq, event FROM experimental_events WHERE actor = ? AND seq >= ? ORDER BY seq LIMIT ?", journal.storageKey, cursor, batchSize)
|
|
73
79
|
if (batch.length === 0) break
|
|
74
80
|
if (batch.some((row, index) => row.seq !== cursor + index)) throw new Error("Journal export page has a gap.")
|
|
75
81
|
const values = batch.map((_, index) => `(${Array.from({ length: 5 }, (_, field) => `$${index * 5 + field + 1}`).join(", ")})`).join(", ")
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Managed models for actors deployed to Tardigrade Cloud. An actor names a catalog model, e.g.
|
|
2
|
+
// "anthropic/claude-sonnet-5.5", and the platform's INFERENCE binding picks the host, protocol, and transport.
|
|
3
|
+
// The actor always sends its full prompt; the binding may send less upstream, but never needs the actor's help.
|
|
4
|
+
import { Effect, Layer, Schema, Stream } from "effect"
|
|
5
|
+
import { AiError, LanguageModel, Prompt, Response, Tool } from "effect/ai"
|
|
6
|
+
import * as TardieAi from "@tardie/ai"
|
|
7
|
+
import { liveModelServices } from "tardie/agent/services"
|
|
8
|
+
import { modelConfigOf } from "tardie/model/config"
|
|
9
|
+
import { layerModelLock } from "tardie/model/lock"
|
|
10
|
+
|
|
11
|
+
// --- Wire contract between the actor and the INFERENCE binding (Workers RPC; values are structured-clonable JSON). ---
|
|
12
|
+
|
|
13
|
+
export type JsonObject = { readonly [key: string]: unknown }
|
|
14
|
+
|
|
15
|
+
export interface ToolSpec {
|
|
16
|
+
readonly name: string
|
|
17
|
+
readonly description?: string
|
|
18
|
+
// parameters is a draft 2020-12 JSON Schema, as Tool.getJsonSchema produces.
|
|
19
|
+
readonly parameters: JsonObject
|
|
20
|
+
readonly strict?: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type ToolChoiceSpec =
|
|
24
|
+
| "auto" | "none" | "required"
|
|
25
|
+
| { readonly tool: string }
|
|
26
|
+
| { readonly mode?: "auto" | "required"; readonly oneOf: ReadonlyArray<string> }
|
|
27
|
+
|
|
28
|
+
export type ResponseFormatSpec =
|
|
29
|
+
| { readonly type: "text" }
|
|
30
|
+
| { readonly type: "json"; readonly objectName: string; readonly schema: JsonObject }
|
|
31
|
+
|
|
32
|
+
// ModelOptions are what change the answer, never how it is fetched. The host maps them per protocol.
|
|
33
|
+
export interface ModelOptions {
|
|
34
|
+
readonly maxOutputTokens?: number
|
|
35
|
+
readonly temperature?: number
|
|
36
|
+
readonly reasoning?: { readonly effort: "minimal" | "low" | "medium" | "high" | "xhigh" }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ModelRequest {
|
|
40
|
+
readonly model: string
|
|
41
|
+
readonly prompt: typeof Prompt.Prompt.Encoded
|
|
42
|
+
readonly tools: ReadonlyArray<ToolSpec>
|
|
43
|
+
readonly toolChoice: ToolChoiceSpec
|
|
44
|
+
readonly responseFormat: ResponseFormatSpec
|
|
45
|
+
readonly options?: ModelOptions
|
|
46
|
+
// session names the conversation (an actor thread) so the host can keep an upstream connection warm for it.
|
|
47
|
+
readonly session?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type EncodedAiError = typeof AiError.AiError.Encoded
|
|
51
|
+
export type GenerateResult = { readonly parts: ReadonlyArray<Response.PartEncoded> } | { readonly error: EncodedAiError }
|
|
52
|
+
// The stream body is newline-delimited JSON, one StreamFrame per line. An error frame ends the stream.
|
|
53
|
+
export type StreamFrame = { readonly part: Response.StreamPartEncoded } | { readonly error: EncodedAiError }
|
|
54
|
+
|
|
55
|
+
export interface ListedModel {
|
|
56
|
+
readonly id: string
|
|
57
|
+
readonly name: string
|
|
58
|
+
readonly contextWindowTokens: number
|
|
59
|
+
readonly maxOutputTokens: number
|
|
60
|
+
readonly pricing: { readonly promptUsdPerToken: number; readonly completionUsdPerToken: number; readonly cachedPromptUsdPerToken?: number; readonly cacheWritePromptUsdPerToken?: number }
|
|
61
|
+
readonly toolCall: boolean
|
|
62
|
+
readonly structuredOutput: boolean
|
|
63
|
+
readonly inputModalities: ReadonlyArray<string>
|
|
64
|
+
readonly outputModalities: ReadonlyArray<string>
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ModelBinding is the INFERENCE binding's model surface.
|
|
68
|
+
export interface ModelBinding {
|
|
69
|
+
readonly models: () => Promise<{ readonly data: ReadonlyArray<ListedModel> }>
|
|
70
|
+
readonly generate: (request: ModelRequest) => Promise<GenerateResult>
|
|
71
|
+
readonly stream: (request: ModelRequest) => Promise<ReadableStream<Uint8Array>>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const encodeAiError = (error: AiError.AiError): EncodedAiError => Schema.encodeSync(AiError.AiError)(error)
|
|
75
|
+
export const decodeAiError = (error: EncodedAiError): AiError.AiError => Schema.decodeSync(AiError.AiError)(error)
|
|
76
|
+
|
|
77
|
+
// --- Actor side ---
|
|
78
|
+
|
|
79
|
+
const failure = (method: string, description: string) => AiError.make({
|
|
80
|
+
module: "TardigradeModels", method,
|
|
81
|
+
reason: new AiError.NetworkError({ reason: "TransportError", method: "RPC", url: "rpc://INFERENCE", description })
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const invalid = (method: string, description: string) => AiError.make({ module: "TardigradeModels", method, reason: new AiError.InvalidRequestError({ description }) })
|
|
85
|
+
|
|
86
|
+
// requestOf turns effect/ai provider options into the wire request. Tools travel as JSON Schema; the host rebuilds them.
|
|
87
|
+
export const requestOf = (provider: LanguageModel.ProviderOptions, model: string, options: ModelOptions | undefined, session: string | undefined, method: string) => Effect.gen(function* () {
|
|
88
|
+
const tools: ToolSpec[] = []
|
|
89
|
+
for (const tool of provider.tools) {
|
|
90
|
+
if (Tool.isProviderDefined(tool)) return yield* invalid(method, `Provider-defined tool ${tool.name} is not served by managed models.`)
|
|
91
|
+
const description = Tool.getDescription(tool)
|
|
92
|
+
const strict = Tool.getStrictMode(tool)
|
|
93
|
+
tools.push({ name: tool.name, parameters: Tool.getJsonSchema(tool) as JsonObject, ...(description === undefined ? {} : { description }), ...(strict === undefined ? {} : { strict }) })
|
|
94
|
+
}
|
|
95
|
+
const prompt = yield* Schema.encodeEffect(Prompt.Prompt)(provider.prompt).pipe(Effect.mapError(error => invalid(method, `Prompt could not be encoded: ${error.message}`)))
|
|
96
|
+
const responseFormat: ResponseFormatSpec = provider.responseFormat.type === "text"
|
|
97
|
+
? { type: "text" }
|
|
98
|
+
: { type: "json", objectName: provider.responseFormat.objectName, schema: Tool.getJsonSchemaFromSchema(provider.responseFormat.schema) as JsonObject }
|
|
99
|
+
return {
|
|
100
|
+
model, prompt, tools, toolChoice: provider.toolChoice as ToolChoiceSpec, responseFormat,
|
|
101
|
+
...(options === undefined ? {} : { options }), ...(session === undefined ? {} : { session })
|
|
102
|
+
} satisfies ModelRequest
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
// managedLanguageModel is an effect/ai LanguageModel whose provider is the INFERENCE binding.
|
|
106
|
+
export const managedLanguageModel = (binding: ModelBinding, model: string, options?: ModelOptions, session?: string) => TardieAi.make({
|
|
107
|
+
generateText: provider => Effect.gen(function* () {
|
|
108
|
+
const request = yield* requestOf(provider, model, options, session, "generateText")
|
|
109
|
+
const result = yield* Effect.tryPromise({ try: () => binding.generate(request), catch: error => failure("generateText", String(error)) })
|
|
110
|
+
if ("error" in result) return yield* Effect.fail(decodeAiError(result.error))
|
|
111
|
+
return [...result.parts]
|
|
112
|
+
}),
|
|
113
|
+
streamText: provider => Stream.unwrap(Effect.gen(function* () {
|
|
114
|
+
const request = yield* requestOf(provider, model, options, session, "streamText")
|
|
115
|
+
const body = yield* Effect.tryPromise({ try: () => binding.stream(request), catch: error => failure("streamText", String(error)) })
|
|
116
|
+
return Stream.fromReadableStream({ evaluate: () => body, onError: error => failure("streamText", String(error)) }).pipe(
|
|
117
|
+
Stream.decodeText,
|
|
118
|
+
Stream.splitLines,
|
|
119
|
+
Stream.filter(line => line.length > 0),
|
|
120
|
+
Stream.mapEffect(line => {
|
|
121
|
+
const frame = JSON.parse(line) as StreamFrame
|
|
122
|
+
return "error" in frame ? Effect.fail(decodeAiError(frame.error)) : Effect.succeed(frame.part)
|
|
123
|
+
})
|
|
124
|
+
)
|
|
125
|
+
}))
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
export interface ManagedModelsOptions {
|
|
129
|
+
// default is the catalog model used unless the actor selects another; see GET /v1/models.
|
|
130
|
+
readonly default: string
|
|
131
|
+
// allow lists the other catalog models the actor may select. The default is always allowed.
|
|
132
|
+
readonly allow?: ReadonlyArray<string>
|
|
133
|
+
// options apply to every model, or per model ID.
|
|
134
|
+
readonly options?: ModelOptions | Readonly<Record<string, ModelOptions>>
|
|
135
|
+
// session names the conversation, normally the actor thread, so the host can reuse upstream connections.
|
|
136
|
+
readonly session?: string
|
|
137
|
+
readonly timeoutMs?: number | null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// MANAGED_PROVIDER is the provider name tardie sees; actors refer to models as { provider: "tardigrade", model_id }.
|
|
141
|
+
export const MANAGED_PROVIDER = "tardigrade"
|
|
142
|
+
const CREDENTIAL = "TARDIGRADE_MANAGED_MODELS"
|
|
143
|
+
// tardie requires a connection shape; the binding never reads it.
|
|
144
|
+
const CONNECTION = { baseUrl: "https://inference.tardigrade.internal/v1", protocol: "openai-chat-completions", env: [CREDENTIAL] } as const
|
|
145
|
+
|
|
146
|
+
const optionsFor = (settings: ManagedModelsOptions, model: string): ModelOptions | undefined => {
|
|
147
|
+
const options = settings.options
|
|
148
|
+
if (options === undefined) return undefined
|
|
149
|
+
const keys = Object.keys(options)
|
|
150
|
+
const perModel = keys.length > 0 && keys.every(key => key.includes("/"))
|
|
151
|
+
return perModel ? (options as Readonly<Record<string, ModelOptions>>)[model] : options as ModelOptions
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const lockOf = (models: ReadonlyArray<ListedModel>) => ({
|
|
155
|
+
schema: 2,
|
|
156
|
+
providers: { [MANAGED_PROVIDER]: CONNECTION },
|
|
157
|
+
models: models.map(model => ({
|
|
158
|
+
provider: MANAGED_PROVIDER, model_id: model.id,
|
|
159
|
+
contextWindowTokens: model.contextWindowTokens, maxOutputTokens: model.maxOutputTokens, pricing: model.pricing,
|
|
160
|
+
toolCall: model.toolCall, structuredOutput: model.structuredOutput,
|
|
161
|
+
inputModalities: [...model.inputModalities], outputModalities: [...model.outputModalities],
|
|
162
|
+
source: "https://api.tardigrade.sh/v1/models"
|
|
163
|
+
}))
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
// The catalog is read once per binding and isolate; a failed read is retried by the next caller.
|
|
167
|
+
const catalogs = new WeakMap<ModelBinding, Promise<{ readonly data: ReadonlyArray<ListedModel> }>>()
|
|
168
|
+
const catalogOf = (binding: ModelBinding) => {
|
|
169
|
+
let pending = catalogs.get(binding)
|
|
170
|
+
if (pending === undefined) {
|
|
171
|
+
pending = binding.models()
|
|
172
|
+
catalogs.set(binding, pending)
|
|
173
|
+
pending.catch(() => catalogs.delete(binding))
|
|
174
|
+
}
|
|
175
|
+
return pending
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// managedModels supplies tardie's model services from the platform catalog, read through the binding.
|
|
179
|
+
export const managedModels = (binding: ModelBinding, settings: ManagedModelsOptions) => Layer.unwrap(Effect.gen(function* () {
|
|
180
|
+
const wanted = [...new Set([settings.default, ...(settings.allow ?? [])])]
|
|
181
|
+
const listed = yield* Effect.tryPromise({ try: () => catalogOf(binding), catch: error => new Error(`Managed model catalog is unavailable: ${String(error)}`) })
|
|
182
|
+
const models = wanted.map(id => listed.data.find(model => model.id === id))
|
|
183
|
+
const missing = wanted.filter((_, index) => models[index] === undefined)
|
|
184
|
+
if (missing.length > 0) return yield* Effect.fail(new Error(`Not managed models: ${missing.join(", ")}. See GET /v1/models.`))
|
|
185
|
+
const catalog = models as ReadonlyArray<ListedModel>
|
|
186
|
+
const config = modelConfigOf({ allow: "*", providers: { [MANAGED_PROVIDER]: CONNECTION }, default: { provider: MANAGED_PROVIDER, model_id: settings.default } })
|
|
187
|
+
const lock = layerModelLock(lockOf(catalog), config)
|
|
188
|
+
const structured = new Set(catalog.filter(model => model.structuredOutput).map(model => model.id))
|
|
189
|
+
return liveModelServices({
|
|
190
|
+
credentials: { [CREDENTIAL]: "managed" },
|
|
191
|
+
...(settings.timeoutMs === undefined ? {} : { timeoutMs: settings.timeoutMs }),
|
|
192
|
+
configure: selected => ({ output: structured.has(selected.model_id) ? { guarantee: "native", withTools: true } : { guarantee: "none" } }),
|
|
193
|
+
providerLayer: provider => {
|
|
194
|
+
// tardie's policy lands in the provider config; carry its output ceiling unless the actor set one.
|
|
195
|
+
const ceiling = (provider.model.config as { max_output_tokens?: number } | undefined)?.max_output_tokens
|
|
196
|
+
const options = optionsFor(settings, provider.model.model)
|
|
197
|
+
const effective = ceiling === undefined || options?.maxOutputTokens !== undefined ? options : { ...options, maxOutputTokens: ceiling }
|
|
198
|
+
return Layer.effect(LanguageModel.LanguageModel, managedLanguageModel(binding, provider.model.model, effective, settings.session))
|
|
199
|
+
},
|
|
200
|
+
}).pipe(Layer.provideMerge(lock))
|
|
201
|
+
}).pipe(Effect.orDie))
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect"
|
|
2
|
+
import { InvalidMessage, MessageConflict } from "tardie/core"
|
|
3
|
+
import type { IncomingMessage, MessageReceipt, MessageSender, MessageTransport } from "tardie/core"
|
|
4
|
+
|
|
5
|
+
export const REPLY_TO_HEADER = "x-tardigrade-reply-to"
|
|
6
|
+
export const WEBHOOK_TRANSPORT = "tardigrade.webhook"
|
|
7
|
+
// REPLY_ACCEPTED echoes on the receipt so the API can tell a reply-aware host from one that ignored the address.
|
|
8
|
+
export const REPLY_ACCEPTED = "accepted"
|
|
9
|
+
export const CallMetadata = Schema.Record(Schema.String, Schema.String.check(Schema.isMaxLength(512))).check(
|
|
10
|
+
Schema.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.")
|
|
11
|
+
)
|
|
12
|
+
export const ReplyAddress = Schema.Struct({
|
|
13
|
+
webhook: Schema.NonEmptyString, account: Schema.NonEmptyString, actor: Schema.NonEmptyString, thread: Schema.NonEmptyString,
|
|
14
|
+
method: Schema.NonEmptyString, id: Schema.NonEmptyString, metadata: CallMetadata, url: Schema.String,
|
|
15
|
+
})
|
|
16
|
+
export type ReplyAddress = typeof ReplyAddress.Type
|
|
17
|
+
export interface WebhookBinding {
|
|
18
|
+
readonly enqueueReply: (address: ReplyAddress, body: Schema.Json, inReplyTo: string) => Promise<void>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// webhookTransport hands results to the platform outbox; customer HTTP never runs in the actor.
|
|
22
|
+
export const webhookTransport = (binding: WebhookBinding | undefined): MessageTransport => ({
|
|
23
|
+
deliver: (address, body, metadata) => Effect.tryPromise({
|
|
24
|
+
try: async () => {
|
|
25
|
+
const reply = Schema.decodeUnknownSync(ReplyAddress, { onExcessProperty: "error" })(address)
|
|
26
|
+
if (!binding) throw new Error("WEBHOOKS binding is required")
|
|
27
|
+
if (metadata.inReplyTo !== reply.id) throw new Error("Webhook reply identifies a different invocation")
|
|
28
|
+
await binding.enqueueReply(reply, body, metadata.inReplyTo)
|
|
29
|
+
return { id: metadata.id }
|
|
30
|
+
},
|
|
31
|
+
catch: cause => cause instanceof Error ? cause : new Error(String(cause)),
|
|
32
|
+
}),
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// receiveWebhookRequest runs after trusted routing and before methodHttp; lookup reads the original journal message and method state.
|
|
36
|
+
export async function receiveWebhookRequest(request: Request, options: {
|
|
37
|
+
readonly actor: string
|
|
38
|
+
readonly receive: (packet: IncomingMessage) => Promise<MessageReceipt>
|
|
39
|
+
readonly lookup: (instance: string, thread: string, id: string) => Promise<{ readonly method: string; readonly from: MessageSender; readonly state: Schema.Json } | undefined>
|
|
40
|
+
}): Promise<Response | undefined> {
|
|
41
|
+
try {
|
|
42
|
+
const path = new URL(request.url).pathname
|
|
43
|
+
const invoke = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/methods\/([^/]+)$/.exec(path)
|
|
44
|
+
if (request.method === "POST" && invoke && request.headers.has(REPLY_TO_HEADER)) {
|
|
45
|
+
const instance = decodeURIComponent(invoke[1]!), thread = decodeURIComponent(invoke[2]!), method = decodeURIComponent(invoke[3]!)
|
|
46
|
+
const id = request.headers.get("idempotency-key")
|
|
47
|
+
let address: ReplyAddress
|
|
48
|
+
try {
|
|
49
|
+
address = Schema.decodeUnknownSync(ReplyAddress, { onExcessProperty: "error" })(JSON.parse(request.headers.get(REPLY_TO_HEADER)!))
|
|
50
|
+
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")
|
|
51
|
+
} catch { return Response.json({ code: "invalid_message", message: "Invalid webhook reply address" }, { status: 400 }) }
|
|
52
|
+
const input = await request.json()
|
|
53
|
+
const receipt = await options.receive({ target: { actor: options.actor, instance, thread }, body: { method, input }, message: { id: id!, from: { transport: WEBHOOK_TRANSPORT, address } } })
|
|
54
|
+
return Response.json(receipt, { status: 202, headers: { [REPLY_TO_HEADER]: REPLY_ACCEPTED } })
|
|
55
|
+
}
|
|
56
|
+
const generic = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/calls\/([^/]+)(\/cancel)?$/.exec(path)
|
|
57
|
+
if (generic && ((request.method === "GET" && !generic[4]) || (request.method === "POST" && generic[4]))) {
|
|
58
|
+
const instance = decodeURIComponent(generic[1]!), thread = decodeURIComponent(generic[2]!), id = decodeURIComponent(generic[3]!)
|
|
59
|
+
const call = await options.lookup(instance, thread, id)
|
|
60
|
+
if (!call) return new Response(null, { status: 404 })
|
|
61
|
+
if (request.method === "GET") return Response.json({ id, method: call.method, ...(call.state as object) })
|
|
62
|
+
let reason: string
|
|
63
|
+
try { reason = Schema.decodeUnknownSync(Schema.Struct({ reason: Schema.String }), { onExcessProperty: "error" })(await request.json()).reason }
|
|
64
|
+
catch { return Response.json({ code: "invalid_message", message: "A cancellation reason is required" }, { status: 400 }) }
|
|
65
|
+
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 } })
|
|
66
|
+
return Response.json({ id }, { status: 202 })
|
|
67
|
+
}
|
|
68
|
+
const cancel = /^\/v1\/actors\/([^/]+)\/threads\/([^/]+)\/methods\/([^/]+)\/calls\/([^/]+)\/cancellation$/.exec(path)
|
|
69
|
+
if (request.method === "PUT" && cancel) {
|
|
70
|
+
const instance = decodeURIComponent(cancel[1]!), thread = decodeURIComponent(cancel[2]!), method = decodeURIComponent(cancel[3]!), id = decodeURIComponent(cancel[4]!)
|
|
71
|
+
const call = await options.lookup(instance, thread, id), from = call?.from
|
|
72
|
+
if (call?.method !== method || !from || !("transport" in from) || from.transport !== WEBHOOK_TRANSPORT) return undefined
|
|
73
|
+
let reason: string
|
|
74
|
+
try { reason = Schema.decodeUnknownSync(Schema.Struct({ reason: Schema.String }), { onExcessProperty: "error" })(await request.json()).reason }
|
|
75
|
+
catch { return Response.json({ code: "invalid_message", message: "A cancellation reason is required" }, { status: 400 }) }
|
|
76
|
+
await options.receive({ target: { actor: options.actor, instance, thread }, body: { method, cancel: { id, reason } }, message: { id: JSON.stringify(["cancel", method, id]), from } })
|
|
77
|
+
return Response.json({ id, method, thread, status: "requested" }, { status: 202 })
|
|
78
|
+
}
|
|
79
|
+
return undefined
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof InvalidMessage || error instanceof SyntaxError || error instanceof MessageConflict) {
|
|
82
|
+
return Response.json({ code: error instanceof MessageConflict ? "conflict" : "invalid_message", message: error.message }, { status: error instanceof MessageConflict ? 409 : 400 })
|
|
83
|
+
}
|
|
84
|
+
throw error
|
|
85
|
+
}
|
|
86
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "actorctl",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-rc.3",
|
|
4
4
|
"description": "Deploy actors, run threads, and read events on Tardigrade Cloud.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "UNLICENSED",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/clavia-labs/tardigrade-cloud.git",
|
|
10
|
+
"directory": "apps/cli"
|
|
11
|
+
},
|
|
7
12
|
"bin": {
|
|
8
13
|
"actorctl": "./dist/actorctl.js"
|
|
9
14
|
},
|
|
@@ -13,19 +18,14 @@
|
|
|
13
18
|
"engines": {
|
|
14
19
|
"bun": ">=1.2"
|
|
15
20
|
},
|
|
16
|
-
"scripts": {
|
|
17
|
-
"build": "bun build.ts",
|
|
18
|
-
"prepublishOnly": "bun build.ts"
|
|
19
|
-
},
|
|
20
21
|
"dependencies": {
|
|
21
22
|
"esbuild": "^0.28.2"
|
|
22
23
|
},
|
|
23
|
-
"devDependencies": {
|
|
24
|
-
"@effect/platform-bun": "4.0.0-rc.115",
|
|
25
|
-
"effect": "4.0.0-rc.115"
|
|
26
|
-
},
|
|
27
24
|
"peerDependencies": {
|
|
28
|
-
"effect": "4.
|
|
25
|
+
"effect": "4.1.2",
|
|
29
26
|
"tardie": "*"
|
|
27
|
+
},
|
|
28
|
+
"tardigrade": {
|
|
29
|
+
"sourceTree": "0bd988a99cccb41246ac29c73eaa35a04cf59019"
|
|
30
30
|
}
|
|
31
31
|
}
|