@swirls/looms 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/actor/cell.d.ts +3 -1
  3. package/dist/actor/cell.js +1 -0
  4. package/dist/actor/host.d.ts +3 -1
  5. package/dist/actor/host.js +1 -0
  6. package/dist/actor/routing.js +2 -1
  7. package/dist/agent/debugger/agent-chat.js +6 -5
  8. package/dist/agent/debugger/index.js +2 -1
  9. package/dist/agent/module.d.ts +207 -1
  10. package/dist/agent/module.js +31 -0
  11. package/dist/agent/scope.js +1 -0
  12. package/dist/agent/signals.d.ts +108 -15
  13. package/dist/agent/signals.js +70 -47
  14. package/dist/approval/debugger/approvals-view.js +1 -1
  15. package/dist/approval/index.d.ts +1 -0
  16. package/dist/approval/index.js +1 -0
  17. package/dist/approval/module.d.ts +42 -1
  18. package/dist/approval/module.js +53 -0
  19. package/dist/approval/scope.js +1 -0
  20. package/dist/approval/signals.d.ts +19 -13
  21. package/dist/approval/signals.js +25 -45
  22. package/dist/approval/steps.d.ts +11 -0
  23. package/dist/approval/steps.js +39 -0
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +49 -14
  26. package/dist/client/client.d.ts +231 -21
  27. package/dist/client/client.js +20 -2
  28. package/dist/cloudflare/delete-terminal-run-storage.d.ts +39 -0
  29. package/dist/cloudflare/delete-terminal-run-storage.js +98 -0
  30. package/dist/cloudflare/durable-object.d.ts +11 -1
  31. package/dist/cloudflare/durable-object.js +23 -0
  32. package/dist/cloudflare/index.d.ts +1 -0
  33. package/dist/cloudflare/index.js +1 -0
  34. package/dist/core/index.d.ts +1 -0
  35. package/dist/core/index.js +1 -0
  36. package/dist/core/module-scope.d.ts +50 -5
  37. package/dist/core/module-scope.js +22 -2
  38. package/dist/core/module.d.ts +29 -2
  39. package/dist/core/projection.d.ts +1 -0
  40. package/dist/core/published.d.ts +59 -1
  41. package/dist/core/published.js +97 -1
  42. package/dist/core/run-context.d.ts +50 -0
  43. package/dist/core/run-context.js +21 -1
  44. package/dist/core/signals.d.ts +56 -0
  45. package/dist/core/signals.js +93 -0
  46. package/dist/core/validate-event.d.ts +12 -1
  47. package/dist/core/validate-event.js +34 -11
  48. package/dist/debugger/app/assets/index-CO5gIvV8.css +2 -0
  49. package/dist/debugger/app/assets/{index-CMRl_aWQ.js → index-VTotlHcm.js} +2 -2
  50. package/dist/debugger/app/assets/routes-CEdsN9DO.js +47 -0
  51. package/dist/debugger/app/index.html +2 -2
  52. package/dist/debugger/index.d.ts +1 -1
  53. package/dist/debugger/index.js +1 -1
  54. package/dist/debugger/lib/cn.d.ts +1 -1
  55. package/dist/debugger/lib/cn.js +12 -1
  56. package/dist/debugger/plugin.d.ts +11 -1
  57. package/dist/debugger/plugin.js +41 -0
  58. package/dist/debugger/shell/debugger-shell.js +1 -1
  59. package/dist/debugger/shell/form-fields.d.ts +17 -0
  60. package/dist/debugger/shell/form-fields.js +38 -0
  61. package/dist/debugger/shell/run-action.d.ts +6 -0
  62. package/dist/debugger/shell/run-action.js +15 -0
  63. package/dist/debugger/shell/run-controls.js +3 -55
  64. package/dist/debugger/shell/schema-form.d.ts +10 -1
  65. package/dist/debugger/shell/schema-form.js +108 -10
  66. package/dist/debugger/shell/signal-form.d.ts +18 -0
  67. package/dist/debugger/shell/signal-form.js +185 -0
  68. package/dist/debugger/shell/start-form.js +2 -32
  69. package/dist/debugger/shell/use-debounced-preview.d.ts +22 -0
  70. package/dist/debugger/shell/use-debounced-preview.js +68 -0
  71. package/dist/evaluator/index.d.ts +1 -1
  72. package/dist/evaluator/index.js +1 -1
  73. package/dist/evaluator/module.d.ts +8 -1
  74. package/dist/evaluator/module.js +33 -0
  75. package/dist/evaluator/scope.js +1 -0
  76. package/dist/projectors/event-log-ops.d.ts +0 -6
  77. package/dist/projectors/event-log-ops.js +2 -12
  78. package/dist/projectors/event-log.d.ts +10 -5
  79. package/dist/projectors/event-log.js +26 -22
  80. package/dist/projectors/replica/columns.d.ts +41 -0
  81. package/dist/projectors/replica/columns.js +77 -0
  82. package/dist/projectors/replica/drizzle.d.ts +328 -57
  83. package/dist/projectors/replica/drizzle.js +18 -14
  84. package/dist/projectors/replica/migrations.d.ts +25 -5
  85. package/dist/projectors/replica/migrations.js +62 -14
  86. package/dist/projectors/replica/postgres.d.ts +12 -11
  87. package/dist/projectors/replica/postgres.js +12 -26
  88. package/dist/projectors/replica/sqlite-bun.d.ts +3 -1
  89. package/dist/projectors/replica/sqlite-bun.js +6 -2
  90. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -5
  91. package/dist/projectors/replica/sqlite-migrations.js +22 -9
  92. package/dist/projectors/replica/sqlite.d.ts +12 -11
  93. package/dist/projectors/replica/sqlite.js +23 -16
  94. package/dist/runtime/looms.d.ts +27 -36
  95. package/dist/runtime/looms.js +1 -0
  96. package/dist/runtime/runtime.js +7 -1
  97. package/dist/runtime/server/http.js +4 -2
  98. package/dist/runtime/server/routes/definitions.d.ts +1 -1
  99. package/dist/runtime/server/routes/definitions.js +58 -2
  100. package/dist/runtime/server/routes/runs.js +25 -1
  101. package/dist/runtime/types.d.ts +6 -1
  102. package/dist/schedule/module.d.ts +117 -1
  103. package/dist/schedule/module.js +30 -0
  104. package/dist/schedule/scope.js +1 -0
  105. package/dist/schedule/signals.d.ts +59 -7
  106. package/dist/schedule/signals.js +35 -17
  107. package/dist/testing/corpus-module.d.ts +1 -1
  108. package/dist/testing/index.js +2 -1
  109. package/dist/testing/module-examples.d.ts +6 -0
  110. package/dist/testing/module-examples.js +66 -0
  111. package/dist/workflow/module.d.ts +3 -1
  112. package/dist/workflow/module.js +13 -0
  113. package/dist/workflow/scope.js +1 -0
  114. package/package.json +1 -1
  115. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  116. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  117. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  118. /package/dist/evaluator/{signals.js → steps.js} +0 -0
