opencode-ahp 0.1.4 → 0.1.6
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/README.md +91 -37
- package/options.example.jsonc +25 -8
- package/package.json +1 -1
- package/src/bridge.ts +335 -127
- package/src/channels.ts +74 -32
- package/src/client-tools.ts +127 -0
- package/src/handshake.ts +2 -3
- package/src/host-base.ts +335 -0
- package/src/host-changesets.ts +381 -0
- package/src/host-chats.ts +300 -0
- package/src/host-client-tools.ts +205 -0
- package/src/host-dispatch.ts +593 -0
- package/src/host-errors.ts +29 -0
- package/src/host-events.ts +386 -0
- package/src/host-rpc.ts +435 -0
- package/src/host-sessions.ts +558 -0
- package/src/host-terminals.ts +654 -0
- package/src/host-turns.ts +82 -0
- package/src/host-types.ts +225 -0
- package/src/host-util.ts +194 -0
- package/src/host.ts +23 -2299
- package/src/index.ts +265 -33
- package/src/keep-alive.ts +3 -3
- package/src/options.ts +23 -9
- package/src/seq.ts +4 -5
- package/src/state.ts +40 -6
- package/src/transport.ts +6 -6
package/src/bridge.ts
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The opencode ⇄ AHP bridge
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* a fake.
|
|
2
|
+
* The opencode ⇄ AHP bridge — the only opencode-aware module, kept pure:
|
|
3
|
+
* it receives the narrow `OpencodeFacade` that src/index.ts implements
|
|
4
|
+
* against the plugin `ctx`, and unit tests inject a fake.
|
|
6
5
|
*
|
|
7
|
-
*
|
|
8
|
-
* agents as AHP customizations
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* mapped event stream) plus the initial-state builders and summary mappers
|
|
13
|
-
* the host uses to seed session/chat stores.
|
|
6
|
+
* Surfaces: the `ahp-root://` catalog (providers as AgentInfo, opencode
|
|
7
|
+
* agents as AHP customizations); the opencode session surface (create/
|
|
8
|
+
* list/get, prompt with delivery, switchAgent/switchModel, interrupt,
|
|
9
|
+
* permission replies, the mapped event stream); and the initial-state
|
|
10
|
+
* builders and summary mappers the host uses to seed session/chat stores.
|
|
14
11
|
*/
|
|
15
12
|
import { pathToFileURL } from "node:url";
|
|
16
13
|
import { sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "./channels.js";
|
|
@@ -63,8 +60,7 @@ export interface FacadeProvider {
|
|
|
63
60
|
export type FacadeAgentMode = "primary" | "subagent" | "all";
|
|
64
61
|
|
|
65
62
|
/**
|
|
66
|
-
* Narrow opencode agent
|
|
67
|
-
* `ctx.agent.list()` → `Agent.Info[]`.
|
|
63
|
+
* Narrow opencode agent, from `ctx.agent.list()` → `Agent.Info[]`.
|
|
68
64
|
*/
|
|
69
65
|
export interface FacadeAgent {
|
|
70
66
|
id: string;
|
|
@@ -91,12 +87,18 @@ export interface FacadeSession {
|
|
|
91
87
|
model?: FacadeModelRef;
|
|
92
88
|
archived?: boolean;
|
|
93
89
|
time: { created: number; updated: number };
|
|
90
|
+
/**
|
|
91
|
+
* Durable, core-opaque session metadata. The host uses
|
|
92
|
+
* one key — `opencode-ahp` — to make the peer-chat binding survive a
|
|
93
|
+
* restart; everything else is passed through opaquely.
|
|
94
|
+
*/
|
|
95
|
+
metadata?: Record<string, unknown>;
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
/** `SessionPromptInput.delivery` (steer | queue; absent = default). */
|
|
97
99
|
export type FacadeDelivery = "steer" | "queue";
|
|
98
100
|
|
|
99
|
-
/** The decision values the host uses (`always` is
|
|
101
|
+
/** The decision values the host uses (`always` is not implemented). */
|
|
100
102
|
export type FacadePermissionDecision = "once" | "reject";
|
|
101
103
|
|
|
102
104
|
/**
|
|
@@ -150,21 +152,39 @@ export interface FacadeTokens {
|
|
|
150
152
|
cache: { read: number; write: number };
|
|
151
153
|
}
|
|
152
154
|
|
|
155
|
+
/**
|
|
156
|
+
* The classified result of one raw opencode V2 event (event capture,
|
|
157
|
+
* design §8.1):
|
|
158
|
+
* - `ok` — mapped into the narrow `FacadeEvent` union;
|
|
159
|
+
* - `dropped` — a known type whose instance carries nothing usable
|
|
160
|
+
* (`reason` names the missing fields), or a malformed envelope
|
|
161
|
+
* (not an object, missing `type`/`sessionID`);
|
|
162
|
+
* - `unimplemented` — an event type the host has no handler for.
|
|
163
|
+
*
|
|
164
|
+
* `mapV2Event` is the thin `ok → event, else null` wrapper over this;
|
|
165
|
+
* src/index.ts's events() generator uses the full outcome for the
|
|
166
|
+
* timestamped capture lines.
|
|
167
|
+
*/
|
|
168
|
+
export type V2EventOutcome =
|
|
169
|
+
| { status: "ok"; event: FacadeEvent }
|
|
170
|
+
| { status: "dropped"; type: string; reason: string }
|
|
171
|
+
| { status: "unimplemented"; type: string };
|
|
172
|
+
|
|
153
173
|
/**
|
|
154
174
|
* The narrow opencode surface the bridge needs. Implemented in
|
|
155
|
-
* src/index.ts against the plugin `ctx` (the only ctx call sites
|
|
156
|
-
*
|
|
175
|
+
* src/index.ts against the plugin `ctx` (the only ctx call sites — this
|
|
176
|
+
* module stays pure); a fake in unit tests.
|
|
157
177
|
*
|
|
158
178
|
* All methods are async: the catalog, agents, and sessions come from the
|
|
159
179
|
* registry/session read APIs, which the docs guarantee reflect every
|
|
160
180
|
* registration so far, including during plugin setup.
|
|
161
181
|
*/
|
|
162
182
|
export interface OpencodeFacade {
|
|
163
|
-
/** Live provider/model catalog (
|
|
183
|
+
/** Live provider/model catalog (`ctx.provider` + `ctx.model`). */
|
|
164
184
|
listCatalog(): Promise<readonly FacadeProvider[]>;
|
|
165
|
-
/** Live opencode agents (
|
|
185
|
+
/** Live opencode agents (`ctx.agent.list()`). */
|
|
166
186
|
listAgents(): Promise<readonly FacadeAgent[]>;
|
|
167
|
-
// ──
|
|
187
|
+
// ── sessions ─────────────────────────────────────────────────
|
|
168
188
|
/**
|
|
169
189
|
* Create an opencode session. `id` is only passed through when it is a
|
|
170
190
|
* valid opencode SessionID (must start with "ses"); the host decides.
|
|
@@ -174,11 +194,19 @@ export interface OpencodeFacade {
|
|
|
174
194
|
title?: string;
|
|
175
195
|
agent?: string;
|
|
176
196
|
model?: FacadeModelRef;
|
|
197
|
+
/** Durable session metadata — the host's chat-binding marker rides here. */
|
|
198
|
+
metadata?: Record<string, unknown>;
|
|
177
199
|
}): Promise<FacadeSession>;
|
|
178
200
|
/** All opencode sessions for this location. */
|
|
179
201
|
listSessions(): Promise<readonly FacadeSession[]>;
|
|
180
202
|
/** One opencode session, or null when it does not exist. */
|
|
181
203
|
getSession(sessionID: string): Promise<FacadeSession | null>;
|
|
204
|
+
/**
|
|
205
|
+
* Remove an opencode session (`ctx.session.remove`). `disposeChat`
|
|
206
|
+
* removes a chat's backend session, and record removal disposes the
|
|
207
|
+
* peer-chat backends (multi-chat: one AHP chat per opencode session).
|
|
208
|
+
*/
|
|
209
|
+
removeSession(sessionID: string): Promise<void>;
|
|
182
210
|
/**
|
|
183
211
|
* Send a prompt. `delivery` maps to `SessionPromptInput.delivery`
|
|
184
212
|
* ("steer" | "queue"); absent = the default (start or continue a turn).
|
|
@@ -199,7 +227,7 @@ export interface OpencodeFacade {
|
|
|
199
227
|
* iterator ends (without error) when the signal aborts.
|
|
200
228
|
*/
|
|
201
229
|
events(signal: AbortSignal): AsyncIterable<FacadeEvent>;
|
|
202
|
-
// ──
|
|
230
|
+
// ── changesets ───────────────────────────────────────────────
|
|
203
231
|
/**
|
|
204
232
|
* Working-tree diff vs HEAD (uncommitted changes, untracked files
|
|
205
233
|
* included), with **absolute** file paths. `[]` when the location is
|
|
@@ -223,8 +251,47 @@ export interface OpencodeFacade {
|
|
|
223
251
|
* (fallback delete), untracked → delete.
|
|
224
252
|
*/
|
|
225
253
|
discardFile(absPath: string): Promise<void>;
|
|
254
|
+
// ── client-provided tools ─────────────────────────
|
|
255
|
+
/**
|
|
256
|
+
* Replace the location's registered client tools with `tools` (the
|
|
257
|
+
* cross-session union of every AHP session's active-client tools;
|
|
258
|
+
* `[]` when none). The implementation applies them to the opencode
|
|
259
|
+
* tool registry (`ctx.tool.transform` + `ctx.tool.reload`) — the
|
|
260
|
+
* registered tools' `execute` routes back to the host.
|
|
261
|
+
*/
|
|
262
|
+
syncClientTools(tools: readonly FacadeClientTool[]): Promise<void>;
|
|
226
263
|
}
|
|
227
264
|
|
|
265
|
+
/**
|
|
266
|
+
* A client-provided tool in its opencode-registration form (the host
|
|
267
|
+
* derives it from the AHP `ToolDefinition`s — `inputSchema` already
|
|
268
|
+
* normalized to an object JSON Schema, `description` already defaulted).
|
|
269
|
+
*/
|
|
270
|
+
export interface FacadeClientTool {
|
|
271
|
+
name: string;
|
|
272
|
+
description: string;
|
|
273
|
+
/** Object JSON Schema for the tool input (raw — opencode passes it through). */
|
|
274
|
+
inputSchema: Record<string, unknown>;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* The settled result of a client-executed tool call, as the opencode
|
|
279
|
+
* `execute` bridge consumes it: `ok` → a `Tool.Result` (the client's
|
|
280
|
+
* `toolCallComplete` content, text blocks joined), not-ok → a thrown
|
|
281
|
+
* `Tool.Error`.
|
|
282
|
+
*/
|
|
283
|
+
export type FacadeClientToolResult =
|
|
284
|
+
| {
|
|
285
|
+
ok: true;
|
|
286
|
+
/** The client's past-tense message (`ToolCallResult.pastTenseMessage`). */
|
|
287
|
+
pastTenseMessage: string;
|
|
288
|
+
/** The client's text content blocks, joined (absent when none). */
|
|
289
|
+
content?: string;
|
|
290
|
+
/** The client's structured content, verbatim. */
|
|
291
|
+
structuredContent?: Record<string, unknown>;
|
|
292
|
+
}
|
|
293
|
+
| { ok: false; error: string };
|
|
294
|
+
|
|
228
295
|
/**
|
|
229
296
|
* One entry of a VCS working-tree diff (the facade's shape — absolute
|
|
230
297
|
* paths, unlike opencode's repo-root-relative `FileDiff.Info`).
|
|
@@ -236,12 +303,12 @@ export interface FacadeDiffFile {
|
|
|
236
303
|
status: "added" | "deleted" | "modified";
|
|
237
304
|
}
|
|
238
305
|
|
|
239
|
-
// ──
|
|
306
|
+
// ── catalog mappers ─────────────────────────────────────────────
|
|
240
307
|
|
|
241
308
|
/**
|
|
242
|
-
* Stable synthetic AHP URI for an opencode agent (
|
|
243
|
-
*
|
|
244
|
-
*
|
|
309
|
+
* Stable synthetic AHP URI for an opencode agent (file URIs are not
|
|
310
|
+
* available for config/built-in agents, and the URI only has to match
|
|
311
|
+
* between the customization tree and `Message.agent`).
|
|
245
312
|
*/
|
|
246
313
|
export function agentUri(id: string): string {
|
|
247
314
|
return `opencode:agent/${id}`;
|
|
@@ -253,8 +320,7 @@ export function agentIDFromUri(uri: string): string | null {
|
|
|
253
320
|
}
|
|
254
321
|
|
|
255
322
|
/**
|
|
256
|
-
* Map opencode agents to AHP `AgentCustomization` children
|
|
257
|
-
* (plan §14.7 mapping table):
|
|
323
|
+
* Map opencode agents to AHP `AgentCustomization` children:
|
|
258
324
|
* - `id` → `uri` (synthetic `opencode:agent/<id>`, stable per agent) and
|
|
259
325
|
* `id` (same value — the host is the minting publisher);
|
|
260
326
|
* - `hidden: true` agents are omitted (internal: summary/title/…);
|
|
@@ -312,7 +378,7 @@ export function agentDirectoryCustomization(
|
|
|
312
378
|
|
|
313
379
|
/**
|
|
314
380
|
* Map the opencode catalog to the AHP root state's `agents` list.
|
|
315
|
-
* Mapping locked 2026-11-07
|
|
381
|
+
* Mapping locked 2026-11-07:
|
|
316
382
|
* - one AgentInfo per opencode provider;
|
|
317
383
|
* - providers with activation "disabled" are excluded;
|
|
318
384
|
* - models with enabled: false are excluded;
|
|
@@ -321,7 +387,7 @@ export function agentDirectoryCustomization(
|
|
|
321
387
|
* · maxPromptTokens ← limit.input;
|
|
322
388
|
* - supportsVision ← capabilities.input contains "image".
|
|
323
389
|
*
|
|
324
|
-
* With opencode agents + a workspace directory
|
|
390
|
+
* With opencode agents + a workspace directory, every
|
|
325
391
|
* AgentInfo also carries the same workspace directory container with the
|
|
326
392
|
* agent children as `customizations` — omitted when there is no visible
|
|
327
393
|
* (non-hidden) agent, so the picker shows the generic provider default
|
|
@@ -358,13 +424,19 @@ export function mapCatalog(
|
|
|
358
424
|
displayName: provider.name,
|
|
359
425
|
description: provider.description ?? provider.name,
|
|
360
426
|
models,
|
|
427
|
+
// Multi-chat: advertise plain multipleChats.
|
|
428
|
+
// No `fork`/`sideChat` sub-caps — the opencode plugin surface has
|
|
429
|
+
// no fork API in 2.2.6, so conformant clients (VS Code gates its
|
|
430
|
+
// UI on these) will never attempt the unsupported source forms.
|
|
431
|
+
// No `multipleWorkingDirectories` either (a location is one dir).
|
|
432
|
+
capabilities: { multipleChats: {} },
|
|
361
433
|
...(customizations !== undefined ? { customizations } : {}),
|
|
362
434
|
});
|
|
363
435
|
}
|
|
364
436
|
return out;
|
|
365
437
|
}
|
|
366
438
|
|
|
367
|
-
// ──
|
|
439
|
+
// ── event mapping ───────────────────────────────────────────────
|
|
368
440
|
|
|
369
441
|
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
|
|
370
442
|
|
|
@@ -376,76 +448,103 @@ function num(v: unknown): number | undefined {
|
|
|
376
448
|
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
377
449
|
}
|
|
378
450
|
|
|
451
|
+
/** "a, b" — the names of the undefined values (drop reasons). */
|
|
452
|
+
function missingOf(vals: Record<string, unknown>): string {
|
|
453
|
+
return Object.keys(vals).filter((k) => vals[k] === undefined).join(", ");
|
|
454
|
+
}
|
|
455
|
+
|
|
379
456
|
/**
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
457
|
+
* Classify a raw opencode V2 event (`{id, type, data}` — the fixture
|
|
458
|
+
* shape) — `mapV2Event` is the thin `ok → event, else null` wrapper
|
|
459
|
+
* over this, and the timestamped capture lines (design §8.1) are
|
|
460
|
+
* formatted from the full outcome. Unknown types classify as
|
|
461
|
+
* `unimplemented` (log-and-continue, as before).
|
|
383
462
|
*/
|
|
384
|
-
export function
|
|
385
|
-
if (!isObj(raw)) return
|
|
463
|
+
export function mapV2EventRaw(raw: unknown): V2EventOutcome {
|
|
464
|
+
if (!isObj(raw)) return { status: "dropped", type: "?", reason: "not an event envelope" };
|
|
386
465
|
const type = str(raw["type"]);
|
|
466
|
+
if (type === undefined) return { status: "dropped", type: "?", reason: "missing: type" };
|
|
387
467
|
const data = isObj(raw["data"]) ? raw["data"] : {};
|
|
388
468
|
const sessionID = str(data["sessionID"]);
|
|
389
|
-
if (
|
|
469
|
+
if (sessionID === undefined) return { status: "dropped", type, reason: "missing: sessionID" };
|
|
470
|
+
|
|
471
|
+
/** The `dropped` outcome for missing fields inside a known type. */
|
|
472
|
+
const drop = (fields: string): V2EventOutcome => ({ status: "dropped", type, reason: `missing: ${fields}` });
|
|
390
473
|
|
|
391
474
|
switch (type) {
|
|
392
475
|
case "session.created":
|
|
393
476
|
return {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
477
|
+
status: "ok",
|
|
478
|
+
event: {
|
|
479
|
+
type: "session.created",
|
|
480
|
+
sessionID,
|
|
481
|
+
title: str(data["title"]),
|
|
482
|
+
agent: str(data["agent"]),
|
|
483
|
+
model: mapModelRef(data["model"]),
|
|
484
|
+
},
|
|
399
485
|
};
|
|
400
486
|
case "session.deleted":
|
|
401
|
-
return { type: "session.deleted", sessionID };
|
|
487
|
+
return { status: "ok", event: { type: "session.deleted", sessionID } };
|
|
402
488
|
case "session.renamed": {
|
|
403
489
|
const title = str(data["title"]);
|
|
404
|
-
|
|
490
|
+
if (title === undefined) return drop("title");
|
|
491
|
+
return { status: "ok", event: { type: "session.renamed", sessionID, title } };
|
|
405
492
|
}
|
|
406
493
|
case "session.inbox.enqueued": {
|
|
407
494
|
const inboxID = str(data["inboxID"]);
|
|
408
495
|
const item = isObj(data["item"]) ? data["item"] : undefined;
|
|
409
496
|
const payload = item !== undefined && isObj(item["payload"]) ? item["payload"] : undefined;
|
|
410
497
|
const text = payload !== undefined ? str(payload["text"]) : undefined;
|
|
411
|
-
if (inboxID === undefined || text === undefined)
|
|
498
|
+
if (inboxID === undefined || text === undefined)
|
|
499
|
+
return drop(missingOf({ inboxID, text }));
|
|
412
500
|
const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
|
|
413
501
|
return {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
502
|
+
status: "ok",
|
|
503
|
+
event: {
|
|
504
|
+
type: "inbox.enqueued",
|
|
505
|
+
sessionID,
|
|
506
|
+
inboxID,
|
|
507
|
+
text,
|
|
508
|
+
delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
|
|
509
|
+
},
|
|
419
510
|
};
|
|
420
511
|
}
|
|
421
512
|
case "session.inbox.delivered": {
|
|
422
513
|
const inboxID = str(data["inboxID"]);
|
|
423
|
-
|
|
514
|
+
if (inboxID === undefined) return drop("inboxID");
|
|
515
|
+
return { status: "ok", event: { type: "inbox.delivered", sessionID, inboxID } };
|
|
424
516
|
}
|
|
425
517
|
case "session.execution.started":
|
|
426
|
-
return { type: "execution.started", sessionID };
|
|
518
|
+
return { status: "ok", event: { type: "execution.started", sessionID } };
|
|
427
519
|
case "session.execution.succeeded":
|
|
428
|
-
return { type: "execution.succeeded", sessionID };
|
|
520
|
+
return { status: "ok", event: { type: "execution.succeeded", sessionID } };
|
|
429
521
|
case "session.execution.failed": {
|
|
430
522
|
const error = isObj(data["error"]) ? data["error"] : undefined;
|
|
431
523
|
return {
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
524
|
+
status: "ok",
|
|
525
|
+
event: {
|
|
526
|
+
type: "execution.failed",
|
|
527
|
+
sessionID,
|
|
528
|
+
error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
|
|
529
|
+
},
|
|
435
530
|
};
|
|
436
531
|
}
|
|
437
532
|
case "session.execution.interrupted":
|
|
438
|
-
return { type: "execution.interrupted", sessionID, reason: str(data["reason"]) ?? "user" };
|
|
533
|
+
return { status: "ok", event: { type: "execution.interrupted", sessionID, reason: str(data["reason"]) ?? "user" } };
|
|
439
534
|
case "session.step.started": {
|
|
440
535
|
const assistantMessageID = str(data["assistantMessageID"]);
|
|
441
536
|
const model = mapModelRef(data["model"]);
|
|
442
|
-
if (assistantMessageID === undefined || model === undefined)
|
|
537
|
+
if (assistantMessageID === undefined || model === undefined)
|
|
538
|
+
return drop(missingOf({ assistantMessageID, model }));
|
|
443
539
|
return {
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
540
|
+
status: "ok",
|
|
541
|
+
event: {
|
|
542
|
+
type: "step.started",
|
|
543
|
+
sessionID,
|
|
544
|
+
assistantMessageID,
|
|
545
|
+
agent: str(data["agent"]) ?? "build",
|
|
546
|
+
model,
|
|
547
|
+
},
|
|
449
548
|
};
|
|
450
549
|
}
|
|
451
550
|
case "session.text.delta":
|
|
@@ -453,13 +552,17 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
|
|
|
453
552
|
const assistantMessageID = str(data["assistantMessageID"]);
|
|
454
553
|
const delta = str(data["delta"]);
|
|
455
554
|
const ordinal = num(data["ordinal"]);
|
|
456
|
-
if (assistantMessageID === undefined || delta === undefined || ordinal === undefined)
|
|
555
|
+
if (assistantMessageID === undefined || delta === undefined || ordinal === undefined)
|
|
556
|
+
return drop(missingOf({ assistantMessageID, delta, ordinal }));
|
|
457
557
|
return {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
558
|
+
status: "ok",
|
|
559
|
+
event: {
|
|
560
|
+
type: type === "session.text.delta" ? "text.delta" : "reasoning.delta",
|
|
561
|
+
sessionID,
|
|
562
|
+
assistantMessageID,
|
|
563
|
+
ordinal,
|
|
564
|
+
delta,
|
|
565
|
+
},
|
|
463
566
|
};
|
|
464
567
|
}
|
|
465
568
|
case "session.text.ended":
|
|
@@ -467,71 +570,84 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
|
|
|
467
570
|
const assistantMessageID = str(data["assistantMessageID"]);
|
|
468
571
|
const text = str(data["text"]);
|
|
469
572
|
const ordinal = num(data["ordinal"]);
|
|
470
|
-
if (assistantMessageID === undefined || text === undefined || ordinal === undefined)
|
|
573
|
+
if (assistantMessageID === undefined || text === undefined || ordinal === undefined)
|
|
574
|
+
return drop(missingOf({ assistantMessageID, text, ordinal }));
|
|
471
575
|
return {
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
576
|
+
status: "ok",
|
|
577
|
+
event: {
|
|
578
|
+
type: type === "session.text.ended" ? "text.ended" : "reasoning.ended",
|
|
579
|
+
sessionID,
|
|
580
|
+
assistantMessageID,
|
|
581
|
+
ordinal,
|
|
582
|
+
text,
|
|
583
|
+
},
|
|
477
584
|
};
|
|
478
585
|
}
|
|
479
586
|
case "session.tool.input.started": {
|
|
480
587
|
const id = str(data["id"]);
|
|
481
588
|
const name = str(data["name"]);
|
|
482
589
|
const assistantMessageID = str(data["assistantMessageID"]);
|
|
483
|
-
if (id === undefined || name === undefined || assistantMessageID === undefined)
|
|
484
|
-
|
|
590
|
+
if (id === undefined || name === undefined || assistantMessageID === undefined)
|
|
591
|
+
return drop(missingOf({ id, name, assistantMessageID }));
|
|
592
|
+
return { status: "ok", event: { type: "tool.input.started", sessionID, assistantMessageID, id, name } };
|
|
485
593
|
}
|
|
486
594
|
case "session.tool.input.ended": {
|
|
487
595
|
const id = str(data["id"]);
|
|
488
596
|
const text = str(data["text"]);
|
|
489
597
|
const assistantMessageID = str(data["assistantMessageID"]);
|
|
490
|
-
if (id === undefined || text === undefined || assistantMessageID === undefined)
|
|
491
|
-
|
|
598
|
+
if (id === undefined || text === undefined || assistantMessageID === undefined)
|
|
599
|
+
return drop(missingOf({ id, text, assistantMessageID }));
|
|
600
|
+
return { status: "ok", event: { type: "tool.input.ended", sessionID, assistantMessageID, id, text } };
|
|
492
601
|
}
|
|
493
602
|
case "session.tool.progress": {
|
|
494
603
|
const id = str(data["id"]);
|
|
495
|
-
|
|
604
|
+
if (id === undefined) return drop("id");
|
|
605
|
+
return { status: "ok", event: { type: "tool.progress", sessionID, id } };
|
|
496
606
|
}
|
|
497
607
|
case "session.tool.success": {
|
|
498
608
|
const id = str(data["id"]);
|
|
499
|
-
if (id === undefined) return
|
|
609
|
+
if (id === undefined) return drop("id");
|
|
500
610
|
const content = Array.isArray(data["content"])
|
|
501
611
|
? (data["content"] as unknown[]).map((c) => (isObj(c) ? mapToolContent(c) : undefined)).filter((c): c is FacadeToolContent => c !== undefined)
|
|
502
612
|
: [];
|
|
503
|
-
return { type: "tool.success", sessionID, id, content, executed: data["executed"] === true };
|
|
613
|
+
return { status: "ok", event: { type: "tool.success", sessionID, id, content, executed: data["executed"] === true } };
|
|
504
614
|
}
|
|
505
615
|
case "session.tool.failed": {
|
|
506
616
|
const id = str(data["id"]);
|
|
507
617
|
const error = isObj(data["error"]) ? data["error"] : undefined;
|
|
508
|
-
if (id === undefined) return
|
|
618
|
+
if (id === undefined) return drop("id");
|
|
509
619
|
return {
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
620
|
+
status: "ok",
|
|
621
|
+
event: {
|
|
622
|
+
type: "tool.failed",
|
|
623
|
+
sessionID,
|
|
624
|
+
id,
|
|
625
|
+
error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
|
|
626
|
+
executed: data["executed"] === true,
|
|
627
|
+
},
|
|
515
628
|
};
|
|
516
629
|
}
|
|
517
630
|
case "session.usage.updated": {
|
|
518
631
|
const tokens = isObj(data["tokens"]) ? data["tokens"] : undefined;
|
|
519
|
-
if (tokens === undefined) return
|
|
632
|
+
if (tokens === undefined) return drop("tokens");
|
|
520
633
|
const cache = isObj(tokens["cache"]) ? tokens["cache"] : undefined;
|
|
521
634
|
return {
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
635
|
+
status: "ok",
|
|
636
|
+
event: {
|
|
637
|
+
type: "usage.updated",
|
|
638
|
+
sessionID,
|
|
639
|
+
tokens: {
|
|
640
|
+
input: num(tokens["input"]) ?? 0,
|
|
641
|
+
output: num(tokens["output"]) ?? 0,
|
|
642
|
+
reasoning: num(tokens["reasoning"]) ?? 0,
|
|
643
|
+
cache: { read: cache !== undefined ? (num(cache["read"]) ?? 0) : 0, write: cache !== undefined ? (num(cache["write"]) ?? 0) : 0 },
|
|
644
|
+
},
|
|
529
645
|
},
|
|
530
646
|
};
|
|
531
647
|
}
|
|
532
648
|
case "permission.asked": {
|
|
533
649
|
const id = str(data["id"]);
|
|
534
|
-
if (id === undefined) return
|
|
650
|
+
if (id === undefined) return drop("id");
|
|
535
651
|
const source = isObj(data["source"]) && data["source"]["type"] === "tool" && str(data["source"]["id"]) !== undefined
|
|
536
652
|
? {
|
|
537
653
|
type: "tool" as const,
|
|
@@ -540,26 +656,40 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
|
|
|
540
656
|
}
|
|
541
657
|
: undefined;
|
|
542
658
|
return {
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
659
|
+
status: "ok",
|
|
660
|
+
event: {
|
|
661
|
+
type: "permission.asked",
|
|
662
|
+
sessionID,
|
|
663
|
+
id,
|
|
664
|
+
action: str(data["action"]) ?? "",
|
|
665
|
+
message: str(data["message"]),
|
|
666
|
+
source,
|
|
667
|
+
},
|
|
549
668
|
};
|
|
550
669
|
}
|
|
551
670
|
case "permission.replied": {
|
|
552
671
|
const requestID = str(data["requestID"]);
|
|
553
672
|
const reply = str(data["reply"]);
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
673
|
+
if (requestID === undefined || reply === undefined)
|
|
674
|
+
return drop(missingOf({ requestID, reply }));
|
|
675
|
+
return { status: "ok", event: { type: "permission.replied", sessionID, requestID, reply } };
|
|
557
676
|
}
|
|
558
677
|
default:
|
|
559
|
-
return
|
|
678
|
+
return { status: "unimplemented", type };
|
|
560
679
|
}
|
|
561
680
|
}
|
|
562
681
|
|
|
682
|
+
/**
|
|
683
|
+
* Map a raw opencode V2 event to the narrow `FacadeEvent` union, or
|
|
684
|
+
* null when the event carries nothing the AHP host needs — the `ok`
|
|
685
|
+
* view of `mapV2EventRaw` (`dropped`/`unimplemented` outcomes are
|
|
686
|
+
* log-and-continue; the capture lines see the full outcome).
|
|
687
|
+
*/
|
|
688
|
+
export function mapV2Event(raw: unknown): FacadeEvent | null {
|
|
689
|
+
const outcome = mapV2EventRaw(raw);
|
|
690
|
+
return outcome.status === "ok" ? outcome.event : null;
|
|
691
|
+
}
|
|
692
|
+
|
|
563
693
|
function mapModelRef(v: unknown): FacadeModelRef | undefined {
|
|
564
694
|
if (!isObj(v)) return undefined;
|
|
565
695
|
const id = str(v["id"]);
|
|
@@ -581,7 +711,57 @@ function mapToolContent(c: Record<string, unknown>): FacadeToolContent | undefin
|
|
|
581
711
|
return undefined;
|
|
582
712
|
}
|
|
583
713
|
|
|
584
|
-
// ──
|
|
714
|
+
// ── event capture lines ───────────────────────────────────────────
|
|
715
|
+
|
|
716
|
+
/** The house log tag (shared with src/index.ts's console lines). */
|
|
717
|
+
export const EVENT_LOG_TAG = "[opencode-ahp]";
|
|
718
|
+
|
|
719
|
+
/** Max characters of the raw `data` JSON on a capture line. */
|
|
720
|
+
const EVENT_LOG_PAYLOAD_MAX = 300;
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Local `HH:MM:SS.mmm` (zero-padded) for capture lines. The `Date` is
|
|
724
|
+
* passed in (not read here) so the formatter stays pure and unit-testable
|
|
725
|
+
* with a fixed instant.
|
|
726
|
+
*/
|
|
727
|
+
export function timeStamp(date: Date): string {
|
|
728
|
+
const pad = (n: number, width = 2) => String(n).padStart(width, "0");
|
|
729
|
+
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* One capture line per raw opencode event (design §8.1):
|
|
734
|
+
*
|
|
735
|
+
* [opencode-ahp] 19:04:41.520 event ok: session.tool.input.started {"…"}
|
|
736
|
+
* [opencode-ahp] 19:04:41.525 event dropped (missing: text): session.tool.input.ended {"…"}
|
|
737
|
+
* [opencode-ahp] 19:04:41.530 event unimplemented: shell.created {"…"}
|
|
738
|
+
*
|
|
739
|
+
* The type is the **raw** opencode type (what the plugin received), and
|
|
740
|
+
* the payload is the raw `data` JSON — truncated to
|
|
741
|
+
* `EVENT_LOG_PAYLOAD_MAX` with an ellipsis — or the whole raw value when
|
|
742
|
+
* the envelope is malformed. `stamp` is precomputed (`timeStamp`) so this
|
|
743
|
+
* stays pure.
|
|
744
|
+
*/
|
|
745
|
+
export function eventLogLine(outcome: V2EventOutcome, raw: unknown, stamp: string): string {
|
|
746
|
+
const type = isObj(raw) ? (str(raw["type"]) ?? "?") : "?";
|
|
747
|
+
const payloadSource = isObj(raw) && isObj(raw["data"]) ? raw["data"] : raw;
|
|
748
|
+
let payload: string;
|
|
749
|
+
try {
|
|
750
|
+
payload = JSON.stringify(payloadSource) ?? "null";
|
|
751
|
+
} catch {
|
|
752
|
+
payload = "(unserializable)";
|
|
753
|
+
}
|
|
754
|
+
if (payload.length > EVENT_LOG_PAYLOAD_MAX) payload = `${payload.slice(0, EVENT_LOG_PAYLOAD_MAX)}…`;
|
|
755
|
+
const kind =
|
|
756
|
+
outcome.status === "ok"
|
|
757
|
+
? "ok"
|
|
758
|
+
: outcome.status === "dropped"
|
|
759
|
+
? `dropped (${outcome.reason})`
|
|
760
|
+
: "unimplemented";
|
|
761
|
+
return `${EVENT_LOG_TAG} ${stamp} event ${kind}: ${type} ${payload}`;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ── state builders & summary mappers ────────────────────────────
|
|
585
765
|
|
|
586
766
|
const STATUS_IDLE_READ = (SessionStatus.Idle | SessionStatus.IsRead) as SessionStatus;
|
|
587
767
|
|
|
@@ -597,7 +777,7 @@ export function modelRefString(model?: FacadeModelRef): string | null {
|
|
|
597
777
|
* Initial `SessionState` for a new or lazily-registered opencode session.
|
|
598
778
|
* `status` starts at `Idle | IsRead` (33) — the session reducer can only
|
|
599
779
|
* move the read/archive/input-needed bits, so the *activity* source of
|
|
600
|
-
* truth is the chat status (synced via `session/chatUpdated
|
|
780
|
+
* truth is the chat status (synced via `session/chatUpdated`).
|
|
601
781
|
* `customizations` carries the workspace agent directory container — the
|
|
602
782
|
* same one the root catalog builds — because VS Code's agent dropdown reads
|
|
603
783
|
* `SessionState.customizations` (root-state customizations are NOT read).
|
|
@@ -610,6 +790,15 @@ export function initialSessionState(input: {
|
|
|
610
790
|
customizations?: Customization[];
|
|
611
791
|
status?: SessionStatus;
|
|
612
792
|
changesets?: Changeset[];
|
|
793
|
+
/**
|
|
794
|
+
* The session's working directories (AHP `SessionMetadata.workingDirectories`):
|
|
795
|
+
* the location directory the session's agent has tool access to. VS Code's
|
|
796
|
+
* session list groups sessions by this workspace (label = the folder name,
|
|
797
|
+
* host-suffixed for remote hosts); a session without it lands in the
|
|
798
|
+
* "Unknown" bucket. Single entry — the host advertises no
|
|
799
|
+
* `multipleWorkingDirectories` capability, so clients may not mutate it.
|
|
800
|
+
*/
|
|
801
|
+
workingDirectories?: string[];
|
|
613
802
|
}): SessionState {
|
|
614
803
|
return {
|
|
615
804
|
provider: input.provider,
|
|
@@ -619,6 +808,9 @@ export function initialSessionState(input: {
|
|
|
619
808
|
activeClients: input.activeClients ?? [],
|
|
620
809
|
chats: [],
|
|
621
810
|
defaultChat: undefined,
|
|
811
|
+
...(input.workingDirectories !== undefined && input.workingDirectories.length > 0
|
|
812
|
+
? { workingDirectories: input.workingDirectories }
|
|
813
|
+
: {}),
|
|
622
814
|
...(input.customizations !== undefined && input.customizations.length > 0
|
|
623
815
|
? { customizations: input.customizations }
|
|
624
816
|
: {}),
|
|
@@ -665,7 +857,8 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
|
|
|
665
857
|
|
|
666
858
|
/**
|
|
667
859
|
* Build the `SessionSummary` for root notifications / `listSessions` from
|
|
668
|
-
* a live record's denormalized fields.
|
|
860
|
+
* a live record's denormalized fields. `chats` is the full catalog in
|
|
861
|
+
* authoritative order (default first, then insertion order).
|
|
669
862
|
*/
|
|
670
863
|
export function buildSessionSummary(input: {
|
|
671
864
|
channel: string;
|
|
@@ -675,8 +868,12 @@ export function buildSessionSummary(input: {
|
|
|
675
868
|
activity?: string;
|
|
676
869
|
createdAt: string;
|
|
677
870
|
modifiedAt: string;
|
|
678
|
-
|
|
871
|
+
chats: ChatSummary[];
|
|
679
872
|
defaultChat: string;
|
|
873
|
+
/** The session's working directories (see `initialSessionState`) — the root
|
|
874
|
+
* channel's session catalog carries the same `SessionMetadata` the session
|
|
875
|
+
* channel does, so the list must show the same workspace. */
|
|
876
|
+
workingDirectories?: string[];
|
|
680
877
|
}): SessionSummary {
|
|
681
878
|
return {
|
|
682
879
|
resource: input.channel,
|
|
@@ -684,9 +881,12 @@ export function buildSessionSummary(input: {
|
|
|
684
881
|
title: input.title,
|
|
685
882
|
status: input.status,
|
|
686
883
|
...(input.activity !== undefined ? { activity: input.activity } : {}),
|
|
884
|
+
...(input.workingDirectories !== undefined && input.workingDirectories.length > 0
|
|
885
|
+
? { workingDirectories: input.workingDirectories }
|
|
886
|
+
: {}),
|
|
687
887
|
createdAt: input.createdAt,
|
|
688
888
|
modifiedAt: input.modifiedAt,
|
|
689
|
-
chats:
|
|
889
|
+
chats: input.chats,
|
|
690
890
|
defaultChat: input.defaultChat,
|
|
691
891
|
};
|
|
692
892
|
}
|
|
@@ -767,10 +967,10 @@ export function pastTenseMessageFor(toolName: string, inputText: string | undefi
|
|
|
767
967
|
return msg;
|
|
768
968
|
}
|
|
769
969
|
|
|
770
|
-
// ──
|
|
970
|
+
// ── changesets ───────────────────────────────────────────────────
|
|
771
971
|
|
|
772
972
|
/**
|
|
773
|
-
* Content-ref URIs the host serves through `resourceRead
|
|
973
|
+
* Content-ref URIs the host serves through `resourceRead`:
|
|
774
974
|
* - `ahp-content://head/<b64url(absPath)>` — the file's content in HEAD
|
|
775
975
|
* (`git show HEAD:<rel>`), for the "before" side of uncommitted/session
|
|
776
976
|
* changes;
|
|
@@ -792,6 +992,11 @@ export function fileUri(absPath: string): string {
|
|
|
792
992
|
return pathToFileURL(absPath).href;
|
|
793
993
|
}
|
|
794
994
|
|
|
995
|
+
/** File URI of a directory — directory paths end with `/` (RFC 8089). */
|
|
996
|
+
export function directoryUri(absPath: string): string {
|
|
997
|
+
return fileUri(absPath.endsWith("/") ? absPath : absPath + "/");
|
|
998
|
+
}
|
|
999
|
+
|
|
795
1000
|
/** Content ref for a file's HEAD content (the "before" of a live diff). */
|
|
796
1001
|
export function headContentRef(absPath: string): string {
|
|
797
1002
|
return CONTENT_HEAD_MARKER + b64url(absPath);
|
|
@@ -840,8 +1045,8 @@ function b64urlDecode(value: string): string | null {
|
|
|
840
1045
|
}
|
|
841
1046
|
|
|
842
1047
|
/**
|
|
843
|
-
* Line diff stats for two file contents (
|
|
844
|
-
* implementation
|
|
1048
|
+
* Line diff stats for two file contents (ported from the ahp-acp-gateway
|
|
1049
|
+
* implementation): CRLF-normalized, trailing newline ignored,
|
|
845
1050
|
* common prefix/suffix stripped, then an LCS DP over the middle with a
|
|
846
1051
|
* 40 000-cell cap (falls back to counting the whole middle when exceeded).
|
|
847
1052
|
*/
|
|
@@ -905,7 +1110,7 @@ export function computeLineDiffStats(
|
|
|
905
1110
|
};
|
|
906
1111
|
}
|
|
907
1112
|
|
|
908
|
-
/** The single operation this host advertises
|
|
1113
|
+
/** The single changeset operation this host advertises. */
|
|
909
1114
|
export const DISCARD_OPERATION_ID = "discard-changes";
|
|
910
1115
|
|
|
911
1116
|
/**
|
|
@@ -927,13 +1132,14 @@ export function discardOperation(): ChangesetOperation {
|
|
|
927
1132
|
/**
|
|
928
1133
|
* The session channel's changeset catalogue: the session-wide changeset
|
|
929
1134
|
* only (the protocol's "session" changeKind — all changes the agent has
|
|
930
|
-
* produced; approximated by the working tree vs HEAD
|
|
1135
|
+
* produced; approximated by the working tree vs HEAD). Takes the session
|
|
1136
|
+
* channel URI as the changeset owner.
|
|
931
1137
|
*/
|
|
932
|
-
export function sessionChangesetCatalog(
|
|
1138
|
+
export function sessionChangesetCatalog(sessionChannel: string): Changeset[] {
|
|
933
1139
|
return [
|
|
934
1140
|
{
|
|
935
1141
|
label: "Session Changes",
|
|
936
|
-
uriTemplate: sessionChangesetURI(
|
|
1142
|
+
uriTemplate: sessionChangesetURI(sessionChannel),
|
|
937
1143
|
changeKind: "session",
|
|
938
1144
|
capabilities: { review: {} },
|
|
939
1145
|
},
|
|
@@ -941,27 +1147,29 @@ export function sessionChangesetCatalog(sessionID: string): Changeset[] {
|
|
|
941
1147
|
}
|
|
942
1148
|
|
|
943
1149
|
/**
|
|
944
|
-
* The chat channel's changeset catalogue:
|
|
945
|
-
* session-wide changeset, and the per-turn template
|
|
946
|
-
* against the chat's turns — the protocol's standard
|
|
1150
|
+
* The chat channel's changeset catalogue: the chat's own uncommitted
|
|
1151
|
+
* changes, the session-wide changeset, and the per-turn template
|
|
1152
|
+
* (`{turnId}` expands against the chat's turns — the protocol's standard
|
|
1153
|
+
* template shapes). Multi-chat: every chat has its own catalogue keyed
|
|
1154
|
+
* off its own channel URI.
|
|
947
1155
|
*/
|
|
948
|
-
export function chatChangesetCatalog(
|
|
1156
|
+
export function chatChangesetCatalog(chatChannel: string, sessionChannel: string): Changeset[] {
|
|
949
1157
|
return [
|
|
950
1158
|
{
|
|
951
1159
|
label: "Uncommitted Changes",
|
|
952
|
-
uriTemplate: uncommittedChangesetURI(
|
|
1160
|
+
uriTemplate: uncommittedChangesetURI(chatChannel),
|
|
953
1161
|
changeKind: "uncommitted",
|
|
954
1162
|
capabilities: { review: {} },
|
|
955
1163
|
},
|
|
956
1164
|
{
|
|
957
1165
|
label: "Session Changes",
|
|
958
|
-
uriTemplate: sessionChangesetURI(
|
|
1166
|
+
uriTemplate: sessionChangesetURI(sessionChannel),
|
|
959
1167
|
changeKind: "session",
|
|
960
1168
|
capabilities: { review: {} },
|
|
961
1169
|
},
|
|
962
1170
|
{
|
|
963
1171
|
label: "Turn Changes",
|
|
964
|
-
uriTemplate: turnChangesetURI(
|
|
1172
|
+
uriTemplate: turnChangesetURI(chatChannel, "{turnId}"),
|
|
965
1173
|
changeKind: "turn",
|
|
966
1174
|
capabilities: { review: {} },
|
|
967
1175
|
},
|
|
@@ -974,8 +1182,8 @@ function withReviewed(file: ChangesetFile, reviewed: boolean | undefined): Chang
|
|
|
974
1182
|
}
|
|
975
1183
|
|
|
976
1184
|
/**
|
|
977
|
-
* `ChangesetFile` entries for the working-tree diff (the `uncommitted`
|
|
978
|
-
* `session` changesets share this approximation
|
|
1185
|
+
* `ChangesetFile` entries for the working-tree diff (the `uncommitted`
|
|
1186
|
+
* and `session` changesets share this approximation):
|
|
979
1187
|
* - added → `after` only, live `file://` content ref;
|
|
980
1188
|
* - deleted → `before` only, HEAD content ref;
|
|
981
1189
|
* - modified → live `file://` after + HEAD before.
|