opencode-acp-provider 1.0.0 → 1.1.0

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.
@@ -0,0 +1,444 @@
1
+ import { mkdtempSync, rmSync, symlinkSync } from "node:fs"
2
+ import { createRequire } from "node:module"
3
+ import { tmpdir } from "node:os"
4
+ import { join } from "node:path"
5
+ import { AcpClient } from "./acp-client.ts"
6
+ import { errorMessage } from "./util.ts"
7
+
8
+ /**
9
+ * One ACP agent process per distinct launch, shared by every OpenCode location.
10
+ *
11
+ * OpenCode loads this plugin once per directory, and each copy used to spawn its
12
+ * own process per agent, paying memory and startup again for every directory.
13
+ * Claude, Codex and Antigravity accept sessions in many directories from one
14
+ * process because each `session/new` carries its own `cwd`, so those agents are
15
+ * shared: `acquire` keys a client by its launch and hands out leases to it.
16
+ *
17
+ * Command Code (`cmd acp`) instead binds a process to the directory of its first
18
+ * session and refuses the others. Such agents use `dedicated`, which keeps one
19
+ * pre-started spare per template. The expensive part (`initialize`, about three
20
+ * seconds for cmd) happens before that binding, and the skills directory passed
21
+ * at spawn is only read when a session starts, so the spare is adopted by
22
+ * symlinking the caller's skills directory into its temporary directory after
23
+ * `initialize`. The link is reported through the lease's `readRoots` so the
24
+ * caller knows it is available.
25
+ *
26
+ * The pool lives on `globalThis` because every location evaluates its own copy
27
+ * of this module; a module-level singleton would give each copy its own pool.
28
+ * The symbol is keyed by ABI and package version so copies from different
29
+ * plugin versions never share a pool whose `AcpClient` they cannot use.
30
+ */
31
+
32
+ export interface AgentLaunch {
33
+ command: string
34
+ args: string[]
35
+ cwd: string
36
+ env: Record<string, string>
37
+ /** Launches with different scopes never share a process. */
38
+ scope?: string
39
+ autoApprove?: boolean
40
+ requestTimeoutMs?: number
41
+ promptTimeoutMs?: number
42
+ allowPathsOutsideCwd?: boolean
43
+ maxFileBytes?: number
44
+ }
45
+
46
+ export interface AgentSubscriber {
47
+ onLog?: (level: "debug" | "warn" | "error", message: string) => void
48
+ onExit?: (error: Error) => void
49
+ }
50
+
51
+ export interface AgentLease {
52
+ readonly client: AcpClient
53
+ /** Extra directories this client's sessions must be allowed to read (an adopted spare's skill link). */
54
+ readonly readRoots: string[]
55
+ /** Give the client back. Idempotent. */
56
+ release(): void
57
+ }
58
+
59
+ export interface DedicatedTemplate {
60
+ /** Build the launch. `skillDir` is where the agent should read skills, or undefined when skills are off. */
61
+ launch: (skillDir: string | undefined) => AgentLaunch
62
+ /** The caller's own skills directory; undefined when skills are off. */
63
+ skillDir?: string
64
+ }
65
+
66
+ export interface AgentPoolOptions {
67
+ /** Keep a shared client running this long after its last lease is released. Default 0 (stop at once). */
68
+ lingerMs?: number
69
+ /** Keep one pre-started spare client per dedicated template. Default false. */
70
+ spares?: boolean
71
+ /** Parent directory for spare skill-link directories. Default os.tmpdir(). */
72
+ tmpDir?: string
73
+ }
74
+
75
+ /** Stands in for any skills directory when keying a template, so only skills-on vs skills-off differ. */
76
+ const SKILL_PLACEHOLDER = "\u0000skill-dir\u0000"
77
+ /** How long a stopped client stays reachable from the process exit hook. */
78
+ const RETIRED_TTL_MS = 5_000
79
+ const SPARE_PREFIX = "opencode-acp-provider-spare-"
80
+
81
+ type LogLevel = "debug" | "warn" | "error"
82
+
83
+ interface SharedEntry {
84
+ client: AcpClient
85
+ subscribers: Array<{ subscriber: AgentSubscriber }>
86
+ linger?: ReturnType<typeof setTimeout>
87
+ }
88
+
89
+ interface Spare {
90
+ client: AcpClient
91
+ dir: string
92
+ link: string
93
+ owner: { subscriber?: AgentSubscriber }
94
+ }
95
+
96
+ interface DedicatedState {
97
+ /** Live dedicated leases for this template. */
98
+ interest: number
99
+ spare?: Spare
100
+ spareStop?: ReturnType<typeof setTimeout>
101
+ }
102
+
103
+ interface Dispatch {
104
+ onLog?: (level: LogLevel, message: string) => void
105
+ onExit?: (error: Error) => void
106
+ }
107
+
108
+ /** Two launches share a client exactly when this key is equal. */
109
+ function launchKey(launch: AgentLaunch) {
110
+ const sortedEnv = Object.keys(launch.env)
111
+ .sort()
112
+ .map((name) => [name, launch.env[name]])
113
+ return JSON.stringify([
114
+ launch.scope ?? null,
115
+ launch.command,
116
+ launch.args,
117
+ launch.cwd,
118
+ sortedEnv,
119
+ launch.autoApprove ?? null,
120
+ launch.requestTimeoutMs ?? null,
121
+ launch.promptTimeoutMs ?? null,
122
+ launch.allowPathsOutsideCwd ?? null,
123
+ launch.maxFileBytes ?? null,
124
+ ])
125
+ }
126
+
127
+ export class AgentPool {
128
+ private readonly lingerMs: number
129
+ private readonly spares: boolean
130
+ private readonly tmpDir: string
131
+ private readonly shared = new Map<string, SharedEntry>()
132
+ private readonly dedicatedStates = new Map<string, DedicatedState>()
133
+ private readonly dedicatedClients = new Set<AcpClient>()
134
+ private readonly retired = new Set<AcpClient>()
135
+ private readonly retireTimers = new Set<ReturnType<typeof setTimeout>>()
136
+ private readonly dirs = new Set<string>()
137
+ private listening = false
138
+ private halted = false
139
+
140
+ constructor(options: AgentPoolOptions = {}) {
141
+ this.lingerMs = options.lingerMs ?? 0
142
+ this.spares = options.spares ?? false
143
+ this.tmpDir = options.tmpDir ?? tmpdir()
144
+ }
145
+
146
+ get stopped() {
147
+ return this.halted
148
+ }
149
+
150
+ /** Agents are spawned detached, so a lingering one must be killed by hand. */
151
+ private readonly onProcessExit = () => {
152
+ for (const client of this.knownClients()) client.killSync()
153
+ }
154
+
155
+ acquire(launch: AgentLaunch, subscriber: AgentSubscriber): AgentLease {
156
+ if (this.halted) throw new Error("ACP agent pool is stopped")
157
+ const key = launchKey(launch)
158
+ const shared = this.shared.get(key) ?? this.createSharedEntry(key, launch)
159
+ this.clearLinger(shared)
160
+
161
+ const registration = { subscriber }
162
+ shared.subscribers.push(registration)
163
+ let released = false
164
+ return {
165
+ client: shared.client,
166
+ readRoots: [],
167
+ release: () => {
168
+ if (released) return
169
+ released = true
170
+ const index = shared.subscribers.indexOf(registration)
171
+ if (index >= 0) shared.subscribers.splice(index, 1)
172
+ // stop() already retired this client and dropped the entry.
173
+ if (this.shared.get(key) !== shared || shared.subscribers.length) return
174
+ if (this.lingerMs > 0) {
175
+ // Stay in the map so a re-acquire before the timer reuses the client.
176
+ const timer = setTimeout(() => {
177
+ shared.linger = undefined
178
+ if (shared.subscribers.length || this.shared.get(key) !== shared) return
179
+ this.shared.delete(key)
180
+ this.retire(shared.client)
181
+ }, this.lingerMs)
182
+ timer.unref?.()
183
+ shared.linger = timer
184
+ } else {
185
+ this.shared.delete(key)
186
+ this.retire(shared.client)
187
+ }
188
+ },
189
+ }
190
+ }
191
+
192
+ private createSharedEntry(key: string, launch: AgentLaunch): SharedEntry {
193
+ let entry: SharedEntry
194
+ const client = this.createClient(launch, {
195
+ onLog: (level, message) => entry.subscribers[0]?.subscriber.onLog?.(level, message),
196
+ onExit: (error) => {
197
+ for (const registration of [...entry.subscribers]) registration.subscriber.onExit?.(error)
198
+ },
199
+ })
200
+ entry = { client, subscribers: [] }
201
+ this.shared.set(key, entry)
202
+ return entry
203
+ }
204
+
205
+ dedicated(template: DedicatedTemplate, subscriber: AgentSubscriber): AgentLease {
206
+ if (this.halted) throw new Error("ACP agent pool is stopped")
207
+ const key = this.templateKey(template)
208
+ let state = this.dedicatedStates.get(key)
209
+ if (!state) {
210
+ state = { interest: 0 }
211
+ this.dedicatedStates.set(key, state)
212
+ }
213
+ if (state.spareStop) {
214
+ clearTimeout(state.spareStop)
215
+ state.spareStop = undefined
216
+ }
217
+
218
+ let adopted: Spare | undefined
219
+ if (this.spares && state.spare) {
220
+ const spare = state.spare
221
+ state.spare = undefined
222
+ if (template.skillDir === undefined) {
223
+ adopted = spare
224
+ } else {
225
+ try {
226
+ symlinkSync(template.skillDir, spare.link, "dir")
227
+ adopted = spare
228
+ } catch (error) {
229
+ subscriber.onLog?.("warn", `could not adopt a warm agent: ${errorMessage(error)}`)
230
+ this.retire(spare.client)
231
+ this.removeDir(spare.dir)
232
+ }
233
+ }
234
+ if (adopted) adopted.owner.subscriber = subscriber
235
+ }
236
+
237
+ const client =
238
+ adopted?.client ??
239
+ this.createClient(template.launch(template.skillDir), {
240
+ onLog: (level, message) => subscriber.onLog?.(level, message),
241
+ onExit: (error) => subscriber.onExit?.(error),
242
+ })
243
+ this.dedicatedClients.add(client)
244
+ state.interest++
245
+ if (this.spares) {
246
+ void client
247
+ .start()
248
+ .catch(() => {})
249
+ .finally(() => this.ensureSpare(key, template))
250
+ }
251
+
252
+ const current = state
253
+ let released = false
254
+ return {
255
+ client,
256
+ readRoots: adopted ? [adopted.dir] : [],
257
+ release: () => {
258
+ if (released) return
259
+ released = true
260
+ this.dedicatedClients.delete(client)
261
+ this.retire(client)
262
+ if (adopted) this.removeDir(adopted.dir)
263
+ current.interest = Math.max(0, current.interest - 1)
264
+ if (current.interest === 0) this.stopSpareLater(current)
265
+ },
266
+ }
267
+ }
268
+
269
+ async stop(): Promise<void> {
270
+ if (this.halted) return
271
+ this.halted = true
272
+ for (const entry of this.shared.values()) this.clearLinger(entry)
273
+ for (const state of this.dedicatedStates.values()) {
274
+ if (state.spareStop) clearTimeout(state.spareStop)
275
+ state.spareStop = undefined
276
+ }
277
+ for (const timer of this.retireTimers) clearTimeout(timer)
278
+ this.retireTimers.clear()
279
+
280
+ const clients = [...this.knownClients()]
281
+ const dirs = [...this.dirs]
282
+ this.shared.clear()
283
+ for (const state of this.dedicatedStates.values()) {
284
+ state.spare = undefined
285
+ state.interest = 0
286
+ }
287
+ this.dedicatedStates.clear()
288
+ this.dedicatedClients.clear()
289
+ this.dirs.clear()
290
+
291
+ const stopping = clients.map((client) => this.retire(client))
292
+ await Promise.allSettled(stopping)
293
+
294
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
295
+ if (this.listening) {
296
+ process.off("exit", this.onProcessExit)
297
+ this.listening = false
298
+ }
299
+ }
300
+
301
+ private templateKey(template: DedicatedTemplate) {
302
+ return launchKey(template.launch(template.skillDir === undefined ? undefined : SKILL_PLACEHOLDER))
303
+ }
304
+
305
+ private clearLinger(entry: SharedEntry) {
306
+ if (!entry.linger) return
307
+ clearTimeout(entry.linger)
308
+ entry.linger = undefined
309
+ }
310
+
311
+ /** Stop the key's spare once nothing needs it, after the shared linger. */
312
+ private stopSpareLater(state: DedicatedState) {
313
+ if (!state.spare) return
314
+ const run = () => {
315
+ state.spareStop = undefined
316
+ if (state.interest !== 0) return
317
+ const spare = state.spare
318
+ if (!spare) return
319
+ state.spare = undefined
320
+ this.retire(spare.client)
321
+ this.removeDir(spare.dir)
322
+ }
323
+ if (this.lingerMs > 0) {
324
+ const timer = setTimeout(run, this.lingerMs)
325
+ timer.unref?.()
326
+ state.spareStop = timer
327
+ } else {
328
+ run()
329
+ }
330
+ }
331
+
332
+ private ensureSpare(key: string, template: DedicatedTemplate) {
333
+ if (!this.spares || this.halted) return
334
+ const state = this.dedicatedStates.get(key)
335
+ if (!state || state.interest === 0 || state.spare) return
336
+ let dir: string | undefined
337
+ try {
338
+ dir = mkdtempSync(join(this.tmpDir, SPARE_PREFIX))
339
+ const spareDir = dir
340
+ this.dirs.add(spareDir)
341
+ const link = join(spareDir, "skills")
342
+ const holder: { spare?: Spare } = {}
343
+ const client = this.createClient(
344
+ template.launch(template.skillDir === undefined ? undefined : link),
345
+ {
346
+ onLog: (level, message) => holder.spare?.owner.subscriber?.onLog?.(level, message),
347
+ onExit: (error) => {
348
+ const spare = holder.spare
349
+ if (!spare) return
350
+ const owner = spare.owner.subscriber
351
+ if (owner) {
352
+ owner.onExit?.(error)
353
+ return
354
+ }
355
+ if (state.spare !== spare) return
356
+ state.spare = undefined
357
+ this.retire(spare.client)
358
+ this.removeDir(spare.dir)
359
+ },
360
+ },
361
+ )
362
+ const spare: Spare = { client, dir: spareDir, link, owner: {} }
363
+ holder.spare = spare
364
+ state.spare = spare
365
+ void client.start().catch(() => {
366
+ if (state.spare !== spare) return
367
+ state.spare = undefined
368
+ this.retire(client)
369
+ this.removeDir(spare.dir)
370
+ })
371
+ } catch {
372
+ if (dir) this.removeDir(dir)
373
+ }
374
+ }
375
+
376
+ private knownClients() {
377
+ const clients = new Set<AcpClient>()
378
+ for (const entry of this.shared.values()) clients.add(entry.client)
379
+ for (const client of this.dedicatedClients) clients.add(client)
380
+ for (const state of this.dedicatedStates.values()) {
381
+ if (state.spare) clients.add(state.spare.client)
382
+ }
383
+ for (const client of this.retired) clients.add(client)
384
+ return clients
385
+ }
386
+
387
+ private createClient(launch: AgentLaunch, dispatch: Dispatch) {
388
+ if (!this.listening) {
389
+ process.on("exit", this.onProcessExit)
390
+ this.listening = true
391
+ }
392
+ return new AcpClient({
393
+ command: launch.command,
394
+ args: launch.args,
395
+ cwd: launch.cwd,
396
+ env: launch.env,
397
+ autoApprove: launch.autoApprove,
398
+ requestTimeoutMs: launch.requestTimeoutMs,
399
+ promptTimeoutMs: launch.promptTimeoutMs,
400
+ allowPathsOutsideCwd: launch.allowPathsOutsideCwd,
401
+ maxFileBytes: launch.maxFileBytes,
402
+ onLog: dispatch.onLog,
403
+ onExit: dispatch.onExit,
404
+ })
405
+ }
406
+
407
+ /** Stop a client and keep it killable from the exit hook for a while. */
408
+ private retire(client: AcpClient) {
409
+ const stopping = client.stop().catch(() => {})
410
+ this.retired.add(client)
411
+ const timer = setTimeout(() => {
412
+ this.retired.delete(client)
413
+ this.retireTimers.delete(timer)
414
+ }, RETIRED_TTL_MS)
415
+ timer.unref?.()
416
+ this.retireTimers.add(timer)
417
+ return stopping
418
+ }
419
+
420
+ private removeDir(dir: string) {
421
+ this.dirs.delete(dir)
422
+ rmSync(dir, { recursive: true, force: true })
423
+ }
424
+ }
425
+
426
+ const POOLS = Symbol.for("opencode-acp-provider.agent-pools")
427
+ /** Bump when AgentPool or AcpClient change incompatibly; copies only share a pool with the same ABI and version. */
428
+ const AGENT_POOL_ABI = 1
429
+
430
+ const { version } = createRequire(import.meta.url)("../package.json") as { version: string }
431
+
432
+ function pools() {
433
+ const scope = globalThis as unknown as Record<symbol, Map<string, AgentPool> | undefined>
434
+ return (scope[POOLS] ??= new Map())
435
+ }
436
+
437
+ export function sharedAgentPool(): AgentPool {
438
+ const key = `${AGENT_POOL_ABI}:${version}`
439
+ const existing = pools().get(key)
440
+ if (existing && !existing.stopped) return existing
441
+ const pool = new AgentPool({ lingerMs: 60_000, spares: true })
442
+ pools().set(key, pool)
443
+ return pool
444
+ }
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  type AcpServerState,
11
11
  type AcpSessionStore,
