@myrialabs/clopen 0.3.11 → 0.3.13
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/backend/auth/session-invalidation.test.ts +116 -0
- package/backend/auth/session-invalidation.ts +78 -0
- package/backend/chat/stream-manager.ts +4 -0
- package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
- package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/audit-log-queries.test.ts +162 -0
- package/backend/database/queries/audit-log-queries.ts +98 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/engine/README.md +101 -29
- package/backend/engine/adapters/claude/message-converter.ts +1 -0
- package/backend/engine/adapters/codex/stream.ts +54 -1
- package/backend/engine/adapters/copilot/stream.ts +79 -19
- package/backend/engine/adapters/opencode/stream.ts +23 -23
- package/backend/engine/adapters/qwen/stream.ts +83 -1
- package/backend/engine/structured-helpers.ts +59 -0
- package/backend/files/file-archive.ts +191 -0
- package/backend/files/file-operations.ts +25 -61
- package/backend/files/file-size-limit.test.ts +85 -0
- package/backend/files/file-size-limit.ts +52 -0
- package/backend/git/git-service.ts +48 -4
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +14 -0
- package/backend/mcp/config.ts +4 -1
- package/backend/mcp/output-validator.test.ts +52 -0
- package/backend/mcp/output-validator.ts +103 -0
- package/backend/mcp/project-context.test.ts +22 -0
- package/backend/mcp/project-context.ts +35 -0
- package/backend/mcp/servers/helper.ts +11 -2
- package/backend/project/status-manager.test.ts +32 -0
- package/backend/project/status-manager.ts +7 -0
- package/backend/projects/project-cleanup-registry.test.ts +48 -0
- package/backend/projects/project-cleanup-registry.ts +44 -0
- package/backend/projects/project-cleanup.integration.test.ts +36 -0
- package/backend/projects/project-cleanup.ts +32 -0
- package/backend/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- package/backend/utils/ws.ts +46 -0
- package/backend/ws/auth/index.ts +4 -0
- package/backend/ws/auth/login.ts +31 -19
- package/backend/ws/auth/users.ts +21 -2
- package/backend/ws/chat/stream.ts +11 -0
- package/backend/ws/files/path-access.test.ts +166 -0
- package/backend/ws/files/path-access.ts +56 -22
- package/backend/ws/files/read.ts +5 -5
- package/backend/ws/files/search.ts +4 -0
- package/backend/ws/files/write.ts +47 -25
- package/backend/ws/git/commit-message.ts +12 -5
- package/backend/ws/git/remote.ts +6 -3
- package/backend/ws/message-rate-limiter.test.ts +79 -0
- package/backend/ws/message-rate-limiter.ts +134 -0
- package/backend/ws/projects/crud.ts +3 -0
- package/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/main-DOVudc3_.js +354 -0
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +4 -0
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +8 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +17 -6
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/index-DmghE6mf.js +0 -2
- package/dist/assets/main-DiDuzJJh.js +0 -318
- package/dist/assets/main-N1w7Llvp.css +0 -1
package/backend/engine/README.md
CHANGED
|
@@ -263,7 +263,7 @@ adapters/<name>/
|
|
|
263
263
|
├── server.ts? ← OPTIONAL subprocess + client lifecycle (opencode)
|
|
264
264
|
├── config.ts? ← OPTIONAL runtime config builder (opencode)
|
|
265
265
|
├── presets.ts? ← OPTIONAL multi-provider/region preset catalog (qwen, opencode)
|
|
266
|
-
└── session-fork.ts? ← OPTIONAL on-disk session fork workaround (codex,
|
|
266
|
+
└── session-fork.ts? ← OPTIONAL on-disk session fork workaround (codex, qwen)
|
|
267
267
|
```
|
|
268
268
|
|
|
269
269
|
Naming rules — strict, even when an SDK's local jargon differs:
|
|
@@ -1299,7 +1299,7 @@ resume.
|
|
|
1299
1299
|
|-----------|----------------------------------------------------------------------------------------------|
|
|
1300
1300
|
| Claude | Pass `forkSession: true` in the SDK options on every call — native. |
|
|
1301
1301
|
| OpenCode | Call `client.session.fork({ path: { id: resume } })` on every resume — native. |
|
|
1302
|
-
| Copilot |
|
|
1302
|
+
| Copilot | Call `client.rpc.sessions.fork({ sessionId: resume })` on every resume — native (`@experimental`, added in `@github/copilot-sdk` 1.0.0-beta.4). |
|
|
1303
1303
|
| Codex | **No native API yet** — fork by copying the rollout JSONL FILE on every resume. |
|
|
1304
1304
|
| Qwen Code | **No native API yet** — fork by copying the chat JSONL FILE on every resume. |
|
|
1305
1305
|
|
|
@@ -1310,29 +1310,13 @@ resume.
|
|
|
1310
1310
|
> the same session id is reused across every turn (visible in persisted
|
|
1311
1311
|
> assistant messages) and downstream branch logic breaks.
|
|
1312
1312
|
|
|
1313
|
-
The
|
|
1314
|
-
state, replace the source id with a fresh one, then
|
|
1315
|
-
fork — but the SDKs lay state out differently. Get
|
|
1316
|
-
`sessionStateExists()` silently returns false on
|
|
1317
|
-
block is skipped, and the engine resumes the
|
|
1318
|
-
the symptom multi-branch checkpoints
|
|
1319
|
-
|
|
1320
|
-
**Copilot — directory layout.** Tracking issues:
|
|
1321
|
-
github/copilot-cli#1313, #1697, #2058. State lives in a directory:
|
|
1322
|
-
|
|
1323
|
-
```
|
|
1324
|
-
~/.copilot/session-state/<sessionId>/
|
|
1325
|
-
├── workspace.yaml ← first line: `id: <sessionId>` ← rewrite
|
|
1326
|
-
├── events.jsonl ← first event session.start.data.sessionId ← rewrite
|
|
1327
|
-
├── checkpoints/
|
|
1328
|
-
├── files/
|
|
1329
|
-
└── research/
|
|
1330
|
-
```
|
|
1331
|
-
|
|
1332
|
-
Both `workspace.yaml#id` and the first `events.jsonl` line's
|
|
1333
|
-
`data.sessionId` must be replaced with the new fork id. After that,
|
|
1334
|
-
`client.resumeSession(forkId, ...)` picks the directory up as a fresh
|
|
1335
|
-
independent session.
|
|
1313
|
+
The two remaining on-disk workarounds (Codex and Qwen) follow the same
|
|
1314
|
+
shape — copy the state, replace the source id with a fresh one, then
|
|
1315
|
+
resume against the fork — but the SDKs lay state out differently. Get
|
|
1316
|
+
the layout wrong and `sessionStateExists()` silently returns false on
|
|
1317
|
+
every turn, the fork block is skipped, and the engine resumes the
|
|
1318
|
+
original session — exactly the symptom multi-branch checkpoints
|
|
1319
|
+
surface as.
|
|
1336
1320
|
|
|
1337
1321
|
**Codex — single rollout JSONL in a date-tree.** The thread id is in
|
|
1338
1322
|
the filename, not a directory name:
|
|
@@ -1394,8 +1378,8 @@ same id across turns is the symptom that forking is gated or skipped.
|
|
|
1394
1378
|
When an SDK eventually adds a native `forkSession` (or equivalent), the
|
|
1395
1379
|
migration is a one-liner: delete that adapter's `session-fork.ts`, drop
|
|
1396
1380
|
the fork block in `stream.ts`, and pass the SDK flag the same way
|
|
1397
|
-
Claude and
|
|
1398
|
-
each `session-fork.ts` pins the migration target.
|
|
1381
|
+
Claude, OpenCode, and Copilot already do. The `// TODO` comment at the
|
|
1382
|
+
top of each `session-fork.ts` pins the migration target.
|
|
1399
1383
|
|
|
1400
1384
|
### 9.11 Reset `currentAccountId` in `dispose()`
|
|
1401
1385
|
|
|
@@ -1664,6 +1648,94 @@ ships, sub-agent tool calls float to the top of the chat. If only step
|
|
|
1664
1648
|
missed (in an SDK that does double-emit), sub-agent text appears in
|
|
1665
1649
|
both places.
|
|
1666
1650
|
|
|
1651
|
+
### 9.16 `generateStructured` — schema strictness & part-extraction fallback
|
|
1652
|
+
|
|
1653
|
+
`generateStructured` powers the AI commit-message generator (and any
|
|
1654
|
+
future one-shot JSON callers). Each adapter satisfies the same
|
|
1655
|
+
`StructuredGenerationOptions → Promise<T>` contract, but the SDKs split
|
|
1656
|
+
sharply on whether they accept a schema natively:
|
|
1657
|
+
|
|
1658
|
+
| Engine | Strategy | Mechanism |
|
|
1659
|
+
|--------------|-----------------|--------------------------------------------------------------|
|
|
1660
|
+
| Claude | Native | `outputFormat: { type: 'json_schema', schema }` on `query()` |
|
|
1661
|
+
| Codex | Native (strict) | `Thread.run(prompt, { outputSchema })` → `Turn.finalResponse`|
|
|
1662
|
+
| OpenCode | Prompt | `client.session.prompt({ tools: {}, … })`, parse text/reasoning parts |
|
|
1663
|
+
| Copilot | Prompt | `createSession({ availableTools: [], streaming: false })` + `sendAndWait` |
|
|
1664
|
+
| Qwen | Prompt | `query({ coreTools: [], maxSessionTurns: 1 })`, read `SDKResultMessageSuccess.result` |
|
|
1665
|
+
|
|
1666
|
+
**Two cross-cutting gotchas you will hit.**
|
|
1667
|
+
|
|
1668
|
+
**1. OpenAI strict mode demands a fully-closed schema.** Codex (via the
|
|
1669
|
+
Responses API) rejects any object that omits `additionalProperties:
|
|
1670
|
+
false` (`invalid_request_error / invalid_json_schema`) and requires
|
|
1671
|
+
every property to appear in `required`. Optional fields must be
|
|
1672
|
+
expressed as nullable type unions, not absent from `required`:
|
|
1673
|
+
|
|
1674
|
+
```ts
|
|
1675
|
+
// backend/ws/git/commit-message.ts — shape that satisfies Codex.
|
|
1676
|
+
{
|
|
1677
|
+
type: 'object',
|
|
1678
|
+
additionalProperties: false,
|
|
1679
|
+
required: ['type', 'scope', 'subject', 'body'],
|
|
1680
|
+
properties: {
|
|
1681
|
+
type: { type: 'string', enum: [...] },
|
|
1682
|
+
scope: { type: ['string', 'null'] }, // was just 'string'
|
|
1683
|
+
subject: { type: 'string' },
|
|
1684
|
+
body: { type: ['string', 'null'] },
|
|
1685
|
+
},
|
|
1686
|
+
}
|
|
1687
|
+
```
|
|
1688
|
+
|
|
1689
|
+
This is the **lowest common denominator** — Claude, OpenCode, Copilot,
|
|
1690
|
+
and Qwen all accept the same shape, so authoring all
|
|
1691
|
+
`generateStructured` schemas to Codex's rules keeps the call site
|
|
1692
|
+
engine-agnostic. Don't lift constraints into the adapter; lift the
|
|
1693
|
+
schema in the caller.
|
|
1694
|
+
|
|
1695
|
+
The consumer of the parsed JSON must then handle `null` for any field
|
|
1696
|
+
that used to be "absent" — the existing falsy guards in
|
|
1697
|
+
`commit-message.ts` (`result.scope ? …`, `result.body ? …`) already do
|
|
1698
|
+
that. The corresponding TS type in `shared/types/git.ts` mirrors this
|
|
1699
|
+
(`scope: string | null`).
|
|
1700
|
+
|
|
1701
|
+
**2. Prompt-engineered engines can return empty `text` parts.** OpenCode
|
|
1702
|
+
in particular emits `reasoning` parts in addition to `text` parts, and
|
|
1703
|
+
on some thinking-heavy models the JSON answer lands in the reasoning
|
|
1704
|
+
stream while `text` is empty. The early implementation that filtered
|
|
1705
|
+
only `p.type === 'text'` raised "OpenCode returned no text content" in
|
|
1706
|
+
that case.
|
|
1707
|
+
|
|
1708
|
+
Two defences, both in `backend/engine/structured-helpers.ts` and the
|
|
1709
|
+
OpenCode adapter:
|
|
1710
|
+
|
|
1711
|
+
- **Fall back across part types.** `text` first, then `reasoning`.
|
|
1712
|
+
Filter out `ignored`/`synthetic` parts so the SDK's own scratch text
|
|
1713
|
+
doesn't leak into the JSON parser. Log the part-type breakdown in the
|
|
1714
|
+
error message so the next failure is diagnosable.
|
|
1715
|
+
- **Extract JSON tolerantly.** `extractJson()` tries, in order: a
|
|
1716
|
+
` ```json ` fenced block, the first balanced `{ … }`, then the raw
|
|
1717
|
+
trimmed text. Models routinely ignore the "no markdown fences"
|
|
1718
|
+
instruction; the parser should not.
|
|
1719
|
+
|
|
1720
|
+
The native engines (Claude, Codex) skip these — Claude exposes
|
|
1721
|
+
`structured_output` on the `result` message and Codex's
|
|
1722
|
+
`Turn.finalResponse` is already the JSON string. They only fall through
|
|
1723
|
+
to `extractJson` defensively against the (rare) `finalResponse` arriving
|
|
1724
|
+
fenced.
|
|
1725
|
+
|
|
1726
|
+
**Cancellation.** Every adapter accepts `options.abortController` and
|
|
1727
|
+
hands its `signal` to whatever the SDK exposes (Codex
|
|
1728
|
+
`TurnOptions.signal`, Claude `Options.abortController`, OpenCode `prompt
|
|
1729
|
+
{ signal }`, Copilot `session.abort()`, Qwen `QueryOptions.abortController`).
|
|
1730
|
+
The contract is the same as `streamQuery`: aborting cancels the in-flight
|
|
1731
|
+
request, not just the await.
|
|
1732
|
+
|
|
1733
|
+
**Engine-not-implemented errors.** `backend/ws/git/commit-message.ts`
|
|
1734
|
+
guards on `engine.generateStructured` — if you add an engine that can't
|
|
1735
|
+
implement structured output, leave the property `undefined` and the WS
|
|
1736
|
+
route will surface `Engine "<name>" does not support structured
|
|
1737
|
+
generation` cleanly.
|
|
1738
|
+
|
|
1667
1739
|
---
|
|
1668
1740
|
|
|
1669
1741
|
## 10. Quick reference table
|
|
@@ -1679,13 +1751,13 @@ both places.
|
|
|
1679
1751
|
| Buffer until usage event arrives | `copilot/message-converter.ts::flushPending` + `captureUsage` |
|
|
1680
1752
|
| Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
|
|
1681
1753
|
| Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
|
|
1682
|
-
| Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/session-fork.ts` (copy disk state) |
|
|
1754
|
+
| Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
|
|
1683
1755
|
| Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
|
|
1684
1756
|
| AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
|
|
1685
1757
|
| MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
|
|
1686
1758
|
| Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
|
|
1687
1759
|
| Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
|
|
1688
|
-
| `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured
|
|
1760
|
+
| `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
|
|
1689
1761
|
| Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
|
|
1690
1762
|
| DB provider/account access | `backend/database/queries/engine-queries.ts` |
|
|
1691
1763
|
| Per-platform install recipe | `backend/engine/install-recipes.ts` |
|
|
@@ -414,6 +414,7 @@ export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null
|
|
|
414
414
|
status: info.status === 'rejected' ? 'rejected' : 'allowed_warning',
|
|
415
415
|
utilization: info.utilization || 0,
|
|
416
416
|
resetsAt: info.resetsAt || null,
|
|
417
|
+
rateLimitType: info.rateLimitType || null,
|
|
417
418
|
};
|
|
418
419
|
}
|
|
419
420
|
|
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
|
|
22
22
|
import { Codex, type Thread, type ThreadOptions, type Input as CodexInput } from '@openai/codex-sdk';
|
|
23
23
|
import type { EngineOutput, EngineModel } from '$shared/types/unified';
|
|
24
|
-
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
24
|
+
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
25
|
+
import { extractJson } from '../../structured-helpers';
|
|
25
26
|
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
26
27
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
27
28
|
import { resolveBinary } from '$backend/utils/cli';
|
|
@@ -266,6 +267,58 @@ export class CodexEngine implements AIEngine {
|
|
|
266
267
|
async interrupt(): Promise<void> {
|
|
267
268
|
await this.cancel();
|
|
268
269
|
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* One-shot structured JSON generation via the SDK's native `outputSchema`.
|
|
273
|
+
* The CLI returns the JSON-serialised object as `Turn.finalResponse` (and
|
|
274
|
+
* as the text of the trailing `agent_message` item) — see codex-sdk
|
|
275
|
+
* `TurnOptions.outputSchema` in `dist/index.d.ts`.
|
|
276
|
+
*/
|
|
277
|
+
async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
|
|
278
|
+
const {
|
|
279
|
+
prompt,
|
|
280
|
+
modelId,
|
|
281
|
+
schema,
|
|
282
|
+
projectPath,
|
|
283
|
+
abortController,
|
|
284
|
+
accountId,
|
|
285
|
+
} = options;
|
|
286
|
+
|
|
287
|
+
if (!this._isInitialized || !this.codex || (accountId != null && accountId !== this.currentAccountId)) {
|
|
288
|
+
if (this._isInitialized) {
|
|
289
|
+
await this.dispose();
|
|
290
|
+
}
|
|
291
|
+
await this.initialize(accountId);
|
|
292
|
+
}
|
|
293
|
+
if (!this.codex) {
|
|
294
|
+
throw new Error('Codex client unavailable.');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const controller = abortController || new AbortController();
|
|
298
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
299
|
+
|
|
300
|
+
const thread = this.codex.startThread({
|
|
301
|
+
model: modelId,
|
|
302
|
+
workingDirectory: resolvedProjectPath,
|
|
303
|
+
skipGitRepoCheck: true,
|
|
304
|
+
sandboxMode: 'read-only',
|
|
305
|
+
approvalPolicy: 'never',
|
|
306
|
+
modelReasoningEffort: 'low',
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
debug.log('engine', `[codex structured] running with model=${modelId}`);
|
|
310
|
+
|
|
311
|
+
const turn = await thread.run(prompt, {
|
|
312
|
+
outputSchema: schema,
|
|
313
|
+
signal: controller.signal,
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
if (!turn.finalResponse) {
|
|
317
|
+
throw new Error('Codex returned empty response');
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return extractJson<T>(turn.finalResponse);
|
|
321
|
+
}
|
|
269
322
|
}
|
|
270
323
|
|
|
271
324
|
// ============================================================================
|
|
@@ -15,7 +15,8 @@ import type {
|
|
|
15
15
|
ModelInfo,
|
|
16
16
|
} from '@github/copilot-sdk';
|
|
17
17
|
import type { EngineOutput, EngineModel } from '$shared/types/unified';
|
|
18
|
-
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
18
|
+
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
19
|
+
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
19
20
|
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
20
21
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
21
22
|
import { debug } from '$shared/utils/logger';
|
|
@@ -46,7 +47,6 @@ import {
|
|
|
46
47
|
convertSubagentStarted,
|
|
47
48
|
convertSubagentEnded,
|
|
48
49
|
} from './message-converter';
|
|
49
|
-
import { forkCopilotSessionState, sessionStateExists } from './session-fork';
|
|
50
50
|
|
|
51
51
|
const ABORT_TIMEOUT_MS = 5000;
|
|
52
52
|
|
|
@@ -304,28 +304,23 @@ export class CopilotEngine implements AIEngine {
|
|
|
304
304
|
|
|
305
305
|
let session: CopilotSession;
|
|
306
306
|
if (resume) {
|
|
307
|
-
// Fork
|
|
307
|
+
// Fork on EVERY resume — same semantics as Claude
|
|
308
308
|
// (`forkSession: true`) and OpenCode (`client.session.fork()`):
|
|
309
309
|
// each turn must produce a brand-new session id so the original
|
|
310
310
|
// branch's history is never mutated and the multi-branch
|
|
311
|
-
// checkpoint tree stays consistent.
|
|
312
|
-
// reuses the same Copilot session id and downstream
|
|
313
|
-
// checkpoint/branch logic loses the ability to replay an
|
|
314
|
-
// earlier point as an independent sibling.
|
|
311
|
+
// checkpoint tree stays consistent.
|
|
315
312
|
//
|
|
316
|
-
//
|
|
317
|
-
//
|
|
318
|
-
//
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
// github/copilot-cli#1313, #1697, #2058). The migration is the
|
|
322
|
-
// same one-liner Claude and OpenCode already use.
|
|
313
|
+
// Uses `client.rpc.sessions.fork` (added in @github/copilot-sdk
|
|
314
|
+
// 1.0.0-beta.4, marked @experimental — see node_modules/
|
|
315
|
+
// @github/copilot-sdk/dist/generated/rpc.d.ts::SessionsForkRequest).
|
|
316
|
+
// Falls back to plain resume if the SDK rejects the fork (source
|
|
317
|
+
// session no longer on disk, server doesn't support the RPC, etc.).
|
|
323
318
|
let resumeId = resume;
|
|
324
|
-
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
319
|
+
try {
|
|
320
|
+
const result = await this.client.rpc.sessions.fork({ sessionId: resume });
|
|
321
|
+
resumeId = result.sessionId;
|
|
322
|
+
} catch (forkErr) {
|
|
323
|
+
debug.warn('engine', `Copilot fork failed for ${resume}, falling back to plain resume (non-fatal):`, forkErr);
|
|
329
324
|
}
|
|
330
325
|
|
|
331
326
|
try {
|
|
@@ -538,6 +533,71 @@ export class CopilotEngine implements AIEngine {
|
|
|
538
533
|
* `wasFreeform` is derived by checking whether the answer matches one
|
|
539
534
|
* of the predefined `choices` captured when the callback was parked.
|
|
540
535
|
*/
|
|
536
|
+
/**
|
|
537
|
+
* One-shot structured JSON generation via prompt engineering.
|
|
538
|
+
*
|
|
539
|
+
* The Copilot SDK has no native `outputSchema` / `response_format`
|
|
540
|
+
* option, so we instruct the model to emit JSON only, disable every
|
|
541
|
+
* tool with `availableTools: []`, and parse the assistant's final
|
|
542
|
+
* message text.
|
|
543
|
+
*/
|
|
544
|
+
async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
|
|
545
|
+
const {
|
|
546
|
+
prompt,
|
|
547
|
+
modelId,
|
|
548
|
+
schema,
|
|
549
|
+
projectPath,
|
|
550
|
+
abortController,
|
|
551
|
+
accountId,
|
|
552
|
+
} = options;
|
|
553
|
+
|
|
554
|
+
if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
|
|
555
|
+
await this.dispose();
|
|
556
|
+
}
|
|
557
|
+
if (!this._isInitialized || !this.client) {
|
|
558
|
+
await this.initialize(accountId);
|
|
559
|
+
}
|
|
560
|
+
if (!this.client) {
|
|
561
|
+
throw new Error('Copilot client unavailable.');
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const controller = abortController || new AbortController();
|
|
565
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
566
|
+
const jsonPrompt = buildJsonPrompt(prompt, schema);
|
|
567
|
+
|
|
568
|
+
const session = await this.client.createSession({
|
|
569
|
+
model: modelId,
|
|
570
|
+
workingDirectory: resolvedProjectPath,
|
|
571
|
+
onPermissionRequest: approveAll,
|
|
572
|
+
availableTools: [],
|
|
573
|
+
streaming: false,
|
|
574
|
+
} as SessionConfig);
|
|
575
|
+
|
|
576
|
+
const onAbort = () => {
|
|
577
|
+
session.abort().catch((err) => {
|
|
578
|
+
debug.warn('engine', 'Copilot structured: abort failed (non-fatal):', err);
|
|
579
|
+
});
|
|
580
|
+
};
|
|
581
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
582
|
+
|
|
583
|
+
debug.log('engine', `[copilot structured] sending prompt to session ${session.sessionId}, model=${modelId}`);
|
|
584
|
+
|
|
585
|
+
try {
|
|
586
|
+
const final = await session.sendAndWait({ prompt: jsonPrompt });
|
|
587
|
+
if (!final?.data?.content) {
|
|
588
|
+
throw new Error('Copilot returned no assistant message content');
|
|
589
|
+
}
|
|
590
|
+
return extractJson<T>(final.data.content);
|
|
591
|
+
} finally {
|
|
592
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
593
|
+
try {
|
|
594
|
+
await session.disconnect();
|
|
595
|
+
} catch (error) {
|
|
596
|
+
debug.warn('engine', 'Copilot structured: session.disconnect failed (non-fatal):', error);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
541
601
|
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
542
602
|
const pending = this.pendingUserAnswers.get(toolUseId);
|
|
543
603
|
if (!pending) {
|
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
} from './message-converter';
|
|
42
42
|
import { ensureClient, getClient, getServerUrl } from './server';
|
|
43
43
|
import { formatSessionError, handleStreamError } from './error-handler';
|
|
44
|
+
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
44
45
|
import { debug } from '$shared/utils/logger';
|
|
45
46
|
|
|
46
47
|
// ============================================================================
|
|
@@ -940,11 +941,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
940
941
|
throw new Error('Failed to create OpenCode session');
|
|
941
942
|
}
|
|
942
943
|
|
|
943
|
-
|
|
944
|
-
const jsonPrompt = `${prompt}
|
|
945
|
-
|
|
946
|
-
IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text:
|
|
947
|
-
${JSON.stringify(schema, null, 2)}`;
|
|
944
|
+
const jsonPrompt = buildJsonPrompt(prompt, schema);
|
|
948
945
|
|
|
949
946
|
debug.log('engine', `[OC structured] Sending prompt to session ${sessionId}, provider=${providerSlug}, modelId=${modelId}`);
|
|
950
947
|
|
|
@@ -965,26 +962,29 @@ ${JSON.stringify(schema, null, 2)}`;
|
|
|
965
962
|
throw new Error('OpenCode returned empty response');
|
|
966
963
|
}
|
|
967
964
|
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
965
|
+
const parts = data.parts || [];
|
|
966
|
+
debug.log('engine', `[OC structured] Got response with ${parts.length} parts (${parts.map((p: any) => p.type).join(', ')})`);
|
|
967
|
+
|
|
968
|
+
// Prefer `text` parts but fall back to `reasoning` parts: some models
|
|
969
|
+
// (notably thinking-heavy ones) emit JSON inside reasoning when tools
|
|
970
|
+
// are disabled and the prompt is short. Both carry a `.text` field.
|
|
971
|
+
const collectText = (type: 'text' | 'reasoning') =>
|
|
972
|
+
parts
|
|
973
|
+
.filter((p: any) => p.type === type && !p.ignored)
|
|
974
|
+
.map((p: any) => p.text || '')
|
|
975
|
+
.join('');
|
|
976
|
+
|
|
977
|
+
const textContent = collectText('text');
|
|
978
|
+
const source = textContent || collectText('reasoning');
|
|
979
|
+
|
|
980
|
+
if (!source) {
|
|
981
|
+
throw new Error(
|
|
982
|
+
`OpenCode returned no parseable content (received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'})`
|
|
983
|
+
);
|
|
976
984
|
}
|
|
977
985
|
|
|
978
|
-
debug.log('engine', `[OC structured] Raw text: ${
|
|
986
|
+
debug.log('engine', `[OC structured] Raw text: ${source.slice(0, 200)}`);
|
|
979
987
|
|
|
980
|
-
|
|
981
|
-
const jsonMatch = fullText.match(/```(?:json)?\s*([\s\S]*?)```/) || fullText.match(/(\{[\s\S]*\})/);
|
|
982
|
-
const jsonText = jsonMatch ? jsonMatch[1].trim() : fullText.trim();
|
|
983
|
-
|
|
984
|
-
try {
|
|
985
|
-
return JSON.parse(jsonText) as T;
|
|
986
|
-
} catch {
|
|
987
|
-
throw new Error(`OpenCode did not return valid JSON: ${jsonText.slice(0, 200)}`);
|
|
988
|
-
}
|
|
988
|
+
return extractJson<T>(source);
|
|
989
989
|
}
|
|
990
990
|
}
|
|
@@ -37,7 +37,8 @@ import {
|
|
|
37
37
|
type ToolInput,
|
|
38
38
|
} from '@qwen-code/sdk';
|
|
39
39
|
import type { EngineOutput, EngineModel } from '$shared/types/unified';
|
|
40
|
-
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
40
|
+
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
41
|
+
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
41
42
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
42
43
|
import { debug } from '$shared/utils/logger';
|
|
43
44
|
import { getEngineEnv } from './environment';
|
|
@@ -345,6 +346,87 @@ export class QwenEngine implements AIEngine {
|
|
|
345
346
|
}
|
|
346
347
|
}
|
|
347
348
|
|
|
349
|
+
/**
|
|
350
|
+
* One-shot structured JSON generation via prompt engineering.
|
|
351
|
+
*
|
|
352
|
+
* The Qwen SDK has no native `outputSchema` / `response_format` option,
|
|
353
|
+
* so we instruct the model to emit JSON only, restrict tools with
|
|
354
|
+
* `coreTools: []`, and parse the final `result` text returned by the
|
|
355
|
+
* SDK's `SDKResultMessageSuccess`.
|
|
356
|
+
*/
|
|
357
|
+
async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
|
|
358
|
+
const {
|
|
359
|
+
prompt,
|
|
360
|
+
modelId,
|
|
361
|
+
schema,
|
|
362
|
+
projectPath,
|
|
363
|
+
abortController,
|
|
364
|
+
accountId,
|
|
365
|
+
} = options;
|
|
366
|
+
|
|
367
|
+
const resolution = getEngineEnv(accountId);
|
|
368
|
+
if (!resolution) {
|
|
369
|
+
throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
|
|
370
|
+
}
|
|
371
|
+
const { env } = resolution;
|
|
372
|
+
|
|
373
|
+
const controller = abortController || new AbortController();
|
|
374
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
375
|
+
const jsonPrompt = buildJsonPrompt(prompt, schema);
|
|
376
|
+
|
|
377
|
+
debug.log('engine', `[qwen structured] running with model=${modelId}`);
|
|
378
|
+
|
|
379
|
+
const sdkOptions: QueryOptions = {
|
|
380
|
+
cwd: resolvedProjectPath,
|
|
381
|
+
model: modelId,
|
|
382
|
+
env,
|
|
383
|
+
authType: 'openai',
|
|
384
|
+
abortController: controller,
|
|
385
|
+
includePartialMessages: false,
|
|
386
|
+
permissionMode: 'default',
|
|
387
|
+
coreTools: [],
|
|
388
|
+
maxSessionTurns: 1,
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
const sdkPrompt: SDKUserMessage = {
|
|
392
|
+
type: 'user',
|
|
393
|
+
uuid: crypto.randomUUID(),
|
|
394
|
+
session_id: '',
|
|
395
|
+
parent_tool_use_id: null,
|
|
396
|
+
message: { role: 'user', content: jsonPrompt },
|
|
397
|
+
};
|
|
398
|
+
const promptIterable = (async function* (): AsyncIterable<SDKUserMessage> {
|
|
399
|
+
yield sdkPrompt;
|
|
400
|
+
})();
|
|
401
|
+
|
|
402
|
+
const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
|
|
403
|
+
|
|
404
|
+
let resultText = '';
|
|
405
|
+
let errorMessage = '';
|
|
406
|
+
try {
|
|
407
|
+
for await (const message of queryInstance) {
|
|
408
|
+
if (message.type === 'result') {
|
|
409
|
+
if (message.subtype === 'success') {
|
|
410
|
+
resultText = message.result || '';
|
|
411
|
+
} else {
|
|
412
|
+
errorMessage = message.error?.message || message.subtype || 'unknown error';
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (controller.signal.aborted) {
|
|
418
|
+
throw new Error('Generation was cancelled');
|
|
419
|
+
}
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (!resultText) {
|
|
424
|
+
throw new Error(errorMessage || 'Qwen returned no result text');
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
return extractJson<T>(resultText);
|
|
428
|
+
}
|
|
429
|
+
|
|
348
430
|
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
349
431
|
const pending = this.pendingAskUserQuestion;
|
|
350
432
|
if (!pending) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for one-shot structured JSON generation.
|
|
3
|
+
*
|
|
4
|
+
* Engines whose SDKs lack a native JSON-schema output mode (OpenCode, Copilot,
|
|
5
|
+
* Qwen) fall back to prompt engineering: instruct the model to emit JSON only,
|
|
6
|
+
* then parse it out of whatever text the model returns. The native path on
|
|
7
|
+
* Claude and Codex doesn't need these helpers.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Wrap a user prompt with a JSON-only instruction and the target schema. */
|
|
11
|
+
export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>): string {
|
|
12
|
+
return `${prompt}
|
|
13
|
+
|
|
14
|
+
IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text, no markdown fences, no commentary:
|
|
15
|
+
${JSON.stringify(schema, null, 2)}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Extract a JSON object from a model response.
|
|
20
|
+
*
|
|
21
|
+
* Models routinely wrap JSON in markdown fences or prose even when asked
|
|
22
|
+
* not to. This searches in order:
|
|
23
|
+
* 1. ```json … ``` or ``` … ``` fenced block
|
|
24
|
+
* 2. The first balanced `{ … }` substring
|
|
25
|
+
* 3. The raw trimmed text
|
|
26
|
+
*
|
|
27
|
+
* Throws if nothing parses.
|
|
28
|
+
*/
|
|
29
|
+
export function extractJson<T = unknown>(text: string): T {
|
|
30
|
+
const trimmed = text.trim();
|
|
31
|
+
if (!trimmed) {
|
|
32
|
+
throw new Error('Empty response — no JSON to parse');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const candidates: string[] = [];
|
|
36
|
+
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
37
|
+
if (fenced) candidates.push(fenced[1].trim());
|
|
38
|
+
|
|
39
|
+
const braceStart = trimmed.indexOf('{');
|
|
40
|
+
const braceEnd = trimmed.lastIndexOf('}');
|
|
41
|
+
if (braceStart !== -1 && braceEnd > braceStart) {
|
|
42
|
+
candidates.push(trimmed.slice(braceStart, braceEnd + 1));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
candidates.push(trimmed);
|
|
46
|
+
|
|
47
|
+
let lastError: unknown;
|
|
48
|
+
for (const candidate of candidates) {
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(candidate) as T;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
lastError = err;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Response did not contain valid JSON: ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` +
|
|
57
|
+
(lastError instanceof Error ? ` (${lastError.message})` : '')
|
|
58
|
+
);
|
|
59
|
+
}
|