@@ -1,51 +1,64 @@
1
- import { Predicate } from 'effect';
1
+ import { Predicate, Schema } from 'effect';
2
+ import { AgentSessionMessageSubmittedPayloadSchema } from './events.js';
2
3
  import { agentModule } from './scope.js';
4
+ const UserMessageInputSchema = Schema.Struct({
5
+ content: Schema.String,
6
+ });
7
+ const SteerInputSchema = Schema.Struct({
8
+ content: Schema.String,
9
+ interrupt: Schema.optional(Schema.Boolean),
10
+ });
11
+ const CancelAgentTurnInputSchema = Schema.Struct({
12
+ childThreadId: Schema.String,
13
+ });
3
14
  /**
4
15
  * Build the `agent.message.received` event for a conversational agent.
5
- * Send it with `looms.signal(runId, [userMessage('Also greet Maya')])`.
16
+ * Send it with `looms.signal(runId, [userMessage({ content: 'Also greet Maya' })])`.
6
17
  */
7
- export function userMessage(content, options = {}) {
8
- return agentModule.input('message.received', { message: { role: 'user', content } }, { threadId: options.threadId });
9
- }
18
+ export const userMessage = agentModule.signal({
19
+ description: 'Append a user message to a conversational agent.',
20
+ input: UserMessageInputSchema,
21
+ build: ({ content }) => agentModule.input('message.received', { message: { role: 'user', content } }),
22
+ });
10
23
  /**
11
24
  * Build the `agent.steered` event: inject a user message mid-run, optionally
12
25
  * interrupting the current turn so the agent replans immediately.
13
26
  */
14
- export function steer(content, options = {}) {
15
- return agentModule.input('steered', {
27
+ export const steer = agentModule.signal({
28
+ description: 'Inject a user message mid-run, optionally interrupting the current turn.',
29
+ input: SteerInputSchema,
30
+ build: ({ content, interrupt }) => agentModule.input('steered', {
16
31
  turn: 0,
17
- interrupt: options.interrupt ?? true,
32
+ interrupt: interrupt ?? true,
18
33
  message: { role: 'user', content },
19
- }, { threadId: options.threadId });
20
- }
34
+ }),
35
+ });
21
36
  /**
22
37
  * Build the `agent.turn.stopped` event. A conversational agent aborts its in-flight turn and
23
38
  * waits for the next message; an agent session cancels its active turn and stays open.
24
39
  */
