@myrialabs/clopen 0.4.40 → 0.4.41

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.
Files changed (95) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  15. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  16. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  17. package/backend/database/migrations/index.ts +21 -0
  18. package/backend/database/queries/file-share-queries.ts +163 -0
  19. package/backend/database/queries/index.ts +6 -4
  20. package/backend/database/queries/profile-queries.ts +5 -3
  21. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  22. package/backend/database/queries/push-subscription-queries.ts +99 -0
  23. package/backend/database/queries/skill-queries.ts +96 -18
  24. package/backend/engine/adapters/claude/stream.ts +2 -1
  25. package/backend/engine/adapters/cline/stream.ts +3 -3
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +3 -3
  28. package/backend/engine/adapters/cursor/stream.ts +25 -3
  29. package/backend/engine/adapters/opencode/stream.ts +4 -6
  30. package/backend/engine/adapters/pi/stream.ts +2 -2
  31. package/backend/engine/adapters/qwen/stream.ts +2 -2
  32. package/backend/engine/artifact-sync.ts +26 -20
  33. package/backend/engine/docs/artifacts.md +81 -22
  34. package/backend/engine/docs/quick-reference.md +2 -1
  35. package/backend/engine/resolve-model.test.ts +108 -0
  36. package/backend/engine/resolve-model.ts +53 -10
  37. package/backend/engine/structured-helpers.ts +22 -0
  38. package/backend/files/file-shares.ts +369 -0
  39. package/backend/files/path-browsing.ts +27 -21
  40. package/backend/http/files-shared.test.ts +505 -0
  41. package/backend/http/files-shared.ts +351 -0
  42. package/backend/http/push.ts +150 -0
  43. package/backend/index.ts +8 -0
  44. package/backend/instructions/index.ts +1 -1
  45. package/backend/instructions/sync.ts +30 -6
  46. package/backend/memory/compose.ts +2 -2
  47. package/backend/memory/consolidate.ts +2 -2
  48. package/backend/memory/extract/episodic.ts +2 -2
  49. package/backend/memory/judge.ts +2 -2
  50. package/backend/profiles/service.ts +7 -6
  51. package/backend/push/sender.ts +172 -0
  52. package/backend/push/tags.ts +25 -0
  53. package/backend/push/vapid-keys.ts +77 -0
  54. package/backend/push/webpush-crypto.test.ts +200 -0
  55. package/backend/push/webpush-crypto.ts +231 -0
  56. package/backend/skills/detect.ts +28 -0
  57. package/backend/skills/index.ts +22 -4
  58. package/backend/skills/invoke.test.ts +114 -0
  59. package/backend/skills/invoke.ts +222 -0
  60. package/backend/skills/service.ts +194 -44
  61. package/backend/skills/spec.ts +35 -0
  62. package/backend/skills/sync.ts +85 -55
  63. package/backend/subagents/detect.ts +2 -3
  64. package/backend/subagents/sync.ts +15 -8
  65. package/backend/work/pull-requests.ts +2 -2
  66. package/backend/ws/chat/stream.ts +100 -8
  67. package/backend/ws/files/index.ts +4 -0
  68. package/backend/ws/files/share.ts +95 -0
  69. package/backend/ws/git/branch-name.ts +2 -2
  70. package/backend/ws/git/commit-message.ts +2 -2
  71. package/backend/ws/index.ts +3 -4
  72. package/backend/ws/profiles/crud.ts +2 -3
  73. package/backend/ws/skills/catalog.ts +5 -1
  74. package/backend/ws/skills/crud.ts +128 -22
  75. package/backend/ws/skills/index.ts +4 -1
  76. package/backend/ws/user/crud.ts +12 -3
  77. package/dist/assets/{index-D4igjF6e.js → index-CeNKKSDR.js} +1 -1
  78. package/dist/assets/{index-DONNwiXm.js → index-DW89566K.js} +1 -1
  79. package/dist/assets/{main-BrfXH1bL.js → main-Cy5DXWPT.js} +592 -590
  80. package/dist/assets/main-DJKj_4By.css +1 -0
  81. package/dist/index.html +7 -2
  82. package/dist/sw.js +112 -0
  83. package/package.json +1 -1
  84. package/shared/constants/engine-tools.ts +31 -6
  85. package/shared/constants/notification-messages.ts +142 -0
  86. package/shared/types/unified/stream.ts +7 -0
  87. package/backend/commands/detect.ts +0 -25
  88. package/backend/commands/index.ts +0 -9
  89. package/backend/commands/service.ts +0 -178
  90. package/backend/commands/store.ts +0 -45
  91. package/backend/commands/sync.ts +0 -94
  92. package/backend/database/queries/command-queries.ts +0 -82
  93. package/backend/ws/commands/crud.ts +0 -157
  94. package/backend/ws/commands/index.ts +0 -8
  95. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Per-stream materialization of the artifact-framework features that sit