12
12
  } from "./server-manager.ts"
13
+ import { sharedAgentPool } from "./agent-pool.ts"
13
14
  import { createShim } from "./shim.ts"
14
15
  import { boundedMessages, historyLimits, recentConversation } from "./prompt.ts"
15
16
  import { createAcpLanguageModel } from "./language-model.ts"
@@ -207,6 +208,7 @@ export default Plugin.define({
207
208
  defaultCwd: ctx.location.directory,
208
209
  log,
209
210
  sessions: sessionStore,
211
+ agents: sharedAgentPool(),
210
212
  onCommands: (server) => void commandBridge?.sync(server),
211
213
  mcp:
212
214
  mcp || openCodeMcp
package/src/mcp-server.ts CHANGED
@@ -46,6 +46,8 @@ const TOOL_ORDER = [
46
46
  "session_prompt",
47
47
  "session_wait",
48
48
  "session_interrupt",
49
+ "worktree_create",
50
+ "worktree_remove",
49
51
  ]
50
52
 
51
53
  export interface McpServerOptions {
@@ -713,7 +715,7 @@ async function buildTools(
713
715
  cursor: stringSchema("Paging cursor."),
714
716
  }),
715
717
  call: async (args, signal) => {
716
- await assertSession(ctx, sessionKey, "*", "list", signal)
718
+ await assertPermission(ctx, sessionKey, "session", "*", "list", signal)
717
719
  return toMcpResult(await ctx.session.list(args ?? {}))
718
720
  },
719
721
  },
@@ -728,7 +730,7 @@ async function buildTools(
728
730
  directory: stringSchema("Defaults to your session's directory."),
729
731
  }),