25
- export function stopAgentTurn(options = {}) {
26
- return agentModule.input('turn.stopped', {}, { threadId: options.threadId });
27
- }
28
- export function submitAgentMessage(messageId, text, options = {}) {
29
- return agentModule.input('session.message.submitted', {
30
- messageId,
31
- text,
32
- delivery: options.delivery,
33
- activeChildThreadId: options.activeChildThreadId,
34
- }, {
35
- threadId: options.threadId,
36
- idempotencyKey: `agent-session-message:${messageId}`,
37
- });
38
- }
39
- export function cancelAgentTurn(childThreadId, options = {}) {
40
- return [
41
- agentModule.input('session.cancel.requested', {}, { threadId: options.threadId }),
40
+ export const stopAgentTurn = agentModule.signal({
41
+ description: 'Stop the in-flight agent turn without ending the run.',
42
+ build: () => agentModule.input('turn.stopped', {}),
43
+ });
44
+ export const submitAgentMessage = agentModule.signal({
45
+ description: 'Submit a message to an agent session.',
46
+ input: AgentSessionMessageSubmittedPayloadSchema,
47
+ build: (input) => agentModule.input('session.message.submitted', input, {
48
+ idempotencyKey: `agent-session-message:${input.messageId}`,
49
+ }),
50
+ });
51
+ export const cancelAgentTurn = agentModule.signal({
52
+ description: 'Cancel the active child turn of an agent session.',
53
+ input: CancelAgentTurnInputSchema,
54
+ build: ({ childThreadId }) => [
55
+ agentModule.input('session.cancel.requested', {}),
42
56
  {
43
57
  type: 'runtime.thread.cancel.requested',
44
58
  payload: { threadId: childThreadId },
45
- threadId: options.threadId,
46
59
  },
47
- ];
48
- }
60
+ ],
61
+ });
49
62
  function activeTurnFrom(value) {
50
63
  if (!Predicate.isObject(value) || !Predicate.isObject(value.activeTurn)) {
51
64
  return null;
@@ -62,27 +75,37 @@ function activeTurnFrom(value) {
62
75
  : null;
63
76
  }
64
77
  /** Events for one session message. A steer aimed at `activeChildThreadId` interrupts that turn in the same batch. */
65
- export function agentSessionMessageEvents(messageId, text, options = {}) {
66
- const events = [submitAgentMessage(messageId, text, options)];
67
- if (options.delivery === 'steer' && options.activeChildThreadId) {
68
- events.push(agentModule.input('steered', {
69
- turn: 0,
70
- messageId,
71
- message: { role: 'user', content: text },
72
- interrupt: true,
73
- }, { threadId: options.activeChildThreadId }));
74
- }
75
- return events;
76
- }
78
+ export const agentSessionMessageEvents = agentModule.signal({
79
+ description: 'Submit a session message, and steer the active child when delivery is steer.',
80
+ input: AgentSessionMessageSubmittedPayloadSchema,
81
+ build: (input) => {
82
+ const submitted = agentModule.input('session.message.submitted', input, {
83
+ idempotencyKey: `agent-session-message:${input.messageId}`,
84
+ });
85
+ if (input.delivery === 'steer' && input.activeChildThreadId) {
86
+ return [
87
+ submitted,
88
+ agentModule.input('steered', {
89
+ turn: 0,
90
+ messageId: input.messageId,
91
+ message: { role: 'user', content: input.text },
92
+ interrupt: true,
93
+ }, { threadId: input.activeChildThreadId }),
94
+ ];
95
+ }
96
+ return [submitted];
97
+ },
98
+ });
77
99
  export function sendAgentSessionMessage(client, runId, messageId, text, options = {}) {
78
100
  return client.getRun(runId).then((run) => {
79
101
  const threadId = options.threadId ?? run.rootThreadId ?? undefined;
80
102
  const active = options.delivery === 'steer' && threadId ? activeTurnFrom(run.threads[threadId]?.state) : null;
81
- return client.signal(runId, agentSessionMessageEvents(messageId, text, {
82
- ...options,
83
- threadId,
103
+ return client.signal(runId, agentSessionMessageEvents({
104
+ messageId,
105
+ text,
106
+ delivery: options.delivery,
84
107
  activeChildThreadId: active?.childThreadId,
85
- }));
108
+ }, { threadId }));
86
109
  });
87
110
  }
88
111
  export function cancelActiveAgentTurn(client, runId, options = {}) {
@@ -100,6 +123,6 @@ export function cancelActiveAgentTurn(client, runId, options = {}) {
100
123
  const cancelled = cancel(runId, active.childThreadId);
101
124
  return Promise.all([requested, cancelled]).then(([, result]) => result);
102
125
  }
103
- return client.signal(runId, cancelAgentTurn(active.childThreadId, { threadId }));
126
+ return client.signal(runId, cancelAgentTurn({ childThreadId: active.childThreadId }, { threadId }));
104
127
  });
105
128
  }
@@ -12,7 +12,7 @@ export function ApprovalsView({ runId }) {
12
12
  return _jsx("p", { className: "text-muted-foreground text-xs", children: "No approvals requested." });
13
13
  }
14
14
  function decide(approvalId, outcome) {
15
- void client.signal(runId, [decision(approvalId, outcome)]);
15
+ void client.signal(runId, [decision({ approvalId, choice: outcome })]);
16
16
  }
