@niwa-labs/requests 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 +2 -2
- package/package.json +41 -4
- package/src/access-ask.ts +97 -0
- package/src/actions.ts +216 -0
- package/src/cockpit/actions.ts +68 -0
- package/src/cockpit/answer-form.tsx +103 -0
- package/src/cockpit/answers.ts +71 -0
- package/src/cockpit/history.tsx +149 -0
- package/src/cockpit/index.tsx +28 -0
- package/src/cockpit/page.tsx +115 -0
- package/src/entity.ts +58 -0
- package/src/index.ts +619 -0
- package/src/question.ts +50 -0
- package/src/records-entry.ts +47 -0
- package/src/records.ts +111 -0
- package/src/resolver.ts +74 -0
- package/src/state.ts +398 -0
- package/test/ask.test.ts +265 -0
- package/test/cockpit-actions.test.ts +36 -0
- package/test/cockpit-answers.test.ts +77 -0
- package/test/deadline.test.ts +40 -0
- package/test/ending.test.ts +223 -0
- package/test/entity.test.ts +18 -0
- package/test/ledger.test.ts +64 -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,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/requests
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Questions to the owner and their typed answers.
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/requests",
|
|
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/plugin": "0.0.0",
|
|
15
|
+
"@niwa-labs/ui-kit": "0.0.0",
|
|
16
|
+
"zod": "^4.6.7"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@happy-dom/global-registrator": "^21.0.4",
|
|
20
|
+
"@niwa-labs/testing": "0.0.0",
|
|
21
|
+
"@tanstack/react-query": "^5.108.2",
|
|
22
|
+
"@types/react": "^19.3.0",
|
|
23
|
+
"@types/react-dom": "^19.3.0",
|
|
24
|
+
"react": "^19.3.1",
|
|
25
|
+
"react-dom": "^19.3.1"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@tanstack/react-query": "^5.108.2",
|
|
29
|
+
"react": "^19.3.1",
|
|
30
|
+
"react-dom": "^19.3.1"
|
|
31
|
+
},
|
|
32
|
+
"peerDependenciesMeta": {
|
|
33
|
+
"@tanstack/react-query": {
|
|
34
|
+
"optional": true
|
|
35
|
+
},
|
|
36
|
+
"react": {
|
|
37
|
+
"optional": true
|
|
38
|
+
},
|
|
39
|
+
"react-dom": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The question of an `ask` rule: a call that meets a rule that asks
|
|
3
|
+
* becomes a request to the owner, and the call waits for its end.
|
|
4
|
+
*
|
|
5
|
+
* The core holds the call and the answers in force; this module only puts the question as a
|
|
6
|
+
* request and says how it ended. Nobody answering, a cancel and an expiry are one thing: no answer.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { ASK_SCOPES, OptionIdSchema, jsonOf, owner } from "@niwa-labs/core";
|
|
12
|
+
import type { Answer, AskOutcome, AskQuestion, Question, QuestionOption, Timestamp, Address } from "@niwa-labs/core";
|
|
13
|
+
|
|
14
|
+
import { Deadline, QuestionName } from "./records.ts";
|
|
15
|
+
import type { RequestCreated, RequestId } from "./records.ts";
|
|
16
|
+
|
|
17
|
+
/** The name of the question the owner is asked when a call meets a rule that asks. */
|
|
18
|
+
export const ACCESS_ASK = QuestionName.parse("access.ask");
|
|
19
|
+
|
|
20
|
+
/** What the owner may answer, as options: the three scopes that let the call through, and a refusal. */
|
|
21
|
+
const OPTIONS: readonly QuestionOption[] = [
|
|
22
|
+
{ id: OptionIdSchema.parse("once"), label: "Allow this call", flavor: "allow_once" },
|
|
23
|
+
{ id: OptionIdSchema.parse("run"), label: "Allow this action for the subject's lifetime", flavor: "allow_always" },
|
|
24
|
+
{ id: OptionIdSchema.parse("always"), label: "Allow always (written into its grant)", flavor: "allow_always" },
|
|
25
|
+
{ id: OptionIdSchema.parse("no"), label: "Refuse", flavor: "reject_once" },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** What the owner is shown of a call: who calls what, with what, and under which rule. */
|
|
29
|
+
export function questionOf(asked: AskQuestion): Question {
|
|
30
|
+
const action = `${asked.name}${asked.target === undefined ? "" : `@${asked.target}`}`;
|
|
31
|
+
const who = `${asked.principal.kind}:${asked.principal.id}`;
|
|
32
|
+
return {
|
|
33
|
+
kind: "permission",
|
|
34
|
+
title: `${who} calls ${action}`,
|
|
35
|
+
options: [...OPTIONS],
|
|
36
|
+
subject: {
|
|
37
|
+
who,
|
|
38
|
+
action,
|
|
39
|
+
rule: asked.rule,
|
|
40
|
+
input: jsonOf(asked.input),
|
|
41
|
+
...(asked.reason === undefined ? {} : { reason: asked.reason }),
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** How an answer to the question ends the wait of the call: only an answer of the owner lets it through. */
|
|
47
|
+
export function outcomeOf(answer: Answer): AskOutcome {
|
|
48
|
+
const chosen = "ids" in answer && answer.ids.length === 1 ? answer.ids[0] : undefined;
|
|
49
|
+
if (chosen === "no") return "refused";
|
|
50
|
+
return ASK_SCOPES.find((scope) => scope === chosen) ?? "unanswered";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The calls that wait for the owner in this process, by the request that asks about them. */
|
|
54
|
+
export class PendingAsks {
|
|
55
|
+
private readonly waiting = new Map<RequestId, (outcome: AskOutcome) => void>();
|
|
56
|
+
|
|
57
|
+
/** Wait for the end of a request; the wait is the call's. */
|
|
58
|
+
expect(id: RequestId): Promise<AskOutcome> {
|
|
59
|
+
return new Promise((resolve) => this.waiting.set(id, resolve));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A request that is not waited for any more. */
|
|
63
|
+
forget(id: RequestId): void {
|
|
64
|
+
this.waiting.delete(id);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The request ended: the call that waited for it goes on or is denied. A request nobody waits for is left alone.
|
|
69
|
+
*
|
|
70
|
+
* An access ask ends only by an answer of the owner. `by` is the address the writer of the answer
|
|
71
|
+
* record is bound to. An answer by anyone else, or by nobody the binding knows, is no answer: the
|
|
72
|
+
* call is denied, whatever the answer says.
|
|
73
|
+
*/
|
|
74
|
+
end(id: RequestId, outcome: AskOutcome, by?: Address): void {
|
|
75
|
+
const resolve = this.waiting.get(id);
|
|
76
|
+
if (resolve === undefined) return;
|
|
77
|
+
this.waiting.delete(id);
|
|
78
|
+
resolve(by?.kind === "owner" ? outcome : "unanswered");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The request a question becomes, addressed to the owner and with a deadline of its own. */
|
|
83
|
+
export function requestOf(
|
|
84
|
+
id: RequestId,
|
|
85
|
+
asked: AskQuestion,
|
|
86
|
+
now: Timestamp,
|
|
87
|
+
timeoutMs: number,
|
|
88
|
+
): z.infer<typeof RequestCreated.schema> {
|
|
89
|
+
return {
|
|
90
|
+
id,
|
|
91
|
+
to: owner,
|
|
92
|
+
answerPolicy: "owner-only",
|
|
93
|
+
question: ACCESS_ASK,
|
|
94
|
+
input: questionOf(asked),
|
|
95
|
+
deadline: Deadline.parse(now + timeoutMs),
|
|
96
|
+
};
|
|
97
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions of the requests module, as typed references: name, description and the two schemas.
|
|
3
|
+
*
|
|
4
|
+
* A caller imports these to call a request action with input and output checked by the type
|
|
5
|
+
* checker, on the host and on a client. The module's factory builds its real actions from the same
|
|
6
|
+
* references (`action(requestOpen, { recovery, run })`).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { AnswerSchema, EntityDescription, IdText, QuestionSchema, actionName, actionRef, getRef, listRef, Address } from "@niwa-labs/core";
|
|
12
|
+
import type { ActionName } from "@niwa-labs/core";
|
|
13
|
+
|
|
14
|
+
import { Deadline, QuestionName, RequestId } from "./records.ts";
|
|
15
|
+
|
|
16
|
+
/** The input of the action that asks. */
|
|
17
|
+
export const AskInput = z.object({
|
|
18
|
+
/** Who may answer. */
|
|
19
|
+
to: Address,
|
|
20
|
+
/** An operator decision bypasses all automatic resolvers. */
|
|
21
|
+
answerPolicy: z.literal("owner-only").optional(),
|
|
22
|
+
/** The name of the question. */
|
|
23
|
+
question: QuestionName,
|
|
24
|
+
/** What is asked: the question, whole. */
|
|
25
|
+
input: QuestionSchema,
|
|
26
|
+
/** When the request stops waiting. Without one it waits for ever. */
|
|
27
|
+
deadline: Deadline.optional(),
|
|
28
|
+
/**
|
|
29
|
+
* Who asks, for a handler that stands for an address of its own: it may then cancel its request
|
|
30
|
+
* as that address. A client is held to the address it is bound to: the payload does not change that.
|
|
31
|
+
*/
|
|
32
|
+
from: Address.optional(),
|
|
33
|
+
/**
|
|
34
|
+
* For a caller in this process: the zod schema of the value of a form. While the ask waits it
|
|
35
|
+
* checks the value whole, refinements included; it is never written.
|
|
36
|
+
*/
|
|
37
|
+
check: z.custom<z.ZodType<unknown>>((value) => value instanceof z.core.$ZodType).optional(),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Which request a command names: its id, a unique prefix or suffix of it (`label:ship`), or the run
|
|
42
|
+
* whose one open ask it is.
|
|
43
|
+
*/
|
|
44
|
+
const Named = {
|
|
45
|
+
id: IdText.optional(),
|
|
46
|
+
run: z.string().min(1).brand<"RunRef">().optional(),
|
|
47
|
+
};
|
|
48
|
+
const oneNamed = (input: { id?: string | undefined; run?: string | undefined }): boolean => (input.id === undefined) !== (input.run === undefined);
|
|
49
|
+
const NAMED = "give the request (id, or a unique start or end of it), or the run whose one open ask it is";
|
|
50
|
+
|
|
51
|
+
export const AnswerInput = z.object({ ...Named, answer: AnswerSchema }).refine(oneNamed, NAMED);
|
|
52
|
+
export const CancelInput = z.object({
|
|
53
|
+
...Named,
|
|
54
|
+
reason: z.string().optional(),
|
|
55
|
+
/**
|
|
56
|
+
* Who cancels, for a handler that stands for an address of its own. A client is held to the
|
|
57
|
+
* address it is bound to, as it is for a message: the payload does not change that.
|
|
58
|
+
*/
|
|
59
|
+
by: Address.optional(),
|
|
60
|
+
}).refine(oneNamed, NAMED);
|
|
61
|
+
export const OpenInput = z.object({ to: Address.optional() });
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* What answering a request answers.
|
|
65
|
+
*
|
|
66
|
+
* An answer is accepted when it stands: it was written, or the same answer already stands.
|
|
67
|
+
* An answer to a request that was cancelled or expired is not accepted, and says why.
|
|
68
|
+
*/
|
|
69
|
+
export const AnswerOutput = z.object({
|
|
70
|
+
id: RequestId,
|
|
71
|
+
/** Whether the answer stands. */
|
|
72
|
+
accepted: z.boolean(),
|
|
73
|
+
/** Why the answer does not stand: the request was over before it came. */
|
|
74
|
+
reason: z.enum(["cancelled", "expired"]).optional(),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export const OpenRequest = z.object({
|
|
78
|
+
answerPolicy: z.literal("owner-only").optional(),
|
|
79
|
+
id: RequestId,
|
|
80
|
+
to: Address,
|
|
81
|
+
question: z.string().min(1),
|
|
82
|
+
input: QuestionSchema,
|
|
83
|
+
from: Address.optional(),
|
|
84
|
+
deadline: z.number().optional(),
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/** A paused invocation is a request with typed choices, listed with the questions. */
|
|
88
|
+
export const OpenPaused = z.object({
|
|
89
|
+
kind: z.literal("paused"),
|
|
90
|
+
invocation: z.string().min(1),
|
|
91
|
+
choices: z.array(z.string()),
|
|
92
|
+
key: z.string().optional(),
|
|
93
|
+
reason: z.string().optional(),
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
export const OpenOutput = z.object({ requests: z.array(z.union([OpenRequest, OpenPaused])) });
|
|
97
|
+
|
|
98
|
+
/** What asking returns once the request is answered: the answer, with the id of the request, so a caller can find it again. */
|
|
99
|
+
export const AskAnswered = z.object({ id: RequestId, answer: AnswerSchema });
|
|
100
|
+
|
|
101
|
+
/** What asking returns outside a step: the request is made and still open; the caller reads or waits for the answer by its id. */
|
|
102
|
+
export const AskOpen = z.object({ id: RequestId, status: z.literal("open") });
|
|
103
|
+
|
|
104
|
+
/** What asking returns: the answer inside a step, the open request outside one. */
|
|
105
|
+
export const AskOutput = z.union([AskAnswered, AskOpen]);
|
|
106
|
+
|
|
107
|
+
/** The answer of an ask a step made: a step waits, so what it gets is always the answer. */
|
|
108
|
+
export function answeredBy(output: z.infer<typeof AskOutput>): z.infer<typeof AskAnswered> {
|
|
109
|
+
if (!("answer" in output)) throw new Error(`the request "${output.id}" is still open`);
|
|
110
|
+
return output;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const requestAsk = actionRef("request.ask", {
|
|
114
|
+
description:
|
|
115
|
+
"Ask a question. As a step of a workflow or of a handler it waits for the answer (the wait survives a restart) and returns the answer with the id of the request. Called directly, from the CLI or MCP, it cannot wait: it creates the request and returns at once {id, status: \"open\"}; poll request.get with that id until its status is no longer open, and read the answer there.",
|
|
116
|
+
input: AskInput,
|
|
117
|
+
output: AskOutput,
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
export const requestAnswer = actionRef("request.answer", {
|
|
121
|
+
description: "Answer a request. Only the addressee may; the first answer stands.",
|
|
122
|
+
input: AnswerInput,
|
|
123
|
+
output: AnswerOutput,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
export const requestCancel = actionRef("request.cancel", {
|
|
127
|
+
description: "Cancel an open request. Only its asker or addressee may.",
|
|
128
|
+
input: CancelInput,
|
|
129
|
+
output: z.object({ id: RequestId }),
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
export const requestOpen = actionRef("request.open", {
|
|
133
|
+
description: "List what waits: the open requests and the invocations paused for a decision.",
|
|
134
|
+
input: OpenInput,
|
|
135
|
+
output: OpenOutput,
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
/** How a request stands: waiting, or how it ended. */
|
|
139
|
+
export const RequestStatus = z.enum(["open", "answered", "cancelled", "expired"]);
|
|
140
|
+
|
|
141
|
+
/** The fields of a request that a list and a read both show. */
|
|
142
|
+
const GLANCE = {
|
|
143
|
+
answerPolicy: z.literal("owner-only").optional(),
|
|
144
|
+
status: RequestStatus,
|
|
145
|
+
question: QuestionName,
|
|
146
|
+
to: Address,
|
|
147
|
+
from: Address.optional(),
|
|
148
|
+
deadline: Deadline.optional(),
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export const requestList = listRef("request.list", {
|
|
152
|
+
kind: "request",
|
|
153
|
+
noun: "request",
|
|
154
|
+
detail: "Open and ended ones, oldest first; the filters narrow by how it stands, who may answer it, who asked and the name of the question.",
|
|
155
|
+
filter: { status: RequestStatus.optional(), to: Address.optional(), from: Address.optional(), question: QuestionName.optional() },
|
|
156
|
+
item: GLANCE,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
/** One request, whole. */
|
|
160
|
+
export const RequestEntity = z.object({
|
|
161
|
+
id: RequestId,
|
|
162
|
+
description: EntityDescription,
|
|
163
|
+
...GLANCE,
|
|
164
|
+
/** What was asked: the question, whole. */
|
|
165
|
+
input: QuestionSchema,
|
|
166
|
+
/** The answer, once there is one. */
|
|
167
|
+
answer: AnswerSchema.optional(),
|
|
168
|
+
/** Who answered or cancelled it, when the caller was bound to an address. */
|
|
169
|
+
by: Address.optional(),
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
export const requestGet = getRef("request.get", {
|
|
173
|
+
kind: "request",
|
|
174
|
+
noun: "request",
|
|
175
|
+
detail: "It carries the question, whole, and the answer once there is one.",
|
|
176
|
+
entity: RequestEntity,
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
export const requestFind = actionRef("request.find", {
|
|
180
|
+
description:
|
|
181
|
+
"Find the request that a record caused: the one a handler woken by that record asked, by the name of its question. How a handler finds its own request again: a caller does not choose the id of one.",
|
|
182
|
+
input: z.object({
|
|
183
|
+
/** The id of the record that caused the request. */
|
|
184
|
+
cause: z.string().min(1),
|
|
185
|
+
/** The name of the question the request asked. */
|
|
186
|
+
question: QuestionName,
|
|
187
|
+
}),
|
|
188
|
+
output: z.object({ id: RequestId.optional() }),
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
/** How an answer given to a resolve was found. */
|
|
192
|
+
export const ResolveInfo = z.object({
|
|
193
|
+
how: z.string().min(1).optional(),
|
|
194
|
+
area: z.string().min(1).optional(),
|
|
195
|
+
source: z.string().min(1).optional(),
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
export const requestResolve = actionRef("request.resolve", {
|
|
199
|
+
description: "Let the resolvers answer a request before it reaches its addressee. An answer given here is the answer: the resolvers are not asked.",
|
|
200
|
+
input: z.object({
|
|
201
|
+
id: RequestId,
|
|
202
|
+
answer: AnswerSchema.optional(),
|
|
203
|
+
/** How the answer given here was found, kept apart from the answer. */
|
|
204
|
+
info: ResolveInfo.optional(),
|
|
205
|
+
}),
|
|
206
|
+
output: z.object({ answered: z.boolean() }),
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
export const REQUEST_ASK: ActionName = actionName("request.ask");
|
|
210
|
+
export const REQUEST_ANSWER: ActionName = actionName("request.answer");
|
|
211
|
+
export const REQUEST_CANCEL: ActionName = actionName("request.cancel");
|
|
212
|
+
export const REQUEST_OPEN: ActionName = actionName("request.open");
|
|
213
|
+
export const REQUEST_LIST: ActionName = actionName("request.list");
|
|
214
|
+
export const REQUEST_GET: ActionName = actionName("request.get");
|
|
215
|
+
export const REQUEST_RESOLVE: ActionName = actionName("request.resolve");
|
|
216
|
+
export const REQUEST_FIND: ActionName = actionName("request.find");
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request actions as the cockpit calls them: name and the part of each schema the page reads.
|
|
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 Option = z.object({ id: z.string(), label: z.string(), description: z.string().optional(), flavor: z.string() });
|
|
11
|
+
export type Option = z.infer<typeof Option>;
|
|
12
|
+
|
|
13
|
+
const Wording = { title: z.string(), detail: z.string().optional() };
|
|
14
|
+
const Pick = { ...Wording, options: z.array(Option), allowOther: z.boolean().optional() };
|
|
15
|
+
|
|
16
|
+
export const Question = z.discriminatedUnion("kind", [
|
|
17
|
+
z.object({ kind: z.literal("choice"), ...Pick }),
|
|
18
|
+
z.object({ kind: z.literal("multi"), ...Pick }),
|
|
19
|
+
z.object({ kind: z.literal("confirm"), ...Pick }),
|
|
20
|
+
z.object({ kind: z.literal("text"), ...Wording }),
|
|
21
|
+
z.object({ kind: z.literal("form"), ...Wording, schema: z.record(z.string(), z.unknown()) }),
|
|
22
|
+
z.object({ kind: z.literal("permission"), ...Wording, options: z.array(Option), subject: z.record(z.string(), z.unknown()) }),
|
|
23
|
+
]);
|
|
24
|
+
export type Question = z.infer<typeof Question>;
|
|
25
|
+
|
|
26
|
+
/** An address, as the page names it: its kind and what it names. */
|
|
27
|
+
export const Address = z.object({ kind: z.string(), id: z.string().optional(), harness: z.string().optional() }).loose();
|
|
28
|
+
export type Address = z.infer<typeof Address>;
|
|
29
|
+
|
|
30
|
+
export const OpenRequest = z.object({ id: z.string(), to: Address, answerPolicy: z.literal("owner-only").optional(), question: z.string(), input: Question, from: Address.optional(), deadline: z.number().optional() });
|
|
31
|
+
export type OpenRequest = z.infer<typeof OpenRequest>;
|
|
32
|
+
|
|
33
|
+
export const OpenPaused = z.object({
|
|
34
|
+
kind: z.literal("paused"),
|
|
35
|
+
invocation: z.string(),
|
|
36
|
+
choices: z.array(z.string()),
|
|
37
|
+
key: z.string().optional(),
|
|
38
|
+
reason: z.string().optional(),
|
|
39
|
+
});
|
|
40
|
+
export type OpenPaused = z.infer<typeof OpenPaused>;
|
|
41
|
+
|
|
42
|
+
export const openAction = {
|
|
43
|
+
name: "request.open",
|
|
44
|
+
input: z.object({}),
|
|
45
|
+
output: z.object({ requests: z.array(z.union([OpenPaused, OpenRequest])) }),
|
|
46
|
+
} as const;
|
|
47
|
+
|
|
48
|
+
/** What an answer to a request is: the options picked, a free text, or the value of a form. */
|
|
49
|
+
export const Answer = z.union([z.object({ ids: z.array(z.string()) }), z.object({ text: z.string() }), z.object({ form: z.unknown() })]);
|
|
50
|
+
export type Answer = z.infer<typeof Answer>;
|
|
51
|
+
|
|
52
|
+
export const answerAction = {
|
|
53
|
+
name: "request.answer",
|
|
54
|
+
input: z.object({ id: z.string(), answer: Answer }),
|
|
55
|
+
output: z.object({ id: z.string(), accepted: z.boolean(), reason: z.enum(["cancelled", "expired"]).optional() }),
|
|
56
|
+
} as const;
|
|
57
|
+
|
|
58
|
+
export const overrideAction = {
|
|
59
|
+
name: "request.resolve",
|
|
60
|
+
input: answerAction.input,
|
|
61
|
+
output: z.object({ answered: z.boolean() }),
|
|
62
|
+
} as const;
|
|
63
|
+
|
|
64
|
+
export const resolveAction = {
|
|
65
|
+
name: "niwa.invocation.resolve",
|
|
66
|
+
input: z.object({ invocation: z.string(), choice: z.string() }),
|
|
67
|
+
output: z.unknown(),
|
|
68
|
+
} as const;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { readFields, SchemaFields, useAction, useViewer, type FormSchema } from "@niwa-labs/cockpit-sdk";
|
|
2
|
+
import { Button, cn } from "@niwa-labs/ui-kit";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
|
|
5
|
+
import { answerAction, overrideAction, type OpenRequest, type Option } from "./actions.ts";
|
|
6
|
+
import { answerOf, EMPTY, type Built, type Filled } from "./answers.ts";
|
|
7
|
+
|
|
8
|
+
function OptionButton({ option, selected, onPick }: { option: Option; selected: boolean; onPick: () => void }) {
|
|
9
|
+
return (
|
|
10
|
+
<button
|
|
11
|
+
type="button"
|
|
12
|
+
aria-pressed={selected}
|
|
13
|
+
onClick={onPick}
|
|
14
|
+
className={cn(
|
|
15
|
+
"flex min-w-0 flex-col items-start rounded-md border px-3 py-2 text-left text-sm wrap-anywhere hover:bg-accent",
|
|
16
|
+
selected && "border-ring bg-accent",
|
|
17
|
+
)}
|
|
18
|
+
>
|
|
19
|
+
<span className="font-medium">{option.label}</span>
|
|
20
|
+
{option.description !== undefined && <span className="text-xs text-muted-foreground">{option.description}</span>}
|
|
21
|
+
</button>
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function AnswerForm({ request, onSent }: { request: OpenRequest; onSent: () => void }) {
|
|
26
|
+
const question = request.input;
|
|
27
|
+
const viewer = useViewer();
|
|
28
|
+
const overriding = viewer.owner && request.to.kind !== "owner" && request.answerPolicy !== "owner-only";
|
|
29
|
+
const answer = useAction(answerAction);
|
|
30
|
+
const override = useAction(overrideAction);
|
|
31
|
+
const send = overriding ? override : answer;
|
|
32
|
+
const allowed = viewer.can(overriding ? overrideAction : answerAction);
|
|
33
|
+
const [filled, setFilled] = useState<Filled>(EMPTY);
|
|
34
|
+
const [problem, setProblem] = useState<string>();
|
|
35
|
+
|
|
36
|
+
const submit = (built: Built): void => {
|
|
37
|
+
if ("problem" in built) return setProblem(built.problem);
|
|
38
|
+
setProblem(undefined);
|
|
39
|
+
send.mutate({ id: request.id, answer: built.answer }, { onSettled: onSent });
|
|
40
|
+
};
|
|
41
|
+
const options = "options" in question ? question.options : [];
|
|
42
|
+
const toggle = (id: string): void => setFilled((now) => {
|
|
43
|
+
const picked = now.picked.includes(id)
|
|
44
|
+
? now.picked.filter((one) => one !== id)
|
|
45
|
+
: question.kind === "multi" ? [...now.picked, id] : [id];
|
|
46
|
+
return { ...now, picked };
|
|
47
|
+
});
|
|
48
|
+
const refused = overriding
|
|
49
|
+
? override.data?.answered === false ? "Не удалось ответить за адресата." : undefined
|
|
50
|
+
: answer.data?.accepted === false
|
|
51
|
+
? answer.data.reason === "expired" ? "Срок ответа истёк." : "Запрос уже закрыт."
|
|
52
|
+
: undefined;
|
|
53
|
+
const typed = question.kind === "text" || ("allowOther" in question && question.allowOther === true);
|
|
54
|
+
const schema: FormSchema | undefined = question.kind === "form" ? question.schema : undefined;
|
|
55
|
+
if (!allowed) return <p className="text-sm text-muted-foreground">Ответ доступен адресату запроса.</p>;
|
|
56
|
+
|
|
57
|
+
return (
|
|
58
|
+
<form
|
|
59
|
+
className="flex min-w-0 flex-col gap-3"
|
|
60
|
+
onSubmit={(event) => {
|
|
61
|
+
event.preventDefault();
|
|
62
|
+
try {
|
|
63
|
+
const value = schema === undefined
|
|
64
|
+
? filled
|
|
65
|
+
: { ...filled, form: readFields(schema, new FormData(event.currentTarget)) };
|
|
66
|
+
submit(answerOf(question, value));
|
|
67
|
+
} catch (error) {
|
|
68
|
+
setProblem(error instanceof Error ? error.message : "Проверьте заполненные поля.");
|
|
69
|
+
}
|
|
70
|
+
}}
|
|
71
|
+
>
|
|
72
|
+
{options.length > 0 && (
|
|
73
|
+
<div className="flex min-w-0 flex-wrap gap-2" role="group" aria-label="Варианты ответа">
|
|
74
|
+
{options.map((option) => (
|
|
75
|
+
<OptionButton key={option.id} option={option} selected={filled.picked.includes(option.id)} onPick={() => toggle(option.id)} />
|
|
76
|
+
))}
|
|
77
|
+
</div>
|
|
78
|
+
)}
|
|
79
|
+
{schema !== undefined && <SchemaFields schema={schema} />}
|
|
80
|
+
{typed && (
|
|
81
|
+
<label className="flex flex-col gap-1 text-sm">
|
|
82
|
+
{question.kind === "text" ? "Ваш ответ" : "Свой вариант"}
|
|
83
|
+
<textarea
|
|
84
|
+
rows={2}
|
|
85
|
+
value={filled.text}
|
|
86
|
+
onChange={(event) => setFilled((now) => ({ ...now, text: event.target.value }))}
|
|
87
|
+
className="w-full min-w-0 rounded-md border bg-background px-3 py-2"
|
|
88
|
+
/>
|
|
89
|
+
</label>
|
|
90
|
+
)}
|
|
91
|
+
<div className="flex min-w-0 flex-wrap items-center gap-3">
|
|
92
|
+
<Button type="submit" size="sm" disabled={send.isPending}>
|
|
93
|
+
{send.isPending ? "Отправляю…" : overriding ? "Ответить за адресата" : "Ответить"}
|
|
94
|
+
</Button>
|
|
95
|
+
{(problem !== undefined || refused !== undefined || send.isError) && (
|
|
96
|
+
<span role="alert" className="min-w-0 text-sm text-destructive wrap-anywhere">
|
|
97
|
+
{problem ?? refused ?? "Не удалось отправить ответ."}
|
|
98
|
+
</span>
|
|
99
|
+
)}
|
|
100
|
+
</div>
|
|
101
|
+
</form>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** What a form of a question turns into: the answer the host takes, or the reason it cannot be sent yet. */
|
|
2
|
+
|
|
3
|
+
import type { Answer, Question } from "./actions.ts";
|
|
4
|
+
|
|
5
|
+
/** What the person has filled in so far. */
|
|
6
|
+
export type Filled = { picked: readonly string[]; text: string; form?: unknown };
|
|
7
|
+
|
|
8
|
+
export const EMPTY: Filled = { picked: [], text: "" };
|
|
9
|
+
|
|
10
|
+
export type Built = { answer: Answer } | { problem: string };
|
|
11
|
+
|
|
12
|
+
const ADDRESS_LABELS: Record<string, string> = {
|
|
13
|
+
owner: "Владелец", agent: "Агент", session: "Сессия", task: "Задача", client: "Клиент", strategy: "Стратегия",
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function addressText(address: { kind: string; id?: string | undefined; harness?: string | undefined }): string {
|
|
17
|
+
const label = ADDRESS_LABELS[address.kind] ?? address.kind;
|
|
18
|
+
const target = [address.harness, address.id].filter(Boolean).join(" · ");
|
|
19
|
+
return target ? `${label} ${target}` : label;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The answer a question takes from what was filled in; a problem says what is missing or wrong. */
|
|
23
|
+
export function answerOf(question: Question, filled: Filled): Built {
|
|
24
|
+
// A question that takes "other" has two ways to answer: pick from its options, or write one of your own.
|
|
25
|
+
// Both at once is not an answer, and the text is never dropped in silence.
|
|
26
|
+
if ("allowOther" in question && question.allowOther === true && filled.text.trim() !== "") {
|
|
27
|
+
return filled.picked.length > 0 ? { problem: "Выберите вариант или напишите свой ответ." } : otherAnswer(filled.text);
|
|
28
|
+
}
|
|
29
|
+
switch (question.kind) {
|
|
30
|
+
case "choice":
|
|
31
|
+
case "confirm":
|
|
32
|
+
case "permission": {
|
|
33
|
+
const [only, ...more] = filled.picked;
|
|
34
|
+
if (only === undefined) return { problem: "Выберите вариант." };
|
|
35
|
+
if (more.length > 0) return { problem: "Выберите один вариант." };
|
|
36
|
+
return { answer: { ids: [only] } };
|
|
37
|
+
}
|
|
38
|
+
case "multi":
|
|
39
|
+
return { answer: { ids: [...filled.picked] } };
|
|
40
|
+
case "text":
|
|
41
|
+
return filled.text.trim() === "" ? { problem: "Напишите ответ." } : { answer: { text: filled.text } };
|
|
42
|
+
case "form":
|
|
43
|
+
return filled.form === undefined ? { problem: "Заполните форму." } : { answer: { form: filled.form } };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The free text of a question that takes "other": an answer of its own, apart from the options. */
|
|
48
|
+
export function otherAnswer(text: string): Built {
|
|
49
|
+
return text.trim() === "" ? { problem: "Напишите ответ." } : { answer: { text } };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** One thing a permission is about, as the page shows it. */
|
|
53
|
+
export type SubjectLine = { label: string; value: unknown };
|
|
54
|
+
|
|
55
|
+
/** What the owner decides on is shown in this order; anything else a subject says follows it. */
|
|
56
|
+
const SUBJECT_ORDER = ["who", "action", "tool", "kind", "target", "rule", "input", "reason"];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What a permission question is about, line by line: who calls what with which input and under which
|
|
60
|
+
* rule, or which tool acts on what. Structured values retain their shape for the display.
|
|
61
|
+
*/
|
|
62
|
+
export function subjectLines(subject: Record<string, unknown>): SubjectLine[] {
|
|
63
|
+
const rank = (key: string): number => {
|
|
64
|
+
const at = SUBJECT_ORDER.indexOf(key);
|
|
65
|
+
return at === -1 ? SUBJECT_ORDER.length : at;
|
|
66
|
+
};
|
|
67
|
+
return Object.keys(subject)
|
|
68
|
+
.filter((key) => subject[key] !== undefined)
|
|
69
|
+
.sort((one, other) => rank(one) - rank(other))
|
|
70
|
+
.map((key) => ({ label: key, value: subject[key] }));
|
|
71
|
+
}
|