730
732
  call: async (args, signal) => {
731
- await assertSession(ctx, sessionKey, "*", "create", signal)
733
+ await assertPermission(ctx, sessionKey, "session", "*", "create", signal)
732
734
  const input = args ?? {}
733
735
  const caller = await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)
734
736
  const directory = nonEmpty(input.directory) ?? (caller as any)?.location?.directory ?? ctx.location.directory
@@ -771,7 +773,7 @@ async function buildTools(
771
773
  ["sessionID", "text"],
772
774
  ),
773
775
  call: async (args, signal) => {
774
- await assertSession(ctx, sessionKey, args.sessionID, "prompt", signal)
776
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "prompt", signal)
775
777
  return toMcpResult(await ctx.session.prompt(args))
776
778
  },
777
779
  },
@@ -823,10 +825,52 @@ async function buildTools(
823
825
  inputSchema: objectSchema({ sessionID: stringSchema("Target session ID."), resume: { type: "boolean" } }, ["sessionID"]),
824
826
 
825
827
  call: async (args, signal) => {
826
- await assertSession(ctx, sessionKey, args.sessionID, "interrupt", signal)
828
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "interrupt", signal)
827
829
  return toMcpResult(await ctx.session.interrupt(args))
828
830
  },
829
831
  },
832
+ {
833
+ name: "worktree_create",
834
+ description: "Create a git worktree for the calling session's project and return its directory. Pass `from` to start it at a specific commit or ref. Mirrors worktree.create.",
835
+ inputSchema: objectSchema({
836
+ from: stringSchema("Commit, branch, or tag to start from. Defaults to the project's current HEAD."),
837
+ branch: stringSchema("Branch for the worktree."),
838
+ name: stringSchema("Name for the worktree; used to pick its directory."),
839
+ directory: stringSchema("Requested directory. The worktree strategy may choose another; use the returned directory."),
840
+ }),
841
+ call: async (args, signal) => {
842
+ await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
843
+ const input: Record<string, string> = { projectID: await callerProjectID(ctx, sessionKey) }
844
+ for (const field of ["from", "branch", "name", "directory"]) {
845
+ const value = nonEmpty(args?.[field])
846
+ if (value) input[field] = value
847
+ }
848
+ const created = await ctx.worktree.create(input as any)
849
+ return toMcpResult({ directory: created.directory })
850
+ },
851
+ },
852
+ {
853
+ name: "worktree_remove",
854
+ description: "Remove a worktree of the calling session's project by its directory. Mirrors worktree.remove.",
855
+ inputSchema: objectSchema(
856
+ {
857
+ directory: stringSchema("Worktree directory, as returned by worktree_create."),
858
+ force: { type: "boolean", description: "Remove even with uncommitted changes. Defaults to false." },
859
+ },
860
+ ["directory"],
861
+ ),
862
+ call: async (args, signal) => {
863
+ const directory = nonEmpty(args?.directory)
864
+ if (!directory) throw new Error("worktree remove requires a directory")
865
+ await assertPermission(ctx, sessionKey, "worktree", directory, "remove", signal)
866
+ await ctx.worktree.remove({
867
+ projectID: await callerProjectID(ctx, sessionKey),
868
+ directory,
869
+ force: args?.force === true,
870
+ } as any)
871
+ return toMcpResult({ directory, removed: true })
872
+ },
873
+ },
830
874
  )
