@camox/api-contract 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ids.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+
3
+ /** The id of a content entity: one UUIDv7, kept in Live and every draft (ADR 0004). */
4
+ export const uuidv7Schema = /* @__PURE__ */ z.uuidv7();
5
+
6
+ /**
7
+ * A Project ID: a UUIDv7 in lowercase only, the form the project's Worker is named by, so an
8
+ * uppercase one fails here rather than silently naming no project.
9
+ */
10
+ export const projectIdSchema = /* @__PURE__ */ z
11
+ .uuidv7()
12
+ .regex(/^[0-9a-f-]+$/, "A Project ID is a UUIDv7 in lowercase");
13
+
14
+ /**
15
+ * `uuidv7Schema` as JSON Schema, for content schemas. Written out rather than derived, so site
16
+ * bundles, which need only this, leave zod out.
17
+ */
18
+ export const uuidv7JsonSchema = {
19
+ type: "string",
20
+ format: "uuid",
21
+ pattern:
22
+ "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-7[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$",
23
+ };
24
+
25
+ /** A text link to a page: this prefix, then the page's UUIDv7. */
26
+ export const PAGE_TEXT_LINK_PREFIX = "camox:page:";
27
+
28
+ /**
29
+ * Mints a UUIDv7 (RFC 9562): a 48-bit millisecond timestamp, then random bits.
30
+ * The server mints ids; clients mint one only for optimistic inserts.
31
+ */
32
+ export function generateUuidv7(): string {
33
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
34
+ let timestamp = Date.now();
35
+ for (let index = 5; index >= 0; index--) {
36
+ bytes[index] = timestamp % 256;
37
+ timestamp = Math.floor(timestamp / 256);
38
+ }
39
+ bytes[6] = (bytes[6]! & 0x0f) | 0x70;
40
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
41
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
42
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
43
+ }
package/src/index.ts CHANGED
@@ -1 +1,7 @@
1
+ export * from "./artifact.ts";
2
+ export * from "./icons.ts";
3
+ export * from "./ids.ts";
4
+ export * from "./reference-query.ts";
1
5
  export type { Router } from "../../../apps/api/src/router";
