@niwa-labs/rin 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 +122 -2
- package/package.json +38 -4
- package/src/admission.ts +73 -0
- package/src/attention.ts +441 -0
- package/src/character.ts +171 -0
- package/src/charter.ts +130 -0
- package/src/cockpit/actions.ts +132 -0
- package/src/cockpit/index.tsx +13 -0
- package/src/cockpit/page.tsx +370 -0
- package/src/cockpit/view.ts +114 -0
- package/src/composition.ts +90 -0
- package/src/index.ts +16 -0
- package/src/plugin.ts +1071 -0
- package/src/presence.ts +57 -0
- package/src/records.ts +546 -0
- package/test/attention.test.ts +265 -0
- package/test/character.test.ts +42 -0
- package/test/charter.test.ts +84 -0
- package/test/cockpit-actions.test.ts +68 -0
- package/test/cockpit-view.test.ts +68 -0
- package/test/composition.test.ts +157 -0
- package/test/plugin.test.ts +988 -0
- package/test/presence.test.ts +38 -0
- package/tsconfig.json +16 -0
package/src/charter.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rin's charter, without a host: how the owner wants her to act, grown from his corrections.
|
|
3
|
+
*
|
|
4
|
+
* Every correction is written down (`rin.corrected`). When corrections about one thing repeat, she is asked whether
|
|
5
|
+
* a rule should cover them; she words the rule and proposes it, and it becomes part of the charter only once the
|
|
6
|
+
* owner confirms it. Consolidation finds the repetition; it never words a rule itself.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Row } from "./attention.ts";
|
|
10
|
+
import { CharterDeclined, CharterDue, CharterProposed, CharterRetired, CharterRuled, Corrected } from "./records.ts";
|
|
11
|
+
import type { CorrectionId, CorrectionItem, NoteChange, RuleId, RuleItem, Topic } from "./records.ts";
|
|
12
|
+
|
|
13
|
+
/** How many corrections about one thing, not yet covered, make a rule due. */
|
|
14
|
+
export const DEFAULT_RULE_AFTER = 2;
|
|
15
|
+
|
|
16
|
+
/** A correction, with the rule that covers it once one was proposed for it. */
|
|
17
|
+
export interface Correction extends CorrectionItem {
|
|
18
|
+
readonly seq: number;
|
|
19
|
+
readonly source?: string;
|
|
20
|
+
/** The note of her memory it is about: its words are read from memory when it is shown. */
|
|
21
|
+
readonly note?: NoteChange;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A rule, from its proposal. */
|
|
25
|
+
export interface Rule extends RuleItem {
|
|
26
|
+
readonly at: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CharterState {
|
|
30
|
+
readonly corrections: Correction[];
|
|
31
|
+
readonly rules: Map<RuleId, Rule>;
|
|
32
|
+
/** The corrections she was already asked about, by what they are about. */
|
|
33
|
+
readonly asked: Map<Topic, Set<CorrectionId>>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Folds the corrections and the rules, in the order they were written. */
|
|
37
|
+
export function foldCharter(rows: readonly Row[]): CharterState {
|
|
38
|
+
const state: CharterState = { corrections: [], rules: new Map(), asked: new Map() };
|
|
39
|
+
const byId = new Map<CorrectionId, Correction>();
|
|
40
|
+
for (const row of rows) {
|
|
41
|
+
switch (row.type) {
|
|
42
|
+
case Corrected.name: {
|
|
43
|
+
const data = Corrected.schema.parse(row.data);
|
|
44
|
+
const correction: Correction = {
|
|
45
|
+
correction: data.correction,
|
|
46
|
+
about: data.about,
|
|
47
|
+
what: data.what,
|
|
48
|
+
by: data.by,
|
|
49
|
+
at: row.at,
|
|
50
|
+
seq: row.seq,
|
|
51
|
+
...(data.source === undefined ? {} : { source: data.source }),
|
|
52
|
+
...(data.note === undefined ? {} : { note: data.note }),
|
|
53
|
+
};
|
|
54
|
+
if (byId.has(correction.correction)) break;
|
|
55
|
+
byId.set(correction.correction, correction);
|
|
56
|
+
state.corrections.push(correction);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case CharterDue.name: {
|
|
60
|
+
const data = CharterDue.schema.parse(row.data);
|
|
61
|
+
const asked = state.asked.get(data.about) ?? new Set();
|
|
62
|
+
for (const id of data.corrections) asked.add(id);
|
|
63
|
+
state.asked.set(data.about, asked);
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
case CharterProposed.name: {
|
|
67
|
+
const data = CharterProposed.schema.parse(row.data);
|
|
68
|
+
state.rules.set(data.rule, { rule: data.rule, about: data.about, text: data.text, status: "proposed", corrections: data.corrections, at: row.at });
|
|
69
|
+
for (const id of data.corrections) {
|
|
70
|
+
const correction = byId.get(id);
|
|
71
|
+
if (correction !== undefined && correction.rule === undefined) Object.assign(correction, { rule: data.rule });
|
|
72
|
+
}
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
case CharterRuled.name:
|
|
76
|
+
setStatus(state, CharterRuled.schema.parse(row.data).rule, "ruled", ["proposed"]);
|
|
77
|
+
break;
|
|
78
|
+
case CharterDeclined.name:
|
|
79
|
+
setStatus(state, CharterDeclined.schema.parse(row.data).rule, "declined", ["proposed"]);
|
|
80
|
+
break;
|
|
81
|
+
case CharterRetired.name:
|
|
82
|
+
setStatus(state, CharterRetired.schema.parse(row.data).rule, "retired", ["ruled", "proposed"]);
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return state;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function setStatus(state: CharterState, id: RuleId, status: Rule["status"], from: readonly Rule["status"][]): void {
|
|
90
|
+
const rule = state.rules.get(id);
|
|
91
|
+
if (rule !== undefined && from.includes(rule.status)) state.rules.set(id, { ...rule, status });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The corrections about one thing that make a rule due: at least `threshold` of them that no rule covers and she
|
|
96
|
+
* was not asked about yet, while no rule about it waits for the owner. Undefined when nothing is due.
|
|
97
|
+
*/
|
|
98
|
+
export function dueFor(state: CharterState, about: Topic, threshold: number): CorrectionId[] | undefined {
|
|
99
|
+
if ([...state.rules.values()].some((rule) => rule.about === about && rule.status === "proposed")) return undefined;
|
|
100
|
+
const asked = state.asked.get(about) ?? new Set<CorrectionId>();
|
|
101
|
+
const open = state.corrections.filter((one) => one.about === about && one.rule === undefined && !asked.has(one.correction));
|
|
102
|
+
return open.length >= threshold ? open.map((one) => one.correction) : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The rules of the charter: confirmed by the owner and not retired, in the order they were proposed. */
|
|
106
|
+
export function ruledRules(state: CharterState): Rule[] {
|
|
107
|
+
return [...state.rules.values()].filter((rule) => rule.status === "ruled");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The rules as she reads them, one a line; empty when there is none. */
|
|
111
|
+
export function charterText(rules: readonly RuleItem[]): string {
|
|
112
|
+
return rules.map((rule) => `- ${rule.rule} (${rule.about}): ${rule.text}`).join("\n");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A rule as it is read. */
|
|
116
|
+
export function ruleView(rule: Rule): RuleItem {
|
|
117
|
+
return { rule: rule.rule, about: rule.about, text: rule.text, status: rule.status, corrections: rule.corrections };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A correction as it is read; `what` is the words it is shown with, which for a note of hers are read from memory. */
|
|
121
|
+
export function correctionView(correction: Correction, what: string = correction.what): CorrectionItem {
|
|
122
|
+
return {
|
|
123
|
+
correction: correction.correction,
|
|
124
|
+
about: correction.about,
|
|
125
|
+
what,
|
|
126
|
+
by: correction.by,
|
|
127
|
+
at: correction.at,
|
|
128
|
+
...(correction.rule === undefined ? {} : { rule: correction.rule }),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions Rin's page calls: the 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
|
|
6
|
+
* actions.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
export const ItemStatus = z.enum(["held", "sending", "unsure", "said", "brought", "dropped", "dismissed"]);
|
|
12
|
+
|
|
13
|
+
export const AttentionView = z.object({
|
|
14
|
+
item: z.string(),
|
|
15
|
+
text: z.string(),
|
|
16
|
+
status: ItemStatus,
|
|
17
|
+
why: z.enum(["next-contact", "quiet-hours", "ceiling", "undelivered"]).optional(),
|
|
18
|
+
kind: z.string().optional(),
|
|
19
|
+
count: z.number().optional(),
|
|
20
|
+
at: z.number(),
|
|
21
|
+
});
|
|
22
|
+
export type AttentionView = z.infer<typeof AttentionView>;
|
|
23
|
+
|
|
24
|
+
export const RuleView = z.object({
|
|
25
|
+
rule: z.string(),
|
|
26
|
+
about: z.string(),
|
|
27
|
+
text: z.string(),
|
|
28
|
+
status: z.enum(["proposed", "ruled", "declined", "retired"]),
|
|
29
|
+
corrections: z.array(z.string()),
|
|
30
|
+
});
|
|
31
|
+
export type RuleView = z.infer<typeof RuleView>;
|
|
32
|
+
|
|
33
|
+
export const attentionAction = {
|
|
34
|
+
name: "rin.attention.list",
|
|
35
|
+
input: z.object({}),
|
|
36
|
+
output: z.object({ items: z.array(AttentionView) }),
|
|
37
|
+
} as const;
|
|
38
|
+
|
|
39
|
+
export const dismissAction = {
|
|
40
|
+
name: "rin.attention.dismiss",
|
|
41
|
+
input: z.object({ item: z.string(), reason: z.string().optional() }),
|
|
42
|
+
output: z.object({ item: z.string() }),
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
export const charterAction = {
|
|
46
|
+
name: "rin.charter",
|
|
47
|
+
input: z.object({}),
|
|
48
|
+
output: z.object({ rules: z.array(RuleView), corrections: z.array(z.object({ correction: z.string(), about: z.string(), what: z.string() })) }),
|
|
49
|
+
} as const;
|
|
50
|
+
|
|
51
|
+
export const retireAction = {
|
|
52
|
+
name: "rin.charter.retire",
|
|
53
|
+
input: z.object({ rule: z.string() }),
|
|
54
|
+
output: z.object({ rule: z.string() }),
|
|
55
|
+
} as const;
|
|
56
|
+
|
|
57
|
+
export const Delivery = z.enum(["waiting", "delivered", "unsent", "possibly-sent"]);
|
|
58
|
+
export type Delivery = z.infer<typeof Delivery>;
|
|
59
|
+
|
|
60
|
+
export const ConversationMessage = z.object({ id: z.string(), turn: z.string().optional(), from: z.enum(["owner", "rin"]), text: z.string(), at: z.number(), delivery: Delivery.optional() });
|
|
61
|
+
export type ConversationMessage = z.infer<typeof ConversationMessage>;
|
|
62
|
+
|
|
63
|
+
export const conversationAction = {
|
|
64
|
+
name: "rin.conversation",
|
|
65
|
+
input: z.object({ conversation: z.string() }),
|
|
66
|
+
output: z.object({ messages: z.array(ConversationMessage) }),
|
|
67
|
+
} as const;
|
|
68
|
+
|
|
69
|
+
export const tellAction = {
|
|
70
|
+
name: "agent.tell",
|
|
71
|
+
input: z.object({ agent: z.string(), text: z.string(), replyTo: z.object({ channel: z.literal("cockpit"), conversation: z.string() }) }),
|
|
72
|
+
output: z.object({ message: z.string() }),
|
|
73
|
+
} as const;
|
|
74
|
+
|
|
75
|
+
export const AgentView = z.object({ name: z.string(), status: z.enum(["new", "working", "asleep"]), source: z.enum(["config", "runtime"]) });
|
|
76
|
+
export type AgentView = z.infer<typeof AgentView>;
|
|
77
|
+
|
|
78
|
+
export const agentsAction = {
|
|
79
|
+
name: "agent.list",
|
|
80
|
+
input: z.object({}),
|
|
81
|
+
output: z.object({ items: z.array(AgentView) }),
|
|
82
|
+
} as const;
|
|
83
|
+
|
|
84
|
+
export const commitmentsAction = {
|
|
85
|
+
name: "commitment.list",
|
|
86
|
+
input: z.object({ to: z.string().optional() }),
|
|
87
|
+
output: z.object({ items: z.array(z.object({ id: z.string(), description: z.string(), status: z.string(), due: z.number().optional() })) }),
|
|
88
|
+
} as const;
|
|
89
|
+
|
|
90
|
+
export const openQuestionsAction = {
|
|
91
|
+
name: "request.open",
|
|
92
|
+
input: z.object({ to: z.object({ kind: z.literal("owner") }) }),
|
|
93
|
+
output: z.object({
|
|
94
|
+
requests: z.array(z.union([
|
|
95
|
+
z.object({ kind: z.literal("paused") }),
|
|
96
|
+
z.object({
|
|
97
|
+
id: z.string(),
|
|
98
|
+
question: z.string(),
|
|
99
|
+
from: z.object({ kind: z.string(), id: z.string().optional() }).optional(),
|
|
100
|
+
input: z.object({ title: z.string() }),
|
|
101
|
+
}),
|
|
102
|
+
])),
|
|
103
|
+
}),
|
|
104
|
+
} as const;
|
|
105
|
+
|
|
106
|
+
export const memoryAction = {
|
|
107
|
+
name: "memory.top",
|
|
108
|
+
input: z.object({ memory: z.string() }),
|
|
109
|
+
output: z.object({ text: z.string() }),
|
|
110
|
+
} as const;
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
const Installation = z.object({ plugin: z.string(), hash: z.string(), version: z.string() });
|
|
114
|
+
|
|
115
|
+
export const selfHistoryAction = {
|
|
116
|
+
name: "rin.self.history",
|
|
117
|
+
input: z.object({}),
|
|
118
|
+
output: z.object({
|
|
119
|
+
mode: z.enum(["off", "ask", "free"]),
|
|
120
|
+
edits: z.array(z.object({
|
|
121
|
+
edit: z.string(), plugin: z.string(), module: z.string().optional(), hash: z.string(), why: z.string(),
|
|
122
|
+
mode: z.enum(["ask", "free"]), status: z.string(), detail: z.string().optional(),
|
|
123
|
+
})),
|
|
124
|
+
installed: z.array(Installation),
|
|
125
|
+
}),
|
|
126
|
+
} as const;
|
|
127
|
+
|
|
128
|
+
export const uninstallAction = {
|
|
129
|
+
name: "plugin.uninstall",
|
|
130
|
+
input: Installation.pick({ plugin: true, hash: true }),
|
|
131
|
+
output: Installation.pick({ plugin: true, hash: true }),
|
|
132
|
+
} as const;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The cockpit module of Rin: her own page, and a tile on the home page with what waits for the owner. */
|
|
2
|
+
|
|
3
|
+
import { definePlugin } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
|
|
5
|
+
import { AttentionTile, RinPage } from "./page.tsx";
|
|
6
|
+
|
|
7
|
+
export default definePlugin({
|
|
8
|
+
id: "rin",
|
|
9
|
+
setup(ctx) {
|
|
10
|
+
ctx.pages.add({ path: "/rin", title: "Рин", nav: { order: 10 }, component: RinPage });
|
|
11
|
+
ctx.slots.register("home.tile", { key: "rin-attention", component: AttentionTile });
|
|
12
|
+
},
|
|
13
|
+
});
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/** Rin's page: talking to her, what she holds and told, her charter, her promises, her memory, the agents she leads. */
|
|
2
|
+
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
|
|
5
|
+
import { EntityLink, PageLink, useAction, useCall, useViewer, recordList, useProjection } from "@niwa-labs/cockpit-sdk";
|
|
6
|
+
import { Button, CopyValue, FileRef, Markdown } from "@niwa-labs/ui-kit";
|
|
7
|
+
|
|
8
|
+
import { agentsAction, attentionAction, charterAction, commitmentsAction, conversationAction, dismissAction, memoryAction, openQuestionsAction, retireAction, selfHistoryAction, tellAction, uninstallAction } from "./actions.ts";
|
|
9
|
+
import type { AttentionView } from "./actions.ts";
|
|
10
|
+
import { attentionGroups, charterRows, conversationRows, ledAgents, tileText, whyText } from "./view.ts";
|
|
11
|
+
|
|
12
|
+
const RIN = "rin";
|
|
13
|
+
const REPLY_ROUTE = { channel: "cockpit", conversation: RIN } as const;
|
|
14
|
+
|
|
15
|
+
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
|
16
|
+
return (
|
|
17
|
+
<section className="flex min-w-0 flex-col gap-2">
|
|
18
|
+
<h3 className="text-sm font-semibold">{title}</h3>
|
|
19
|
+
{children}
|
|
20
|
+
</section>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function Quiet({ children }: { children: React.ReactNode }) {
|
|
25
|
+
return <p className="text-sm text-muted-foreground">{children}</p>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function Talk() {
|
|
29
|
+
const tell = useAction(tellAction);
|
|
30
|
+
const [text, setText] = useState("");
|
|
31
|
+
return (
|
|
32
|
+
<form
|
|
33
|
+
className="flex min-w-0 flex-wrap items-start gap-2"
|
|
34
|
+
onSubmit={(event) => {
|
|
35
|
+
event.preventDefault();
|
|
36
|
+
const sent = text.trim();
|
|
37
|
+
if (sent === "" || tell.isPending) return;
|
|
38
|
+
tell.mutate({ agent: RIN, text: sent, replyTo: REPLY_ROUTE }, {
|
|
39
|
+
onSuccess: () => setText((current) => current.trim() === sent ? "" : current),
|
|
40
|
+
});
|
|
41
|
+
}}
|
|
42
|
+
>
|
|
43
|
+
<textarea className="min-h-16 flex-1 rounded-md border bg-background p-2 text-sm" aria-label="Написать Рин" value={text} placeholder="Написать Рин" onChange={(event) => setText(event.target.value)} />
|
|
44
|
+
<Button type="submit" size="sm" disabled={tell.isPending || text.trim() === ""}>
|
|
45
|
+
Отправить
|
|
46
|
+
</Button>
|
|
47
|
+
{tell.isError ? <span role="alert" className="text-xs text-destructive">{tell.error.message}</span> : null}
|
|
48
|
+
</form>
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function Conversation() {
|
|
53
|
+
const conversation = useCall(conversationAction, { conversation: REPLY_ROUTE.conversation }, { refreshOn: { types: ["message.sent", "agent.turn.delivered", "agent.turn.failed", "agent.turn.replied"] } });
|
|
54
|
+
if (conversation.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
55
|
+
if (conversation.isError) return <p role="alert" className="text-sm text-destructive">{conversation.error.message}</p>;
|
|
56
|
+
const rows = conversationRows(conversation.data.messages);
|
|
57
|
+
if (rows.length === 0) return <Quiet>Сообщений пока нет. Напишите Рин, чтобы начать разговор.</Quiet>;
|
|
58
|
+
return (
|
|
59
|
+
<ul className="flex flex-col gap-2">
|
|
60
|
+
{rows.map((row) => (
|
|
61
|
+
<li key={row.id} data-slot="rin-message" data-who={row.who} data-turn={row.turn} className="flex min-w-0 flex-col rounded-lg border bg-card px-3 py-2">
|
|
62
|
+
<span className="text-sm">
|
|
63
|
+
<span className="font-medium">{row.who}</span>
|
|
64
|
+
</span>
|
|
65
|
+
<span className="whitespace-pre-wrap break-words text-sm">{row.text}
|
|
66
|
+
</span>
|
|
67
|
+
<span className="text-xs text-muted-foreground">
|
|
68
|
+
{new Date(row.at).toLocaleString("ru")}
|
|
69
|
+
{row.state === undefined ? "" : ` · ${row.state}`}
|
|
70
|
+
</span>
|
|
71
|
+
</li>
|
|
72
|
+
))}
|
|
73
|
+
</ul>
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const OCCASION_LABEL: Readonly<Record<string, string>> = {
|
|
78
|
+
agent: "Агент", ci: "Проверки", task: "Задача", question: "Вопрос", workflow: "Сценарий",
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
function Item({ item, owner }: { item: AttentionView; owner: boolean }) {
|
|
82
|
+
const dismiss = useAction(dismissAction);
|
|
83
|
+
const open = item.status === "held" || item.status === "sending" || item.status === "unsure" || item.status === "said" || item.status === "brought";
|
|
84
|
+
const kind = item.kind === undefined ? undefined : OCCASION_LABEL[item.kind];
|
|
85
|
+
return (
|
|
86
|
+
<li data-slot="rin-attention" data-status={item.status} className="flex min-w-0 flex-wrap items-start gap-3 border-b px-3 py-3 last:border-b-0">
|
|
87
|
+
<div className="flex min-w-0 flex-col">
|
|
88
|
+
<span className="text-sm">{item.text}</span>
|
|
89
|
+
<span className="text-xs text-muted-foreground">
|
|
90
|
+
{kind === undefined ? "" : `${kind} · `}
|
|
91
|
+
{whyText(item)} · {new Date(item.at).toLocaleString("ru")}
|
|
92
|
+
</span>
|
|
93
|
+
</div>
|
|
94
|
+
{owner && open ? (
|
|
95
|
+
<Button className="ml-auto" variant="outline" size="sm" disabled={dismiss.isPending} onClick={() => dismiss.mutate({ item: item.item })}>
|
|
96
|
+
Скрыть
|
|
97
|
+
</Button>
|
|
98
|
+
) : null}
|
|
99
|
+
{dismiss.isError ? <p role="alert" className="w-full text-xs text-destructive">{dismiss.error.message}</p> : null}
|
|
100
|
+
</li>
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function Attention() {
|
|
105
|
+
const viewer = useViewer();
|
|
106
|
+
const attention = useCall(attentionAction, {}, { refreshOn: { types: ["rin.*"] } });
|
|
107
|
+
if (attention.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
108
|
+
if (attention.isError) return <p role="alert" className="text-sm text-destructive">{attention.error.message}</p>;
|
|
109
|
+
const groups = attentionGroups(attention.data.items);
|
|
110
|
+
const list = (items: AttentionView[]) => (
|
|
111
|
+
<ul className="rounded-lg border bg-card">{items.map((item) => <Item key={item.item} item={item} owner={viewer.owner} />)}</ul>
|
|
112
|
+
);
|
|
113
|
+
return (
|
|
114
|
+
<>
|
|
115
|
+
<Section title="Отложенные сообщения">
|
|
116
|
+
{groups.waiting.length ? list(groups.waiting) : <Quiet>У Рин нет сообщений, ожидающих доставки.</Quiet>}
|
|
117
|
+
</Section>
|
|
118
|
+
{groups.told.length ? <details className="space-y-2"><summary className="cursor-pointer text-sm font-medium">История уведомлений ({groups.told.length})</summary>{list(groups.told)}</details> : null}
|
|
119
|
+
</>
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function Charter() {
|
|
124
|
+
const viewer = useViewer();
|
|
125
|
+
const charter = useCall(charterAction, {}, { refreshOn: { types: ["rin.charter.*", "rin.corrected"] } });
|
|
126
|
+
const retire = useAction(retireAction);
|
|
127
|
+
if (charter.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
128
|
+
if (charter.isError) return <p role="alert" className="text-sm text-destructive">{charter.error.message}</p>;
|
|
129
|
+
const rows = charterRows(charter.data.rules);
|
|
130
|
+
return rows.length === 0 ? (
|
|
131
|
+
<Quiet>В уставе пока нет правил. Учтено поправок: {charter.data.corrections.length}.</Quiet>
|
|
132
|
+
) : (
|
|
133
|
+
<ul className="flex flex-col gap-2">
|
|
134
|
+
{rows.map((row) => (
|
|
135
|
+
<li key={row.rule} data-slot="rin-rule" data-status={row.status} className="flex min-w-0 flex-wrap items-start gap-3 border-b px-3 py-3 last:border-b-0">
|
|
136
|
+
<div className="min-w-0 flex-1">
|
|
137
|
+
<p className="break-words text-sm">{row.text}</p>
|
|
138
|
+
<p className="text-xs text-muted-foreground">{row.label} · {row.about} · поправок: {row.corrections}</p>
|
|
139
|
+
</div>
|
|
140
|
+
{viewer.owner && (row.status === "ruled" || row.status === "proposed") ? (
|
|
141
|
+
<Button variant="outline" size="sm" disabled={retire.isPending} onClick={() => retire.mutate({ rule: row.rule })}>
|
|
142
|
+
Снять правило
|
|
143
|
+
</Button>
|
|
144
|
+
) : null}
|
|
145
|
+
</li>
|
|
146
|
+
))}
|
|
147
|
+
</ul>
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const PROMISE_STATUS: Readonly<Record<string, string>> = {
|
|
152
|
+
proposed: "Ждёт подтверждения", open: "Открыто", due: "Срок наступил",
|
|
153
|
+
kept: "Выполнено", "kept-late": "Выполнено с опозданием", missed: "Просрочено",
|
|
154
|
+
cancelled: "Отменено", declined: "Отклонено",
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
function Promises() {
|
|
158
|
+
const promises = useCall(commitmentsAction, { to: RIN }, { refreshOn: { types: ["commitment.*"] } });
|
|
159
|
+
if (promises.isPending) return <Quiet>Загружаем поручения…</Quiet>;
|
|
160
|
+
if (promises.isError) return <p role="alert" className="text-sm text-destructive">Не удалось загрузить поручения. {promises.error.message}</p>;
|
|
161
|
+
const active = (one: { status: string }) => one.status === "proposed" || one.status === "open" || one.status === "due";
|
|
162
|
+
const open = promises.data.items.filter(active).sort((a, b) => (a.due ?? Infinity) - (b.due ?? Infinity));
|
|
163
|
+
const history = promises.data.items.filter((item) => !active(item));
|
|
164
|
+
const list = (items: typeof open) => (
|
|
165
|
+
<ul className="divide-y rounded-lg border bg-card px-3">
|
|
166
|
+
{items.map((one) => (
|
|
167
|
+
<li key={one.id} className="space-y-1 py-2">
|
|
168
|
+
<p className="break-words text-sm">{one.description}</p>
|
|
169
|
+
<p className="desk-tools text-xs text-muted-foreground">
|
|
170
|
+
<span>{PROMISE_STATUS[one.status] ?? "Статус не определён"}</span>
|
|
171
|
+
{one.due === undefined ? null : <time dateTime={new Date(one.due).toISOString()}>До {new Date(one.due).toLocaleString("ru")}</time>}
|
|
172
|
+
</p>
|
|
173
|
+
</li>
|
|
174
|
+
))}
|
|
175
|
+
</ul>
|
|
176
|
+
);
|
|
177
|
+
return (
|
|
178
|
+
<>
|
|
179
|
+
{open.length ? list(open) : <Quiet>Открытых поручений для Рин нет.</Quiet>}
|
|
180
|
+
{history.length ? <details className="space-y-2">
|
|
181
|
+
<summary className="cursor-pointer text-sm font-medium">Завершённые поручения ({history.length})</summary>
|
|
182
|
+
{list(history)}
|
|
183
|
+
</details> : null}
|
|
184
|
+
</>
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function Questions() {
|
|
189
|
+
const viewer = useViewer();
|
|
190
|
+
const available = viewer.owner && viewer.can(openQuestionsAction);
|
|
191
|
+
const open = useCall(openQuestionsAction, { to: { kind: "owner" } }, { enabled: available, refreshOn: { types: ["request.*"] } });
|
|
192
|
+
if (!available) return null;
|
|
193
|
+
const questions = (open.data?.requests ?? []).flatMap((row) => {
|
|
194
|
+
if (!("id" in row)) return [];
|
|
195
|
+
const title = row.question === "rin.charter.confirm" ? "Подтверждение правила устава" :
|
|
196
|
+
row.question === "rin.self-edit.confirm" ? "Подтверждение установки модуля" :
|
|
197
|
+
row.from?.kind === "agent" && row.from.id === RIN ? "Вопрос Рин" : undefined;
|
|
198
|
+
return title === undefined ? [] : [{ id: row.id, title, question: row.input.title }];
|
|
199
|
+
});
|
|
200
|
+
return (
|
|
201
|
+
<Section title="Открытые вопросы">
|
|
202
|
+
{open.isPending ? <Quiet>Загружаем вопросы…</Quiet> :
|
|
203
|
+
open.isError ? <p role="alert" className="text-sm text-destructive">Не удалось загрузить вопросы. {open.error.message}</p> :
|
|
204
|
+
questions.length === 0 ? <Quiet>Сейчас Рин не ждёт ваших решений.</Quiet> :
|
|
205
|
+
<ul className="divide-y rounded-lg border bg-card px-3">
|
|
206
|
+
{questions.map((row) => (
|
|
207
|
+
<li key={row.id} className="space-y-1 py-2">
|
|
208
|
+
<p className="flex flex-wrap items-center gap-2 text-sm font-medium">
|
|
209
|
+
{row.title} <EntityLink entity={{ kind: "request", id: row.id }} short />
|
|
210
|
+
</p>
|
|
211
|
+
<p className="break-words text-sm text-muted-foreground">{row.question}</p>
|
|
212
|
+
</li>
|
|
213
|
+
))}
|
|
214
|
+
</ul>}
|
|
215
|
+
</Section>
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function Memory() {
|
|
220
|
+
const top = useCall(memoryAction, { memory: RIN }, { refreshOn: { types: ["memory.*"] } });
|
|
221
|
+
if (top.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
222
|
+
if (top.isError) return <p role="alert" className="text-sm text-destructive">{top.error.message}</p>;
|
|
223
|
+
if (top.data.text === "") return <Quiet>В приоритетной памяти пока пусто.</Quiet>;
|
|
224
|
+
const text = top.data.text.replace(/^About the owner:\n(?=- )/gm, "**О владельце**\n\n")
|
|
225
|
+
.replace(/^In general:\n(?=- )/gm, "**Общее**\n\n");
|
|
226
|
+
return <Markdown text={text} />;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const AGENT_STATUS = { new: "Новый", working: "В работе", asleep: "Неактивен" };
|
|
230
|
+
|
|
231
|
+
function Agents() {
|
|
232
|
+
const agents = useCall(agentsAction, {}, { refreshOn: { types: ["agent.*"] } });
|
|
233
|
+
if (agents.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
234
|
+
if (agents.isError) return <p role="alert" className="text-sm text-destructive">{agents.error.message}</p>;
|
|
235
|
+
const led = ledAgents(agents.data.items);
|
|
236
|
+
if (led.length === 0) return <Quiet>Других агентов пока нет.</Quiet>;
|
|
237
|
+
return (
|
|
238
|
+
<ul className="flex flex-col gap-1 text-sm">
|
|
239
|
+
{led.map((agent) => (
|
|
240
|
+
<li key={agent.name}>
|
|
241
|
+
{agent.name} <span className="text-xs text-muted-foreground">· {AGENT_STATUS[agent.status]}</span>
|
|
242
|
+
</li>
|
|
243
|
+
))}
|
|
244
|
+
</ul>
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const MODULE_STATUS: Readonly<Record<string, string>> = {
|
|
249
|
+
pending: "Ждёт решения", installing: "Устанавливается", installed: "Установлен",
|
|
250
|
+
declined: "Отклонён", cancelled: "Отменён", expired: "Срок истёк",
|
|
251
|
+
"not-his": "Подтверждение владельца не получено", failed: "Ошибка установки", unknown: "Итог неизвестен",
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
function SelfEdits() {
|
|
255
|
+
const history = useCall(selfHistoryAction, {}, { refreshOn: { types: ["rin.self-edit.*", "niwa.plugin.*"] } });
|
|
256
|
+
const uninstall = useAction(uninstallAction);
|
|
257
|
+
const [selected, setSelected] = useState<{ plugin: string; hash: string }>();
|
|
258
|
+
if (history.isPending) return <Quiet>Загружаем…</Quiet>;
|
|
259
|
+
if (history.isError) return <p role="alert" className="text-sm text-destructive">{history.error.message}</p>;
|
|
260
|
+
const { mode, edits, installed } = history.data;
|
|
261
|
+
return (
|
|
262
|
+
<details className="space-y-2">
|
|
263
|
+
<summary className="cursor-pointer text-sm font-semibold">Модули Рин</summary>
|
|
264
|
+
<Quiet>{mode === "off" ? "Установка модулей отключена." : mode === "ask" ? "Установка требует вашего подтверждения." : "Рин может устанавливать модули самостоятельно."}</Quiet>
|
|
265
|
+
{installed.length > 0 ? (
|
|
266
|
+
<ul className="flex flex-col gap-2 text-sm">
|
|
267
|
+
{installed.map((entry) => {
|
|
268
|
+
const confirming = selected?.plugin === entry.plugin && selected.hash === entry.hash;
|
|
269
|
+
return (
|
|
270
|
+
<li key={entry.plugin} className="flex items-center gap-2">
|
|
271
|
+
<span className="mr-auto">{entry.plugin} · {entry.version}</span>
|
|
272
|
+
{confirming ? (
|
|
273
|
+
<>
|
|
274
|
+
<Button size="sm" variant="outline" onClick={() => setSelected(undefined)} disabled={uninstall.isPending}>Отмена</Button>
|
|
275
|
+
<Button size="sm" variant="destructive" disabled={uninstall.isPending} onClick={() => uninstall.mutate(selected, { onSuccess: () => setSelected(undefined) })}>
|
|
276
|
+
Подтвердить удаление
|
|
277
|
+
</Button>
|
|
278
|
+
</>
|
|
279
|
+
) : (
|
|
280
|
+
<Button size="sm" variant="outline" disabled={uninstall.isPending} onClick={() => setSelected(entry)}>Удалить</Button>
|
|
281
|
+
)}
|
|
282
|
+
</li>
|
|
283
|
+
);
|
|
284
|
+
})}
|
|
285
|
+
</ul>
|
|
286
|
+
) : null}
|
|
287
|
+
{uninstall.isError ? <p role="alert" className="text-sm text-destructive">{uninstall.error.message}</p> : null}
|
|
288
|
+
{edits.length > 0 ? (
|
|
289
|
+
<ul className="flex flex-col gap-2 text-sm">
|
|
290
|
+
{edits.map((edit) => (
|
|
291
|
+
<li key={edit.edit} className="flex flex-col rounded-lg border bg-card px-3 py-2">
|
|
292
|
+
<span>{edit.plugin} · {MODULE_STATUS[edit.status] ?? "Статус не определён"}</span>
|
|
293
|
+
<span>{edit.why}</span>
|
|
294
|
+
<div className="flex flex-wrap items-center gap-2 text-xs">{edit.module ? <FileRef path={edit.module} /> : null}<CopyValue value={edit.hash} label={edit.hash.slice(0, 12)} /></div>
|
|
295
|
+
{edit.detail ? <span>{edit.detail}</span> : null}
|
|
296
|
+
</li>
|
|
297
|
+
))}
|
|
298
|
+
</ul>
|
|
299
|
+
) : null}
|
|
300
|
+
</details>
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function RinPage() {
|
|
305
|
+
const { owner } = useViewer();
|
|
306
|
+
return (
|
|
307
|
+
<article className="desk-page p-4">
|
|
308
|
+
<h1>Рин</h1>
|
|
309
|
+
<Questions />
|
|
310
|
+
<Section title="Поручения и обязательства">
|
|
311
|
+
<Promises />
|
|
312
|
+
</Section>
|
|
313
|
+
<Attention />
|
|
314
|
+
{owner ? (
|
|
315
|
+
<Section title="Разговор">
|
|
316
|
+
<Talk />
|
|
317
|
+
<Conversation />
|
|
318
|
+
</Section>
|
|
319
|
+
) : null}
|
|
320
|
+
<Section title="Устав">
|
|
321
|
+
<Charter />
|
|
322
|
+
</Section>
|
|
323
|
+
{owner ? <SelfEdits /> : null}
|
|
324
|
+
<details className="space-y-2">
|
|
325
|
+
<summary className="cursor-pointer text-sm font-semibold">Приоритетная память</summary>
|
|
326
|
+
<Memory />
|
|
327
|
+
</details>
|
|
328
|
+
<Section title="Агенты Рин">
|
|
329
|
+
<Agents />
|
|
330
|
+
</Section>
|
|
331
|
+
</article>
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const ACTIVITY_LABEL = new Map<string, string>([
|
|
336
|
+
["rin.occasion.opened", "Замечено событие"],
|
|
337
|
+
["rin.attention.held", "Сообщение отложено"],
|
|
338
|
+
["rin.attention.said", "Сообщение доставлено"],
|
|
339
|
+
["rin.attention.unsure", "Доставка не подтверждена"],
|
|
340
|
+
["rin.attention.brought", "Событие обсуждено"],
|
|
341
|
+
["rin.corrected", "Учтена поправка"],
|
|
342
|
+
["rin.charter.proposed", "Предложено правило"],
|
|
343
|
+
["rin.charter.ruled", "Правило принято"],
|
|
344
|
+
["rin.charter.retired", "Правило снято"],
|
|
345
|
+
["rin.self-edit.proposed", "Предложена установка модуля"],
|
|
346
|
+
["rin.self-edit.settled", "Получен результат установки"],
|
|
347
|
+
]);
|
|
348
|
+
const recentActivity = recordList({ types: [...ACTIVITY_LABEL.keys()] }, 8);
|
|
349
|
+
|
|
350
|
+
/** Recent decisions and the items that need the owner. */
|
|
351
|
+
export function AttentionTile() {
|
|
352
|
+
const recent = useProjection(recentActivity);
|
|
353
|
+
const attention = useCall(attentionAction, {}, { refreshOn: { types: ["rin.attention.*"] } });
|
|
354
|
+
return (
|
|
355
|
+
<section data-slot="rin-tile" className="desk-section"><h2>Последние действия Рин</h2>
|
|
356
|
+
<PageLink to="/rin">Открыть Рин →</PageLink>
|
|
357
|
+
{attention.error ? <p role="alert">{attention.error.message}</p> : attention.data && <p>{tileText(attention.data.items)}</p>}
|
|
358
|
+
{!recent.length && <p>Заметных действий пока нет.</p>}
|
|
359
|
+
{recent.length > 0 && <ul className="space-y-2">{recent.toReversed().map((record) => {
|
|
360
|
+
const data = (record.data ?? {}) as Record<string, unknown>;
|
|
361
|
+
const detail = typeof data["text"] === "string" ? data["text"] : undefined;
|
|
362
|
+
return <li key={record.id} className="text-sm">
|
|
363
|
+
<time className="mr-2 text-muted-foreground">{new Date(record.at).toLocaleTimeString("ru", { hour: "2-digit", minute: "2-digit" })}</time>
|
|
364
|
+
{ACTIVITY_LABEL.get(record.type)}
|
|
365
|
+
{detail ? <p className="break-words text-muted-foreground">{detail}</p> : null}
|
|
366
|
+
</li>;
|
|
367
|
+
})}</ul>}
|
|
368
|
+
</section>
|
|
369
|
+
);
|
|
370
|
+
}
|