831
875
 
832
876
  return tools
@@ -849,15 +893,23 @@ async function subagentDescription(ctx: Ctx) {
849
893
  }
850
894
 
851
895
  /**
852
- * Ask for the `session` permission on a target session. Listing spans sessions,
853
- * so it is asserted against `"*"` and needs an explicit permission of its own.
896
+ * Ask for a `session` or `worktree` permission on a target. Listing spans
897
+ * targets, so it is asserted against `"*"` and needs an explicit permission of
898
+ * its own.
854
899
  */
855
- async function assertSession(ctx: Ctx, caller: string, target: any, operation: string, signal: AbortSignal) {
856
- if (!target) throw new Error(`session ${operation} requires a sessionID`)
900
+ async function assertPermission(
901
+ ctx: Ctx,
902
+ caller: string,
903
+ action: "session" | "worktree",
904
+ target: any,
905
+ operation: string,
906
+ signal: AbortSignal,
907
+ ) {
908
+ if (!target) throw new Error(`${action} ${operation} requires a ${action === "session" ? "sessionID" : "target"}`)
857
909
  try {
858
910
  await ctx.permission.assert({
859
911
  sessionID: caller as any,
860
- action: "session",
912
+ action,
861
913
  resources: [String(target)],
862
914
  metadata: { operation },
863
915
  } as any)
@@ -865,7 +917,7 @@ async function assertSession(ctx: Ctx, caller: string, target: any, operation: s
865
917
  if (signal.aborted) throw error
866
918
  const message = error instanceof Error && error.message ? `: ${error.message}` : ""
867
919
  const scope = target === "*" ? "" : ` on ${target}`
868
- throw new Error(`Permission denied: session ${operation}${scope}${message}`)
920
+ throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
869
921
  }
870
922
  }
871
923
 
@@ -878,10 +930,16 @@ async function readTarget(
878
930
  signal: AbortSignal,
879
931
  ) {
880
932
  const target = typeof requested === "string" && requested ? requested : caller
881
- if (target !== caller) await assertSession(ctx, caller, target, operation, signal)
933
+ if (target !== caller) await assertPermission(ctx, caller, "session", target, operation, signal)
882
934
  return target
883
935
  }
884
936
 
937
+ /** The calling session's project, falling back to the plugin's own project. */
938
+ async function callerProjectID(ctx: Ctx, sessionKey: string) {
939
+ const caller = (await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)) as any
940
+ return caller?.projectID ?? ctx.location.project.id
941
+ }
942
+
885
943
  function nonEmpty(value: unknown): string | undefined {
886
944
  return typeof value === "string" && value.trim() ? value.trim() : undefined
887
945
  }