17
17
  return (_jsx("ul", { className: "grid gap-2", children: state.items.map((item) => (_jsxs("li", { className: "border-border bg-card/60 rounded-lg border p-2.5", children: [_jsxs("div", { className: "flex items-center gap-2 text-xs", children: [_jsx("span", { className: "min-w-0 flex-1 truncate font-medium", children: item.title || item.approvalId }), _jsx(StatusBadge, { status: item.status })] }), item.status === 'pending' && !finished ? (_jsxs("div", { className: "mt-2 flex gap-1.5", children: [_jsx(Button, { size: "xs", onClick: () => decide(item.approvalId, 'approve'), children: "Approve" }), _jsx(Button, { size: "xs", variant: "outline", onClick: () => decide(item.approvalId, 'reject'), children: "Reject" })] })) : null] }, item.approvalId))) }));
18
18
  }
@@ -3,4 +3,5 @@ export * from './scope';
3
3
  export * from './effects';
4
4
  export * from './projections';
5
5
  export * from './signals';
6
+ export * from './steps';
6
7
  export * from './module';
@@ -3,4 +3,5 @@ export * from './scope.js';
3
3
  export * from './effects.js';
4
4
  export * from './projections.js';
5
5
  export * from './signals.js';
6
+ export * from './steps.js';
6
7
  export * from './module.js';
@@ -1,3 +1,4 @@
1
+ import { gate } from './steps';
1
2
  export declare function approval(): import("@swirls/looms/core").RuntimeModule<"approval", import("@swirls/looms/core").EventCatalog<"approval", {
2
3
  requested: import("effect/Schema").Struct<{
3
4
  readonly approvalId: import("effect/Schema").String;
@@ -313,7 +314,26 @@ export declare function approval(): import("@swirls/looms/core").RuntimeModule<"
313
314
  readonly threadId: string | null;
314
315
  }[];
315
316
  }>;
316
- }, import("effect/Context").Service.Any> & {
317
+ }, import("effect/Context").Service.Any, {
318
+ decision: import("@swirls/looms/core").SignalDefinition<{
319
+ readonly approvalId: string;
320
+ readonly choice: "approve" | "reject" | {
321
+ readonly actionId: string;
322
+ readonly outcome: "approve" | "reject";
323
+ readonly payload?: import("effect/Schema").Json | undefined;
324
+ };
325
+ }, Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
326
+ readonly type: "approval.decided";
327
+ readonly payload: {
328
+ readonly approvalId: string;
329
+ readonly actionId: string;
330
+ readonly outcome: "approve" | "reject";
331
+ readonly payload?: import("effect/Schema").Json | undefined;
332
+ };
333
+ }>;
334
+ }, {
335
+ gate: typeof gate;
336
+ }> & {
317
337
  readonly effects: {
318
338
  request: import("@swirls/looms/core").LocalEffectDefinition<{
319
339
  readonly approvalId: string;
@@ -611,4 +631,25 @@ export declare function approval(): import("@swirls/looms/core").RuntimeModule<"
611
631
  }[];
612
632
  }>;
613
633
  };
634
+ readonly signals: {
635
+ decision: import("@swirls/looms/core").SignalDefinition<{
636
+ readonly approvalId: string;
637
+ readonly choice: "approve" | "reject" | {
638
+ readonly actionId: string;
639
+ readonly outcome: "approve" | "reject";
640
+ readonly payload?: import("effect/Schema").Json | undefined;
641
+ };
642
+ }, Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
643
+ readonly type: "approval.decided";
644
+ readonly payload: {
645
+ readonly approvalId: string;
646
+ readonly actionId: string;
647
+ readonly outcome: "approve" | "reject";
648
+ readonly payload?: import("effect/Schema").Json | undefined;
649
+ };
650
+ }>;
651
+ };
652
+ readonly steps: {
653
+ gate: typeof gate;
654
+ };
614
655
  };
@@ -2,9 +2,62 @@ import { defineModule } from '@swirls/looms/core';
2
2
  import { requestApprovalEffect } from './effects.js';
3
3
  import { pendingApprovals } from './projections.js';
4
4
  import { approvalModule } from './scope.js';
