@niwa-labs/history 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 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
- # Temporary Holding Version
1
+ # @niwa-labs/history
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reading a session's transcript through its harness's reading side: read with a bound harness (every record, or a digest or a brief in windows), plain-text search over the records, and a description of how much of a transcript was actually read. The `history` plugin lists the sessions the reading sides hold (`history.list`), reads and searches a transcript (`history.read`, `history.search`), and watches a session of any harness as it grows and records how far its checklist is, when it pauses and when it ends; the transcript itself is never written into the journal. `/records` holds the schemas of the queries, the records and the actions, and `sessionEnded(session)`, the query of the end of one watched session. `/flow` gives workflow scripts `readSession`, which reads a transcript in windows, and `untilSessionEnded`, which waits for a watched session to end; each is a step of the script.
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@niwa-labs/history",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts",
8
+ "./records": "./src/records.ts",
9
+ "./flow": "./src/flow.ts"
10
+ },
11
+ "dependencies": {
12
+ "@niwa-labs/core": "0.0.0",
13
+ "@niwa-labs/digest": "0.0.0",
14
+ "@niwa-labs/harness": "0.0.0",
15
+ "@niwa-labs/plugin": "0.0.0",
16
+ "zod": "^4.6.7"
17
+ }
18
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Coverage: how much of a session was actually read.
3
+ *
4
+ * Only `empty` says there is nothing there; every other status says the answer is not known.
5
+ */
6
+
7
+ import type { Coverage } from "@niwa-labs/harness";
8
+
9
+ /** Whether the coverage says there is nothing there. */
10
+ export function isEmpty(coverage: Coverage): boolean {
11
+ return coverage.status === "empty";
12
+ }
13
+
14
+ /** A one-line description of the coverage. It says "nothing" only for `empty`. */
15
+ export function describeCoverage(coverage: Coverage): string {
16
+ switch (coverage.status) {
17
+ case "empty":
18
+ return "scanned and empty";
19
+ case "not-scanned":
20
+ return "not scanned";
21
+ case "failed":
22
+ return `scan failed: ${coverage.reason}`;
23
+ case "unavailable":
24
+ return `unavailable: ${coverage.reason}`;
25
+ }
26
+ }
package/src/flow.ts ADDED
@@ -0,0 +1,125 @@
1
+ // The history entry for workflow scripts: read the transcript of a session in windows that fit a
2
+ // budget, and wait for a watched session to end, each as a step of the script. A step names its
3
+ // call (`label`), so a replay does not read or wait again.
4
+ //
5
+ // import { readSession, untilSessionEnded } from "@niwa-labs/history/flow"
6
+ // const win = await readSession("read", { session, mode: "digest", from, budget: 40_000 })
7
+ // // win.entries, win.next (null at the end), win.files (give it to the next read), win.omitted
8
+ // const end = await untilSessionEnded("end", { session, timeout: "2h" })
9
+ // // end.ended, end.certainty ("exact" or "guessed"), end.at (the position to read on from)
10
+
11
+ import type { z } from "zod";
12
+
13
+ import type { TypeQuery } from "@niwa-labs/core";
14
+ import type { Brief, DigestEntry, FileIndex } from "@niwa-labs/digest";
15
+ import type { SessionId, SessionRecord } from "@niwa-labs/harness";
16
+
17
+ import { sessionEnded } from "./records.ts";
18
+ import type { EndSignal, ReadAnswerSchema, historyRead } from "./records.ts";
19
+
20
+ /** `call` is a global of a workflow script. */
21
+ declare const call: (name: string, input: unknown, opts?: { label?: string; reason?: string }) => Promise<unknown>;
22
+
23
+ /** A duration as a script writes it: milliseconds, or a text such as "30s", "5m", "2h". */
24
+ export type Duration = number | string;
25
+
26
+ /** The `wait` of a workflow script, as far as the helpers use it: one query of one type, typed by it. */
27
+ type ScriptWait = <D>(query: TypeQuery<D>, opts: { from?: number; timeout?: Duration; label?: string }) => Promise<{ data: D; at: number } | { timedOut: true }>;
28
+
29
+ /** The `wait` of the script that calls a helper: a global, read when the helper is called. */
30
+ function scriptWait(): ScriptWait {
31
+ const wait = (globalThis as { wait?: unknown }).wait;
32
+ if (typeof wait !== "function") throw new Error('@niwa-labs/history/flow runs inside a workflow script: "wait" is not a global here');
33
+ return wait as ScriptWait;
34
+ }
35
+
36
+ /** What a read is given: the session, and what to read of it. */
37
+ export type ReadSessionInput = z.input<typeof historyRead.input>;
38
+
39
+ /** One window of a read. */
40
+ export interface SessionWindow {
41
+ /** How the window was kept, as asked: `digest` when the read named no mode, `full` for a read of the records before a locator. */
42
+ readonly mode: "full" | "digest" | "brief";
43
+ /** The entries of a digest, in the order of the session; empty for the other modes. */
44
+ readonly entries: DigestEntry[];
45
+ /** The brief of a `brief` read. */
46
+ readonly brief?: Brief;
47
+ /** The records of a `full` read. */
48
+ readonly records: SessionRecord[];
49
+ /** Where the next window reads from; `null` when this one read to the end of what is there now. */
50
+ readonly next: string | null;
51
+ /** The last record the window holds: where a read of a session that still grows goes on from. */
52
+ readonly upto: string | null;
53
+ /** The file index to give the next read as `files`. */
54
+ readonly files: FileIndex;
55
+ /** How many records left nothing in the window. */
56
+ readonly omitted: number;
57
+ /** True when a read of the records before a locator found more before them; false for every other read. */
58
+ readonly hasEarlier: boolean;
59
+ /** True when the read started over: the position given belonged to another source, and what was gathered before no longer holds. */
60
+ readonly restarted: boolean;
61
+ }
62
+
63
+ /**
64
+ * Reads a window of a session as the step `label`. A read that could not be made (the harness has
65
+ * no reading side, the transcript is unreadable) throws, never an empty window: "nothing was read"
66
+ * is not "nothing is there".
67
+ */
68
+ export async function readSession(label: string, input: ReadSessionInput): Promise<SessionWindow> {
69
+ // Records before a locator are read whole: a digest is the default of a read forward only.
70
+ const mode = input.mode ?? (input.window === undefined ? "digest" : "full");
71
+ const answer = (await call("history.read", { ...input, mode }, { label })) as z.output<typeof ReadAnswerSchema>;
72
+ const { coverage } = answer;
73
+ if (coverage.status === "failed" || coverage.status === "unavailable") {
74
+ throw new Error(`the session could not be read (${coverage.status}): ${coverage.reason}`);
75
+ }
76
+ if (answer.digest === undefined) {
77
+ // A full read: every record, in the harness's own order, with nothing to go on from.
78
+ return {
79
+ mode: "full",
80
+ entries: [],
81
+ records: answer.records as SessionRecord[],
82
+ next: null,
83
+ upto: answer.records.length === 0 ? null : answer.records[answer.records.length - 1]!.locator,
84
+ files: { files: [] },
85
+ omitted: 0,
86
+ hasEarlier: answer.page?.hasEarlier ?? false,
87
+ restarted: answer.records.some((record) => record.reanchored === true),
88
+ };
89
+ }
90
+ const { digest } = answer;
91
+ return {
92
+ mode: digest.view.mode,
93
+ entries: digest.view.mode === "digest" ? (digest.view.entries as DigestEntry[]) : [],
94
+ ...(digest.view.mode === "brief" ? { brief: digest.view.brief as Brief } : {}),
95
+ records: [],
96
+ next: digest.next,
97
+ upto: digest.upto,
98
+ files: digest.files as FileIndex,
99
+ omitted: digest.omitted,
100
+ hasEarlier: false,
101
+ restarted: digest.restarted,
102
+ };
103
+ }
104
+
105
+ /** How a watched session ended, with the position of the record that says so; or that it did not end in time. */
106
+ export type SessionEnd =
107
+ | { readonly ended: true; readonly certainty: "exact" | "guessed"; readonly why?: EndSignal; readonly at: number }
108
+ | { readonly ended: false };
109
+
110
+ /**
111
+ * Waits, as the step `label`, for the end of a session a watch follows (`history.watch`): written
112
+ * after `from`, or after the wait began. `exact` when niwa or the harness said so, `guessed` when
113
+ * only a sign points to it. Without a `timeout` it waits for ever; with one it answers
114
+ * `{ ended: false }` when the time runs out.
115
+ */
116
+ export async function untilSessionEnded(label: string, opts: { session: SessionId; from?: number; timeout?: Duration }): Promise<SessionEnd> {
117
+ const waited = await scriptWait()(sessionEnded(opts.session), {
118
+ ...(opts.from === undefined ? {} : { from: opts.from }),
119
+ ...(opts.timeout === undefined ? {} : { timeout: opts.timeout }),
120
+ label,
121
+ });
122
+ if ("timedOut" in waited) return { ended: false };
123
+ const { certainty, why } = waited.data;
124
+ return { ended: true, certainty, ...(why === undefined ? {} : { why }), at: waited.at };
125
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ // The history entry: reading the transcript of a session through its harness's reading side — read, search and coverage.
2
+ // The schemas of what these are given and answer with are in `@niwa-labs/history/records`.
3
+
4
+ export { describeCoverage, isEmpty } from "./coverage.ts";
5
+ export { matchText, recordText, searchRecords, searchTranscript } from "./search.ts";
6
+ export { listSessions, readTranscript, searchSession } from "./read.ts";
7
+ export type { ReadAnswer, ReadQuery, ReadingBinding } from "./read.ts";
8
+ export type { SearchMatch, SearchQuery, SessionListing } from "./records.ts";
9
+ export { history } from "./plugin.ts";
10
+ export type { HistoryOptions } from "./plugin.ts";
11
+ export { DEFAULT_WATCH_TIMING, SYSTEM_CLOCK, watchSession } from "./watch.ts";
12
+ export type { Progress, WatchClock, WatchEvent, WatchOptions, WatchTiming } from "./watch.ts";
package/src/plugin.ts ADDED
@@ -0,0 +1,426 @@
1
+ /**
2
+ * The history plugin: `history.list` of the sessions, `history.read` and `history.search` of a
3
+ * transcript, and `history.watch` and `history.unwatch` over the reading sides of the
4
+ * installations it is given. A watch writes what it learns as records (records.ts) and goes on after
5
+ * a restart from where the last pause left it; the transcript itself is never written.
6
+ *
7
+ * A session niwa starts is watched by itself, from its `session.started`: its progress is written like
8
+ * any other's, a long quiet is a pause and never a guessed end, and its `session.ended` is the exact
9
+ * end. The plugin reads those records by their names, so it imports nothing of the sessions module.
10
+ */
11
+
12
+ import { action, recordTypeName, seq } from "@niwa-labs/core";
13
+ import type { JournalReader, Seq, StoredRecord } from "@niwa-labs/core";
14
+ import { plugin } from "@niwa-labs/plugin";
15
+ import type { Plugin, PluginApi, Subscriber } from "@niwa-labs/plugin";
16
+ import { HarnessInstanceRegistry, harnessId, requireAbility, sessionId } from "@niwa-labs/harness";
17
+ import type { Locator, SessionId } from "@niwa-labs/harness";
18
+
19
+ import { listSessions, readTranscript, searchSession } from "./read.ts";
20
+ import type { ReadingBinding } from "./read.ts";
21
+ import {
22
+ GUESSED_SIGNALS,
23
+ HISTORY_TYPES,
24
+ HistorySessionEnded,
25
+ HistorySessionPaused,
26
+ HistorySessionSeen,
27
+ HistorySessionUnwatched,
28
+ SessionProgress,
29
+ historyList,
30
+ historyRead,
31
+ historySearch,
32
+ historySignal,
33
+ historyUnwatch,
34
+ historyWatch,
35
+ } from "./records.ts";
36
+ import type { EndSignal } from "./records.ts";
37
+ import { DEFAULT_WATCH_TIMING, SYSTEM_CLOCK, watchSession } from "./watch.ts";
38
+ import type { Progress, WatchClock, WatchTiming } from "./watch.ts";
39
+
40
+ export interface HistoryOptions {
41
+ /**
42
+ * The installations whose sessions can be read and watched, each with its own reading side: the
43
+ * bindings, or the registry they are kept in. Each installation is read in its own home.
44
+ */
45
+ readonly harnesses: readonly ReadingBinding[] | HarnessInstanceRegistry;
46
+ readonly timing?: WatchTiming;
47
+ readonly clock?: WatchClock;
48
+ }
49
+
50
+ function bindingsOf(options: HistoryOptions): ReadingBinding[] {
51
+ const { harnesses } = options;
52
+ return harnesses instanceof HarnessInstanceRegistry ? harnesses.bindings() : [...harnesses];
53
+ }
54
+
55
+ const keyOf = (id: SessionId): string => `${id.harness}\u0000${id.native}`;
56
+
57
+ /** The names of the records of the sessions module this plugin reads: a session niwa started, and its end. */
58
+ const SESSION_STARTED = recordTypeName("session.started");
59
+ const SESSION_ENDED = recordTypeName("session.ended");
60
+ /** The record the insert inside a harness writes when the harness says a session ended. */
61
+ const INSERT_SESSION_ENDED = recordTypeName("insert.session-ended");
62
+
63
+ /** A session as the sessions module names it, `<harness> <native>`, as a reading side names it. */
64
+ function sessionOfRef(ref: unknown): SessionId | undefined {
65
+ if (typeof ref !== "string") return undefined;
66
+ const space = ref.indexOf(" ");
67
+ if (space <= 0 || space === ref.length - 1) return undefined;
68
+ return sessionId(harnessId(ref.slice(0, space)), ref.slice(space + 1));
69
+ }
70
+
71
+ /** The session a record of the insert names, `{ harness, native }`. */
72
+ function sessionOfPair(value: unknown): SessionId | undefined {
73
+ if (value === null || typeof value !== "object") return undefined;
74
+ const { harness, native } = value as { harness?: unknown; native?: unknown };
75
+ return typeof harness === "string" && typeof native === "string" && harness !== "" && native !== "" ? sessionId(harnessId(harness), native) : undefined;
76
+ }
77
+
78
+ /** Did niwa start this session? Its own `session.started` says so. */
79
+ function ownedBy(journal: JournalReader | undefined, id: SessionId): boolean {
80
+ return (journal?.find({ type: SESSION_STARTED, field: "session", equals: `${id.harness} ${id.native}` }).length ?? 0) > 0;
81
+ }
82
+
83
+ /**
84
+ * Where a watch of a session stands in the journal: watched or not, its process, and where it got to.
85
+ * The position, the progress and whether a pause was said all come from the last record of a pause
86
+ * or of progress, which is where the watch left off.
87
+ */
88
+ interface Standing {
89
+ watching: boolean;
90
+ from?: Locator;
91
+ progress?: Progress;
92
+ paused: boolean;
93
+ pid?: number;
94
+ }
95
+
96
+ type Standings = Map<string, Standing & { session: SessionId }>;
97
+
98
+ /** Fold records, in the order the journal holds them, into where each watch stands. */
99
+ function foldStanding(standing: Standings, records: readonly StoredRecord[]): void {
100
+ for (const stored of records) {
101
+ const session = (stored.data as { session?: SessionId }).session;
102
+ if (session === undefined) continue;
103
+ const key = keyOf(session);
104
+ const now = standing.get(key) ?? { session, watching: false, paused: false };
105
+ if (stored.type === HistorySessionSeen.name) {
106
+ now.watching = true;
107
+ const { pid } = HistorySessionSeen.schema.parse(stored.data);
108
+ if (pid === undefined) delete now.pid;
109
+ else now.pid = pid;
110
+ } else if (stored.type === HistorySessionEnded.name || stored.type === HistorySessionUnwatched.name) now.watching = false;
111
+ else if (stored.type === HistorySessionPaused.name) {
112
+ now.from = HistorySessionPaused.schema.parse(stored.data).upto;
113
+ now.paused = true;
114
+ } else if (stored.type === SessionProgress.name) {
115
+ const { done, total, at } = SessionProgress.schema.parse(stored.data);
116
+ now.progress = { done, total };
117
+ // Progress is written when the session grew: it is the later position, and the pause before it is over.
118
+ if (at !== undefined) now.from = at;
119
+ now.paused = false;
120
+ }
121
+ standing.set(key, now);
122
+ }
123
+ }
124
+
125
+ /** Does a process live? A process that exists but is not ours to signal lives too. */
126
+ function lives(pid: number): boolean {
127
+ try {
128
+ process.kill(pid, 0);
129
+ return true;
130
+ } catch (error) {
131
+ return (error as { code?: unknown }).code === "EPERM";
132
+ }
133
+ }
134
+
135
+ export function history(options: HistoryOptions): Plugin {
136
+ return plugin("history", (api: PluginApi) => {
137
+ api.declare(...HISTORY_TYPES);
138
+ const bindings = bindingsOf(options);
139
+ /** The watches that are on: the signal that stops one, and the task that settles when it has stopped writing. */
140
+ const watches = new Map<string, { readonly controller: AbortController; finished: Promise<void> }>();
141
+ const clock = options.clock ?? SYSTEM_CLOCK;
142
+ const timing = options.timing ?? DEFAULT_WATCH_TIMING;
143
+
144
+ /**
145
+ * Where each watch stands, from the journal: all of it is read the first time, and afterwards only
146
+ * the records written since, so the cost does not grow with the history of the host.
147
+ */
148
+ let known: { journal: JournalReader; upto: Seq; standing: Standings } | undefined;
149
+ const standingNow = (): Standings => {
150
+ const journal = api.journal?.();
151
+ if (journal === undefined) return new Map();
152
+ if (known?.journal !== journal) known = { journal, upto: seq(0), standing: new Map() };
153
+ const written = journal.since(known.upto, HISTORY_TYPES.map((type) => type.name));
154
+ foldStanding(known.standing, written);
155
+ const last = written[written.length - 1];
156
+ if (last !== undefined) known.upto = last.seq;
157
+ return known.standing;
158
+ };
159
+
160
+ const readingOf = (id: SessionId) => {
161
+ const binding = bindings.find((candidate) => candidate.instance.id === id.harness);
162
+ if (binding === undefined || binding.reading === undefined) {
163
+ throw new Error(`harness "${id.harness}" has no reading side to watch a session with`);
164
+ }
165
+ requireAbility(binding.instance, "reading", "read");
166
+ return binding.reading;
167
+ };
168
+
169
+ /** The starts of watches in progress, by session: a start is reserved before its first await. */
170
+ const starting = new Map<string, Promise<void>>();
171
+
172
+ /**
173
+ * Start watching a session with `start`, unless it is watched or a start is already under way, in
174
+ * which case the caller shares that start. The reservation is released when the start is done or fails.
175
+ */
176
+ const begin = async (id: SessionId, start: () => Promise<void>): Promise<void> => {
177
+ const key = keyOf(id);
178
+ const under = starting.get(key);
179
+ if (under !== undefined) return await under;
180
+ const running = watches.get(key);
181
+ if (running !== undefined && !running.controller.signal.aborted) return;
182
+ // A watch that is stopping finishes what it was writing before the next one starts.
183
+ const task = running === undefined ? start() : running.finished.then(start);
184
+ starting.set(key, task);
185
+ try {
186
+ await task;
187
+ } finally {
188
+ starting.delete(key);
189
+ }
190
+ };
191
+
192
+ /** Stop following a session, when it is followed, and wait until the watch has stopped writing. */
193
+ const stop = async (id: SessionId): Promise<void> => {
194
+ const watch = watches.get(keyOf(id));
195
+ if (watch === undefined) return;
196
+ watch.controller.abort();
197
+ await watch.finished;
198
+ };
199
+
200
+ /**
201
+ * End the watch of a session with the record `write` makes. The watch is stopped first and what it
202
+ * was writing lands before the end, never after it; when the watch itself wrote the end meanwhile,
203
+ * nothing more is written. False when the session is not watched.
204
+ */
205
+ const finish = async (id: SessionId, write: () => Promise<unknown>): Promise<boolean> => {
206
+ if (standingNow().get(keyOf(id))?.watching !== true) return false;
207
+ await stop(id);
208
+ if (standingNow().get(keyOf(id))?.watching !== true) return false;
209
+ await write();
210
+ return true;
211
+ };
212
+
213
+ /**
214
+ * Write a record the watch learned. A write that fails while the host runs is tried again, so a
215
+ * watch does not end with the journal still saying it is on; a stop ends the trying.
216
+ */
217
+ const publish = async (signal: AbortSignal, write: () => Promise<unknown>): Promise<boolean> => {
218
+ while (!signal.aborted) {
219
+ try {
220
+ await write();
221
+ return true;
222
+ } catch {
223
+ await clock.sleep(timing.pollMs, signal);
224
+ }
225
+ }
226
+ return false;
227
+ };
228
+
229
+ /** Follow a session; what it learns is written as records until it ends or the watch stops. */
230
+ const follow = (id: SessionId, standing: Partial<Omit<Standing, "watching">>): void => {
231
+ const key = keyOf(id);
232
+ if (watches.has(key)) return;
233
+ const reading = readingOf(id);
234
+ const controller = new AbortController();
235
+ const watch = { controller, finished: Promise.resolve() };
236
+ watches.set(key, watch);
237
+ const owned = ownedBy(api.journal?.(), id);
238
+ watch.finished = (async () => {
239
+ try {
240
+ const events = watchSession(reading, id, {
241
+ signal: controller.signal,
242
+ timing,
243
+ clock,
244
+ ...(standing.from === undefined ? {} : { from: standing.from }),
245
+ ...(standing.progress === undefined ? {} : { progress: standing.progress }),
246
+ ...(standing.paused ? { paused: true } : {}),
247
+ // A session niwa runs ends when niwa says so: its quiet is a wait for the next turn.
248
+ ...(owned ? { guessEnd: false } : {}),
249
+ ...(standing.pid === undefined ? {} : { alive: () => lives(standing.pid!) }),
250
+ });
251
+ for await (const event of events) {
252
+ let written: boolean;
253
+ switch (event.kind) {
254
+ case "progress":
255
+ written = await publish(controller.signal, () => api.emit(SessionProgress, { session: id, done: event.done, total: event.total, at: event.at }));
256
+ break;
257
+ case "paused":
258
+ written = await publish(controller.signal, () => api.emit(HistorySessionPaused, { session: id, upto: event.upto, why: event.why }));
259
+ break;
260
+ case "ended":
261
+ written = await publish(controller.signal, () => api.emit(HistorySessionEnded, { session: id, certainty: event.certainty, why: event.why }));
262
+ break;
263
+ }
264
+ if (!written) break;
265
+ }
266
+ } catch {
267
+ // A watch that cannot go on is dropped; the journal still says it is on, so the next start resumes it.
268
+ } finally {
269
+ if (watches.get(key) === watch) watches.delete(key);
270
+ }
271
+ })();
272
+ };
273
+
274
+ /** The certainty a signal of the end gives. */
275
+ const certaintyOf = (signal: EndSignal) => (GUESSED_SIGNALS.includes(signal) ? "guessed" : "exact");
276
+
277
+ api.action(
278
+ action(historyWatch, {
279
+ // A watch that is already on is left as it is: it may be asked for again.
280
+ recovery: "repeat",
281
+ effect: "record",
282
+ world: "niwa",
283
+ run: async (input, ctx) => {
284
+ const id = input.session;
285
+ await begin(id, async () => {
286
+ const reading = readingOf(id);
287
+ let cwd: string | undefined;
288
+ for await (const info of reading.list({ natives: [id.native] })) cwd = info.cwd ?? cwd;
289
+ // A session watched before goes on from where that watch left it, saying no progress twice.
290
+ const before = { ...standingNow().get(keyOf(id)) };
291
+ await ctx.emit(HistorySessionSeen, {
292
+ session: id,
293
+ harness: id.harness,
294
+ ...(cwd === undefined ? {} : { cwd }),
295
+ ...(input.pid === undefined ? {} : { pid: input.pid }),
296
+ });
297
+ // Only where the earlier watch got to is carried over: the process is the one this call names, if any.
298
+ follow(id, {
299
+ ...(before.from === undefined ? {} : { from: before.from }),
300
+ ...(before.progress === undefined ? {} : { progress: before.progress }),
301
+ paused: before.paused === true,
302
+ ...(input.pid === undefined ? {} : { pid: input.pid }),
303
+ });
304
+ });
305
+ return { watching: true };
306
+ },
307
+ }),
308
+ );
309
+
310
+ api.action(
311
+ action(historyRead, {
312
+ // A read changes nothing: it may be made again.
313
+ recovery: "repeat",
314
+ effect: "read",
315
+ world: "local",
316
+ run: async (input) => await readTranscript(bindings.find((candidate) => candidate.instance.id === input.session.harness), input.session, input),
317
+ }),
318
+ );
319
+
320
+ api.action(
321
+ action(historyList, {
322
+ // A listing changes nothing: it may be made again.
323
+ recovery: "repeat",
324
+ effect: "read",
325
+ world: "local",
326
+ run: async (input) => await listSessions(bindings, input),
327
+ }),
328
+ );
329
+
330
+ api.action(
331
+ action(historySearch, {
332
+ recovery: "repeat",
333
+ effect: "read",
334
+ world: "local",
335
+ run: async (input) =>
336
+ await searchSession(
337
+ bindings.find((candidate) => candidate.instance.id === input.session.harness),
338
+ input.session,
339
+ input,
340
+ ),
341
+ }),
342
+ );
343
+
344
+ api.action(
345
+ action(historyUnwatch, {
346
+ recovery: "repeat",
347
+ effect: "record",
348
+ world: "niwa",
349
+ run: async (input, ctx) => {
350
+ // The journal says whether a watch is on: one whose task has gone is still stopped by writing so.
351
+ const stopped = await finish(input.session, () => ctx.emit(HistorySessionUnwatched, { session: input.session }));
352
+ return { stopped };
353
+ },
354
+ }),
355
+ );
356
+
357
+ api.action(
358
+ action(historySignal, {
359
+ // An end already written is not written again: the signal may be given again.
360
+ recovery: "repeat",
361
+ effect: "record",
362
+ world: "niwa",
363
+ run: async (input, ctx) => {
364
+ // A session niwa runs ends when niwa says so: a sign that only suggests an end does not end it.
365
+ if (GUESSED_SIGNALS.includes(input.signal) && ownedBy(api.journal?.(), input.session)) return { ended: false };
366
+ const ended = await finish(input.session, () =>
367
+ ctx.emit(HistorySessionEnded, { session: input.session, certainty: certaintyOf(input.signal), why: input.signal }),
368
+ );
369
+ return { ended };
370
+ },
371
+ }),
372
+ );
373
+
374
+ // The sessions niwa starts, and the ends niwa and the inserts say: read by their names, from the
375
+ // moment the plugin first serves, so the sessions of an older journal are not watched again.
376
+ let firstServed: number | undefined;
377
+ api.subscribers(() => {
378
+ const journal = api.journal?.();
379
+ if (journal === undefined) return [];
380
+ firstServed ??= journal.last();
381
+ // One subscription, so a session's start is always taken before its end.
382
+ const sessions: Subscriber = {
383
+ id: "niwa-sessions",
384
+ queries: [{ types: [SESSION_STARTED, SESSION_ENDED, INSERT_SESSION_ENDED] }],
385
+ from: firstServed,
386
+ handler: async (data, step, stored) => {
387
+ const { session, cwd } = data as { session?: unknown; cwd?: unknown };
388
+ if (stored.type === SESSION_STARTED) {
389
+ const id = sessionOfRef(session);
390
+ if (id === undefined) return;
391
+ // A session of an installation with no reading side has no transcript to follow.
392
+ if (bindings.find((candidate) => candidate.instance.id === id.harness)?.reading === undefined) return;
393
+ await begin(id, async () => {
394
+ await step.emit(HistorySessionSeen, { session: id, harness: id.harness, ...(typeof cwd === "string" ? { cwd } : {}) });
395
+ follow(id, {});
396
+ });
397
+ return;
398
+ }
399
+ const id = stored.type === SESSION_ENDED ? sessionOfRef(session) : sessionOfPair(session);
400
+ if (id === undefined) return;
401
+ const why: EndSignal = stored.type === SESSION_ENDED ? "session-ended" : "end-hook";
402
+ await finish(id, () => step.emit(HistorySessionEnded, { session: id, certainty: certaintyOf(why), why }));
403
+ },
404
+ };
405
+ return [sessions];
406
+ });
407
+
408
+ // The watches the journal says are on go on from their last pause; all stop with the host.
409
+ api.service(() => {
410
+ if (api.journal?.() !== undefined) {
411
+ for (const [, standing] of standingNow()) {
412
+ if (!standing.watching) continue;
413
+ try {
414
+ follow(standing.session, standing);
415
+ } catch {
416
+ // An installation that is gone has nothing to watch with.
417
+ }
418
+ }
419
+ }
420
+ return () => {
421
+ for (const { controller } of watches.values()) controller.abort();
422
+ watches.clear();
423
+ };
424
+ });
425
+ });
426
+ }