@niwa-labs/sessions 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 +17 -2
- package/package.json +46 -4
- package/src/actions.ts +350 -0
- package/src/ask.ts +230 -0
- package/src/box.ts +87 -0
- package/src/caps.ts +149 -0
- package/src/catalog.ts +146 -0
- package/src/cockpit/actions.ts +52 -0
- package/src/cockpit/index.tsx +36 -0
- package/src/cockpit/pages.tsx +190 -0
- package/src/cockpit/transcript.ts +64 -0
- package/src/confirm.ts +228 -0
- package/src/discover.ts +107 -0
- package/src/identity.ts +64 -0
- package/src/index.ts +1874 -0
- package/src/insert-plugin.ts +263 -0
- package/src/insert-routing.ts +84 -0
- package/src/life.ts +59 -0
- package/src/prompt.ts +50 -0
- package/src/records-entry.ts +91 -0
- package/src/records.ts +395 -0
- package/src/refusal.ts +13 -0
- package/src/reverse.ts +260 -0
- package/src/support.ts +93 -0
- package/src/visible.ts +28 -0
- package/test/access-self-answer.test.ts +197 -0
- package/test/box-socket.test.ts +132 -0
- package/test/cockpit-actions.test.ts +19 -0
- package/test/cockpit-transcript.test.ts +71 -0
- package/test/fixtures/restart-host.ts +175 -0
- package/test/grant-box.test.ts +102 -0
- package/test/insert-permission.test.ts +285 -0
- package/test/restart.test.ts +168 -0
- package/test/sessions-reverse.test.ts +341 -0
- package/test/sessions.test.ts +658 -0
- package/tsconfig.json +15 -0
package/src/box.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a session's grant makes of its launch, and the box it runs in.
|
|
3
|
+
*
|
|
4
|
+
* The `tool:` rules become the tool allowance of the harness. A rule that asks (`ask`) grants
|
|
5
|
+
* nothing at launch: the owner's answer comes at the moment of a call, and a launch has no such
|
|
6
|
+
* moment, so it is left out.
|
|
7
|
+
*
|
|
8
|
+
* The box is the host's default for sessions (`allow: ["project", "toolchains"]` unless the host
|
|
9
|
+
* says otherwise), what the start asks for besides or instead, and always the profile of the
|
|
10
|
+
* installation the session runs on, with a temp directory of its own and the host's socket.
|
|
11
|
+
* Widening beyond the default takes the `box.*` rules of the caller's grant.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { coveringRule, matches, rule, specsOf } from "@niwa-labs/core";
|
|
15
|
+
import type { Grant, Rule, RuleSpec, Verb } from "@niwa-labs/core";
|
|
16
|
+
import type { ToolAllowance, ToolsMode } from "@niwa-labs/harness";
|
|
17
|
+
|
|
18
|
+
import { SessionRefusal } from "./refusal.ts";
|
|
19
|
+
|
|
20
|
+
/** The verbs whose rules are for the launch and not for niwa's own actions. */
|
|
21
|
+
const LAUNCH_VERBS: readonly Verb[] = ["tool"];
|
|
22
|
+
|
|
23
|
+
/** The rules that say how far a box may be widened: held by the action that makes a box, never called. */
|
|
24
|
+
const BOX_RULES = "box.";
|
|
25
|
+
|
|
26
|
+
/** Is this rule, as it is written, one of the launch: a tool, or how far a box may be widened? */
|
|
27
|
+
export function isLaunchRule(spec: RuleSpec): boolean {
|
|
28
|
+
const parsed = rule(spec);
|
|
29
|
+
return LAUNCH_VERBS.includes(parsed.verb) || (parsed.verb === "call" && parsed.name.startsWith(BOX_RULES));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The launch rules a child takes from its caller: when the child asked for no tool, the tools the
|
|
34
|
+
* caller holds, as it holds them. A child is never wider than its caller, so a limited caller's
|
|
35
|
+
* child is not left with every tool by asking for none. A caller that nothing limits has no rules
|
|
36
|
+
* to hand down.
|
|
37
|
+
*/
|
|
38
|
+
export function inheritedLaunch(caller: Grant | "unlimited", asked: readonly RuleSpec[]): RuleSpec[] {
|
|
39
|
+
if (caller === "unlimited") return [];
|
|
40
|
+
const named = asked.map(rule);
|
|
41
|
+
const inheritsTools = !named.some((entry) => entry.verb === "tool");
|
|
42
|
+
const isBoxRule = (entry: Rule) => entry.verb === "call" && entry.name.startsWith(BOX_RULES);
|
|
43
|
+
const inheritsBox = !named.some(isBoxRule);
|
|
44
|
+
const rules = caller.rules.filter((entry) => (inheritsTools && entry.verb === "tool") || (inheritsBox && isBoxRule(entry)));
|
|
45
|
+
return specsOf({ rules });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function plain(of: Rule): Rule {
|
|
49
|
+
if (of.target !== undefined) {
|
|
50
|
+
throw new SessionRefusal("rule-target", `${of.verb}:${of.name} has a target, which means nothing for a launch`);
|
|
51
|
+
}
|
|
52
|
+
return of;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The tools of a session: the mode the start asked for, held within the allow-list its grant
|
|
57
|
+
* makes. Only niwa's tools is narrower than any allow-list; two allow-lists keep the names both
|
|
58
|
+
* have.
|
|
59
|
+
*/
|
|
60
|
+
export function toolsOfSession(asked: ToolsMode | undefined, granted: ToolAllowance | undefined): ToolsMode | undefined {
|
|
61
|
+
if (asked === undefined || asked === "all") return granted;
|
|
62
|
+
if (asked === "niwa-only" || granted === undefined) return asked;
|
|
63
|
+
return { allow: asked.allow.filter((tool) => granted.allow.includes(tool)) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The tools a grant allows. `tool:*` and no `tool:` rule at all leave the tools to the harness;
|
|
68
|
+
* the tool names are the harness's own.
|
|
69
|
+
*/
|
|
70
|
+
export function toolsOfGrant(given: Grant): ToolAllowance | undefined {
|
|
71
|
+
const tools = given.rules.filter((each) => LAUNCH_VERBS.includes(each.verb)).map(plain);
|
|
72
|
+
const allowed = tools.filter((each) => !each.ask);
|
|
73
|
+
const exception = tools.find((entry) => entry.ask && allowed.some((other) => matches(other.name, entry.name)));
|
|
74
|
+
if (exception !== undefined) {
|
|
75
|
+
throw new SessionRefusal("tool-exception", `the launch cannot express a tool allowance with an exception for ${exception.name}`);
|
|
76
|
+
}
|
|
77
|
+
const allow = allowed.map((each) => String(each.name));
|
|
78
|
+
return tools.length === 0 || allow.includes("*") ? undefined : { allow };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Whether a caller holds a rule of the box (`box.read@/data`): the rule of its grant that covers
|
|
83
|
+
* it, as it is written; the rule itself for a caller nothing limits; undefined when none does.
|
|
84
|
+
*/
|
|
85
|
+
export function heldRule(rights: Grant | "unlimited", needed: string): string | undefined {
|
|
86
|
+
return rights === "unlimited" ? needed : coveringRule(rights, needed);
|
|
87
|
+
}
|
package/src/caps.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ceiling of a harness: how many of its sessions may run a turn at once on this host.
|
|
3
|
+
*
|
|
4
|
+
* A session holds a slot while it runs a turn: from the moment a start, a send or an ask into it is
|
|
5
|
+
* let through until the journal says its turn ended, or the session did, or the ask was answered.
|
|
6
|
+
* A session that sleeps between turns holds nothing, and neither does one this host does not
|
|
7
|
+
* follow: its process is not this host's, and nor does a turn that began before this host served.
|
|
8
|
+
* A session counts once however many calls go into it, and a call into a session that holds a slot
|
|
9
|
+
* already is let through: it joins that session's queue, not the harness's. What a slot is held by
|
|
10
|
+
* is read from the journal at every look; only the calls on their way to the harness are counted
|
|
11
|
+
* in memory, until the turn they began is in the journal.
|
|
12
|
+
*
|
|
13
|
+
* A call over the ceiling waits until a slot is free, in the order nothing promises.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { JournalReader, Seq } from "@niwa-labs/core";
|
|
17
|
+
import type { DeliveryReceipt } from "@niwa-labs/harness";
|
|
18
|
+
|
|
19
|
+
import type { SessionRef } from "./identity.ts";
|
|
20
|
+
import { SessionEnded, SessionTurnEnded, SessionTurnStarted } from "./records.ts";
|
|
21
|
+
|
|
22
|
+
/** How long a waiting call sleeps before it looks again when nothing is committed. */
|
|
23
|
+
const LOOK_AGAIN_MS = 1000;
|
|
24
|
+
|
|
25
|
+
/** A slot that was let through: told the session its call reached, and let go when the call is over. */
|
|
26
|
+
export interface Slot {
|
|
27
|
+
/** The call reached a session: a turn that the receipt says began or waits holds the slot until it ends. */
|
|
28
|
+
reached(ref: SessionRef, receipt: DeliveryReceipt | undefined): void;
|
|
29
|
+
/** The call is over, or began no turn: the slot is free. */
|
|
30
|
+
release(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CapsDeps {
|
|
34
|
+
readonly journal: () => JournalReader | undefined;
|
|
35
|
+
readonly untilCommit: (ms: number) => Promise<void>;
|
|
36
|
+
/** The sessions this host follows now. */
|
|
37
|
+
readonly followed: () => Iterable<SessionRef>;
|
|
38
|
+
/** The harness a session is of. */
|
|
39
|
+
readonly harnessOf: (ref: SessionRef) => string;
|
|
40
|
+
/** The last record before this host served: a turn that began at or before it is one a process of another host ran. */
|
|
41
|
+
readonly servedAfter: () => Seq;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const FREE: Slot = { reached() {}, release() {} };
|
|
45
|
+
|
|
46
|
+
/** The ceilings of the harnesses that have one, and the slots their sessions hold. */
|
|
47
|
+
export class HarnessCaps {
|
|
48
|
+
/** The starts let through that have not named a session yet, by harness. */
|
|
49
|
+
readonly #going = new Map<string, number>();
|
|
50
|
+
/** The calls into a session that are going now, by session. */
|
|
51
|
+
readonly #into = new Map<SessionRef, number>();
|
|
52
|
+
/** The sessions a call reached whose turn the journal does not show yet, with the position the call was let through at. */
|
|
53
|
+
readonly #reached = new Map<SessionRef, Seq>();
|
|
54
|
+
/** Wakes the calls that wait when a slot is let go here. */
|
|
55
|
+
#wake: () => void = () => {};
|
|
56
|
+
#woken = new Promise<void>((resolve) => {
|
|
57
|
+
this.#wake = resolve;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
constructor(
|
|
61
|
+
private readonly caps: Readonly<Record<string, number>>,
|
|
62
|
+
private readonly deps: CapsDeps,
|
|
63
|
+
) {
|
|
64
|
+
for (const [harness, cap] of Object.entries(caps)) {
|
|
65
|
+
if (!Number.isInteger(cap) || cap < 1) throw new TypeError(`the ceiling of harness "${harness}" must be a whole number of at least 1, got ${String(cap)}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Waits for a slot of the harness and takes it: for a new session, or for the session `into`. A harness with no
|
|
71
|
+
* ceiling, and a session that holds a slot already, are let through at once.
|
|
72
|
+
*/
|
|
73
|
+
async admit(harness: string, into?: SessionRef): Promise<Slot> {
|
|
74
|
+
const cap = this.caps[harness];
|
|
75
|
+
if (cap === undefined) return FREE;
|
|
76
|
+
for (;;) {
|
|
77
|
+
const busy = this.#busy(harness);
|
|
78
|
+
if ((into !== undefined && busy.sessions.has(into)) || busy.count < cap) break;
|
|
79
|
+
const woken = this.#woken;
|
|
80
|
+
await Promise.race([this.deps.untilCommit(LOOK_AGAIN_MS), woken]);
|
|
81
|
+
}
|
|
82
|
+
// What the journal says after this moment is about the turn this call may begin.
|
|
83
|
+
const admitted = this.#last();
|
|
84
|
+
if (into === undefined) this.#going.set(harness, (this.#going.get(harness) ?? 0) + 1);
|
|
85
|
+
else this.#into.set(into, (this.#into.get(into) ?? 0) + 1);
|
|
86
|
+
let held = true;
|
|
87
|
+
const leave = (): void => {
|
|
88
|
+
if (!held) return;
|
|
89
|
+
held = false;
|
|
90
|
+
if (into === undefined) this.#going.set(harness, (this.#going.get(harness) ?? 1) - 1);
|
|
91
|
+
else {
|
|
92
|
+
const left = (this.#into.get(into) ?? 1) - 1;
|
|
93
|
+
if (left > 0) this.#into.set(into, left);
|
|
94
|
+
else this.#into.delete(into);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
reached: (ref, receipt) => {
|
|
99
|
+
// A message that joined a running turn began none of its own.
|
|
100
|
+
if (receipt !== undefined && receipt.status !== "delivered") this.#reached.set(ref, admitted);
|
|
101
|
+
leave();
|
|
102
|
+
this.#notify();
|
|
103
|
+
},
|
|
104
|
+
release: () => {
|
|
105
|
+
leave();
|
|
106
|
+
this.#notify();
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The slots of a harness that are held now, and the sessions that hold them. */
|
|
112
|
+
#busy(harness: string): { count: number; sessions: Set<SessionRef> } {
|
|
113
|
+
const journal = this.deps.journal();
|
|
114
|
+
const sessions = new Set<SessionRef>();
|
|
115
|
+
for (const ref of new Set([...this.deps.followed(), ...this.#reached.keys(), ...this.#into.keys()])) {
|
|
116
|
+
if (this.deps.harnessOf(ref) !== harness) continue;
|
|
117
|
+
if (this.#into.has(ref) || (journal !== undefined && this.#running(journal, ref))) sessions.add(ref);
|
|
118
|
+
}
|
|
119
|
+
return { count: sessions.size + (this.#going.get(harness) ?? 0), sessions };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Does the session run a turn: its last turn began and did not end, or a call reached it and its turn has not begun yet. */
|
|
123
|
+
#running(journal: JournalReader, ref: SessionRef): boolean {
|
|
124
|
+
const last = (type: string): Seq | undefined => journal.find({ type: type as never, field: "session", equals: ref }).at(-1)?.seq;
|
|
125
|
+
const start = last(SessionTurnStarted.name);
|
|
126
|
+
const began = start === undefined || start <= this.deps.servedAfter() ? undefined : start;
|
|
127
|
+
const ended = Math.max(last(SessionTurnEnded.name) ?? 0, last(SessionEnded.name) ?? 0);
|
|
128
|
+
const reached = this.#reached.get(ref);
|
|
129
|
+
if (reached !== undefined) {
|
|
130
|
+
// The journal caught up with the call: from here it says whether the turn runs.
|
|
131
|
+
if ((began !== undefined && began > reached) || ended > reached) this.#reached.delete(ref);
|
|
132
|
+
else return true;
|
|
133
|
+
}
|
|
134
|
+
return began !== undefined && began > ended;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The position of the latest record. */
|
|
138
|
+
#last(): Seq {
|
|
139
|
+
return this.deps.journal()?.last() ?? (0 as Seq);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
#notify(): void {
|
|
143
|
+
const wake = this.#wake;
|
|
144
|
+
this.#woken = new Promise<void>((resolve) => {
|
|
145
|
+
this.#wake = resolve;
|
|
146
|
+
});
|
|
147
|
+
wake();
|
|
148
|
+
}
|
|
149
|
+
}
|
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The catalog: what niwa knows about the sessions there are, without copying any of them.
|
|
3
|
+
*
|
|
4
|
+
* It holds a pointer and an index per session. The harness's own transcript is never in here: a
|
|
5
|
+
* reader asks the reading side for it. Whom a session serves is not a field of the session: the
|
|
6
|
+
* attachments are kept apart, each with its source.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { Address } from "@niwa-labs/core";
|
|
12
|
+
import type { StoredRecord, Timestamp } from "@niwa-labs/core";
|
|
13
|
+
|
|
14
|
+
import { SessionRefSchema } from "./identity.ts";
|
|
15
|
+
import type { NiwaSessionId, SessionRef } from "./identity.ts";
|
|
16
|
+
import { LIFE_TYPES, lifeOf } from "./life.ts";
|
|
17
|
+
import type { LifeState } from "./life.ts";
|
|
18
|
+
import { SessionActivity, SessionBelongs, SessionModel, SessionStarted } from "./records.ts";
|
|
19
|
+
import type { BelongingSource } from "./records.ts";
|
|
20
|
+
|
|
21
|
+
/** What niwa knows about one session. Every field but the pointer may be absent. */
|
|
22
|
+
export interface SessionEntry {
|
|
23
|
+
readonly ref: SessionRef;
|
|
24
|
+
/** The id niwa gave the session; absent for a session niwa did not start. */
|
|
25
|
+
readonly id?: NiwaSessionId;
|
|
26
|
+
/** A readable title, as the reading side gives it. */
|
|
27
|
+
readonly title?: string;
|
|
28
|
+
readonly run?: string | undefined;
|
|
29
|
+
readonly cwd?: string;
|
|
30
|
+
/** The model the harness named for the session; absent until it names one. */
|
|
31
|
+
readonly model?: string;
|
|
32
|
+
readonly startedAt?: number;
|
|
33
|
+
/** The last sign of life, when one is known. */
|
|
34
|
+
readonly lastActivityAt?: number;
|
|
35
|
+
readonly state: LifeState;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One attachment of a session, from a record of its own. */
|
|
39
|
+
export interface Belonging {
|
|
40
|
+
readonly session: SessionRef;
|
|
41
|
+
/** The address the session serves, as a tagged value. */
|
|
42
|
+
readonly to: Address;
|
|
43
|
+
readonly source: BelongingSource;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The sessions niwa knows: from its own records, and from what the reading sides list. */
|
|
47
|
+
export class SessionCatalog {
|
|
48
|
+
private readonly entries = new Map<SessionRef, SessionEntry>();
|
|
49
|
+
private readonly attachments: Belonging[] = [];
|
|
50
|
+
|
|
51
|
+
/** Every session, in the order of the pointer. */
|
|
52
|
+
all(): SessionEntry[] {
|
|
53
|
+
return [...this.entries.values()].sort((a, b) => a.ref.localeCompare(b.ref));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get(ref: SessionRef): SessionEntry | undefined {
|
|
57
|
+
return this.entries.get(ref);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The attachments of the given sessions. */
|
|
61
|
+
belongings(refs: ReadonlySet<SessionRef>): Belonging[] {
|
|
62
|
+
return this.attachments.filter((belonging) => refs.has(belonging.session));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Put a session in. What is already known is kept: an absent fact never replaces a known one. */
|
|
66
|
+
remember(entry: SessionEntry): void {
|
|
67
|
+
const known = this.entries.get(entry.ref);
|
|
68
|
+
if (known === undefined) {
|
|
69
|
+
this.entries.set(entry.ref, entry);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
this.entries.set(entry.ref, {
|
|
73
|
+
ref: known.ref,
|
|
74
|
+
...(known.run ?? entry.run ? { run: known.run ?? entry.run } : {}),
|
|
75
|
+
id: known.id ?? entry.id,
|
|
76
|
+
title: known.title ?? entry.title,
|
|
77
|
+
cwd: known.cwd ?? entry.cwd,
|
|
78
|
+
model: known.model ?? entry.model,
|
|
79
|
+
startedAt: known.startedAt ?? entry.startedAt,
|
|
80
|
+
lastActivityAt: known.lastActivityAt ?? entry.lastActivityAt,
|
|
81
|
+
state: known.state === "unknown" ? entry.state : known.state,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build the catalog from niwa's own session records, given in journal order.
|
|
87
|
+
*
|
|
88
|
+
* `bootedAt` is when this process began: a turn left open by an earlier process is `unknown`.
|
|
89
|
+
*/
|
|
90
|
+
static fromRecords(records: readonly StoredRecord[], bootedAt: Timestamp): SessionCatalog {
|
|
91
|
+
const catalog = new SessionCatalog();
|
|
92
|
+
const life = new Map<SessionRef, StoredRecord[]>();
|
|
93
|
+
const starts = new Map<SessionRef, z.output<typeof SessionStarted.schema> & { at: Timestamp }>();
|
|
94
|
+
const activity = new Map<SessionRef, Timestamp>();
|
|
95
|
+
const models = new Map<SessionRef, string>();
|
|
96
|
+
|
|
97
|
+
for (const record of records) {
|
|
98
|
+
const ref = refOf(record);
|
|
99
|
+
if (ref === undefined) continue;
|
|
100
|
+
if (LIFE_TYPES.includes(record.type)) life.set(ref, [...(life.get(ref) ?? []), record]);
|
|
101
|
+
if (record.type === SessionStarted.name && !starts.has(ref)) {
|
|
102
|
+
const started = SessionStarted.schema.safeParse(record.data);
|
|
103
|
+
if (started.success) starts.set(ref, { ...started.data, at: record.at });
|
|
104
|
+
}
|
|
105
|
+
if (record.type === SessionActivity.name) activity.set(ref, record.at);
|
|
106
|
+
if (record.type === SessionModel.name) {
|
|
107
|
+
const named = SessionModel.schema.safeParse(record.data);
|
|
108
|
+
if (named.success) models.set(ref, named.data.model);
|
|
109
|
+
}
|
|
110
|
+
if (record.type === SessionBelongs.name) {
|
|
111
|
+
const attachment = belongingOf(ref, record);
|
|
112
|
+
if (attachment !== undefined) catalog.attachments.push(attachment);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
for (const [ref, start] of starts) {
|
|
117
|
+
catalog.remember({
|
|
118
|
+
ref,
|
|
119
|
+
id: start.id,
|
|
120
|
+
...(start.run ? { run: start.run } : {}),
|
|
121
|
+
cwd: start.cwd,
|
|
122
|
+
model: models.get(ref),
|
|
123
|
+
startedAt: start.at,
|
|
124
|
+
lastActivityAt: activity.get(ref),
|
|
125
|
+
state: lifeOf(life.get(ref) ?? [], bootedAt),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
return catalog;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function dataOf(record: StoredRecord): { session?: unknown; to?: { kind?: unknown; id?: unknown }; source?: unknown } {
|
|
133
|
+
return record.data as ReturnType<typeof dataOf>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The pointer a session record names, when it names one. */
|
|
137
|
+
function refOf(record: StoredRecord): SessionRef | undefined {
|
|
138
|
+
const parsed = SessionRefSchema.safeParse(dataOf(record).session);
|
|
139
|
+
return parsed.success ? parsed.data : undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function belongingOf(session: SessionRef, record: StoredRecord): Belonging | undefined {
|
|
143
|
+
const parsed = SessionBelongs.schema.safeParse(record.data);
|
|
144
|
+
if (!parsed.success) return undefined;
|
|
145
|
+
return { session, to: parsed.data.to, source: parsed.data.source };
|
|
146
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session 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 SessionState = z.enum(["running", "idle", "ended", "unknown"]);
|
|
11
|
+
|
|
12
|
+
export const SessionEntry = z.object({
|
|
13
|
+
id: z.string().optional(),
|
|
14
|
+
ref: z.string(),
|
|
15
|
+
run: z.string().optional(),
|
|
16
|
+
title: z.string().optional(),
|
|
17
|
+
cwd: z.string().optional(),
|
|
18
|
+
model: z.string().optional(),
|
|
19
|
+
startedAt: z.number().optional(),
|
|
20
|
+
lastActivityAt: z.number().optional(),
|
|
21
|
+
state: SessionState,
|
|
22
|
+
});
|
|
23
|
+
export type SessionEntry = z.infer<typeof SessionEntry>;
|
|
24
|
+
|
|
25
|
+
export const listAction = {
|
|
26
|
+
name: "session.list",
|
|
27
|
+
input: z.object({ limit: z.number().int().positive().optional(), cursor: z.string().optional(), managedOnly: z.boolean().optional() }),
|
|
28
|
+
output: z.object({ sessions: z.array(SessionEntry), total: z.number(), nextCursor: z.string().optional(), unreadable: z.array(z.object({ harness: z.string(), reason: z.string() })).optional(), hint: z.string().optional() }),
|
|
29
|
+
} as const;
|
|
30
|
+
|
|
31
|
+
const Base = { locator: z.string().optional(), at: z.number().optional() };
|
|
32
|
+
|
|
33
|
+
/** A record of a session's transcript. Kinds the page does not draw are `unknown`. */
|
|
34
|
+
export const TranscriptRecord = z.discriminatedUnion("kind", [
|
|
35
|
+
z.object({ kind: z.literal("user"), text: z.string(), ...Base }),
|
|
36
|
+
z.object({ kind: z.literal("assistant"), text: z.string(), model: z.string().optional(), ...Base }),
|
|
37
|
+
z.object({ kind: z.literal("thinking"), text: z.string(), redacted: z.boolean(), ...Base }),
|
|
38
|
+
z.object({ kind: z.literal("tool-call"), callId: z.string(), name: z.string(), input: z.unknown().optional(), ...Base }),
|
|
39
|
+
z.object({ kind: z.literal("tool-result"), callId: z.string(), name: z.string().optional(), output: z.unknown().optional(), ok: z.boolean().optional(), ...Base }),
|
|
40
|
+
z.object({ kind: z.literal("checklist"), callId: z.string().optional(), items: z.array(z.object({ text: z.string(), state: z.string() })), ...Base }),
|
|
41
|
+
z.object({ kind: z.literal("permission"), callId: z.string().optional(), tool: z.string().optional(), outcome: z.string(), ...Base }),
|
|
42
|
+
z.object({ kind: z.literal("compaction"), summary: z.string(), ...Base }),
|
|
43
|
+
z.object({ kind: z.literal("nested"), child: z.object({ harness: z.string(), native: z.string() }), ...Base }),
|
|
44
|
+
z.object({ kind: z.literal("unknown"), raw: z.unknown().optional(), ...Base }),
|
|
45
|
+
]);
|
|
46
|
+
export type TranscriptRecord = z.infer<typeof TranscriptRecord>;
|
|
47
|
+
|
|
48
|
+
export const readAction = {
|
|
49
|
+
name: "session.read",
|
|
50
|
+
input: z.object({ session: z.string(), window: z.object({ limit: z.number().int().positive().max(250), before: z.string().optional() }).optional() }),
|
|
51
|
+
output: z.object({ records: z.array(TranscriptRecord), coverage: z.object({ status: z.string(), reason: z.string().optional() }).optional(), page: z.object({ hasEarlier: z.boolean() }).optional() }),
|
|
52
|
+
} as const;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The cockpit module of the sessions plugin: the list of sessions and the transcript of one. */
|
|
2
|
+
|
|
3
|
+
import { definePlugin } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
|
|
5
|
+
import { SessionPage, SessionsPage, SessionsTile } from "./pages.tsx";
|
|
6
|
+
|
|
7
|
+
export default definePlugin({
|
|
8
|
+
id: "sessions",
|
|
9
|
+
setup(ctx) {
|
|
10
|
+
ctx.pages.add({
|
|
11
|
+
path: "/sessions",
|
|
12
|
+
title: "Сессии",
|
|
13
|
+
nav: { order: 20 },
|
|
14
|
+
commandHeading: true,
|
|
15
|
+
commands: [{ action: "session.start", label: "Начать сессию" }],
|
|
16
|
+
component: SessionsPage,
|
|
17
|
+
});
|
|
18
|
+
ctx.pages.add({
|
|
19
|
+
path: "/sessions/$sessionId",
|
|
20
|
+
title: "Сессия",
|
|
21
|
+
commands: ({ params }) => [
|
|
22
|
+
{ action: "session.send", label: "Отправить сообщение", preset: { session: params.sessionId } },
|
|
23
|
+
{ action: "session.resume", label: "Продолжить сессию", preset: { session: params.sessionId } },
|
|
24
|
+
{ action: "session.interrupt", label: "Прервать ход", preset: { session: params.sessionId } },
|
|
25
|
+
],
|
|
26
|
+
component: SessionPage,
|
|
27
|
+
});
|
|
28
|
+
if (ctx.viewer.can("session.list"))
|
|
29
|
+
ctx.slots.register("home.main", { key: "sessions", order: 20, component: SessionsTile });
|
|
30
|
+
ctx.entities.register("session", {
|
|
31
|
+
label: "Сессия",
|
|
32
|
+
prefix: "s",
|
|
33
|
+
href: (id) => `/sessions/${encodeURIComponent(id)}`,
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
});
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/** The sessions of the host and the transcript of one of them. */
|
|
2
|
+
|
|
3
|
+
import { EntityLink, PageLink, useCall, type PageProps } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
import {
|
|
5
|
+
FileRef,
|
|
6
|
+
Markdown,
|
|
7
|
+
Message,
|
|
8
|
+
MessageAvatar,
|
|
9
|
+
MessageBubble,
|
|
10
|
+
MessageContent,
|
|
11
|
+
MessageHeader,
|
|
12
|
+
PageSection,
|
|
13
|
+
StateRing,
|
|
14
|
+
ToolCall,
|
|
15
|
+
Transcript,
|
|
16
|
+
formatAgo,
|
|
17
|
+
type WorkState,
|
|
18
|
+
} from "@niwa-labs/ui-kit";
|
|
19
|
+
|
|
20
|
+
import { useEffect, useMemo, useState } from "react";
|
|
21
|
+
import type { HomeTileProps } from "@niwa-labs/cockpit-sdk";
|
|
22
|
+
import { listAction, readAction, type SessionEntry } from "./actions.ts";
|
|
23
|
+
import { itemsOf, type TranscriptItem } from "./transcript.ts";
|
|
24
|
+
|
|
25
|
+
const RING: Readonly<Record<SessionEntry["state"], WorkState>> = { running: "running", idle: "waiting", ended: "done", unknown: "pending" };
|
|
26
|
+
const SESSION_STATE_LABEL: Readonly<Record<SessionEntry["state"], string>> = {
|
|
27
|
+
running: "Идёт ход",
|
|
28
|
+
idle: "Между ходами",
|
|
29
|
+
ended: "Завершена",
|
|
30
|
+
unknown: "Состояние неизвестно",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function SessionRow({ entry }: { entry: SessionEntry }) {
|
|
34
|
+
const session = entry.id ?? entry.ref;
|
|
35
|
+
const title = entry.title?.trim() || entry.model || entry.ref;
|
|
36
|
+
return (
|
|
37
|
+
<li data-slot="session-row" data-state={entry.state} className="flex min-w-0 flex-col gap-1 py-2">
|
|
38
|
+
<div className="flex min-w-0 items-center gap-2">
|
|
39
|
+
<StateRing state={RING[entry.state]} label={SESSION_STATE_LABEL[entry.state]} aria-hidden="true" />
|
|
40
|
+
<PageLink to={`/sessions/${encodeURIComponent(session)}`} className="min-w-0 wrap-anywhere text-sm font-semibold hover:underline focus-visible:underline">
|
|
41
|
+
{title}
|
|
42
|
+
{title !== session && <span className="sr-only"> · {session}</span>}
|
|
43
|
+
</PageLink>
|
|
44
|
+
</div>
|
|
45
|
+
<div data-slot="session-meta" className="flex min-w-0 flex-wrap items-center gap-2 pl-4 text-xs text-muted-foreground">
|
|
46
|
+
<span>{SESSION_STATE_LABEL[entry.state]}</span>
|
|
47
|
+
{entry.id && <EntityLink entity={{ kind: "session", id: entry.id }} short />}
|
|
48
|
+
{entry.run && <EntityLink entity={{ kind: "run", id: entry.run }} short />}
|
|
49
|
+
{entry.model && entry.model !== title && <span className="min-w-0 wrap-anywhere">{entry.model}</span>}
|
|
50
|
+
{entry.lastActivityAt !== undefined && (
|
|
51
|
+
<time className="tabular-nums" dateTime={new Date(entry.lastActivityAt).toISOString()}>
|
|
52
|
+
{formatAgo(entry.lastActivityAt)}
|
|
53
|
+
</time>
|
|
54
|
+
)}
|
|
55
|
+
</div>
|
|
56
|
+
{entry.cwd && <div className="min-w-0 pl-4 text-xs"><FileRef path={entry.cwd} /></div>}
|
|
57
|
+
</li>
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function SessionsTile({ project, reportProjects }: HomeTileProps) {
|
|
62
|
+
const sessions = useCall(listAction, { managedOnly: true, limit: 500 }, { refreshOn: { types: ["session.*"] } });
|
|
63
|
+
const dirs = useMemo(() => [...new Set(sessions.data?.sessions.flatMap(s => s.cwd ? [s.cwd] : []))], [sessions.data]);
|
|
64
|
+
useEffect(() => reportProjects?.(dirs), [dirs, reportProjects]);
|
|
65
|
+
const rows = sessions.data?.sessions.filter(s => !s.run && (!project || s.cwd === project)).slice(0, 30);
|
|
66
|
+
return <PageSection title="Самостоятельные сессии">
|
|
67
|
+
{sessions.error ? <p role="alert">{sessions.error.message}</p> : !rows ? <p>Загружаю…</p> : rows.length ? <ul>{rows.map(s => <SessionRow key={s.ref} entry={s} />)}</ul> : <p>Нет сессий вне запусков.</p>}
|
|
68
|
+
<PageLink to="/sessions">Все сессии →</PageLink></PageSection>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function SessionsPage() {
|
|
72
|
+
const [source, setSource] = useState<"managed" | "all">("managed");
|
|
73
|
+
return (
|
|
74
|
+
<>
|
|
75
|
+
<div className="desk-tools" role="group" aria-label="Источник сессий">
|
|
76
|
+
<button type="button" className={source === "managed" ? "desk-primary" : undefined} aria-pressed={source === "managed"} onClick={() => setSource("managed")}>
|
|
77
|
+
Сессии Niwa
|
|
78
|
+
</button>
|
|
79
|
+
<button type="button" className={source === "all" ? "desk-primary" : undefined} aria-pressed={source === "all"} onClick={() => setSource("all")}>
|
|
80
|
+
Вся история с диска
|
|
81
|
+
</button>
|
|
82
|
+
</div>
|
|
83
|
+
<SessionResults key={source} managedOnly={source === "managed"} />
|
|
84
|
+
</>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function SessionResults({ managedOnly }: { managedOnly: boolean }) {
|
|
89
|
+
const [cursors, setCursors] = useState<string[]>([]);
|
|
90
|
+
const cursor = cursors.at(-1);
|
|
91
|
+
const sessions = useCall(listAction, { managedOnly, limit: 100, ...(cursor && { cursor }) }, { refreshOn: { types: ["session.*"] } });
|
|
92
|
+
const nextCursor = sessions.data?.nextCursor;
|
|
93
|
+
return (
|
|
94
|
+
<div className="flex min-w-0 flex-col gap-3">
|
|
95
|
+
{sessions.data?.unreadable?.map(h => <p role="status" key={h.harness}>{h.harness} · {h.reason}</p>)}
|
|
96
|
+
{sessions.isPending ? (
|
|
97
|
+
<p role="status" className="text-sm text-muted-foreground">{managedOnly ? "Загружаю сессии…" : "Читаю историю с диска…"}</p>
|
|
98
|
+
) : sessions.isError ? (
|
|
99
|
+
<p role="alert" className="text-sm text-destructive">Не удалось прочитать сессии: {sessions.error.message}</p>
|
|
100
|
+
) : sessions.data.sessions.length === 0 ? (
|
|
101
|
+
<p className="text-sm text-muted-foreground">Сессий пока нет.</p>
|
|
102
|
+
) : (
|
|
103
|
+
<>
|
|
104
|
+
<ul data-slot="sessions" aria-label={managedOnly ? "Сессии Niwa" : "Вся история с диска"} className="m-0 list-none divide-y rounded-lg border bg-card px-3 text-card-foreground">
|
|
105
|
+
{sessions.data.sessions.map((entry) => (
|
|
106
|
+
<SessionRow key={entry.ref} entry={entry} />
|
|
107
|
+
))}
|
|
108
|
+
</ul>
|
|
109
|
+
{sessions.data.total > sessions.data.sessions.length ? (
|
|
110
|
+
<p className="text-xs text-muted-foreground">
|
|
111
|
+
Показано {sessions.data.sessions.length} из {sessions.data.total} сессий.
|
|
112
|
+
</p>
|
|
113
|
+
) : null}
|
|
114
|
+
</>
|
|
115
|
+
)}
|
|
116
|
+
{(cursor || nextCursor) && (
|
|
117
|
+
<nav className="desk-tools" aria-label="Страницы списка сессий">
|
|
118
|
+
{cursor && <button type="button" onClick={() => setCursors(c => c.slice(0, -1))}>← Предыдущие сессии</button>}
|
|
119
|
+
{nextCursor && <button type="button" onClick={() => setCursors(c => [...c, nextCursor])}>Следующие сессии →</button>}
|
|
120
|
+
</nav>
|
|
121
|
+
)}
|
|
122
|
+
</div>
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function Item({ item }: { item: TranscriptItem }) {
|
|
127
|
+
if (item.kind === "tool") {
|
|
128
|
+
return (
|
|
129
|
+
<div className="px-4 py-1">
|
|
130
|
+
<ToolCall name={item.name} state={item.state} input={item.input} output={item.output} />
|
|
131
|
+
</div>
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (item.kind === "note") {
|
|
135
|
+
return (
|
|
136
|
+
<div className="px-4 py-1 text-xs text-muted-foreground">
|
|
137
|
+
<span className="font-medium">{item.label}</span>
|
|
138
|
+
{item.text === "" ? null : <span className="ml-2 line-clamp-3 whitespace-pre-wrap">{item.text}</span>}
|
|
139
|
+
</div>
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
return (
|
|
143
|
+
<div className="px-4 py-2">
|
|
144
|
+
<Message align={item.role === "user" ? "end" : "start"}>
|
|
145
|
+
{item.role === "assistant" ? <MessageAvatar className="size-7 text-xs">AI</MessageAvatar> : null}
|
|
146
|
+
<MessageContent>
|
|
147
|
+
{item.role === "assistant" && item.model !== undefined ? <MessageHeader>{item.model}</MessageHeader> : null}
|
|
148
|
+
<MessageBubble>{item.role === "user" ? <p className="whitespace-pre-wrap">{item.text}</p> : <Markdown text={item.text} />}</MessageBubble>
|
|
149
|
+
</MessageContent>
|
|
150
|
+
</Message>
|
|
151
|
+
</div>
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function SessionPage({ params }: PageProps<"/sessions/$sessionId">) {
|
|
156
|
+
return <SessionTranscript key={params.sessionId} id={params.sessionId} />;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function SessionTranscript({ id }: { id: string }) {
|
|
160
|
+
const [anchors, setAnchors] = useState<string[]>([]);
|
|
161
|
+
const before = anchors.at(-1);
|
|
162
|
+
const read = useCall(readAction, { session: id, window: { limit: 200, ...(before && { before }) } }, { refreshOn: { types: ["session.*"] } });
|
|
163
|
+
return (
|
|
164
|
+
<div data-slot="session-page" className="flex h-full min-h-0 min-w-0 flex-col">
|
|
165
|
+
<header className="flex min-w-0 items-center gap-2 border-b px-4 py-3">
|
|
166
|
+
<PageLink to="/sessions" className="text-sm text-muted-foreground hover:underline">
|
|
167
|
+
Sessions
|
|
168
|
+
</PageLink>
|
|
169
|
+
<span className="text-muted-foreground">/</span>
|
|
170
|
+
<EntityLink entity={{ kind: "session", id }} />
|
|
171
|
+
</header>
|
|
172
|
+
{read.data?.coverage?.reason && <p role="alert">{read.data.coverage.reason}</p>}
|
|
173
|
+
{read.isPending ? (
|
|
174
|
+
<p className="p-4 text-sm text-muted-foreground">Loading the transcript…</p>
|
|
175
|
+
) : read.isError ? (
|
|
176
|
+
<p role="alert" className="p-4 text-sm text-destructive">The transcript could not be read: {read.error.message}</p>
|
|
177
|
+
) : (
|
|
178
|
+
<Transcript
|
|
179
|
+
items={itemsOf(read.data.records)}
|
|
180
|
+
itemKey={(item) => item.key}
|
|
181
|
+
renderItem={(item) => <Item item={item} />}
|
|
182
|
+
empty="Nothing has been said in this session yet."
|
|
183
|
+
className="min-h-80"
|
|
184
|
+
/>
|
|
185
|
+
)}
|
|
186
|
+
<div className="desk-tools">{read.data?.page?.hasEarlier && read.data.records[0]?.locator && <button onClick={() => setAnchors(a => [...a, read.data.records[0]!.locator!])}>← Предыдущие сообщения</button>}
|
|
187
|
+
{before && <button onClick={() => setAnchors(a => a.slice(0, -1))}>Следующие сообщения →</button>}</div>
|
|
188
|
+
</div>
|
|
189
|
+
);
|
|
190
|
+
}
|