3
- * alongside Skills — Commands, Subagents, and (global) Instructions.
3
+ * alongside Skills — Subagents and (global) Instructions — plus the cleanup of
4
+ * artifacts earlier versions wrote for the now-merged Commands feature.
4
5
  *
5
6
  * Called at stream start by every engine adapter, right after `syncSkills`, so
6
- * the newly-added features share the exact same trigger point without each
7
- * adapter growing three separate calls.
7
+ * the features share the exact same trigger point without each adapter growing
8
+ * separate calls.
8
9
  *
9
10
  * GLOBAL scope only: writing project-scoped instructions into a repo's
10
11
  * `CLAUDE.md` / `AGENTS.md` touches the working tree, which the project's rules
@@ -12,40 +13,45 @@
12
13
  * Each underlying sync swallows its own errors, so this never throws.
13
14
  */
14
15
 
15
- import { syncCommands, buildCommandsPromptContext } from '$backend/commands';
16
16
  import { syncSubagents, buildSubagentsPromptContext } from '$backend/subagents';
17
- import { syncInstructions } from '$backend/instructions';
18
- import { buildSkillsPromptContext } from '$backend/skills';
19
- import type { ArtifactEngine } from '$backend/artifacts';
17
+ import { syncInstructions, buildInstructionsPromptContext } from '$backend/instructions';
18
+ import { buildSkillsPromptContext, stripLegacyCommandArtifacts } from '$backend/skills';
19
+ import { readsGlobalMemoryFile, type ArtifactEngine } from '$backend/artifacts';
20
20
 
21
21
  export async function syncEngineArtifacts(engine: ArtifactEngine, profileId?: number): Promise<void> {
22
- // Sequential, NOT Promise.all: on synthetic engines (Codex/OpenCode) all three
22
+ // Sequential, NOT Promise.all: on synthetic engines (Codex/OpenCode) these
23
23
  // write their own managed block into the SAME memory file (AGENTS.md). Running
24
24
  // them concurrently would race the read-modify-write and drop blocks. Each call
25
25
  // swallows its own errors, so a failure in one doesn't stop the others.
26
26
  //
27
- // `profileId` scopes Commands/Subagents to the active Profile's bundle (see
27
+ // `profileId` scopes Subagents to the active Profile's bundle (see
28
28
  // `backend/profiles`). Instructions are NOT profile-bundled — they always sync
29
29
  // their full global set.
30
- await syncCommands(engine, profileId);
30
+ await stripLegacyCommandArtifacts(engine);
31
31
  await syncSubagents(engine, profileId);
32
32
  await syncInstructions(engine);
33
33
  }
34
34
 
35
35
  /**
36
- * The combined, profile-scoped Skills + Commands + Subagents preamble that
37
- * prompt-scoped engines (OpenCode/Codex/Copilot) inject into each turn's prompt.
36
+ * The combined, profile-scoped artifact preamble that prompt-scoped engines
37
+ * inject into each turn's prompt.
38
38
  *
39
- * Their runtimes read these artifacts through a channel that is SHARED across
40
- * sessions and not reliably re-read per turn (a persistent server/client and/or
41
- * a global memory file), so the on-disk/global-file filter can't express a
42
- * per-session Profile. Injecting the scoped set into the prompt is the one
43
- * channel that is genuinely per-session. Returns '' when nothing applies.
39
+ * Their runtimes read artifacts through a channel that is SHARED across sessions
40
+ * and not reliably re-read per turn (a persistent server/client and/or a global
41
+ * memory file), so the on-disk/global-file filter can't express a per-session
42
+ * Profile. Injecting the scoped set into the prompt is the one channel that is
43
+ * genuinely per-session. Returns '' when nothing applies.
44
+ *
45
+ * `engine` decides whether Instructions ride along. Codex/Copilot/OpenCode read
46
+ * the memory file `syncInstructions` writes, so adding them here would say the
47
+ * same thing twice. Cline and Cursor read no such file — for them the prompt is
48
+ * the ONLY channel, and before this parameter existed their Instructions were
49
+ * written to a file nothing opened and silently never applied.
44
50
  */
