@niwa-labs/workflow 0.0.0-stage → 0.0.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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/package.json +55 -4
  4. package/src/actions.ts +408 -0
  5. package/src/agent.ts +211 -0
  6. package/src/ask.ts +84 -0
  7. package/src/bridge.ts +710 -0
  8. package/src/catalogue.ts +74 -0
  9. package/src/check.ts +880 -0
  10. package/src/child.ts +1378 -0
  11. package/src/cockpit/actions.ts +128 -0
  12. package/src/cockpit/catalogue-actions.ts +97 -0
  13. package/src/cockpit/dashboard.tsx +134 -0
  14. package/src/cockpit/groups.ts +45 -0
  15. package/src/cockpit/index.tsx +50 -0
  16. package/src/cockpit/launch.tsx +136 -0
  17. package/src/cockpit/plan.ts +101 -0
  18. package/src/cockpit/run-commands.tsx +102 -0
  19. package/src/cockpit/run-page.tsx +140 -0
  20. package/src/cockpit/run-summary.ts +16 -0
  21. package/src/cockpit/runs.tsx +73 -0
  22. package/src/cockpit/statistics.tsx +176 -0
  23. package/src/cockpit/track.tsx +159 -0
  24. package/src/cockpit/workflows.tsx +383 -0
  25. package/src/describe-cache.ts +122 -0
  26. package/src/describe.ts +174 -0
  27. package/src/guide.ts +213 -0
  28. package/src/index.ts +2813 -0
  29. package/src/inspect.ts +235 -0
  30. package/src/installation.ts +90 -0
  31. package/src/language.ts +217 -0
  32. package/src/records-entry.ts +63 -0
  33. package/src/records.ts +574 -0
  34. package/src/registry.ts +250 -0
  35. package/src/revise.ts +89 -0
  36. package/src/runner.ts +339 -0
  37. package/src/script-types.ts +549 -0
  38. package/src/stats.ts +460 -0
  39. package/src/status.ts +512 -0
  40. package/src/store.ts +259 -0
  41. package/src/subscriptions.ts +102 -0
  42. package/src/waiting.ts +61 -0
  43. package/test/cockpit-actions.test.ts +20 -0
  44. package/test/cockpit-groups.test.ts +42 -0
  45. package/test/cockpit-plan.test.ts +118 -0
  46. package/test/fixtures/branches-host.ts +58 -0
  47. package/test/fixtures/branches-script.js +23 -0
  48. package/test/fixtures/bridge-host.ts +23 -0
  49. package/test/fixtures/bridge-keys-script.js +15 -0
  50. package/test/fixtures/bridge-wait-script.js +8 -0
  51. package/test/fixtures/cancel-host.ts +58 -0
  52. package/test/fixtures/cancel-script.js +12 -0
  53. package/test/fixtures/crash-host.ts +61 -0
  54. package/test/fixtures/crash-script.js +14 -0
  55. package/test/fixtures/ping-records.ts +20 -0
  56. package/test/fixtures/revision-host.ts +57 -0
  57. package/test/fixtures/revision-script.js +11 -0
  58. package/test/fixtures/running-host.ts +61 -0
  59. package/test/fixtures/running-script.js +12 -0
  60. package/test/fixtures/with-data/flow.ts +2 -0
  61. package/test/fixtures/with-data/table.json +1 -0
  62. package/test/git-repo.ts +45 -0
  63. package/test/git-worktree.test.ts +413 -0
  64. package/test/question-format.test.ts +279 -0
  65. package/test/workflow-agent-caps.test.ts +91 -0
  66. package/test/workflow-agent-lifetime.test.ts +93 -0
  67. package/test/workflow-agent-options.test.ts +216 -0
  68. package/test/workflow-agent-schema.test.ts +386 -0
  69. package/test/workflow-agent-typings.test.ts +241 -0
  70. package/test/workflow-ask-resume.test.ts +145 -0
  71. package/test/workflow-branch-keys.test.ts +133 -0
  72. package/test/workflow-bridge-inproc.test.ts +230 -0
  73. package/test/workflow-bridge.test.ts +141 -0
  74. package/test/workflow-builtin-candidate.test.ts +230 -0
  75. package/test/workflow-builtin.test.ts +197 -0
  76. package/test/workflow-cancel-agent.test.ts +144 -0
  77. package/test/workflow-cancel.test.ts +166 -0
  78. package/test/workflow-chain.test.ts +84 -0
  79. package/test/workflow-check-options.test.ts +144 -0
  80. package/test/workflow-check-uses.test.ts +148 -0
  81. package/test/workflow-check.test.ts +282 -0
  82. package/test/workflow-contract.test.ts +295 -0
  83. package/test/workflow-crash-resume.test.ts +141 -0
  84. package/test/workflow-deadline.test.ts +102 -0
  85. package/test/workflow-describe-cache.test.ts +240 -0
  86. package/test/workflow-directory.test.ts +73 -0
  87. package/test/workflow-emits.test.ts +261 -0
  88. package/test/workflow-group-keys.test.ts +72 -0
  89. package/test/workflow-harnesses.test.ts +262 -0
  90. package/test/workflow-inspect.test.ts +152 -0
  91. package/test/workflow-language-types.test.ts +148 -0
  92. package/test/workflow-manifest.test.ts +93 -0
  93. package/test/workflow-manual-pause.test.ts +116 -0
  94. package/test/workflow-owners.test.ts +154 -0
  95. package/test/workflow-pause.test.ts +200 -0
  96. package/test/workflow-phases.test.ts +445 -0
  97. package/test/workflow-plugin-entries.test.ts +59 -0
  98. package/test/workflow-record-refs.test.ts +310 -0
  99. package/test/workflow-replay.test.ts +206 -0
  100. package/test/workflow-resume-once.test.ts +188 -0
  101. package/test/workflow-revision.test.ts +216 -0
  102. package/test/workflow-scope.test.ts +505 -0
  103. package/test/workflow-script-defaults.test.ts +119 -0
  104. package/test/workflow-script-error.test.ts +228 -0
  105. package/test/workflow-script-libraries.test.ts +88 -0
  106. package/test/workflow-script-packages.test.ts +119 -0
  107. package/test/workflow-stdout.test.ts +89 -0
  108. package/test/workflow-stop.test.ts +299 -0
  109. package/test/workflow-store.test.ts +220 -0
  110. package/test/workflow-visible.test.ts +136 -0
  111. package/test/workflow-wait-version.test.ts +54 -0
  112. package/test/workflow-wait.test.ts +224 -0
  113. package/test/workflow-waiting-agent.test.ts +64 -0
  114. package/tsconfig.json +15 -0
