@myrialabs/clopen 0.3.12 → 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.
Files changed (35) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/engine/README.md +101 -29
  6. package/backend/engine/adapters/codex/stream.ts +54 -1
  7. package/backend/engine/adapters/copilot/stream.ts +79 -19
  8. package/backend/engine/adapters/opencode/stream.ts +23 -23
  9. package/backend/engine/adapters/qwen/stream.ts +83 -1
  10. package/backend/engine/structured-helpers.ts +59 -0
  11. package/backend/files/file-archive.ts +191 -0
  12. package/backend/files/file-operations.ts +18 -65
  13. package/backend/files/file-size-limit.test.ts +71 -15
  14. package/backend/files/file-size-limit.ts +36 -8
  15. package/backend/http/files-upload.ts +168 -0
  16. package/backend/index.ts +8 -0
  17. package/backend/mcp/servers/helper.ts +5 -1
  18. package/backend/terminal/pty-session-manager.ts +3 -0
  19. package/backend/terminal/stream-manager.ts +1 -1
  20. package/backend/ws/auth/users.ts +1 -1
  21. package/backend/ws/files/path-access.test.ts +166 -0
  22. package/backend/ws/files/path-access.ts +56 -22
  23. package/backend/ws/files/read.ts +5 -5
  24. package/backend/ws/files/write.ts +47 -25
  25. package/backend/ws/git/commit-message.ts +12 -5
  26. package/backend/ws/terminal/session.ts +1 -0
  27. package/dist/assets/main-BqiSLc8F.css +1 -0
  28. package/dist/assets/{main-HIDO3ugS.js → main-DOVudc3_.js} +232 -231
  29. package/dist/index.html +2 -2
  30. package/package.json +8 -7
  31. package/shared/types/git.ts +4 -2
  32. package/shared/types/stores/settings.ts +2 -0
  33. package/shared/utils/ws-server.ts +6 -0
  34. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  35. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -1,12 +1,18 @@
1
1
  import { describe, expect, test, mock, beforeEach } from 'bun:test';
2
2
  import { invalidateUserSessions, getActiveSessionCountForUser } from './session-invalidation';
3
3
 
4
- // Mock the ws module
5
4
  const mockGetConnectionsForUser = mock(() => [] as any[]);
6
5
  const mockClearAuthForConnections = mock(() => 0);
7
6
  const mockGetProjectChatSessions = mock(() => new Map());
8
7
  const mockEmitUser = mock(() => {});
9
8
 
