opencode-ahp 0.1.3 → 0.1.5
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 +95 -20
- package/options.example.jsonc +20 -9
- package/package.json +1 -1
- package/src/bridge.ts +427 -33
- package/src/channels.ts +131 -18
- package/src/client-tools.ts +127 -0
- package/src/handshake.ts +2 -3
- package/src/host.ts +2231 -243
- package/src/index.ts +273 -24
- package/src/keep-alive.ts +3 -3
- package/src/options.ts +12 -7
- package/src/seq.ts +4 -5
- package/src/state.ts +52 -5
- package/src/transport.ts +15 -8
package/src/bridge.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
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";
|
|
13
|
+
import { sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "./channels.js";
|
|
16
14
|
import {
|
|
15
|
+
ChangesetOperationScope,
|
|
16
|
+
ChangesetOperationStatus,
|
|
17
17
|
CustomizationLoadStatus,
|
|
18
18
|
CustomizationType,
|
|
19
19
|
MessageKind,
|
|
@@ -21,10 +21,14 @@ import {
|
|
|
21
21
|
SessionStatus,
|
|
22
22
|
type AgentCustomization,
|
|
23
23
|
type AgentInfo,
|
|
24
|
+
type Changeset,
|
|
25
|
+
type ChangesetFile,
|
|
26
|
+
type ChangesetOperation,
|
|
24
27
|
type ChatSummary,
|
|
25
28
|
type ChatState,
|
|
26
29
|
type Customization,
|
|
27
30
|
type DirectoryCustomization,
|
|
31
|
+
type FileEdit,
|
|
28
32
|
type Message,
|
|
29
33
|
type SessionActiveClient,
|
|
30
34
|
type SessionState,
|
|
@@ -56,8 +60,7 @@ export interface FacadeProvider {
|
|
|
56
60
|
export type FacadeAgentMode = "primary" | "subagent" | "all";
|
|
57
61
|
|
|
58
62
|
/**
|
|
59
|
-
* Narrow opencode agent
|
|
60
|
-
* `ctx.agent.list()` → `Agent.Info[]`.
|
|
63
|
+
* Narrow opencode agent, from `ctx.agent.list()` → `Agent.Info[]`.
|
|
61
64
|
*/
|
|
62
65
|
export interface FacadeAgent {
|
|
63
66
|
id: string;
|
|
@@ -84,12 +87,18 @@ export interface FacadeSession {
|
|
|
84
87
|
model?: FacadeModelRef;
|
|
85
88
|
archived?: boolean;
|
|
86
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>;
|
|
87
96
|
}
|
|
88
97
|
|
|
89
98
|
/** `SessionPromptInput.delivery` (steer | queue; absent = default). */
|
|
90
99
|
export type FacadeDelivery = "steer" | "queue";
|
|
91
100
|
|
|
92
|
-
/** The decision values the host uses (`always` is
|
|
101
|
+
/** The decision values the host uses (`always` is not implemented). */
|
|
93
102
|
export type FacadePermissionDecision = "once" | "reject";
|
|
94
103
|
|
|
95
104
|
/**
|
|
@@ -145,19 +154,19 @@ export interface FacadeTokens {
|
|
|
145
154
|
|
|
146
155
|
/**
|
|
147
156
|
* The narrow opencode surface the bridge needs. Implemented in
|
|
148
|
-
* src/index.ts against the plugin `ctx` (the only ctx call sites
|
|
149
|
-
*
|
|
157
|
+
* src/index.ts against the plugin `ctx` (the only ctx call sites — this
|
|
158
|
+
* module stays pure); a fake in unit tests.
|
|
150
159
|
*
|
|
151
160
|
* All methods are async: the catalog, agents, and sessions come from the
|
|
152
161
|
* registry/session read APIs, which the docs guarantee reflect every
|
|
153
162
|
* registration so far, including during plugin setup.
|
|
154
163
|
*/
|
|
155
164
|
export interface OpencodeFacade {
|
|
156
|
-
/** Live provider/model catalog (
|
|
165
|
+
/** Live provider/model catalog (`ctx.provider` + `ctx.model`). */
|
|
157
166
|
listCatalog(): Promise<readonly FacadeProvider[]>;
|
|
158
|
-
/** Live opencode agents (
|
|
167
|
+
/** Live opencode agents (`ctx.agent.list()`). */
|
|
159
168
|
listAgents(): Promise<readonly FacadeAgent[]>;
|
|
160
|
-
// ──
|
|
169
|
+
// ── sessions ─────────────────────────────────────────────────
|
|
161
170
|
/**
|
|
162
171
|
* Create an opencode session. `id` is only passed through when it is a
|
|
163
172
|
* valid opencode SessionID (must start with "ses"); the host decides.
|
|
@@ -167,11 +176,19 @@ export interface OpencodeFacade {
|
|
|
167
176
|
title?: string;
|
|
168
177
|
agent?: string;
|
|
169
178
|
model?: FacadeModelRef;
|
|
179
|
+
/** Durable session metadata — the host's chat-binding marker rides here. */
|
|
180
|
+
metadata?: Record<string, unknown>;
|
|
170
181
|
}): Promise<FacadeSession>;
|
|
171
182
|
/** All opencode sessions for this location. */
|
|
172
183
|
listSessions(): Promise<readonly FacadeSession[]>;
|
|
173
184
|
/** One opencode session, or null when it does not exist. */
|
|
174
185
|
getSession(sessionID: string): Promise<FacadeSession | null>;
|
|
186
|
+
/**
|
|
187
|
+
* Remove an opencode session (`ctx.session.remove`). `disposeChat`
|
|
188
|
+
* removes a chat's backend session, and record removal disposes the
|
|
189
|
+
* peer-chat backends (multi-chat: one AHP chat per opencode session).
|
|
190
|
+
*/
|
|
191
|
+
removeSession(sessionID: string): Promise<void>;
|
|
175
192
|
/**
|
|
176
193
|
* Send a prompt. `delivery` maps to `SessionPromptInput.delivery`
|
|
177
194
|
* ("steer" | "queue"); absent = the default (start or continue a turn).
|
|
@@ -192,14 +209,88 @@ export interface OpencodeFacade {
|
|
|
192
209
|
* iterator ends (without error) when the signal aborts.
|
|
193
210
|
*/
|
|
194
211
|
events(signal: AbortSignal): AsyncIterable<FacadeEvent>;
|
|
212
|
+
// ── changesets ───────────────────────────────────────────────
|
|
213
|
+
/**
|
|
214
|
+
* Working-tree diff vs HEAD (uncommitted changes, untracked files
|
|
215
|
+
* included), with **absolute** file paths. `[]` when the location is
|
|
216
|
+
* not a git repo, has no changes, or the diff fails (R2: degrade to
|
|
217
|
+
* empty, never throw).
|
|
218
|
+
*/
|
|
219
|
+
vcsDiffWorking(): Promise<readonly FacadeDiffFile[]>;
|
|
220
|
+
/**
|
|
221
|
+
* The file's content in HEAD (`git show HEAD:<rel>`), or null when the
|
|
222
|
+
* location is not a repo, HEAD is missing, or the file is not tracked.
|
|
223
|
+
*/
|
|
224
|
+
gitHeadFile(absPath: string): Promise<string | null>;
|
|
225
|
+
/** Read a UTF-8 file from disk, or null when it does not exist. */
|
|
226
|
+
readFile(absPath: string): Promise<string | null>;
|
|
227
|
+
/** Write a UTF-8 file (creating parent directories as needed). */
|
|
228
|
+
writeFile(absPath: string, content: string): Promise<void>;
|
|
229
|
+
/** Delete a file; no-op when it does not exist. */
|
|
230
|
+
deleteFile(absPath: string): Promise<void>;
|
|
231
|
+
/**
|
|
232
|
+
* Discard changes to one file: tracked → `git checkout HEAD -- <rel>`
|
|
233
|
+
* (fallback delete), untracked → delete.
|
|
234
|
+
*/
|
|
235
|
+
discardFile(absPath: string): Promise<void>;
|
|
236
|
+
// ── client-provided tools ─────────────────────────
|
|
237
|
+
/**
|
|
238
|
+
* Replace the location's registered client tools with `tools` (the
|
|
239
|
+
* cross-session union of every AHP session's active-client tools;
|
|
240
|
+
* `[]` when none). The implementation applies them to the opencode
|
|
241
|
+
* tool registry (`ctx.tool.transform` + `ctx.tool.reload`) — the
|
|
242
|
+
* registered tools' `execute` routes back to the host.
|
|
243
|
+
*/
|
|
244
|
+
syncClientTools(tools: readonly FacadeClientTool[]): Promise<void>;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* A client-provided tool in its opencode-registration form (the host
|
|
249
|
+
* derives it from the AHP `ToolDefinition`s — `inputSchema` already
|
|
250
|
+
* normalized to an object JSON Schema, `description` already defaulted).
|
|
251
|
+
*/
|
|
252
|
+
export interface FacadeClientTool {
|
|
253
|
+
name: string;
|
|
254
|
+
description: string;
|
|
255
|
+
/** Object JSON Schema for the tool input (raw — opencode passes it through). */
|
|
256
|
+
inputSchema: Record<string, unknown>;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The settled result of a client-executed tool call, as the opencode
|
|
261
|
+
* `execute` bridge consumes it: `ok` → a `Tool.Result` (the client's
|
|
262
|
+
* `toolCallComplete` content, text blocks joined), not-ok → a thrown
|
|
263
|
+
* `Tool.Error`.
|
|
264
|
+
*/
|
|
265
|
+
export type FacadeClientToolResult =
|
|
266
|
+
| {
|
|
267
|
+
ok: true;
|
|
268
|
+
/** The client's past-tense message (`ToolCallResult.pastTenseMessage`). */
|
|
269
|
+
pastTenseMessage: string;
|
|
270
|
+
/** The client's text content blocks, joined (absent when none). */
|
|
271
|
+
content?: string;
|
|
272
|
+
/** The client's structured content, verbatim. */
|
|
273
|
+
structuredContent?: Record<string, unknown>;
|
|
274
|
+
}
|
|
275
|
+
| { ok: false; error: string };
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* One entry of a VCS working-tree diff (the facade's shape — absolute
|
|
279
|
+
* paths, unlike opencode's repo-root-relative `FileDiff.Info`).
|
|
280
|
+
*/
|
|
281
|
+
export interface FacadeDiffFile {
|
|
282
|
+
path: string;
|
|
283
|
+
additions: number;
|
|
284
|
+
deletions: number;
|
|
285
|
+
status: "added" | "deleted" | "modified";
|
|
195
286
|
}
|
|
196
287
|
|
|
197
|
-
// ──
|
|
288
|
+
// ── catalog mappers ─────────────────────────────────────────────
|
|
198
289
|
|
|
199
290
|
/**
|
|
200
|
-
* Stable synthetic AHP URI for an opencode agent (
|
|
201
|
-
*
|
|
202
|
-
*
|
|
291
|
+
* Stable synthetic AHP URI for an opencode agent (file URIs are not
|
|
292
|
+
* available for config/built-in agents, and the URI only has to match
|
|
293
|
+
* between the customization tree and `Message.agent`).
|
|
203
294
|
*/
|
|
204
295
|
export function agentUri(id: string): string {
|
|
205
296
|
return `opencode:agent/${id}`;
|
|
@@ -211,8 +302,7 @@ export function agentIDFromUri(uri: string): string | null {
|
|
|
211
302
|
}
|
|
212
303
|
|
|
213
304
|
/**
|
|
214
|
-
* Map opencode agents to AHP `AgentCustomization` children
|
|
215
|
-
* (plan §14.7 mapping table):
|
|
305
|
+
* Map opencode agents to AHP `AgentCustomization` children:
|
|
216
306
|
* - `id` → `uri` (synthetic `opencode:agent/<id>`, stable per agent) and
|
|
217
307
|
* `id` (same value — the host is the minting publisher);
|
|
218
308
|
* - `hidden: true` agents are omitted (internal: summary/title/…);
|
|
@@ -270,7 +360,7 @@ export function agentDirectoryCustomization(
|
|
|
270
360
|
|
|
271
361
|
/**
|
|
272
362
|
* Map the opencode catalog to the AHP root state's `agents` list.
|
|
273
|
-
* Mapping locked 2026-11-07
|
|
363
|
+
* Mapping locked 2026-11-07:
|
|
274
364
|
* - one AgentInfo per opencode provider;
|
|
275
365
|
* - providers with activation "disabled" are excluded;
|
|
276
366
|
* - models with enabled: false are excluded;
|
|
@@ -279,7 +369,7 @@ export function agentDirectoryCustomization(
|
|
|
279
369
|
* · maxPromptTokens ← limit.input;
|
|
280
370
|
* - supportsVision ← capabilities.input contains "image".
|
|
281
371
|
*
|
|
282
|
-
* With opencode agents + a workspace directory
|
|
372
|
+
* With opencode agents + a workspace directory, every
|
|
283
373
|
* AgentInfo also carries the same workspace directory container with the
|
|
284
374
|
* agent children as `customizations` — omitted when there is no visible
|
|
285
375
|
* (non-hidden) agent, so the picker shows the generic provider default
|
|
@@ -316,13 +406,19 @@ export function mapCatalog(
|
|
|
316
406
|
displayName: provider.name,
|
|
317
407
|
description: provider.description ?? provider.name,
|
|
318
408
|
models,
|
|
409
|
+
// Multi-chat: advertise plain multipleChats.
|
|
410
|
+
// No `fork`/`sideChat` sub-caps — the opencode plugin surface has
|
|
411
|
+
// no fork API in 2.2.6, so conformant clients (VS Code gates its
|
|
412
|
+
// UI on these) will never attempt the unsupported source forms.
|
|
413
|
+
// No `multipleWorkingDirectories` either (a location is one dir).
|
|
414
|
+
capabilities: { multipleChats: {} },
|
|
319
415
|
...(customizations !== undefined ? { customizations } : {}),
|
|
320
416
|
});
|
|
321
417
|
}
|
|
322
418
|
return out;
|
|
323
419
|
}
|
|
324
420
|
|
|
325
|
-
// ──
|
|
421
|
+
// ── event mapping ───────────────────────────────────────────────
|
|
326
422
|
|
|
327
423
|
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
|
|
328
424
|
|
|
@@ -539,7 +635,7 @@ function mapToolContent(c: Record<string, unknown>): FacadeToolContent | undefin
|
|
|
539
635
|
return undefined;
|
|
540
636
|
}
|
|
541
637
|
|
|
542
|
-
// ──
|
|
638
|
+
// ── state builders & summary mappers ────────────────────────────
|
|
543
639
|
|
|
544
640
|
const STATUS_IDLE_READ = (SessionStatus.Idle | SessionStatus.IsRead) as SessionStatus;
|
|
545
641
|
|
|
@@ -555,7 +651,7 @@ export function modelRefString(model?: FacadeModelRef): string | null {
|
|
|
555
651
|
* Initial `SessionState` for a new or lazily-registered opencode session.
|
|
556
652
|
* `status` starts at `Idle | IsRead` (33) — the session reducer can only
|
|
557
653
|
* move the read/archive/input-needed bits, so the *activity* source of
|
|
558
|
-
* truth is the chat status (synced via `session/chatUpdated
|
|
654
|
+
* truth is the chat status (synced via `session/chatUpdated`).
|
|
559
655
|
* `customizations` carries the workspace agent directory container — the
|
|
560
656
|
* same one the root catalog builds — because VS Code's agent dropdown reads
|
|
561
657
|
* `SessionState.customizations` (root-state customizations are NOT read).
|
|
@@ -567,6 +663,7 @@ export function initialSessionState(input: {
|
|
|
567
663
|
activeClients?: SessionActiveClient[];
|
|
568
664
|
customizations?: Customization[];
|
|
569
665
|
status?: SessionStatus;
|
|
666
|
+
changesets?: Changeset[];
|
|
570
667
|
}): SessionState {
|
|
571
668
|
return {
|
|
572
669
|
provider: input.provider,
|
|
@@ -579,6 +676,7 @@ export function initialSessionState(input: {
|
|
|
579
676
|
...(input.customizations !== undefined && input.customizations.length > 0
|
|
580
677
|
? { customizations: input.customizations }
|
|
581
678
|
: {}),
|
|
679
|
+
...(input.changesets !== undefined ? { changesets: input.changesets } : {}),
|
|
582
680
|
};
|
|
583
681
|
}
|
|
584
682
|
|
|
@@ -587,6 +685,7 @@ export function initialChatState(input: {
|
|
|
587
685
|
resource: string;
|
|
588
686
|
title: string;
|
|
589
687
|
modifiedAt: string;
|
|
688
|
+
changesets?: Changeset[];
|
|
590
689
|
}): ChatState {
|
|
591
690
|
return {
|
|
592
691
|
resource: input.resource,
|
|
@@ -594,6 +693,7 @@ export function initialChatState(input: {
|
|
|
594
693
|
status: STATUS_IDLE_READ,
|
|
595
694
|
modifiedAt: input.modifiedAt,
|
|
596
695
|
turns: [],
|
|
696
|
+
...(input.changesets !== undefined ? { changesets: input.changesets } : {}),
|
|
597
697
|
};
|
|
598
698
|
}
|
|
599
699
|
|
|
@@ -619,7 +719,8 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
|
|
|
619
719
|
|
|
620
720
|
/**
|
|
621
721
|
* Build the `SessionSummary` for root notifications / `listSessions` from
|
|
622
|
-
* a live record's denormalized fields.
|
|
722
|
+
* a live record's denormalized fields. `chats` is the full catalog in
|
|
723
|
+
* authoritative order (default first, then insertion order).
|
|
623
724
|
*/
|
|
624
725
|
export function buildSessionSummary(input: {
|
|
625
726
|
channel: string;
|
|
@@ -629,7 +730,7 @@ export function buildSessionSummary(input: {
|
|
|
629
730
|
activity?: string;
|
|
630
731
|
createdAt: string;
|
|
631
732
|
modifiedAt: string;
|
|
632
|
-
|
|
733
|
+
chats: ChatSummary[];
|
|
633
734
|
defaultChat: string;
|
|
634
735
|
}): SessionSummary {
|
|
635
736
|
return {
|
|
@@ -640,7 +741,7 @@ export function buildSessionSummary(input: {
|
|
|
640
741
|
...(input.activity !== undefined ? { activity: input.activity } : {}),
|
|
641
742
|
createdAt: input.createdAt,
|
|
642
743
|
modifiedAt: input.modifiedAt,
|
|
643
|
-
chats:
|
|
744
|
+
chats: input.chats,
|
|
644
745
|
defaultChat: input.defaultChat,
|
|
645
746
|
};
|
|
646
747
|
}
|
|
@@ -720,3 +821,296 @@ export function pastTenseMessageFor(toolName: string, inputText: string | undefi
|
|
|
720
821
|
}
|
|
721
822
|
return msg;
|
|
722
823
|
}
|
|
824
|
+
|
|
825
|
+
// ── changesets ───────────────────────────────────────────────────
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Content-ref URIs the host serves through `resourceRead`:
|
|
829
|
+
* - `ahp-content://head/<b64url(absPath)>` — the file's content in HEAD
|
|
830
|
+
* (`git show HEAD:<rel>`), for the "before" side of uncommitted/session
|
|
831
|
+
* changes;
|
|
832
|
+
* - `ahp-content://snap/<b64url(session)>/<b64url(turn)>/<b64url(absPath)>/<part>`
|
|
833
|
+
* — a turn's captured pre-edit (`before`) or post-turn (`after`) content
|
|
834
|
+
* from the in-memory snapshot store. Opaque and unguessable (base64url
|
|
835
|
+
* segments, not path segments) so a client cannot point the host at
|
|
836
|
+
* arbitrary snapshots.
|
|
837
|
+
*
|
|
838
|
+
* The "after" side of uncommitted/session changes is the live disk path
|
|
839
|
+
* itself (`file://`), read through `resourceRead` at view time.
|
|
840
|
+
*/
|
|
841
|
+
const CONTENT_REF_PREFIX = "ahp-content://";
|
|
842
|
+
const CONTENT_HEAD_MARKER = "ahp-content://head/";
|
|
843
|
+
const CONTENT_SNAP_MARKER = "ahp-content://snap/";
|
|
844
|
+
|
|
845
|
+
/** The `file://` URI of an absolute path (a `ChangesetFile.id`). */
|
|
846
|
+
export function fileUri(absPath: string): string {
|
|
847
|
+
return pathToFileURL(absPath).href;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/** File URI of a directory — directory paths end with `/` (RFC 8089). */
|
|
851
|
+
export function directoryUri(absPath: string): string {
|
|
852
|
+
return fileUri(absPath.endsWith("/") ? absPath : absPath + "/");
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/** Content ref for a file's HEAD content (the "before" of a live diff). */
|
|
856
|
+
export function headContentRef(absPath: string): string {
|
|
857
|
+
return CONTENT_HEAD_MARKER + b64url(absPath);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Content ref for one part of a turn's snapshot. */
|
|
861
|
+
export function snapContentRef(sessionID: string, turnId: string, absPath: string, part: "before" | "after"): string {
|
|
862
|
+
return `${CONTENT_SNAP_MARKER}${b64url(sessionID)}/${b64url(turnId)}/${b64url(absPath)}/${part}`;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** Parsed content-ref URI, or null when the URI is not one of ours. */
|
|
866
|
+
export type ParsedContentRef =
|
|
867
|
+
| { kind: "head"; path: string }
|
|
868
|
+
| { kind: "snap"; sessionID: string; turnId: string; path: string; part: "before" | "after" };
|
|
869
|
+
|
|
870
|
+
export function parseContentRef(uri: string): ParsedContentRef | null {
|
|
871
|
+
if (uri.startsWith(CONTENT_HEAD_MARKER)) {
|
|
872
|
+
const path = b64urlDecode(uri.slice(CONTENT_HEAD_MARKER.length));
|
|
873
|
+
return path !== null ? { kind: "head", path } : null;
|
|
874
|
+
}
|
|
875
|
+
if (uri.startsWith(CONTENT_SNAP_MARKER)) {
|
|
876
|
+
const segments = uri.slice(CONTENT_SNAP_MARKER.length).split("/");
|
|
877
|
+
if (segments.length !== 4) return null;
|
|
878
|
+
const [sessionID, turnId, path, part] = segments as [string, string, string, string];
|
|
879
|
+
const dSession = b64urlDecode(sessionID);
|
|
880
|
+
const dTurn = b64urlDecode(turnId);
|
|
881
|
+
const dPath = b64urlDecode(path);
|
|
882
|
+
if (dSession === null || dTurn === null || dPath === null) return null;
|
|
883
|
+
if (part !== "before" && part !== "after") return null;
|
|
884
|
+
return { kind: "snap", sessionID: dSession, turnId: dTurn, path: dPath, part };
|
|
885
|
+
}
|
|
886
|
+
return null;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function b64url(value: string): string {
|
|
890
|
+
return Buffer.from(value, "utf-8").toString("base64url");
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
function b64urlDecode(value: string): string | null {
|
|
894
|
+
if (value.length === 0) return null;
|
|
895
|
+
// base64url alphabet check — rejects path separators and junk, which is
|
|
896
|
+
// what keeps a malformed ref from being mis-split into other segments.
|
|
897
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null;
|
|
898
|
+
const text = Buffer.from(value, "base64url").toString("utf-8");
|
|
899
|
+
return text.length > 0 ? text : null;
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/**
|
|
903
|
+
* Line diff stats for two file contents (ported from the ahp-acp-gateway
|
|
904
|
+
* implementation): CRLF-normalized, trailing newline ignored,
|
|
905
|
+
* common prefix/suffix stripped, then an LCS DP over the middle with a
|
|
906
|
+
* 40 000-cell cap (falls back to counting the whole middle when exceeded).
|
|
907
|
+
*/
|
|
908
|
+
export function computeLineDiffStats(
|
|
909
|
+
oldText: string | null | undefined,
|
|
910
|
+
newText: string | null | undefined,
|
|
911
|
+
): { added: number; removed: number } {
|
|
912
|
+
const splitLines = (text: string | null | undefined): string[] => {
|
|
913
|
+
if (!text) return [];
|
|
914
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
915
|
+
const lines = normalized.split("\n");
|
|
916
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") {
|
|
917
|
+
lines.pop();
|
|
918
|
+
}
|
|
919
|
+
return lines;
|
|
920
|
+
};
|
|
921
|
+
const oldLines = splitLines(oldText);
|
|
922
|
+
const newLines = splitLines(newText);
|
|
923
|
+
if (oldLines.length === 0) {
|
|
924
|
+
return { added: newLines.length, removed: 0 };
|
|
925
|
+
}
|
|
926
|
+
if (newLines.length === 0) {
|
|
927
|
+
return { added: 0, removed: oldLines.length };
|
|
928
|
+
}
|
|
929
|
+
let prefix = 0;
|
|
930
|
+
const minLen = Math.min(oldLines.length, newLines.length);
|
|
931
|
+
while (prefix < minLen && oldLines[prefix] === newLines[prefix]) {
|
|
932
|
+
prefix++;
|
|
933
|
+
}
|
|
934
|
+
let suffix = 0;
|
|
935
|
+
while (
|
|
936
|
+
suffix < minLen - prefix &&
|
|
937
|
+
oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]
|
|
938
|
+
) {
|
|
939
|
+
suffix++;
|
|
940
|
+
}
|
|
941
|
+
const oldMid = oldLines.slice(prefix, oldLines.length - suffix);
|
|
942
|
+
const newMid = newLines.slice(prefix, newLines.length - suffix);
|
|
943
|
+
if (oldMid.length * newMid.length > 40_000) {
|
|
944
|
+
return { added: newMid.length, removed: oldMid.length };
|
|
945
|
+
}
|
|
946
|
+
const dp = new Uint32Array((oldMid.length + 1) * (newMid.length + 1));
|
|
947
|
+
const width = newMid.length + 1;
|
|
948
|
+
for (let i = 1; i <= oldMid.length; i++) {
|
|
949
|
+
const oldLine = oldMid[i - 1]!;
|
|
950
|
+
for (let j = 1; j <= newMid.length; j++) {
|
|
951
|
+
const idx = i * width + j;
|
|
952
|
+
if (oldLine === newMid[j - 1]) {
|
|
953
|
+
dp[idx] = dp[(i - 1) * width + (j - 1)]! + 1;
|
|
954
|
+
} else {
|
|
955
|
+
const up = dp[(i - 1) * width + j]!;
|
|
956
|
+
const left = dp[i * width + (j - 1)]!;
|
|
957
|
+
dp[idx] = up >= left ? up : left;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const lcs = dp[oldMid.length * width + newMid.length]!;
|
|
962
|
+
return {
|
|
963
|
+
added: Math.max(0, newMid.length - lcs),
|
|
964
|
+
removed: Math.max(0, oldMid.length - lcs),
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** The single changeset operation this host advertises. */
|
|
969
|
+
export const DISCARD_OPERATION_ID = "discard-changes";
|
|
970
|
+
|
|
971
|
+
/**
|
|
972
|
+
* The `discard-changes` operation (gateway-identical shape): restores one
|
|
973
|
+
* file from the changeset's "before" content — HEAD for uncommitted/session
|
|
974
|
+
* changes, the turn's pre-edit snapshot for turn changes.
|
|
975
|
+
*/
|
|
976
|
+
export function discardOperation(): ChangesetOperation {
|
|
977
|
+
return {
|
|
978
|
+
id: DISCARD_OPERATION_ID,
|
|
979
|
+
label: "Discard Changes",
|
|
980
|
+
confirmation: "Are you sure you want to discard changes to this file?",
|
|
981
|
+
icon: "discard",
|
|
982
|
+
scopes: [ChangesetOperationScope.Resource],
|
|
983
|
+
status: ChangesetOperationStatus.Idle,
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* The session channel's changeset catalogue: the session-wide changeset
|
|
989
|
+
* only (the protocol's "session" changeKind — all changes the agent has
|
|
990
|
+
* produced; approximated by the working tree vs HEAD). Takes the session
|
|
991
|
+
* channel URI as the changeset owner.
|
|
992
|
+
*/
|
|
993
|
+
export function sessionChangesetCatalog(sessionChannel: string): Changeset[] {
|
|
994
|
+
return [
|
|
995
|
+
{
|
|
996
|
+
label: "Session Changes",
|
|
997
|
+
uriTemplate: sessionChangesetURI(sessionChannel),
|
|
998
|
+
changeKind: "session",
|
|
999
|
+
capabilities: { review: {} },
|
|
1000
|
+
},
|
|
1001
|
+
];
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* The chat channel's changeset catalogue: the chat's own uncommitted
|
|
1006
|
+
* changes, the session-wide changeset, and the per-turn template
|
|
1007
|
+
* (`{turnId}` expands against the chat's turns — the protocol's standard
|
|
1008
|
+
* template shapes). Multi-chat: every chat has its own catalogue keyed
|
|
1009
|
+
* off its own channel URI.
|
|
1010
|
+
*/
|
|
1011
|
+
export function chatChangesetCatalog(chatChannel: string, sessionChannel: string): Changeset[] {
|
|
1012
|
+
return [
|
|
1013
|
+
{
|
|
1014
|
+
label: "Uncommitted Changes",
|
|
1015
|
+
uriTemplate: uncommittedChangesetURI(chatChannel),
|
|
1016
|
+
changeKind: "uncommitted",
|
|
1017
|
+
capabilities: { review: {} },
|
|
1018
|
+
},
|
|
1019
|
+
{
|
|
1020
|
+
label: "Session Changes",
|
|
1021
|
+
uriTemplate: sessionChangesetURI(sessionChannel),
|
|
1022
|
+
changeKind: "session",
|
|
1023
|
+
capabilities: { review: {} },
|
|
1024
|
+
},
|
|
1025
|
+
{
|
|
1026
|
+
label: "Turn Changes",
|
|
1027
|
+
uriTemplate: turnChangesetURI(chatChannel, "{turnId}"),
|
|
1028
|
+
changeKind: "turn",
|
|
1029
|
+
capabilities: { review: {} },
|
|
1030
|
+
},
|
|
1031
|
+
];
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** Carry a file's previous `reviewed` flag into a rebuilt entry (gateway behavior). */
|
|
1035
|
+
function withReviewed(file: ChangesetFile, reviewed: boolean | undefined): ChangesetFile {
|
|
1036
|
+
return reviewed === undefined ? file : { ...file, reviewed };
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* `ChangesetFile` entries for the working-tree diff (the `uncommitted`
|
|
1041
|
+
* and `session` changesets share this approximation):
|
|
1042
|
+
* - added → `after` only, live `file://` content ref;
|
|
1043
|
+
* - deleted → `before` only, HEAD content ref;
|
|
1044
|
+
* - modified → live `file://` after + HEAD before.
|
|
1045
|
+
* `id` is the `file://` URI (the target of `invokeChangesetOperation`).
|
|
1046
|
+
*/
|
|
1047
|
+
export function buildWorkingChangesetFiles(input: {
|
|
1048
|
+
diffs: readonly FacadeDiffFile[];
|
|
1049
|
+
reviewedById: ReadonlyMap<string, boolean>;
|
|
1050
|
+
}): ChangesetFile[] {
|
|
1051
|
+
const out: ChangesetFile[] = [];
|
|
1052
|
+
for (const f of input.diffs) {
|
|
1053
|
+
if (f.path.length === 0) continue;
|
|
1054
|
+
const id = fileUri(f.path);
|
|
1055
|
+
const edit: FileEdit =
|
|
1056
|
+
f.status === "added"
|
|
1057
|
+
? {
|
|
1058
|
+
after: { uri: id, content: { uri: id } },
|
|
1059
|
+
diff: { added: f.additions, removed: 0 },
|
|
1060
|
+
}
|
|
1061
|
+
: f.status === "deleted"
|
|
1062
|
+
? {
|
|
1063
|
+
before: { uri: id, content: { uri: headContentRef(f.path) } },
|
|
1064
|
+
diff: { added: 0, removed: f.deletions },
|
|
1065
|
+
}
|
|
1066
|
+
: {
|
|
1067
|
+
before: { uri: id, content: { uri: headContentRef(f.path) } },
|
|
1068
|
+
after: { uri: id, content: { uri: id } },
|
|
1069
|
+
diff: { added: f.additions, removed: f.deletions },
|
|
1070
|
+
};
|
|
1071
|
+
out.push(withReviewed({ id, edit }, input.reviewedById.get(id)));
|
|
1072
|
+
}
|
|
1073
|
+
return out;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* `ChangesetFile` entries for one turn's captured file changes:
|
|
1078
|
+
* - both sides use opaque snapshot content refs (the "after" is what the
|
|
1079
|
+
* host read from disk at turn end — strictly correct even if a later
|
|
1080
|
+
* turn edits the same file again);
|
|
1081
|
+
* - `before === null` → the turn added the file; `after === null` → the
|
|
1082
|
+
* turn deleted it; `before === after` → dropped (no net change).
|
|
1083
|
+
*/
|
|
1084
|
+
export function buildTurnChangesetFiles(input: {
|
|
1085
|
+
sessionID: string;
|
|
1086
|
+
turnId: string;
|
|
1087
|
+
/** absPath → captured {before, after} (null = file absent on that side). */
|
|
1088
|
+
files: ReadonlyMap<string, { before: string | null; after: string | null }>;
|
|
1089
|
+
reviewedById: ReadonlyMap<string, boolean>;
|
|
1090
|
+
}): ChangesetFile[] {
|
|
1091
|
+
const out: ChangesetFile[] = [];
|
|
1092
|
+
for (const [absPath, snap] of input.files) {
|
|
1093
|
+
if (snap.before === snap.after) continue;
|
|
1094
|
+
const id = fileUri(absPath);
|
|
1095
|
+
const beforeRef = snapContentRef(input.sessionID, input.turnId, absPath, "before");
|
|
1096
|
+
const afterRef = snapContentRef(input.sessionID, input.turnId, absPath, "after");
|
|
1097
|
+
const edit: FileEdit =
|
|
1098
|
+
snap.before === null
|
|
1099
|
+
? {
|
|
1100
|
+
after: { uri: id, content: { uri: afterRef } },
|
|
1101
|
+
diff: computeLineDiffStats(null, snap.after),
|
|
1102
|
+
}
|
|
1103
|
+
: snap.after === null
|
|
1104
|
+
? {
|
|
1105
|
+
before: { uri: id, content: { uri: beforeRef } },
|
|
1106
|
+
diff: computeLineDiffStats(snap.before, null),
|
|
1107
|
+
}
|
|
1108
|
+
: {
|
|
1109
|
+
before: { uri: id, content: { uri: beforeRef } },
|
|
1110
|
+
after: { uri: id, content: { uri: afterRef } },
|
|
1111
|
+
diff: computeLineDiffStats(snap.before, snap.after),
|
|
1112
|
+
};
|
|
1113
|
+
out.push(withReviewed({ id, edit }, input.reviewedById.get(id)));
|
|
1114
|
+
}
|
|
1115
|
+
return out;
|
|
1116
|
+
}
|