45
- export function buildArtifactsPromptContext(profileId?: number): string {
51
+ export function buildArtifactsPromptContext(engine: ArtifactEngine, profileId?: number): string {
46
52
  return [
53
+ readsGlobalMemoryFile(engine) ? '' : buildInstructionsPromptContext(),
47
54
  buildSkillsPromptContext(profileId),
48
- buildCommandsPromptContext(profileId),
49
- buildSubagentsPromptContext(profileId)
55
+ buildSubagentsPromptContext(engine, profileId)
50
56
  ].filter(Boolean).join('\n\n');
51
57
  }
@@ -4,8 +4,8 @@
4
4
 
5
5
  The adapters stream chat; **artifacts** are the reusable "extensions" the user
6
6
  manages in **Settings → Artifacts & Access** that shape what each engine sees and
7
- may do during that stream — Skills, Commands, Subagents, Instructions,
8
- Permissions, Profiles, and Integrations (MCP).
7
+ may do during that stream — Skills, Subagents, Instructions, Permissions,
8
+ Profiles, and Integrations (MCP).
9
9
 
10
10
  They are a **separate subsystem** (`backend/artifacts/` + one module per feature)
11
11
  that meets the adapter layer at exactly one seam: `backend/engine/artifact-sync.ts`,
@@ -15,26 +15,28 @@ point** — the per-feature source of truth is the doc-comment atop each module
15
15
 
16
16
  ### 8.1 What lives under "Artifacts & Access"
17
17
 
18
- Seven menus, each a canonical source (DB metadata + on-disk store, or a repo
19
- file) that is **materialized** per engine. Coverage differs by engine because
20
- each exposes a different native surface.
18
+ Six menus, each a canonical source (DB metadata + on-disk store, or a repo file)
19
+ that is **materialized** per engine. Coverage differs by engine because each
20
+ exposes a different native surface.
21
21
 
22
22
  | Menu (UI) | Backend module | WS router | Materialized as |
23
23
  |------------------|-------------------------|----------------------------|-----------------|
24
24
  | Integrations | `backend/mcp/` + `backend/integrations/` | `backend/ws/mcp/` + `backend/ws/integrations/` | config object + `/mcp/ext/<slug>` bridge — **not** a file artifact (see §8.5) |
25
- | Skills | `backend/skills/` | `backend/ws/skills/` | `folder-md` in a native dir, or synthetic preamble |
26
- | Commands | `backend/commands/` | `backend/ws/commands/` | `single-md` in a native dir, or synthetic preamble |
27
- | Subagents | `backend/subagents/` | `backend/ws/subagents/` | `single-md` in a native dir, or synthetic preamble |
28
- | Instructions | `backend/instructions/` | `backend/ws/instructions/` | `preamble-region` inside the engine memory file |
25
+ | Skills | `backend/skills/` | `backend/ws/skills/` | `folder-md` in a native dir, or synthetic preamble; `/slash` skills are expanded by Clopen (§8.6) |
26
+ | Subagents | `backend/subagents/` | `backend/ws/subagents/` | `single-md` in a native dir, or synthetic preamble — only for engines that can delegate |
27
+ | Instructions | `backend/instructions/` | `backend/ws/instructions/` | `preamble-region` inside the engine memory file, or the prompt for engines that read no such file |
29
28
  | Permissions | `backend/permissions/` | `backend/ws/permissions/` | runtime hook (+ optional Claude `settings.json`) |
30
29
  | Profiles | `backend/profiles/` | `backend/ws/profiles/` | not materialized — a **bundle** that narrows the others |
31
30
 
32
31
  `ArtifactType` (`backend/artifacts/types.ts`) is
33
- `skill | command | subagent | instruction | mcp | permission`. Two deliberate
32
+ `skill | command | subagent | instruction | mcp | permission`. Three deliberate
34
33
  mismatches with the menu list:
35
34
 
36
35
  - **`mcp` is a reserved slot with no adapter** — MCP servers are config objects,
37
36
  not files, so they keep their own path (§8.5).
37
+ - **`command` is a legacy slot** — Commands merged into Skills (migration 079,
38
+ §8.6). Nothing is materialized for it any more; the type survives so
39
+ `stripLegacyCommandArtifacts` can clean out what older versions wrote.
38
40
  - **Profiles is not an artifact type** — it is a bundling/scoping concept layered
39
41
  on top of the others (§8.4).
40
42
 
@@ -48,9 +50,9 @@ resolves **where** an artifact is materialized and **in what shape**
48
50
  Two strategies recur, mirroring the two engine families:
49
51
 
50
52
  - **NATIVE** (Claude, Qwen, Copilot) — the engine reads a real artifact
51
- directory (Claude `<config>/{skills,commands,agents}`, OpenCode
52
- `<config>/opencode/{command,agent}`, Codex `$CODEX_HOME/prompts`). Clopen
53
- mirrors only the slugs it owns into that dir (`ownership: 'whole-file'`).
53
+ directory (Claude `<config>/{skills,agents}`, OpenCode
54
+ `<config>/opencode/agent`, Pi `<agentDir>/skills`). Clopen mirrors only the
55
+ slugs it owns into that dir (`ownership: 'whole-file'`).
54
56
  - **SYNTHETIC** (Codex, OpenCode) — no native concept for a type, so Clopen
55
57
  injects a marker-delimited block (`preamble-region`) into the engine's global
56
58
  memory file (`AGENTS.md`).
@@ -77,29 +79,35 @@ growing separate calls (see the file taxonomy in §2.6).
77
79
 
78
80
  | Export | Role |
79
81
  |--------|------|
80
- | `syncEngineArtifacts(engine, profileId?)` | Materializes Commands, Subagents, and Instructions for the engine. **Global scope only** — writing project-scoped instructions into a repo's `CLAUDE.md` / `AGENTS.md` touches the working tree, which must be an explicit user action, never silent at stream start. |
81
- | `buildArtifactsPromptContext(profileId?)` | Returns the combined, profile-scoped Skills + Commands + Subagents preamble that **prompt-scoped engines** (OpenCode / Codex / Copilot) inject into each turn's prompt. |
82
+ | `syncEngineArtifacts(engine, profileId?)` | Strips legacy Command artifacts, then materializes Subagents and Instructions for the engine. **Global scope only** — writing project-scoped instructions into a repo's `CLAUDE.md` / `AGENTS.md` touches the working tree, which must be an explicit user action, never silent at stream start. |
83
+ | `buildArtifactsPromptContext(engine, profileId?)` | Returns the combined, profile-scoped preamble that **prompt-scoped engines** (OpenCode / Codex / Copilot / Cline / Cursor) inject into each turn's prompt. |
82
84
 
83
- > **Sequential, not `Promise.all`.** On synthetic engines all three sync calls
84
- > write into the same `AGENTS.md`; running them concurrently would race the
85
+ > **Sequential, not `Promise.all`.** On synthetic engines these calls write into
86
+ > the same `AGENTS.md`; running them concurrently would race the
85
87
  > read-modify-write and drop blocks. Each call swallows its own errors, so one
86
88
  > failure never stops the others and the function never throws.
87
89
 
88
- `profileId` scopes Commands/Subagents to the active Profile's bundle (§8.4);
90
+ `profileId` scopes Skills/Subagents to the active Profile's bundle (§8.4);
89
91
  Instructions are never profile-bundled. Prompt-scoped engines need the preamble
90
92
  because they read artifacts through a channel shared across sessions and not
91
93
  reliably re-read per turn — the prompt is the one genuinely per-session channel.
92
94
 
95
+ `engine` decides whether **Instructions** ride along in that preamble.
96
+ `readsGlobalMemoryFile()` is false for Cline and Cursor: both are in-process SDKs
97
+ that build their own system prompt and resolve ambient rules from the workspace,
98
+ so an `AGENTS.md` written into their isolated config dir is a file nothing opens.
99
+ For them the prompt is the only channel — before this, Instructions silently
100
+ never applied there at all.
101
+
93
102
  ### 8.4 Per-artifact map
94
103
 
95
104
  | Artifact | Canonical source | Scope | Sync behaviour |
96
105
  |----------|------------------|-------|----------------|
97
- | **Skills** (`backend/skills/`) | DB metadata + on-disk store; marketplace-installable | global, project | mirrored folder (`folder-md`) on native engines, synthetic preamble otherwise. Keeps its own `syncSkills` call — the framework generalized this mechanic |
98
- | **Commands** (`backend/commands/`) | custom slash commands | global, project | one `.md` per command into the engine command dir, or synthetic preamble. Profile-bundled |
99
- | **Subagents** (`backend/subagents/`) | specialized delegated agents | global, project | one `.md` per subagent, or synthetic preamble. Profile-bundled |
106
+ | **Skills** (`backend/skills/`) | DB metadata + on-disk store; marketplace-installable | global, project | mirrored folder (`folder-md`) on native engines, synthetic preamble otherwise. Only `auto`-triggered skills are advertised; `slash` ones are expanded by Clopen (§8.6). Profile-bundled |
107
+ | **Subagents** (`backend/subagents/`) | specialized delegated agents | global, project | one `.md` per subagent, or synthetic preamble — and **nothing at all** for engines `canDelegateSubagents()` rejects (Codex, Copilot, Qwen), which have no surface to register one with. Profile-bundled |
100
108
  | **Instructions** (`backend/instructions/`) | a shared instruction block | global, project | marker region inside the engine memory file (`CLAUDE.md` / `QWEN.md` / `AGENTS.md`). Global set always synced in full; never profile-bundled |
101
109
  | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime check** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter runs at whichever surface fires for every tool call — for Claude a `PreToolUse` hook, since `bypassPermissions` auto-approves before `canUseTool` is consulted. The matrix only describes the optional on-disk file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`); its `deny` rules do bite even under `bypassPermissions`, an allowlist has no on-disk equivalent |
102
- | **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Commands-only profile never disables every Skill |
110
+ | **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Subagents-only profile never disables every Skill |
103
111
 
104
112
  ### 8.5 Integrations (MCP + connected accounts)
105
113
 
@@ -128,6 +136,57 @@ the remote HTTP bridge, per-engine config, and tool overrides — see
128
136
  [`backend/mcp/README.md`](../../mcp/README.md). The engine-side MCP reuse rules
129
137
  live in §10.12 (internal bridge) and §10.18 (external servers).
130
138
 
139
+ ### 8.6 Skills cover both triggers (the Commands merge)
140
+
141
+ Skills and Commands used to be two menus over one mechanic: the same
142
+ frontmatter + Markdown document, the same `materializeArtifacts` call, the same
143
+ profile bundling. They differed only in **who pulls the trigger**. Migration 079
144
+ folded them into one artifact with two independent switches:
145
+
146
+ | `triggers` | Invoked by | Delivery |
147
+ |------------|-----------|----------|
148
+ | `auto` | the model, from the skill's `description` | advertised in the skills preamble / native skills dir |
149
+ | `slash` | the user, by typing `/<slug>` | expanded by Clopen before the prompt reaches the engine |
150
+
151
+ A skill can carry both. Two frontmatter keys come with the merge:
152
+ `argument-hint` (shown in the chat "/" picker) and `uses` — a list of sibling
153
+ slugs force-loaded whenever the skill runs, which is how one invocation pulls in
154
+ several skills **deterministically** instead of hoping the model notices them.
155
+ The spec tells runtimes to ignore frontmatter keys they don't model, so a Clopen
156
+ skill is still a portable SKILL.md.
157
+
158
+ **Clopen is the invoker, not the engine.** `backend/skills/invoke.ts` resolves
159
+ `/<slug>`, substitutes `$ARGUMENTS` / `$1`…`$9`, prepends the `uses` load block
160
+ (absolute SKILL.md paths, so bundled `scripts/` and `references/` stay reachable),
161
+ and `backend/chat/stream-manager.ts` swaps the result into the ENGINE prompt
162
+ only — the saved user message keeps the `/slug` the user typed, exactly like the
163
+ handoff and memory blocks beside it.
164
+
165
+ This is the point of the merge. Only four of the eight engines have a native
166
+ command directory (Claude, Codex, OpenCode, Pi); the other four were handed a
167
+ list of command *names* with no bodies and no argument substitution, so `/review-pr
168
+ 123` produced an invented procedure. Expanding once, centrally, makes a slash
169
+ skill behave identically everywhere.
170
+
171
+ The old per-command **model override did not survive the merge**. A skill runs on
172
+ the session's model whichever trigger fires; pinning a model on the `slash` half
173
+ only would have made two halves of one artifact behave differently for a reason
174
+ no one could see in the UI.
175
+
176
+ Nothing is written to the native command directories any more.
177
+ `stripLegacyCommandArtifacts()` (called from `syncEngineArtifacts`) clears them
178
+ and any `CLOPEN:COMMANDS` block, so a renamed or deleted command stops being
179
+ offered by an engine's own picker.
180
+
181
+ **The migration copies, it does not move.** Each `{clopenDir}/commands/<slug>.md`
182
+ is read into `{clopenDir}/skills/<slug>/SKILL.md` and then left where it is, and
183
+ an existing SKILL.md is never overwritten with an empty body. A command document
184
+ is prose the user wrote and Clopen holds the only copy of; a migration that
185
+ deletes the source gets exactly one attempt, and against a database whose files
186
+ aren't beside it — restored from another machine, a data dir assembled by hand —
187
+ it would replace every prompt with nothing, irreversibly. A stale `commands/`
188
+ folder is the cheap half of that trade.
189
+
131
190
  ---
132
191
 
133
192
  See also: [`backend/artifacts/`](../../artifacts/) (matrix, generic sync/detect,
@@ -29,7 +29,8 @@
29
29
  | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
30
30
  | MCP servers exposed over HTTP (single source) | `backend/mcp/internal/remote-server.ts`, `backend/mcp/internal/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
31
31
  | Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
32
- | Per-stream artifact sync (Commands/Subagents/Instructions) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
32
+ | Per-stream artifact sync (Subagents/Instructions + legacy Command cleanup) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
33
+ | `/slash` skill expansion (all engines) | `backend/skills/invoke.ts::expandSlashInvocation`, applied in `backend/chat/stream-manager.ts` (see §8.6) |
33
34
  | Profile scoping (narrow active artifacts) | `backend/profiles/service.ts::resolveActiveProfileId` + `artifactFilter` (see §8.4) |
34
35
  | Permission enforcement (runtime check) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4); Claude wires it into a `PreToolUse` hook in `claude/stream.ts` |