9
+ const mockKillSession = mock(() => {});
10
+ const mockGetAllSessions = mock(() => [] as Array<{
11
+ sessionId: string;
12
+ projectId?: string;
13
+ userId: string;
14
+ }>);
15
+
10
16
  mock.module('$backend/utils/ws', () => ({
11
17
  ws: {
12
18
  getConnectionsForUser: mockGetConnectionsForUser,
@@ -18,12 +24,21 @@ mock.module('$backend/utils/ws', () => ({
18
24
  }
19
25
  }));
20
26
 
27
+ mock.module('$backend/terminal/pty-session-manager', () => ({
28
+ ptySessionManager: {
29
+ getAllSessions: mockGetAllSessions,
30
+ killSession: mockKillSession
31
+ }
32
+ }));
33
+
21
34
  describe('invalidateUserSessions', () => {
22
35
  beforeEach(() => {
23
36
  mockGetConnectionsForUser.mockClear();
24
37
  mockClearAuthForConnections.mockClear();
25
38
  mockGetProjectChatSessions.mockClear();
26
39
  mockEmitUser.mockClear();
40
+ mockKillSession.mockClear();
41
+ mockGetAllSessions.mockClear();
27
42
  });
28
43
 
29
44
  test('clears auth on all connections for a user', () => {
@@ -46,6 +61,35 @@ describe('invalidateUserSessions', () => {
46
61
 
47
62
  expect(cleared).toBe(0);
48
63
  });
64
+
65
+ test('kills only PTY sessions owned by the revoked user in the project', () => {
66
+ mockGetConnectionsForUser.mockReturnValue(['conn1']);
67
+ mockClearAuthForConnections.mockReturnValue(1);
68
+ mockGetAllSessions.mockReturnValue([
69
+ { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' },
70
+ { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
71
+ { sessionId: 'bob-other', projectId: 'proj-2', userId: 'bob' }
72
+ ]);
73
+
74
+ invalidateUserSessions('bob', 'proj-1');
75
+
76
+ expect(mockKillSession).toHaveBeenCalledTimes(1);
77
+ expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
78
+ });
79
+
80
+ test('kills PTY sessions when user has no websocket connections but project access was revoked', () => {
81
+ mockGetConnectionsForUser.mockReturnValue([]);
82
+ mockGetAllSessions.mockReturnValue([
83
+ { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
84
+ { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' }
85
+ ]);
86
+
87
+ const cleared = invalidateUserSessions('bob', 'proj-1');
88
+
89
+ expect(cleared).toBe(0);
90
+ expect(mockKillSession).toHaveBeenCalledTimes(1);
91
+ expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
92
+ });
49
93
  });
50
94
 
51
95
  describe('getActiveSessionCountForUser', () => {
@@ -7,19 +7,28 @@
7
7
 
8
8
  import { ws } from '$backend/utils/ws';
9
9
  import { debug } from '$shared/utils/logger';
10
+ import { ptySessionManager } from '$backend/terminal/pty-session-manager';
10
11
 
11
12
  /**
12
13
  * Invalidate all active WebSocket sessions for a specific user.
13
14
  * This clears their in-memory auth state and triggers a force-logout
14
15
  * event so the frontend knows to disconnect and re-authenticate.
15
16
  *
17
+ * Also kills any PTY terminal sessions belonging to the specified
18
+ * project to prevent orphaned processes from continuing to run
19
+ * after access is revoked.
20
+ *
16
21
  * @param userId - The user whose sessions should be invalidated
22
+ * @param projectId - Optional project ID to scope PTY cleanup
17
23
  * @returns The number of connections that were cleared
18
24
  */
19
- export function invalidateUserSessions(userId: string): number {
25
+ export function invalidateUserSessions(userId: string, projectId?: string): number {
20
26
  const connections = ws.getConnectionsForUser(userId);
21
27
  if (connections.length === 0) {
22
28
  debug.log('auth', `No active sessions to invalidate for user ${userId}`);
29
+ if (projectId) {
30
+ killUserPtySessionsForProject(userId, projectId);
31
+ }
23
32
  return 0;
24
33
  }
25
34
 
@@ -29,9 +38,34 @@ export function invalidateUserSessions(userId: string): number {
29
38
  // Notify only this user's active connections to force logout.
30
39
  ws.emit.user(userId, 'auth:force-logout-user', { reason: 'Project access revoked' });
31
40
 
41
+ if (projectId) {
42
+ killUserPtySessionsForProject(userId, projectId);
43
+ }
44
+
32
45
  return cleared;
33
46
  }
34
47
 
48
+ /**
49
+ * Kill PTY terminal sessions owned by a specific user in a project.
50
+ * Prevents orphaned shell processes from continuing to run after
51
+ * project access is revoked, without affecting other users' sessions.
52
+ */
53
+ function killUserPtySessionsForProject(userId: string, projectId: string): void {
54
+ let killedCount = 0;
55
+
56
+ for (const session of ptySessionManager.getAllSessions()) {
57
+ if (session.projectId === projectId && session.userId === userId) {
58
+ debug.log('auth', `Killing PTY session ${session.sessionId} for user ${userId} (project ${projectId} access revoked)`);
59
+ ptySessionManager.killSession(session.sessionId, 'SIGKILL');
60
+ killedCount++;
61
+ }
62
+ }
63
+
64
+ if (killedCount > 0) {
65
+ debug.log('auth', `Killed ${killedCount} PTY session(s) for user ${userId} in project ${projectId}`);
66
+ }
67
+ }
68
+
35
69
  /**
36
70
  * Get the number of active WebSocket connections for a user.
37
71
  * Useful for logging and debugging.
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Migration 037: Repair auth_audit_log schema for early-applied databases
3
+ *
4
+ * Some databases applied an early version of migration 036 that did not
5
+ * include the actor_user_id column. The original CREATE statement uses
6
+ * IF NOT EXISTS, so a re-run won't alter the existing table. This
7
+ * migration adds the missing column when absent.
8
+ */
9
+
10
+ import type { DatabaseConnection } from '$shared/types/database/connection';
11
+
12
+ export const description = 'Repair auth_audit_log schema (add missing actor_user_id column)';
13
+
14
+ interface SqliteColumnInfo {
15
+ name: string;
16
+ }
17
+
18
+ export function up(db: DatabaseConnection): void {
19
+ const columns = db
20
+ .prepare(`PRAGMA table_info(auth_audit_log)`)
21
+ .all() as SqliteColumnInfo[];
22
+
23
+ if (columns.length === 0) {
24
+ // Table doesn't exist yet — migration 036 will create it with the
25
+ // correct schema. Nothing to repair.
26
+ return;
27
+ }
28
+
29
+ const hasActorUserId = columns.some((c) => c.name === 'actor_user_id');
30
+ if (!hasActorUserId) {
31
+ db.exec(`ALTER TABLE auth_audit_log ADD COLUMN actor_user_id TEXT;`);
32
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_audit_actor_user_id ON auth_audit_log(actor_user_id);`);
33
+ }
34
+ }
35
+
36
+ export function down(_db: DatabaseConnection): void {
37
+ // Non-destructive repair — no reversal needed.
38
+ }
@@ -35,6 +35,7 @@ import * as migration033 from './033_seed_codex_provider';
35
35
  import * as migration034 from './034_seed_qwen_provider';
36
36
  import * as migration035 from './035_add_owner_to_db_client_connections';
37
37
  import * as migration036 from './036_create_auth_audit_log';
38
+ import * as migration037 from './037_repair_auth_audit_log_schema';
38
39
 
39
40
  // Export all migrations in order
40
41
  export const migrations = [
@@ -253,6 +254,12 @@ export const migrations = [
253
254
  description: migration036.description,
254
255
  up: migration036.up,
255
256
  down: migration036.down
257
+ },
258
+ {
259
+ id: '037',
260
+ description: migration037.description,
261
+ up: migration037.up,
262
+ down: migration037.down
256
263
  }
257
264
  ];
258
265
 
@@ -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, copilot)
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 | **No native API yet** — fork by copying the on-disk session-state DIRECTORY on every resume. |
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 three on-disk workarounds all follow the same shape — copy the
1314
- state, replace the source id with a fresh one, then resume against the
1315
- fork — but the SDKs lay state out differently. Get the layout wrong and
1316
- `sessionStateExists()` silently returns false on every turn, the fork
1317
- block is skipped, and the engine resumes the original session — exactly
1318
- the symptom multi-branch checkpoints surface as.
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 OpenCode already do. The `// TODO` comment at the top of
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`, `opencode/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` |
@@ -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-by-copy on EVERY resume — same semantics as Claude
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. Without this, every turn
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
- // Falls through to a plain resume only when the source state
317
- // can't be found on disk (best-effort recovery).
318
- //
319
- // TODO: replace this fork-by-copy block with a native SDK API
320
- // once @github/copilot-sdk adds `forkSession` (issues
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
- if (sessionStateExists(resume)) {
325
- const forkId = crypto.randomUUID();
326
- if (forkCopilotSessionState(resume, forkId)) {
327
- resumeId = forkId;
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
- // Wrap prompt with JSON instruction since v1 doesn't support format option
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
- debug.log('engine', `[OC structured] Got response with ${data.parts?.length || 0} parts`);
969
-
970
- // Extract text content from response parts and parse as JSON
971
- const textParts = (data.parts || []).filter((p: any) => p.type === 'text');
972
- const fullText = textParts.map((p: any) => p.text || '').join('');
973
-
974
- if (!fullText) {
975
- throw new Error('OpenCode returned no text content');
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: ${fullText.slice(0, 200)}`);
986
+ debug.log('engine', `[OC structured] Raw text: ${source.slice(0, 200)}`);
979
987
 
980
- // Try to extract JSON from the response (may include markdown fences)
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
  }