opencode-ahp 0.1.8 → 0.1.9

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.
@@ -46,9 +46,13 @@ export class HostChangesets extends HostBase {
46
46
  if (!isRecord(parsed)) return;
47
47
  const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
48
48
  if (typeof rawPath !== "string") return;
49
- const absPath = this.resolveSnapshotPath(rawPath);
49
+ // The owning record's directory scopes the clamp: a cross-location
50
+ // session's tool calls target its own working directory, not the
51
+ // location directory (legacy sessions resolve against the location).
52
+ const sessionDir = this.byOpencode.get(chat.sessionID)?.rec.directory;
53
+ const absPath = this.resolveSnapshotPath(rawPath, sessionDir);
50
54
  if (absPath === null) {
51
- this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
55
+ this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the session's working directory; not captured`);
52
56
  return;
53
57
  }
54
58
  let before: string | null;
@@ -67,9 +71,13 @@ export class HostChangesets extends HostBase {
67
71
  chat.turnSnapshots.set(turnId, turnFiles);
68
72
  }
69
73
 
70
- /** Resolve a tool-input path against the location directory (must stay inside it). */
71
- private resolveSnapshotPath(rawPath: string): string | null {
72
- const dir = this.opts.defaultDirectory;
74
+ /**
75
+ * Resolve a tool-input path against the session's working directory —
76
+ * its own directory, or the location directory for legacy sessions
77
+ * (`sessionDir` undefined) — and require it to stay inside it.
78
+ */
79
+ private resolveSnapshotPath(rawPath: string, sessionDir?: string): string | null {
80
+ const dir = sessionDir ?? this.opts.defaultDirectory;
73
81
  if (dir === undefined) return null;
74
82
  const absPath = resolvePath(dir, rawPath);
75
83
  return isPathInside(absPath, dir) ? absPath : null;
@@ -102,7 +110,9 @@ export class HostChangesets extends HostBase {
102
110
  reviewedById: this.reviewedById(store),
103
111
  });
104
112
  } else {
105
- const diffs = await this.opts.facade.vcsDiffWorking();
113
+ // Per-session diff: the session's own working directory
114
+ // (cross-location sessions), or the location directory (legacy).
115
+ const diffs = await this.opts.facade.vcsDiffWorking(rec.directory);
106
116
  files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
107
117
  }
108
118
  } catch (err) {
@@ -198,8 +208,10 @@ export class HostChangesets extends HostBase {
198
208
  this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
199
209
  return;
200
210
  }
201
- if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
202
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
211
+ // Per-session confinement: the path must live in the location
212
+ // directory or in one of the live sessions' own working directories.
213
+ if (this.containingSessionDir(absPath) === undefined) {
214
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside every session's working directory");
203
215
  return;
204
216
  }
205
217
  let content: string | null;
@@ -227,13 +239,14 @@ export class HostChangesets extends HostBase {
227
239
  return;
228
240
  }
229
241
  if (ref.kind === "head") {
230
- if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
231
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
242
+ const dir = this.containingSessionDir(ref.path);
243
+ if (dir === undefined) {
244
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside every session's working directory");
232
245
  return;
233
246
  }
234
247
  let content: string | null;
235
248
  try {
236
- content = await this.opts.facade.gitHeadFile(ref.path);
249
+ content = await this.opts.facade.gitHeadFile(ref.path, dir);
237
250
  } catch (err) {
238
251
  this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
239
252
  return;
@@ -323,8 +336,11 @@ export class HostChangesets extends HostBase {
323
336
  this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
324
337
  return;
325
338
  }
326
- if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
327
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
339
+ // Confine to the session's own working directory (legacy sessions:
340
+ // the location directory) — the changeset's files live there.
341
+ const sessionDir = rec.directory ?? this.opts.defaultDirectory;
342
+ if (sessionDir !== undefined && !isPathInside(absPath, sessionDir)) {
343
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the session's working directory");
328
344
  return;
329
345
  }
330
346
  this.publish({
@@ -337,7 +353,7 @@ export class HostChangesets extends HostBase {
337
353
  // (changesetStoreOf resolved it above).
338
354
  await this.restoreTurnFile(rec.chats.get(parsed.ownerUri)!, parsed.turnId, absPath);
339
355
  } else {
340
- await this.opts.facade.discardFile(absPath);
356
+ await this.opts.facade.discardFile(absPath, rec.directory);
341
357
  }
342
358
  } catch (err) {
343
359
  this.publish({
package/src/host-chats.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { HostClientTools } from "./host-client-tools.js";
6
6
  import { ActionType, Message } from "@microsoft/agent-host-protocol";
7
7
  import { agentIDFromUri, chatChangesetCatalog, chatSummaryOf, initialChatState } from "./bridge.js";
8
- import { channelKind, sessionIDOf } from "./channels.js";
8
+ import { channelKind, isSessionChannel, sessionIDOf } from "./channels.js";
9
9
  import { ERROR_INVALID_PARAMS } from "./handshake.js";
10
10
  import { isRecord } from "./options.js";
11
11
  import { createChatStateStore } from "./state.js";
@@ -109,8 +109,13 @@ export class HostChats extends HostClientTools {
109
109
  const params = isRecord(msg.params) ? msg.params : {};
110
110
  const channel = params["channel"];
111
111
  const chatURI = params["chat"];
112
- if (typeof channel !== "string" || channelKind(channel) !== "session") {
113
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-session:/… channel");
112
+ if (typeof channel !== "string" || !isSessionChannel(channel)) {
113
+ this.sendError(
114
+ socketId,
115
+ msg.id,
116
+ ERROR_INVALID_PARAMS,
117
+ "createChat requires a session channel (ahp-session:/… or <provider>:/…)",
118
+ );
114
119
  return;
115
120
  }
116
121
  const rec = this.byChannel.get(channel);
@@ -157,6 +162,10 @@ export class HostChats extends HostClientTools {
157
162
  created = await this.opts.facade.createSession({
158
163
  model,
159
164
  metadata: { [AHP_METADATA_KEY]: { chat: chatURI, owner: rec.sessionID } },
165
+ // A peer backend runs in the same location as its owner (a
166
+ // session with a working directory must not get its chats forked
167
+ // into the plugin's own location).
168
+ ...(rec.directory !== undefined ? { location: { directory: rec.directory } } : {}),
160
169
  });
161
170
  } catch (err) {
162
171
  this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the chat's backend session: ${errorMessage(err)}`);
@@ -84,6 +84,25 @@ export class HostClientTools extends HostTurns {
84
84
  return findProvider(rec.sessionStore.state.activeClients, toolName);
85
85
  }
86
86
 
87
+ /**
88
+ * The cross-session union of every live session's active-client
89
+ * tool names — the names the location-global opencode registry
90
+ * currently carries because of AHP clients (see
91
+ * {@link syncClientToolsToOpencode}). Used to keep those names out
92
+ * of a session's `serverTools` snapshot: a client tool already
93
+ * reaches the model through the client and must not echo back as a
94
+ * server tool.
95
+ */
96
+ protected clientToolNames(): ReadonlySet<string> {
97
+ const names = new Set<string>();
98
+ for (const rec of this.sessions.values()) {
99
+ for (const client of rec.sessionStore.state.activeClients) {
100
+ for (const tool of client.tools) names.add(tool.name);
101
+ }
102
+ }
103
+ return names;
104
+ }
105
+
87
106
  /**
88
107
  * Re-sync the location-global opencode tool registry with the
89
108
  * cross-session union of every live session's active-client tools
@@ -3,8 +3,8 @@
3
3
  */
4
4
 
5
5
  import { HostSessions } from "./host-sessions.js";
6
- import { ActionType, SessionInputRequestKind, SessionStatus, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
7
- import { FacadeDelivery } from "./bridge.js";
6
+ import { ActionType, SessionInputRequestKind, SessionStatus, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionCustomizationToggledAction, SessionMcpServerStartRequestedAction, SessionMcpServerStopRequestedAction, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
7
+ import { FacadeDelivery, MCP_CUSTOMIZATION_ID_PREFIX } from "./bridge.js";
8
8
  import { normalizeToolDefinitions } from "./client-tools.js";
9
9
  import { channelKind, parseChangesetChannel } from "./channels.js";
10
10
  import { isRecord } from "./options.js";
@@ -164,6 +164,11 @@ export class HostDispatch extends HostSessions {
164
164
  case ActionType.SessionIsArchivedChanged:
165
165
  this.echo(channel, stateAction, origin);
166
166
  return;
167
+ case ActionType.SessionCustomizationToggled:
168
+ case ActionType.SessionMcpServerStartRequested:
169
+ case ActionType.SessionMcpServerStopRequested:
170
+ await this.dispatchMcpControl(channel, stateAction, origin);
171
+ return;
167
172
  default:
168
173
  this.echo(channel, stateAction, origin, `unsupported action: ${String(stateAction.type)}`);
169
174
  }
@@ -187,6 +192,66 @@ export class HostDispatch extends HostSessions {
187
192
  return null;
188
193
  }
189
194
 
195
+ /**
196
+ * MCP-server toggle (design §7.5): the panel's enable toggle
197
+ * (`session/customizationToggled` on an `opencode:mcp/<name>` id) and
198
+ * the dedicated control actions (`session/mcpServerStartRequested` /
199
+ * `mcpServerStopRequested`) all map to the facade's `setMcpDisabled`
200
+ * — opencode's `disabled` config flag layered over the file config by
201
+ * the plugin's MCP transform, followed by the MCP re-reconcile the
202
+ * reload awaits. Once the status is settled, the accepted echo goes
203
+ * out and the per-location catalog is re-snapshotted and re-pushed to
204
+ * every live session, so each panel's entry converges on the new
205
+ * `state` (stopped / ready / …) and the `enablement` its toggle reads.
206
+ * Every other customization (agents, skills, directories) is a static
207
+ * file/config definition opencode cannot disable — rejected, so the
208
+ * write-ahead client rolls the toggle back.
209
+ */
210
+ private async dispatchMcpControl(
211
+ channel: string,
212
+ stateAction: StateAction,
213
+ origin: ActionOrigin | undefined,
214
+ ): Promise<void> {
215
+ const a = stateAction as
216
+ | SessionCustomizationToggledAction
217
+ | SessionMcpServerStartRequestedAction
218
+ | SessionMcpServerStopRequestedAction;
219
+ const id = typeof a.id === "string" ? a.id : undefined;
220
+ if (id === undefined || !id.startsWith(MCP_CUSTOMIZATION_ID_PREFIX)) {
221
+ this.echo(
222
+ channel,
223
+ stateAction,
224
+ origin,
225
+ a.type === ActionType.SessionCustomizationToggled
226
+ ? "cannot toggle: only MCP servers are togglable on this host — agents and skills are static file/config definitions"
227
+ : "cannot start or stop: only MCP servers accept start/stop on this host",
228
+ );
229
+ return;
230
+ }
231
+ const name = id.slice(MCP_CUSTOMIZATION_ID_PREFIX.length);
232
+ let disabled: boolean;
233
+ if (a.type === ActionType.SessionMcpServerStopRequested) {
234
+ disabled = true;
235
+ } else if (a.type === ActionType.SessionMcpServerStartRequested) {
236
+ disabled = false;
237
+ } else {
238
+ // `session/customizationToggled`: the effective decision is the
239
+ // most specific entry — the protocol allows treating
240
+ // `enablement[0].enabled ?? true` as the effective enabled value
241
+ // (absent or empty array = enabled).
242
+ const first = Array.isArray(a.enablement) ? a.enablement[0] : undefined;
243
+ disabled = !(first?.enabled ?? true);
244
+ }
245
+ try {
246
+ await this.opts.facade.setMcpDisabled(name, disabled);
247
+ } catch (err) {
248
+ this.echo(channel, stateAction, origin, `mcp toggle failed: ${errorMessage(err)}`);
249
+ return;
250
+ }
251
+ this.echo(channel, stateAction, origin);
252
+ await this.reannounceCatalogs();
253
+ }
254
+
190
255
  // `echo` (accepted echoes + write-ahead rejections) lives on HostBase
191
256
  // so the terminal section below this one can reuse it.
192
257
 
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Resources section (design §11): the filesystem `resource*` commands the
3
+ * VS Code folder picker drives — `resourceResolve` (the existence check),
4
+ * `resourceList` (navigating the server's filesystem), and `resourceMkdir`
5
+ * (creating a new project directory). These are token-authenticated and
6
+ * NOT location-confined: by default a client may name any path (matching
7
+ * the VS Code reference agent host, which exposes the whole host
8
+ * filesystem). The optional `allowedWorkingDirectories` option (design
9
+ * §3.3) scopes them to an allowlist of path prefixes.
10
+ */
11
+
12
+ import { HostChangesets } from "./host-changesets.js";
13
+ import { fileURLToPath } from "node:url";
14
+ import { directoryUri, fileUri, type FacadeResourceInfo } from "./bridge.js";
15
+ import { ERROR_INVALID_PARAMS } from "./handshake.js";
16
+ import { isRecord } from "./options.js";
17
+ import {
18
+ ERROR_ALREADY_EXISTS,
19
+ ERROR_INTERNAL,
20
+ ERROR_NOT_FOUND,
21
+ ERROR_PERMISSION_DENIED,
22
+ } from "./host-errors.js";
23
+ import { RpcMessage } from "./host-types.js";
24
+ import { errorMessage } from "./host-util.js";
25
+
26
+ export class HostResources extends HostChangesets {
27
+ /**
28
+ * `resourceResolve` (AHP root command): resolve one filesystem URI to
29
+ * its metadata (canonical URI, type, size, mtime/ctime, etag). The
30
+ * default `followSymlinks: true` follows symlinks and canonicalizes the
31
+ * path; `false` stats the path itself. Errors: -32008 (not found),
32
+ * -32009 (permission denied), -32602 (not a file URI), -32603 (other).
33
+ */
34
+ protected async handleResourceResolve(socketId: number, msg: RpcMessage): Promise<void> {
35
+ const params = isRecord(msg.params) ? msg.params : {};
36
+ const absPath = this.resourceUri(socketId, msg, params, "resourceResolve");
37
+ if (absPath === null) return;
38
+ if (!(await this.resourceAllowed(socketId, msg, absPath))) return;
39
+ // Absent / `true` follow symlinks (the default); only `false` stats
40
+ // the path itself (lstat semantics).
41
+ const followSymlinks = params["followSymlinks"] !== false;
42
+ let info: FacadeResourceInfo;
43
+ try {
44
+ info = await this.opts.facade.resolveResource(absPath, followSymlinks);
45
+ } catch (err) {
46
+ this.sendResourceError(socketId, msg.id, err);
47
+ return;
48
+ }
49
+ this.sendFrame(socketId, {
50
+ jsonrpc: "2.0",
51
+ id: msg.id ?? null,
52
+ result: {
53
+ uri: info.type === "directory" ? directoryUri(info.path) : fileUri(info.path),
54
+ type: info.type,
55
+ size: info.size,
56
+ mtime: new Date(info.mtime).toISOString(),
57
+ ctime: new Date(info.ctime).toISOString(),
58
+ // Weak etag of size + mtime (the spec's example shape); stable for
59
+ // a given file state, changes when the file changes.
60
+ etag: `W/"${info.size}-${info.mtime}"`,
61
+ },
62
+ });
63
+ }
64
+
65
+ /**
66
+ * `resourceList` (AHP root command): list one directory's immediate
67
+ * entries (name + file/directory kind) for remote folder pickers. The
68
+ * target MUST exist and be a directory — otherwise an error: -32008
69
+ * (missing), -32602 (not a directory), -32009 (inaccessible), -32603.
70
+ */
71
+ protected async handleResourceList(socketId: number, msg: RpcMessage): Promise<void> {
72
+ const params = isRecord(msg.params) ? msg.params : {};
73
+ const absPath = this.resourceUri(socketId, msg, params, "resourceList");
74
+ if (absPath === null) return;
75
+ if (!(await this.resourceAllowed(socketId, msg, absPath))) return;
76
+ let entries;
77
+ try {
78
+ entries = await this.opts.facade.listDirectory(absPath);
79
+ } catch (err) {
80
+ this.sendResourceError(socketId, msg.id, err);
81
+ return;
82
+ }
83
+ this.sendFrame(socketId, {
84
+ jsonrpc: "2.0",
85
+ id: msg.id ?? null,
86
+ result: {
87
+ entries: entries.map((e) => ({ name: e.name, type: e.type })),
88
+ },
89
+ });
90
+ }
91
+
92
+ /**
93
+ * `resourceMkdir` (AHP root command): create a directory with `mkdir -p`
94
+ * semantics (parents created as needed; an existing directory is a
95
+ * no-op success). Errors: -32009 (permission denied), -32010 (the path
96
+ * exists as a non-directory), -32602 (not a file URI), -32603 (other).
97
+ */
98
+ protected async handleResourceMkdir(socketId: number, msg: RpcMessage): Promise<void> {
99
+ const params = isRecord(msg.params) ? msg.params : {};
100
+ const absPath = this.resourceUri(socketId, msg, params, "resourceMkdir");
101
+ if (absPath === null) return;
102
+ if (!(await this.resourceAllowed(socketId, msg, absPath))) return;
103
+ try {
104
+ await this.opts.facade.mkdirResource(absPath);
105
+ } catch (err) {
106
+ this.sendResourceError(socketId, msg.id, err);
107
+ return;
108
+ }
109
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: {} });
110
+ }
111
+
112
+ /**
113
+ * The `uri` param of a `resource*` command as an absolute filesystem
114
+ * path. Sends the error and returns null when it is not a non-empty
115
+ * string or not a decodable `file://` URI. A directory URI may carry a
116
+ * trailing slash (RFC 8089) — it is dropped so the facade sees a plain
117
+ * absolute path (the resolve result re-adds it for directories).
118
+ */
119
+ private resourceUri(socketId: number, msg: RpcMessage, params: Record<string, unknown>, method: string): string | null {
120
+ const uri = params["uri"];
121
+ if (typeof uri !== "string" || uri.length === 0) {
122
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `${method} requires a uri`);
123
+ return null;
124
+ }
125
+ try {
126
+ const path = fileURLToPath(uri);
127
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
128
+ } catch {
129
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `${method} uri must be a file URI: ${uri}`);
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * The directory allowlist (the `allowedWorkingDirectories` option): the
136
+ * `resource*` commands are otherwise unconfined, so when the policy is
137
+ * restricted every `uri` must resolve under one of the prefixes (after
138
+ * symlink resolution). A denial is a flat -32009 — the message is
139
+ * deliberately identical for every denied path (no existence oracle);
140
+ * the full detail goes to the log.
141
+ */
142
+ private async resourceAllowed(socketId: number, msg: RpcMessage, absPath: string): Promise<boolean> {
143
+ const policy = this.opts.pathPolicy;
144
+ if (policy === undefined || (await policy.allows(absPath))) return true;
145
+ this.log(`resource command denied by the directory allowlist: ${absPath}`);
146
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is not permitted by host policy");
147
+ return false;
148
+ }
149
+
150
+ /**
151
+ * Map a Node `ErrnoException` from the resource facade to the AHP error
152
+ * codes: ENOENT → NotFound, EACCES/EPERM → PermissionDenied, ENOTDIR →
153
+ * InvalidParams ("not a directory"), EEXIST → AlreadyExists, other →
154
+ * Internal.
155
+ */
156
+ private sendResourceError(socketId: number, id: unknown, err: unknown): void {
157
+ const code = (err as NodeJS.ErrnoException | null)?.code;
158
+ switch (code) {
159
+ case "ENOENT":
160
+ this.sendError(socketId, id, ERROR_NOT_FOUND, errorMessage(err));
161
+ break;
162
+ case "EACCES":
163
+ case "EPERM":
164
+ this.sendError(socketId, id, ERROR_PERMISSION_DENIED, errorMessage(err));
165
+ break;
166
+ case "ENOTDIR":
167
+ this.sendError(socketId, id, ERROR_INVALID_PARAMS, `not a directory: ${errorMessage(err)}`);
168
+ break;
169
+ case "EEXIST":
170
+ this.sendError(socketId, id, ERROR_ALREADY_EXISTS, errorMessage(err));
171
+ break;
172
+ default:
173
+ this.sendError(socketId, id, ERROR_INTERNAL, errorMessage(err));
174
+ break;
175
+ }
176
+ }
177
+ }
package/src/host-rpc.ts CHANGED
@@ -180,6 +180,15 @@ export class HostRpc extends HostEvents {
180
180
  case "resourceRead":
181
181
  await this.handleResourceRead(socketId, msg);
182
182
  break;
183
+ case "resourceResolve":
184
+ await this.handleResourceResolve(socketId, msg);
185
+ break;
186
+ case "resourceList":
187
+ await this.handleResourceList(socketId, msg);
188
+ break;
189
+ case "resourceMkdir":
190
+ await this.handleResourceMkdir(socketId, msg);
191
+ break;
183
192
  case "invokeChangesetOperation":
184
193
  await this.handleInvokeChangesetOperation(socketId, msg);
185
194
  break;