5
+ import { decision } from './signals.js';
6
+ import { gate } from './steps.js';
5
7
  export function approval() {
6
8
  return defineModule(approvalModule, () => ({
7
9
  effects: { request: requestApprovalEffect },
8
10
  projections: { pendingApprovals },
11
+ signals: { decision },
12
+ steps: { gate },
13
+ examples: [
14
+ {
15
+ name: 'a decision resolves the pending approval',
16
+ events: [
17
+ approvalModule.input('requested', {
18
+ approvalId: 'apr_1',
19
+ title: 'Charge $40',
20
+ description: 'Card charge',
21
+ actions: [{ id: 'approve', label: 'Approve', outcome: 'approve' }],
22
+ }, { threadId: 'thread_1' }),
23
+ decision({ approvalId: 'apr_1', choice: 'approve' }),
24
+ ],
25
+ projections: {
26
+ pendingApprovals: {
27
+ items: [
28
+ {
29
+ approvalId: 'apr_1',
30
+ title: 'Charge $40',
31
+ description: 'Card charge',
32
+ status: 'approved',
33
+ threadId: 'thread_1',
34
+ },
35
+ ],
36
+ },
37
+ },
38
+ },
39
+ {
40
+ name: 'a request without a description stays pending',
41
+ events: [
42
+ approvalModule.input('requested', {
43
+ approvalId: 'apr_2',
44
+ title: 'Refund',
45
+ actions: [{ id: 'approve', label: 'Approve', outcome: 'approve' }],
46
+ }, { threadId: 'thread_2' }),
47
+ ],
48
+ projections: {
49
+ pendingApprovals: {
50
+ items: [
51
+ {
52
+ approvalId: 'apr_2',
53
+ title: 'Refund',
54
+ status: 'pending',
55
+ threadId: 'thread_2',
56
+ },
57
+ ],
58
+ },
59
+ },
60
+ },
61
+ ],
9
62
  }));
10
63
  }
@@ -3,5 +3,6 @@ import { approvalCatalog } from './events.js';
3
3
  export const approvalModule = createModuleScope({
4
4
  namespace: 'approval',
5
5
  protocolVersion: '1.0.0',
6
+ description: 'Human gates that park a run until someone decides.',
6
7
  events: approvalCatalog,
7
8
  });
@@ -1,14 +1,5 @@
1
- import { type EventInput, type JsonValue, type RuntimeEffect } from '@swirls/looms/core';
2
- import type { ApprovalAction } from './events';
3
- export declare function gate(args: {
4
- title: string;
5
- description?: string;
6
- approvalId?: string;
7
- actions?: ApprovalAction[];
8
- schema?: JsonValue;
9
- /** Absolute epoch milliseconds. Decision and timer waits race; the first wins. */
10
- timeoutAt?: number;
11
- }): RuntimeEffect[];
1
+ import { Schema } from 'effect';
2
+ import { type JsonValue } from '@swirls/looms/core';
12
3
  export type ApprovalChoice = 'approve' | 'reject' | {
13
4
  actionId: string;
14
5
  outcome: 'approve' | 'reject';
@@ -16,6 +7,21 @@ export type ApprovalChoice = 'approve' | 'reject' | {
16
7
  };
17
8
  /**
18
9
  * Build the `approval.decided` event that resolves a pending gate.
19
- * Send it with `looms.signal(runId, [decision(approvalId, 'approve')])`.
10
+ * Send it with `looms.signal(runId, [decision({ approvalId, choice: 'approve' })])`.
20
11
  */
21
- export declare function decision(approvalId: string, choice: ApprovalChoice): EventInput;
12
+ export declare const decision: import("@swirls/looms/core").SignalDefinition<{
13
+ readonly approvalId: string;
14
+ readonly choice: "approve" | "reject" | {
15
+ readonly actionId: string;
16
+ readonly outcome: "approve" | "reject";
17
+ readonly payload?: Schema.Json | undefined;
18
+ };
19
+ }, Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
20
+ readonly type: "approval.decided";
21
+ readonly payload: {
22
+ readonly approvalId: string;
23
+ readonly actionId: string;
24
+ readonly outcome: "approve" | "reject";
25
+ readonly payload?: Schema.Json | undefined;
26
+ };
27
+ }>;
@@ -1,50 +1,30 @@
1
- import { createWaitId, invoke, isJsonString, wait, } from '@swirls/looms/core';
2
- import { requestApprovalEffect } from './effects.js';
1
+ import { Schema } from 'effect';
2
+ import { isJsonString } from '@swirls/looms/core';
3
3
  import { approvalModule } from './scope.js';
