opencode-acp-provider 1.0.0 → 1.1.1

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/src/mcp-server.ts CHANGED
@@ -4,6 +4,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
4
4
  import { posix, win32 } from "node:path"
5
5
  import { fileURLToPath } from "node:url"
6
6
  import type { Plugin } from "@opencode/plugin"
7
+ import { Schema } from "effect"
7
8
  import packageJson from "../package.json" with { type: "json" }
8
9
  import type { AcpMcpServer } from "./acp-client.ts"
9
10
  import type { LogFn, McpLease } from "./server-manager.ts"
@@ -20,14 +21,6 @@ const MAX_CONTEXT_CHARS = 60_000
20
21
  /** Live tokens above this suggest leases are not being released. */
21
22
  const TOKEN_WARN_THRESHOLD = 256
22
23
 
23
- const SUBAGENT_DESCRIPTION = [
24
- "Spawns an agent in a child session to work on the specified task.",
25
- "Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `<subagent>` message each time the child goes idle, including after later work.",
26
- "Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll, or proactively check on the child's progress.",
27
- "New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
28
- "Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.",
29
- ].join("\n")
30
-
31
24
  /**
32
25
  * Order used by the initialize instructions. Clients that defer MCP tools (Codex
33
26
  * shows only the server's `instructions` until a namespace is loaded, and appends
@@ -37,6 +30,7 @@ const SUBAGENT_DESCRIPTION = [
37
30
  const TOOL_ORDER = [
38
31
  "question",
39
32
  "subagent",
33
+ "subagent_list",
40
34
  "models",
41
35
  "todowrite",
42
36
  "session_create",
@@ -46,6 +40,8 @@ const TOOL_ORDER = [
46
40
  "session_prompt",
47
41
  "session_wait",
48
42
  "session_interrupt",
43
+ "worktree_create",
44
+ "worktree_remove",
49
45
  ]
50
46
 
51
47
  export interface McpServerOptions {
@@ -71,6 +67,7 @@ interface McpTool {
71
67
  name: string
72
68
  description: string
73
69
  inputSchema: Record<string, unknown>
70
+ nativeInput?: unknown
74
71
  call: (args: any, signal: AbortSignal) => Promise<any>
75
72
  }
76
73
 
@@ -94,6 +91,47 @@ const objectSchema = (properties: Record<string, unknown>, required: string[] =
94
91
 
95
92
  const stringSchema = (description?: string) => ({ type: "string", ...(description ? { description } : {}) })
96
93
 
94
+ function schemaRecord(value: unknown): Record<string, unknown> | undefined {
95
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined
96
+ }
97
+
98
+ function nativeSchema(input: unknown) {
99
+ try {
100
+ if (Schema.isSchema(input)) {
101
+ return Schema.toJsonSchemaDocument(input, {
102
+ referencePolicy: () => undefined,
103
+ generateDescriptions: false,
104
+ }).schema
105
+ }
106
+ const schema = schemaRecord(input)
107
+ const jsonSchema = schemaRecord(schemaRecord(schema?.["~standard"])?.jsonSchema)
108
+ if (typeof jsonSchema?.input === "function") return jsonSchema.input({ target: "draft-2020-12" }) as unknown
109
+ return schema
110
+ } catch {
111
+ // Not every registry schema supports JSON Schema export.
112
+ return undefined
113
+ }
114
+ }
115
+
116
+ // Only copy annotations at existing field paths; the bridge owns the wire shape and constraints.
117
+ function withNativeDescriptions(input: Record<string, unknown>, source: unknown): Record<string, unknown> {
118
+ const native = schemaRecord(source)
119
+ if (!native) return input
120
+ const result = { ...input }
121
+ if (typeof native.description === "string") result.description = native.description
122
+ const properties = schemaRecord(input.properties)
123
+ const nativeProperties = schemaRecord(native.properties)
124
+ if (properties && nativeProperties) {
125
+ result.properties = Object.fromEntries(Object.entries(properties).map(([key, value]) => {
126
+ const field = schemaRecord(value)
127
+ return [key, field ? withNativeDescriptions(field, nativeProperties[key]) : value]
128
+ }))
129
+ }
130
+ const items = schemaRecord(input.items)
131
+ if (items) result.items = withNativeDescriptions(items, native.items)
132
+ return result
133
+ }
134
+
97
135
  /**
98
136
  * How to launch the stdio bridge. An absolute runtime runs directly; a bare
99
137
  * name (default `node`) is looked up on PATH, through `/usr/bin/env` on POSIX
@@ -326,16 +364,14 @@ export async function createMcpServer(options: McpServerOptions): Promise<McpSer
326
364
  tools: tools.map((tool) => ({
327
365
  name: tool.name,
328
366
  description: tool.description,
329
- inputSchema: tool.inputSchema,
367
+ inputSchema: withNativeDescriptions(tool.inputSchema, nativeSchema(tool.nativeInput)),
330
368
  })),
331
369
  })
332
370
  }
333
371
  case "tools/call": {
334
372
  const name = String(message.params?.name ?? "")
335
373
  const args = message.params?.arguments ?? {}
336
- // A call needs the handler, not the descriptions, so skip the agent
337
- // lookup that only feeds the subagent description.
338
- const tools = await buildTools(ctx, sessionKey, options.localService, log, { describe: false })
374
+ const tools = await buildTools(ctx, sessionKey, options.localService, log)
339
375
  const tool = tools.find((candidate) => candidate.name === name)
340
376
  if (!tool) return fail(-32602, `Unknown tool: ${name}`)
341
377
  const startedAt = Date.now()
@@ -486,7 +522,7 @@ async function buildInstructions(
486
522
  log?: LogFn,
487
523
  ) {
488
524
  // Only the names are used here.
489
- const tools = await buildTools(ctx, sessionKey, service, log, { describe: false })
525
+ const tools = await buildTools(ctx, sessionKey, service, log)
490
526
  if (!tools.length) return undefined
491
527
  const names = new Set(tools.map((tool) => tool.name))
492
528
  // Tools the model is most likely to need come first; some clients append this
@@ -509,7 +545,7 @@ async function buildInstructions(
509
545
  }
510
546
  if (names.has("subagent")) {
511
547
  lines.push(
512
- "Use `subagent` for delegation instead of a native subagent or task tool: call it with { agent, description, prompt }.",
548
+ "Use `subagent_list` to discover agent IDs and descriptions, then delegate with `subagent` ({ agent, description, prompt }).",
513
549
  "It returns at once and reports back with a <subagent> message when the child goes idle; do not poll it.",
514
550
  )
515
551
  }
@@ -524,7 +560,6 @@ async function buildTools(
524
560
  sessionKey: string,
525
561
  localService?: LocalServiceSource,
526
562
  log?: LogFn,
527
- { describe = true }: { describe?: boolean } = {},
528
563
  ): Promise<McpTool[]> {
529
564
  const tools: McpTool[] = []
530
565
  const available = await ctx.tool.list().catch(() => [])
@@ -561,7 +596,8 @@ async function buildTools(
561
596
  if (models) {
562
597
  tools.push({
563
598
  name: "models",
564
- description: "Search the models available to use. Use this to turn a model name the user mentions into an exact reference for a tool that takes a model. Check your own provider first.",
599
+ description: models.description,
600
+ nativeInput: models.input,
565
601
  inputSchema: objectSchema({
566
602
  query: stringSchema("Text to search for in model names and IDs."),
567
603
  provider: stringSchema("Provider ID or name to filter by. Try your own provider first."),
@@ -586,7 +622,8 @@ async function buildTools(
586
622
  if (subagent) {
587
623
  tools.push({
588
624
  name: "subagent",
589
- description: describe ? await subagentDescription(ctx) : SUBAGENT_DESCRIPTION,
625
+ description: subagent.description,
626
+ nativeInput: subagent.input,
590
627
  inputSchema: objectSchema(
591
628
  {
592
629
  agent: stringSchema(
@@ -608,28 +645,35 @@ async function buildTools(
608
645
  return toMcpResult(await invoke(subagent, input, signal))
609
646
  },
610
647
  })
648
+ tools.push({
649
+ name: "subagent_list",
650
+ description: "List available OpenCode subagents and their descriptions. Call before delegating with `subagent` to pick a valid `agent` ID.",
651
+ inputSchema: objectSchema({}),
652
+ call: async () => {
653
+ const { data } = await ctx.agent.list()
654
+ const agents = data
655
+ .filter((agent) => agent.mode !== "primary" && !agent.hidden)
656
+ .sort((left, right) => left.id.localeCompare(right.id))
657
+ .map(({ id, description }) => ({
658
+ id,
659
+ description,
660
+ }))
661
+ return toMcpResult({ agents })
662
+ },
663
+ })
611
664
  }
612
665
 
613
666
  const question = find("question")
614
667
  if (question) {
615
668
  tools.push({
616
669
  name: "question",
617
- description: [
618
- "Use this tool when you need to ask the user questions during execution. This allows you to:",
619
- "1. Gather user preferences or requirements",
620
- "2. Clarify ambiguous instructions",
621
- "3. Get decisions on implementation choices as you work",
622
- "4. Offer choices to the user about what direction to take.",
623
- "",
624
- "Usage notes:",
625
- "- A \"Type your own answer\" option is added automatically; don't include a separate option for free form answers",
626
- "- Set `multiple: true` to allow selecting more than one option",
627
- "- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label",
628
- ].join("\n"),
670
+ description: question.description,
671
+ nativeInput: question.input,
629
672
  inputSchema: objectSchema({
630
673
  questions: {
631
674
  type: "array",
632
675
  description: "Questions to ask",
676
+ minItems: 1,
633
677
  items: objectSchema(
634
678
  {
635
679
  header: stringSchema("Very short label (max 30 chars)"),
@@ -667,15 +711,8 @@ async function buildTools(
667
711
  if (todowrite) {
668
712
  tools.push({
669
713
  name: "todowrite",
670
- description: [
671
- "Create and update a todo list for the current session. The user sees it as your working plan.",
672
- "",
673
- "Use it proactively when a task has 3 or more distinct steps, or when the user gives several tasks or asks for a todo list. Skip it for a single simple task or a purely conversational request. When in doubt, use it.",
674
- "",
675
- "- Send the full list on every call; it replaces the previous one.",
676
- "- Mark items `in_progress` when you start them and `completed` as soon as they're actually done.",
677
- "- Only call it when the list changes.",
678
- ].join("\n"),
714
+ description: todowrite.description,
715
+ nativeInput: todowrite.input,
679
716
  inputSchema: objectSchema({
680
717
  todos: {
681
718
  type: "array",
@@ -713,7 +750,7 @@ async function buildTools(
713
750
  cursor: stringSchema("Paging cursor."),
714
751
  }),
715
752
  call: async (args, signal) => {
716
- await assertSession(ctx, sessionKey, "*", "list", signal)
753
+ await assertPermission(ctx, sessionKey, "session", "*", "list", signal)
717
754
  return toMcpResult(await ctx.session.list(args ?? {}))
718
755
  },
719
756
  },
@@ -728,7 +765,7 @@ async function buildTools(
728
765
  directory: stringSchema("Defaults to your session's directory."),
729
766
  }),
730
767
  call: async (args, signal) => {
731
- await assertSession(ctx, sessionKey, "*", "create", signal)
768
+ await assertPermission(ctx, sessionKey, "session", "*", "create", signal)
732
769
  const input = args ?? {}
733
770
  const caller = await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)
734
771
  const directory = nonEmpty(input.directory) ?? (caller as any)?.location?.directory ?? ctx.location.directory
@@ -771,7 +808,7 @@ async function buildTools(
771
808
  ["sessionID", "text"],
772
809
  ),
773
810
  call: async (args, signal) => {
774
- await assertSession(ctx, sessionKey, args.sessionID, "prompt", signal)
811
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "prompt", signal)
775
812
  return toMcpResult(await ctx.session.prompt(args))
776
813
  },
777
814
  },
@@ -823,41 +860,75 @@ async function buildTools(
823
860
  inputSchema: objectSchema({ sessionID: stringSchema("Target session ID."), resume: { type: "boolean" } }, ["sessionID"]),
824
861
 
825
862
  call: async (args, signal) => {
826
- await assertSession(ctx, sessionKey, args.sessionID, "interrupt", signal)
863
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "interrupt", signal)
827
864
  return toMcpResult(await ctx.session.interrupt(args))
828
865
  },
829
866
  },
867
+ {
868
+ name: "worktree_create",
869
+ 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.",
870
+ inputSchema: objectSchema({
871
+ from: stringSchema("Commit, branch, or tag to start from. Defaults to the project's current HEAD."),
872
+ branch: stringSchema("Branch for the worktree."),
873
+ name: stringSchema("Name for the worktree; used to pick its directory."),
874
+ directory: stringSchema("Requested directory. The worktree strategy may choose another; use the returned directory."),
875
+ }),
876
+ call: async (args, signal) => {
877
+ await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
878
+ const input: Record<string, string> = { projectID: await callerProjectID(ctx, sessionKey) }
879
+ for (const field of ["from", "branch", "name", "directory"]) {
880
+ const value = nonEmpty(args?.[field])
881
+ if (value) input[field] = value
882
+ }
883
+ const created = await ctx.worktree.create(input as any)
884
+ return toMcpResult({ directory: created.directory })
885
+ },
886
+ },
887
+ {
888
+ name: "worktree_remove",
889
+ description: "Remove a worktree of the calling session's project by its directory. Mirrors worktree.remove.",
890
+ inputSchema: objectSchema(
891
+ {
892
+ directory: stringSchema("Worktree directory, as returned by worktree_create."),
893
+ force: { type: "boolean", description: "Remove even with uncommitted changes. Defaults to false." },
894
+ },
895
+ ["directory"],
896
+ ),
897
+ call: async (args, signal) => {
898
+ const directory = nonEmpty(args?.directory)
899
+ if (!directory) throw new Error("worktree remove requires a directory")
900
+ await assertPermission(ctx, sessionKey, "worktree", directory, "remove", signal)
901
+ await ctx.worktree.remove({
902
+ projectID: await callerProjectID(ctx, sessionKey),
903
+ directory,
904
+ force: args?.force === true,
905
+ } as any)
906
+ return toMcpResult({ directory, removed: true })
907
+ },
908
+ },
830
909
  )
831
910
 
832
911
  return tools
833
912
  }
834
913
 
835
- async function subagentDescription(ctx: Ctx) {
836
- const parts = [SUBAGENT_DESCRIPTION]
837
- try {
838
- const agents = (await ctx.agent.list()).data
839
- const available = agents
840
- .filter((agent) => agent.mode !== "primary" && !agent.hidden)
841
- .sort((left, right) => left.id.localeCompare(right.id))
842
- if (available.length) {
843
- parts.push("", "Available subagents:", ...available.map((agent) => `- ${agent.id}: ${agent.description ?? "This subagent should only be called when explicitly requested."}`))
844
- }
845
- } catch {
846
- // agent discovery is best effort
847
- }
848
- return parts.join("\n")
849
- }
850
-
851
914
  /**
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.
915
+ * Ask for a `session` or `worktree` permission on a target. Listing spans
916
+ * targets, so it is asserted against `"*"` and needs an explicit permission of
917
+ * its own.
854
918
  */
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`)
919
+ async function assertPermission(
920
+ ctx: Ctx,
921
+ caller: string,
922
+ action: "session" | "worktree",
923
+ target: any,
924
+ operation: string,
925
+ signal: AbortSignal,
926
+ ) {
927
+ if (!target) throw new Error(`${action} ${operation} requires a ${action === "session" ? "sessionID" : "target"}`)
857
928
  try {
858
929
  await ctx.permission.assert({
859
930
  sessionID: caller as any,
860
- action: "session",
931
+ action,
861
932
  resources: [String(target)],
862
933
  metadata: { operation },
863
934
  } as any)
@@ -865,7 +936,7 @@ async function assertSession(ctx: Ctx, caller: string, target: any, operation: s
865
936
  if (signal.aborted) throw error
866
937
  const message = error instanceof Error && error.message ? `: ${error.message}` : ""
867
938
  const scope = target === "*" ? "" : ` on ${target}`
868
- throw new Error(`Permission denied: session ${operation}${scope}${message}`)
939
+ throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
869
940
  }
870
941
  }
871
942
 
@@ -878,10 +949,16 @@ async function readTarget(
878
949
  signal: AbortSignal,
879
950
  ) {
880
951
  const target = typeof requested === "string" && requested ? requested : caller
881
- if (target !== caller) await assertSession(ctx, caller, target, operation, signal)
952
+ if (target !== caller) await assertPermission(ctx, caller, "session", target, operation, signal)
882
953
  return target
883
954
  }
884
955
 
956
+ /** The calling session's project, falling back to the plugin's own project. */
957
+ async function callerProjectID(ctx: Ctx, sessionKey: string) {
958
+ const caller = (await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)) as any
959
+ return caller?.projectID ?? ctx.location.project.id
960
+ }
961
+
885
962
  function nonEmpty(value: unknown): string | undefined {
886
963
  return typeof value === "string" && value.trim() ? value.trim() : undefined
887
964
  }
@@ -940,4 +1017,3 @@ function boundContext(messages: any[]) {
940
1017
  }
941
1018
  return { messages: messages.slice(start), truncated: true, omittedMessages: start }
942
1019
  }
943
-
package/src/prompt.ts CHANGED
@@ -18,12 +18,29 @@ export function isAuxiliaryRequest(kind: unknown) {
18
18
  return kind === "title" || kind === "generate" || kind === "compaction"
19
19
  }
20
20
 
21
+ /**
22
+ * OpenCode injects harness blocks such as `<system-reminder>` (plan mode,
23
+ * opened-file notes) and `<system-update>` into user text. ACP agents run on
24
+ * their own instructions, so drop them. Only whole blocks that start and end
25
+ * on their own lines match, so a user mentioning a tag inline is untouched.
26
+ */
27
+ const SYSTEM_BLOCK = /(^|\n)[ \t]*<(system(?:[-_][a-z]+)*)(?:\s[^>]*)?>[\s\S]*?<\/\2>[ \t]*(?=\n|$)/gi
28
+
29
+ export function stripSystemBlocks(text: string): string {
30
+ if (!text.includes("<system")) return text
31
+ const stripped = text.replace(SYSTEM_BLOCK, "$1")
32
+ return stripped === text ? text : stripped.replace(/\n{3,}/g, "\n\n").trim()
33
+ }
34
+
21
35
  export function textOf(message: ChatMessage): string {
22
- if (typeof message.content === "string") return message.content
23
- if (!Array.isArray(message.content)) return ""
24
- return message.content
25
- .flatMap((part) => part?.type === "text" && typeof part.text === "string" && part.text ? [part.text] : [])
26
- .join("\n")
36
+ const text = typeof message.content === "string"
37
+ ? message.content
38
+ : Array.isArray(message.content)
39
+ ? message.content
40
+ .flatMap((part) => part?.type === "text" && typeof part.text === "string" && part.text ? [part.text] : [])
41
+ .join("\n")
42
+ : ""
43
+ return message.role === "user" ? stripSystemBlocks(text) : text
27
44
  }
28
45
 
29
46
  const conversational = (message: ChatMessage) => message.role === "user" || message.role === "assistant"