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/src/host.ts
CHANGED
|
@@ -35,8 +35,13 @@
|
|
|
35
35
|
* *notifications* in AHP 1.0.0 (ephemeral, not replayed) — only
|
|
36
36
|
* `root/activeSessionsChanged` is a sequencer action.
|
|
37
37
|
*/
|
|
38
|
+
import { resolve as resolvePath } from "node:path";
|
|
39
|
+
import { fileURLToPath } from "node:url";
|
|
38
40
|
import {
|
|
39
41
|
ActionType,
|
|
42
|
+
ChangesetOperationScope,
|
|
43
|
+
ChangesetOperationStatus,
|
|
44
|
+
ChangesetStatus,
|
|
40
45
|
PendingMessageKind,
|
|
41
46
|
ReconnectResultType,
|
|
42
47
|
ResponsePartKind,
|
|
@@ -54,6 +59,8 @@ import {
|
|
|
54
59
|
type ChatToolCallConfirmedAction,
|
|
55
60
|
type ChatTurnCancelledAction,
|
|
56
61
|
type ChatTurnStartedAction,
|
|
62
|
+
type ChangesetAction,
|
|
63
|
+
type ChangesetFilesReviewChangedAction,
|
|
57
64
|
type ErrorResponsePart,
|
|
58
65
|
type Implementation,
|
|
59
66
|
type Message,
|
|
@@ -75,14 +82,21 @@ import {
|
|
|
75
82
|
agentDirectoryCustomization,
|
|
76
83
|
agentIDFromUri,
|
|
77
84
|
buildSessionSummary,
|
|
85
|
+
buildTurnChangesetFiles,
|
|
86
|
+
buildWorkingChangesetFiles,
|
|
87
|
+
chatChangesetCatalog,
|
|
78
88
|
chatSummaryOf,
|
|
79
89
|
displayNameFor,
|
|
90
|
+
discardOperation,
|
|
91
|
+
fileUri,
|
|
80
92
|
initialChatState,
|
|
81
93
|
initialSessionState,
|
|
82
94
|
invocationMessageFor,
|
|
83
95
|
mapCatalog,
|
|
84
96
|
mapAgentCustomizations,
|
|
97
|
+
parseContentRef,
|
|
85
98
|
pastTenseMessageFor,
|
|
99
|
+
sessionChangesetCatalog,
|
|
86
100
|
userMessage,
|
|
87
101
|
type FacadeDelivery,
|
|
88
102
|
type FacadeEvent,
|
|
@@ -90,15 +104,28 @@ import {
|
|
|
90
104
|
type FacadeSession,
|
|
91
105
|
type OpencodeFacade,
|
|
92
106
|
} from "./bridge.js";
|
|
93
|
-
import {
|
|
107
|
+
import {
|
|
108
|
+
ChannelRegistry,
|
|
109
|
+
ROOT_CHANNEL,
|
|
110
|
+
channelKind,
|
|
111
|
+
chatChannelURI,
|
|
112
|
+
parseChangesetChannel,
|
|
113
|
+
sessionChannelURI,
|
|
114
|
+
sessionChangesetURI,
|
|
115
|
+
sessionIDOf,
|
|
116
|
+
turnChangesetURI,
|
|
117
|
+
uncommittedChangesetURI,
|
|
118
|
+
} from "./channels.js";
|
|
94
119
|
import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
|
|
95
120
|
import { isRecord } from "./options.js";
|
|
96
121
|
import { Sequencer } from "./seq.js";
|
|
97
122
|
import {
|
|
98
123
|
createChatStateStore,
|
|
124
|
+
createChangesetStateStore,
|
|
99
125
|
createRootStateStore,
|
|
100
126
|
createSessionStateStore,
|
|
101
127
|
type ChatStateStore,
|
|
128
|
+
type ChangesetStateStore,
|
|
102
129
|
type RootStateStore,
|
|
103
130
|
type SessionStateStore,
|
|
104
131
|
} from "./state.js";
|
|
@@ -110,6 +137,8 @@ export const ERROR_INTERNAL = -32603;
|
|
|
110
137
|
export const ERROR_SESSION_NOT_FOUND = -32001;
|
|
111
138
|
export const ERROR_NO_PROVIDER = -32002;
|
|
112
139
|
export const ERROR_SESSION_EXISTS = -32003;
|
|
140
|
+
export const ERROR_NOT_FOUND = -32008;
|
|
141
|
+
export const ERROR_PERMISSION_DENIED = -32009;
|
|
113
142
|
|
|
114
143
|
// ActionType / ReconnectResultType are `declare const enum` in the package
|
|
115
144
|
// but are also real runtime objects (verified against the published dist),
|
|
@@ -177,6 +206,16 @@ interface SessionRecord {
|
|
|
177
206
|
toolForPermission: Map<string, string>;
|
|
178
207
|
/** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
|
|
179
208
|
lastInbox: { text: string; delivery: string } | null;
|
|
209
|
+
// ── Phase 2: changesets ────────────────────────────────────────────────
|
|
210
|
+
/** Live changeset stores, keyed by changeset URI (created on subscribe). */
|
|
211
|
+
changesets: Map<string, ChangesetStateStore>;
|
|
212
|
+
/**
|
|
213
|
+
* Per-turn file snapshots for the turn changesets: turnId → absPath →
|
|
214
|
+
* captured {before (pre-edit disk read), after (disk at turn end)}.
|
|
215
|
+
* `null` = the file was absent on that side. Kept until the session is
|
|
216
|
+
* removed (content refs + discard-restore read them, plan §14.10).
|
|
217
|
+
*/
|
|
218
|
+
turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
|
|
180
219
|
}
|
|
181
220
|
|
|
182
221
|
export interface HostOptions {
|
|
@@ -185,6 +224,8 @@ export interface HostOptions {
|
|
|
185
224
|
replayWindow: number;
|
|
186
225
|
/** The opencode instance's working directory (InitializeResult.defaultDirectory). */
|
|
187
226
|
defaultDirectory?: string;
|
|
227
|
+
/** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
|
|
228
|
+
changesets: boolean;
|
|
188
229
|
/** Deliver a JSON-serializable frame to a connection. */
|
|
189
230
|
send: (socketId: number, message: unknown) => void;
|
|
190
231
|
/** Close one connection (a superseded duplicate clientId). */
|
|
@@ -203,6 +244,14 @@ const RECONNECT_DEFAULT_VERSION = "1.0.0";
|
|
|
203
244
|
const EXTERNAL_REGISTER_GRACE_MS = 250;
|
|
204
245
|
/** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
|
|
205
246
|
const LIST_SESSIONS_DEFAULT_LIMIT = 100;
|
|
247
|
+
/**
|
|
248
|
+
* The file-mutating opencode tools whose inputs carry a target path — the
|
|
249
|
+
* turn-changeset before-capture watches only these (`tool.input.ended`
|
|
250
|
+
* fires before execution, so the pre-edit content is still on disk).
|
|
251
|
+
*/
|
|
252
|
+
const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
|
|
253
|
+
/** The tool-input keys that carry a file path (checked in order). */
|
|
254
|
+
const SNAPSHOT_PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
|
|
206
255
|
|
|
207
256
|
export class Host {
|
|
208
257
|
private readonly seq: Sequencer;
|
|
@@ -373,6 +422,12 @@ export class Host {
|
|
|
373
422
|
case "createSession":
|
|
374
423
|
await this.handleCreateSession(socketId, msg);
|
|
375
424
|
break;
|
|
425
|
+
case "resourceRead":
|
|
426
|
+
await this.handleResourceRead(socketId, msg);
|
|
427
|
+
break;
|
|
428
|
+
case "invokeChangesetOperation":
|
|
429
|
+
await this.handleInvokeChangesetOperation(socketId, msg);
|
|
430
|
+
break;
|
|
376
431
|
case "setClientManagedSettingsPermissions":
|
|
377
432
|
// VS Code-specific post-init notification (plan §14.7): the
|
|
378
433
|
// permissions VS Code manages in its own settings UI. AHP 1.0.0
|
|
@@ -577,6 +632,14 @@ export class Host {
|
|
|
577
632
|
return;
|
|
578
633
|
}
|
|
579
634
|
const suffix = sessionIDOf(channel) as string;
|
|
635
|
+
// A suffix containing the changeset marker would make this session
|
|
636
|
+
// channel string-identical to the changeset URI of the session before
|
|
637
|
+
// the marker — the changeset kind would win (channelKind), making the
|
|
638
|
+
// session channel un-subscribable. Reject it instead.
|
|
639
|
+
if (suffix.includes("/changeset/")) {
|
|
640
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "channel suffix must not contain \"/changeset/\"");
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
580
643
|
for (const rec of this.sessions.values()) {
|
|
581
644
|
if (rec.channel === channel) {
|
|
582
645
|
this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
|
|
@@ -670,6 +733,8 @@ export class Host {
|
|
|
670
733
|
permissionForTool: new Map(),
|
|
671
734
|
toolForPermission: new Map(),
|
|
672
735
|
lastInbox: null,
|
|
736
|
+
changesets: new Map(),
|
|
737
|
+
turnSnapshots: new Map(),
|
|
673
738
|
};
|
|
674
739
|
this.sessions.set(created.sessionID, rec);
|
|
675
740
|
this.byChannel.set(channel, rec);
|
|
@@ -690,6 +755,19 @@ export class Host {
|
|
|
690
755
|
channel,
|
|
691
756
|
action: { type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(created.sessionID) },
|
|
692
757
|
});
|
|
758
|
+
// Phase 2: advertise the changeset catalogues (session channel: the
|
|
759
|
+
// session-wide changeset; chat channel: uncommitted + session + the
|
|
760
|
+
// per-turn template).
|
|
761
|
+
if (this.opts.changesets) {
|
|
762
|
+
this.publish({
|
|
763
|
+
channel,
|
|
764
|
+
action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(created.sessionID) },
|
|
765
|
+
});
|
|
766
|
+
this.publish({
|
|
767
|
+
channel: chatChannelURI(created.sessionID),
|
|
768
|
+
action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(created.sessionID) },
|
|
769
|
+
});
|
|
770
|
+
}
|
|
693
771
|
// Root: active-session count (action, replayed) + sessionAdded (notification).
|
|
694
772
|
this.publish({
|
|
695
773
|
channel: ROOT_CHANNEL,
|
|
@@ -778,6 +856,16 @@ export class Host {
|
|
|
778
856
|
}
|
|
779
857
|
|
|
780
858
|
const kind = channelKind(channel);
|
|
859
|
+
if (kind === "changeset") {
|
|
860
|
+
// The only client-dispatchable changeset action is the per-file
|
|
861
|
+
// review toggle — echo it through the official reducer.
|
|
862
|
+
if (stateAction.type === ActionType.ChangesetFilesReviewChanged) {
|
|
863
|
+
this.dispatchChangesetFilesReviewChanged(channel, stateAction, origin);
|
|
864
|
+
} else {
|
|
865
|
+
this.echo(channel, stateAction, origin, `unsupported action on changeset channel: ${String(action.type)}`);
|
|
866
|
+
}
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
781
869
|
if (kind !== "session" && kind !== "chat") {
|
|
782
870
|
this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
|
|
783
871
|
return;
|
|
@@ -1054,7 +1142,28 @@ export class Host {
|
|
|
1054
1142
|
// The opencode `session.execution.interrupted` event finds no active
|
|
1055
1143
|
// turn after the echo finalized it (skipped); run the queued/steering
|
|
1056
1144
|
// handoff now, on the host side.
|
|
1057
|
-
this.finishTurn(rec);
|
|
1145
|
+
await this.finishTurn(rec);
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* `changeset/filesReviewChanged` (the only client-dispatchable changeset
|
|
1150
|
+
* action): validate the channel resolves to a live store, then echo —
|
|
1151
|
+
* the official reducer toggles `reviewed` per matched file id.
|
|
1152
|
+
*/
|
|
1153
|
+
private dispatchChangesetFilesReviewChanged(channel: string, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
1154
|
+
const a = action as ChangesetFilesReviewChangedAction;
|
|
1155
|
+
if (!Array.isArray(a.files) || !a.files.every((f) => typeof f === "string") || typeof a.reviewed !== "boolean") {
|
|
1156
|
+
this.echo(channel, action, origin, "invalid changeset/filesReviewChanged params");
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
const parsed = parseChangesetChannel(channel);
|
|
1160
|
+
const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
|
|
1161
|
+
const store = rec !== undefined ? rec.changesets.get(channel) : undefined;
|
|
1162
|
+
if (rec === undefined || store === undefined) {
|
|
1163
|
+
this.echo(channel, action, origin, "no such changeset");
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
this.echo(channel, action, origin);
|
|
1058
1167
|
}
|
|
1059
1168
|
|
|
1060
1169
|
private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
@@ -1160,7 +1269,7 @@ export class Host {
|
|
|
1160
1269
|
channel: chatURI,
|
|
1161
1270
|
action: { type: ActionType.ChatTurnComplete, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
|
|
1162
1271
|
});
|
|
1163
|
-
this.finishTurn(rec);
|
|
1272
|
+
await this.finishTurn(rec);
|
|
1164
1273
|
return;
|
|
1165
1274
|
case "execution.failed":
|
|
1166
1275
|
if (rec.currentTurnId === null) return;
|
|
@@ -1172,7 +1281,7 @@ export class Host {
|
|
|
1172
1281
|
channel: chatURI,
|
|
1173
1282
|
action: { type: ActionType.ChatError, turnId: rec.currentTurnId, duration: this.turnDuration(rec), part },
|
|
1174
1283
|
});
|
|
1175
|
-
this.finishTurn(rec);
|
|
1284
|
+
await this.finishTurn(rec);
|
|
1176
1285
|
return;
|
|
1177
1286
|
case "execution.interrupted":
|
|
1178
1287
|
// Skipped when the client's own `chat/turnCancelled` echo already
|
|
@@ -1182,7 +1291,7 @@ export class Host {
|
|
|
1182
1291
|
channel: chatURI,
|
|
1183
1292
|
action: { type: ActionType.ChatTurnCancelled, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
|
|
1184
1293
|
});
|
|
1185
|
-
this.finishTurn(rec);
|
|
1294
|
+
await this.finishTurn(rec);
|
|
1186
1295
|
return;
|
|
1187
1296
|
case "step.started":
|
|
1188
1297
|
rec.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
|
|
@@ -1256,6 +1365,11 @@ export class Host {
|
|
|
1256
1365
|
return;
|
|
1257
1366
|
case "tool.input.ended":
|
|
1258
1367
|
rec.toolInput.set(ev.id, ev.text);
|
|
1368
|
+
// Phase 2: for file-mutating tools, capture the pre-edit file
|
|
1369
|
+
// content now (the event fires before execution — the last safe
|
|
1370
|
+
// point). Awaited in the sequential pump so the capture is
|
|
1371
|
+
// complete before `execution.*` can end the turn.
|
|
1372
|
+
if (this.opts.changesets) await this.captureTurnBefore(rec, ev.id, ev.text);
|
|
1259
1373
|
return;
|
|
1260
1374
|
case "tool.progress":
|
|
1261
1375
|
// First sign the tool is actually running (opencode auto-approved):
|
|
@@ -1403,8 +1517,13 @@ export class Host {
|
|
|
1403
1517
|
* during the turn, and auto-start the next turn from the queue (the
|
|
1404
1518
|
* queued prompt was already sent with `delivery: "queue"` — opencode
|
|
1405
1519
|
* starts it automatically; this only updates the AHP state).
|
|
1520
|
+
*
|
|
1521
|
+
* Phase 2: then refresh the session's changesets — the turn's captured
|
|
1522
|
+
* "after" content is read from disk here, and the uncommitted/session/
|
|
1523
|
+
* turn changesets recompute (async: awaits the facade).
|
|
1406
1524
|
*/
|
|
1407
|
-
private finishTurn(rec: SessionRecord): void {
|
|
1525
|
+
private async finishTurn(rec: SessionRecord): Promise<void> {
|
|
1526
|
+
const endedTurnId = rec.currentTurnId;
|
|
1408
1527
|
rec.currentTurnId = null;
|
|
1409
1528
|
rec.turnStartedAt = null;
|
|
1410
1529
|
const state = rec.chatStore.state;
|
|
@@ -1426,6 +1545,373 @@ export class Host {
|
|
|
1426
1545
|
// A queued prompt from outside AHP (e.g. the TUI).
|
|
1427
1546
|
this.startTurn(rec, userMessage(rec.lastInbox.text));
|
|
1428
1547
|
}
|
|
1548
|
+
if (this.opts.changesets && endedTurnId !== null) {
|
|
1549
|
+
await this.refreshTurnChangesets(rec, endedTurnId);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// ── Phase 2: changesets ────────────────────────────────────────────────
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* Capture the pre-edit content of a file-mutating tool's target file for
|
|
1557
|
+
* the current turn's changeset (first capture per file wins — the
|
|
1558
|
+
* pre-turn content survives later edits in the same turn). No-op when
|
|
1559
|
+
* the tool is not file-mutating, the input carries no parseable path,
|
|
1560
|
+
* or the path resolves outside the location directory.
|
|
1561
|
+
*/
|
|
1562
|
+
private async captureTurnBefore(rec: SessionRecord, toolCallId: string, inputJson: string): Promise<void> {
|
|
1563
|
+
const turnId = rec.currentTurnId;
|
|
1564
|
+
const toolName = rec.toolName.get(toolCallId);
|
|
1565
|
+
if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
|
|
1566
|
+
let parsed: unknown;
|
|
1567
|
+
try {
|
|
1568
|
+
parsed = JSON.parse(inputJson);
|
|
1569
|
+
} catch {
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
if (!isRecord(parsed)) return;
|
|
1573
|
+
const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
|
|
1574
|
+
if (typeof rawPath !== "string") return;
|
|
1575
|
+
const absPath = this.resolveSnapshotPath(rawPath);
|
|
1576
|
+
if (absPath === null) {
|
|
1577
|
+
this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
let before: string | null;
|
|
1581
|
+
try {
|
|
1582
|
+
before = await this.opts.facade.readFile(absPath);
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
this.log(`turn snapshot: read of ${absPath} failed: ${errorMessage(err)}`);
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1587
|
+
// The pump is sequential, so the turn cannot have ended between the
|
|
1588
|
+
// call and the await — but the record may be gone (session deleted).
|
|
1589
|
+
if (rec.currentTurnId !== turnId || !this.sessions.has(rec.sessionID)) return;
|
|
1590
|
+
const turnFiles = rec.turnSnapshots.get(turnId) ?? new Map();
|
|
1591
|
+
if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
|
|
1592
|
+
rec.turnSnapshots.set(turnId, turnFiles);
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
/** Resolve a tool-input path against the location directory (must stay inside it). */
|
|
1596
|
+
private resolveSnapshotPath(rawPath: string): string | null {
|
|
1597
|
+
const dir = this.opts.defaultDirectory;
|
|
1598
|
+
if (dir === undefined) return null;
|
|
1599
|
+
const absPath = resolvePath(dir, rawPath);
|
|
1600
|
+
return isPathInside(absPath, dir) ? absPath : null;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
/** Get-or-create the changeset store for a URI (fresh stores start computing). */
|
|
1604
|
+
private changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore {
|
|
1605
|
+
let store = rec.changesets.get(uri);
|
|
1606
|
+
if (store === undefined) {
|
|
1607
|
+
store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
|
|
1608
|
+
rec.changesets.set(uri, store);
|
|
1609
|
+
}
|
|
1610
|
+
return store;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
/** The store's current per-file review flags, keyed by file id. */
|
|
1614
|
+
private reviewedById(store: ChangesetStateStore): Map<string, boolean> {
|
|
1615
|
+
const out = new Map<string, boolean>();
|
|
1616
|
+
for (const f of store.state.files) {
|
|
1617
|
+
if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
|
|
1618
|
+
}
|
|
1619
|
+
return out;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/**
|
|
1623
|
+
* Recompute one changeset and publish the delta (gateway's
|
|
1624
|
+
* `updateChangesetChannel` pattern): `changeset/contentChanged` when the
|
|
1625
|
+
* file list changed (the discard operation is (re)attached while files
|
|
1626
|
+
* exist, and cleared when they vanish), then `changeset/statusChanged`
|
|
1627
|
+
* to ready when the status was not ready. A failed computation publishes
|
|
1628
|
+
* `changeset/statusChanged` with an error.
|
|
1629
|
+
*/
|
|
1630
|
+
private async refreshChangeset(rec: SessionRecord, uri: string): Promise<void> {
|
|
1631
|
+
const parsed = parseChangesetChannel(uri);
|
|
1632
|
+
if (parsed === null) return;
|
|
1633
|
+
const store = this.changesetStore(rec, uri);
|
|
1634
|
+
let files;
|
|
1635
|
+
try {
|
|
1636
|
+
if (parsed.kind === "turn") {
|
|
1637
|
+
files = buildTurnChangesetFiles({
|
|
1638
|
+
sessionID: parsed.sessionID,
|
|
1639
|
+
turnId: parsed.turnId ?? "",
|
|
1640
|
+
files: rec.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
|
|
1641
|
+
reviewedById: this.reviewedById(store),
|
|
1642
|
+
});
|
|
1643
|
+
} else {
|
|
1644
|
+
const diffs = await this.opts.facade.vcsDiffWorking();
|
|
1645
|
+
files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
|
|
1646
|
+
}
|
|
1647
|
+
} catch (err) {
|
|
1648
|
+
this.publish({
|
|
1649
|
+
channel: uri,
|
|
1650
|
+
action: {
|
|
1651
|
+
type: ActionType.ChangesetStatusChanged,
|
|
1652
|
+
status: ChangesetStatus.Error,
|
|
1653
|
+
error: { errorType: "changeset-computation", message: errorMessage(err) },
|
|
1654
|
+
},
|
|
1655
|
+
});
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const state = store.state;
|
|
1659
|
+
const hadFiles = state.files.length > 0;
|
|
1660
|
+
const hasFiles = files.length > 0;
|
|
1661
|
+
if (JSON.stringify(state.files) !== JSON.stringify(files)) {
|
|
1662
|
+
this.publish({
|
|
1663
|
+
channel: uri,
|
|
1664
|
+
action: {
|
|
1665
|
+
type: ActionType.ChangesetContentChanged,
|
|
1666
|
+
files,
|
|
1667
|
+
...(hasFiles ? { operations: [discardOperation()] } : {}),
|
|
1668
|
+
},
|
|
1669
|
+
});
|
|
1670
|
+
// operations persist across contentChanged — clear them explicitly
|
|
1671
|
+
// when the changeset empties out.
|
|
1672
|
+
if (!hasFiles && state.operations !== undefined && state.operations.length > 0) {
|
|
1673
|
+
this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: undefined } });
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
if (!hadFiles && hasFiles && state.operations === undefined) {
|
|
1677
|
+
// contentChanged above already attached the operation; this branch
|
|
1678
|
+
// is unreachable unless the reducer drops it — kept as a guard.
|
|
1679
|
+
this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: [discardOperation()] } });
|
|
1680
|
+
}
|
|
1681
|
+
if (state.status !== ChangesetStatus.Ready) {
|
|
1682
|
+
this.publish({ channel: uri, action: { type: ActionType.ChangesetStatusChanged, status: ChangesetStatus.Ready } });
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
/**
|
|
1687
|
+
* At a turn terminal: read the disk into each captured file's `after`
|
|
1688
|
+
* (a file deleted during the turn stays null → "deleted"), then refresh
|
|
1689
|
+
* the uncommitted, session, and ended-turn changesets — only the ones a
|
|
1690
|
+
* client has subscribed (unsubscribed changesets cost no seq).
|
|
1691
|
+
*/
|
|
1692
|
+
private async refreshTurnChangesets(rec: SessionRecord, turnId: string): Promise<void> {
|
|
1693
|
+
const turnFiles = rec.turnSnapshots.get(turnId);
|
|
1694
|
+
if (turnFiles !== undefined) {
|
|
1695
|
+
for (const [absPath, snap] of turnFiles) {
|
|
1696
|
+
if (snap.after === null) {
|
|
1697
|
+
try {
|
|
1698
|
+
snap.after = await this.opts.facade.readFile(absPath);
|
|
1699
|
+
} catch {
|
|
1700
|
+
snap.after = null;
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
for (const uri of [
|
|
1706
|
+
uncommittedChangesetURI(rec.sessionID),
|
|
1707
|
+
sessionChangesetURI(rec.sessionID),
|
|
1708
|
+
turnChangesetURI(rec.sessionID, turnId),
|
|
1709
|
+
]) {
|
|
1710
|
+
if (rec.changesets.has(uri)) await this.refreshChangeset(rec, uri);
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
/**
|
|
1715
|
+
* `resourceRead` (AHP root command): serve file content for the URIs
|
|
1716
|
+
* this host advertises in changesets —
|
|
1717
|
+
* - `file://` → live disk, confined to the location directory;
|
|
1718
|
+
* - `ahp-content://head/…` → the file's HEAD content;
|
|
1719
|
+
* - `ahp-content://snap/…` → a turn's captured before/after content.
|
|
1720
|
+
* Errors: -32008 (not found), -32009 (path outside the location).
|
|
1721
|
+
*/
|
|
1722
|
+
private async handleResourceRead(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1723
|
+
const params = isRecord(msg.params) ? msg.params : {};
|
|
1724
|
+
const uri = params["uri"];
|
|
1725
|
+
if (typeof uri !== "string" || uri.length === 0) {
|
|
1726
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resourceRead requires a content URI");
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
const encoding: "base64" | "utf-8" = params["encoding"] === "utf-8" ? "utf-8" : "base64";
|
|
1730
|
+
if (uri.startsWith("file://")) {
|
|
1731
|
+
let absPath: string;
|
|
1732
|
+
try {
|
|
1733
|
+
absPath = fileURLToPath(uri);
|
|
1734
|
+
} catch {
|
|
1735
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
|
|
1739
|
+
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
let content: string | null;
|
|
1743
|
+
try {
|
|
1744
|
+
content = await this.opts.facade.readFile(absPath);
|
|
1745
|
+
} catch (err) {
|
|
1746
|
+
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, `read failed: ${errorMessage(err)}`);
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
if (content === null) {
|
|
1750
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
// Opaque content refs require the changesets capability.
|
|
1757
|
+
if (!this.opts.changesets) {
|
|
1758
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const ref = parseContentRef(uri);
|
|
1762
|
+
if (ref === null) {
|
|
1763
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1766
|
+
if (ref.kind === "head") {
|
|
1767
|
+
if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
|
|
1768
|
+
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
let content: string | null;
|
|
1772
|
+
try {
|
|
1773
|
+
content = await this.opts.facade.gitHeadFile(ref.path);
|
|
1774
|
+
} catch (err) {
|
|
1775
|
+
this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
if (content === null) {
|
|
1779
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not in HEAD: ${ref.path}`);
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
// snap — in-memory turn snapshot of a live session.
|
|
1786
|
+
const rec = this.sessions.get(ref.sessionID);
|
|
1787
|
+
if (rec === undefined) {
|
|
1788
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
const snap = rec.turnSnapshots.get(ref.turnId)?.get(ref.path);
|
|
1792
|
+
const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
|
|
1793
|
+
if (content === null) {
|
|
1794
|
+
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
/** Encode content for a `resourceRead` result (utf-8 or base64). */
|
|
1801
|
+
private encodeContent(content: string, encoding: "base64" | "utf-8") {
|
|
1802
|
+
return {
|
|
1803
|
+
data: encoding === "utf-8" ? content : Buffer.from(content, "utf-8").toString("base64"),
|
|
1804
|
+
encoding,
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
/**
|
|
1809
|
+
* `invokeChangesetOperation`: the host's only operation is
|
|
1810
|
+
* `discard-changes` (resource-scoped) — restore one file from the
|
|
1811
|
+
* changeset's "before" content. Status flows through the
|
|
1812
|
+
* `changeset/operationStatusChanged` stream; the JSON-RPC result carries
|
|
1813
|
+
* a human-readable message.
|
|
1814
|
+
*/
|
|
1815
|
+
private async handleInvokeChangesetOperation(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1816
|
+
const params = isRecord(msg.params) ? msg.params : {};
|
|
1817
|
+
const channel = params["channel"];
|
|
1818
|
+
const operationId = params["operationId"];
|
|
1819
|
+
if (typeof channel !== "string" || channel.length === 0 || typeof operationId !== "string" || operationId.length === 0) {
|
|
1820
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "invokeChangesetOperation requires channel + operationId");
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
const parsed = parseChangesetChannel(channel);
|
|
1824
|
+
if (parsed === null) {
|
|
1825
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
const rec = this.sessions.get(parsed.sessionID);
|
|
1829
|
+
if (rec === undefined) {
|
|
1830
|
+
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
const store = rec.changesets.get(channel);
|
|
1834
|
+
if (store === undefined) {
|
|
1835
|
+
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
const op = store.state.operations?.find((o) => o.id === operationId);
|
|
1839
|
+
if (op === undefined) {
|
|
1840
|
+
this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, `unknown operation: ${operationId}`);
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
if (!op.scopes.includes(ChangesetOperationScope.Resource)) {
|
|
1844
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `operation ${operationId} is not resource-scoped`);
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const target = params["target"];
|
|
1848
|
+
if (!isRecord(target) || target["kind"] !== "resource" || typeof target["resource"] !== "string") {
|
|
1849
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resource-scoped operation requires a resource target");
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
let absPath: string;
|
|
1853
|
+
try {
|
|
1854
|
+
absPath = fileURLToPath(target["resource"] as string);
|
|
1855
|
+
} catch {
|
|
1856
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "target.resource must be a file URI");
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
if (!store.state.files.some((f) => f.id === fileUri(absPath))) {
|
|
1860
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1863
|
+
if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
|
|
1864
|
+
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
this.publish({
|
|
1868
|
+
channel,
|
|
1869
|
+
action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Running },
|
|
1870
|
+
});
|
|
1871
|
+
try {
|
|
1872
|
+
if (parsed.kind === "turn" && parsed.turnId !== undefined) {
|
|
1873
|
+
await this.restoreTurnFile(rec, parsed.turnId, absPath);
|
|
1874
|
+
} else {
|
|
1875
|
+
await this.opts.facade.discardFile(absPath);
|
|
1876
|
+
}
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
this.publish({
|
|
1879
|
+
channel,
|
|
1880
|
+
action: {
|
|
1881
|
+
type: ActionType.ChangesetOperationStatusChanged,
|
|
1882
|
+
operationId,
|
|
1883
|
+
status: ChangesetOperationStatus.Error,
|
|
1884
|
+
error: { errorType: "operation-failed", message: errorMessage(err) },
|
|
1885
|
+
},
|
|
1886
|
+
});
|
|
1887
|
+
this.sendError(socketId, msg.id, ERROR_INTERNAL, errorMessage(err));
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
await this.refreshChangeset(rec, channel);
|
|
1891
|
+
this.publish({
|
|
1892
|
+
channel,
|
|
1893
|
+
action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Idle },
|
|
1894
|
+
});
|
|
1895
|
+
this.sendFrame(socketId, {
|
|
1896
|
+
jsonrpc: "2.0",
|
|
1897
|
+
id: msg.id ?? null,
|
|
1898
|
+
result: { message: `Discarded changes to ${absPath}` },
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
/**
|
|
1903
|
+
* Restore one file from a turn's before-snapshot: the file was added by
|
|
1904
|
+
* the turn (before === null) → delete it; otherwise write the pre-edit
|
|
1905
|
+
* content back.
|
|
1906
|
+
*/
|
|
1907
|
+
private async restoreTurnFile(rec: SessionRecord, turnId: string, absPath: string): Promise<void> {
|
|
1908
|
+
const snap = rec.turnSnapshots.get(turnId)?.get(absPath);
|
|
1909
|
+
const before = snap?.before ?? null;
|
|
1910
|
+
if (before === null) {
|
|
1911
|
+
await this.opts.facade.deleteFile(absPath);
|
|
1912
|
+
} else {
|
|
1913
|
+
await this.opts.facade.writeFile(absPath, before);
|
|
1914
|
+
}
|
|
1429
1915
|
}
|
|
1430
1916
|
|
|
1431
1917
|
/**
|
|
@@ -1538,6 +2024,12 @@ export class Host {
|
|
|
1538
2024
|
sessionStore.apply({ type: ActionType.SessionReady });
|
|
1539
2025
|
sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) });
|
|
1540
2026
|
sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(fs.sessionID) });
|
|
2027
|
+
// Phase 2: advertise the changeset catalogues directly on the fresh
|
|
2028
|
+
// stores (registration is server-side bookkeeping — no seq, no actions).
|
|
2029
|
+
if (this.opts.changesets) {
|
|
2030
|
+
sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(fs.sessionID) });
|
|
2031
|
+
chatStore.apply({ type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(fs.sessionID) });
|
|
2032
|
+
}
|
|
1541
2033
|
const rec: SessionRecord = {
|
|
1542
2034
|
sessionID: fs.sessionID,
|
|
1543
2035
|
channel,
|
|
@@ -1556,6 +2048,8 @@ export class Host {
|
|
|
1556
2048
|
permissionForTool: new Map(),
|
|
1557
2049
|
toolForPermission: new Map(),
|
|
1558
2050
|
lastInbox: null,
|
|
2051
|
+
changesets: new Map(),
|
|
2052
|
+
turnSnapshots: new Map(),
|
|
1559
2053
|
};
|
|
1560
2054
|
this.sessions.set(fs.sessionID, rec);
|
|
1561
2055
|
this.byChannel.set(channel, rec);
|
|
@@ -1571,6 +2065,14 @@ export class Host {
|
|
|
1571
2065
|
|
|
1572
2066
|
/** Drop a session record and announce the removal on the root channel. */
|
|
1573
2067
|
private removeRecord(rec: SessionRecord): void {
|
|
2068
|
+
// Phase 2: every live changeset URI is about to become un-subscribable —
|
|
2069
|
+
// dispatch `changeset/cleared` (protocol case 2) before the teardown so
|
|
2070
|
+
// subscribers release their references.
|
|
2071
|
+
for (const uri of rec.changesets.keys()) {
|
|
2072
|
+
this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
|
|
2073
|
+
}
|
|
2074
|
+
rec.changesets.clear();
|
|
2075
|
+
rec.turnSnapshots.clear();
|
|
1574
2076
|
this.sessions.delete(rec.sessionID);
|
|
1575
2077
|
this.byChannel.delete(rec.channel);
|
|
1576
2078
|
this.byChannel.delete(chatChannelURI(rec.sessionID));
|
|
@@ -1597,6 +2099,20 @@ export class Host {
|
|
|
1597
2099
|
private async snapshotFor(uri: string): Promise<Snapshot | null> {
|
|
1598
2100
|
const kind = channelKind(uri);
|
|
1599
2101
|
if (kind === "unknown") return null;
|
|
2102
|
+
if (kind === "changeset") {
|
|
2103
|
+
if (!this.opts.changesets) return null;
|
|
2104
|
+
const parsed = parseChangesetChannel(uri);
|
|
2105
|
+
if (parsed === null) return null;
|
|
2106
|
+
const rec = this.sessions.get(parsed.sessionID);
|
|
2107
|
+
if (rec === undefined) return null;
|
|
2108
|
+
const store = this.changesetStore(rec, uri);
|
|
2109
|
+
// First subscribe (or a failed computation) triggers the computation;
|
|
2110
|
+
// subsequent subscribes return the last completed state.
|
|
2111
|
+
if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
|
|
2112
|
+
await this.refreshChangeset(rec, uri);
|
|
2113
|
+
}
|
|
2114
|
+
return { resource: uri, state: store.state, fromSeq: this.seq.seq };
|
|
2115
|
+
}
|
|
1600
2116
|
if (kind !== "root") {
|
|
1601
2117
|
const rec = this.byChannel.get(uri);
|
|
1602
2118
|
if (rec === undefined) return null;
|
|
@@ -1655,6 +2171,13 @@ export class Host {
|
|
|
1655
2171
|
const kind = channelKind(draft.channel);
|
|
1656
2172
|
if (kind === "root") {
|
|
1657
2173
|
this.state.apply(draft.action as RootAction);
|
|
2174
|
+
} else if (kind === "changeset") {
|
|
2175
|
+
// Changeset stores live on the record (keyed by URI), resolved
|
|
2176
|
+
// through the parsed owner session.
|
|
2177
|
+
const parsed = parseChangesetChannel(draft.channel);
|
|
2178
|
+
const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
|
|
2179
|
+
const store = rec !== undefined ? rec.changesets.get(draft.channel) : undefined;
|
|
2180
|
+
if (store !== undefined) store.apply(draft.action as ChangesetAction);
|
|
1658
2181
|
} else {
|
|
1659
2182
|
// byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
|
|
1660
2183
|
// is not always the opencode session id (client-chosen suffixes).
|
|
@@ -1793,3 +2316,15 @@ function mapToolResultContent(content: readonly { type: string; text?: string }[
|
|
|
1793
2316
|
}
|
|
1794
2317
|
return out;
|
|
1795
2318
|
}
|
|
2319
|
+
|
|
2320
|
+
/**
|
|
2321
|
+
* True when `child` is `parent` itself or strictly inside it (both resolved
|
|
2322
|
+
* first, so relative segments and `..` cannot escape the comparison). Used
|
|
2323
|
+
* to confine turn-snapshot paths and `resourceRead`/`invokeChangesetOperation`
|
|
2324
|
+
* targets to the location directory.
|
|
2325
|
+
*/
|
|
2326
|
+
function isPathInside(child: string, parent: string): boolean {
|
|
2327
|
+
const a = resolvePath(child);
|
|
2328
|
+
const b = resolvePath(parent);
|
|
2329
|
+
return a === b || a.startsWith(b + "/");
|
|
2330
|
+
}
|