35
36
  | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `resolveGenerationTarget` is the last place a misconfigured one-shot
3
+ * generation can be caught before it becomes an opaque adapter failure.
4
+ *
5
+ * Handed a blank or stale model id, engines don't refuse — they run with no
6
+ * model and return nothing, which surfaced as "OpenCode returned empty
7
+ * response". That sentence names the symptom and nothing else: not the cause,
8
+ * not the fix, and a different wording per engine for the same situation. These
9
+ * tests pin that each of those cases now throws *here*, naming the settings page
10
+ * that owns the choice.
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test';
14
+ import { registerModels } from '$shared/constants/engines';
15
+ import type { EngineModel, EngineType } from '$shared/types/unified';
16
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from './resolve-model';
17
+ import type { AIEngine } from './types';
18
+
19
+ /** The parts of an EngineModel this resolution actually reads. */
20
+ function model(engineType: EngineType, provider: string, id: string, accountId = 0): EngineModel {
21
+ return {
22
+ engine: {
23
+ type: engineType,
24
+ provider,
25
+ model: { id, name: id },
26
+ account: { id: accountId, name: 'test' }
27
+ }
28
+ } as EngineModel;
29
+ }
30
+
31
+ /** A stand-in engine whose catalog the test controls. */
32
+ function fakeEngine(engineType: EngineType, catalog: EngineModel[] | Error): AIEngine {
33
+ return {
34
+ name: engineType,
35
+ getAvailableModels: async () => {
36
+ if (catalog instanceof Error) throw catalog;
37
+ return catalog;
38
+ }
39
+ } as unknown as AIEngine;
40
+ }
41
+
42
+ describe('resolveGenerationTarget', () => {
43
+ test('resolves the provider and account from the catalog, ignoring a stale hint', async () => {
44
+ registerModels('opencode', [model('opencode', 'anthropic', 'claude-sonnet-5', 7)]);
45
+ const target = await resolveGenerationTarget(
46
+ fakeEngine('opencode', []),
47
+ 'claude-sonnet-5',
48
+ 'openai' // drifted: the catalog is the source of truth
49
+ );
50
+ expect(target).toEqual({ providerSlug: 'anthropic', modelId: 'claude-sonnet-5', accountId: 7 });
51
+ });
52
+
53
+ test('a blank model id is rejected, naming the settings page that owns it', async () => {
54
+ registerModels('opencode', []);
55
+ const promise = resolveGenerationTarget(
56
+ fakeEngine('opencode', [model('opencode', 'anthropic', 'claude-sonnet-5')]),
57
+ '',
58
+ 'anthropic',
59
+ GENERATION_SETTINGS.artifact
60
+ );
61
+ await expect(promise).rejects.toThrow(/No model is selected.*Settings → Models → Artifacts/);
62
+ });
63
+
64
+ test('whitespace is not a model id either', async () => {
65
+ registerModels('opencode', []);
66
+ await expect(
67
+ resolveGenerationTarget(fakeEngine('opencode', []), ' ', undefined, GENERATION_SETTINGS.commit)
68
+ ).rejects.toThrow(/Settings → Models → Commit message/);
69
+ });
70
+
71
+ test('an engine with no models at all says so, and points at Engines', async () => {
72
+ registerModels('opencode', []);
73
+ const promise = resolveGenerationTarget(
74
+ fakeEngine('opencode', []),
75
+ 'some-model',
76
+ undefined,
77
+ GENERATION_SETTINGS.artifact
78
+ );
79
+ // "Pick a model again" would be useless advice when there is nothing to pick.
80
+ await expect(promise).rejects.toThrow(/no models available.*Settings → Engines/s);
81
+ });
82
+
83
+ test('a model the catalog no longer offers is rejected, not passed through', async () => {
84
+ // This is the OpenCode case exactly: the catalog is fetched live, the saved
85
+ // id disappeared, and the provider hint still looks plausible. Trusting the
86
+ // hint here is what sent an unknown model id to the engine.
87
+ registerModels('opencode', []);
88
+ const promise = resolveGenerationTarget(
89
+ fakeEngine('opencode', [model('opencode', 'anthropic', 'claude-sonnet-5')]),
90
+ 'gone-model',
91
+ 'anthropic',
92
+ GENERATION_SETTINGS.artifact
93
+ );
94
+ await expect(promise).rejects.toThrow(/"gone-model" is no longer offered.*Settings → Models → Artifacts/);
95
+ });
96
+
97
+ test('an unreachable catalog falls back to the hint instead of blocking', async () => {
98
+ // Offline or a crashed engine process: we cannot verify, so we also cannot
99
+ // claim the model is wrong. Let the adapter try and report what it finds.
100
+ registerModels('opencode', []);
101
+ const target = await resolveGenerationTarget(
102
+ fakeEngine('opencode', new Error('server unreachable')),
103
+ 'claude-sonnet-5',
104
+ 'anthropic'
105
+ );
106
+ expect(target).toEqual({ providerSlug: 'anthropic', modelId: 'claude-sonnet-5' });
107
+ });
108
+ });
@@ -17,13 +17,25 @@
17
17
  * account a model belongs to, so resolve against it and treat the caller's