4
- export function gate(args) {
5
- const approvalId = args.approvalId ?? createWaitId('approval');
6
- const actions = args.actions ?? [
7
- { id: 'approve', label: 'Approve', outcome: 'approve' },
8
- { id: 'reject', label: 'Reject', outcome: 'reject' },
9
- ];
10
- const effects = [
11
- invoke(requestApprovalEffect, {
12
- approvalId,
13
- title: args.title,
14
- description: args.description,
15
- actions,
16
- schema: args.schema,
17
- }, `request_${approvalId}`),
18
- wait({
19
- waitId: createWaitId(approvalId, 'decision'),
20
- on: { type: 'approval.decided', match: { approvalId } },
21
- tag: { approvalId, raceId: approvalId },
22
- }),
23
- ];
24
- if (args.timeoutAt !== undefined) {
25
- if (!Number.isFinite(args.timeoutAt)) {
26
- throw new Error('Approval timeoutAt must be a finite epoch timestamp');
27
- }
28
- effects.push(wait({
29
- waitId: createWaitId(approvalId, 'timeout'),
30
- on: { timerAt: args.timeoutAt },
31
- tag: {
32
- approvalId,
33
- raceId: approvalId,
34
- outcome: 'timeout',
35
- error: `Approval ${approvalId} timed out`,
36
- },
37
- }));
38
- }
39
- return effects;
4
+ const ApprovalChoiceSchema = Schema.Union([
5
+ Schema.Literal('approve'),
6
+ Schema.Literal('reject'),
7
+ Schema.Struct({
8
+ actionId: Schema.String,
9
+ outcome: Schema.Union([Schema.Literal('approve'), Schema.Literal('reject')]),
10
+ payload: Schema.optional(Schema.Json),
11
+ }),
12
+ ]);
13
+ const DecisionInputSchema = Schema.Struct({
14
+ approvalId: Schema.String,
15
+ choice: ApprovalChoiceSchema,
16
+ });
17
+ function decidedFrom(approvalId, choice) {
18
+ return isJsonString(choice)
19
+ ? { approvalId, actionId: choice, outcome: choice }
20
+ : { approvalId, actionId: choice.actionId, outcome: choice.outcome, payload: choice.payload };
40
21
  }
41
22
  /**
42
23
  * Build the `approval.decided` event that resolves a pending gate.
43
- * Send it with `looms.signal(runId, [decision(approvalId, 'approve')])`.
24
+ * Send it with `looms.signal(runId, [decision({ approvalId, choice: 'approve' })])`.
44
25
  */
45
- export function decision(approvalId, choice) {
46
- const decided = isJsonString(choice)
47
- ? { approvalId, actionId: choice, outcome: choice }
48
- : { approvalId, actionId: choice.actionId, outcome: choice.outcome, payload: choice.payload };
49
- return approvalModule.input('decided', decided);
50
- }
26
+ export const decision = approvalModule.signal({
27
+ description: 'Resolve a pending approval gate.',
28
+ input: DecisionInputSchema,
29
+ build: ({ approvalId, choice }) => approvalModule.input('decided', decidedFrom(approvalId, choice)),
30
+ });
@@ -0,0 +1,11 @@
1
+ import { type JsonValue, type RuntimeEffect } from '@swirls/looms/core';
2
+ import type { ApprovalAction } from './events';
3
+ export declare function gate(args: {
4
+ title: string;
5
+ description?: string;
6
+ approvalId?: string;
7
+ actions?: ApprovalAction[];
8
+ schema?: JsonValue;
9
+ /** Absolute epoch milliseconds. Decision and timer waits race; the first wins. */
10
+ timeoutAt?: number;
11
+ }): RuntimeEffect[];
@@ -0,0 +1,39 @@
1
+ import { createWaitId, invoke, wait } from '@swirls/looms/core';
2
+ import { requestApprovalEffect } from './effects.js';
3
+ export function gate(args) {
4
+ const approvalId = args.approvalId ?? createWaitId('approval');
5
+ const actions = args.actions ?? [
6
+ { id: 'approve', label: 'Approve', outcome: 'approve' },
7
+ { id: 'reject', label: 'Reject', outcome: 'reject' },
8
+ ];
9
+ const effects = [
10
+ invoke(requestApprovalEffect, {
11
+ approvalId,
12
+ title: args.title,
13
+ description: args.description,
14
+ actions,
15
+ schema: args.schema,
16
+ }, `request_${approvalId}`),
17
+ wait({
18
+ waitId: createWaitId(approvalId, 'decision'),
19
+ on: { type: 'approval.decided', match: { approvalId } },
20
+ tag: { approvalId, raceId: approvalId },
21
+ }),
22
+ ];
23
+ if (args.timeoutAt !== undefined) {
24
+ if (!Number.isFinite(args.timeoutAt)) {
25
+ throw new Error('Approval timeoutAt must be a finite epoch timestamp');
26
+ }
27
+ effects.push(wait({
28
+ waitId: createWaitId(approvalId, 'timeout'),
29
+ on: { timerAt: args.timeoutAt },
30
+ tag: {
31
+ approvalId,
32
+ raceId: approvalId,
33
+ outcome: 'timeout',
34
+ error: `Approval ${approvalId} timed out`,
35
+ },
36
+ }));
37
+ }
38
+ return effects;
39
+ }
@@ -6,7 +6,7 @@ export declare const looms: Command.Command<"looms", {
6
6
  readonly url: string;
7
7
  }, {
8
8
  readonly url: string;
9
- }, CliError.UserError, never>;
9
+ }, CliError.UserError, Path.Path>;
10
10
  export declare const cliTestLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Stdio.Stdio | Terminal.Terminal, never, never>;
11
11
  /** Run the CLI with an explicit argv (for tests and programmatic use). */
12
12
  export declare const runCli: (argv: ReadonlyArray<string>) => Effect.Effect<void, CliError.CliError, Command.Environment>;
@@ -4,9 +4,9 @@ import { ChildProcessSpawner } from 'effect/unstable/process';
4
4
  import { steer as steerEvent } from '@swirls/looms/agent';
5
5
  import { decision } from '@swirls/looms/approval';
6
6
  import { createLoomsClient } from '@swirls/looms/client';