@@ -0,0 +1,54 @@
1
+ // A script waits for a record type at the version the host knows it by: the version is not a part
2
+ // of what the script writes, so a type at its second version answers a wait by its name.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+
8
+ import { record } from "@niwa-labs/core";
9
+ import { plugin } from "@niwa-labs/plugin";
10
+ import { createNiwa, eventually, requests, tempHome, timers } from "@niwa-labs/testing";
11
+ import type { Host } from "@niwa-labs/testing";
12
+ import { z } from "zod";
13
+
14
+ import { workflow, workflowStart } from "../src/index.ts";
15
+
16
+ const homes: Array<{ cleanup(): Promise<void> }> = [];
17
+ const hosts: Host[] = [];
18
+
19
+ afterEach(async () => {
20
+ for (const host of hosts.splice(0)) await host.close().catch(() => {});
21
+ for (const home of homes.splice(0)) await home.cleanup();
22
+ }, 60_000);
23
+
24
+ /** A type at its second version: its records carry version 2. */
25
+ const Built = record("build.finished", z.object({ id: z.string(), green: z.boolean() }), { version: 2 });
26
+
27
+ test("a wait by name answers with a record of a type the host knows at its second version", async () => {
28
+ const home = await tempHome();
29
+ homes.push(home);
30
+ const host = createNiwa({ home: home.path });
31
+ host.use(requests(), timers([]), plugin("builds", (api) => api.declare(Built)), workflow());
32
+ await host.serve();
33
+ hosts.push(host);
34
+ await host.emit(Built, { id: "b-1", green: true });
35
+ await mkdir(home.path, { recursive: true });
36
+ const file = join(home.path, "built.ts");
37
+ await writeFile(
38
+ file,
39
+ [
40
+ 'export default workflow({ uses: ["niwa.records.read"], output: z.json() }, async () => {',
41
+ ' const built = await wait("build.finished", { filter: { id: "b-1" }, from: 0, timeout: "5s" });',
42
+ ' return "timedOut" in built ? "timed out" : built.data;',
43
+ "});",
44
+ ].join("\n"),
45
+ );
46
+ const { run } = await host.call(workflowStart, { file });
47
+ await eventually(
48
+ async () => (await host.records.read({ types: ["workflow.run.finished"], filter: { run } })).length === 1,
49
+ 20_000,
50
+ "the run should finish",
51
+ );
52
+ const [finished] = await host.records.read({ types: ["workflow.run.finished"], filter: { run } });
53
+ expect((finished?.data as { outcome: { result: unknown } }).outcome.result).toEqual({ id: "b-1", green: true });
54
+ }, 60_000);
@@ -0,0 +1,224 @@
1
+ // The calls an agent uses to drive a run: `workflow.start` with `wait`, `workflow.wait` and
2
+ // `workflow.runs`. No model is involved: the scripts finish, fail or ask.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+
8
+ import { actionName, grant, principalOf } from "@niwa-labs/core";
9
+ import { connect, createNiwa, eventually, requests, timers, tempHome } from "@niwa-labs/testing";
10
+ import type { Host, NiwaApi } from "@niwa-labs/testing";
11
+ import { workflow } from "../src/index.ts";
12
+ import type { RunStatus } from "../src/status.ts";
13
+
14
+ const START = actionName("workflow.start");
15
+ const WAIT = actionName("workflow.wait");
16
+ const RUNS = actionName("workflow.runs");
17
+
18
+ const homes: Array<{ cleanup(): Promise<void> }> = [];
19
+ const hosts: Host[] = [];
20
+
21
+ afterEach(async () => {
22
+ for (const host of hosts.splice(0)) await host.close().catch(() => {});
23
+ for (const home of homes.splice(0)) await home.cleanup();
24
+ });
25
+
26
+ async function served(): Promise<{ host: Host; home: string }> {
27
+ const home = await tempHome();
28
+ homes.push(home);
29
+ const host = createNiwa({ home: home.path });
30
+ host.use(requests(), timers([]), workflow());
31
+ await host.serve();
32
+ hosts.push(host);
33
+ return { host, home: home.path };
34
+ }
35
+
36
+ async function scriptIn(home: string, name: string, lines: readonly string[]): Promise<string> {
37
+ await mkdir(home, { recursive: true });
38
+ const file = join(home, name);
39
+ await writeFile(file, lines.join("\n"));
40
+ return file;
41
+ }
42
+
43
+ const statusOf = async (host: Host, run: string, timeoutMs?: number): Promise<RunStatus> =>
44
+ (await host.call(WAIT, { run, ...(timeoutMs === undefined ? {} : { timeoutMs }) })) as RunStatus;
45
+
46
+ test("start with wait answers with the result when the run finishes", async () => {
47
+ const { host, home } = await served();
48
+ const file = await scriptIn(home, "done.js", ["export default workflow({ output: z.json() }, async () => { return { answer: 42 }; });"]);
49
+ const started = (await host.call(START, { file, wait: true, timeoutMs: 20_000 })) as RunStatus & { finished: boolean };
50
+ expect(started.run).toMatch(/^run-[0-9a-f]{6,8}$/);
51
+ expect(started).toMatchObject({ state: "finished", finished: true, outcome: { status: "done", result: { answer: 42 } }, requests: [] });
52
+ // Waiting for a run that has ended answers at once.
53
+ expect(await statusOf(host, started.run)).toMatchObject({ state: "finished", outcome: { status: "done", result: { answer: 42 } } });
54
+ }, 30_000);
55
+
56
+ test("wait returns a paused run with its reason and the invocation to resolve", async () => {
57
+ const { host, home } = await served();
58
+ const file = await scriptIn(home, "boom.js", ['export default workflow({}, async () => { throw new Error("boom"); });']);
59
+ const runBoom = ((await host.call(START, { file })) as { run: string }).run;
60
+ const paused = await statusOf(host, runBoom, 20_000);
61
+ expect(paused.state).toBe("paused");
62
+ expect(paused.reason).toContain("boom");
63
+ // An error of the script outside any step has no step to skip.
64
+ expect(paused.choices).toEqual(["retry", "cancel"]);
65
+ expect(paused.invocation).toBeString();
66
+
67
+ const { runs } = (await host.call(RUNS, {})) as { runs: string[] };
68
+ expect(runs).toHaveLength(1);
69
+ expect(runs[0]).toContain(`${runBoom} boom paused boom`);
70
+ expect(runs[0]).toContain(`resolve: niwa workflow.resume --run ${runBoom} --choice retry|cancel`);
71
+ }, 30_000);
72
+
73
+ test("the end of the timeout is not an error: the run is running, and says what it asked", async () => {
74
+ const { host, home } = await served();
75
+ const file = await scriptIn(home, "asks.js", ['export default workflow({ output: z.json() }, async () => { return await ask.confirm("go on?"); });']);
76
+ const runAsks = ((await host.call(START, { file })) as { run: string }).run;
77
+ const started = Date.now();
78
+ let status = await statusOf(host, runAsks, 300);
79
+ // The question may not be written yet at the first look: the run asks once it has started.
80
+ while (status.requests.length === 0 && Date.now() - started < 20_000) status = await statusOf(host, runAsks, 300);
81
+ expect(status.state).toBe("running");
82
+ expect(status.requests).toHaveLength(1);
83
+ const { runs } = (await host.call(RUNS, {})) as { runs: string[] };
84
+ expect(runs[0]).toMatch(/running {2}ask req-[0-9a-f]{6,8}/);
85
+ expect(status.waiting).toBe(`ask ${status.requests[0]}`);
86
+ }, 30_000);
87
+
88
+ test("runs lists by state and keeps the latest ones; an unknown run is refused", async () => {
89
+ const { host, home } = await served();
90
+ const done = await scriptIn(home, "ok.js", ["export default workflow({ output: z.number() }, async () => { return 1; });"]);
91
+ const boom = await scriptIn(home, "bad.js", ['export default workflow({}, async () => { throw new Error("no"); });']);
92
+ const finished: string[] = [];
93
+ for (let n = 0; n < 2; n += 1) finished.push(((await host.call(START, { file: done, wait: true })) as { run: string }).run);
94
+ const run3 = ((await host.call(START, { file: boom, wait: true, timeoutMs: 20_000 })) as { run: string }).run;
95
+
96
+ const lines = async (input: Record<string, unknown>): Promise<string[]> => ((await host.call(RUNS, input)) as { runs: string[] }).runs;
97
+ expect(await lines({})).toHaveLength(3);
98
+ expect((await lines({ state: "finished" })).map((line) => line.split(" ")[0])).toEqual(finished);
99
+ expect((await lines({ state: "paused" })).map((line) => line.split(" ")[0])).toEqual([run3]);
100
+ expect((await lines({ limit: 1 })).map((line) => line.split(" ")[0])).toEqual([run3]);
101
+ await expect(statusOf(host, "run-ffffff")).rejects.toThrow('no run "run-ffffff"');
102
+ }, 30_000);
103
+
104
+ test("a read filtered by run gives everything about that run: its records, its steps and its questions, and nothing of another run", async () => {
105
+ const { host, home } = await served();
106
+ const asks = await scriptIn(home, "asker.js", ['export default workflow({ output: z.json() }, async () => { return await ask.confirm("one?"); });']);
107
+ const other = await scriptIn(home, "other.js", ["export default workflow({ output: z.number() }, async () => { return 2; });"]);
108
+ const runMine = ((await host.call(START, { file: asks })) as { run: string }).run;
109
+ const runOther = ((await host.call(START, { file: other, wait: true })) as { run: string }).run;
110
+ const started = Date.now();
111
+ while ((await statusOf(host, runMine, 300)).requests.length === 0 && Date.now() - started < 20_000) continue;
112
+
113
+ const read = (await host.call(actionName("niwa.records.search"), { filter: { run: runMine } })) as { records: Array<{ type: string; data: { run?: string } }> };
114
+ const types = read.records.map((row) => String(row.type));
115
+ expect(types).toContain("workflow.run.requested");
116
+ expect(types).toContain("request.created");
117
+ expect(types.some((type) => type.startsWith("niwa.step."))).toBe(true);
118
+ expect(read.records.some((row) => row.data.run === runOther)).toBe(false);
119
+ expect(types).not.toContain("workflow.run.finished");
120
+ }, 30_000);
121
+
122
+ test("a run paused for a revision, that only cancel answers, is paused and not finished", async () => {
123
+ const { host, home } = await served();
124
+ const body = (limit: number): string =>
125
+ `export default workflow({ uses: ["niwa.records.read"] }, async () => { await call("niwa.records.read", { limit: ${limit} }); throw new Error("x"); });`;
126
+ const file = await scriptIn(home, "edit.js", [body(1)]);
127
+ const runEdit = ((await host.call(START, { file })) as { run: string }).run;
128
+ expect((await statusOf(host, runEdit, 20_000)).state).toBe("paused");
129
+ await writeFile(file, body(2));
130
+ // A retry of the pause meets the edited script: the run waits for a revision or a cancel.
131
+ await host.call(actionName("workflow.resume"), { run: runEdit, choice: "retry" });
132
+ await eventually(async () => (await statusOf(host, runEdit, 300)).choices?.length === 1, 10_000, "the run should wait for a revision");
133
+ const shown = await statusOf(host, runEdit, 300);
134
+ expect(shown).toMatchObject({ state: "paused", choices: ["cancel"] });
135
+ const { runs } = (await host.call(RUNS, {})) as { runs: string[] };
136
+ expect(runs[0]).toContain(`resolve: niwa workflow.revise --run ${runEdit}`);
137
+ await host.call(actionName("workflow.cancel"), { run: runEdit });
138
+ expect(await statusOf(host, runEdit)).toMatchObject({ state: "finished", outcome: { status: "cancelled" } });
139
+ }, 30_000);
140
+
141
+ test("a client that is not the owner waits for and lists only the runs it started", async () => {
142
+ const { host, home } = await served();
143
+ const file = await scriptIn(home, "mine.js", ["export default workflow({ output: z.number() }, async () => { return 1; });"]);
144
+ const clients: NiwaApi[] = [];
145
+ const holding = async (name: string): Promise<NiwaApi> => {
146
+ const secret = host.issueToken(principalOf("session", name), { grant: grant(["workflow.start", "workflow.wait", "workflow.runs"]) });
147
+ const client = await connect({ home, id: `session:${name}`, token: secret });
148
+ clients.push(client);
149
+ return client;
150
+ };
151
+ try {
152
+ const first = await holding("first");
153
+ const second = await holding("second");
154
+ const runFirst = ((await first.call(START, { file, wait: true, timeoutMs: 20_000 })) as { run: string }).run;
155
+ await expect(second.call(WAIT, { run: runFirst })).rejects.toThrow("only the owner or whoever made it");
156
+ expect(await first.call(WAIT, { run: runFirst })).toMatchObject({ state: "finished" });
157
+ expect(((await second.call(RUNS, {})) as { runs: string[] }).runs).toEqual([]);
158
+ expect(((await first.call(RUNS, {})) as { runs: string[] }).runs).toHaveLength(1);
159
+ expect(((await host.call(RUNS, {})) as { runs: string[] }).runs).toHaveLength(1);
160
+ } finally {
161
+ for (const client of clients) await client.close().catch(() => undefined);
162
+ }
163
+ }, 30_000);
164
+
165
+ test("niwa.host.status counts the runs by state and the open requests", async () => {
166
+ const { host, home } = await served();
167
+ const done = await scriptIn(home, "done.js", ["export default workflow({ output: z.number() }, async () => { return 1; });"]);
168
+ const asks = await scriptIn(home, "asks.js", ['export default workflow({ output: z.json() }, async () => { return await ask.confirm("go on?"); });']);
169
+ const runDone = ((await host.call(START, { file: done, wait: true, timeoutMs: 20_000 })) as { run: string }).run;
170
+ const runAsks = ((await host.call(START, { file: asks })) as { run: string }).run;
171
+ const started = Date.now();
172
+ // The run asks once it has started: look until the question is written.
173
+ while ((await statusOf(host, runAsks, 300)).requests.length === 0 && Date.now() - started < 20_000);
174
+ const status = (await host.call(actionName("niwa.host.status"), {})) as { plugins: Array<{ name: string; summary?: Record<string, number> }> };
175
+ expect(status.plugins.find((one) => one.name === "workflow")?.summary).toEqual({ running: 1, paused: 0, finished: 1 });
176
+ expect(status.plugins.find((one) => one.name === "requests")?.summary).toEqual({ open: 1 });
177
+ }, 30_000);
178
+
179
+ test("a run that is going shows its phase and what it waits for: a sleep with its time, a wait with its type", async () => {
180
+ const { host, home } = await served();
181
+ const sleeper = await scriptIn(home, "sleeper.js", [
182
+ 'export default workflow({ output: z.number(), phases: [{ title: "resting" }, { title: "after" }] }, async () => { phase("resting"); await sleep("2h", { label: "nap" }); return 1; });',
183
+ ]);
184
+ const waiter = await scriptIn(home, "waiter.js", [
185
+ 'export default workflow({ output: z.number() }, async () => { await wait("x.y"); return 1; });',
186
+ ]);
187
+ const runSleeper = ((await host.call(START, { file: sleeper })) as { run: string }).run;
188
+ const runWaiter = ((await host.call(START, { file: waiter })) as { run: string }).run;
189
+ const lineOf = async (run: string, text: RegExp): Promise<string> => {
190
+ const started = Date.now();
191
+ for (;;) {
192
+ const line = ((await host.call(RUNS, {})) as { runs: string[] }).runs.find((one) => one.startsWith(run)) ?? "";
193
+ if (text.test(line) || Date.now() - started > 20_000) return line;
194
+ await Bun.sleep(100);
195
+ }
196
+ };
197
+ expect(await lineOf(runSleeper, /sleep nap/)).toMatch(new RegExp(`^${runSleeper} {2}sleeper {2}running {2}resting \\(1/2\\) {2}sleep nap until \\d\\d:\\d\\d:\\d\\d$`));
198
+ expect(await lineOf(runWaiter, /wait x/)).toMatch(new RegExp(`^${runWaiter} {2}waiter {2}running {2}wait x\\.y$`));
199
+ const status = await statusOf(host, runSleeper, 200);
200
+ expect(status).toMatchObject({ state: "running", currentPhases: ["resting"], phases: [{ title: "resting", state: "current" }, { title: "after", state: "ahead" }] });
201
+ expect(status.waiting).toMatch(/^sleep nap until/);
202
+ }, 30_000);
203
+
204
+ test("timer.list shows the pending sleeps with who asked and the timers with their schedule", async () => {
205
+ const home = await tempHome();
206
+ homes.push(home);
207
+ const host = createNiwa({ home: home.path });
208
+ host.use(requests(), timers([{ id: "digest", daily: "21:00" }]), workflow());
209
+ await host.serve();
210
+ hosts.push(host);
211
+ const file = await scriptIn(home.path, "napper.js", ['export default workflow({ output: z.number() }, async () => { await sleep("2h", { label: "nap" }); return 1; });']);
212
+ await host.call(START, { file });
213
+ const list = async () => (await host.call(actionName("timer.list"), {})) as { sleeps: string[]; timers: Array<{ name: string; schedule: unknown; nextDue: number | null; lastFiring: string | null }> };
214
+ const started = Date.now();
215
+ while ((await list()).sleeps.length === 0 && Date.now() - started < 20_000) await Bun.sleep(100);
216
+ const { sleeps, timers: scheduled } = await list();
217
+ expect(sleeps).toHaveLength(1);
218
+ expect(sleeps[0]).toMatch(/^\d\d:\d\d:\d\d {2}run-[0-9a-f]{6,8} {2}nap$/);
219
+ expect(scheduled).toHaveLength(1);
220
+ expect(scheduled[0]).toMatchObject({ name: "digest", schedule: { kind: "daily", time: "21:00" }, lastFiring: null });
221
+ expect(scheduled[0]?.nextDue).toBeGreaterThan(Date.now());
222
+ const status = (await host.call(actionName("niwa.host.status"), {})) as { plugins: Array<{ name: string; summary?: Record<string, number> }> };
223
+ expect(status.plugins.find((one) => one.name === "timers")?.summary).toEqual({ sleeps: 1 });
224
+ }, 30_000);
@@ -0,0 +1,64 @@
1
+ // A run that waits for an agent says which: `session <harness> <session> turn N`.
2
+ // The agent action here is a stub that records the start of a session and a turn, then holds.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+
8
+ import { action, actionName, idSchema } from "@niwa-labs/core";
9
+ import { harnessId, sessionId } from "@niwa-labs/harness";
10
+ import { plugin } from "@niwa-labs/plugin";
11
+ import { SessionStarted, SessionTurnStarted, sessionRef } from "@niwa-labs/sessions/records";
12
+ import { createNiwa, gate, tempHome } from "@niwa-labs/testing";
13
+ import type { Host } from "@niwa-labs/testing";
14
+ import { workflow } from "../src/index.ts";
15
+ import { z } from "zod";
16
+
17
+ const hosts: Host[] = [];
18
+ const homes: Array<{ cleanup(): Promise<void> }> = [];
19
+
20
+ afterEach(async () => {
21
+ for (const host of hosts.splice(0)) await host.close().catch(() => {});
22
+ for (const home of homes.splice(0)) await home.cleanup();
23
+ });
24
+
25
+ test("a run waiting for an agent shows its harness, session and turn", async () => {
26
+ const home = await tempHome();
27
+ homes.push(home);
28
+ const session = sessionRef(sessionId(harnessId("fake"), "0a1b2c3d-1111-2222-3333-444455556666"));
29
+ const fake = action("session.start.fake", {
30
+ description: "A stub agent: it starts a session and a turn, and holds.",
31
+ input: z.object({ prompt: z.string() }),
32
+ output: z.object({ answer: z.string() }),
33
+ recovery: "repeat",
34
+ effect: "write",
35
+ run: async (_input, ctx) => {
36
+ await ctx.emit(SessionStarted, { session, id: idSchema("session").parse("s-0a1b2c") });
37
+ await ctx.emit(SessionTurnStarted, { session, turn: 1 });
38
+ await gate(home.path, "agent-held").wait();
39
+ return { answer: "done" };
40
+ },
41
+ });
42
+ const host = createNiwa({ home: home.path });
43
+ host.use(
44
+ plugin("sessions", (api) => {
45
+ api.declare(SessionStarted, SessionTurnStarted);
46
+ api.action(fake);
47
+ }),
48
+ workflow({ agents: { fake } }),
49
+ );
50
+ await host.serve();
51
+ hosts.push(host);
52
+ await mkdir(home.path, { recursive: true });
53
+ const file = join(home.path, "agent.js");
54
+ await writeFile(file, 'export default workflow({ output: z.json() }, async () => { return await ask({ harness: "fake" }, "hello"); });');
55
+ await host.call(actionName("workflow.start"), { file });
56
+ const started = Date.now();
57
+ let line = "";
58
+ while (!line.includes("turn 1") && Date.now() - started < 20_000) {
59
+ line = ((await host.call(actionName("workflow.runs"), {})) as { runs: string[] }).runs[0] ?? "";
60
+ await Bun.sleep(100);
61
+ }
62
+ expect(line).toContain("running session fake s-0a1b2c turn 1");
63
+ gate(home.path, "agent-held").open();
64
+ }, 30_000);
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": [
5
+ "ESNext",
6
+ "DOM",
7
+ "DOM.Iterable",
8
+ "DOM.AsyncIterable"
9
+ ],
10
+ "jsx": "react-jsx"
11
+ },
12
+ "include": [
13
+ "src"
14
+ ]
15
+ }