18
18
  * `providerSlug` as a hint. Keeping this in one place means a new engine is
19
19
  * covered without touching any call site.
20
+ *
21
+ * It is also the only place that can tell a MISCONFIGURED generation apart from
22
+ * a failed one. An engine handed a blank or stale model id doesn't refuse — it
23
+ * runs with no model and returns nothing, surfacing as "OpenCode returned empty
24
+ * response" (or the equivalent on any other engine), which tells the user
25
+ * neither what went wrong nor where to fix it. So the checks below fail loudly,
26
+ * before the engine is called, naming the settings page that owns the choice.
20
27
  */
21
28
 
22
- import { getModelsByEngine, registerModels } from '$shared/constants/engines';
29
+ import { getModelsByEngine, registerModels, ENGINES } from '$shared/constants/engines';
23
30
  import { debug } from '$shared/utils/logger';
24
31
  import type { EngineModel } from '$shared/types/unified';
25
32
  import type { AIEngine } from './types';
26
33
 
34
+ /** Human name for an engine, for error messages that point at Settings. */
35
+ function engineLabel(engineType: string): string {
36
+ return ENGINES.find(e => e.type === engineType)?.name ?? engineType;
37
+ }
38
+
27
39
  /** Engine-verified coordinates for a one-shot generation call. */
