opencode-copilot-delegate 0.11.0 → 0.12.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.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Wires graceful shutdown for the RPC server.
3
+ *
4
+ * This helper is intentionally NOT exported from `src/index.ts`. Any named
5
+ * export from the plugin entry is treated as a plugin factory by the OpenCode
6
+ * loader and called with `undefined` input, which crashes plugin loading. The
7
+ * same issue bit Systematic in v2.5.0 and v2.12.1. Moving helpers that are
8
+ * only needed internally into `src/lib/` keeps the plugin entry's public
9
+ * surface to `export default` only.
10
+ *
11
+ * Paired with `src/runtime/plugin-singleton.ts`: the singleton ensures the
12
+ * RPC server starts exactly once per process; this helper ensures it shuts
13
+ * down exactly once. Both constraints exist because the RPC server holds
14
+ * exclusive process resources (a bound TCP port and a PID file entry) —
15
+ * the same "exclusive resource" constraint that distinguishes this plugin
16
+ * from Systematic's stateless plugins and justifies retaining the singleton
17
+ * pattern after Systematic replaced it in PR #352
18
+ * (https://github.com/marcusrbrown/systematic/pull/352).
19
+ */
20
+ /**
21
+ * Wraps a `closeRpcServer` callback so it runs at most once, and registers
22
+ * `beforeExit` / `SIGTERM` handlers that trigger it automatically.
23
+ *
24
+ * Returns the idempotent `closeOnce` function so callers can also trigger
25
+ * shutdown imperatively (e.g. in tests via `__captureRpcCleanup`).
26
+ */
27
+ export declare function wireRpcServerCleanup(closeRpcServer: () => Promise<void>): () => Promise<void>;
@@ -0,0 +1,7 @@
1
+ export declare function normalizeContinuityError(stderr: string): string | null;
2
+ export declare function resolveConfigDir(explicit?: string): string;
3
+ export declare function isCopilotSessionUuid(value: string): boolean;
4
+ export type SessionLookupResult = boolean | {
5
+ error: string;
6
+ };
7
+ export declare function hasLocalCopilotSession(uuid: string, configDir: string): Promise<SessionLookupResult>;
@@ -0,0 +1,11 @@
1
+ type TargetId = {
2
+ type: 'uuid' | 'name';
3
+ value: string;
4
+ };
5
+ type ValidationError = {
6
+ error: string;
7
+ };
8
+ export declare function validateTargetId(value: string): TargetId | ValidationError;
9
+ export declare function validateAddDirs(values: string[], allowedRoots: string[]): string[] | ValidationError;
10
+ export declare function validateCwd(value: string, allowedRoots: string[]): string | ValidationError;
11
+ export {};
@@ -6,6 +6,7 @@
6
6
  * gracefully rather than erroring.
7
7
  */
8
8
  import type { ParsedEvent } from './jsonl-parser';
9
+ import type { TaskOrigin } from './task-registry';
9
10
  /** Status of a delegated Copilot task. */
10
11
  export type TaskStatus = 'running' | 'cancelling' | 'complete' | 'failed' | 'cancelled';
11
12
  /** Summary of a single tool call made during the Copilot session. */
@@ -33,6 +34,10 @@ export type EnvelopeInput = {
33
34
  modelName?: string;
34
35
  errorText?: string;
35
36
  timedOut?: boolean;
37
+ /** Source of the task — pass-through from `TaskState.origin`. */
38
+ origin?: TaskOrigin;
39
+ /** Upstream Copilot session UUID — pass-through from `TaskState`. */
40
+ copilotSessionId?: string;
36
41
  };
37
42
  /** The structured result envelope returned by `copilot_output`. */
38
43
  export type OutputEnvelope = {
@@ -48,6 +53,19 @@ export type OutputEnvelope = {
48
53
  error?: string;
49
54
  timed_out?: boolean;
50
55
  events_count: number;
56
+ /**
57
+ * Source of the task. Always populated; defaults to `'spawn'` for inputs
58
+ * that predate the discriminator (back-compat). Consumers branch on this
59
+ * to distinguish a fresh delegation from a resumed/connected session
60
+ * without re-reading the registry.
61
+ */
62
+ origin: TaskOrigin;
63
+ /**
64
+ * Upstream Copilot session UUID, when known. Captured from the JSONL
65
+ * `result` event during the task lifecycle. Omitted when the subprocess
66
+ * never emitted a `result` event (e.g., killed early or crashed).
67
+ */
68
+ copilot_session_id?: string;
51
69
  };
52
70
  /**
53
71
  * Build the structured output envelope from parsed events and task metadata.
@@ -10,6 +10,8 @@
10
10
  * the same counter value and both setting noReply: false.
11
11
  */
12
12
  import type { TaskStatus } from './envelope';
13
+ import type { SpawnCopilotResult } from './subprocess';
14
+ import type { TaskOrigin, TaskState } from './task-registry';
13
15
  /** Minimal client interface for notification injection. */
14
16
  export type NotifyClient = {
15
17
  session: {
@@ -55,6 +57,12 @@ export type NotifyTaskInfo = {
55
57
  modelName?: string;
56
58
  startedAt: number;
57
59
  exitCode?: number;
60
+ /**
61
+ * Source of the task. Optional for back-compat with callers that
62
+ * predate the discriminator (S2 Unit 1); existing call sites and
63
+ * tests omit it and the formatter falls back to the spawn variant.
64
+ */
65
+ origin?: TaskOrigin;
58
66
  };
59
67
  /** Increment the in-flight counter for a parent session. */
60
68
  export declare function incrementInFlight(parentSessionID: string): void;
@@ -69,3 +77,22 @@ export declare function notifySpawn(client: NotifyClient, taskId: string): Promi
69
77
  * Never throws — logs and swallows prompt/toast errors.
70
78
  */
71
79
  export declare function notifyCompletion(client: NotifyClient, task: NotifyTaskInfo): Promise<void>;
80
+ /**
81
+ * Attach the post-completion pipeline to a task and its underlying spawn
82
+ * result. Encapsulates the back-patch of late-arriving fields from
83
+ * `SpawnCopilotResult` to the registry `TaskState`, then dispatches the
84
+ * completion notification.
85
+ *
86
+ * The back-patch is load-bearing: `task` is created up-front from a
87
+ * snapshot of `spawnFields`, so post-spawn fields populated by the
88
+ * subprocess wrapper (status, finalMessage, copilotSessionId, etc) live
89
+ * on `spawnResult` until they are explicitly synced. Any field assigned
90
+ * after `createTask` returned needs to appear in the assign list —
91
+ * otherwise it is invisible to `copilot_output` even when present on
92
+ * `spawnResult`.
93
+ *
94
+ * Origin-aware notification text is delegated to `buildNotificationText`
95
+ * via `task.origin`, so this helper itself is origin-agnostic — the same
96
+ * pipeline drives spawn-, resume-, and (eventually) connect-origin tasks.
97
+ */
98
+ export declare function attachCompletionPipeline(task: TaskState, spawnResult: SpawnCopilotResult, client: NotifyClient): void;
@@ -44,6 +44,26 @@
44
44
  * restart. OpenCode currently surfaces a failed plugin factory as a
45
45
  * startup error rather than retrying within the process, so this matches
46
46
  * the upstream contract.
47
+ *
48
+ * **Why this plugin keeps the singleton pattern when Systematic dropped it.**
49
+ * Systematic's PR #352 (https://github.com/marcusrbrown/systematic/pull/352,
50
+ * shipped in v2.12.1/v2.12.2) replaced `plugInOnce` with per-load
51
+ * registration guarded by a marker flag. That change was correct for
52
+ * Systematic: its plugins are stateless and idempotent — they register
53
+ * tools and inject prompts, but they do not bind ports or write PID files.
54
+ * Running the same Systematic plugin factory twice in the same process is
55
+ * harmless because the second run produces the same registrations as the
56
+ * first.
57
+ *
58
+ * This plugin's init is not idempotent. `doInit` starts an RPC server that
59
+ * binds a TCP port and writes a PID file to a well-known path. A second
60
+ * `doInit` call in the same process would attempt to bind the same port
61
+ * (EADDRINUSE) and overwrite the PID file with a duplicate entry. The
62
+ * singleton pattern is the correct constraint here: exactly one server
63
+ * starts per process, and exactly one PID file entry is written. The
64
+ * paired `wireRpcServerCleanup` helper in `src/lib/rpc-cleanup.ts`
65
+ * enforces the matching invariant on shutdown — the server closes exactly
66
+ * once. Both guards exist because the resource is exclusive to the process.
47
67
  */
48
68
  export interface PlugInOnceOptions<T> {
49
69
  /** Heavy init work that should run at most once per process. */
@@ -7,11 +7,11 @@ export declare const TasksListResponseSchema: z.ZodObject<{
7
7
  tasks: z.ZodArray<z.ZodObject<{
8
8
  taskId: z.ZodString;
9
9
  status: z.ZodEnum<{
10
- running: "running";
10
+ cancelled: "cancelled";
11
11
  cancelling: "cancelling";
12
12
  complete: "complete";
13
13
  failed: "failed";
14
- cancelled: "cancelled";
14
+ running: "running";
15
15
  }>;
16
16
  agent: z.ZodString;
17
17
  model: z.ZodString;
@@ -19,6 +19,14 @@ export type SpawnCopilotResult = {
19
19
  stdoutLineBuffer: string;
20
20
  finalMessage?: string;
21
21
  errorText?: string;
22
+ /**
23
+ * Upstream Copilot session UUID captured from the terminal `result`
24
+ * JSONL event. Populated alongside `assignFinalMessage` in both the
25
+ * happy-path (`finalizeTask`) and cancelled-close branches; left
26
+ * undefined when no `result` event arrived (process killed early or
27
+ * crashed before emitting one).
28
+ */
29
+ copilotSessionId?: string;
22
30
  };
23
31
  export declare function spawnCopilot(args: string[], opts: SpawnCopilotOptions): SpawnCopilotResult;
24
32
  export {};
@@ -1,4 +1,14 @@
1
1
  import type { SpawnCopilotResult } from './subprocess';
2
+ /**
3
+ * Source of a TaskState.
4
+ *
5
+ * - `spawn` — fresh `copilot -p` subprocess started by `copilot_delegate`.
6
+ * - `resume` — `copilot --resume=<id>` continuation of a prior session.
7
+ * - `connect` — `copilot --connect=<id>` attach to a running session
8
+ * (deferred from the v0.x first slice; the type seam is in place for
9
+ * forward compatibility per the S2 plan amendment).
10
+ */
11
+ export type TaskOrigin = 'spawn' | 'resume' | 'connect';
2
12
  export type TaskState = SpawnCopilotResult & {
3
13
  parentSessionID: string;
4
14
  startedAt: number;
@@ -6,6 +16,14 @@ export type TaskState = SpawnCopilotResult & {
6
16
  cwd: string;
7
17
  agentName?: string;
8
18
  modelName?: string;
19
+ origin: TaskOrigin;
20
+ /** Workspace paths passed via `--add-dir` (captured for resume reuse). */
21
+ addDirs?: string[];
22
+ /** ps comm + lstart captured at spawn time for connect identity gating. */
23
+ psIdentity?: {
24
+ comm: string;
25
+ lstart: string;
26
+ };
9
27
  };
10
28
  export type CreateTaskInput = Omit<SpawnCopilotResult, 'taskId'> & {
11
29
  parentSessionID: string;
@@ -14,6 +32,16 @@ export type CreateTaskInput = Omit<SpawnCopilotResult, 'taskId'> & {
14
32
  cwd: string;
15
33
  agentName?: string;
16
34
  modelName?: string;
35
+ /**
36
+ * Source of the task. Optional on input — defaults to `'spawn'` so
37
+ * existing call sites that predate the discriminator keep working.
38
+ */
39
+ origin?: TaskOrigin;
40
+ addDirs?: string[];
41
+ psIdentity?: {
42
+ comm: string;
43
+ lstart: string;
44
+ };
17
45
  pidFilePath?: string;
18
46
  };
19
47
  export declare function createTask(input: CreateTaskInput, taskId?: string): TaskState;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * copilot_resume tool — resumes a prior Copilot session by ID, name, or prefix.
3
+ *
4
+ * Wraps `copilot --resume=<target_id>` with:
5
+ * - Concurrency cap: same 10-task limit as copilot_delegate
6
+ * - Input validation (validateTargetId, validateAddDirs, validateCwd)
7
+ * - UUID preflight: checks local session.db before spawning; fs errors → structured { error }
8
+ * - configDir propagation: resolved configDir is passed as COPILOT_CONFIG_DIR env to the
9
+ * spawned process so preflight and CLI use the same session store
10
+ * - Known-task add_dir reuse: if a prior task's copilotSessionId matches target_id,
11
+ * its captured addDirs are reused when the caller omits add_dir; inherited paths bypass
12
+ * explicit containment so multi-repo context from the prior task is preserved
13
+ * - Symlink containment: realpath-based canonicalization in validateAddDirs/validateCwd
14
+ * - CLI no-match stderr normalization to structured { error } response
15
+ * - origin: 'resume' on the created TaskState
16
+ * - Full completion pipeline (attachCompletionPipeline) identical to delegate
17
+ *
18
+ * Public tool args use snake_case (target_id, add_dir, config_dir) consistent with
19
+ * the rest of the plugin's public API surface.
20
+ *
21
+ * No `prompt` argument — resume + new prompt is a fork operation.
22
+ *
23
+ * Exports `launchResume` for RPC reuse.
24
+ */
25
+ import type { PluginInput } from '@opencode-ai/plugin';
26
+ export type LaunchResumeOptions = {
27
+ client: PluginInput['client'];
28
+ directory: string;
29
+ sessionID: string;
30
+ targetId: string;
31
+ cwd?: string;
32
+ addDirs?: string[];
33
+ configDir?: string;
34
+ pidFilePath?: string;
35
+ };
36
+ export type LaunchResumeResult = {
37
+ task_id: string;
38
+ } | {
39
+ error: string;
40
+ };
41
+ export declare function launchResume(opts: LaunchResumeOptions): Promise<LaunchResumeResult>;
42
+ type ResumeToolOptions = {
43
+ client: PluginInput['client'];
44
+ directory: string;
45
+ pidFilePath?: string;
46
+ };
47
+ export declare function createResumeTool(options: ResumeToolOptions): {
48
+ description: string;
49
+ args: {
50
+ target_id: import("zod").ZodString;
51
+ cwd: import("zod").ZodOptional<import("zod").ZodString>;
52
+ add_dir: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
53
+ config_dir: import("zod").ZodOptional<import("zod").ZodString>;
54
+ };
55
+ execute(args: {
56
+ target_id: string;
57
+ cwd?: string | undefined;
58
+ add_dir?: string[] | undefined;
59
+ config_dir?: string | undefined;
60
+ }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
61
+ };
62
+ export {};
package/dist/tui/index.js CHANGED
@@ -11186,7 +11186,7 @@ function finalize(ctx, schema) {
11186
11186
  result.$schema = "http://json-schema.org/draft-07/schema#";
11187
11187
  } else if (ctx.target === "draft-04") {
11188
11188
  result.$schema = "http://json-schema.org/draft-04/schema#";
11189
- } else if (ctx.target === "openapi-3.0") {} else {}
11189
+ } else if (ctx.target === "openapi-3.0") {}
11190
11190
  if (ctx.external?.uri) {
11191
11191
  const id = ctx.external.registry.get(schema)?.id;
11192
11192
  if (!id)
@@ -11434,7 +11434,7 @@ var literalProcessor = (schema, ctx, json, _params) => {
11434
11434
  if (val === undefined) {
11435
11435
  if (ctx.unrepresentable === "throw") {
11436
11436
  throw new Error("Literal `undefined` cannot be represented in JSON Schema");
11437
- } else {}
11437
+ }
11438
11438
  } else if (typeof val === "bigint") {
11439
11439
  if (ctx.unrepresentable === "throw") {
11440
11440
  throw new Error("BigInt literals cannot be represented in JSON Schema");
@@ -14054,6 +14054,40 @@ function errorMessage2(error48) {
14054
14054
  }
14055
14055
  return "Unknown RPC error.";
14056
14056
  }
14057
+ function hasKeymapRegisterLayer(api2) {
14058
+ const candidate = api2.keymap;
14059
+ return candidate != null && typeof candidate.registerLayer === "function";
14060
+ }
14061
+ function registerCopilotStatusCommand(api2, openList) {
14062
+ if (hasKeymapRegisterLayer(api2)) {
14063
+ return api2.keymap.registerLayer({
14064
+ commands: [{
14065
+ namespace: "palette",
14066
+ name: "copilot-status",
14067
+ title: "Copilot Status",
14068
+ category: "Copilot",
14069
+ run() {
14070
+ openList();
14071
+ }
14072
+ }],
14073
+ bindings: []
14074
+ });
14075
+ }
14076
+ if (typeof api2.command?.register === "function") {
14077
+ return api2.command.register(() => [{
14078
+ title: "Copilot Status",
14079
+ value: "/copilot-status",
14080
+ slash: {
14081
+ name: "copilot-status"
14082
+ },
14083
+ onSelect() {
14084
+ openList();
14085
+ }
14086
+ }]);
14087
+ }
14088
+ console.warn("[opencode-copilot-delegate] No supported TUI command-registration API found (neither api.keymap.registerLayer nor api.command.register). The /copilot-status slash command will not be available, but the plugin remains loaded.");
14089
+ return () => {};
14090
+ }
14057
14091
  var tui = async (api2) => {
14058
14092
  const rpc = createRpcClient();
14059
14093
  const closeDialog = () => {
@@ -14082,16 +14116,9 @@ var tui = async (api2) => {
14082
14116
  });
14083
14117
  });
14084
14118
  };
14085
- const unregister = api2.command.register(() => [{
14086
- title: "Copilot Status",
14087
- value: "/copilot-status",
14088
- slash: {
14089
- name: "copilot-status"
14090
- },
14091
- onSelect: () => {
14092
- openList();
14093
- }
14094
- }]);
14119
+ const unregister = registerCopilotStatusCommand(api2, () => {
14120
+ openList();
14121
+ });
14095
14122
  api2.lifecycle.onDispose(() => {
14096
14123
  rpc.dispose();
14097
14124
  unregister();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-copilot-delegate",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "OpenCode plugin that delegates tasks to GitHub Copilot CLI as background subprocesses",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -52,16 +52,17 @@
52
52
  "node": ">=24"
53
53
  },
54
54
  "peerDependencies": {
55
- "@opencode-ai/plugin": ">=1.14.0"
55
+ "@opencode-ai/plugin": ">=1.14.41"
56
56
  },
57
57
  "devDependencies": {
58
- "@biomejs/biome": "2.4.14",
58
+ "@biomejs/biome": "2.5.3",
59
59
  "@changesets/cli": "2.31.0",
60
- "@opencode-ai/plugin": "1.14.31",
61
- "@types/bun": "1.3.13",
62
- "@types/node": "24.12.2",
60
+ "@opencode-ai/plugin": "1.17.13",
61
+ "@types/babel__core": "7.20.5",
62
+ "@types/bun": "1.3.14",
63
+ "@types/node": "24.13.2",
63
64
  "rimraf": "6.1.3",
64
- "typescript": "6.0.3"
65
+ "typescript": "7.0.2"
65
66
  },
66
67
  "scripts": {
67
68
  "clean": "rimraf dist",
@@ -78,10 +79,10 @@
78
79
  "publish-changesets": "bun run build && changeset publish"
79
80
  },
80
81
  "dependencies": {
81
- "@opentui/core": "0.2.1",
82
- "@opentui/solid": "0.2.1",
82
+ "@opentui/core": "0.2.6",
83
+ "@opentui/solid": "0.2.6",
83
84
  "fkill": "10.0.3",
84
- "solid-js": "1.9.12",
85
+ "solid-js": "1.9.14",
85
86
  "zod": "^4.3.0"
86
87
  },
87
88
  "overrides": {
@@ -32,6 +32,11 @@ type ToastCall = {
32
32
  duration?: number
33
33
  }
34
34
 
35
+ type KeymapLayerCall = {
36
+ commands: ReadonlyArray<Record<string, unknown>>
37
+ bindings: ReadonlyArray<unknown>
38
+ }
39
+
35
40
  type TestApiControls = {
36
41
  api: TuiPluginApi
37
42
  commandFactories: Array<() => TuiCommand[]>
@@ -41,6 +46,21 @@ type TestApiControls = {
41
46
  disposeHandlers: Array<() => void | Promise<void>>
42
47
  toastCalls: ToastCall[]
43
48
  unregisterCalls: number
49
+ keymapLayerCalls: KeymapLayerCall[]
50
+ keymapUnregisterCalls: number
51
+ }
52
+
53
+ type CreateTestApiOptions = {
54
+ /**
55
+ * Which TUI registration surfaces the api stub exposes:
56
+ * - `'command'` (default): only `api.command.register` — OpenCode 1.14.41 baseline
57
+ * - `'keymap'`: only `api.keymap.registerLayer` — OpenCode 1.14.44+ canonical (and the 1.14.42–43 gap)
58
+ * - `'both'`: both surfaces — the 1.14.44+ shim era where `command.register` is restored as a deprecated shim
59
+ *
60
+ * Default `'command'` preserves the existing test suite's assertions about the
61
+ * legacy `command.register` registration path without modification.
62
+ */
63
+ surfaces?: 'command' | 'keymap' | 'both'
44
64
  }
45
65
 
46
66
  const originalFetch = globalThis.fetch
@@ -75,26 +95,54 @@ async function loadTuiPlugin(): Promise<TuiPlugin> {
75
95
  return plugin as TuiPlugin
76
96
  }
77
97
 
78
- function createTestApi(): TestApiControls {
98
+ function createTestApi(options: CreateTestApiOptions = {}): TestApiControls {
99
+ const surfaces = options.surfaces ?? 'command'
100
+ const exposeKeymap = surfaces === 'keymap' || surfaces === 'both'
101
+ const exposeCommand = surfaces === 'command' || surfaces === 'both'
102
+
79
103
  const commandFactories: Array<() => TuiCommand[]> = []
80
104
  const dialogReplacements: DialogReplacement[] = []
81
105
  const dialogSizes: Array<'medium' | 'large' | 'xlarge'> = []
82
106
  const disposeHandlers: Array<() => void | Promise<void>> = []
83
107
  const toastCalls: ToastCall[] = []
108
+ const keymapLayerCalls: KeymapLayerCall[] = []
84
109
  let clearCalls = 0
85
110
  let unregisterCalls = 0
111
+ let keymapUnregisterCalls = 0
112
+
113
+ const commandSurface = exposeCommand
114
+ ? {
115
+ register: (cb: () => TuiCommand[]) => {
116
+ commandFactories.push(cb)
117
+ return () => {
118
+ unregisterCalls += 1
119
+ }
120
+ },
121
+ trigger: () => {},
122
+ show: () => {},
123
+ }
124
+ : undefined
125
+
126
+ const keymapSurface = exposeKeymap
127
+ ? {
128
+ registerLayer: (layer: {
129
+ commands: ReadonlyArray<Record<string, unknown>>
130
+ bindings: ReadonlyArray<unknown>
131
+ }) => {
132
+ keymapLayerCalls.push({
133
+ commands: layer.commands,
134
+ bindings: layer.bindings,
135
+ })
136
+ return () => {
137
+ keymapUnregisterCalls += 1
138
+ }
139
+ },
140
+ }
141
+ : undefined
86
142
 
87
143
  const api = {
88
- command: {
89
- register: (cb: () => TuiCommand[]) => {
90
- commandFactories.push(cb)
91
- return () => {
92
- unregisterCalls += 1
93
- }
94
- },
95
- trigger: () => {},
96
- show: () => {},
97
- },
144
+ ...(commandSurface ? { command: commandSurface } : {}),
145
+ ...(keymapSurface ? { keymap: keymapSurface } : {}),
98
146
  ui: {
99
147
  Dialog: ((props: { children?: JSX.Element }) =>
100
148
  props.children ?? null) as TuiPluginApi['ui']['Dialog'],
@@ -148,6 +196,10 @@ function createTestApi(): TestApiControls {
148
196
  get unregisterCalls() {
149
197
  return unregisterCalls
150
198
  },
199
+ keymapLayerCalls,
200
+ get keymapUnregisterCalls() {
201
+ return keymapUnregisterCalls
202
+ },
151
203
  }
152
204
  }
153
205
 
@@ -353,6 +405,77 @@ describe('tui entrypoint', () => {
353
405
  expect(controls.toastCalls).toEqual([])
354
406
  })
355
407
 
408
+ it('prefers api.keymap.registerLayer when available (OpenCode 1.14.44+)', async () => {
409
+ const plugin = await loadTuiPlugin()
410
+ const controls = createTestApi({ surfaces: 'keymap' })
411
+
412
+ await plugin(controls.api, undefined, makePluginMeta())
413
+
414
+ expect(controls.keymapLayerCalls).toHaveLength(1)
415
+ expect(controls.commandFactories).toHaveLength(0)
416
+
417
+ const layer = controls.keymapLayerCalls[0]
418
+ expect(layer.bindings).toEqual([])
419
+ expect(layer.commands).toHaveLength(1)
420
+
421
+ const command = layer.commands[0]
422
+ expect(command).toMatchObject({
423
+ namespace: 'palette',
424
+ name: 'copilot-status',
425
+ title: 'Copilot Status',
426
+ category: 'Copilot',
427
+ })
428
+ expect(typeof command.run).toBe('function')
429
+
430
+ expect(controls.disposeHandlers).toHaveLength(1)
431
+ await controls.disposeHandlers[0]()
432
+ expect(controls.keymapUnregisterCalls).toBe(1)
433
+ expect(controls.unregisterCalls).toBe(0)
434
+ })
435
+
436
+ it('prefers api.keymap.registerLayer when both APIs exist (1.14.44+ shim era)', async () => {
437
+ const plugin = await loadTuiPlugin()
438
+ const controls = createTestApi({ surfaces: 'both' })
439
+
440
+ await plugin(controls.api, undefined, makePluginMeta())
441
+
442
+ expect(controls.keymapLayerCalls).toHaveLength(1)
443
+ expect(controls.commandFactories).toHaveLength(0)
444
+ })
445
+
446
+ it('falls back to api.command.register when keymap.registerLayer is absent (OpenCode 1.14.41)', async () => {
447
+ const plugin = await loadTuiPlugin()
448
+ const controls = createTestApi({ surfaces: 'command' })
449
+
450
+ await plugin(controls.api, undefined, makePluginMeta())
451
+
452
+ expect(controls.commandFactories).toHaveLength(1)
453
+ expect(controls.keymapLayerCalls).toHaveLength(0)
454
+ expect(controls.disposeHandlers).toHaveLength(1)
455
+
456
+ // Dispose unregisters via the command-register path, mirroring the
457
+ // keymap-path test's assertion that the correct teardown route runs.
458
+ await controls.disposeHandlers[0]()
459
+ expect(controls.unregisterCalls).toBe(1)
460
+ expect(controls.keymapUnregisterCalls).toBe(0)
461
+ })
462
+
463
+ it('opens the modal list when the keymap-path command is run', async () => {
464
+ const plugin = await loadTuiPlugin()
465
+ const controls = createTestApi({ surfaces: 'keymap' })
466
+
467
+ await plugin(controls.api, undefined, makePluginMeta())
468
+
469
+ const command = controls.keymapLayerCalls[0]?.commands[0] as
470
+ | (Record<string, unknown> & { run?: () => void })
471
+ | undefined
472
+ expect(command).toBeDefined()
473
+ command?.run?.()
474
+
475
+ expect(controls.dialogReplacements).toHaveLength(1)
476
+ expect(controls.dialogSizes).toEqual(['large'])
477
+ })
478
+
356
479
  it('keeps /copilot-status on a single read-only dialog replacement', async () => {
357
480
  const plugin = await loadTuiPlugin()
358
481
  const controls = createTestApi()