@niwa-labs/delegate 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/src/records.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The records entry of delegate: the records it writes, the typed references of its actions, and the
3
+ * request for context a data owner serves. No factory and nothing that runs.
4
+ *
5
+ * Delegate answers for the owner the requests put to one agent. It recalls what the owner decided
6
+ * about the same question in the same area; it lets the agent, or a judge of the area, decide within
7
+ * bounds; and what nobody may decide it forwards to the owner, whose answer becomes his decision.
8
+ */
9
+
10
+ import { Address, AnswerSchema, EntityDescription, IdText, QuestionSchema, actionRef, idSchema, listRef, record } from "@niwa-labs/core";
11
+ import type { Id } from "@niwa-labs/core";
12
+ import { QuestionName, RequestId } from "@niwa-labs/requests/records";
13
+ import { z } from "zod";
14
+
15
+ import { JournalPosition } from "./context.ts";
16
+
17
+ export { ContextAnswer, ContextItem, ContextRequest, JournalPosition, SourceRef, contextSource } from "./context.ts";
18
+
19
+ /** The id of a decision, `dec-3fa9c2`. */
20
+ export const DecisionId = idSchema("decision");
21
+ export type DecisionId = Id<"decision">;
22
+
23
+ /** Who decided: the owner, the agent within its bounds, or the judge of the area. */
24
+ export const DecisionKind = z.enum(["owner", "agent", "judge"]);
25
+ export type DecisionKind = z.infer<typeof DecisionKind>;
26
+
27
+ /**
28
+ * A question was decided in an area.
29
+ *
30
+ * The key of a question is its name and what was asked, without the area: the area is the scope of
31
+ * the decision, not part of the question. The owner's decisions are what is recalled.
32
+ */
33
+ export const DecisionMade = record(
34
+ "delegate.decided",
35
+ z.object({
36
+ id: DecisionId,
37
+ /** A few words a person reads in a list: the title of the question. */
38
+ description: EntityDescription,
39
+ /** The key of the question. */
40
+ question: z.string().min(1),
41
+ area: z.string().min(1),
42
+ kind: DecisionKind,
43
+ answer: AnswerSchema,
44
+ /** The request the decision answered. */
45
+ request: RequestId,
46
+ /** The records it stands on: the answer of the owner or the judge, the sources an agent read. */
47
+ grounds: z.array(z.string().min(1)),
48
+ /** Who decided, when it speaks as an address. */
49
+ by: Address.optional(),
50
+ }),
51
+ { guard: {
52
+ group: "delegate.decision", key: data => data.id,
53
+ initial: () => false,
54
+ admit: decided => decided ? { code: "decided", reason: "the request is already decided" } : undefined,
55
+ fold: () => true,
56
+ } },
57
+ );
58
+
59
+ /** A decision was revoked: it is no longer recalled. */
60
+ export const DecisionRevoked = record(
61
+ "delegate.revoked",
62
+ z.object({ decision: DecisionId, by: Address.optional(), reason: z.string().min(1).optional() }),
63
+ );
64
+
65
+ /** A request put to the agent was passed on: to the judge of its area or to the owner. */
66
+ export const RequestForwarded = record(
67
+ "delegate.forwarded",
68
+ z.object({ request: RequestId, to: Address }),
69
+ );
70
+
71
+ /** One handler owns forwarding and resolving this request throughout its lifetime. */
72
+ export const HandlingStarted = record("delegate.handling.started", z.object({ request: RequestId }), { guard: {
73
+ group: "delegate.handling", key: data => data.request,
74
+ initial: () => false,
75
+ admit: started => started ? { code: "claimed", reason: "the request already has a delegate" } : undefined,
76
+ fold: () => true,
77
+ } });
78
+
79
+ /** The record types delegate declares. */
80
+ export const DELEGATE_TYPES = [HandlingStarted, DecisionMade, DecisionRevoked, RequestForwarded] as const;
81
+
82
+ export const delegateRecall = actionRef("delegate.recall", {
83
+ description:
84
+ "Says what the owner decided about a question in its area: the same question name and what was asked, without the area. Give asOf, a journal position, to read the decisions as they stood then. A question without an area recalls nothing.",
85
+ input: z.strictObject({ question: QuestionName, input: QuestionSchema, asOf: JournalPosition.optional() }),
86
+ output: z.union([
87
+ z.object({ found: z.literal(false) }),
88
+ z.object({ found: z.literal(true), answer: AnswerSchema, area: z.string(), decision: DecisionId }),
89
+ ]),
90
+ });
91
+
92
+ export const delegateDecide = actionRef("delegate.decide", {
93
+ description:
94
+ "Decides an open request put to the agent, within bounds: the area must be the area the request names, a grant allows delegate.decide@<area>, and the answer must be one its question takes. A request is decided once: the same answer again gives the decision back, another is refused. The answer answers the request and is kept as a decision; whatever was forwarded for it is withdrawn. A decision the request did not take, because it ended otherwise first, is revoked.",
95
+ input: z.strictObject({
96
+ /** The request: its id, or a unique start or end of it among the requests put to the agent. */
97
+ request: IdText,
98
+ /** The area of the request: what the grant is checked against. */
99
+ area: z.string().min(1),
100
+ answer: AnswerSchema,
101
+ /** The records the decision stands on, such as the sources read for it. */
102
+ grounds: z.array(z.string().min(1)).default([]),
103
+ }),
104
+ output: z.object({ decision: DecisionId }),
105
+ target: (input) => input.area,
106
+ });
107
+
108
+ export const delegateRevoke = actionRef("delegate.revoke", {
109
+ description: "Revokes a decision so it is no longer recalled. Only the owner may.",
110
+ input: z.strictObject({ decision: IdText, reason: z.string().min(1).optional() }),
111
+ output: z.object({ decision: DecisionId }),
112
+ });
113
+
114
+ export const delegateDecisionList = listRef("delegate.decision.list", {
115
+ kind: "decision",
116
+ noun: "decision",
117
+ detail: "Oldest first, revoked ones too; the filters narrow by area and by who decided.",
118
+ filter: { area: z.string().min(1).optional(), kind: DecisionKind.optional() },
119
+ item: { area: z.string(), kind: DecisionKind, request: RequestId, revoked: z.boolean() },
120
+ });
@@ -0,0 +1,78 @@
1
+ // The request for context is a contract between delegate and a data owner it does not import: the
2
+ // owner serves it under its own name, and both sides are held to the same schemas.
3
+
4
+ import { expect, test } from "bun:test";
5
+
6
+ import { action } from "@niwa-labs/core";
7
+ import { plugin } from "@niwa-labs/plugin";
8
+ import { createNiwa, tempHome } from "@niwa-labs/testing";
9
+
10
+ import { contextSource } from "../src/records.ts";
11
+ import type { ContextRequest } from "../src/records.ts";
12
+
13
+ const memoryContext = contextSource("memory.context");
14
+
15
+ const asked: ContextRequest[] = [];
16
+
17
+ /** A data owner with one conclusion to tell and one note it keeps back. */
18
+ const dataOwner = plugin("memory", (api) => {
19
+ api.action(
20
+ action(memoryContext, {
21
+ recovery: "repeat",
22
+ effect: "read",
23
+ world: "niwa",
24
+ run: async (input) => {
25
+ asked.push(input);
26
+ const at = input.at ?? 7;
27
+ return {
28
+ at,
29
+ items: [{ text: "Reviews are done in the morning.", source: { owner: { kind: "agent" as const, id: input.memory }, note: "note-1a2b3c4d", seq: at } }],
30
+ withheld: [{ note: "note-9f8e7d6c" }],
31
+ };
32
+ },
33
+ }),
34
+ );
35
+ });
36
+
37
+ test("a data owner answers a request for context with conclusions that name who holds them", async () => {
38
+ const home = await tempHome();
39
+ const niwa = createNiwa({ home: home.path });
40
+ try {
41
+ niwa.use(dataOwner);
42
+ await niwa.serve();
43
+ const answer = await niwa.call(memoryContext, {
44
+ memory: "rin",
45
+ query: "When does the owner review code?",
46
+ purpose: "judge a request for the owner",
47
+ for: { kind: "agent", id: "judge" },
48
+ at: 3,
49
+ });
50
+ expect(answer).toEqual({
51
+ at: 3,
52
+ items: [{ text: "Reviews are done in the morning.", source: { owner: { kind: "agent", id: "rin" }, note: "note-1a2b3c4d", seq: 3 } }],
53
+ withheld: [{ note: "note-9f8e7d6c" }],
54
+ });
55
+ expect(asked.at(-1)?.for).toEqual({ kind: "agent", id: "judge" });
56
+ } finally {
57
+ await niwa.close();
58
+ await home.cleanup();
59
+ }
60
+ });
61
+
62
+ test("a request for context names its reader by address and says why", async () => {
63
+ const home = await tempHome();
64
+ const niwa = createNiwa({ home: home.path });
65
+ try {
66
+ niwa.use(dataOwner);
67
+ await niwa.serve();
68
+ const before = asked.length;
69
+ const bareReader = niwa.call(memoryContext, { memory: "rin", query: "anything", purpose: "judge", for: "judge" } as never);
70
+ await expect(bareReader).rejects.toThrow();
71
+ const noPurpose = niwa.call(memoryContext, { memory: "rin", query: "anything", for: { kind: "owner" } } as never);
72
+ await expect(noPurpose).rejects.toThrow();
73
+ expect(asked.length).toBe(before);
74
+ } finally {
75
+ await niwa.close();
76
+ await home.cleanup();
77
+ }
78
+ });