@oisin-ee/pi-dogsled 0.34.2 → 0.36.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.
@@ -0,0 +1,54 @@
1
+ /** A value at one replay revision. */
2
+ interface Version<Value> {
3
+ readonly revision: number;
4
+ readonly value: Value;
5
+ }
6
+
7
+ const first = 0,
8
+ step = 1,
9
+ halves = 2,
10
+ last = -1;
11
+
12
+ /** Retains only changed values, with stable reads of earlier frames. */
13
+ class History<Key, Value> {
14
+ readonly #values = new Map<Key, Version<Value>[]>();
15
+
16
+ /**
17
+ * Records one changed value.
18
+ * @param {Key} key Value identity.
19
+ * @param {number} revision Replay revision.
20
+ * @param {Value} value New value.
21
+ */
22
+ public set(key: Key, revision: number, value: Value): void {
23
+ const versions = this.#values.get(key) ?? [];
24
+ versions.push({ revision, value });
25
+ this.#values.set(key, versions);
26
+ }
27
+
28
+ /**
29
+ * Finds the value at or before one revision.
30
+ * @param {Key} key Value identity.
31
+ * @param {number} revision Replay revision.
32
+ * @returns {Value | undefined} Recorded value.
33
+ */
34
+ public get(key: Key, revision: number): Value | undefined {
35
+ const versions = this.#values.get(key) ?? [],
36
+ latest = versions.at(last);
37
+ if (latest !== undefined && latest.revision <= revision) {
38
+ return latest.value;
39
+ }
40
+ let lower = first,
41
+ upper = versions.length;
42
+ while (lower < upper) {
43
+ const middle = Math.floor((lower + upper) / halves);
44
+ if ((versions.at(middle)?.revision ?? Infinity) <= revision) {
45
+ lower = middle + step;
46
+ } else {
47
+ upper = middle;
48
+ }
49
+ }
50
+ return lower === first ? undefined : versions.at(lower - step)?.value;
51
+ }
52
+ }
53
+
54
+ export { History };
@@ -0,0 +1,106 @@
1
+ // Retained a479b93 reader; only local state/reminder import paths differ.
2
+ import type {
3
+ BoundaryResult,
4
+ ExtensionContext,
5
+ ExtensionUIContext,
6
+ SessionBoundaryDraft,
7
+ SessionEntry,
8
+ Theme,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { REMINDER_ENTRY, reminder } from "./old-reminder-fixture.ts";
11
+ import { parse, view, widget } from "./wasm.ts";
12
+ import { TodoWidget } from "./widget.ts";
13
+ import { isOwnSource } from "./source.ts";
14
+ import { latestSnapshot } from "./old-state-fixture.ts";
15
+
16
+ interface TodoContext {
17
+ readonly mode: ExtensionContext["mode"];
18
+ readonly sessionManager: { readonly getBranch: () => readonly SessionEntry[] };
19
+ readonly ui: Readonly<Pick<ExtensionUIContext, "notify" | "setWidget">>;
20
+ }
21
+ interface SettleEvent {
22
+ readonly outcome: "completed" | "aborted" | "error";
23
+ readonly continue: boolean;
24
+ readonly context: { readonly canContinue: boolean };
25
+ readonly entries: readonly SessionBoundaryDraft[];
26
+ }
27
+ interface TodoHost {
28
+ readonly getAllTools: () => readonly {
29
+ readonly name: string;
30
+ readonly sourceInfo: { readonly path: string };
31
+ }[];
32
+ }
33
+
34
+ /**
35
+ * Whether this source owns the todo registration.
36
+ * @param {TodoHost} pi Tool metadata reader.
37
+ * @returns {boolean} Whether this source won.
38
+ */
39
+ const ownsTodo = (pi: TodoHost): boolean =>
40
+ pi.getAllTools().some((tool) => tool.name === "todo" && isOwnSource(tool.sourceInfo.path)),
41
+ /**
42
+ * Renders the selected branch snapshot, and removes the widget when the list is empty.
43
+ * @param {TodoContext} ctx Branch and UI methods.
44
+ * @param {boolean} expanded Whether to reveal secondary task groups.
45
+ */
46
+ replay = (ctx: TodoContext, expanded = false): void => {
47
+ if (ctx.mode !== "tui") {
48
+ return;
49
+ }
50
+ const list = parse(latestSnapshot(ctx.sessionManager.getBranch())),
51
+ rows = widget(list, expanded);
52
+ ctx.ui.setWidget(
53
+ "pi-todo",
54
+ rows === undefined
55
+ ? undefined
56
+ : (_tui: unknown, theme: Readonly<Pick<Theme, "fg" | "bold">>): TodoWidget =>
57
+ new TodoWidget(rows, expanded, theme),
58
+ );
59
+ },
60
+ /**
61
+ * Applies the completion decision at pi's final actionable boundary.
62
+ * @param {TodoHost} pi Tool metadata reader.
63
+ * @param {SettleEvent} event The boundary facts.
64
+ * @param {TodoContext} ctx Branch and UI methods.
65
+ * @returns {BoundaryResult} The unchanged boundary or an added visible reminder.
66
+ */
67
+ settle = (pi: TodoHost, event: SettleEvent, ctx: TodoContext): BoundaryResult => {
68
+ if (event.outcome !== "completed" || event.continue || !ownsTodo(pi)) {
69
+ return {};
70
+ }
71
+ const content = reminder(ctx.sessionManager.getBranch(), event.entries);
72
+ return typeof content === "string"
73
+ ? {
74
+ continue: true,
75
+ entries: [
76
+ ...event.entries,
77
+ { content, customType: REMINDER_ENTRY, display: true, type: "custom_message" },
78
+ ],
79
+ }
80
+ : {};
81
+ },
82
+ /**
83
+ * Prints the branch list for /todos.
84
+ * @param {TodoContext} ctx Branch and UI methods.
85
+ */
86
+ show = (ctx: TodoContext): void => {
87
+ const list = parse(latestSnapshot(ctx.sessionManager.getBranch()));
88
+ ctx.ui.notify(view(list), "info");
89
+ },
90
+ /**
91
+ * Replays or reports the winning source at startup.
92
+ * @param {TodoHost} pi Tool metadata reader.
93
+ * @param {TodoContext} ctx Branch and UI methods.
94
+ */
95
+ start = (pi: TodoHost, ctx: TodoContext): void => {
96
+ if (ownsTodo(pi)) {
97
+ replay(ctx);
98
+ } else {
99
+ const owner = pi.getAllTools().find((tool) => tool.name === "todo"),
100
+ source = owner ? owner.sourceInfo.path : "another source";
101
+ ctx.ui.notify(`pi-todo is inactive: todo belongs to ${source}.`, "warning");
102
+ }
103
+ };
104
+
105
+ export { ownsTodo, replay, settle, show, start };
106
+ export type { SettleEvent, TodoContext, TodoHost };
@@ -0,0 +1,290 @@
1
+ // Retained a479b93 reader; only local state/tool import paths differ.
2
+ import type {
3
+ ActiveUnit,
4
+ ClaimResult,
5
+ ImportReceipt,
6
+ SettlementResult,
7
+ TodoList,
8
+ UnitContract,
9
+ UnitRef,
10
+ } from "./wasm.ts";
11
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import { STATE_ENTRY, branchSnapshot } from "./old-state-fixture.ts";
13
+ import type { TodoParams, TodoResult, TodoSession } from "./old-tool-fixture.ts";
14
+ import { active, claim, importUnit, imported, inspect, parse, protect, settle } from "./wasm.ts";
15
+ import { ownsTodo } from "./lifecycle.ts";
16
+ import { repositoryIdentity } from "./repository.ts";
17
+ import { runTodo } from "./old-tool-fixture.ts";
18
+
19
+ /** Stable extension-only result envelope. */
20
+ type Result<Value> =
21
+ | { readonly ok: true; readonly value: Value }
22
+ | { readonly ok: false; readonly error: { readonly code: string; readonly message: string } };
23
+ /** Wire acknowledgements use explicit null for an unsealed import. */
24
+ type ImportAcknowledgement = Omit<ImportReceipt, "seal"> & {
25
+ readonly seal: ImportReceipt["seal"] | null;
26
+ };
27
+ /** Capability acquisition does not expose a model-facing tool. */
28
+ interface TaskProviderV1 {
29
+ readonly inspect: (id: string) => Result<UnitContract>;
30
+ readonly claim: (input: unknown) => Result<ClaimResult>;
31
+ readonly settle: (input: unknown) => Result<SettlementResult>;
32
+ readonly active: () => Result<ActiveUnit | null>;
33
+ readonly imported: () => Result<ImportAcknowledgement | null>;
34
+ }
35
+ interface ProviderHost {
36
+ readonly appendEntry: ExtensionAPI["appendEntry"];
37
+ readonly getAllTools: ExtensionAPI["getAllTools"];
38
+ readonly events: Readonly<ExtensionAPI["events"]>;
39
+ }
40
+ interface Acquisition {
41
+ readonly version: number;
42
+ readonly reply: (provider: TaskProviderV1) => void;
43
+ }
44
+
45
+ const version = 1,
46
+ /**
47
+ * Validates an extension capability acquisition.
48
+ * @param {unknown} request Untrusted event payload.
49
+ * @returns {boolean} Whether a versioned callback is present.
50
+ */
51
+ acquisition = (request: unknown): request is Acquisition =>
52
+ typeof request === "object" &&
53
+ request !== null &&
54
+ "version" in request &&
55
+ request.version === version &&
56
+ "reply" in request &&
57
+ typeof request.reply === "function" &&
58
+ Object.keys(request).every((key) => key === "version" || key === "reply"),
59
+ /**
60
+ * Runs synchronous policy through the capability envelope.
61
+ * @param {Function} operation Core operation.
62
+ * @returns {Result} Output or explicit failure.
63
+ */
64
+ result = <Value>(operation: () => Value): Result<Value> => {
65
+ try {
66
+ return { ok: true, value: operation() };
67
+ } catch (error: unknown) {
68
+ const message = error instanceof Error ? error.message : String(error),
69
+ [code] = message.split(":");
70
+ return { error: { code: code ?? "CONTRACT_INCOMPLETE", message }, ok: false };
71
+ }
72
+ };
73
+
74
+ /** One serialization boundary for todo operations and extension mutations. */
75
+ class TaskProvider {
76
+ readonly #host: ProviderHost;
77
+ readonly #leases = new Map<string, UnitRef>();
78
+ #context: ExtensionContext | undefined;
79
+ #mutating = false;
80
+ #generation = Symbol("task-provider");
81
+
82
+ public constructor(host: ProviderHost) {
83
+ this.#host = host;
84
+ }
85
+
86
+ /** Registers a versioned synchronous capability only for the winning todo owner. */
87
+ public register(): void {
88
+ this.#host.events.on("oisin.tasks.acquire.v1", (request: unknown): void => {
89
+ if (!ownsTodo(this.#host) || !acquisition(request)) {
90
+ return;
91
+ }
92
+ request.reply(this.capability());
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Refreshes the context at the actual call boundary.
98
+ * @param {ExtensionContext} ctx Current runtime context.
99
+ */
100
+ public context(ctx: ExtensionContext): void {
101
+ this.#context = ctx;
102
+ }
103
+
104
+ /** Removes runtime-only leases on extension shutdown. */
105
+ public stop(): void {
106
+ this.#generation = Symbol("task-provider");
107
+ this.#leases.clear();
108
+ this.#context = undefined;
109
+ }
110
+
111
+ /**
112
+ * Holds a revision until this invocation ends.
113
+ * @param {string} id Runtime invocation ID.
114
+ * @param {Readonly<UnitRef>} reference Executing revision.
115
+ */
116
+ public lease(id: string, reference: Readonly<UnitRef>): void {
117
+ this.#leases.set(id, structuredClone(reference));
118
+ }
119
+
120
+ /**
121
+ * Releases only the matching invocation.
122
+ * @param {string} id Ended invocation ID.
123
+ */
124
+ public release(id: string): void {
125
+ this.#leases.delete(id);
126
+ }
127
+
128
+ /**
129
+ * Serializes normal todo operations with extension mutations.
130
+ * @param {TodoParams} params Model-authored request.
131
+ * @param {ExtensionContext} ctx Current context.
132
+ * @returns {TodoResult} Persisted result.
133
+ */
134
+ public run(params: TodoParams, ctx: ExtensionContext): TodoResult {
135
+ this.context(ctx);
136
+ return this.#mutation(() => runTodo(params, this.#session()));
137
+ }
138
+
139
+ /**
140
+ * Imports startup transport through the same atomic mutation boundary.
141
+ * @param {string} source Untrusted seed JSON.
142
+ * @param {string} origin Checkout origin URL.
143
+ * @param {ExtensionContext} ctx Current runtime authority.
144
+ */
145
+ public import(source: string, origin: string, ctx: ExtensionContext): void {
146
+ this.context(ctx);
147
+ this.#mutation(() => {
148
+ const session = this.#session(),
149
+ change = importUnit(
150
+ branchSnapshot(session.branch()),
151
+ source,
152
+ session.sessionId,
153
+ repositoryIdentity(origin),
154
+ );
155
+ if (change.persist) {
156
+ session.append(STATE_ENTRY, change.list);
157
+ }
158
+ });
159
+ }
160
+
161
+ /**
162
+ * Creates methods that recheck ownership and branch state.
163
+ * @returns {TaskProviderV1} Extension-only capability.
164
+ */
165
+ public capability(): TaskProviderV1 {
166
+ const generation = this.#generation,
167
+ respond = <Value>(operation: () => Value): Result<Value> =>
168
+ this.#respond(generation, operation);
169
+ return {
170
+ active: () =>
171
+ respond(() => {
172
+ const session = this.#session();
173
+ return active(branchSnapshot(session.branch()), session.sessionId) ?? null;
174
+ }),
175
+ claim: (input) =>
176
+ respond(() =>
177
+ this.#mutation(() => {
178
+ const session = this.#session(),
179
+ change = claim(
180
+ branchSnapshot(session.branch()),
181
+ JSON.stringify(input),
182
+ session.sessionId,
183
+ );
184
+ if (change.persist) {
185
+ session.append(STATE_ENTRY, change.list);
186
+ }
187
+ return change.value;
188
+ }),
189
+ ),
190
+ imported: () => respond(() => this.#imported()),
191
+ inspect: (id) => respond(() => inspect(branchSnapshot(this.#session().branch()), id)),
192
+ settle: (input) =>
193
+ respond(() =>
194
+ this.#mutation(() => {
195
+ const session = this.#session(),
196
+ change = settle(
197
+ branchSnapshot(session.branch()),
198
+ JSON.stringify(input),
199
+ session.sessionId,
200
+ );
201
+ if (change.persist) {
202
+ session.append(STATE_ENTRY, change.list);
203
+ }
204
+ return change.value;
205
+ }),
206
+ ),
207
+ };
208
+ }
209
+
210
+ #imported(): ImportAcknowledgement | null {
211
+ const session = this.#session(),
212
+ receipt = imported(branchSnapshot(session.branch()), session.sessionId);
213
+ return receipt === undefined
214
+ ? null
215
+ : Object.assign({}, receipt, { seal: receipt.seal ?? null });
216
+ }
217
+
218
+ #respond<Value>(generation: symbol, operation: () => Value): Result<Value> {
219
+ return result(() => {
220
+ if (generation !== this.#generation) {
221
+ throw new Error("PROVIDER_UNAVAILABLE: capability belongs to a closed runtime");
222
+ }
223
+ return operation();
224
+ });
225
+ }
226
+
227
+ #mutation<Value>(operation: () => Value): Value {
228
+ if (this.#mutating) {
229
+ throw new Error("UNIT_ALREADY_BOUND: a task mutation is already in progress");
230
+ }
231
+ this.#mutating = true;
232
+ try {
233
+ return operation();
234
+ } finally {
235
+ this.#mutating = false;
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Rejects branch rewind around an immutable seed or seal.
241
+ * @param {ExtensionContext} ctx Runtime session.
242
+ * @param {TodoList} branch Current branch snapshot.
243
+ */
244
+ static #importScope(ctx: ExtensionContext, branch: TodoList): void {
245
+ const sessionId = ctx.sessionManager.getSessionId(),
246
+ receipt = imported(branch, sessionId);
247
+ for (const entry of ctx.sessionManager.getEntries()) {
248
+ if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
249
+ const recorded = imported(parse(entry.data), sessionId);
250
+ if (
251
+ recorded !== undefined &&
252
+ (receipt === undefined ||
253
+ JSON.stringify(recorded.execution) !== JSON.stringify(receipt.execution) ||
254
+ recorded.digest !== receipt.digest ||
255
+ (recorded.seal !== undefined && receipt.seal === undefined))
256
+ ) {
257
+ throw new Error("SEEDED_SCOPE_LOCKED: branch cannot discard imported scope or its seal");
258
+ }
259
+ }
260
+ }
261
+ }
262
+
263
+ #session(): TodoSession {
264
+ const ctx = this.#context;
265
+ if (ctx === undefined || !ownsTodo(this.#host)) {
266
+ throw new Error("PROVIDER_UNAVAILABLE: pi-todo does not own an active session");
267
+ }
268
+ const sessionId = ctx.sessionManager.getSessionId(),
269
+ leaf = ctx.sessionManager.getLeafId(),
270
+ before = branchSnapshot(ctx.sessionManager.getBranch());
271
+ TaskProvider.#importScope(ctx, before);
272
+ return {
273
+ append: (customType: string, list: TodoList): void => {
274
+ if (
275
+ ctx.sessionManager.getSessionId() !== sessionId ||
276
+ ctx.sessionManager.getLeafId() !== leaf
277
+ ) {
278
+ throw new Error("STALE_ORIGIN: session branch changed during task mutation");
279
+ }
280
+ protect(before, list, [...this.#leases.values()]);
281
+ this.#host.appendEntry(customType, list);
282
+ },
283
+ branch: () => ctx.sessionManager.getBranch(),
284
+ sessionId,
285
+ };
286
+ }
287
+ }
288
+
289
+ export { TaskProvider };
290
+ export type { Result, TaskProviderV1 };
@@ -0,0 +1,31 @@
1
+ // Retained a479b93 reader; only local state/tool import paths differ.
2
+ import type { SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import { completionReminder, parse } from "./wasm.ts";
4
+ import type { ReminderFact } from "./wasm.ts";
5
+ import { STATE_ENTRY } from "./old-state-fixture.ts";
6
+
7
+ const REMINDER_ENTRY = "todo-reminder",
8
+ /**
9
+ * Projects pi's branch and boundary drafts into core-owned reminder facts.
10
+ * @param {readonly SessionEntry[]} branch Persisted branch entries.
11
+ * @param {readonly SessionBoundaryDraft[]} drafts Proposed boundary entries.
12
+ * @returns {string | undefined} The next reminder, when permitted.
13
+ */
14
+ reminder = (
15
+ branch: readonly SessionEntry[],
16
+ drafts: readonly SessionBoundaryDraft[],
17
+ ): string | undefined => {
18
+ const facts: ReminderFact[] = [];
19
+ for (const entry of [...branch, ...drafts]) {
20
+ if (entry.type === "message" && entry.message.role === "user") {
21
+ facts.push({ kind: "user" });
22
+ } else if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
23
+ facts.push({ kind: "snapshot", list: parse(entry.data) });
24
+ } else if (entry.type === "custom_message" && entry.customType === REMINDER_ENTRY) {
25
+ facts.push({ kind: "reminder" });
26
+ }
27
+ }
28
+ return completionReminder({ facts });
29
+ };
30
+
31
+ export { REMINDER_ENTRY, reminder };
@@ -0,0 +1,106 @@
1
+ // Retained a479b93 reader; only local state/tool import paths differ.
2
+ import type { CustomEntry, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { ExecutionRef, TodoList, UnitRef } from "./wasm.ts";
4
+ import { parse } from "./wasm.ts";
5
+
6
+ /** The snapshot of a branch with no list yet. */
7
+ const EMPTY: unknown = { tasks: [] },
8
+ /** The custom entry that holds the list after every change. */
9
+ STATE_ENTRY = "todo-state",
10
+ /**
11
+ * Whether `entry` is a stored list.
12
+ * @param {SessionEntry} entry A branch entry.
13
+ * @returns {boolean} True for a `todo-state` custom entry.
14
+ */
15
+ isStateEntry = (entry: SessionEntry): entry is CustomEntry =>
16
+ entry.type === "custom" && entry.customType === STATE_ENTRY,
17
+ /**
18
+ * The latest stored snapshot on the branch, unvalidated: the core validates it.
19
+ * @param {readonly SessionEntry[]} branch The session branch, oldest entry first.
20
+ * @returns {unknown} The latest snapshot, or an empty list when there is none.
21
+ */
22
+ latestSnapshot = (branch: readonly SessionEntry[]): unknown => {
23
+ for (const entry of branch.toReversed()) {
24
+ if (isStateEntry(entry)) {
25
+ return entry.data;
26
+ }
27
+ }
28
+ return EMPTY;
29
+ },
30
+ /**
31
+ * Resolves the first branch entry for a contract revision.
32
+ * @param {Readonly<UnitRef>} reference Revision identity.
33
+ * @param {string} entryId Containing Pi entry.
34
+ * @param {Readonly<Map<string, string>>} origins Prior branch origins.
35
+ * @returns {string} The revision's originating entry.
36
+ */
37
+ originFor = (
38
+ reference: Readonly<UnitRef>,
39
+ entryId: string,
40
+ origins: Readonly<Map<string, string>>,
41
+ ): string => {
42
+ const key = JSON.stringify([reference.sessionId, reference.unitId, reference.revision]),
43
+ origin = origins.get(key) ?? entryId;
44
+ origins.set(key, origin);
45
+ return origin;
46
+ };
47
+
48
+ /** Derives entry provenance without rewriting the imported lead reference. */
49
+ class Provenance {
50
+ readonly #origins = new Map<string, string>();
51
+ readonly #seals = new Map<string, string>();
52
+
53
+ /**
54
+ * Resolves contract and seal provenance for one task snapshot.
55
+ * @param {Readonly<object>} unit Task provenance fields.
56
+ * @param {string} entryId Snapshot identity.
57
+ */
58
+ public resolve(
59
+ unit: {
60
+ readonly reference: Readonly<UnitRef>;
61
+ readonly imported:
62
+ | {
63
+ readonly seed: { readonly execution: Readonly<ExecutionRef> };
64
+ readonly seal: { readonly entryId: string } | undefined;
65
+ }
66
+ | undefined;
67
+ },
68
+ entryId: string,
69
+ ): void {
70
+ if (unit.imported === undefined) {
71
+ Object.assign(unit.reference, {
72
+ contractEntryId: originFor(unit.reference, entryId, this.#origins),
73
+ });
74
+ } else if (unit.imported.seal !== undefined) {
75
+ const key = JSON.stringify(unit.imported.seed.execution),
76
+ sealEntry = this.#seals.get(key) ?? entryId;
77
+ this.#seals.set(key, sealEntry);
78
+ Object.assign(unit.imported.seal, { entryId: sealEntry });
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Reads revision origins from the entries that first introduced them.
85
+ * Status-only snapshots cannot move a revision's origin.
86
+ * @param {readonly SessionEntry[]} branch Current branch in chronological order.
87
+ * @returns {TodoList} Validated snapshot with derived provenance.
88
+ */
89
+ const branchSnapshot = (branch: readonly SessionEntry[]): TodoList => {
90
+ const provenance = new Provenance();
91
+ let current: TodoList = { tasks: [] };
92
+ for (const entry of branch.filter((candidate) => isStateEntry(candidate))) {
93
+ current = parse(entry.data);
94
+ for (const task of current.tasks.flatMap((root) => [root, ...(root.subtasks ?? [])])) {
95
+ if (task.unit !== undefined) {
96
+ provenance.resolve(
97
+ { imported: task.unit.imported, reference: task.unit.reference },
98
+ entry.id,
99
+ );
100
+ }
101
+ }
102
+ }
103
+ return current;
104
+ };
105
+
106
+ export { STATE_ENTRY, branchSnapshot, latestSnapshot };
@@ -0,0 +1,61 @@
1
+ // Retained a479b93 reader; only local state/tool import paths differ.
2
+ import { STATE_ENTRY, branchSnapshot } from "./old-state-fixture.ts";
3
+ import { apply, view } from "./wasm.ts";
4
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
5
+ import type { Static } from "typebox";
6
+ import type { TodoList } from "./wasm.ts";
7
+ import type { parameters } from "./schema.ts";
8
+ import { workUnitGuidance } from "./guidance.ts";
9
+
10
+ /** One `todo` call, as the schema in `index.ts` admits it. */
11
+ type TodoParams = Static<typeof parameters>;
12
+
13
+ /** What a call reads from and writes to the session. */
14
+ interface TodoSession {
15
+ readonly sessionId: string;
16
+ readonly branch: () => readonly SessionEntry[];
17
+ readonly append: (customType: string, list: TodoList) => void;
18
+ }
19
+
20
+ /** The tool result: the summary for the model and the list for rendering. */
21
+ interface TodoResult {
22
+ readonly content: [{ readonly type: "text"; readonly text: string }];
23
+ readonly details: TodoList;
24
+ }
25
+
26
+ /**
27
+ * The result for `list`.
28
+ * @param {TodoList} list A valid list.
29
+ * @param {boolean} creation Whether the call created work.
30
+ * @returns {TodoResult} The summary and the list.
31
+ */
32
+ const result = (list: TodoList, creation: boolean): TodoResult => ({
33
+ content: [
34
+ { text: creation ? `${view(list)}\n\n${workUnitGuidance}` : view(list), type: "text" },
35
+ ],
36
+ details: list,
37
+ }),
38
+ /**
39
+ * Runs one call. A rejected operation throws the core's message, so pi marks
40
+ * the result failed, and nothing is stored.
41
+ * @param {TodoParams} params The validated tool arguments.
42
+ * @param {TodoSession} session The branch to read and the entry writer.
43
+ * @returns {TodoResult} The result for the model and the renderer.
44
+ */
45
+ runTodo = (params: TodoParams, session: TodoSession): TodoResult => {
46
+ const current = branchSnapshot(session.branch()),
47
+ { list, persist } = apply(current, params, {
48
+ mutationId: crypto.randomUUID(),
49
+ sessionId: session.sessionId,
50
+ });
51
+ if (persist) {
52
+ session.append(STATE_ENTRY, list);
53
+ }
54
+ return result(
55
+ persist ? branchSnapshot(session.branch()) : list,
56
+ params.op === "init" || params.op === "append",
57
+ );
58
+ };
59
+
60
+ export { runTodo };
61
+ export type { TodoParams, TodoResult, TodoSession };