28
40
  export interface GenerationTarget {
29
41
  providerSlug: string;
@@ -32,22 +44,44 @@ export interface GenerationTarget {
32
44
  accountId?: number;
33
45
  }
34
46
 
47
+ /**
48
+ * Where the user picks the model for this generation, named in error messages so
49
+ * the fix is one click away instead of a guess.
50
+ */
51
+ export const GENERATION_SETTINGS = {
52
+ artifact: 'Settings → Models → Artifacts',
53
+ commit: 'Settings → Models → Commit message',
54
+ memory: 'Settings → Models → Memory',
55
+ assistant: 'Settings → Models'
56
+ } as const;
57
+
58
+ export type GenerationSettingsPath = (typeof GENERATION_SETTINGS)[keyof typeof GENERATION_SETTINGS];
59
+
35
60
  /**
36
61
  * Resolve `providerSlug` (and the owning account) for `modelId` from the
37
62
  * engine's catalog. `providerHint` is the caller-supplied slug — used only when
38
63
  * the catalog can't answer.
39
64
  *
40
- * Throws when the model belongs to no provider this engine offers, which is a
41
- * far more actionable error than the engine-specific failure it would become.
65
+ * Throws when the model is blank, when the engine offers no models at all, or
66
+ * when the catalog says the model doesn't exist. Each of those would otherwise
67
+ * become an opaque "returned empty response" deep inside an adapter.
42
68
  */
43
69
  export async function resolveGenerationTarget(
44
70
  engine: AIEngine,
45
71
  modelId: string,
46
- providerHint?: string
72
+ providerHint?: string,
73
+ settingsPath: string = GENERATION_SETTINGS.assistant
47
74
  ): Promise<GenerationTarget> {
48
75
  const engineType = engine.name;
76
+ const label = engineLabel(engineType);
49
77
  const byId = (models: EngineModel[]) => models.find(m => m.engine.model.id === modelId);
50
78
 
79
+ // No model at all. Engines that take `model` as optional silently fall back to
80
+ // a default that may not exist, so this can never be passed through.
81
+ if (!modelId.trim()) {
82
+ throw new Error(`No model is selected for ${label}. Choose one in ${settingsPath}.`);
83
+ }
84
+
51
85
  // The registry is filled by `models:list`; only pay for a catalog fetch when
52
86
  // this process hasn't seen the engine (or the model) yet.
53
87
  let catalog = getModelsByEngine(engineType);
@@ -76,12 +110,21 @@ export async function resolveGenerationTarget(
76
110
  };
77
111
  }
78
112
 
79
- // Unknown model: only trust the hint if this engine actually serves that
80
- // provider, otherwise it is drift and would fail deep inside the adapter.
81
- if (providerHint && catalog.some(m => m.engine.provider === providerHint)) {
82
- debug.warn('engine', `Model "${modelId}" missing from ${engineType} catalog; falling back to caller provider "${providerHint}"`);
83
- return { providerSlug: providerHint, modelId };
113
+ // The catalog came back empty: the engine isn't signed in, or has no provider
114
+ // configured. Saying "pick a model again" would be useless — there is nothing
115
+ // to pick until the engine itself is set up.
116
+ if (catalog.length === 0) {
117
+ throw new Error(
118
+ `${label} has no models available — it may not be signed in or configured. ` +
119
+ `Set it up in Settings → Engines → ${label}, then choose a model in ${settingsPath}.`
120
+ );
84
121
  }
85
122
 
86
- throw new Error(`Model "${modelId}" is not available for engine "${engineType}". Pick it again in Settings → Models.`);
123
+ // The catalog answered and this model isn't in it. Engines whose model list is
124
+ // fetched live (OpenCode, Cline, Pi, Cursor) can drop a model between the day
125
+ // it was saved and the day it is used, and passing the stale id through is
126
+ // exactly what produced an empty response with no explanation.
127
+ throw new Error(
128
+ `Model "${modelId}" is no longer offered by ${label}. Choose a model again in ${settingsPath}.`
129
+ );
87
130
  }
@@ -7,6 +7,28 @@
7
7
  * Claude and Codex doesn't need these helpers.
8
8
  */
9
9
 
10
+ /**
11
+ * The error every adapter raises when a one-shot generation comes back with
12
+ * nothing.
13
+ *
14
+ * Each engine used to phrase this itself — "OpenCode returned empty response",
15
+ * "Pi returned no structured output" — which named the symptom and nothing else.
16
+ * The user is left with a dead end: no cause, no fix, and a different sentence
17
+ * per engine for the same situation. An empty completion is almost always an
18
+ * unusable model (dropped from a live catalog, not enabled for the account) or a
19
+ * disconnected engine, so say that and name both places it is fixed.
20
+ *
21
+ * `detail` carries whatever the adapter actually observed (parts received, an
22
+ * SDK error string) — useful in a bug report, never the whole message.
23
+ */
24
+ export function emptyGenerationError(engineLabel: string, detail?: string): Error {
25
+ return new Error(
26
+ `${engineLabel} returned nothing for this request${detail ? ` (${detail})` : ''}. ` +
27
+ `The selected model may be unavailable for your account — pick another in Settings → Models, ` +
28
+ `and check ${engineLabel} is connected in Settings → Engines.`
29
+ );
30
+ }
31
+
10
32
  /** Wrap a user prompt with a JSON-only instruction and the target schema. */
11
33
  export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>): string {
12
34
  return `${prompt}