7
- import { stringifyJson, stringifyJsonPretty } from '@swirls/looms/core';
7
+ import { stringifyJson, stringifyJsonPretty, } from '@swirls/looms/core';
8
8
  import { postgresReplica } from '@swirls/looms/projectors/replica';
9
- import { generateReplicaMigrations, } from '@swirls/looms/projectors/replica/migrations';
9
+ import { generateReplicaMigrations, postgresReplicaMigrations, } from '@swirls/looms/projectors/replica/migrations';
10
10
  import {} from '@swirls/looms/projectors/replica/sqlite';
11
11
  import { openSqliteReplicaFile } from '@swirls/looms/projectors/replica/sqlite-bun';
12
12
  import { createLooms } from '@swirls/looms/runtime';
@@ -76,7 +76,7 @@ const approve = Command.make('approve', {
76
76
  }
77
77
  const outcome = accept ? 'approve' : 'reject';
78
78
  const { url } = yield* loomsBase;
79
- const result = yield* tryClient(() => clientFor(url).signal(runId, [decision(approvalId, outcome)]));
79
+ const result = yield* tryClient(() => clientFor(url).signal(runId, [decision({ approvalId, choice: outcome })]));
80
80
  yield* Console.log(stringifyJsonPretty(result));
81
81
  return undefined;
82
82
  })).pipe(Command.withDescription('Approve or reject a pending approval'), Command.withShortDescription('Decide an approval'));
@@ -103,7 +103,7 @@ const steer = Command.make('steer', {
103
103
  interrupt: Flag.boolean('interrupt').pipe(Flag.withDescription('Interrupt the current turn (use --no-interrupt to disable)'), Flag.withDefault(true)),
104
104
  }, Effect.fn('steer')(function* ({ runId, message, interrupt }) {
105
105
  const { url } = yield* loomsBase;
106
- const result = yield* tryClient(() => clientFor(url).signal(runId, [steerEvent(message.join(' '), { interrupt })]));
106
+ const result = yield* tryClient(() => clientFor(url).signal(runId, [steerEvent({ content: message.join(' '), interrupt })]));
107
107
  yield* Console.log(stringifyJsonPretty(result));
108
108
  })).pipe(Command.withDescription('Send a steering message to a running agent'), Command.withShortDescription('Steer an agent'));
