paseo-dsh 0.0.0-stage → 0.2.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,297 @@
1
+ /**
2
+ * DSH session events -> Paseo timeline items.
3
+ *
4
+ * DSH publishes complete message snapshots (`assistant/message`, `tool/call`,
5
+ * `tool/result`) rather than text deltas, and Paseo derives its own live delta
6
+ * from a stable item id. Re-emitting an id therefore updates a row in place.
7
+ *
8
+ * @module dsh-paseo/server/timeline
9
+ */
10
+ import type {
11
+ ProviderTimelineItem,
12
+ ProviderToolCallDetail,
13
+ } from "@getpaseo/plugin/server/provider";
14
+ import type { JsonValue } from "@getpaseo/protocol/agent-types";
15
+
16
+ interface DshEvent {
17
+ type: string;
18
+ seq?: number;
19
+ [key: string]: unknown;
20
+ }
21
+
22
+ function isRecord(value: unknown): value is Record<string, unknown> {
23
+ return typeof value === "object" && value !== null;
24
+ }
25
+
26
+ function parseArguments(raw: unknown): Record<string, unknown> {
27
+ if (isRecord(raw)) return raw;
28
+ if (typeof raw !== "string" || raw.trim() === "") return {};
29
+ try {
30
+ const parsed: unknown = JSON.parse(raw);
31
+ return isRecord(parsed) ? parsed : { value: parsed };
32
+ } catch {
33
+ return { value: raw };
34
+ }
35
+ }
36
+
37
+ function textOf(content: unknown): string {
38
+ if (!Array.isArray(content)) return "";
39
+ return content
40
+ .filter((block): block is Record<string, unknown> => isRecord(block) && block.type === "text")
41
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
42
+ .join("");
43
+ }
44
+
45
+ function stringField(source: Record<string, unknown>, key: string): string | undefined {
46
+ const value = source[key];
47
+ return typeof value === "string" && value !== "" ? value : undefined;
48
+ }
49
+
50
+ /** Map one DSH tool call onto the richest Paseo tool detail available. */
51
+ function toolDetail(name: string, input: Record<string, unknown>, output?: string): ProviderToolCallDetail {
52
+ const filePath = stringField(input, "file_path") ?? stringField(input, "filePath");
53
+ switch (name) {
54
+ case "bash":
55
+ case "pwsh": {
56
+ const command = stringField(input, "command") ?? "";
57
+ const exitCode = typeof input.exit_code === "number" ? input.exit_code : undefined;
58
+ return {
59
+ type: "shell",
60
+ command,
61
+ ...(stringField(input, "cwd") === undefined ? {} : { cwd: stringField(input, "cwd") as string }),
62
+ ...(output === undefined ? {} : { output }),
63
+ ...(exitCode === undefined ? {} : { exitCode }),
64
+ };
65
+ }
66
+ case "read":
67
+ return {
68
+ type: "read",
69
+ filePath: filePath ?? "",
70
+ ...(output === undefined ? {} : { content: output }),
71
+ ...(typeof input.offset === "number" ? { offset: input.offset } : {}),
72
+ ...(typeof input.limit === "number" ? { limit: input.limit } : {}),
73
+ };
74
+ case "write":
75
+ return {
76
+ type: "write",
77
+ filePath: filePath ?? "",
78
+ ...(typeof input.content === "string" ? { content: input.content } : {}),
79
+ };
80
+ case "edit":
81
+ return {
82
+ type: "edit",
83
+ filePath: filePath ?? "",
84
+ ...(typeof input.old_string === "string" ? { oldString: input.old_string } : {}),
85
+ ...(typeof input.new_string === "string" ? { newString: input.new_string } : {}),
86
+ };
87
+ case "grep":
88
+ case "glob":
89
+ case "web_search":
90
+ return {
91
+ type: "search",
92
+ query:
93
+ stringField(input, "pattern") ??
94
+ stringField(input, "query") ??
95
+ stringField(input, "path") ??
96
+ "",
97
+ toolName: name === "web_search" ? "web_search" : name,
98
+ ...(output === undefined ? {} : { content: output }),
99
+ };
100
+ case "web_fetch":
101
+ return {
102
+ type: "fetch",
103
+ url: stringField(input, "url") ?? "",
104
+ ...(output === undefined ? {} : { result: output }),
105
+ };
106
+ case "todo_write":
107
+ return { type: "plain_text", label: "Update tasks", icon: "sparkles" };
108
+ case "ask_user_question":
109
+ return { type: "plain_text", label: "Asked the user", icon: "sparkles" };
110
+ case "exit_plan_mode":
111
+ // Paseo renders this as the readable plan card, and its own Codex adapter
112
+ // emits the same item next to the approval buttons. The plan has to be
113
+ // visible *before* the choice, so this is the copy that carries it.
114
+ return { type: "plan", text: stringField(input, "plan") ?? "" };
115
+ case "subagent":
116
+ return {
117
+ type: "sub_agent",
118
+ ...(stringField(input, "description") === undefined
119
+ ? {}
120
+ : { description: stringField(input, "description") as string }),
121
+ log: output ?? "",
122
+ };
123
+ default:
124
+ return {
125
+ type: "unknown",
126
+ input: input as unknown as JsonValue,
127
+ output: (output ?? null) as JsonValue,
128
+ };
129
+ }
130
+ }
131
+
132
+ /** Extract `todo_write` items into Paseo's native todo row. */
133
+ function todoItems(input: Record<string, unknown>): Array<{ text: string; completed: boolean }> | null {
134
+ const raw = input.todos;
135
+ if (!Array.isArray(raw)) return null;
136
+ const items = raw
137
+ .filter(isRecord)
138
+ .map((todo) => ({
139
+ text:
140
+ stringField(todo, "content") ?? stringField(todo, "text") ?? stringField(todo, "activeForm") ?? "",
141
+ completed: todo.status === "completed",
142
+ }))
143
+ .filter((todo) => todo.text !== "");
144
+ return items.length === 0 ? null : items;
145
+ }
146
+
147
+ export class TimelineBuilder {
148
+ #items = new Map<string, ProviderTimelineItem>();
149
+ #toolNames = new Map<string, string>();
150
+ #toolInputs = new Map<string, Record<string, unknown>>();
151
+
152
+ /**
153
+ * Fold one DSH session event into zero or more complete Paseo item snapshots.
154
+ *
155
+ * The wire envelope is `{ type, seq, time, data }`, so every handler reads the
156
+ * `data` payload rather than the envelope itself.
157
+ */
158
+ consume(event: DshEvent): ProviderTimelineItem[] {
159
+ const data = isRecord(event.data) ? event.data : {};
160
+ switch (event.type) {
161
+ case "assistant/message":
162
+ return this.#assistantMessage(data);
163
+ case "tool/call":
164
+ return this.#toolCall(data);
165
+ case "tool/result":
166
+ return this.#toolResult(data);
167
+ case "turn/end":
168
+ return this.#turnEnd(data);
169
+ default:
170
+ return [];
171
+ }
172
+ }
173
+
174
+ #put(item: ProviderTimelineItem): ProviderTimelineItem[] {
175
+ this.#items.set(item.id, item);
176
+ return [item];
177
+ }
178
+
179
+ #assistantMessage(data: Record<string, unknown>): ProviderTimelineItem[] {
180
+ const message = isRecord(data.message) ? data.message : undefined;
181
+ const content = message?.content;
182
+ if (!Array.isArray(content)) return [];
183
+ const turn = typeof data.turn === "number" ? data.turn : 0;
184
+ const step = typeof data.step === "number" ? data.step : 0;
185
+ const out: ProviderTimelineItem[] = [];
186
+
187
+ const reasoning = content
188
+ .filter((block): block is Record<string, unknown> => isRecord(block) && block.type === "reasoning")
189
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
190
+ .filter((text) => text !== "")
191
+ .join("\n");
192
+ if (reasoning !== "") {
193
+ out.push(
194
+ ...this.#put({
195
+ type: "reasoning",
196
+ id: `reasoning:${turn}:${step}`,
197
+ text: reasoning,
198
+ }),
199
+ );
200
+ }
201
+
202
+ const text = textOf(content);
203
+ if (text !== "") {
204
+ out.push(
205
+ ...this.#put({
206
+ type: "assistant_message",
207
+ id: `assistant:${turn}:${step}`,
208
+ text,
209
+ ...(typeof message?.id === "string" ? { messageId: message.id } : {}),
210
+ }),
211
+ );
212
+ }
213
+
214
+ for (const block of content) {
215
+ if (!isRecord(block) || block.type !== "tool-call") continue;
216
+ const callId = stringField(block, "id") ?? `tool:${turn}:${step}`;
217
+ const name = stringField(block, "name") ?? "tool";
218
+ const input = parseArguments(block.arguments);
219
+ this.#toolNames.set(callId, name);
220
+ this.#toolInputs.set(callId, input);
221
+ out.push(...this.#emitToolCall(callId, name, input, "running"));
222
+ }
223
+ return out;
224
+ }
225
+
226
+ #toolCall(data: Record<string, unknown>): ProviderTimelineItem[] {
227
+ const callId = stringField(data, "callId");
228
+ if (callId === undefined) return [];
229
+ const name = stringField(data, "name") ?? "tool";
230
+ const input = parseArguments(data.arguments);
231
+ this.#toolNames.set(callId, name);
232
+ this.#toolInputs.set(callId, input);
233
+ const previous = this.#items.get(`tool:${callId}`);
234
+ const status = previous !== undefined && previous.type === "tool_call" ? previous.status : "running";
235
+ return this.#emitToolCall(callId, name, input, status === "running" ? "running" : status);
236
+ }
237
+
238
+ #toolResult(data: Record<string, unknown>): ProviderTimelineItem[] {
239
+ const message = isRecord(data.message) ? data.message : undefined;
240
+ const callId = stringField(data, "toolCallId") ?? (message === undefined ? undefined : stringField(message, "toolCallId"));
241
+ if (callId === undefined) return [];
242
+ const name = this.#toolNames.get(callId) ?? "tool";
243
+ const input = this.#toolInputs.get(callId) ?? {};
244
+ const output = message === undefined ? "" : textOf(message.content);
245
+ const failed = message?.isError === true;
246
+
247
+ const out: ProviderTimelineItem[] = [];
248
+ if (name === "todo_write" && !failed) {
249
+ const items = todoItems(input);
250
+ if (items !== null) {
251
+ out.push(...this.#put({ type: "todo", id: `todo:${callId}`, items }));
252
+ }
253
+ }
254
+ out.push(
255
+ ...this.#put({
256
+ type: "tool_call",
257
+ id: `tool:${callId}`,
258
+ callId,
259
+ name,
260
+ detail: toolDetail(name, input, output === "" ? undefined : output),
261
+ ...(failed
262
+ ? { status: "failed" as const, error: { message: output || "tool failed" } }
263
+ : { status: "completed" as const, error: null }),
264
+ }),
265
+ );
266
+ return out;
267
+ }
268
+
269
+ #turnEnd(data: Record<string, unknown>): ProviderTimelineItem[] {
270
+ const reason = isRecord(data.reason) ? data.reason : undefined;
271
+ if (reason?.kind !== "error" && reason?.kind !== "failed") return [];
272
+ const error = isRecord(reason.error) ? reason.error : undefined;
273
+ const message =
274
+ (error === undefined ? undefined : stringField(error, "message")) ?? "The turn failed.";
275
+ const turn = typeof data.turn === "number" ? data.turn : 0;
276
+ return this.#put({ type: "error", id: `error:${turn}`, message });
277
+ }
278
+
279
+ #emitToolCall(
280
+ callId: string,
281
+ name: string,
282
+ input: Record<string, unknown>,
283
+ status: "running" | "completed" | "failed" | "canceled",
284
+ ): ProviderTimelineItem[] {
285
+ const item: ProviderTimelineItem = {
286
+ type: "tool_call",
287
+ id: `tool:${callId}`,
288
+ callId,
289
+ name,
290
+ detail: toolDetail(name, input),
291
+ ...(status === "failed"
292
+ ? { status: "failed" as const, error: { message: "tool failed" } }
293
+ : { status, error: null }),
294
+ };
295
+ return this.#put(item);
296
+ }
297
+ }