opencode-ahp 0.1.3 → 0.1.4
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 +49 -9
- package/options.example.jsonc +9 -3
- package/package.json +1 -1
- package/src/bridge.ts +331 -0
- package/src/channels.ts +80 -3
- package/src/host.ts +541 -6
- package/src/index.ts +131 -1
- package/src/options.ts +3 -1
- package/src/state.ts +25 -1
- package/src/transport.ts +9 -2
package/README.md
CHANGED
|
@@ -4,11 +4,13 @@ OpenCode v2 plugin that hosts the **Agent Host Protocol (AHP) 1.0.0**
|
|
|
4
4
|
in-process so opencode is a native agent in the **VS Code Agents window** —
|
|
5
5
|
on this machine and (MVP scope) on other machines over the local LAN.
|
|
6
6
|
|
|
7
|
-
> **Status: Phase
|
|
8
|
-
> streaming, tool calls, permission prompts,
|
|
7
|
+
> **Status: Phase 3 — wss:// transport complete.** Sessions, model +
|
|
8
|
+
> agent pickers, streaming, tool calls, permission prompts,
|
|
9
|
+
> steering/queue, usage, **changesets (uncommitted / session / per-turn
|
|
10
|
+
> diffs with `discard-changes`)**, and reconnect replay are
|
|
9
11
|
> live-verified over the LAN with VS Code 1.145.2 (real Agents window ↔
|
|
10
|
-
> host)
|
|
11
|
-
> [`plan.md`](plan.md).
|
|
12
|
+
> host), over plain `ws://` **and native `wss://`** (TLS-terminated).
|
|
13
|
+
> The full plan and wire findings live in [`plan.md`](plan.md).
|
|
12
14
|
|
|
13
15
|
## What you get
|
|
14
16
|
|
|
@@ -29,9 +31,16 @@ In the Agents window, an `opencode` host with:
|
|
|
29
31
|
approval prompt; approve runs the tool, deny blocks it.
|
|
30
32
|
- **Steering + queue** — a message sent mid-turn steers the active turn or
|
|
31
33
|
queues for the next one (AHP `pendingMessageSet`).
|
|
34
|
+
- **Changesets** — per-session diff channels (uncommitted, session, and
|
|
35
|
+
per-turn) backed by the location's git state: live `file://` refs,
|
|
36
|
+
`git show HEAD:` before-refs, and in-memory turn snapshots; the
|
|
37
|
+
`discard-changes` operation restores a file. Requires the location
|
|
38
|
+
directory to be a git repository (otherwise the changesets are empty);
|
|
39
|
+
opt out with `capabilities.changesets: false`.
|
|
32
40
|
|
|
33
|
-
Not yet
|
|
34
|
-
|
|
41
|
+
Not yet: cancelling a queued message and the `always` permission reply
|
|
42
|
+
(Phase 4 extensions); official conformance-suite coverage (Phase 5,
|
|
43
|
+
last — after the extensions land).
|
|
35
44
|
|
|
36
45
|
## Requirements
|
|
37
46
|
|
|
@@ -84,12 +93,12 @@ sibling of `src/index.ts` (checkouts only — copy
|
|
|
84
93
|
| `path` | `"/ahp"` | WS path — VS Code's URL carries it verbatim |
|
|
85
94
|
| `token` | auto | Omit → generated on first start, persisted in opencode's plugin storage, printed once to the service log. Accepted via the `?token=` query param and `Authorization: Bearer <token>`. **Always enforced**, loopback or not |
|
|
86
95
|
| `allowedOrigins` | `"*"` | `"*"` or an exact list, e.g. `["vscode://vscode"]`. The token is still always required regardless |
|
|
87
|
-
| `tls` | `null` | `{ keyPath, certPath }` — native TLS → `wss://` (
|
|
88
|
-
| `healthPath` | `"/healthz"` |
|
|
96
|
+
| `tls` | `null` | `{ keyPath, certPath }` — native TLS termination → `wss://` (off-LAN transports, D3). PEM **file paths**; the port becomes TLS-only (plain-HTTP requests to it fail) and the health endpoint is then HTTPS: `curl -k https://…:8765/healthz`. A missing/unreadable file disables the AHP listener — the opencode server keeps running |
|
|
97
|
+
| `healthPath` | `"/healthz"` | Health endpoint (no auth): `curl …:8765/healthz` → `ok` (over the same TLS termination when `tls` is set) |
|
|
89
98
|
| `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout (`experimental.location_idle_timeout`, default 60 min) by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. The anchor (`opencode-ahp (keep-alive)`) is a real opencode session: it shows in the TUI session list but is hidden from AHP clients (opencode's plugin surface cannot archive it) |
|
|
90
99
|
| `keepAliveIntervalMinutes` | `10` | Minutes between keep-alive touches; keep well below the effective idle timeout |
|
|
91
100
|
| `replayWindow` | `1000` | Per-channel actions kept for reconnect replay; older gaps → fresh snapshot |
|
|
92
|
-
| `capabilities` | `{ changesets:
|
|
101
|
+
| `capabilities` | `{ changesets: true, terminals: false, automations: false }` | Advertised in `initialize` — never advertise what we don't implement. Set `changesets` to `false` to disable the diff channels (the session/chat snapshots then carry no changeset catalogues and changeset URIs resolve to nothing) |
|
|
93
102
|
|
|
94
103
|
## Remote access (local LAN — MVP)
|
|
95
104
|
|
|
@@ -165,6 +174,33 @@ Note: the Agents window's built-in **SSH** and **Dev tunnels** flows run
|
|
|
165
174
|
For a third-party host, only raw network reachability of the `ws(s)://`
|
|
166
175
|
URL matters.
|
|
167
176
|
|
|
177
|
+
### Off-LAN: native `wss://` (Phase 3)
|
|
178
|
+
|
|
179
|
+
When plain LAN `ws://` doesn't fit (host on another network, or
|
|
180
|
+
token-in-URL on a shared network you don't want), set `tls` and the same
|
|
181
|
+
listener serves `wss://` — native termination in `Bun.serve`, no proxy in
|
|
182
|
+
the middle:
|
|
183
|
+
|
|
184
|
+
```jsonc
|
|
185
|
+
"options": {
|
|
186
|
+
"host": "0.0.0.0",
|
|
187
|
+
"token": "change-me-to-a-long-random-string",
|
|
188
|
+
"tls": {
|
|
189
|
+
"keyPath": "/path/tls-key.pem",
|
|
190
|
+
"certPath": "/path/tls-cert.pem"
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The client URL becomes `wss://<host>:8767/ahp?token=<token>` and the
|
|
196
|
+
token/Origin policy is unchanged. The certificate must be trusted by the
|
|
197
|
+
client machine for the URL's hostname: VS Code expects a real chain
|
|
198
|
+
(mkcert on a dev network, or any CA the client trusts); self-signed
|
|
199
|
+
certs only work for script-based checks
|
|
200
|
+
(`NODE_TLS_REJECT_UNAUTHORIZED=0`). With `tls` set the port is
|
|
201
|
+
**TLS-only** — plain-HTTP requests to it fail, and the health check
|
|
202
|
+
becomes `curl -k https://<host>:<port>/healthz` → `ok`.
|
|
203
|
+
|
|
168
204
|
## Development
|
|
169
205
|
|
|
170
206
|
```sh
|
|
@@ -180,6 +216,10 @@ Dependency-free live probes (Node ≥ 20 global WebSocket):
|
|
|
180
216
|
node scripts/ahp-client.mjs --token <token> [--base http://127.0.0.1:8765]
|
|
181
217
|
# Phase 1 end-to-end: createSession → agent-picker snapshot → full turn lifecycle
|
|
182
218
|
node scripts/ahp-phase1.mjs --token <token> --base http://127.0.0.1:8765 --provider opencode
|
|
219
|
+
# Phase 2 end-to-end: changesets (edit → diffs → discard) + mid-turn reconnect/replay
|
|
220
|
+
node scripts/ahp-phase2.mjs --token <token> --base http://127.0.0.1:8765
|
|
221
|
+
# the same probes over native wss:// (self-signed test cert):
|
|
222
|
+
NODE_TLS_REJECT_UNAUTHORIZED=0 node scripts/ahp-phase2.mjs --token <token> --base https://127.0.0.1:8765
|
|
183
223
|
```
|
|
184
224
|
|
|
185
225
|
## Publishing
|
package/options.example.jsonc
CHANGED
|
@@ -28,8 +28,10 @@
|
|
|
28
28
|
// ["vscode://vscode"]. The token is always required regardless (R5).
|
|
29
29
|
// "allowedOrigins": "*",
|
|
30
30
|
|
|
31
|
-
// Native TLS via Bun.serve → wss:// (
|
|
32
|
-
//
|
|
31
|
+
// Native TLS termination via Bun.serve → wss:// (off-LAN transports,
|
|
32
|
+
// D3). Paths to the PEM key and certificate files; with this set the
|
|
33
|
+
// port is TLS-only (health endpoint → `curl -k https://…/healthz`).
|
|
34
|
+
// The cert must be trusted by client machines for the URL hostname.
|
|
33
35
|
// "tls": { "keyPath": "/path/key.pem", "certPath": "/path/cert.pem" },
|
|
34
36
|
|
|
35
37
|
// Plain-HTTP health endpoint (no auth).
|
|
@@ -51,6 +53,10 @@
|
|
|
51
53
|
// "replayWindow": 1000,
|
|
52
54
|
|
|
53
55
|
// What initialize advertises — never advertise what we don't implement.
|
|
54
|
-
//
|
|
56
|
+
// Default: { "changesets": true, "terminals": false, "automations": false }.
|
|
57
|
+
// Set "changesets": false to disable the diff channels (no changeset
|
|
58
|
+
// catalogues in the session/chat snapshots; changeset URIs resolve to
|
|
59
|
+
// nothing). Changesets require the location directory to be a git
|
|
60
|
+
// repository.
|
|
55
61
|
// "capabilities": { "changesets": false, "terminals": false, "automations": false }
|
|
56
62
|
}
|
package/package.json
CHANGED
package/src/bridge.ts
CHANGED
|
@@ -13,7 +13,10 @@
|
|
|
13
13
|
* the host uses to seed session/chat stores.
|
|
14
14
|
*/
|
|
15
15
|
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "./channels.js";
|
|
16
17
|
import {
|
|
18
|
+
ChangesetOperationScope,
|
|
19
|
+
ChangesetOperationStatus,
|
|
17
20
|
CustomizationLoadStatus,
|
|
18
21
|
CustomizationType,
|
|
19
22
|
MessageKind,
|
|
@@ -21,10 +24,14 @@ import {
|
|
|
21
24
|
SessionStatus,
|
|
22
25
|
type AgentCustomization,
|
|
23
26
|
type AgentInfo,
|
|
27
|
+
type Changeset,
|
|
28
|
+
type ChangesetFile,
|
|
29
|
+
type ChangesetOperation,
|
|
24
30
|
type ChatSummary,
|
|
25
31
|
type ChatState,
|
|
26
32
|
type Customization,
|
|
27
33
|
type DirectoryCustomization,
|
|
34
|
+
type FileEdit,
|
|
28
35
|
type Message,
|
|
29
36
|
type SessionActiveClient,
|
|
30
37
|
type SessionState,
|
|
@@ -192,6 +199,41 @@ export interface OpencodeFacade {
|
|
|
192
199
|
* iterator ends (without error) when the signal aborts.
|
|
193
200
|
*/
|
|
194
201
|
events(signal: AbortSignal): AsyncIterable<FacadeEvent>;
|
|
202
|
+
// ── Phase 2: changesets ───────────────────────────────────────────────
|
|
203
|
+
/**
|
|
204
|
+
* Working-tree diff vs HEAD (uncommitted changes, untracked files
|
|
205
|
+
* included), with **absolute** file paths. `[]` when the location is
|
|
206
|
+
* not a git repo, has no changes, or the diff fails (R2: degrade to
|
|
207
|
+
* empty, never throw).
|
|
208
|
+
*/
|
|
209
|
+
vcsDiffWorking(): Promise<readonly FacadeDiffFile[]>;
|
|
210
|
+
/**
|
|
211
|
+
* The file's content in HEAD (`git show HEAD:<rel>`), or null when the
|
|
212
|
+
* location is not a repo, HEAD is missing, or the file is not tracked.
|
|
213
|
+
*/
|
|
214
|
+
gitHeadFile(absPath: string): Promise<string | null>;
|
|
215
|
+
/** Read a UTF-8 file from disk, or null when it does not exist. */
|
|
216
|
+
readFile(absPath: string): Promise<string | null>;
|
|
217
|
+
/** Write a UTF-8 file (creating parent directories as needed). */
|
|
218
|
+
writeFile(absPath: string, content: string): Promise<void>;
|
|
219
|
+
/** Delete a file; no-op when it does not exist. */
|
|
220
|
+
deleteFile(absPath: string): Promise<void>;
|
|
221
|
+
/**
|
|
222
|
+
* Discard changes to one file: tracked → `git checkout HEAD -- <rel>`
|
|
223
|
+
* (fallback delete), untracked → delete.
|
|
224
|
+
*/
|
|
225
|
+
discardFile(absPath: string): Promise<void>;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* One entry of a VCS working-tree diff (the facade's shape — absolute
|
|
230
|
+
* paths, unlike opencode's repo-root-relative `FileDiff.Info`).
|
|
231
|
+
*/
|
|
232
|
+
export interface FacadeDiffFile {
|
|
233
|
+
path: string;
|
|
234
|
+
additions: number;
|
|
235
|
+
deletions: number;
|
|
236
|
+
status: "added" | "deleted" | "modified";
|
|
195
237
|
}
|
|
196
238
|
|
|
197
239
|
// ── Phase 0: catalog mappers ─────────────────────────────────────────────
|
|
@@ -567,6 +609,7 @@ export function initialSessionState(input: {
|
|
|
567
609
|
activeClients?: SessionActiveClient[];
|
|
568
610
|
customizations?: Customization[];
|
|
569
611
|
status?: SessionStatus;
|
|
612
|
+
changesets?: Changeset[];
|
|
570
613
|
}): SessionState {
|
|
571
614
|
return {
|
|
572
615
|
provider: input.provider,
|
|
@@ -579,6 +622,7 @@ export function initialSessionState(input: {
|
|
|
579
622
|
...(input.customizations !== undefined && input.customizations.length > 0
|
|
580
623
|
? { customizations: input.customizations }
|
|
581
624
|
: {}),
|
|
625
|
+
...(input.changesets !== undefined ? { changesets: input.changesets } : {}),
|
|
582
626
|
};
|
|
583
627
|
}
|
|
584
628
|
|
|
@@ -587,6 +631,7 @@ export function initialChatState(input: {
|
|
|
587
631
|
resource: string;
|
|
588
632
|
title: string;
|
|
589
633
|
modifiedAt: string;
|
|
634
|
+
changesets?: Changeset[];
|
|
590
635
|
}): ChatState {
|
|
591
636
|
return {
|
|
592
637
|
resource: input.resource,
|
|
@@ -594,6 +639,7 @@ export function initialChatState(input: {
|
|
|
594
639
|
status: STATUS_IDLE_READ,
|
|
595
640
|
modifiedAt: input.modifiedAt,
|
|
596
641
|
turns: [],
|
|
642
|
+
...(input.changesets !== undefined ? { changesets: input.changesets } : {}),
|
|
597
643
|
};
|
|
598
644
|
}
|
|
599
645
|
|
|
@@ -720,3 +766,288 @@ export function pastTenseMessageFor(toolName: string, inputText: string | undefi
|
|
|
720
766
|
}
|
|
721
767
|
return msg;
|
|
722
768
|
}
|
|
769
|
+
|
|
770
|
+
// ── Phase 2: changesets ───────────────────────────────────────────────────
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Content-ref URIs the host serves through `resourceRead` (plan §14.10):
|
|
774
|
+
* - `ahp-content://head/<b64url(absPath)>` — the file's content in HEAD
|
|
775
|
+
* (`git show HEAD:<rel>`), for the "before" side of uncommitted/session
|
|
776
|
+
* changes;
|
|
777
|
+
* - `ahp-content://snap/<b64url(session)>/<b64url(turn)>/<b64url(absPath)>/<part>`
|
|
778
|
+
* — a turn's captured pre-edit (`before`) or post-turn (`after`) content
|
|
779
|
+
* from the in-memory snapshot store. Opaque and unguessable (base64url
|
|
780
|
+
* segments, not path segments) so a client cannot point the host at
|
|
781
|
+
* arbitrary snapshots.
|
|
782
|
+
*
|
|
783
|
+
* The "after" side of uncommitted/session changes is the live disk path
|
|
784
|
+
* itself (`file://`), read through `resourceRead` at view time.
|
|
785
|
+
*/
|
|
786
|
+
const CONTENT_REF_PREFIX = "ahp-content://";
|
|
787
|
+
const CONTENT_HEAD_MARKER = "ahp-content://head/";
|
|
788
|
+
const CONTENT_SNAP_MARKER = "ahp-content://snap/";
|
|
789
|
+
|
|
790
|
+
/** The `file://` URI of an absolute path (a `ChangesetFile.id`). */
|
|
791
|
+
export function fileUri(absPath: string): string {
|
|
792
|
+
return pathToFileURL(absPath).href;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** Content ref for a file's HEAD content (the "before" of a live diff). */
|
|
796
|
+
export function headContentRef(absPath: string): string {
|
|
797
|
+
return CONTENT_HEAD_MARKER + b64url(absPath);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** Content ref for one part of a turn's snapshot. */
|
|
801
|
+
export function snapContentRef(sessionID: string, turnId: string, absPath: string, part: "before" | "after"): string {
|
|
802
|
+
return `${CONTENT_SNAP_MARKER}${b64url(sessionID)}/${b64url(turnId)}/${b64url(absPath)}/${part}`;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** Parsed content-ref URI, or null when the URI is not one of ours. */
|
|
806
|
+
export type ParsedContentRef =
|
|
807
|
+
| { kind: "head"; path: string }
|
|
808
|
+
| { kind: "snap"; sessionID: string; turnId: string; path: string; part: "before" | "after" };
|
|
809
|
+
|
|
810
|
+
export function parseContentRef(uri: string): ParsedContentRef | null {
|
|
811
|
+
if (uri.startsWith(CONTENT_HEAD_MARKER)) {
|
|
812
|
+
const path = b64urlDecode(uri.slice(CONTENT_HEAD_MARKER.length));
|
|
813
|
+
return path !== null ? { kind: "head", path } : null;
|
|
814
|
+
}
|
|
815
|
+
if (uri.startsWith(CONTENT_SNAP_MARKER)) {
|
|
816
|
+
const segments = uri.slice(CONTENT_SNAP_MARKER.length).split("/");
|
|
817
|
+
if (segments.length !== 4) return null;
|
|
818
|
+
const [sessionID, turnId, path, part] = segments as [string, string, string, string];
|
|
819
|
+
const dSession = b64urlDecode(sessionID);
|
|
820
|
+
const dTurn = b64urlDecode(turnId);
|
|
821
|
+
const dPath = b64urlDecode(path);
|
|
822
|
+
if (dSession === null || dTurn === null || dPath === null) return null;
|
|
823
|
+
if (part !== "before" && part !== "after") return null;
|
|
824
|
+
return { kind: "snap", sessionID: dSession, turnId: dTurn, path: dPath, part };
|
|
825
|
+
}
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
function b64url(value: string): string {
|
|
830
|
+
return Buffer.from(value, "utf-8").toString("base64url");
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
function b64urlDecode(value: string): string | null {
|
|
834
|
+
if (value.length === 0) return null;
|
|
835
|
+
// base64url alphabet check — rejects path separators and junk, which is
|
|
836
|
+
// what keeps a malformed ref from being mis-split into other segments.
|
|
837
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null;
|
|
838
|
+
const text = Buffer.from(value, "base64url").toString("utf-8");
|
|
839
|
+
return text.length > 0 ? text : null;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Line diff stats for two file contents (port of the ahp-acp-gateway
|
|
844
|
+
* implementation, plan §14.10): CRLF-normalized, trailing newline ignored,
|
|
845
|
+
* common prefix/suffix stripped, then an LCS DP over the middle with a
|
|
846
|
+
* 40 000-cell cap (falls back to counting the whole middle when exceeded).
|
|
847
|
+
*/
|
|
848
|
+
export function computeLineDiffStats(
|
|
849
|
+
oldText: string | null | undefined,
|
|
850
|
+
newText: string | null | undefined,
|
|
851
|
+
): { added: number; removed: number } {
|
|
852
|
+
const splitLines = (text: string | null | undefined): string[] => {
|
|
853
|
+
if (!text) return [];
|
|
854
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
855
|
+
const lines = normalized.split("\n");
|
|
856
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") {
|
|
857
|
+
lines.pop();
|
|
858
|
+
}
|
|
859
|
+
return lines;
|
|
860
|
+
};
|
|
861
|
+
const oldLines = splitLines(oldText);
|
|
862
|
+
const newLines = splitLines(newText);
|
|
863
|
+
if (oldLines.length === 0) {
|
|
864
|
+
return { added: newLines.length, removed: 0 };
|
|
865
|
+
}
|
|
866
|
+
if (newLines.length === 0) {
|
|
867
|
+
return { added: 0, removed: oldLines.length };
|
|
868
|
+
}
|
|
869
|
+
let prefix = 0;
|
|
870
|
+
const minLen = Math.min(oldLines.length, newLines.length);
|
|
871
|
+
while (prefix < minLen && oldLines[prefix] === newLines[prefix]) {
|
|
872
|
+
prefix++;
|
|
873
|
+
}
|
|
874
|
+
let suffix = 0;
|
|
875
|
+
while (
|
|
876
|
+
suffix < minLen - prefix &&
|
|
877
|
+
oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]
|
|
878
|
+
) {
|
|
879
|
+
suffix++;
|
|
880
|
+
}
|
|
881
|
+
const oldMid = oldLines.slice(prefix, oldLines.length - suffix);
|
|
882
|
+
const newMid = newLines.slice(prefix, newLines.length - suffix);
|
|
883
|
+
if (oldMid.length * newMid.length > 40_000) {
|
|
884
|
+
return { added: newMid.length, removed: oldMid.length };
|
|
885
|
+
}
|
|
886
|
+
const dp = new Uint32Array((oldMid.length + 1) * (newMid.length + 1));
|
|
887
|
+
const width = newMid.length + 1;
|
|
888
|
+
for (let i = 1; i <= oldMid.length; i++) {
|
|
889
|
+
const oldLine = oldMid[i - 1]!;
|
|
890
|
+
for (let j = 1; j <= newMid.length; j++) {
|
|
891
|
+
const idx = i * width + j;
|
|
892
|
+
if (oldLine === newMid[j - 1]) {
|
|
893
|
+
dp[idx] = dp[(i - 1) * width + (j - 1)]! + 1;
|
|
894
|
+
} else {
|
|
895
|
+
const up = dp[(i - 1) * width + j]!;
|
|
896
|
+
const left = dp[i * width + (j - 1)]!;
|
|
897
|
+
dp[idx] = up >= left ? up : left;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const lcs = dp[oldMid.length * width + newMid.length]!;
|
|
902
|
+
return {
|
|
903
|
+
added: Math.max(0, newMid.length - lcs),
|
|
904
|
+
removed: Math.max(0, oldMid.length - lcs),
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/** The single operation this host advertises (plan §11 Phase 2). */
|
|
909
|
+
export const DISCARD_OPERATION_ID = "discard-changes";
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* The `discard-changes` operation (gateway-identical shape): restores one
|
|
913
|
+
* file from the changeset's "before" content — HEAD for uncommitted/session
|
|
914
|
+
* changes, the turn's pre-edit snapshot for turn changes.
|
|
915
|
+
*/
|
|
916
|
+
export function discardOperation(): ChangesetOperation {
|
|
917
|
+
return {
|
|
918
|
+
id: DISCARD_OPERATION_ID,
|
|
919
|
+
label: "Discard Changes",
|
|
920
|
+
confirmation: "Are you sure you want to discard changes to this file?",
|
|
921
|
+
icon: "discard",
|
|
922
|
+
scopes: [ChangesetOperationScope.Resource],
|
|
923
|
+
status: ChangesetOperationStatus.Idle,
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* The session channel's changeset catalogue: the session-wide changeset
|
|
929
|
+
* only (the protocol's "session" changeKind — all changes the agent has
|
|
930
|
+
* produced; approximated by the working tree vs HEAD, plan §14.10).
|
|
931
|
+
*/
|
|
932
|
+
export function sessionChangesetCatalog(sessionID: string): Changeset[] {
|
|
933
|
+
return [
|
|
934
|
+
{
|
|
935
|
+
label: "Session Changes",
|
|
936
|
+
uriTemplate: sessionChangesetURI(sessionID),
|
|
937
|
+
changeKind: "session",
|
|
938
|
+
capabilities: { review: {} },
|
|
939
|
+
},
|
|
940
|
+
];
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* The chat channel's changeset catalogue: uncommitted changes, the
|
|
945
|
+
* session-wide changeset, and the per-turn template (`{turnId}` expands
|
|
946
|
+
* against the chat's turns — the protocol's standard template shapes).
|
|
947
|
+
*/
|
|
948
|
+
export function chatChangesetCatalog(sessionID: string): Changeset[] {
|
|
949
|
+
return [
|
|
950
|
+
{
|
|
951
|
+
label: "Uncommitted Changes",
|
|
952
|
+
uriTemplate: uncommittedChangesetURI(sessionID),
|
|
953
|
+
changeKind: "uncommitted",
|
|
954
|
+
capabilities: { review: {} },
|
|
955
|
+
},
|
|
956
|
+
{
|
|
957
|
+
label: "Session Changes",
|
|
958
|
+
uriTemplate: sessionChangesetURI(sessionID),
|
|
959
|
+
changeKind: "session",
|
|
960
|
+
capabilities: { review: {} },
|
|
961
|
+
},
|
|
962
|
+
{
|
|
963
|
+
label: "Turn Changes",
|
|
964
|
+
uriTemplate: turnChangesetURI(sessionID, "{turnId}"),
|
|
965
|
+
changeKind: "turn",
|
|
966
|
+
capabilities: { review: {} },
|
|
967
|
+
},
|
|
968
|
+
];
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** Carry a file's previous `reviewed` flag into a rebuilt entry (gateway behavior). */
|
|
972
|
+
function withReviewed(file: ChangesetFile, reviewed: boolean | undefined): ChangesetFile {
|
|
973
|
+
return reviewed === undefined ? file : { ...file, reviewed };
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* `ChangesetFile` entries for the working-tree diff (the `uncommitted` and
|
|
978
|
+
* `session` changesets share this approximation, plan §14.10):
|
|
979
|
+
* - added → `after` only, live `file://` content ref;
|
|
980
|
+
* - deleted → `before` only, HEAD content ref;
|
|
981
|
+
* - modified → live `file://` after + HEAD before.
|
|
982
|
+
* `id` is the `file://` URI (the target of `invokeChangesetOperation`).
|
|
983
|
+
*/
|
|
984
|
+
export function buildWorkingChangesetFiles(input: {
|
|
985
|
+
diffs: readonly FacadeDiffFile[];
|
|
986
|
+
reviewedById: ReadonlyMap<string, boolean>;
|
|
987
|
+
}): ChangesetFile[] {
|
|
988
|
+
const out: ChangesetFile[] = [];
|
|
989
|
+
for (const f of input.diffs) {
|
|
990
|
+
if (f.path.length === 0) continue;
|
|
991
|
+
const id = fileUri(f.path);
|
|
992
|
+
const edit: FileEdit =
|
|
993
|
+
f.status === "added"
|
|
994
|
+
? {
|
|
995
|
+
after: { uri: id, content: { uri: id } },
|
|
996
|
+
diff: { added: f.additions, removed: 0 },
|
|
997
|
+
}
|
|
998
|
+
: f.status === "deleted"
|
|
999
|
+
? {
|
|
1000
|
+
before: { uri: id, content: { uri: headContentRef(f.path) } },
|
|
1001
|
+
diff: { added: 0, removed: f.deletions },
|
|
1002
|
+
}
|
|
1003
|
+
: {
|
|
1004
|
+
before: { uri: id, content: { uri: headContentRef(f.path) } },
|
|
1005
|
+
after: { uri: id, content: { uri: id } },
|
|
1006
|
+
diff: { added: f.additions, removed: f.deletions },
|
|
1007
|
+
};
|
|
1008
|
+
out.push(withReviewed({ id, edit }, input.reviewedById.get(id)));
|
|
1009
|
+
}
|
|
1010
|
+
return out;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* `ChangesetFile` entries for one turn's captured file changes:
|
|
1015
|
+
* - both sides use opaque snapshot content refs (the "after" is what the
|
|
1016
|
+
* host read from disk at turn end — strictly correct even if a later
|
|
1017
|
+
* turn edits the same file again);
|
|
1018
|
+
* - `before === null` → the turn added the file; `after === null` → the
|
|
1019
|
+
* turn deleted it; `before === after` → dropped (no net change).
|
|
1020
|
+
*/
|
|
1021
|
+
export function buildTurnChangesetFiles(input: {
|
|
1022
|
+
sessionID: string;
|
|
1023
|
+
turnId: string;
|
|
1024
|
+
/** absPath → captured {before, after} (null = file absent on that side). */
|
|
1025
|
+
files: ReadonlyMap<string, { before: string | null; after: string | null }>;
|
|
1026
|
+
reviewedById: ReadonlyMap<string, boolean>;
|
|
1027
|
+
}): ChangesetFile[] {
|
|
1028
|
+
const out: ChangesetFile[] = [];
|
|
1029
|
+
for (const [absPath, snap] of input.files) {
|
|
1030
|
+
if (snap.before === snap.after) continue;
|
|
1031
|
+
const id = fileUri(absPath);
|
|
1032
|
+
const beforeRef = snapContentRef(input.sessionID, input.turnId, absPath, "before");
|
|
1033
|
+
const afterRef = snapContentRef(input.sessionID, input.turnId, absPath, "after");
|
|
1034
|
+
const edit: FileEdit =
|
|
1035
|
+
snap.before === null
|
|
1036
|
+
? {
|
|
1037
|
+
after: { uri: id, content: { uri: afterRef } },
|
|
1038
|
+
diff: computeLineDiffStats(null, snap.after),
|
|
1039
|
+
}
|
|
1040
|
+
: snap.after === null
|
|
1041
|
+
? {
|
|
1042
|
+
before: { uri: id, content: { uri: beforeRef } },
|
|
1043
|
+
diff: computeLineDiffStats(snap.before, null),
|
|
1044
|
+
}
|
|
1045
|
+
: {
|
|
1046
|
+
before: { uri: id, content: { uri: beforeRef } },
|
|
1047
|
+
after: { uri: id, content: { uri: afterRef } },
|
|
1048
|
+
diff: computeLineDiffStats(snap.before, snap.after),
|
|
1049
|
+
};
|
|
1050
|
+
out.push(withReviewed({ id, edit }, input.reviewedById.get(id)));
|
|
1051
|
+
}
|
|
1052
|
+
return out;
|
|
1053
|
+
}
|
package/src/channels.ts
CHANGED
|
@@ -4,17 +4,26 @@
|
|
|
4
4
|
* sessions. Pure in-memory — no runtime dependencies.
|
|
5
5
|
*
|
|
6
6
|
* Phase 0 only the root channel is live; session/chat URI handling and
|
|
7
|
-
* the session registry land with Phase 1 (session support).
|
|
7
|
+
* the session registry land with Phase 1 (session support). Phase 2 adds
|
|
8
|
+
* the changeset channel kind (`<owner>/changeset/{uncommitted|session|
|
|
9
|
+
* turn/<turnId>}` — plan §11).
|
|
8
10
|
*/
|
|
9
11
|
|
|
10
12
|
export const ROOT_CHANNEL = "ahp-root://";
|
|
11
13
|
const SESSION_PREFIX = "ahp-session:/";
|
|
12
14
|
const CHAT_PREFIX = "ahp-chat:/";
|
|
15
|
+
const CHANGASET_MARKER = "/changeset/";
|
|
13
16
|
|
|
14
|
-
export type ChannelKind = "root" | "session" | "chat" | "unknown";
|
|
17
|
+
export type ChannelKind = "root" | "session" | "chat" | "changeset" | "unknown";
|
|
15
18
|
|
|
16
19
|
export function channelKind(uri: string): ChannelKind {
|
|
17
20
|
if (uri === ROOT_CHANNEL) return "root";
|
|
21
|
+
// A changeset URI is an owner session/chat URI plus `/changeset/<kind>`.
|
|
22
|
+
// Checked before the owner prefixes so `<sessionURI>/changeset/session`
|
|
23
|
+
// is not misread as a session channel whose suffix contains the marker
|
|
24
|
+
// (createSession rejects such suffixes, so no live session channel can
|
|
25
|
+
// contain the marker — plan §14).
|
|
26
|
+
if (uri.lastIndexOf(CHANGASET_MARKER) > 0) return "changeset";
|
|
18
27
|
if (uri.startsWith(SESSION_PREFIX) && uri.length > SESSION_PREFIX.length) return "session";
|
|
19
28
|
if (uri.startsWith(CHAT_PREFIX) && uri.length > CHAT_PREFIX.length) return "chat";
|
|
20
29
|
return "unknown";
|
|
@@ -42,6 +51,67 @@ export function sessionIDOf(uri: string): string | null {
|
|
|
42
51
|
return null;
|
|
43
52
|
}
|
|
44
53
|
|
|
54
|
+
/**
|
|
55
|
+
* The three changeset kinds this host advertises (plan §11 Phase 2):
|
|
56
|
+
* - `uncommitted`: working tree vs HEAD (owner: the chat channel);
|
|
57
|
+
* - `session`: session-wide changes, same approximation (owner: the
|
|
58
|
+
* session channel — the protocol's "session" changeKind);
|
|
59
|
+
* - `turn`: the files a single turn captured before its edits
|
|
60
|
+
* (owner: the chat channel; `turnId` is the AHP turn id).
|
|
61
|
+
*/
|
|
62
|
+
export type ChangesetKind = "uncommitted" | "session" | "turn";
|
|
63
|
+
|
|
64
|
+
export interface ParsedChangesetChannel {
|
|
65
|
+
/** The owner session/chat channel URI (valid — see `sessionIDOf`). */
|
|
66
|
+
ownerUri: string;
|
|
67
|
+
/** The owner's opencode session id. */
|
|
68
|
+
sessionID: string;
|
|
69
|
+
kind: ChangesetKind;
|
|
70
|
+
/** Present iff `kind === "turn"`. */
|
|
71
|
+
turnId?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Parse a changeset channel URI of the shape
|
|
76
|
+
* `<owner session|chat URI>/changeset/{uncommitted|session|turn/<turnId>}`,
|
|
77
|
+
* or null when the URI is not one. `lastIndexOf` splits on the LAST marker,
|
|
78
|
+
* and the owner must classify as a session/chat channel — so a URI whose
|
|
79
|
+
* owner itself contains the marker fails (no live session channel ever
|
|
80
|
+
* contains it: createSession rejects such suffixes).
|
|
81
|
+
*/
|
|
82
|
+
export function parseChangesetChannel(uri: string): ParsedChangesetChannel | null {
|
|
83
|
+
const index = uri.lastIndexOf(CHANGASET_MARKER);
|
|
84
|
+
if (index <= 0) return null;
|
|
85
|
+
const ownerUri = uri.slice(0, index);
|
|
86
|
+
const sessionID = sessionIDOf(ownerUri);
|
|
87
|
+
if (sessionID === null) return null;
|
|
88
|
+
const rest = uri.slice(index + CHANGASET_MARKER.length);
|
|
89
|
+
if (rest === "uncommitted" || rest === "session") {
|
|
90
|
+
return { ownerUri, sessionID, kind: rest };
|
|
91
|
+
}
|
|
92
|
+
if (rest.startsWith("turn/")) {
|
|
93
|
+
const turnId = rest.slice("turn/".length);
|
|
94
|
+
// Non-empty, no slashes: an AHP turn id (host-minted `turn-…`).
|
|
95
|
+
if (turnId.length > 0 && !turnId.includes("/")) return { ownerUri, sessionID, kind: "turn", turnId };
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Changeset URI of a session's uncommitted (working-tree) changes. */
|
|
101
|
+
export function uncommittedChangesetURI(sessionID: string): string {
|
|
102
|
+
return `${chatChannelURI(sessionID)}/changeset/uncommitted`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Changeset URI of a session's session-wide changes. */
|
|
106
|
+
export function sessionChangesetURI(sessionID: string): string {
|
|
107
|
+
return `${sessionChannelURI(sessionID)}/changeset/session`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Changeset URI of one turn's captured file changes. */
|
|
111
|
+
export function turnChangesetURI(sessionID: string, turnId: string): string {
|
|
112
|
+
return `${chatChannelURI(sessionID)}/changeset/turn/${turnId}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
45
115
|
export interface SubscribeOutcome {
|
|
46
116
|
ok: boolean;
|
|
47
117
|
reason?: "unknown-uri" | "no-such-session";
|
|
@@ -60,7 +130,14 @@ export class ChannelRegistry {
|
|
|
60
130
|
const kind = channelKind(uri);
|
|
61
131
|
if (kind === "unknown") return { ok: false, reason: "unknown-uri" };
|
|
62
132
|
if (kind !== "root") {
|
|
63
|
-
|
|
133
|
+
let id: string | null;
|
|
134
|
+
if (kind === "changeset") {
|
|
135
|
+
const parsed = parseChangesetChannel(uri);
|
|
136
|
+
if (parsed === null) return { ok: false, reason: "unknown-uri" };
|
|
137
|
+
id = parsed.sessionID;
|
|
138
|
+
} else {
|
|
139
|
+
id = sessionIDOf(uri);
|
|
140
|
+
}
|
|
64
141
|
if (id === null || !this.sessions.has(id)) return { ok: false, reason: "no-such-session" };
|
|
65
142
|
}
|
|
66
143
|
let set = this.subs.get(socketId);
|