@niwa-labs/tasks 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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/package.json +42 -4
- package/src/actions.ts +109 -0
- package/src/cockpit/actions.ts +52 -0
- package/src/cockpit/index.tsx +32 -0
- package/src/cockpit/pages.tsx +103 -0
- package/src/executor.ts +214 -0
- package/src/index.ts +516 -0
- package/src/ledger.ts +88 -0
- package/src/owner.ts +178 -0
- package/src/records-entry.ts +38 -0
- package/src/records.ts +118 -0
- package/src/strategy.ts +60 -0
- package/test/asker.test.ts +67 -0
- package/test/cockpit-actions.test.ts +19 -0
- package/test/executor.test.ts +520 -0
- package/test/ledger.test.ts +172 -0
- package/test/notifications.test.ts +170 -0
- package/test/queries.test.ts +19 -0
- package/test/steps.test.ts +147 -0
- package/test/tasks.test.ts +536 -0
- package/tsconfig.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niwa Labs contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/tasks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Tracked tasks: a task is a contract (what to do, who asked, who is responsible, where to report) and the records that say how it went. A task is created with `task.create`, reported on with `task.report`, and ended once with `task.finish` or `task.fail`; `task.result` gives the outcome and waits for it. The assignment, the updates and the outcome travel as messages, sent through the messages module.
|
|
4
|
+
|
|
5
|
+
The root entry holds the plugin, the executor and the strategy contract; `@niwa-labs/tasks/records` holds the records, the typed action references and the functions that fold the state of a task from the journal, which other plugins may import. It also holds the query builders of a task's records, `taskDone(id)` and `taskUpdates(id)`: a workflow script waits for or reads them with its data typed (`await wait(taskDone(task.id), { timeout: "30m" })`), and a handler subscribes to them.
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/tasks",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./records": "./src/records-entry.ts",
|
|
9
|
+
"./cockpit": "./src/cockpit/index.tsx"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@niwa-labs/cockpit-sdk": "0.0.0",
|
|
13
|
+
"@niwa-labs/core": "0.0.0",
|
|
14
|
+
"@niwa-labs/messages": "0.0.0",
|
|
15
|
+
"@niwa-labs/plugin": "0.0.0",
|
|
16
|
+
"@niwa-labs/ui-kit": "0.0.0",
|
|
17
|
+
"zod": "^4.6.7"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@happy-dom/global-registrator": "^21.0.4",
|
|
21
|
+
"@niwa-labs/testing": "0.0.0",
|
|
22
|
+
"@tanstack/react-query": "^5.108.2",
|
|
23
|
+
"@types/react": "^19.3.0",
|
|
24
|
+
"@types/react-dom": "^19.3.0",
|
|
25
|
+
"react": "^19.3.1",
|
|
26
|
+
"react-dom": "^19.3.1"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@tanstack/react-query": "^5.108.2",
|
|
30
|
+
"react": "^19.3.1",
|
|
31
|
+
"react-dom": "^19.3.1"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"@tanstack/react-query": {
|
|
35
|
+
"optional": true
|
|
36
|
+
},
|
|
37
|
+
"react": {
|
|
38
|
+
"optional": true
|
|
39
|
+
},
|
|
40
|
+
"react-dom": {
|
|
41
|
+
"optional": true
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions of the tasks module, as typed references: name, description and the two schemas.
|
|
3
|
+
*
|
|
4
|
+
* A caller imports these to call a task action with the input and the output checked by the type
|
|
5
|
+
* checker, on the host and on a client, without any data of the module. The module's factory builds
|
|
6
|
+
* its real actions from the same references (`action(taskCreate, { recovery, run })`), so the
|
|
7
|
+
* schemas here are the ones the host checks against.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
|
|
12
|
+
import { JsonValueSchema, actionRef, getRef, listRef, Address } from "@niwa-labs/core";
|
|
13
|
+
|
|
14
|
+
import { ResultSchema } from "@niwa-labs/messages/records";
|
|
15
|
+
|
|
16
|
+
import { TaskContract, TaskId, TaskKind, TaskOutcome } from "./records.ts";
|
|
17
|
+
|
|
18
|
+
/** The input of the action that makes a task: the contract without its id, which niwa issues. */
|
|
19
|
+
export const CreateInput = TaskContract.omit({ id: true }).strict();
|
|
20
|
+
|
|
21
|
+
/** The input of the action that reports on a task. */
|
|
22
|
+
export const ReportInput = z.object({ task: TaskId, text: z.string().min(1), data: JsonValueSchema.optional() });
|
|
23
|
+
|
|
24
|
+
/** The input of the action that finishes a task with a result. */
|
|
25
|
+
export const FinishInput = z.object({
|
|
26
|
+
task: TaskId,
|
|
27
|
+
/** The result of the work: when the task declared a result schema, it must fit it. */
|
|
28
|
+
result: JsonValueSchema,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
/** The input of the action that ends a task as failed. */
|
|
32
|
+
export const FailInput = z.object({
|
|
33
|
+
task: TaskId,
|
|
34
|
+
/** Why the work did not succeed. */
|
|
35
|
+
reason: z.string().min(1),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** What the actions that finish or fail a task and ask for its result return. */
|
|
39
|
+
export const OutcomeOutput = z.object({ task: TaskId, outcome: TaskOutcome });
|
|
40
|
+
|
|
41
|
+
export const taskCreate = actionRef("task.create", {
|
|
42
|
+
description:
|
|
43
|
+
"Make a task: a few words of description, what to do, who asked, who is responsible, where to report. " +
|
|
44
|
+
"`result` may declare the shape the result must have, as a JSON Schema of an object: " +
|
|
45
|
+
"whoever does the work is shown it, and `task.finish` refuses a result that does not fit. " +
|
|
46
|
+
"A client asks as the address it speaks as: `askedBy` must be that address, and another is refused. " +
|
|
47
|
+
"It returns the id niwa issued at once, and the work goes on in the background.",
|
|
48
|
+
input: CreateInput,
|
|
49
|
+
output: z.object({ id: TaskId }),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export const taskReport = actionRef("task.report", {
|
|
53
|
+
description: "Report what happened on a task while the work goes on.",
|
|
54
|
+
input: ReportInput,
|
|
55
|
+
output: z.object({ task: TaskId }),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export const taskFinish = actionRef("task.finish", {
|
|
59
|
+
description:
|
|
60
|
+
"Finish a task with its result. When the task declared a result schema, the result must fit it, or the task stays open. " +
|
|
61
|
+
"A task ends once, with a result or a failure; the first end stands.",
|
|
62
|
+
input: FinishInput,
|
|
63
|
+
output: OutcomeOutput,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export const taskFail = actionRef("task.fail", {
|
|
67
|
+
description: "End a task as failed, with the reason. A task ends once, with a result or a failure; the first end stands.",
|
|
68
|
+
input: FailInput,
|
|
69
|
+
output: OutcomeOutput,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
export const taskResult = actionRef("task.result", {
|
|
73
|
+
description:
|
|
74
|
+
"The result of a task. If the task is not done yet, this waits for it. The answer is read from the journal.",
|
|
75
|
+
input: z.object({ task: TaskId }),
|
|
76
|
+
output: OutcomeOutput,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/** Whether a task is still being worked on. */
|
|
80
|
+
export const TaskStatus = z.enum(["open", "done"]);
|
|
81
|
+
|
|
82
|
+
/** One task as `task.get` shows it: the contract, where it stands, and how it ended when it did. */
|
|
83
|
+
export const TaskEntity = TaskContract.extend({ status: TaskStatus, outcome: TaskOutcome.optional() });
|
|
84
|
+
export type TaskEntity = z.infer<typeof TaskEntity>;
|
|
85
|
+
|
|
86
|
+
export const taskList = listRef("task.list", {
|
|
87
|
+
kind: "task",
|
|
88
|
+
noun: "task",
|
|
89
|
+
detail: "The filter `status` keeps the open tasks or the done ones.",
|
|
90
|
+
filter: { status: TaskStatus.optional() },
|
|
91
|
+
item: { status: TaskStatus, kind: TaskKind, responsible: Address },
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
export const taskGet = getRef("task.get", {
|
|
95
|
+
kind: "task",
|
|
96
|
+
noun: "task",
|
|
97
|
+
detail: "It shows the whole contract, where the task stands and how it ended.",
|
|
98
|
+
entity: TaskEntity,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
/** The open tasks that the caller is responsible for, each with the schema its result must fit when it declared one. */
|
|
102
|
+
export const taskAssigned = actionRef("task.assigned", {
|
|
103
|
+
description:
|
|
104
|
+
"The open tasks the caller is responsible for: the id, the description and, for a task that declares one, the schema its result must fit.",
|
|
105
|
+
input: z.object({}),
|
|
106
|
+
output: z.object({
|
|
107
|
+
tasks: z.array(z.object({ task: TaskId, description: TaskContract.shape.description, result: ResultSchema.optional() })),
|
|
108
|
+
}),
|
|
109
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The task actions as the cockpit calls them: name and the part of each schema the pages read.
|
|
3
|
+
*
|
|
4
|
+
* The module runs in the browser and cannot import the host-side schemas, which reach for Node. A field the host
|
|
5
|
+
* stopped sending fails the page that reads it, which `test/cockpit-actions.test.ts` checks against the real actions.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
10
|
+
export const Address = z.object({ kind: z.string(), id: z.string().optional(), harness: z.string().optional() }).loose();
|
|
11
|
+
|
|
12
|
+
export const TaskStatus = z.enum(["open", "done"]);
|
|
13
|
+
|
|
14
|
+
export const TaskItem = z.object({
|
|
15
|
+
id: z.string(),
|
|
16
|
+
description: z.string(),
|
|
17
|
+
status: TaskStatus,
|
|
18
|
+
kind: z.string(),
|
|
19
|
+
responsible: Address,
|
|
20
|
+
});
|
|
21
|
+
export type TaskItem = z.infer<typeof TaskItem>;
|
|
22
|
+
|
|
23
|
+
export const listAction = {
|
|
24
|
+
name: "task.list",
|
|
25
|
+
input: z.object({ status: TaskStatus.optional() }),
|
|
26
|
+
output: z.object({ items: z.array(TaskItem) }),
|
|
27
|
+
} as const;
|
|
28
|
+
|
|
29
|
+
export const Outcome = z.discriminatedUnion("status", [
|
|
30
|
+
z.object({ status: z.literal("result"), result: z.unknown() }),
|
|
31
|
+
z.object({ status: z.literal("failure"), reason: z.string() }),
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export const TaskEntity = z.object({
|
|
35
|
+
id: z.string(),
|
|
36
|
+
kind: z.string(),
|
|
37
|
+
description: z.string(),
|
|
38
|
+
text: z.string(),
|
|
39
|
+
askedBy: Address,
|
|
40
|
+
responsible: Address,
|
|
41
|
+
reportTo: Address,
|
|
42
|
+
status: TaskStatus,
|
|
43
|
+
outcome: Outcome.optional(),
|
|
44
|
+
result: z.record(z.string(), z.unknown()).optional(),
|
|
45
|
+
});
|
|
46
|
+
export type TaskEntity = z.infer<typeof TaskEntity>;
|
|
47
|
+
|
|
48
|
+
export const getAction = {
|
|
49
|
+
name: "task.get",
|
|
50
|
+
input: z.object({ id: z.string() }),
|
|
51
|
+
output: TaskEntity,
|
|
52
|
+
} as const;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** The cockpit module of the tasks plugin: the list of tasks and the page of one. */
|
|
2
|
+
|
|
3
|
+
import { definePlugin } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
|
|
5
|
+
import { TaskPage, TasksPage } from "./pages.tsx";
|
|
6
|
+
|
|
7
|
+
export default definePlugin({
|
|
8
|
+
id: "tasks",
|
|
9
|
+
setup(ctx) {
|
|
10
|
+
ctx.pages.add({
|
|
11
|
+
path: "/tasks",
|
|
12
|
+
title: "Задачи",
|
|
13
|
+
commandHeading: true,
|
|
14
|
+
nav: { order: 40 },
|
|
15
|
+
commands: [
|
|
16
|
+
{
|
|
17
|
+
action: "task.create",
|
|
18
|
+
label: "Создать задачу",
|
|
19
|
+
preset: { askedBy: { kind: "owner" }, reportTo: { kind: "owner" } },
|
|
20
|
+
},
|
|
21
|
+
],
|
|
22
|
+
component: TasksPage,
|
|
23
|
+
});
|
|
24
|
+
ctx.pages.add({
|
|
25
|
+
path: "/tasks/$taskId",
|
|
26
|
+
panel: true,
|
|
27
|
+
title: "Задача",
|
|
28
|
+
component: TaskPage,
|
|
29
|
+
});
|
|
30
|
+
ctx.entities.register("task", { label: "Задача", prefix: "task", href: (id) => `/tasks/${encodeURIComponent(id)}` });
|
|
31
|
+
},
|
|
32
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/** The host's tasks, grouped by state, with the contract and outcome of each task. */
|
|
2
|
+
|
|
3
|
+
import { EntityLink, PageCommands, PageLink, useCall, type PageProps } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
import { CopyValue, DataValue, PageSection, SchemaView, StateRing } from "@niwa-labs/ui-kit";
|
|
5
|
+
import type { z } from "zod";
|
|
6
|
+
|
|
7
|
+
import { getAction, listAction, type Address, type TaskItem } from "./actions.ts";
|
|
8
|
+
|
|
9
|
+
const refreshOn = { types: ["task.*"] };
|
|
10
|
+
|
|
11
|
+
function TaskAddress({ address }: { address: z.infer<typeof Address> }) {
|
|
12
|
+
if (address.kind === "owner") return <>Владелец</>;
|
|
13
|
+
if (address.kind === "task" && address.id) return <EntityLink entity={{ kind: "task", id: address.id }} short />;
|
|
14
|
+
if (address.kind === "session" && address.id) {
|
|
15
|
+
const label = [address.harness, address.id].filter(Boolean).join(" · ");
|
|
16
|
+
return <EntityLink entity={address.id} label={label} />;
|
|
17
|
+
}
|
|
18
|
+
return <>{address.id ?? address.kind}</>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function TaskRow({ task }: { task: TaskItem }) {
|
|
22
|
+
const done = task.status === "done";
|
|
23
|
+
return (
|
|
24
|
+
<li data-slot="task-row" data-status={task.status} className="flex min-w-0 items-start gap-3 py-2">
|
|
25
|
+
<span className="mt-1 shrink-0">
|
|
26
|
+
<StateRing state={done ? "done" : "running"} label={done ? "Завершена" : "В работе"} />
|
|
27
|
+
</span>
|
|
28
|
+
<div className="min-w-0 flex flex-col gap-1">
|
|
29
|
+
<PageLink to={"/tasks/" + encodeURIComponent(task.id)} className="text-base font-semibold wrap-anywhere hover:underline">
|
|
30
|
+
{task.description}
|
|
31
|
+
</PageLink>
|
|
32
|
+
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground wrap-anywhere">
|
|
33
|
+
<span>{task.kind}</span>
|
|
34
|
+
<span>Ответственный · <TaskAddress address={task.responsible} /></span>
|
|
35
|
+
</div>
|
|
36
|
+
</div>
|
|
37
|
+
</li>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function TasksPage() {
|
|
42
|
+
const tasks = useCall(listAction, {}, { refreshOn });
|
|
43
|
+
if (tasks.isPending) return <p role="status">Загружаю задачи…</p>;
|
|
44
|
+
if (tasks.isError) return <p role="alert">Не удалось загрузить задачи.</p>;
|
|
45
|
+
const open = tasks.data.items.filter((task) => task.status === "open").toReversed();
|
|
46
|
+
const done = tasks.data.items.filter((task) => task.status === "done").toReversed();
|
|
47
|
+
return (
|
|
48
|
+
<>
|
|
49
|
+
<PageSection title="В работе">
|
|
50
|
+
{open.length === 0 ? <p>Открытых задач нет.</p> : (
|
|
51
|
+
<ul data-slot="tasks" className="divide-y">{open.map((task) => <TaskRow key={task.id} task={task} />)}</ul>
|
|
52
|
+
)}
|
|
53
|
+
</PageSection>
|
|
54
|
+
{done.length > 0 && (
|
|
55
|
+
<PageSection title="Завершённые">
|
|
56
|
+
<ul data-slot="completed-tasks" className="divide-y">{done.map((task) => <TaskRow key={task.id} task={task} />)}</ul>
|
|
57
|
+
</PageSection>
|
|
58
|
+
)}
|
|
59
|
+
</>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function TaskPage({ params }: PageProps<"/tasks/$taskId">) {
|
|
64
|
+
const task = useCall(getAction, { id: params.taskId }, { refreshOn });
|
|
65
|
+
if (task.isPending) return <p role="status">Загружаю задачу…</p>;
|
|
66
|
+
if (task.isError) return <p role="alert">Не удалось загрузить задачу.</p>;
|
|
67
|
+
const { data } = task;
|
|
68
|
+
const state = data.status === "open" ? "running" : data.outcome?.status === "failure" ? "failed" : "done";
|
|
69
|
+
const status = state === "running" ? "В работе" : state === "failed" ? "Не выполнена" : "Завершена";
|
|
70
|
+
return (
|
|
71
|
+
<article data-slot="task-page" className="desk-page">
|
|
72
|
+
<header className="min-w-0 flex flex-col gap-3">
|
|
73
|
+
<p className="flex min-w-0 flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
|
74
|
+
<StateRing state={state} label={status} />
|
|
75
|
+
<span>{status} · {data.kind}</span>
|
|
76
|
+
<CopyValue value={data.id} name="Скопировать номер задачи" />
|
|
77
|
+
</p>
|
|
78
|
+
<h2 className="text-2xl font-semibold wrap-anywhere">{data.description}</h2>
|
|
79
|
+
{data.status === "open" && (
|
|
80
|
+
<PageCommands commands={[
|
|
81
|
+
{ action: "task.report", label: "Добавить отчёт", preset: { task: data.id } },
|
|
82
|
+
{ action: "task.finish", label: "Завершить задачу", preset: { task: data.id } },
|
|
83
|
+
]} />
|
|
84
|
+
)}
|
|
85
|
+
</header>
|
|
86
|
+
{data.text !== data.description && <p className="whitespace-pre-wrap wrap-anywhere">{data.text}</p>}
|
|
87
|
+
<PageSection title="Участники">
|
|
88
|
+
<dl className="nw-fields">
|
|
89
|
+
<div><dt>Поставил задачу</dt><dd><TaskAddress address={data.askedBy} /></dd></div>
|
|
90
|
+
<div><dt>Ответственный</dt><dd><TaskAddress address={data.responsible} /></dd></div>
|
|
91
|
+
<div><dt>Получатель отчёта</dt><dd><TaskAddress address={data.reportTo} /></dd></div>
|
|
92
|
+
</dl>
|
|
93
|
+
</PageSection>
|
|
94
|
+
{data.outcome?.status === "failure" ? (
|
|
95
|
+
<PageSection title="Почему задача не выполнена"><DataValue value={data.outcome.reason} /></PageSection>
|
|
96
|
+
) : data.outcome?.status === "result" ? (
|
|
97
|
+
<PageSection title="Результат" data-slot="task-result"><DataValue value={data.outcome.result} /></PageSection>
|
|
98
|
+
) : data.result && (
|
|
99
|
+
<PageSection title="Ожидаемый результат"><SchemaView schema={data.result} /></PageSection>
|
|
100
|
+
)}
|
|
101
|
+
</article>
|
|
102
|
+
);
|
|
103
|
+
}
|
package/src/executor.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The executor: the plain way of doing a task.
|
|
3
|
+
*
|
|
4
|
+
* The address "an agent in this harness" is `executor(harnessId)`. It means: somebody who runs
|
|
5
|
+
* in that harness and does the work. It is the simplest responsible party there is — one agent,
|
|
6
|
+
* one session, one answer.
|
|
7
|
+
*
|
|
8
|
+
* It names a harness by id and imports no harness kind. How it works is the business of the
|
|
9
|
+
* sessions module; a different way of working is a strategy (see `strategy.ts`).
|
|
10
|
+
*
|
|
11
|
+
* The work is plain: a session is started with the assignment, the session is asked for the
|
|
12
|
+
* result, and the task ends with what the session said. The sessions module is reached by the
|
|
13
|
+
* name of its actions, the way the messages module reaches "session.send": the tasks module
|
|
14
|
+
* imports no sessions module and names no harness kind.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { action, actionName, jsonOf } from "@niwa-labs/core";
|
|
18
|
+
import type { Address, Step, StoredRecord } from "@niwa-labs/core";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
|
|
21
|
+
import { trigger } from "@niwa-labs/plugin";
|
|
22
|
+
import type { PluginApi, Trigger } from "@niwa-labs/plugin";
|
|
23
|
+
import { MessageSent, render } from "@niwa-labs/messages/records";
|
|
24
|
+
import type { Message } from "@niwa-labs/messages/records";
|
|
25
|
+
|
|
26
|
+
import type { TaskLedger } from "./ledger.ts";
|
|
27
|
+
import { TaskRefusal, decide, fitsRecord } from "./owner.ts";
|
|
28
|
+
import { TaskCreated, TaskDone } from "./records.ts";
|
|
29
|
+
import type { TaskOutcome } from "./records.ts";
|
|
30
|
+
|
|
31
|
+
/** The prefix of the address of an executor: "executor:<harness>". */
|
|
32
|
+
const EXECUTOR_PREFIX = "executor:";
|
|
33
|
+
|
|
34
|
+
/** The schema the answer of the session must pass when the task declared none: one field, the result of the task. */
|
|
35
|
+
const RESULT_SCHEMA: Record<string, unknown> = {
|
|
36
|
+
type: "object",
|
|
37
|
+
properties: { result: { type: "string" } },
|
|
38
|
+
required: ["result"],
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** The answer of the session, as the schema says it is. */
|
|
42
|
+
const Answer = z.object({ result: z.string() });
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The trigger: the assignments that are for an agent.
|
|
46
|
+
*
|
|
47
|
+
* It is the type "message.sent" narrowed to the assignments sent to an agent. Whether the agent is
|
|
48
|
+
* an executor — its id names a harness — and whether there is a task to answer for is more than
|
|
49
|
+
* equality says: the handler checks it, and passes over the assignments for anybody else.
|
|
50
|
+
*/
|
|
51
|
+
export const ExecutorAssignment: Trigger<Message> = trigger(MessageSent, {
|
|
52
|
+
name: "message.sent:executor",
|
|
53
|
+
filter: { "to.kind": "agent", "body.type": "assignment" },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** Is the assignment one for an executor: an agent whose id names a harness, with a task to answer for? */
|
|
57
|
+
export function forExecutor(message: Message): boolean {
|
|
58
|
+
if (message.to.kind !== "agent" || !message.to.id.startsWith(EXECUTOR_PREFIX)) return false;
|
|
59
|
+
return typeof message.task === "string" && message.task.length > 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The handler of the executor: it does the work of one task.
|
|
64
|
+
*
|
|
65
|
+
* The session is started with the assignment, the session is asked for the result, and the task
|
|
66
|
+
* ends with what it said. When the task declared a result schema, the session is asked by that
|
|
67
|
+
* schema and its whole answer is the result; otherwise the result is a text. The end of the task
|
|
68
|
+
* is written here, by the responsible party itself:
|
|
69
|
+
* the executor is the party the task named, so it may end it, and it does it through the same
|
|
70
|
+
* rule and the same record the actions "task.finish" and "task.fail" use.
|
|
71
|
+
*
|
|
72
|
+
* The work is the work of the contract, once: only the Assignment the creation of the task caused
|
|
73
|
+
* starts a session, and the brief is made from the contract, not from the message. Another message
|
|
74
|
+
* that calls itself an assignment of the task is refused, and the assignment that was delivered
|
|
75
|
+
* again finds its invocation, with the session it started.
|
|
76
|
+
*
|
|
77
|
+
* A session that cannot be started, or that does not give an answer the schema accepts, did not do
|
|
78
|
+
* the task: the task ends as failed, with the reason, and its addressee is told. A call that was
|
|
79
|
+
* cut off is another matter: nobody knows what came of it, so the invocation waits for the owner.
|
|
80
|
+
*/
|
|
81
|
+
export function executorHandler(
|
|
82
|
+
ledger: TaskLedger,
|
|
83
|
+
authorize: PluginApi["authorize"],
|
|
84
|
+
): (message: Message, step: Step, record: StoredRecord) => Promise<void> {
|
|
85
|
+
const check = action("task.executor.authorize", {
|
|
86
|
+
description: "Checks the task creator's permission before each executor call.",
|
|
87
|
+
input: z.object({ name: z.enum(["session.start", "session.ask"]), input: z.unknown() }),
|
|
88
|
+
output: z.boolean(),
|
|
89
|
+
recovery: "repeat",
|
|
90
|
+
effect: "read",
|
|
91
|
+
run: async ({ name, input }, ctx) => {
|
|
92
|
+
await authorize(ctx.caller, "call", name, { input });
|
|
93
|
+
return true;
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
return async (message, step, record) => {
|
|
97
|
+
if (!forExecutor(message)) return;
|
|
98
|
+
if (message.task === undefined) {
|
|
99
|
+
throw new TaskRefusal("no-task", "the assignment names no task");
|
|
100
|
+
}
|
|
101
|
+
const task = message.task;
|
|
102
|
+
const harness = harnessOf(message);
|
|
103
|
+
const address = { kind: "agent" as const, id: `${EXECUTOR_PREFIX}${harness}` };
|
|
104
|
+
|
|
105
|
+
// A task that cannot be ended by this executor is refused before any work is done.
|
|
106
|
+
const before = ledger.state(task);
|
|
107
|
+
if (before?.status === "done") return;
|
|
108
|
+
decide(before, { kind: "finish", task, by: address });
|
|
109
|
+
if (before === undefined) return;
|
|
110
|
+
if (ledger.assignment(task)?.id !== record.id) {
|
|
111
|
+
throw new TaskRefusal("not-the-assignment", `the message is not the assignment of the task "${task}"`);
|
|
112
|
+
}
|
|
113
|
+
const creation = ledger.created(task);
|
|
114
|
+
const creator = creation?.actor;
|
|
115
|
+
if (creator === undefined) throw new TaskRefusal("unknown", "the task has no creation record");
|
|
116
|
+
const initiator = creator.kind === "client" ? creator.principal : TaskCreated.schema.parse(creation?.data).initiator;
|
|
117
|
+
if (creator.kind === "client" && initiator === undefined) {
|
|
118
|
+
throw new TaskRefusal("unbound", "the task creator has no authenticated principal");
|
|
119
|
+
}
|
|
120
|
+
const contract = before.contract;
|
|
121
|
+
const declared = contract.result;
|
|
122
|
+
|
|
123
|
+
/** End the task with an outcome, unless it already has an end: the same fact, written once. */
|
|
124
|
+
const end = async (outcome: TaskOutcome) => {
|
|
125
|
+
const state = ledger.state(task);
|
|
126
|
+
if (state?.status === "done") return;
|
|
127
|
+
const kept: TaskOutcome = fitsRecord(task, outcome) ? outcome : { status: "failure", reason: "the result is too large to be kept with the task" };
|
|
128
|
+
decide(state, { kind: "finish", task, by: address, outcome: kept });
|
|
129
|
+
await step.emit(TaskDone, { task, outcome: kept });
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// Each authorization is its own durable step. Replaying a completed
|
|
133
|
+
// launch never repeats the owner's permission question.
|
|
134
|
+
const call = async <O>(name: "session.start" | "session.ask", input: unknown, key: string):
|
|
135
|
+
Promise<{ ok: true; value: O } | { ok: false; reason: string }> => {
|
|
136
|
+
const options = initiator === undefined ? { key } : { key, as: initiator };
|
|
137
|
+
if (initiator !== undefined) {
|
|
138
|
+
const checked = await step.outcome(check, { name, input }, { key: `${key}:permission`, as: initiator });
|
|
139
|
+
if (checked.status !== "completed") return { ok: false, reason: checked.status === "failed" ? checked.error : checked.status };
|
|
140
|
+
}
|
|
141
|
+
const target = actionName(name);
|
|
142
|
+
const outcome = await step.outcome<unknown, O>(target, input, options);
|
|
143
|
+
if (outcome.status === "completed") return { ok: true, value: outcome.value };
|
|
144
|
+
if (outcome.status === "failed") return { ok: false, reason: outcome.error || "it failed" };
|
|
145
|
+
if (outcome.status === "denied") return { ok: false, reason: outcome.reason };
|
|
146
|
+
return { ok: true, value: await step<unknown, O>(target, input, options) };
|
|
147
|
+
};
|
|
148
|
+
const started = await call<{ session: string }>("session.start", {
|
|
149
|
+
harness,
|
|
150
|
+
visible: { actions: ["submit-answer"] },
|
|
151
|
+
prompt: render({
|
|
152
|
+
id: message.id,
|
|
153
|
+
from: contract.askedBy,
|
|
154
|
+
to: contract.responsible,
|
|
155
|
+
task,
|
|
156
|
+
body: {
|
|
157
|
+
type: "assignment",
|
|
158
|
+
text: contract.text,
|
|
159
|
+
kind: contract.kind,
|
|
160
|
+
...(declared === undefined ? {} : { result: declared }),
|
|
161
|
+
},
|
|
162
|
+
}),
|
|
163
|
+
}, "start");
|
|
164
|
+
if (!started.ok) return end({ status: "failure", reason: `the session could not be started: ${started.reason}` });
|
|
165
|
+
|
|
166
|
+
const answered = await call<{ value: unknown }>("session.ask", {
|
|
167
|
+
session: started.value.session,
|
|
168
|
+
prompt: "Give the result of the task.",
|
|
169
|
+
schema: declared ?? RESULT_SCHEMA,
|
|
170
|
+
}, "ask");
|
|
171
|
+
if (!answered.ok) return end({ status: "failure", reason: `the session gave no result: ${answered.reason}` });
|
|
172
|
+
|
|
173
|
+
await end(outcomeOf(answered.value.value, declared !== undefined));
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The address of an agent in a harness.
|
|
179
|
+
*
|
|
180
|
+
* It is the address of an agent, not of a session: the session is started later, and a task and
|
|
181
|
+
* a session are different things.
|
|
182
|
+
*/
|
|
183
|
+
export function executor(harness: string): Address {
|
|
184
|
+
if (typeof harness !== "string" || harness.trim().length === 0) {
|
|
185
|
+
throw new TypeError("a harness id must be a non-empty string");
|
|
186
|
+
}
|
|
187
|
+
return { kind: "agent", id: `executor:${harness}` };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The harness an executor address names. */
|
|
191
|
+
function harnessOf(message: Message): string {
|
|
192
|
+
if (message.to.kind !== "agent" || !message.to.id.startsWith(EXECUTOR_PREFIX)) {
|
|
193
|
+
throw new TaskRefusal("not-an-executor", "the assignment is not for an executor");
|
|
194
|
+
}
|
|
195
|
+
const harness = message.to.id.slice(EXECUTOR_PREFIX.length);
|
|
196
|
+
if (harness.length === 0) {
|
|
197
|
+
throw new TaskRefusal("not-an-executor", `"${message.to.id}" names no harness`);
|
|
198
|
+
}
|
|
199
|
+
return harness;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* How the task ended, from what the session answered.
|
|
204
|
+
*
|
|
205
|
+
* The answer is a result or nothing: a session that did not answer with a result did not do
|
|
206
|
+
* the task, and the task ends in a failure rather than with a made-up result. When the task
|
|
207
|
+
* declared a schema, the session has answered by it and the answer is the result.
|
|
208
|
+
*/
|
|
209
|
+
function outcomeOf(value: unknown, declared: boolean): TaskOutcome {
|
|
210
|
+
if (declared) return { status: "result", result: jsonOf(value) };
|
|
211
|
+
const parsed = Answer.safeParse(value);
|
|
212
|
+
if (parsed.success) return { status: "result", result: parsed.data.result };
|
|
213
|
+
return { status: "failure", reason: "the session did not answer with a result" };
|
|
214
|
+
}
|