109
109
  const tail = Command.make('tail', {
@@ -122,6 +122,36 @@ const tail = Command.make('tail', {
122
122
  })).pipe(Command.withDescription('Stream events for a run'), Command.withShortDescription('Tail run events'));
123
123
  const databaseFlag = Flag.string('database').pipe(Flag.withDescription('Postgres connection string, or a SQLite file path with --dialect sqlite (env DATABASE_URL)'), Flag.withFallbackConfig(Config.string('DATABASE_URL')));
124
124
  const dialectFlag = Flag.string('dialect').pipe(Flag.withDescription('Replica dialect: postgres (default) or sqlite'), Flag.withDefault('postgres'));
125
+ const configFlag = Flag.optional(Flag.string('config').pipe(Flag.withDescription('Module that exports the run attributes from defineRunAttributes, as `attributes` or default')));
126
+ const RunAttributeFieldsSchema = Schema.Record(Schema.String, Schema.Struct({
127
+ required: Schema.optional(Schema.Boolean),
128
+ index: Schema.optional(Schema.Boolean),
129
+ fieldName: Schema.optional(Schema.String),
130
+ }));
131
+ function configError(cause, userMessage) {
132
+ return new CliError.UserError({ cause, userMessage });
133
+ }
134
+ function loadAttributes(config) {
135
+ if (Option.isNone(config)) {
136
+ return Effect.succeed({});
137
+ }
138
+ return Effect.gen(function* () {
139
+ const path = yield* Path.Path;
140
+ const url = yield* path
141
+ .toFileUrl(path.resolve(config.value))
142
+ .pipe(Effect.mapError((cause) => configError(cause, `Invalid --config ${config.value}`)));
143
+ const exported = yield* Effect.tryPromise({
144
+ try: () => import(url.href).then((module) => module),
145
+ catch: (cause) => configError(cause, `Could not load --config ${config.value}: ${String(cause)}`),
146
+ });
147
+ const attributes = yield* Schema.decodeUnknownEffect(RunAttributeFieldsSchema)(exported.attributes ?? exported.default).pipe(Effect.mapError((cause) => configError(cause, `--config ${config.value} must export defineRunAttributes(...) as \`attributes\` or default`)));
148
+ yield* Effect.try({
149
+ try: () => postgresReplicaMigrations(attributes),
150
+ catch: (cause) => configError(cause, cause instanceof Error ? cause.message : String(cause)),
151
+ });
152
+ return attributes;
153
+ });
154
+ }
125
155
  function asDialect(value) {
126
156
  switch (value) {
127
157
  case 'postgres':
@@ -131,9 +161,9 @@ function asDialect(value) {
131
161
  return undefined;
132
162
  }
133
163
  }
134
- function openReplica(dialect, database, migrate) {
164
+ function openReplica(dialect, database, migrate, additionalFields) {
135
165
  if (dialect === 'sqlite') {
136
- const replica = openSqliteReplicaFile(database, migrate);
166
+ const replica = openSqliteReplicaFile(database, migrate, additionalFields);
137
167
  return {
138
168
  pendingMigrations: () => replica.pendingMigrations(),
139
169
  migrate: () => replica.migrate(),
@@ -141,7 +171,7 @@ function openReplica(dialect, database, migrate) {
141
171
  dispose: () => replica.dispose?.() ?? Promise.resolve(),
142
172
  };
143
173
  }
144
- const replica = postgresReplica({ url: database, migrate });
174
+ const replica = postgresReplica({ url: database, migrate, additionalFields });
145
175
  return {
146
176
  pendingMigrations: () => replica.pendingMigrations(),
147
177
  migrate: () => replica.migrate(),
@@ -154,8 +184,10 @@ const generate = Command.make('generate', {
154
184
  dialect: dialectFlag,
155
185
  journal: Flag.optional(Flag.string('journal').pipe(Flag.withDescription('Also update a migration journal. Only `drizzle` is supported, and only for Postgres'))),
156
186
  check: Flag.boolean('check').pipe(Flag.withDescription('Exit non-zero when a migration is pending, and write nothing'), Flag.withDefault(false)),
157
- }, Effect.fn('replica.generate')(function* ({ out, dialect, journal, check }) {
187
+ config: configFlag,
188
+ }, Effect.fn('replica.generate')(function* ({ out, dialect, journal, check, config }) {
158
189
  const parsed = asDialect(dialect);
190
+ const additionalFields = yield* loadAttributes(config);
159
191
  if (!parsed) {
160
192
  return yield* new CliError.UserError({
161
193
  cause: dialect,
@@ -175,8 +207,8 @@ const generate = Command.make('generate', {
175
207
  });
176
208
  }
177
209
  const generateOptions = Option.isSome(journal)
178
- ? { out, check, dialect: parsed, journal: 'drizzle' }
179
- : { out, check, dialect: parsed };
210
+ ? { out, check, dialect: parsed, additionalFields, journal: 'drizzle' }
211
+ : { out, check, dialect: parsed, additionalFields };
180
212
  const result = yield* tryClient(() => generateReplicaMigrations(generateOptions));
181
213
  if (check && result.pending.length > 0) {
182
214
  return yield* new CliError.UserError({
@@ -192,8 +224,9 @@ const generate = Command.make('generate', {
192
224
  }
193
225
  return yield* Effect.void;
194
226
  })).pipe(Command.withDescription('Write replica migrations the host does not already have'), Command.withShortDescription('Write replica SQL'));
195
- const migrate = Command.make('migrate', { database: databaseFlag, dialect: dialectFlag }, Effect.fn('replica.migrate')(function* ({ database, dialect }) {
227
+ const migrate = Command.make('migrate', { database: databaseFlag, dialect: dialectFlag, config: configFlag }, Effect.fn('replica.migrate')(function* ({ database, dialect, config }) {
196
228
  const parsed = asDialect(dialect);
229
+ const additionalFields = yield* loadAttributes(config);
197
230
  if (!parsed) {
198
231
  return yield* new CliError.UserError({
199
232
  cause: dialect,
@@ -206,7 +239,7 @@ const migrate = Command.make('migrate', { database: databaseFlag, dialect: diale
206
239
  userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
207
240
  });
208
241
  }
209
- const replica = openReplica(parsed, database, 'auto');
242
+ const replica = openReplica(parsed, database, 'auto', additionalFields);
210
243
  yield* tryClient(() => replica.migrate().then(() => replica.dispose()));
211
244
  return yield* Console.log('Looms replica migrations applied');
212
245
  })).pipe(Command.withDescription('Apply pending replica migrations'), Command.withShortDescription('Apply replica SQL'));
@@ -214,8 +247,10 @@ const status = Command.make('status', {
214
247
  database: databaseFlag,
215
248
  dialect: dialectFlag,
216
249
  run: Flag.optional(Flag.string('run').pipe(Flag.withDescription('Also print freshness for this run id'))),
217
- }, Effect.fn('replica.status')(function* ({ database, dialect, run }) {
250
+ config: configFlag,
251
+ }, Effect.fn('replica.status')(function* ({ database, dialect, run, config }) {
218
252
  const parsed = asDialect(dialect);
253
+ const additionalFields = yield* loadAttributes(config);
219
254
  if (!parsed) {
220
255
  return yield* new CliError.UserError({
221
256
  cause: dialect,
@@ -228,7 +263,7 @@ const status = Command.make('status', {
228
263
  userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
229
264
  });
230
265
  }
231
- const replica = openReplica(parsed, database, 'verify');
266
+ const replica = openReplica(parsed, database, 'verify', additionalFields);
232
267
  const pending = yield* tryClient(() => replica.pendingMigrations());
233
268
  yield* Console.log(pending.length === 0
234
269
  ? 'Looms replica schema is up to date'