6
+ export type { PublishPreview } from "../../../apps/api/src/domains/drafts/publish";
7
+ export type { EntityKind } from "../../../apps/api/src/domains/drafts/overlay";
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Project Slugs Camox keeps for its own hosts and pages, so no project's `<slug>.camox.site`
5
+ * looks like one of them.
6
+ */
7
+ export const RESERVED_PROJECT_SLUGS: ReadonlySet<string> = new Set([
8
+ "www",
9
+ "api",
10
+ "app",
11
+ "dashboard",
12
+ "studio",
13
+ "sites",
14
+ "site",
15
+ "docs",
16
+ "blog",
17
+ "help",
18
+ "support",
19
+ "status",
20
+ "admin",
21
+ "auth",
22
+ "login",
23
+ "mail",
24
+ "email",
25
+ "cdn",
26
+ "static",
27
+ "assets",
28
+ "files",
29
+ "camox",
30
+ ]);
31
+
32
+ /**
33
+ * A Project Slug: one lowercase DNS label, the only depth Universal SSL covers on `camox.site`,
34
+ * made of letters, digits and inner hyphens.
35
+ */
36
+ export const projectSlugSchema = /* @__PURE__ */ z
37
+ .string()
38
+ .min(1, "Enter a slug")
39
+ .max(63, "Use at most 63 characters")
40
+ .regex(
41
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
42
+ "Use lowercase letters, digits and hyphens, without a hyphen at either end",
43
+ );
44
+
45
+ /** Why a slug can't be given to a new project. */
46
+ export type UnavailableSlugReason = "invalid" | "reserved" | "taken";
47
+
48
+ /** What a member is told when a slug can't be used, by reason. */
49
+ export const UNAVAILABLE_SLUG_MESSAGES: Record<UnavailableSlugReason, string> = {
50
+ invalid: "Use lowercase letters, digits and hyphens, without a hyphen at either end.",
51
+ reserved: "This slug is reserved by Camox. Choose another.",
52
+ taken: "This slug is already taken. Choose another.",
53
+ };
54
+
55
+ /**
56
+ * Where a project is in its life: `settingUp` from its creation until its first release
57
+ * succeeds, then `live`. `setupFailed` when its setup gave up: Camox is told and fixes it.
58
+ */
59
+ export type ProjectStatus = "settingUp" | "live" | "setupFailed";
60
+
61
+ /**
62
+ * The steps a project's setup goes through before it's live, as its page lists them: copying the
63
+ * Template into its repo, then its first release building it and serving it from its Worker.
64
+ */
65
+ export type ProjectSetupStep = "copyTemplate" | "build" | "serve";
66
+
67
+ export const PROJECT_SETUP_STEPS: readonly ProjectSetupStep[] = ["copyTemplate", "build", "serve"];
package/src/query-keys.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { EndedDraft } from "./drafts";
2
+
1
3
  /**
2
4
  * Use TypeScript to enforce 'camox' as the first query key to ensure they're all namespaced.
3
5
  * This is because the Tanstack Query client on the frontend may be shared with the user's routes,
@@ -7,52 +9,88 @@ export type QueryKey = [first: "camox", ...rest: Array<string | number>];
7
9
  type QueryKeyGroup = Record<string, QueryKey | ((...args: any[]) => QueryKey)>;
8
10
 
9
11
  /**
10
- * Source axis on read query keys. `'live'` reads the page's live published
11
- * checkpoint snapshot; `'draft'` reads the live editor rows. The two render
12
- * through the same component — only the cache slot differs, so toggling the
13
- * source select is instant once both have been seeded.
14
- *
15
- * Block / page-read query keys include the source as the trailing key segment.
16
- * Omitting it on `invalidateQueries` is a prefix invalidation that hits every
17
- * source — used for navigation events and other source-agnostic invalidations.
18
- * Edit-time invalidations (which only touch draft data) pass `'draft'`
19
- * explicitly so the `'live'` cache stays untouched.
12
+ * The key prefixes the API's realtime invalidations name (ADR 0011). The studio caches each read
13
+ * under one of them, with the scope appended, so an invalidation reaches every read it should;
14
+ * the studio's own keys live with its reads, in the SDK.
20
15
  */
