@chimp-labs/keel-ai-kit 0.0.0-stage → 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.
package/dist/agent.js ADDED
@@ -0,0 +1,886 @@
1
+ import { Cause, Context, Duration, Effect, Exit, Option, Queue, Schema, Stream, } from "effect";
2
+ import { randomUUID } from "node:crypto";
3
+ import { enforceServiceAuth, ensureTable, findById, insertRow, KeelBindSym, KeelDefaultLayerSym, KeelEnsureSym, KeelErrorMetaSym, KeelInfraSym, KeelKindSym, KeelMetaSym, RelationalStore, SearchEngine, searchHybrid, searchText, searchVector, selectRows, sendSignal, Signal, Table, updateById, VectorSearch, WorkflowStore, } from "@chimp-labs/keel";
4
+ import { toEffectSchema, } from "@chimp-labs/keel/sdk";
5
+ import { LlmMemoryLive, LlmProvider, } from "./llm.js";
6
+ import { SandboxRuntime, sandboxExec, sandboxReadText, sandboxWriteFile, withSandbox, } from "./sandbox.js";
7
+ // ---------------------------------------------------------------------------
8
+ // Typed Errors
9
+ // ---------------------------------------------------------------------------
10
+ export class AgentError extends Schema.TaggedError()("AgentError", {
11
+ agent: Schema.String,
12
+ runId: Schema.String,
13
+ cause: Schema.Unknown,
14
+ }) {
15
+ static [KeelErrorMetaSym] = {
16
+ category: "internal",
17
+ httpStatus: 500,
18
+ retryable: true,
19
+ };
20
+ }
21
+ export class AgentNotFoundError extends Schema.TaggedError()("AgentNotFoundError", {
22
+ agent: Schema.String,
23
+ runId: Schema.String,
24
+ }) {
25
+ static [KeelErrorMetaSym] = {
26
+ category: "not_found",
27
+ httpStatus: 404,
28
+ retryable: false,
29
+ };
30
+ }
31
+ export class AgentMaxStepsError extends Schema.TaggedError()("AgentMaxStepsError", {
32
+ agent: Schema.String,
33
+ runId: Schema.String,
34
+ maxSteps: Schema.Int,
35
+ }) {
36
+ static [KeelErrorMetaSym] = {
37
+ category: "internal",
38
+ httpStatus: 500,
39
+ retryable: false,
40
+ };
41
+ }
42
+ export class AgentApprovalRejectedError extends Schema.TaggedError()("AgentApprovalRejectedError", {
43
+ agent: Schema.String,
44
+ runId: Schema.String,
45
+ tool: Schema.String,
46
+ reason: Schema.optional(Schema.String),
47
+ }) {
48
+ static [KeelErrorMetaSym] = {
49
+ category: "forbidden",
50
+ httpStatus: 403,
51
+ retryable: false,
52
+ };
53
+ }
54
+ export class AgentApprovalTimeoutError extends Schema.TaggedError()("AgentApprovalTimeoutError", {
55
+ agent: Schema.String,
56
+ runId: Schema.String,
57
+ tool: Schema.String,
58
+ }) {
59
+ static [KeelErrorMetaSym] = {
60
+ category: "timeout",
61
+ httpStatus: 504,
62
+ retryable: true,
63
+ };
64
+ }
65
+ export class AgentToolError extends Schema.TaggedError()("AgentToolError", {
66
+ agent: Schema.String,
67
+ runId: Schema.String,
68
+ tool: Schema.String,
69
+ cause: Schema.Unknown,
70
+ }) {
71
+ static [KeelErrorMetaSym] = {
72
+ category: "internal",
73
+ httpStatus: 500,
74
+ retryable: false,
75
+ };
76
+ }
77
+ // ---------------------------------------------------------------------------
78
+ // Human-in-the-Loop Approval Signal Schema
79
+ // ---------------------------------------------------------------------------
80
+ export const AgentApprovalDecisionSchema = Schema.Struct({
81
+ callId: Schema.String,
82
+ approved: Schema.Boolean,
83
+ reason: Schema.optional(Schema.String),
84
+ approverId: Schema.optional(Schema.String),
85
+ modifiedInput: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
86
+ });
87
+ // ---------------------------------------------------------------------------
88
+ // JSON Schema Generation Helper (Effect v4 `Schema.toJsonSchemaDocument`)
89
+ // ---------------------------------------------------------------------------
90
+ export const schemaToJsonSchema = (schema) => {
91
+ try {
92
+ const doc = Schema.toJsonSchemaDocument(schema);
93
+ const root = doc.schema;
94
+ if (doc.definitions && Object.keys(doc.definitions).length > 0) {
95
+ return { ...root, $defs: doc.definitions };
96
+ }
97
+ return root;
98
+ }
99
+ catch {
100
+ return { type: "object", properties: {} };
101
+ }
102
+ };
103
+ export function agentTool(config) {
104
+ return {
105
+ name: config.name,
106
+ description: config.description,
107
+ input: toEffectSchema(config.input),
108
+ ...(config.output !== undefined ? { output: toEffectSchema(config.output) } : {}),
109
+ ...(config.auth !== undefined ? { auth: config.auth } : {}),
110
+ ...(config.iam !== undefined ? { iam: config.iam } : {}),
111
+ ...(config.requiresApproval !== undefined
112
+ ? { requiresApproval: config.requiresApproval }
113
+ : {}),
114
+ ...(config.resources !== undefined ? { resources: config.resources } : {}),
115
+ execute: (input, ctx) => {
116
+ const res = config.execute(input, ctx);
117
+ if (Effect.isEffect(res))
118
+ return res;
119
+ return Effect.tryPromise({
120
+ try: () => Promise.resolve(res),
121
+ catch: (err) => err,
122
+ });
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Declaratively exposes an existing Keel `Service` operation as a typed Agent
128
+ * tool — inheriting its input/output schemas, auto-generating JSON Schema,
129
+ * and enforcing its declared IAM permissions against `CurrentPrincipal`.
130
+ */
131
+ export const serviceTool = (service, opName, options) => {
132
+ const op = service.operations[opName];
133
+ const toolName = (options?.name ?? `${service.serviceName}_${opName}`);
134
+ const authRule = options?.auth ?? op.auth;
135
+ return {
136
+ name: toolName,
137
+ description: options?.description ??
138
+ `Invoke ${service.serviceName}.${opName} service operation`,
139
+ input: op.input,
140
+ output: op.output,
141
+ ...(authRule !== undefined ? { auth: authRule } : {}),
142
+ ...(service.iam !== undefined ? { iam: service.iam } : {}),
143
+ ...(options?.requiresApproval !== undefined
144
+ ? { requiresApproval: options.requiresApproval }
145
+ : {}),
146
+ resources: [service],
147
+ execute: (input) => Effect.flatMap(service, (svc) => svc[opName](input)),
148
+ };
149
+ };
150
+ const SandboxToolInputSchema = Schema.Struct({
151
+ command: Schema.String,
152
+ files: Schema.optional(Schema.Record(Schema.String, Schema.String)),
153
+ readPaths: Schema.optional(Schema.Array(Schema.String)),
154
+ cwd: Schema.optional(Schema.String),
155
+ });
156
+ /**
157
+ * Declaratively exposes a Keel `Sandbox` as a typed Agent tool for isolated
158
+ * code execution. Creates a scoped sandbox per call, writes optional files,
159
+ * executes `command`, reads optional `readPaths`, and destroys the sandbox.
160
+ */
161
+ export const sandboxTool = (sandbox, options) => {
162
+ const toolName = (options?.name ??
163
+ `sandbox_${sandbox.sandboxName.replace(/[^A-Za-z0-9_-]+/g, "_")}`);
164
+ return {
165
+ name: toolName,
166
+ description: options?.description ??
167
+ `Run a shell command inside the isolated "${sandbox.sandboxName}" sandbox (${sandbox.image})`,
168
+ input: SandboxToolInputSchema,
169
+ ...(options?.auth !== undefined ? { auth: options.auth } : {}),
170
+ ...(options?.iam !== undefined ? { iam: options.iam } : {}),
171
+ ...(options?.requiresApproval !== undefined
172
+ ? { requiresApproval: options.requiresApproval }
173
+ : {}),
174
+ resources: [sandbox],
175
+ execute: (input) => withSandbox(sandbox, (handle) => Effect.gen(function* () {
176
+ if (input.files) {
177
+ for (const [path, content] of Object.entries(input.files)) {
178
+ yield* sandboxWriteFile(handle, path, content);
179
+ }
180
+ }
181
+ const res = yield* sandboxExec(handle, input.command, {
182
+ ...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
183
+ ...(options?.defaultTimeout !== undefined
184
+ ? { timeout: options.defaultTimeout }
185
+ : {}),
186
+ });
187
+ const outFiles = {};
188
+ for (const path of input.readPaths ?? []) {
189
+ const text = yield* sandboxReadText(handle, path).pipe(Effect.catch(() => Effect.succeed("")));
190
+ outFiles[path] = text;
191
+ }
192
+ return {
193
+ exitCode: res.exitCode,
194
+ stdout: res.stdout,
195
+ stderr: res.stderr,
196
+ files: outFiles,
197
+ };
198
+ })),
199
+ };
200
+ };
201
+ const SearchToolInputSchema = Schema.Struct({
202
+ query: Schema.String,
203
+ limit: Schema.optional(Schema.Int),
204
+ filter: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
205
+ });
206
+ /**
207
+ * Declaratively exposes a Keel `SearchIndex` as a typed RAG retrieval tool
208
+ * supporting full-text BM25, vector KNN, or hybrid RRF search.
209
+ */
210
+ export const searchTool = (index, options) => {
211
+ const toolName = (options?.name ??
212
+ `search_${index.indexName.replace(/[^A-Za-z0-9_-]+/g, "_")}`);
213
+ const mode = options?.mode ?? (options?.embed ? "hybrid" : "text");
214
+ const defaultLimit = options?.defaultLimit ?? 5;
215
+ return {
216
+ name: toolName,
217
+ description: options?.description ??
218
+ `Search the "${index.indexName}" knowledge index (${mode} search)`,
219
+ input: SearchToolInputSchema,
220
+ ...(options?.auth !== undefined ? { auth: options.auth } : {}),
221
+ ...(options?.iam !== undefined ? { iam: options.iam } : {}),
222
+ ...(options?.requiresApproval !== undefined
223
+ ? { requiresApproval: options.requiresApproval }
224
+ : {}),
225
+ resources: [index],
226
+ execute: (input) => Effect.gen(function* () {
227
+ const limit = input.limit ?? defaultLimit;
228
+ if (mode === "text" || !options?.embed) {
229
+ return yield* searchText(index, input.query, {
230
+ limit,
231
+ ...(input.filter ? { filter: input.filter } : {}),
232
+ });
233
+ }
234
+ const vecRaw = options.embed(input.query);
235
+ const vector = Effect.isEffect(vecRaw)
236
+ ? yield* vecRaw
237
+ : yield* Effect.tryPromise({
238
+ try: () => vecRaw,
239
+ catch: (cause) => cause,
240
+ });
241
+ if (mode === "vector") {
242
+ return yield* searchVector(index, vector, {
243
+ limit,
244
+ ...(input.filter ? { filter: input.filter } : {}),
245
+ });
246
+ }
247
+ return yield* searchHybrid(index, {
248
+ query: input.query,
249
+ vector,
250
+ limit,
251
+ ...(input.filter ? { filter: input.filter } : {}),
252
+ });
253
+ }),
254
+ };
255
+ };
256
+ export const agentRunsTableName = (agentName) => `keel_agent_${agentName.toLowerCase().replace(/[^a-z0-9_]+/g, "_")}_runs`;
257
+ export const agentApprovalSignalName = (agentName) => `keel.agent.${agentName}.approval`;
258
+ const defaultAgentLlmLayer = () => LlmMemoryLive();
259
+ export const Agent = (agentName, config) => {
260
+ const tools = (config.tools ?? []);
261
+ const output = (config.output ?? Schema.String);
262
+ const maxSteps = config.maxSteps ?? 10;
263
+ const approvalTimeout = config.approvalTimeout ?? "24 hours";
264
+ const onApprovalRejected = config.onApprovalRejected ?? "return_to_model";
265
+ const tableName = agentRunsTableName(agentName);
266
+ const approvalSignalName = agentApprovalSignalName(agentName);
267
+ const referencedResources = [];
268
+ if (config.iam)
269
+ referencedResources.push(config.iam);
270
+ for (const t of tools) {
271
+ if (t.iam)
272
+ referencedResources.push(t.iam);
273
+ if (t.resources)
274
+ referencedResources.push(...t.resources);
275
+ }
276
+ const AgentClass = class {
277
+ static agentName = agentName;
278
+ static model = config.model;
279
+ static instructions = config.instructions;
280
+ static tools = tools;
281
+ static output = output;
282
+ static iam = config.iam;
283
+ static maxSteps = maxSteps;
284
+ static temperature = config.temperature;
285
+ static maxTokens = config.maxTokens;
286
+ static approvalTimeout = approvalTimeout;
287
+ static onApprovalRejected = onApprovalRejected;
288
+ static tableName = tableName;
289
+ static approvalSignalName = approvalSignalName;
290
+ static resources = referencedResources;
291
+ static [KeelKindSym] = "agent";
292
+ static [KeelMetaSym] = {
293
+ kind: "agent",
294
+ name: agentName,
295
+ model: config.model,
296
+ tools: tools.map((t) => t.name),
297
+ tableName,
298
+ hasApprovalTools: tools.some((t) => t.requiresApproval !== undefined && t.requiresApproval !== false),
299
+ };
300
+ static [KeelInfraSym] = () => ({
301
+ children: referencedResources,
302
+ });
303
+ static [KeelDefaultLayerSym] = defaultAgentLlmLayer;
304
+ static [KeelEnsureSym] = () => ensureAgentTable(AgentClass);
305
+ static [KeelBindSym] = (runner) => bindAgent(runner, AgentClass);
306
+ };
307
+ return AgentClass;
308
+ };
309
+ // ---------------------------------------------------------------------------
310
+ // Internal Durable Run Persistence Table & Approval Signal
311
+ // ---------------------------------------------------------------------------
312
+ const AgentRunRowSchema = Schema.Struct({
313
+ runId: Schema.String,
314
+ status: Schema.String,
315
+ messagesJson: Schema.String,
316
+ outputJson: Schema.NullOr(Schema.String),
317
+ pendingApprovalJson: Schema.NullOr(Schema.String),
318
+ stepCount: Schema.Int,
319
+ totalInputTokens: Schema.Int,
320
+ totalOutputTokens: Schema.Int,
321
+ error: Schema.NullOr(Schema.String),
322
+ createdAt: Schema.String,
323
+ updatedAt: Schema.String,
324
+ });
325
+ const tableCache = new Map();
326
+ const makeRunsTable = (tableName) => Table(tableName, {
327
+ select: AgentRunRowSchema,
328
+ insert: AgentRunRowSchema,
329
+ primaryKey: "runId",
330
+ columns: {
331
+ runId: { type: "text" },
332
+ status: { type: "text" },
333
+ messagesJson: { type: "text" },
334
+ outputJson: { type: "text", nullable: true },
335
+ pendingApprovalJson: { type: "text", nullable: true },
336
+ stepCount: { type: "integer" },
337
+ totalInputTokens: { type: "integer" },
338
+ totalOutputTokens: { type: "integer" },
339
+ error: { type: "text", nullable: true },
340
+ createdAt: { type: "text" },
341
+ updatedAt: { type: "text" },
342
+ },
343
+ });
344
+ const getRunsTable = (agent) => {
345
+ let tbl = tableCache.get(agent.tableName);
346
+ if (!tbl) {
347
+ tbl = makeRunsTable(agent.tableName);
348
+ tableCache.set(agent.tableName, tbl);
349
+ }
350
+ return tbl;
351
+ };
352
+ /** Deterministic Keel `Signal` used to approve or reject pending tool calls for an `Agent`. */
353
+ export const AgentApprovalSignal = (agent) => Signal(agent.approvalSignalName, { payload: AgentApprovalDecisionSchema });
354
+ const rowToRecord = (agentName, row) => ({
355
+ runId: row.runId,
356
+ agent: agentName,
357
+ status: row.status,
358
+ messages: JSON.parse(row.messagesJson),
359
+ output: row.outputJson !== null ? JSON.parse(row.outputJson) : undefined,
360
+ pendingApproval: row.pendingApprovalJson !== null
361
+ ? JSON.parse(row.pendingApprovalJson)
362
+ : undefined,
363
+ stepCount: row.stepCount,
364
+ totalInputTokens: row.totalInputTokens,
365
+ totalOutputTokens: row.totalOutputTokens,
366
+ error: row.error ?? undefined,
367
+ createdAt: row.createdAt,
368
+ updatedAt: row.updatedAt,
369
+ });
370
+ /** Ensures the internal durable runs `Table` for `agent` exists on `RelationalStore`. */
371
+ export const ensureAgentTable = (agent) => ensureTable(getRunsTable(agent));
372
+ /** Sends a human-in-the-loop approval or rejection `Signal` to a suspended agent run. */
373
+ export const approveAgentTool = (agent, runId, decision) => sendSignal(runId, AgentApprovalSignal(agent), decision);
374
+ /** Reads the current durable state, transcript, and pending approval of an agent run. */
375
+ export const getAgentRun = (agent, runId) => Effect.gen(function* () {
376
+ const tbl = getRunsTable(agent);
377
+ const rowOpt = yield* findById(tbl, runId).pipe(Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId, cause })));
378
+ if (Option.isNone(rowOpt)) {
379
+ return yield* new AgentNotFoundError({ agent: agent.agentName, runId });
380
+ }
381
+ return rowToRecord(agent.agentName, rowOpt.value);
382
+ });
383
+ /** Lists all persisted runs for an agent. */
384
+ export const listAgentRuns = (agent) => selectRows(getRunsTable(agent)).pipe(Stream.runCollect, Effect.map((rows) => rows.map((r) => rowToRecord(agent.agentName, r))), Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId: "*", cause })));
385
+ const awaitApprovalSignal = (agent, runId, callId, toolName, timeout) => Effect.gen(function* () {
386
+ const store = yield* WorkflowStore;
387
+ const sigName = agent.approvalSignalName;
388
+ const decode = Schema.decodeUnknownSync(AgentApprovalDecisionSchema);
389
+ const waitLoop = Effect.scoped(Effect.gen(function* () {
390
+ if (store.subscribeSignalsReady) {
391
+ const queue = yield* store.subscribeSignalsReady(runId, sigName);
392
+ // Drain already-queued signals first
393
+ while (true) {
394
+ const existing = yield* store.takeSignal(runId, sigName);
395
+ if (Option.isNone(existing))
396
+ break;
397
+ const dec = decode(existing.value);
398
+ if (dec.callId === callId)
399
+ return dec;
400
+ }
401
+ // Wait for live signal arrival
402
+ while (true) {
403
+ const rawExit = yield* Queue.take(queue).pipe(Effect.exit);
404
+ if (Exit.isFailure(rawExit)) {
405
+ return yield* new AgentApprovalTimeoutError({
406
+ agent: agent.agentName,
407
+ runId,
408
+ tool: toolName,
409
+ });
410
+ }
411
+ const dec = decode(rawExit.value);
412
+ if (dec.callId === callId)
413
+ return dec;
414
+ }
415
+ }
416
+ // Fallback: check queued then subscribe stream
417
+ while (true) {
418
+ const existing = yield* store.takeSignal(runId, sigName);
419
+ if (Option.isNone(existing))
420
+ break;
421
+ const dec = decode(existing.value);
422
+ if (dec.callId === callId)
423
+ return dec;
424
+ }
425
+ const matched = yield* store.subscribeSignals(runId, sigName).pipe(Stream.map((raw) => decode(raw)), Stream.filter((d) => d.callId === callId), Stream.runHead);
426
+ if (Option.isSome(matched))
427
+ return matched.value;
428
+ return yield* new AgentApprovalTimeoutError({
429
+ agent: agent.agentName,
430
+ runId,
431
+ tool: toolName,
432
+ });
433
+ }));
434
+ const timed = yield* waitLoop.pipe(Effect.timeoutOption(timeout));
435
+ if (Option.isNone(timed)) {
436
+ return yield* new AgentApprovalTimeoutError({
437
+ agent: agent.agentName,
438
+ runId,
439
+ tool: toolName,
440
+ });
441
+ }
442
+ return timed.value;
443
+ });
444
+ const parseStructuredOutput = (agent, runId, rawText) => {
445
+ if (agent.output === Schema.String) {
446
+ return Effect.succeed(rawText);
447
+ }
448
+ return Effect.try({
449
+ try: () => {
450
+ const trimmed = rawText.trim();
451
+ // Strip optional markdown ```json ... ``` fences
452
+ const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
453
+ const jsonStr = fenced ? fenced[1] : trimmed;
454
+ const parsed = JSON.parse(jsonStr);
455
+ return Schema.decodeUnknownSync(agent.output)(parsed);
456
+ },
457
+ catch: (cause) => new AgentError({
458
+ agent: agent.agentName,
459
+ runId,
460
+ cause: new Error(`Failed to decode structured agent output: ${cause instanceof Error ? cause.message : String(cause)}`),
461
+ }),
462
+ });
463
+ };
464
+ const isToolApprovalRequired = (tool, input, ctx) => {
465
+ if (!tool.requiresApproval)
466
+ return false;
467
+ if (typeof tool.requiresApproval === "function") {
468
+ return tool.requiresApproval(input, ctx);
469
+ }
470
+ return tool.requiresApproval === true;
471
+ };
472
+ /**
473
+ * Runs a durable multi-turn AI `Agent` backed by:
474
+ * - `LlmProvider` (swappable: Memory, OpenAI, Anthropic, Gemini, Bedrock, Ollama, OpenRouter, LiteLLM)
475
+ * - `WorkflowStore` (step-level journaling for crash-resume + live `Signal` human-in-the-loop approvals)
476
+ * - `RelationalStore` (persisted run transcripts, token usage, and pending approval state)
477
+ * - Optional tool dependencies (`Service`, `SandboxRuntime`, `SearchEngine`, `VectorSearch`, `IAM`)
478
+ */
479
+ export const runAgent = (agent, options) => Effect.gen(function* () {
480
+ const llm = yield* LlmProvider;
481
+ const wfStore = yield* WorkflowStore;
482
+ const runsTable = getRunsTable(agent);
483
+ const runId = options.runId ?? `agent_${randomUUID()}`;
484
+ const maxSteps = options.maxSteps ?? agent.maxSteps;
485
+ const approvalTimeout = options.approvalTimeout ?? agent.approvalTimeout;
486
+ const nowIso = () => new Date().toISOString();
487
+ // Ensure table exists (idempotent, works on Memory/SQLite/Postgres/SurrealDB)
488
+ const relOpt = yield* Effect.serviceOption(RelationalStore);
489
+ const hasRel = Option.isSome(relOpt);
490
+ if (hasRel) {
491
+ yield* ensureTable(runsTable).pipe(Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId, cause })));
492
+ }
493
+ // Build tool lookup & JSON Schema definitions for LLM
494
+ const toolMap = new Map();
495
+ const llmTools = [];
496
+ for (const tool of agent.tools) {
497
+ toolMap.set(tool.name, tool);
498
+ llmTools.push({
499
+ name: tool.name,
500
+ description: tool.description,
501
+ parameters: schemaToJsonSchema(tool.input),
502
+ });
503
+ }
504
+ const systemPrompt = typeof agent.instructions === "function"
505
+ ? agent.instructions({ metadata: options.metadata })
506
+ : agent.instructions;
507
+ // Load or initialize durable run record
508
+ let messages = [];
509
+ let stepCount = 0;
510
+ let totalInputTokens = 0;
511
+ let totalOutputTokens = 0;
512
+ let createdAt = nowIso();
513
+ let existingRow;
514
+ if (hasRel) {
515
+ const found = yield* findById(runsTable, runId).pipe(Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId, cause })));
516
+ if (Option.isSome(found)) {
517
+ existingRow = found.value;
518
+ messages = [...JSON.parse(found.value.messagesJson)];
519
+ stepCount = found.value.stepCount;
520
+ totalInputTokens = found.value.totalInputTokens;
521
+ totalOutputTokens = found.value.totalOutputTokens;
522
+ createdAt = found.value.createdAt;
523
+ }
524
+ }
525
+ if (messages.length === 0) {
526
+ messages.push({ role: "system", content: systemPrompt });
527
+ }
528
+ // Append prompt unless we are crash-resuming an in-flight turn whose prompt is already recorded
529
+ const lastMsg = messages[messages.length - 1];
530
+ const isCrashResumeSamePrompt = existingRow?.status === "running" ||
531
+ existingRow?.status === "waiting_approval" ||
532
+ (lastMsg?.role === "user" && lastMsg.content === options.prompt);
533
+ if (!isCrashResumeSamePrompt) {
534
+ messages.push({ role: "user", content: options.prompt });
535
+ }
536
+ // Determine invocation epoch so multi-turn continuations get fresh journal keys
537
+ // while crash-resumes of an incomplete invocation replay exact step keys!
538
+ const invocationStepKey = `invocation:active`;
539
+ const existingInvStep = yield* wfStore.getStep(runId, invocationStepKey);
540
+ const invocationBaseStep = Option.isSome(existingInvStep) &&
541
+ typeof existingInvStep.value.output?.baseStep === "number" &&
542
+ existingInvStep.value.output?.completed === false
543
+ ? existingInvStep.value.output.baseStep
544
+ : stepCount;
545
+ yield* wfStore.saveStep({
546
+ id: `${runId}:${invocationStepKey}`,
547
+ runId,
548
+ stepName: invocationStepKey,
549
+ status: "completed",
550
+ output: { baseStep: invocationBaseStep, completed: false },
551
+ createdAt: nowIso(),
552
+ });
553
+ const persistRun = (patch) => {
554
+ if (!hasRel)
555
+ return Effect.void;
556
+ const row = {
557
+ runId,
558
+ status: patch.status,
559
+ messagesJson: JSON.stringify(messages),
560
+ outputJson: patch.output !== undefined ? JSON.stringify(patch.output) : null,
561
+ pendingApprovalJson: patch.pendingApproval !== undefined
562
+ ? JSON.stringify(patch.pendingApproval)
563
+ : null,
564
+ stepCount,
565
+ totalInputTokens,
566
+ totalOutputTokens,
567
+ error: patch.error ?? null,
568
+ createdAt,
569
+ updatedAt: nowIso(),
570
+ };
571
+ if (!existingRow) {
572
+ existingRow = row;
573
+ return insertRow(runsTable, row).pipe(Effect.asVoid, Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId, cause })));
574
+ }
575
+ existingRow = row;
576
+ return updateById(runsTable, runId, row).pipe(Effect.asVoid, Effect.mapError((cause) => new AgentError({ agent: agent.agentName, runId, cause })));
577
+ };
578
+ yield* persistRun({ status: "running" });
579
+ const responseSchema = agent.output !== Schema.String
580
+ ? schemaToJsonSchema(agent.output)
581
+ : undefined;
582
+ // Durable ReAct / Tool-Calling Loop
583
+ for (let localTurn = 0; localTurn < maxSteps; localTurn++) {
584
+ const turnNumber = invocationBaseStep + localTurn + 1;
585
+ const llmStepName = `turn:${turnNumber}:llm`;
586
+ // 1. Journaled LLM Call (replays cached response on crash-resume!)
587
+ const cachedLlm = yield* wfStore.getStep(runId, llmStepName);
588
+ let response;
589
+ if (Option.isSome(cachedLlm)) {
590
+ response = cachedLlm.value.output;
591
+ }
592
+ else {
593
+ response = yield* llm.generate({
594
+ model: agent.model,
595
+ messages,
596
+ ...(llmTools.length > 0 ? { tools: llmTools } : {}),
597
+ ...(options.temperature ?? agent.temperature !== undefined
598
+ ? { temperature: options.temperature ?? agent.temperature }
599
+ : {}),
600
+ ...(options.maxTokens ?? agent.maxTokens !== undefined
601
+ ? { maxTokens: options.maxTokens ?? agent.maxTokens }
602
+ : {}),
603
+ ...(responseSchema !== undefined ? { responseSchema } : {}),
604
+ ...(options.metadata !== undefined
605
+ ? { metadata: options.metadata }
606
+ : {}),
607
+ });
608
+ yield* wfStore.saveStep({
609
+ id: `${runId}:${llmStepName}`,
610
+ runId,
611
+ stepName: llmStepName,
612
+ status: "completed",
613
+ output: response,
614
+ createdAt: nowIso(),
615
+ });
616
+ }
617
+ stepCount = Math.max(stepCount, turnNumber);
618
+ if (!Option.isSome(cachedLlm) && response.usage) {
619
+ totalInputTokens += response.usage.inputTokens;
620
+ totalOutputTokens += response.usage.outputTokens;
621
+ }
622
+ // Append assistant turn if not already present at this position
623
+ const assistantMsg = {
624
+ role: "assistant",
625
+ content: response.content,
626
+ ...(response.toolCalls.length > 0
627
+ ? { toolCalls: response.toolCalls }
628
+ : {}),
629
+ };
630
+ const prevMsg = messages[messages.length - 1];
631
+ const alreadyAppended = prevMsg?.role === "assistant" &&
632
+ prevMsg.content === assistantMsg.content &&
633
+ JSON.stringify(prevMsg.toolCalls ?? []) ===
634
+ JSON.stringify(assistantMsg.toolCalls ?? []);
635
+ if (!alreadyAppended) {
636
+ messages.push(assistantMsg);
637
+ }
638
+ // 2. Final Answer (no tool calls requested)
639
+ if (response.toolCalls.length === 0) {
640
+ const parsedOutput = yield* parseStructuredOutput(agent, runId, response.content);
641
+ yield* wfStore.saveStep({
642
+ id: `${runId}:${invocationStepKey}`,
643
+ runId,
644
+ stepName: invocationStepKey,
645
+ status: "completed",
646
+ output: { baseStep: stepCount, completed: true },
647
+ createdAt: nowIso(),
648
+ });
649
+ yield* persistRun({ status: "completed", output: parsedOutput });
650
+ return {
651
+ runId,
652
+ agent: agent.agentName,
653
+ output: parsedOutput,
654
+ messages,
655
+ stepCount,
656
+ totalInputTokens,
657
+ totalOutputTokens,
658
+ };
659
+ }
660
+ // 3. Execute Each Tool Call (Journaled + IAM-Enforced + Signal Approval)
661
+ for (const call of response.toolCalls) {
662
+ const toolStepName = `turn:${turnNumber}:tool:${call.id}`;
663
+ const cachedTool = yield* wfStore.getStep(runId, toolStepName);
664
+ let toolResultMsg;
665
+ if (Option.isSome(cachedTool)) {
666
+ toolResultMsg = cachedTool.value.output;
667
+ }
668
+ else {
669
+ const tool = toolMap.get(call.name);
670
+ if (!tool) {
671
+ toolResultMsg = {
672
+ role: "tool",
673
+ toolCallId: call.id,
674
+ name: call.name,
675
+ content: JSON.stringify({
676
+ error: `Unknown tool "${call.name}"`,
677
+ }),
678
+ isError: true,
679
+ };
680
+ }
681
+ else {
682
+ // Decode & validate tool arguments via Schema
683
+ const decodedInputExit = yield* Effect.try({
684
+ try: () => Schema.decodeUnknownSync(tool.input)(call.arguments),
685
+ catch: (cause) => cause,
686
+ }).pipe(Effect.exit);
687
+ if (Exit.isFailure(decodedInputExit)) {
688
+ toolResultMsg = {
689
+ role: "tool",
690
+ toolCallId: call.id,
691
+ name: call.name,
692
+ content: JSON.stringify({
693
+ error: `Invalid tool input: ${String(Cause.squash(decodedInputExit.cause))}`,
694
+ }),
695
+ isError: true,
696
+ };
697
+ }
698
+ else {
699
+ let effectiveInput = decodedInputExit.value;
700
+ const toolCtx = {
701
+ agent: agent.agentName,
702
+ runId,
703
+ callId: call.id,
704
+ step: turnNumber,
705
+ };
706
+ // Enforce tool-level / service-level IAM permissions against CurrentPrincipal
707
+ const effectiveIam = tool.iam ?? agent.iam;
708
+ if (tool.auth !== undefined && effectiveIam !== undefined) {
709
+ yield* enforceServiceAuth(effectiveIam, tool.auth, effectiveInput, {
710
+ service: `agent:${agent.agentName}`,
711
+ operation: tool.name,
712
+ }).pipe(Effect.tapError((err) => persistRun({
713
+ status: "failed",
714
+ error: `${err._tag}: ${"reason" in err ? err.reason : String(err)}`,
715
+ })));
716
+ }
717
+ // Human-in-the-loop approval via Signal (if required)
718
+ let approved = true;
719
+ let rejectionReason;
720
+ if (isToolApprovalRequired(tool, effectiveInput, toolCtx)) {
721
+ const approvalStepName = `turn:${turnNumber}:approval:${call.id}`;
722
+ const cachedApproval = yield* wfStore.getStep(runId, approvalStepName);
723
+ let decision;
724
+ if (Option.isSome(cachedApproval)) {
725
+ decision = cachedApproval.value.output;
726
+ }
727
+ else {
728
+ yield* persistRun({
729
+ status: "waiting_approval",
730
+ pendingApproval: {
731
+ callId: call.id,
732
+ tool: tool.name,
733
+ input: call.arguments,
734
+ requestedAt: nowIso(),
735
+ },
736
+ });
737
+ decision = yield* awaitApprovalSignal(agent, runId, call.id, tool.name, approvalTimeout).pipe(Effect.tapError((err) => persistRun({
738
+ status: "failed",
739
+ error: `${err._tag}`,
740
+ })));
741
+ yield* wfStore.saveStep({
742
+ id: `${runId}:${approvalStepName}`,
743
+ runId,
744
+ stepName: approvalStepName,
745
+ status: "completed",
746
+ output: decision,
747
+ createdAt: nowIso(),
748
+ });
749
+ yield* persistRun({ status: "running" });
750
+ }
751
+ approved = decision.approved;
752
+ rejectionReason = decision.reason;
753
+ if (approved && decision.modifiedInput !== undefined) {
754
+ effectiveInput = yield* Effect.try({
755
+ try: () => Schema.decodeUnknownSync(tool.input)(decision.modifiedInput),
756
+ catch: (cause) => new AgentToolError({
757
+ agent: agent.agentName,
758
+ runId,
759
+ tool: tool.name,
760
+ cause,
761
+ }),
762
+ });
763
+ }
764
+ }
765
+ if (!approved) {
766
+ if (agent.onApprovalRejected === "fail") {
767
+ yield* persistRun({
768
+ status: "failed",
769
+ error: `Approval rejected for tool "${tool.name}"${rejectionReason ? `: ${rejectionReason}` : ""}`,
770
+ });
771
+ return yield* new AgentApprovalRejectedError({
772
+ agent: agent.agentName,
773
+ runId,
774
+ tool: tool.name,
775
+ ...(rejectionReason !== undefined
776
+ ? { reason: rejectionReason }
777
+ : {}),
778
+ });
779
+ }
780
+ toolResultMsg = {
781
+ role: "tool",
782
+ toolCallId: call.id,
783
+ name: tool.name,
784
+ content: JSON.stringify({
785
+ approved: false,
786
+ error: `Tool call rejected by human approver${rejectionReason ? `: ${rejectionReason}` : ""}`,
787
+ }),
788
+ isError: true,
789
+ };
790
+ }
791
+ else {
792
+ // Execute tool cleanly and capture typed output or failure
793
+ const execExit = yield* tool
794
+ .execute(effectiveInput, toolCtx)
795
+ .pipe(Effect.exit);
796
+ if (Exit.isFailure(execExit)) {
797
+ const err = Cause.squash(execExit.cause);
798
+ // Propagate IAM Unauthorized/Forbidden errors immediately (fail-closed!)
799
+ if (err &&
800
+ typeof err === "object" &&
801
+ (err._tag === "UnauthorizedError" ||
802
+ err._tag === "ForbiddenError")) {
803
+ yield* persistRun({
804
+ status: "failed",
805
+ error: `${err._tag}: ${err.reason ?? ""}`,
806
+ });
807
+ return yield* Effect.fail(err);
808
+ }
809
+ toolResultMsg = {
810
+ role: "tool",
811
+ toolCallId: call.id,
812
+ name: tool.name,
813
+ content: JSON.stringify({
814
+ error: err instanceof Error
815
+ ? err.message
816
+ : typeof err === "object" && err !== null
817
+ ? err
818
+ : String(err),
819
+ }),
820
+ isError: true,
821
+ };
822
+ }
823
+ else {
824
+ const outVal = execExit.value;
825
+ toolResultMsg = {
826
+ role: "tool",
827
+ toolCallId: call.id,
828
+ name: tool.name,
829
+ content: typeof outVal === "string"
830
+ ? outVal
831
+ : JSON.stringify(outVal ?? null),
832
+ };
833
+ }
834
+ }
835
+ }
836
+ }
837
+ yield* wfStore.saveStep({
838
+ id: `${runId}:${toolStepName}`,
839
+ runId,
840
+ stepName: toolStepName,
841
+ status: "completed",
842
+ output: toolResultMsg,
843
+ createdAt: nowIso(),
844
+ });
845
+ }
846
+ // Avoid duplicate tool message on crash-resume
847
+ const alreadyHasToolMsg = messages.some((m) => m.role === "tool" && m.toolCallId === call.id);
848
+ if (!alreadyHasToolMsg) {
849
+ messages.push(toolResultMsg);
850
+ }
851
+ }
852
+ yield* persistRun({ status: "running" });
853
+ }
854
+ yield* persistRun({
855
+ status: "failed",
856
+ error: `Agent "${agent.agentName}" exceeded maxSteps (${maxSteps})`,
857
+ });
858
+ return yield* new AgentMaxStepsError({
859
+ agent: agent.agentName,
860
+ runId,
861
+ maxSteps,
862
+ });
863
+ });
864
+ /** Continues an existing durable multi-turn agent conversation on `runId`. */
865
+ export const continueAgent = (agent, runId, prompt, options) => runAgent(agent, { ...options, runId, prompt });
866
+ // ---------------------------------------------------------------------------
867
+ // Plain TypeScript SDK Binding (`bindAgent`, `BoundAgent`, `agent`)
868
+ // ---------------------------------------------------------------------------
869
+ export const bindAgent = (runner, agentDef) => ({
870
+ descriptor: agentDef,
871
+ ensure: (options) => runner.run(ensureAgentTable(agentDef), options),
872
+ run: (options) => runner.run(runAgent(agentDef, options), options),
873
+ continue: (runId, prompt, options) => runner.run(continueAgent(agentDef, runId, prompt, options), options),
874
+ approve: (runId, decision, options) => runner.run(approveAgentTool(agentDef, runId, decision), options),
875
+ getRun: (runId, options) => runner.run(getAgentRun(agentDef, runId), options),
876
+ listRuns: (options) => runner.run(listAgentRuns(agentDef), options),
877
+ });
878
+ /** Plain TypeScript SDK descriptor builder for `Agent` (supports Standard Schema v1 & `k.*`). */
879
+ export const agent = (agentName, config) => {
880
+ const { output, ...rest } = config;
881
+ return Agent(agentName, {
882
+ ...rest,
883
+ ...(output !== undefined ? { output: toEffectSchema(output) } : {}),
884
+ });
885
+ };
886
+ //# sourceMappingURL=agent.js.map