opencode-ahp 0.0.0-stage → 0.1.1

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/bridge.ts ADDED
@@ -0,0 +1,722 @@
1
+ /**
2
+ * The opencode ⇄ AHP bridge (plan §6.1 bridge.ts) — the only opencode-
3
+ * aware module, kept pure: it receives the narrow `OpencodeFacade` that
4
+ * src/index.ts implements against the plugin `ctx`, and unit tests inject
5
+ * a fake.
6
+ *
7
+ * Phase 0: the `ahp-root://` catalog (providers as AgentInfo, opencode
8
+ * agents as AHP customizations — plan §14.7).
9
+ *
10
+ * Phase 1: the opencode session surface (create/list/get, prompt with
11
+ * delivery, switchAgent/switchModel, interrupt, permission replies, the
12
+ * mapped event stream) plus the initial-state builders and summary mappers
13
+ * the host uses to seed session/chat stores.
14
+ */
15
+ import { pathToFileURL } from "node:url";
16
+ import {
17
+ CustomizationLoadStatus,
18
+ CustomizationType,
19
+ MessageKind,
20
+ SessionLifecycle,
21
+ SessionStatus,
22
+ type AgentCustomization,
23
+ type AgentInfo,
24
+ type ChatSummary,
25
+ type ChatState,
26
+ type Customization,
27
+ type DirectoryCustomization,
28
+ type Message,
29
+ type SessionActiveClient,
30
+ type SessionState,
31
+ type SessionSummary,
32
+ type SessionModelInfo,
33
+ } from "@microsoft/agent-host-protocol";
34
+
35
+ export type ProviderActivation = "auto" | "enabled" | "disabled";
36
+
37
+ export interface FacadeModel {
38
+ providerID: string;
39
+ modelID: string;
40
+ name: string;
41
+ enabled: boolean;
42
+ limit: { context?: number; output?: number; input?: number };
43
+ /** ModelInfo.capabilities.input (e.g. ["text", "image"]). */
44
+ inputModalities: string[];
45
+ }
46
+
47
+ export interface FacadeProvider {
48
+ providerID: string;
49
+ name: string;
50
+ description?: string;
51
+ activation: ProviderActivation;
52
+ models: FacadeModel[];
53
+ }
54
+
55
+ /** The opencode agent modes (Agent.Info.mode). */
56
+ export type FacadeAgentMode = "primary" | "subagent" | "all";
57
+
58
+ /**
59
+ * Narrow opencode agent (plan §14.7 mapping table), from
60
+ * `ctx.agent.list()` → `Agent.Info[]`.
61
+ */
62
+ export interface FacadeAgent {
63
+ id: string;
64
+ name: string;
65
+ description?: string;
66
+ /** The `Model.Ref` the agent is pinned to; absent = inherit the session model. */
67
+ model?: { providerID: string; modelID: string };
68
+ mode: FacadeAgentMode;
69
+ /** Internal agents (summary/title/compaction/…) — never surfaced. */
70
+ hidden: boolean;
71
+ }
72
+
73
+ export interface FacadeModelRef {
74
+ providerID: string;
75
+ modelID: string;
76
+ variant?: string;
77
+ }
78
+
79
+ /** A narrow opencode session (`ctx.session.*` → `SessionInfo`). */
80
+ export interface FacadeSession {
81
+ sessionID: string;
82
+ title?: string;
83
+ agent?: string;
84
+ model?: FacadeModelRef;
85
+ archived?: boolean;
86
+ time: { created: number; updated: number };
87
+ }
88
+
89
+ /** `SessionPromptInput.delivery` (steer | queue; absent = default). */
90
+ export type FacadeDelivery = "steer" | "queue";
91
+
92
+ /** The decision values the host uses (`always` is out of MVP scope). */
93
+ export type FacadePermissionDecision = "once" | "reject";
94
+
95
+ /**
96
+ * A mapped opencode V2 event — the narrow, discriminated union the host's
97
+ * event pump consumes. `mapV2Event` is the only place that knows the raw
98
+ * wire shape; everything downstream works on this union.
99
+ */
100
+ export type FacadeEvent =
101
+ | { type: "session.created"; sessionID: string; title?: string; agent?: string; model?: FacadeModelRef }
102
+ | { type: "session.deleted"; sessionID: string }
103
+ | { type: "session.renamed"; sessionID: string; title: string }
104
+ | { type: "inbox.enqueued"; sessionID: string; inboxID: string; text: string; delivery: FacadeDelivery | "default" }
105
+ | { type: "inbox.delivered"; sessionID: string; inboxID: string }
106
+ | { type: "execution.started"; sessionID: string }
107
+ | { type: "execution.succeeded"; sessionID: string }
108
+ | { type: "execution.failed"; sessionID: string; error: { type: string; message: string } }
109
+ | { type: "execution.interrupted"; sessionID: string; reason: string }
110
+ | { type: "step.started"; sessionID: string; assistantMessageID: string; agent: string; model: FacadeModelRef }
111
+ | { type: "text.delta"; sessionID: string; assistantMessageID: string; ordinal: number; delta: string }
112
+ | { type: "text.ended"; sessionID: string; assistantMessageID: string; ordinal: number; text: string }
113
+ | { type: "reasoning.delta"; sessionID: string; assistantMessageID: string; ordinal: number; delta: string }
114
+ | { type: "reasoning.ended"; sessionID: string; assistantMessageID: string; ordinal: number; text: string }
115
+ | { type: "tool.input.started"; sessionID: string; assistantMessageID: string; id: string; name: string }
116
+ | { type: "tool.input.ended"; sessionID: string; assistantMessageID: string; id: string; text: string }
117
+ | { type: "tool.progress"; sessionID: string; id: string }
118
+ | { type: "tool.success"; sessionID: string; id: string; content: FacadeToolContent[]; executed?: boolean }
119
+ | { type: "tool.failed"; sessionID: string; id: string; error: { type: string; message: string }; executed?: boolean }
120
+ | { type: "usage.updated"; sessionID: string; tokens: FacadeTokens }
121
+ | {
122
+ type: "permission.asked";
123
+ sessionID: string;
124
+ id: string;
125
+ action: string;
126
+ message?: string;
127
+ /** Present when the permission was raised by a tool call (`id` = the tool call id). */
128
+ source?: { type: "tool"; messageID: string; id: string };
129
+ }
130
+ | { type: "permission.replied"; sessionID: string; requestID: string; reply: string };
131
+
132
+ export interface FacadeToolContent {
133
+ type: string;
134
+ text?: string;
135
+ data?: string;
136
+ contentType?: string;
137
+ }
138
+
139
+ export interface FacadeTokens {
140
+ input: number;
141
+ output: number;
142
+ reasoning: number;
143
+ cache: { read: number; write: number };
144
+ }
145
+
146
+ /**
147
+ * The narrow opencode surface the bridge needs. Implemented in
148
+ * src/index.ts against the plugin `ctx` (the only ctx call sites, plan
149
+ * §7 pure-module principle); a fake in unit tests.
150
+ *
151
+ * All methods are async: the catalog, agents, and sessions come from the
152
+ * registry/session read APIs, which the docs guarantee reflect every
153
+ * registration so far, including during plugin setup.
154
+ */
155
+ export interface OpencodeFacade {
156
+ /** Live provider/model catalog (plan §3.2: `ctx.provider` + `ctx.model`). */
157
+ listCatalog(): Promise<readonly FacadeProvider[]>;
158
+ /** Live opencode agents (plan §14.7: `ctx.agent.list()`). */
159
+ listAgents(): Promise<readonly FacadeAgent[]>;
160
+ // ── Phase 1: sessions ─────────────────────────────────────────────────
161
+ /**
162
+ * Create an opencode session. `id` is only passed through when it is a
163
+ * valid opencode SessionID (must start with "ses"); the host decides.
164
+ */
165
+ createSession(input?: {
166
+ id?: string;
167
+ title?: string;
168
+ agent?: string;
169
+ model?: FacadeModelRef;
170
+ }): Promise<FacadeSession>;
171
+ /** All opencode sessions for this location. */
172
+ listSessions(): Promise<readonly FacadeSession[]>;
173
+ /** One opencode session, or null when it does not exist. */
174
+ getSession(sessionID: string): Promise<FacadeSession | null>;
175
+ /**
176
+ * Send a prompt. `delivery` maps to `SessionPromptInput.delivery`
177
+ * ("steer" | "queue"); absent = the default (start or continue a turn).
178
+ * Resolves with the user message id opencode assigned.
179
+ */
180
+ prompt(input: { sessionID: string; text: string; delivery?: FacadeDelivery }): Promise<{ messageID: string }>;
181
+ switchModel(input: { sessionID: string; model: FacadeModelRef }): Promise<void>;
182
+ switchAgent(input: { sessionID: string; agent: string }): Promise<void>;
183
+ interrupt(input: { sessionID: string }): Promise<void>;
184
+ rename(input: { sessionID: string; title: string }): Promise<void>;
185
+ replyPermission(input: {
186
+ sessionID: string;
187
+ requestID: string;
188
+ decision: FacadePermissionDecision;
189
+ }): Promise<void>;
190
+ /**
191
+ * The mapped event stream. The host passes its pump AbortSignal; the
192
+ * iterator ends (without error) when the signal aborts.
193
+ */
194
+ events(signal: AbortSignal): AsyncIterable<FacadeEvent>;
195
+ }
196
+
197
+ // ── Phase 0: catalog mappers ─────────────────────────────────────────────
198
+
199
+ /**
200
+ * Stable synthetic AHP URI for an opencode agent (plan §14.7: file URIs
201
+ * are not available for config/built-in agents, and the URI only has to
202
+ * match between the customization tree and `Message.agent`).
203
+ */
204
+ export function agentUri(id: string): string {
205
+ return `opencode:agent/${id}`;
206
+ }
207
+
208
+ /** The opencode agent id behind a synthetic `opencode:agent/<id>` URI, or null. */
209
+ export function agentIDFromUri(uri: string): string | null {
210
+ return uri.startsWith("opencode:agent/") ? uri.slice("opencode:agent/".length) : null;
211
+ }
212
+
213
+ /**
214
+ * Map opencode agents to AHP `AgentCustomization` children
215
+ * (plan §14.7 mapping table):
216
+ * - `id` → `uri` (synthetic `opencode:agent/<id>`, stable per agent) and
217
+ * `id` (same value — the host is the minting publisher);
218
+ * - `hidden: true` agents are omitted (internal: summary/title/…);
219
+ * - pinned `model` → `<providerID>/<modelID>` — the same ref format as
220
+ * `SessionModelInfo.id`, so the pin resolves against the model picker;
221
+ * - `mode: "subagent"` → `disableUserInvocation: true` (delegatable, but
222
+ * not selectable in the user picker);
223
+ * - `permissions` have no AHP field — opencode enforces them itself.
224
+ */
225
+ export function mapAgentCustomizations(agents: readonly FacadeAgent[]): AgentCustomization[] {
226
+ const out: AgentCustomization[] = [];
227
+ for (const agent of agents) {
228
+ if (agent.hidden) continue;
229
+ const uri = agentUri(agent.id);
230
+ const child: AgentCustomization = {
231
+ type: CustomizationType.Agent,
232
+ id: uri,
233
+ uri,
234
+ name: agent.name,
235
+ };
236
+ if (agent.description !== undefined) child.description = agent.description;
237
+ if (agent.model !== undefined) child.model = `${agent.model.providerID}/${agent.model.modelID}`;
238
+ if (agent.mode === "subagent") child.disableUserInvocation = true;
239
+ out.push(child);
240
+ }
241
+ return out;
242
+ }
243
+
244
+ /**
245
+ * The workspace directory container that carries the agent children.
246
+ * Attached to every `AgentInfo.customizations` (feeds the Agents
247
+ * window's agent picker before any session exists) and to live
248
+ * `SessionState.customizations` (the picker reads session-state
249
+ * customizations — the root-cause fix for the empty dropdown, 2026-11-08).
250
+ * `writable: false` — clients never write agents into the
251
+ * workspace through this host.
252
+ */
253
+ export function agentDirectoryCustomization(
254
+ directory: string,
255
+ agents: readonly FacadeAgent[],
256
+ ): DirectoryCustomization {
257
+ const name = directory.split(/[\\/]/).filter(Boolean).pop() ?? "workspace";
258
+ return {
259
+ type: CustomizationType.Directory,
260
+ id: `opencode:directory:${directory}`,
261
+ uri: pathToFileURL(directory).href,
262
+ name,
263
+ enabled: true,
264
+ contents: CustomizationType.Agent,
265
+ writable: false,
266
+ load: { kind: CustomizationLoadStatus.Loaded },
267
+ children: mapAgentCustomizations(agents),
268
+ };
269
+ }
270
+
271
+ /**
272
+ * Map the opencode catalog to the AHP root state's `agents` list.
273
+ * Mapping locked 2026-11-07 (plan §14):
274
+ * - one AgentInfo per opencode provider;
275
+ * - providers with activation "disabled" are excluded;
276
+ * - models with enabled: false are excluded;
277
+ * - SessionModelInfo.id is a "<providerID>/<modelID>" ref;
278
+ * - maxContextWindow ← limit.context · maxOutputTokens ← limit.output
279
+ * · maxPromptTokens ← limit.input;
280
+ * - supportsVision ← capabilities.input contains "image".
281
+ *
282
+ * With opencode agents + a workspace directory (plan §14.7), every
283
+ * AgentInfo also carries the same workspace directory container with the
284
+ * agent children as `customizations` — omitted when there is no visible
285
+ * (non-hidden) agent, so the picker shows the generic provider default
286
+ * instead of an empty workspace entry.
287
+ */
288
+ export function mapCatalog(
289
+ providers: readonly FacadeProvider[],
290
+ agents: readonly FacadeAgent[] = [],
291
+ workspaceDirectory?: string,
292
+ ): AgentInfo[] {
293
+ const customizations =
294
+ workspaceDirectory !== undefined && mapAgentCustomizations(agents).length > 0
295
+ ? [agentDirectoryCustomization(workspaceDirectory, agents)]
296
+ : undefined;
297
+ const out: AgentInfo[] = [];
298
+ for (const provider of providers) {
299
+ if (provider.activation === "disabled") continue;
300
+ const models: SessionModelInfo[] = [];
301
+ for (const model of provider.models) {
302
+ if (!model.enabled) continue;
303
+ const info: SessionModelInfo = {
304
+ id: `${provider.providerID}/${model.modelID}`,
305
+ provider: provider.providerID,
306
+ name: model.name,
307
+ supportsVision: model.inputModalities.includes("image"),
308
+ };
309
+ if (model.limit.context !== undefined) info.maxContextWindow = model.limit.context;
310
+ if (model.limit.output !== undefined) info.maxOutputTokens = model.limit.output;
311
+ if (model.limit.input !== undefined) info.maxPromptTokens = model.limit.input;
312
+ models.push(info);
313
+ }
314
+ out.push({
315
+ provider: provider.providerID,
316
+ displayName: provider.name,
317
+ description: provider.description ?? provider.name,
318
+ models,
319
+ ...(customizations !== undefined ? { customizations } : {}),
320
+ });
321
+ }
322
+ return out;
323
+ }
324
+
325
+ // ── Phase 1: event mapping ───────────────────────────────────────────────
326
+
327
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
328
+
329
+ function str(v: unknown): string | undefined {
330
+ return typeof v === "string" && v.length > 0 ? v : undefined;
331
+ }
332
+
333
+ function num(v: unknown): number | undefined {
334
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
335
+ }
336
+
337
+ /**
338
+ * Map a raw opencode V2 event (`{id, type, data}` — the fixture shape) to
339
+ * the narrow `FacadeEvent` union, or null when the event carries nothing
340
+ * the AHP host needs. Unknown types map to null (log-and-continue).
341
+ */
342
+ export function mapV2Event(raw: unknown): FacadeEvent | null {
343
+ if (!isObj(raw)) return null;
344
+ const type = str(raw["type"]);
345
+ const data = isObj(raw["data"]) ? raw["data"] : {};
346
+ const sessionID = str(data["sessionID"]);
347
+ if (type === undefined || sessionID === undefined) return null;
348
+
349
+ switch (type) {
350
+ case "session.created":
351
+ return {
352
+ type: "session.created",
353
+ sessionID,
354
+ title: str(data["title"]),
355
+ agent: str(data["agent"]),
356
+ model: mapModelRef(data["model"]),
357
+ };
358
+ case "session.deleted":
359
+ return { type: "session.deleted", sessionID };
360
+ case "session.renamed": {
361
+ const title = str(data["title"]);
362
+ return title !== undefined ? { type: "session.renamed", sessionID, title } : null;
363
+ }
364
+ case "session.inbox.enqueued": {
365
+ const inboxID = str(data["inboxID"]);
366
+ const item = isObj(data["item"]) ? data["item"] : undefined;
367
+ const payload = item !== undefined && isObj(item["payload"]) ? item["payload"] : undefined;
368
+ const text = payload !== undefined ? str(payload["text"]) : undefined;
369
+ if (inboxID === undefined || text === undefined) return null;
370
+ const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
371
+ return {
372
+ type: "inbox.enqueued",
373
+ sessionID,
374
+ inboxID,
375
+ text,
376
+ delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
377
+ };
378
+ }
379
+ case "session.inbox.delivered": {
380
+ const inboxID = str(data["inboxID"]);
381
+ return inboxID !== undefined ? { type: "inbox.delivered", sessionID, inboxID } : null;
382
+ }
383
+ case "session.execution.started":
384
+ return { type: "execution.started", sessionID };
385
+ case "session.execution.succeeded":
386
+ return { type: "execution.succeeded", sessionID };
387
+ case "session.execution.failed": {
388
+ const error = isObj(data["error"]) ? data["error"] : undefined;
389
+ return {
390
+ type: "execution.failed",
391
+ sessionID,
392
+ error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
393
+ };
394
+ }
395
+ case "session.execution.interrupted":
396
+ return { type: "execution.interrupted", sessionID, reason: str(data["reason"]) ?? "user" };
397
+ case "session.step.started": {
398
+ const assistantMessageID = str(data["assistantMessageID"]);
399
+ const model = mapModelRef(data["model"]);
400
+ if (assistantMessageID === undefined || model === undefined) return null;
401
+ return {
402
+ type: "step.started",
403
+ sessionID,
404
+ assistantMessageID,
405
+ agent: str(data["agent"]) ?? "build",
406
+ model,
407
+ };
408
+ }
409
+ case "session.text.delta":
410
+ case "session.reasoning.delta": {
411
+ const assistantMessageID = str(data["assistantMessageID"]);
412
+ const delta = str(data["delta"]);
413
+ const ordinal = num(data["ordinal"]);
414
+ if (assistantMessageID === undefined || delta === undefined || ordinal === undefined) return null;
415
+ return {
416
+ type: type === "session.text.delta" ? "text.delta" : "reasoning.delta",
417
+ sessionID,
418
+ assistantMessageID,
419
+ ordinal,
420
+ delta,
421
+ };
422
+ }
423
+ case "session.text.ended":
424
+ case "session.reasoning.ended": {
425
+ const assistantMessageID = str(data["assistantMessageID"]);
426
+ const text = str(data["text"]);
427
+ const ordinal = num(data["ordinal"]);
428
+ if (assistantMessageID === undefined || text === undefined || ordinal === undefined) return null;
429
+ return {
430
+ type: type === "session.text.ended" ? "text.ended" : "reasoning.ended",
431
+ sessionID,
432
+ assistantMessageID,
433
+ ordinal,
434
+ text,
435
+ };
436
+ }
437
+ case "session.tool.input.started": {
438
+ const id = str(data["id"]);
439
+ const name = str(data["name"]);
440
+ const assistantMessageID = str(data["assistantMessageID"]);
441
+ if (id === undefined || name === undefined || assistantMessageID === undefined) return null;
442
+ return { type: "tool.input.started", sessionID, assistantMessageID, id, name };
443
+ }
444
+ case "session.tool.input.ended": {
445
+ const id = str(data["id"]);
446
+ const text = str(data["text"]);
447
+ const assistantMessageID = str(data["assistantMessageID"]);
448
+ if (id === undefined || text === undefined || assistantMessageID === undefined) return null;
449
+ return { type: "tool.input.ended", sessionID, assistantMessageID, id, text };
450
+ }
451
+ case "session.tool.progress": {
452
+ const id = str(data["id"]);
453
+ return id !== undefined ? { type: "tool.progress", sessionID, id } : null;
454
+ }
455
+ case "session.tool.success": {
456
+ const id = str(data["id"]);
457
+ if (id === undefined) return null;
458
+ const content = Array.isArray(data["content"])
459
+ ? (data["content"] as unknown[]).map((c) => (isObj(c) ? mapToolContent(c) : undefined)).filter((c): c is FacadeToolContent => c !== undefined)
460
+ : [];
461
+ return { type: "tool.success", sessionID, id, content, executed: data["executed"] === true };
462
+ }
463
+ case "session.tool.failed": {
464
+ const id = str(data["id"]);
465
+ const error = isObj(data["error"]) ? data["error"] : undefined;
466
+ if (id === undefined) return null;
467
+ return {
468
+ type: "tool.failed",
469
+ sessionID,
470
+ id,
471
+ error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
472
+ executed: data["executed"] === true,
473
+ };
474
+ }
475
+ case "session.usage.updated": {
476
+ const tokens = isObj(data["tokens"]) ? data["tokens"] : undefined;
477
+ if (tokens === undefined) return null;
478
+ const cache = isObj(tokens["cache"]) ? tokens["cache"] : undefined;
479
+ return {
480
+ type: "usage.updated",
481
+ sessionID,
482
+ tokens: {
483
+ input: num(tokens["input"]) ?? 0,
484
+ output: num(tokens["output"]) ?? 0,
485
+ reasoning: num(tokens["reasoning"]) ?? 0,
486
+ cache: { read: cache !== undefined ? (num(cache["read"]) ?? 0) : 0, write: cache !== undefined ? (num(cache["write"]) ?? 0) : 0 },
487
+ },
488
+ };
489
+ }
490
+ case "permission.asked": {
491
+ const id = str(data["id"]);
492
+ if (id === undefined) return null;
493
+ const source = isObj(data["source"]) && data["source"]["type"] === "tool" && str(data["source"]["id"]) !== undefined
494
+ ? {
495
+ type: "tool" as const,
496
+ messageID: str(data["source"]["messageID"]) ?? "",
497
+ id: str(data["source"]["id"]) as string,
498
+ }
499
+ : undefined;
500
+ return {
501
+ type: "permission.asked",
502
+ sessionID,
503
+ id,
504
+ action: str(data["action"]) ?? "",
505
+ message: str(data["message"]),
506
+ source,
507
+ };
508
+ }
509
+ case "permission.replied": {
510
+ const requestID = str(data["requestID"]);
511
+ const reply = str(data["reply"]);
512
+ return requestID !== undefined && reply !== undefined
513
+ ? { type: "permission.replied", sessionID, requestID, reply }
514
+ : null;
515
+ }
516
+ default:
517
+ return null;
518
+ }
519
+ }
520
+
521
+ function mapModelRef(v: unknown): FacadeModelRef | undefined {
522
+ if (!isObj(v)) return undefined;
523
+ const id = str(v["id"]);
524
+ const providerID = str(v["providerID"]);
525
+ if (id === undefined || providerID === undefined) return undefined;
526
+ const variant = str(v["variant"]);
527
+ return variant !== undefined ? { providerID, modelID: id, variant } : { providerID, modelID: id };
528
+ }
529
+
530
+ function mapToolContent(c: Record<string, unknown>): FacadeToolContent | undefined {
531
+ const t = str(c["type"]);
532
+ if (t === undefined) return undefined;
533
+ if (t === "text") {
534
+ return { type: t, text: str(c["text"]) ?? "" };
535
+ }
536
+ if (t === "file" || t === "patch") {
537
+ return { type: t, text: str(c["text"]) ?? str(c["patch"]) ?? "" };
538
+ }
539
+ return undefined;
540
+ }
541
+
542
+ // ── Phase 1: state builders & summary mappers ────────────────────────────
543
+
544
+ const STATUS_IDLE_READ = (SessionStatus.Idle | SessionStatus.IsRead) as SessionStatus;
545
+
546
+ /**
547
+ * The `<providerID>/<modelID>` ref of a FacadeModelRef (the
548
+ * `SessionModelInfo.id` format), or null when absent.
549
+ */
550
+ export function modelRefString(model?: FacadeModelRef): string | null {
551
+ return model !== undefined ? `${model.providerID}/${model.modelID}` : null;
552
+ }
553
+
554
+ /**
555
+ * Initial `SessionState` for a new or lazily-registered opencode session.
556
+ * `status` starts at `Idle | IsRead` (33) — the session reducer can only
557
+ * move the read/archive/input-needed bits, so the *activity* source of
558
+ * truth is the chat status (synced via `session/chatUpdated`, plan §14.9).
559
+ * `customizations` carries the workspace agent directory container — the
560
+ * same one the root catalog builds — because VS Code's agent dropdown reads
561
+ * `SessionState.customizations` (root-state customizations are NOT read).
562
+ */
563
+ export function initialSessionState(input: {
564
+ sessionID: string;
565
+ provider: string;
566
+ title: string;
567
+ activeClients?: SessionActiveClient[];
568
+ customizations?: Customization[];
569
+ status?: SessionStatus;
570
+ }): SessionState {
571
+ return {
572
+ provider: input.provider,
573
+ title: input.title,
574
+ status: input.status ?? STATUS_IDLE_READ,
575
+ lifecycle: SessionLifecycle.Creating,
576
+ activeClients: input.activeClients ?? [],
577
+ chats: [],
578
+ defaultChat: undefined,
579
+ ...(input.customizations !== undefined && input.customizations.length > 0
580
+ ? { customizations: input.customizations }
581
+ : {}),
582
+ };
583
+ }
584
+
585
+ /** Initial `ChatState` for a session's single default chat. */
586
+ export function initialChatState(input: {
587
+ resource: string;
588
+ title: string;
589
+ modifiedAt: string;
590
+ }): ChatState {
591
+ return {
592
+ resource: input.resource,
593
+ title: input.title,
594
+ status: STATUS_IDLE_READ,
595
+ modifiedAt: input.modifiedAt,
596
+ turns: [],
597
+ };
598
+ }
599
+
600
+ /** The denormalized `ChatSummary` view of a chat state. */
601
+ export function chatSummaryOf(chat: ChatState): ChatSummary {
602
+ const summary: ChatSummary = {
603
+ resource: chat.resource,
604
+ title: chat.title,
605
+ status: chat.status,
606
+ modifiedAt: chat.modifiedAt,
607
+ };
608
+ if (chat.activity !== undefined) summary.activity = chat.activity;
609
+ return summary;
610
+ }
611
+
612
+ /** The user-origin AHP `Message` for a plain text prompt. */
613
+ export function userMessage(text: string, model?: string, agentUri?: string): Message {
614
+ const message: Message = { text, origin: { kind: MessageKind.User } };
615
+ if (model !== undefined) message.model = { id: model };
616
+ if (agentUri !== undefined) message.agent = { uri: agentUri };
617
+ return message;
618
+ }
619
+
620
+ /**
621
+ * Build the `SessionSummary` for root notifications / `listSessions` from
622
+ * a live record's denormalized fields.
623
+ */
624
+ export function buildSessionSummary(input: {
625
+ channel: string;
626
+ provider: string;
627
+ title: string;
628
+ status: SessionStatus;
629
+ activity?: string;
630
+ createdAt: string;
631
+ modifiedAt: string;
632
+ chat: ChatSummary;
633
+ defaultChat: string;
634
+ }): SessionSummary {
635
+ return {
636
+ resource: input.channel,
637
+ provider: input.provider,
638
+ title: input.title,
639
+ status: input.status,
640
+ ...(input.activity !== undefined ? { activity: input.activity } : {}),
641
+ createdAt: input.createdAt,
642
+ modifiedAt: input.modifiedAt,
643
+ chats: [input.chat],
644
+ defaultChat: input.defaultChat,
645
+ };
646
+ }
647
+
648
+ /**
649
+ * Human-readable display name for an opencode tool (opencode ships no
650
+ * display names; the names are lowercase identifiers like `shell`).
651
+ */
652
+ export function displayNameFor(toolName: string): string {
653
+ const known: Record<string, string> = {
654
+ shell: "Shell",
655
+ bash: "Shell",
656
+ read: "Read file",
657
+ write: "Write file",
658
+ edit: "Edit file",
659
+ apply: "Apply patch",
660
+ glob: "Search files",
661
+ grep: "Search content",
662
+ webfetch: "Fetch URL",
663
+ websearch: "Web search",
664
+ task: "Task",
665
+ todowrite: "Todo",
666
+ todoread: "Todo",
667
+ };
668
+ return known[toolName] ?? toolName.charAt(0).toUpperCase() + toolName.slice(1);
669
+ }
670
+
671
+ function jsonValue(v: unknown): string | null {
672
+ if (typeof v === "string") return v;
673
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
674
+ return null;
675
+ }
676
+
677
+ /**
678
+ * A present-tense, human-readable description of what a tool call will do
679
+ * (the AHP `invocationMessage`), derived from the (JSON-string) input.
680
+ * `shell`/`bash` → the command; file/url tools → the target; fallback →
681
+ * the tool name.
682
+ */
683
+ export function invocationMessageFor(toolName: string, inputText: string | undefined): string {
684
+ let input: Record<string, unknown> | undefined;
685
+ if (inputText !== undefined && inputText.length > 0) {
686
+ try {
687
+ const parsed: unknown = JSON.parse(inputText);
688
+ if (isObj(parsed)) input = parsed;
689
+ } catch {
690
+ input = undefined;
691
+ }
692
+ }
693
+ const first =
694
+ (input !== undefined
695
+ ? [
696
+ jsonValue(input["command"]),
697
+ jsonValue(input["cmd"]),
698
+ jsonValue(input["path"]),
699
+ jsonValue(input["file"]),
700
+ jsonValue(input["filePath"]),
701
+ jsonValue(input["url"]),
702
+ ].find((v) => v !== null)
703
+ : undefined) ?? null;
704
+ if (first !== null) {
705
+ return toolName === "shell" || toolName === "bash" ? `Run \`${first}\`` : first;
706
+ }
707
+ return displayNameFor(toolName);
708
+ }
709
+
710
+ /**
711
+ * Past-tense variant for `ToolCallResult.pastTenseMessage`
712
+ * ("Ran `cmd`", the file/url target, or the tool name).
713
+ */
714
+ export function pastTenseMessageFor(toolName: string, inputText: string | undefined): string {
715
+ const msg = invocationMessageFor(toolName, inputText);
716
+ if (msg.startsWith("Run `")) return msg.replace(/^Run /, "Ran ");
717
+ if (msg === displayNameFor(toolName)) {
718
+ const known: Record<string, string> = { Shell: "Ran shell command" };
719
+ return known[msg] ?? `Ran ${toolName}`;
720
+ }
721
+ return msg;
722
+ }