21
- export type ReadSource = "draft" | "live";
22
-
23
16
  export const queryKeys = {
17
+ collections: {
18
+ record: (projectUuid: string, collectionId: string, id: string) => [
19
+ "camox",
20
+ "collections",
21
+ "record",
22
+ projectUuid,
23
+ collectionId,
24
+ id,
25
+ ],
26
+ records: (projectUuid: string, collectionId: string) => [
27
+ "camox",
28
+ "collections",
29
+ "records",
30
+ projectUuid,
31
+ collectionId,
32
+ ],
33
+ },
24
34
  pages: {
25
35
  list: ["camox", "pages", "list"],
26
- getByPath: (path: string, source?: ReadSource) =>
27
- source
28
- ? ["camox", "pages", "getByPath", path, source]
29
- : ["camox", "pages", "getByPath", path],
36
+ getByPath: (path: string) => ["camox", "pages", "getByPath", path],
30
37
  getByPathAll: ["camox", "pages", "getByPath"],
31
- getById: (id: number) => ["camox", "pages", "getById", id],
38
+ getById: (id: string) => ["camox", "pages", "getById", id],
32
39
  },
33
40
  files: {
34
41
  list: ["camox", "files", "list"],
35
- get: (id: number) => ["camox", "files", "get", id],
42
+ get: (id: string) => ["camox", "files", "get", id],
36
43
  },
37
44
  blocks: {
38
- get: (id: number, source?: ReadSource) =>
39
- source ? ["camox", "blocks", "get", id, source] : ["camox", "blocks", "get", id],
45
+ get: (id: string) => ["camox", "blocks", "get", id],
46
+ // Every placement change refreshes what's under this prefix: counts, pages using a block.
40
47
  getUsageCounts: ["camox", "blocks", "getUsageCounts"],
41
- getPageMarkdown: (pageId: number) => ["camox", "blocks", "getPageMarkdown", pageId],
42
- },
43
- repeatableItems: {
44
- get: (id: number) => ["camox", "repeatableItems", "get", id],
48
+ // Under the usage counts prefix, so placing or removing the block refreshes it too.
49
+ getSyncedContent: (type: string) => ["camox", "blocks", "getUsageCounts", "synced", type],
50
+ getPageMarkdown: (pageId: string) => ["camox", "blocks", "getPageMarkdown", pageId],
45
51
  },
46
52
  layouts: {
47
53
  all: ["camox", "layouts"],
48
54
  },
49
- environments: {
50
- all: ["camox", "environments"],
51
- checkCompatibility: ["camox", "environments", "checkCompatibility"],
55
+ drafts: {
56
+ all: ["camox", "drafts"],
57
+ // Open drafts and Live's latest publish: the same for every viewer, whatever they're in.
58
+ list: ["camox", "drafts", "list"],
59
+ // The draft a viewer is in, scoped to it like content.
60
+ get: ["camox", "drafts", "get"],
52
61
  },
53
62
  } satisfies Record<string, QueryKeyGroup>;
54
63
 
64
+ /** The last segment of a query key: what the query reads, Live or a draft (ADR 0011). */
65
+ export const LIVE_KEY_SCOPE = "live";
66
+
67
+ /**
68
+ * A query key read from Live (`draftId` null) or from a draft. The keys above are prefixes naming
69
+ * what a query reads; the cache holds them with the scope appended, so each draft's queries are
70
+ * kept and invalidated apart.
71
+ */
72
+ export function inScope(key: QueryKey, draftId: string | null): QueryKey {
73
+ return [...key, draftId ?? LIVE_KEY_SCOPE];
74
+ }
75
+
76
+ /** The scope a scoped query key ends in: `"live"` or a draft's id. */
77
+ export function scopeOfKey(key: readonly unknown[]): unknown {
78
+ return key[key.length - 1];
79
+ }
80
+
81
+ /**
82
+ * Refetch the queries under these prefixes. `draftId` names the draft the change came from, so
83
+ * only that draft's queries refetch; a Live change (`null`) refetches every draft's too, since
84
+ * drafts read Live wherever they change nothing.
85
+ */
55
86
  export type InvalidationMessage = {
56
87
  type: "invalidate";
88
+ draftId: string | null;
57
89
  targets: QueryKey[];
58
90
  };
91
+
92
+ /** A draft was published or discarded: its viewers go back to Live. */
93
+ export type DraftEndedMessage = { type: "draftEnded" } & EndedDraft;
94
+
95
+ /** Everything the project room broadcasts. */
96
+ export type ProjectRoomMessage = InvalidationMessage | DraftEndedMessage;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Rules for query-backed reference lists, shared by the SDK (builders) and the API (definition
3
+ * sync), so both accept and reject the same queries.
4
+ */
5
+
6
+ /** The most records a query-backed list resolves to, and its default `limit`. */
7
+ export const QUERY_LIMIT_CAP = 100;
8
+
9
+ /** Record metadata a query can order by. Collections cannot name fields after them. */
10
+ export type SystemOrderKey = "createdAt" | "publishedAt";
11
+ export const SYSTEM_ORDER_KEYS: readonly SystemOrderKey[] = ["createdAt", "publishedAt"];
12
+
13
+ export function isSystemOrderKey(key: string): key is SystemOrderKey {
14
+ return (SYSTEM_ORDER_KEYS as readonly string[]).includes(key);
15
+ }
16
+
17
+ /** Whether a reference list field is query-backed: code defines its records, nothing is stored. */
18
+ export function isQueryBacked(field: object | null | undefined) {
19
+ return !!field && (field as { query?: unknown }).query !== undefined;
20
+ }
21
+
22
+ /**
23
+ * Why a query is invalid, if it is. `fieldTypeOf` gives the collection field type an ordering
24
+ * key names; keys must name a `String` field or system metadata.
25
+ */
26
+ export function referenceQueryProblem(
27
+ query: unknown,
28
+ fieldTypeOf: (key: string) => unknown,
29
+ ): string | undefined {
30
+ if (!query || typeof query !== "object" || Array.isArray(query)) return "query must be an object";
31
+ const { orderBy, limit, ...rest } = query as Record<string, unknown>;
32
+ if (Object.keys(rest).length) return "query only supports orderBy and limit";
33
+ const validLimit =
34
+ typeof limit === "number" && Number.isInteger(limit) && limit >= 1 && limit <= QUERY_LIMIT_CAP;
35
+ if (limit !== undefined && !validLimit) {
36
+ return `limit must be an integer from 1 to ${QUERY_LIMIT_CAP}`;
37
+ }
38
+ if (orderBy === undefined) return;
39
+ const entries =
40
+ orderBy && typeof orderBy === "object" && !Array.isArray(orderBy)
41
+ ? Object.entries(orderBy)
42
+ : [];
43
+ if (entries.length !== 1) return "orderBy takes a single key";
44
+ const [[key, direction]] = entries;
45
+ if (direction !== "asc" && direction !== "desc") return 'order must be "asc" or "desc"';
46
+ if (isSystemOrderKey(key)) return;
47
+ if (fieldTypeOf(key) !== "String") return `cannot order by "${key}"`;
48
+ }
package/src/threads.ts ADDED
@@ -0,0 +1,327 @@
1
+ import type { AssistantMessage, Message } from "@earendil-works/pi-ai";
2
+ import type { AgentEvent, EntryRecord } from "@earendil-works/pi-durable";
3
+ import { z } from "zod";
4
+
5
+ // A thread with Camox's agent, as the studio shows it. The thread's Durable Object sends Pi's own
6
+ // agent events over its socket, and this module is the one place that interprets them: the
7
+ // studio and the API's tests fold them with the same code.
8
+
9
+ /**
10
+ * The kind of the transcript entry recording an editor's message, with its sender and the
11
+ * operation id the studio sent it with as data (`editorMessageDataSchema`).
12
+ */
13
+ export const EDITOR_MESSAGE_ENTRY = "camox.editor-message";
14
+
15
+ /** The kind of the transcript entry recording that an editor stopped a run, with them as data. */
16
+ export const RUN_STOPPED_ENTRY = "camox.run-stopped";
17
+
18
+ /** Who sent a message in a thread. */
19
+ export const threadSenderSchema = z.object({
20
+ id: z.string(),
21
+ name: z.string(),
22
+ image: z.string().nullable(),
23
+ });
24
+ export type ThreadSender = z.infer<typeof threadSenderSchema>;
25
+
26
+ /** Whether `data` names a sender. */
27
+ export const isSender = (data: unknown): data is ThreadSender =>
28
+ threadSenderSchema.safeParse(data).success;
29
+
30
+ /** What an editor's message entry records: who sent it, and the operation id it was sent with. */
31
+ export const editorMessageDataSchema = threadSenderSchema.extend({
32
+ operationId: z.string().optional(),
33
+ });
34
+
35
+ /**
36
+ * A draft a Live thread started with its first write, becoming its thread, and the operation ids
37
+ * of the messages of the run that made the write: the studio that sent one of them enters the
38
+ * draft with the thread.
39
+ */
40
+ export const startedDraftSchema = z.object({
41
+ draftId: z.string(),
42
+ operationIds: z.array(z.string()),
43
+ });
44
+ export type StartedDraft = z.infer<typeof startedDraftSchema>;
45
+
46
+ /** How a write touched what it names. */
47
+ export const touchKindSchema = z.enum(["created", "edited", "moved", "deleted", "settings"]);
48
+ export type TouchKind = z.infer<typeof touchKindSchema>;
49
+
50
+ /**
51
+ * One thing a script's successful write touched, named so the studio can locate it: a Page (and
52
+ * its Block, if any), a Synced Block's shared content, by its block definition, or a Layout (and
53
+ * its Block, if any). `settings` is a Page's settings only (nickname, path, SEO, layout). `locale`
54
+ * is the Locale the write was in, for a localized tool. Writes to Collection Records, Files and
55
+ * Locales aren't on the Canvas, so they're left out.
56
+ */
57
+ const touchBaseSchema = z.object({ kind: touchKindSchema, locale: z.string().optional() });
58
+
59
+ export const touchSchema = z.discriminatedUnion("entity", [
60
+ touchBaseSchema.extend({
61
+ entity: z.literal("page"),
62
+ pageId: z.string(),
63
+ blockId: z.string().optional(),
64
+ }),
65
+ touchBaseSchema.extend({
66
+ entity: z.literal("synced-block"),
67
+ /** The Synced Block's block definition id. */
68
+ blockType: z.string(),
69
+ }),
70
+ touchBaseSchema.extend({
71
+ entity: z.literal("layout"),
72
+ layoutId: z.string(),
73
+ blockId: z.string().optional(),
74
+ }),
75
+ ]);
76
+ export type Touch = z.infer<typeof touchSchema>;
77
+
78
+ /**
79
+ * What one code-mode script's successful writes touched, in write order, and the operation ids
80
+ * of the messages of the run it belongs to: only the studio that sent one of them follows it.
81
+ */
82
+ export const touchedBatchSchema = z.object({
83
+ operationIds: z.array(z.string()),
84
+ touches: z.array(touchSchema),
85
+ });
86
+ export type TouchedBatch = z.infer<typeof touchedBatchSchema>;
87
+
88
+ /** A message the studio shows in a thread. */
89
+ export type ThreadMessage =
90
+ | { id: string; from: "editor"; sender: ThreadSender; text: string }
91
+ /** The agent's final message of a turn, in Markdown. */
92
+ | { id: string; from: "agent"; text: string }
93
+ /**
94
+ * In place of the agent's message, for a turn that ended without one: the model failed (after
95
+ * Pi's retries), or its answer was cut short. Sending again retries.
96
+ */
97
+ | { id: string; from: "failed" }
98
+ /** In place of the agent's message, for a turn an editor stopped: `sender` stopped it. */
99
+ | { id: string; from: "stopped"; sender: ThreadSender };
100
+
101
+ /** Where a Live thread's messages went when it started a draft, beside its transcript. */
102
+ type LiveThreadHandoff = {
103
+ /**
104
+ * The draft this Live thread started with its first write, whose thread it became. The studio
105
+ * that sent a message of that run enters the draft with the thread; other tabs on Live move to
106
+ * the editor's fresh Live thread.
107
+ */
108
+ startedDraft?: StartedDraft;
109
+ /** The draft the editor's previous Live thread continued in, for a fresh Live thread. */
110
+ continuedIn?: StartedDraft;
111
+ };
112
+
113
+ /** Everything the studio shows for a thread. */
114
+ export type ThreadView = LiveThreadHandoff & {
115
+ messages: readonly ThreadMessage[];
116
+ /** Whether a run is going: the agent is working on a turn, and stopping would end it. */
117
+ running: boolean;
118
+ };
119
+
120
+ export const EMPTY_THREAD_VIEW: ThreadView = { messages: [], running: false };
121
+
122
+ /**
123
+ * What a thread's view is folded from: the steps of its transcript that matter to the studio,
124
+ * and whether a run is going. The studio and the tests fold Pi's events into this, and derive
125
+ * the view from it with `threadViewOf`, so a snapshot and the events that led to it show the same.
126
+ */
127
+ export type ThreadState = LiveThreadHandoff & { steps: readonly ThreadStep[]; running: boolean };
128
+
129
+ export const EMPTY_THREAD_STATE: ThreadState = { steps: [], running: false };
130
+
131
+ /** One transcript entry, as far as the studio's view is concerned. */
132
+ type ThreadStep = { id: string } & (
133
+ | { type: "editor"; sender: ThreadSender; text: string }
134
+ | { type: "answer"; text: string }
135
+ /** A round of tool calls, or their results: the run goes on after it. */
136
+ | { type: "tools" }
137
+ /** A model call that ended without an answer: failed, aborted, or cut short. */
138
+ | { type: "unfinished" }
139
+ | { type: "stopped"; sender: ThreadSender }
140
+ );
141
+
142
+ /** Studio → thread. */
143
+ export const threadClientMessageSchema = z.discriminatedUnion("type", [
144
+ /**
145
+ * An editor's message. The operation id is generated by the studio and kept across resends, so
146
+ * a message resent after a dropped connection is one submission.
147
+ */
148
+ z.object({ type: z.literal("send"), operationId: z.string().min(1), text: z.string().min(1) }),
149
+ /** Stops the run going, if any. What the agent changed before stays. */
150
+ z.object({ type: z.literal("stop") }),
151
+ /** Asks for a fresh snapshot of the thread. */
152
+ z.object({ type: z.literal("resync") }),
153
+ ]);
154
+ export type ThreadClientMessage = z.infer<typeof threadClientMessageSchema>;
155
+
156
+ /** Thread → studio. */
157
+ export type ThreadServerMessage =
158
+ /**
159
+ * Pi's agent events. The first batch after connecting or resyncing starts with a `snapshot`,
160
+ * which replaces whatever the studio folded before.
161
+ */
162
+ | { type: "events"; events: readonly AgentEvent[] }
163
+ /** The thread recorded the message sent with this operation id (once, however often sent). */
164
+ | { type: "accepted"; operationId: string }
165
+ /** This Live thread started a draft with its first write, and became that draft's thread. */
166
+ | { type: "started-draft"; startedDraft: StartedDraft }
167
+ /**
168
+ * The editor's previous Live thread continued in this draft: this one is fresh. Sent before
169
+ * the snapshot.
170
+ */
171
+ | { type: "continued-in"; continuedIn: StartedDraft }
172
+ /**
173
+ * A code-mode script that wrote something ended, failed or not: what its successful writes
174
+ * touched. Sent once per such script, live only: a snapshot never replays past touches.
175
+ */
176
+ | { type: "touched"; touched: TouchedBatch }
177
+ | { type: "error"; operationId?: string; message: string };
178
+
179
+ /**
180
+ * The code a thread closes its sockets with once it ended with its draft, and for good: it's
181
+ * deleted, so reconnecting reaches nothing. A development draft, which stays open, gets a new
182
+ * thread the next time the studio connects.
183
+ */
184
+ export const THREAD_ENDED_CLOSE_CODE = 4000;
185
+
186
+ const textOf = (content: Message["content"]) =>
187
+ typeof content === "string"
188
+ ? content
189
+ : content
190
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
191
+ .join("")
192
+ .trim();
193
+
194
+ /** What an assistant message is to the thread: a final answer, a tool round, or neither. */
195
+ function assistantStep(id: string, message: AssistantMessage): ThreadStep {
196
+ if (message.content.some((part) => part.type === "toolCall")) return { id, type: "tools" };
197
+ // Thinking is never shown. An answer cut short by the model's length limit isn't one.
198
+ const text = message.stopReason === "stop" ? textOf(message.content) : "";
199
+ return text ? { id, type: "answer", text } : { id, type: "unfinished" };
200
+ }
201
+
202
+ /** The sender an entry's data names, if any, without other fields it may carry. */
203
+ function senderOf(data: unknown): ThreadSender | undefined {
204
+ if (!isSender(data)) return undefined;
205
+ const { id, name, image } = data;
206
+ return { id, name, image };
207
+ }
208
+
209
+ /** The step an entry is, if it's one the view depends on. */
210
+ function threadStepOf(entry: EntryRecord): ThreadStep | undefined {
211
+ const id = String(entry.id);
212
+ const sender = senderOf(entry.data);
213
+ if (entry.kind === RUN_STOPPED_ENTRY && sender) return { id, type: "stopped", sender };
214
+ const message = entry.model?.find((candidate) => candidate.role !== "system");
215
+ if (!message) return undefined;
216
+ if (entry.kind === EDITOR_MESSAGE_ENTRY && message.role === "user" && sender) {
217
+ return { id, type: "editor", sender, text: textOf(message.content) };
218
+ }
219
+ if (message.role === "assistant") return assistantStep(id, message);
220
+ if (message.role === "toolResult") return { id, type: "tools" };
221
+ return undefined;
222
+ }
223
+
224
+ /**
225
+ * What the studio shows for a thread. A turn starts with an editor's message, and messages sent
226
+ * while it runs join it. It ends with the agent's final message; text written beside tool calls
227
+ * is never shown. A stopped turn shows who stopped it instead, and whatever its run wrote after
228
+ * the stop is left out. A turn that ended without either shows a failed line in its place: its
229
+ * run is over, or a later message started another run after its last model call came back
230
+ * unfinished. While Pi retries a failed call, the run goes on, so the turn shows as working.
231
+ */
232
+ export function threadViewOf({ steps, running, ...drafts }: ThreadState): ThreadView {
233
+ const messages: ThreadMessage[] = [];
234
+ // The latest editor's message of a turn still waiting for the agent's message.
235
+ let waiting: string | undefined;
236
+ let unfinished = false;
237
+ /** Ends the turn waiting for the agent's message, if any. */
238
+ const endTurn = () => {
239
+ waiting = undefined;
240
+ unfinished = false;
241
+ };
242
+ /** Ends the turn waiting for the agent's message with a failed line, if any. */
243
+ const fail = () => {
244
+ if (waiting !== undefined) messages.push({ id: `${waiting}:failed`, from: "failed" });
245
+ endTurn();
246
+ };
247
+
248
+ for (const step of steps) {
249
+ switch (step.type) {
250
+ case "editor":
251
+ // Pi places a steering message only once a model call is settled: after a round of tool
252
+ // calls, or with the answer ending the run. Never between a failed call and its retry, so
253
+ // an editor's message after an unfinished call means that call's turn is over.
254
+ if (unfinished) fail();
255
+ messages.push({ id: step.id, from: "editor", sender: step.sender, text: step.text });
256
+ waiting = step.id;
257
+ break;
258
+ case "stopped":
259
+ if (waiting === undefined) break;
260
+ messages.push({ id: step.id, from: "stopped", sender: step.sender });
261
+ endTurn();
262
+ break;
263
+ case "answer":
264
+ // A stopped turn's run may still answer before it ends.
265
+ if (waiting === undefined && messages.at(-1)?.from === "stopped") break;
266
+ messages.push({ id: step.id, from: "agent", text: step.text });
267
+ endTurn();
268
+ break;
269
+ case "tools":
270
+ unfinished = false;
271
+ break;
272
+ case "unfinished":
273
+ unfinished = true;
274
+ break;
275
+ }
276
+ }
277
+ if (!running) fail();
278
+ return { ...drafts, messages, running };
279
+ }
280
+
281
+ const append = (state: ThreadState, entry: EntryRecord | undefined): ThreadState => {
282
+ const step = entry && threadStepOf(entry);
283
+ if (!step || state.steps.some((known) => known.id === step.id)) return state;
284
+ return { ...state, steps: [...state.steps, step] };
285
+ };
286
+
287
+ /** Folds one of Pi's agent events into the thread's state. */
288
+ export function reduceThreadState(state: ThreadState, event: AgentEvent): ThreadState {
289
+ switch (event.type) {
290
+ case "snapshot":
291
+ return {
292
+ ...state,
293
+ steps: event.entries.flatMap((entry) => threadStepOf(entry) ?? []),
294
+ running: event.run !== undefined,
295
+ };
296
+ case "run_start":
297
+ return { ...state, running: true };
298
+ case "run_end":
299
+ return { ...state, running: false };
300
+ case "message_end":
301
+ case "entry_appended":
302
+ case "tool_execution_end":
303
+ return append(state, event.entry);
304
+ default:
305
+ return state;
306
+ }
307
+ }
308
+
309
+ /** Folds a batch of Pi's agent events into the thread's state. */
310
+ export const reduceThreadEvents = (
311
+ state: ThreadState,
312
+ events: readonly AgentEvent[],
313
+ ): ThreadState => events.reduce(reduceThreadState, state);
314
+
315
+ /** Folds what the thread sent over its socket into the thread's state. */
316
+ export function reduceThreadFrame(state: ThreadState, frame: ThreadServerMessage): ThreadState {
317
+ switch (frame.type) {
318
+ case "events":
319
+ return reduceThreadEvents(state, frame.events);
320
+ case "started-draft":
321
+ return { ...state, startedDraft: frame.startedDraft };
322
+ case "continued-in":
323
+ return { ...state, continuedIn: frame.continuedIn };
324
+ default:
325
+ return state;
326
+ }
327
+ }