@openchamber/web 1.22.1 → 1.22.2

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 (111) hide show
  1. package/bin/cli.js +4 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-BI-TY1UG.js} +1 -1
  6. package/dist/assets/{DiffView-CNnDxRmO.js → DiffView-cOmByCaX.js} +3 -3
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-BwSnDlNy.js} +1 -1
  8. package/dist/assets/FilesView-DRRy_6oZ.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-B7YCg1YM.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-CjzNsiIU.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BYlE0YrW.js} +1 -1
  12. package/dist/assets/{MarkdownImageGallery-DffjmciG.js → MarkdownImageGallery-DlTF-wua.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-CqgeZRlP.js +12 -0
  14. package/dist/assets/{OnboardingScreen-CTZe6HZn.js → OnboardingScreen-BsJU7oav.js} +1 -1
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CDNu968J.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BvwtCxW4.js → PierreDiffViewer-BoBsAanf.js} +1 -1
  17. package/dist/assets/{PlanView-C1qvAm7m.js → PlanView-Cxr8LQT1.js} +4 -4
  18. package/dist/assets/SettingsView-bsKpCZbB.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-B0rHQdw4.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-6zP8hwzX.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-Bvwh4Y31.js} +2 -2
  22. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-aaIfrRxl.js} +1 -1
  23. package/dist/assets/{WalkthroughView-D-HFgdmM.js → WalkthroughView-baZ0ssy9.js} +2 -2
  24. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-DfgllYQc.js} +2 -2
  25. package/dist/assets/{contextPanelEmbeddedChat-CV-DwAiX.js → contextPanelEmbeddedChat-prHos-tt.js} +1 -1
  26. package/dist/assets/{de-Cv_4FoXm.js → de-hknQLFxa.js} +2 -2
  27. package/dist/assets/{es-BIWNEbnS.js → es-C_bD3kvW.js} +2 -2
  28. package/dist/assets/{fr-SD3OfMHJ.js → fr-BVF-C2Nu.js} +2 -2
  29. package/dist/assets/index-B0aX0JeI.js +39 -0
  30. package/dist/assets/{index-DLiD86ge.js → index-DUwZ2cWA.js} +1 -1
  31. package/dist/assets/index-Dl3xbAB_.css +1 -0
  32. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-COIS9Df5.js} +1 -1
  33. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-D7LEG-KY.js} +1 -1
  34. package/dist/assets/{ja-D7I9HofF.js → ja-B2G5hD59.js} +2 -2
  35. package/dist/assets/{ko-BsVJM_PQ.js → ko-D6OrOdZ3.js} +2 -2
  36. package/dist/assets/main-BBuBZzoi.js +930 -0
  37. package/dist/assets/{main-DCB4JgVe.js → main-CwIEELQq.js} +2 -2
  38. package/dist/assets/{markdownCore-BoQVG5-a.js → markdownCore-BE_Hhps5.js} +2 -2
  39. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CeXAoWiF.js} +2 -2
  40. package/dist/assets/{mobile-DZV_sfX7.js → mobile-ilq39yLQ.js} +2 -2
  41. package/dist/assets/{patchFileDiff-Chmiz6hq.js → patchFileDiff-DLky6SYr.js} +5 -5
  42. package/dist/assets/{pl-XR9Bs8Be.js → pl-CVroZXt1.js} +2 -2
  43. package/dist/assets/{pt-BR-Due4be8g.js → pt-BR-eH3onaIW.js} +2 -2
  44. package/dist/assets/{renderElectronMiniChatApp-8tXADjfl.js → renderElectronMiniChatApp-BsywqmJT.js} +2 -2
  45. package/dist/assets/{renderMobileApp-Cji7Hma5.js → renderMobileApp-CDun1795.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-DebJIo5U.js +17 -0
  47. package/dist/assets/{scheduledTasksApi-9e-UX6im.js → scheduledTasksApi-B0tChXQC.js} +1 -1
  48. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-DJSXdcG4.js} +1 -1
  49. package/dist/assets/tr-BvtU2tXS.js +7 -0
  50. package/dist/assets/{uk-COYh2BaN.js → uk-nu36iqFz.js} +2 -2
  51. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-Bb1Zihd2.js} +134 -131
  52. package/dist/assets/useInlineCommentController-B8dQWRpH.js +2 -0
  53. package/dist/assets/{useRootScrollLock-KzOUytpn.js → useRootScrollLock-DrJ8gE-x.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-CNjvbb69.js} +2 -2
  55. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  56. package/dist/assets/{web-components-B6QgbmTo.js → web-components-C06MmTcR.js} +1 -1
  57. package/dist/assets/{zh-CN-Cjk6lzhc.js → zh-CN-BClBzZ64.js} +2 -2
  58. package/dist/assets/{zh-TW-Dk0dOg03.js → zh-TW-CXtSqJHF.js} +2 -2
  59. package/dist/index.html +5 -5
  60. package/dist/mini-chat.html +4 -4
  61. package/dist/mobile.html +4 -4
  62. package/package.json +3 -3
  63. package/server/index.js +7 -1
  64. package/server/lib/changelog/update-notes.js +82 -0
  65. package/server/lib/changelog/update-notes.test.js +59 -0
  66. package/server/lib/fs/DOCUMENTATION.md +2 -0
  67. package/server/lib/fs/routes.js +32 -21
  68. package/server/lib/fs/routes.test.js +77 -0
  69. package/server/lib/git/service.js +10 -0
  70. package/server/lib/git/service.test.js +18 -0
  71. package/server/lib/message-queue/DOCUMENTATION.md +17 -7
  72. package/server/lib/message-queue/runtime.js +59 -7
  73. package/server/lib/message-queue/runtime.test.js +59 -3
  74. package/server/lib/opencode/DOCUMENTATION.md +8 -4
  75. package/server/lib/opencode/config-paths.test.js +116 -0
  76. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  77. package/server/lib/opencode/input-history-scope.js +14 -0
  78. package/server/lib/opencode/plugins.js +2 -2
  79. package/server/lib/opencode/providers.js +44 -2
  80. package/server/lib/opencode/providers.test.js +131 -4
  81. package/server/lib/opencode/routes.js +4 -4
  82. package/server/lib/opencode/server-startup-runtime.js +1 -1
  83. package/server/lib/opencode/settings-helpers.js +28 -0
  84. package/server/lib/opencode/settings-helpers.test.js +177 -0
  85. package/server/lib/opencode/shared.js +4 -1
  86. package/server/lib/opencode/skill-routes.js +2 -1
  87. package/server/lib/opencode/snippets.js +1 -2
  88. package/server/lib/package-manager.js +3 -28
  89. package/server/lib/quota/utils/auth.js +1 -1
  90. package/server/lib/relay/host-client.test.js +9 -1
  91. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  92. package/server/lib/session-goal/runtime.js +76 -11
  93. package/server/lib/session-goal/runtime.test.js +426 -0
  94. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  95. package/server/lib/skills-catalog/install.js +3 -2
  96. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  97. package/server/lib/terminal/runtime.js +150 -19
  98. package/server/lib/terminal/runtime.test.js +553 -26
  99. package/server/lib/terminal/shells.js +17 -0
  100. package/server/lib/terminal/shells.test.js +32 -1
  101. package/server/lib/walkthrough/routes.test.js +26 -5
  102. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  103. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  104. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  105. package/dist/assets/index-CHUT_bDS.css +0 -1
  106. package/dist/assets/index-DDInLQDd.js +0 -40
  107. package/dist/assets/main-De8Z5w49.js +0 -928
  108. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  109. package/dist/assets/tr-DBJcAv4y.js +0 -7
  110. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  111. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
@@ -46,6 +46,78 @@ const startIdleTick = async (fetchImpl) => {
46
46
  return { runtime, getSmallModelService };
47
47
  };
48
48
 
49
+ const assistantMessage = (id, infoOverrides = {}) => ({
50
+ info: {
51
+ id,
52
+ sessionID: SESSION_ID,
53
+ role: 'assistant',
54
+ providerID: 'provider',
55
+ modelID: 'model',
56
+ time: { created: 2, completed: 2 },
57
+ tokens: { input: 1, output: 1, cache: { read: 0 } },
58
+ ...infoOverrides,
59
+ },
60
+ parts: [{ type: 'text', text: 'The agent made progress.' }],
61
+ });
62
+
63
+ const createRuntimeHarness = ({ messages, messageFactory, goalOverrides = {}, maxAutoTurns = 20 }) => {
64
+ const requests = [];
65
+ let messageFetchCount = 0;
66
+ const activeSession = {
67
+ ...session,
68
+ metadata: { openchamber: { goal: { ...goal, ...goalOverrides } } },
69
+ };
70
+ const service = {
71
+ generateSmallModelText: vi.fn(async () => ({
72
+ text: '{"verdict":"continue","note":"More work remains"}',
73
+ providerID: 'provider',
74
+ modelID: 'model',
75
+ })),
76
+ };
77
+ const fetchImpl = vi.fn(async (input, init = {}) => {
78
+ const pathname = requestPath(input);
79
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
80
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') {
81
+ activeSession.metadata = JSON.parse(init.body).metadata;
82
+ return jsonResponse(activeSession);
83
+ }
84
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(activeSession);
85
+ if (pathname === '/session/status') return jsonResponse({});
86
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
87
+ if (pathname === `/session/${SESSION_ID}/message`) {
88
+ const nextMessages = messageFactory ? messageFactory(messageFetchCount) : messages;
89
+ messageFetchCount += 1;
90
+ return jsonResponse(nextMessages);
91
+ }
92
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
93
+ throw new Error(`Unexpected request: ${pathname}`);
94
+ });
95
+ vi.stubGlobal('fetch', fetchImpl);
96
+ const runtime = createSessionGoalRuntime({
97
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
98
+ getOpenCodeAuthHeaders: () => ({}),
99
+ getSmallModelService: async () => service,
100
+ isEnabled: () => true,
101
+ idleQuietMs: 10,
102
+ maxAutoTurns,
103
+ });
104
+ return { runtime, requests, service, activeSession };
105
+ };
106
+
107
+ const runIdleTick = async (runtime) => {
108
+ runtime.processPayload({
109
+ type: 'session.status',
110
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
111
+ });
112
+ await vi.runOnlyPendingTimersAsync();
113
+ };
114
+
115
+ const lastPatchedGoal = (requests) => {
116
+ const patches = requests.filter((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
117
+ expect(patches.length).toBeGreaterThan(0);
118
+ return JSON.parse(patches.at(-1).body).metadata.openchamber.goal;
119
+ };
120
+
49
121
  describe('session goal live activity gate', () => {
50
122
  beforeEach(() => {
51
123
  vi.useFakeTimers();
@@ -178,4 +250,358 @@ describe('session goal live activity gate', () => {
178
250
  });
179
251
  runtime.stop();
180
252
  });
253
+
254
+ it('skips audit and sends continuation prompt when assistant message finishes with length stop', async () => {
255
+ const requests = [];
256
+ const fetchImpl = vi.fn(async (input, init = {}) => {
257
+ const pathname = requestPath(input);
258
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
259
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') return jsonResponse(session);
260
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(session);
261
+ if (pathname === '/session/status') return jsonResponse({});
262
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
263
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
264
+ if (pathname === `/session/${SESSION_ID}/message`) {
265
+ return jsonResponse([{
266
+ info: {
267
+ id: 'msg_assistant_len',
268
+ sessionID: SESSION_ID,
269
+ role: 'assistant',
270
+ providerID: 'provider',
271
+ modelID: 'model',
272
+ finish: 'length',
273
+ time: { completed: 2 },
274
+ tokens: { input: 100, output: 4096, reasoning: 4096, cache: { read: 0 } },
275
+ },
276
+ parts: [{ type: 'reasoning', text: 'Drafting extensive implementation...' }],
277
+ }]);
278
+ }
279
+ throw new Error(`Unexpected request: ${pathname}`);
280
+ });
281
+ const service = {
282
+ generateSmallModelText: vi.fn(),
283
+ };
284
+ vi.stubGlobal('fetch', fetchImpl);
285
+ const runtime = createSessionGoalRuntime({
286
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
287
+ getOpenCodeAuthHeaders: () => ({}),
288
+ getSmallModelService: async () => service,
289
+ isEnabled: () => true,
290
+ idleQuietMs: 10,
291
+ });
292
+
293
+ runtime.processPayload({
294
+ type: 'session.status',
295
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
296
+ });
297
+ await vi.runOnlyPendingTimersAsync();
298
+
299
+ // Audit must be skipped on length-truncated turn
300
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
301
+
302
+ // Goal accounting is persisted and turnsUsed incremented
303
+ const patch = requests.find((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
304
+ expect(patch).toBeDefined();
305
+ const writtenGoal = JSON.parse(patch.body).metadata.openchamber.goal;
306
+ expect(writtenGoal).toMatchObject({
307
+ status: 'active',
308
+ turnsUsed: 2,
309
+ });
310
+
311
+ // Continuation prompt is dispatched
312
+ const promptAsync = requests.find((request) => request.pathname === `/session/${SESSION_ID}/prompt_async` && request.method === 'POST');
313
+ expect(promptAsync).toBeDefined();
314
+ const promptBody = JSON.parse(promptAsync.body);
315
+ expect(promptBody.parts[0].text).toContain('Continue working toward the active session goal.');
316
+ runtime.stop();
317
+ });
318
+
319
+ it('skips audit and sends continuation prompt when assistant message carries MessageOutputLengthError', async () => {
320
+ const requests = [];
321
+ const fetchImpl = vi.fn(async (input, init = {}) => {
322
+ const pathname = requestPath(input);
323
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
324
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') return jsonResponse(session);
325
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(session);
326
+ if (pathname === '/session/status') return jsonResponse({});
327
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
328
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
329
+ if (pathname === `/session/${SESSION_ID}/message`) {
330
+ return jsonResponse([{
331
+ info: {
332
+ id: 'msg_assistant_len_err',
333
+ sessionID: SESSION_ID,
334
+ role: 'assistant',
335
+ providerID: 'provider',
336
+ modelID: 'model',
337
+ error: { name: 'MessageOutputLengthError', message: 'Maximum token limit reached' },
338
+ time: { completed: 2 },
339
+ tokens: { input: 100, output: 4096, reasoning: 4096, cache: { read: 0 } },
340
+ },
341
+ parts: [{ type: 'reasoning', text: 'Drafting extensive implementation...' }],
342
+ }]);
343
+ }
344
+ throw new Error(`Unexpected request: ${pathname}`);
345
+ });
346
+ const service = {
347
+ generateSmallModelText: vi.fn(),
348
+ };
349
+ vi.stubGlobal('fetch', fetchImpl);
350
+ const runtime = createSessionGoalRuntime({
351
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
352
+ getOpenCodeAuthHeaders: () => ({}),
353
+ getSmallModelService: async () => service,
354
+ isEnabled: () => true,
355
+ idleQuietMs: 10,
356
+ });
357
+
358
+ runtime.processPayload({
359
+ type: 'session.status',
360
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
361
+ });
362
+ await vi.runOnlyPendingTimersAsync();
363
+
364
+ // Audit must be skipped on MessageOutputLengthError
365
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
366
+
367
+ // Goal remains active and turnsUsed incremented
368
+ const patch = requests.find((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
369
+ expect(patch).toBeDefined();
370
+ const writtenGoal = JSON.parse(patch.body).metadata.openchamber.goal;
371
+ expect(writtenGoal).toMatchObject({
372
+ status: 'active',
373
+ turnsUsed: 2,
374
+ });
375
+
376
+ // Continuation prompt is dispatched
377
+ const promptAsync = requests.find((request) => request.pathname === `/session/${SESSION_ID}/prompt_async` && request.method === 'POST');
378
+ expect(promptAsync).toBeDefined();
379
+ runtime.stop();
380
+ });
381
+
382
+ it.each([
383
+ { name: 'APIError', error: { name: 'APIError', message: 'provider failed' } },
384
+ { name: 'StructuredOutputError', error: { name: 'StructuredOutputError', message: 'invalid output' } },
385
+ { name: 'unnamed errors', error: {} },
386
+ ])('blocks a length finish when the assistant also has a non-length $name', async ({ error }) => {
387
+ const { runtime, requests, service } = createRuntimeHarness({
388
+ messages: [assistantMessage('msg_assistant_error', { finish: 'length', error })],
389
+ });
390
+
391
+ await runIdleTick(runtime);
392
+
393
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
394
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
395
+ expect(lastPatchedGoal(requests)).toMatchObject({
396
+ status: 'blocked',
397
+ statusReason: error.name || 'assistant turn failed',
398
+ });
399
+ runtime.stop();
400
+ });
401
+
402
+ it('blocks after two consecutive length-truncated agent turns without persisting a counter, regardless of message IDs', async () => {
403
+ const firstLength = assistantMessage('z', { finish: 'length', time: { created: 10, completed: 11 } });
404
+ const summary = assistantMessage('summary', { summary: true, time: { created: 15, completed: 16 } });
405
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
406
+ const { runtime, requests, service } = createRuntimeHarness({
407
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, summary, secondLength],
408
+ });
409
+
410
+ await runIdleTick(runtime);
411
+ runtime.processPayload({
412
+ type: 'session.status',
413
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
414
+ });
415
+ await vi.runOnlyPendingTimersAsync();
416
+
417
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
418
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(1);
419
+ expect(lastPatchedGoal(requests)).toMatchObject({
420
+ status: 'blocked',
421
+ statusReason: 'repeated output truncation',
422
+ });
423
+ runtime.stop();
424
+ });
425
+
426
+ it('allows one explicit Resume after repeated truncation, then blocks another cutoff', async () => {
427
+ const first = assistantMessage('first', { finish: 'length', time: { created: 10, completed: 11 } });
428
+ const second = assistantMessage('second', { finish: 'length', time: { created: 20, completed: 21 } });
429
+ const messages = [first, second];
430
+ const { runtime, requests, activeSession } = createRuntimeHarness({ messages });
431
+ try {
432
+ await runIdleTick(runtime);
433
+ expect(lastPatchedGoal(requests).status).toBe('blocked');
434
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(0);
435
+ Object.assign(activeSession.metadata.openchamber.goal, { status: 'active', statusReason: 'resumed', turnsUsed: 0 });
436
+ await runIdleTick(runtime);
437
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active', statusReason: '', turnsUsed: 1 });
438
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(1);
439
+ messages.push(assistantMessage('third', { finish: 'length', time: { created: 30, completed: 31 } }));
440
+ await runIdleTick(runtime);
441
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'blocked', statusReason: 'repeated output truncation' });
442
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(1);
443
+ } finally {
444
+ runtime.stop();
445
+ }
446
+ });
447
+
448
+ it.each([
449
+ { tokenBudget: 1, error: undefined, expectedStatus: 'budgetLimited' },
450
+ { tokenBudget: null, error: { name: 'APIError' }, expectedStatus: 'blocked' },
451
+ ])('keeps $expectedStatus protection on explicit Resume', async ({ tokenBudget, error, expectedStatus }) => {
452
+ const { runtime, requests } = createRuntimeHarness({
453
+ goalOverrides: { statusReason: 'resumed', tokenBudget },
454
+ messages: [assistantMessage('resumed', { finish: 'length', error })],
455
+ });
456
+ try {
457
+ await runIdleTick(runtime);
458
+ expect(lastPatchedGoal(requests).status).toBe(expectedStatus);
459
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(0);
460
+ } finally {
461
+ runtime.stop();
462
+ }
463
+ });
464
+
465
+ it('continues after a truncated agent turn followed by a length-finished summary', async () => {
466
+ const firstLength = assistantMessage('agent-length', { finish: 'length', time: { created: 10, completed: 11 } });
467
+ const summary = assistantMessage('summary', {
468
+ summary: true,
469
+ finish: 'length',
470
+ time: { created: 15, completed: 16 },
471
+ });
472
+ const { runtime, requests, service } = createRuntimeHarness({
473
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, summary],
474
+ });
475
+
476
+ await runIdleTick(runtime);
477
+ await runIdleTick(runtime);
478
+
479
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
480
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
481
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
482
+ runtime.stop();
483
+ });
484
+
485
+ it('does not infer a repeated streak when a completed assistant timestamp is missing', async () => {
486
+ const firstLength = assistantMessage('z', { finish: 'length', time: { completed: 11 } });
487
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
488
+ const { runtime, requests, service } = createRuntimeHarness({
489
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, secondLength],
490
+ });
491
+
492
+ await runIdleTick(runtime);
493
+ await runIdleTick(runtime);
494
+
495
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
496
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
497
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
498
+ runtime.stop();
499
+ });
500
+
501
+ it('ignores a missing timestamp on an older assistant when known post-goal turns establish a streak', async () => {
502
+ const olderLength = assistantMessage('legacy', { finish: 'length', time: { completed: 5 } });
503
+ const firstLength = assistantMessage('z', { finish: 'length', time: { created: 10, completed: 11 } });
504
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
505
+ const { runtime, requests, service } = createRuntimeHarness({
506
+ goalOverrides: { createdAt: 6 },
507
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [olderLength, firstLength, secondLength],
508
+ });
509
+
510
+ await runIdleTick(runtime);
511
+ await runIdleTick(runtime);
512
+
513
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
514
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(1);
515
+ expect(lastPatchedGoal(requests)).toMatchObject({
516
+ status: 'blocked',
517
+ statusReason: 'repeated output truncation',
518
+ });
519
+ runtime.stop();
520
+ });
521
+
522
+ it('does not count a previous truncated turn created at the goal boundary', async () => {
523
+ const firstLength = assistantMessage('before-boundary', { finish: 'length', time: { created: 10, completed: 11 } });
524
+ const secondLength = assistantMessage('after-boundary', { finish: 'length', time: { created: 20, completed: 21 } });
525
+ const { runtime, requests, service } = createRuntimeHarness({
526
+ goalOverrides: { createdAt: 10 },
527
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, secondLength],
528
+ });
529
+
530
+ await runIdleTick(runtime);
531
+ await runIdleTick(runtime);
532
+
533
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
534
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
535
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
536
+ runtime.stop();
537
+ });
538
+
539
+ it('allows length recovery after an ordinary assistant turn breaks the streak', async () => {
540
+ const firstLength = assistantMessage('msg_length_before_normal', { finish: 'length' });
541
+ const normal = assistantMessage('msg_normal');
542
+ const secondLength = assistantMessage('msg_length_after_normal', { finish: 'length' });
543
+ const { runtime, requests, service } = createRuntimeHarness({
544
+ messageFactory: (fetchCount) => fetchCount < 2
545
+ ? [firstLength]
546
+ : [firstLength, normal, secondLength],
547
+ });
548
+
549
+ await runIdleTick(runtime);
550
+ await runIdleTick(runtime);
551
+
552
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
553
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
554
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
555
+ runtime.stop();
556
+ });
557
+
558
+ it('keeps MessageAbortedError pause behavior instead of continuing', async () => {
559
+ const { runtime, requests, service } = createRuntimeHarness({
560
+ messages: [assistantMessage('msg_aborted', { error: { name: 'MessageAbortedError' } })],
561
+ });
562
+
563
+ await runIdleTick(runtime);
564
+
565
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
566
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
567
+ expect(lastPatchedGoal(requests)).toMatchObject({
568
+ status: 'paused',
569
+ statusReason: 'paused after abort',
570
+ });
571
+ runtime.stop();
572
+ });
573
+
574
+ it('checks the token budget before allowing length recovery', async () => {
575
+ const { runtime, requests, service } = createRuntimeHarness({
576
+ goalOverrides: { tokenBudget: 5 },
577
+ messages: [assistantMessage('msg_budget_length', {
578
+ finish: 'length',
579
+ tokens: { input: 3, output: 3, cache: { read: 0 } },
580
+ })],
581
+ });
582
+
583
+ await runIdleTick(runtime);
584
+
585
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
586
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
587
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'budgetLimited' });
588
+ runtime.stop();
589
+ });
590
+
591
+ it('checks the auto-continuation cap before allowing length recovery', async () => {
592
+ const { runtime, requests, service } = createRuntimeHarness({
593
+ maxAutoTurns: 1,
594
+ messages: [assistantMessage('msg_cap_length', { finish: 'length' })],
595
+ });
596
+
597
+ await runIdleTick(runtime);
598
+
599
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
600
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
601
+ expect(lastPatchedGoal(requests)).toMatchObject({
602
+ status: 'blocked',
603
+ statusReason: 'auto-continuation limit reached',
604
+ });
605
+ runtime.stop();
606
+ });
181
607
  });
@@ -58,7 +58,7 @@ The following functions are internal helpers used by exported functions:
58
58
  - `safeRm(dir)`: Safely remove directory recursively (ignores errors).
59
59
  - `ensureDir(dirPath)`: Ensure directory exists with recursive creation.
60
60
  - `copyDirectoryNoSymlinks(srcDir, dstDir)`: Copy directory contents without symlinks, with path traversal protection.
61
- - `normalizeUserSkillDir(userSkillDir)`: Normalize user skill directory path (handles legacy `~/.config/opencode/skill` → `~/.config/opencode/skills` migration).
61
+ - `normalizeUserSkillDir(userSkillDir)`: Normalize the user skill directory path (handles the legacy `skill` directory in the XDG config location, or `~/.config/opencode/skill` when XDG is unset, by selecting the plural `skills` directory when appropriate).
62
62
 
63
63
  ### Git Clone Helpers (`install.js`, `scan.js`)
64
64
  - `cloneRepo({ cloneUrl, identity, tempDir })`: Clone git repository with preferred partial clone (`--filter=blob:none`) and fallback. Uses non-interactive mode.
@@ -4,13 +4,14 @@ import path from 'path';
4
4
 
5
5
  import { assertGitAvailable, looksLikeAuthError, runGit } from './git.js';
6
6
  import { parseSkillRepoSource } from './source.js';
7
+ import { OPENCODE_CONFIG_DIR } from '../opencode/shared.js';
7
8
 
8
9
  const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/;
9
10
 
10
11
  function normalizeUserSkillDir(userSkillDir) {
11
12
  if (!userSkillDir) return null;
12
- const legacySkillDir = path.join(os.homedir(), '.config', 'opencode', 'skill');
13
- const pluralSkillDir = path.join(os.homedir(), '.config', 'opencode', 'skills');
13
+ const legacySkillDir = path.join(OPENCODE_CONFIG_DIR, 'skill');
14
+ const pluralSkillDir = path.join(OPENCODE_CONFIG_DIR, 'skills');
14
15
  if (userSkillDir === legacySkillDir) {
15
16
  if (fs.existsSync(legacySkillDir) && !fs.existsSync(pluralSkillDir)) return legacySkillDir;
16
17
  return pluralSkillDir;
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Ownership
4
4
 
5
- `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
5
+ `runtime.js` owns terminal identity, PTY processes, launch mode, session purpose, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families, resolves the persisted shell ID, and builds the per-shell argv for interactive versus command launches. Clients own tab arrangement. Interactive terminals use stable IDs; project actions keep a stable UI tab and allocate a fresh terminal ID for each command execution. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
6
6
 
7
7
  ## Protocol
8
8
 
@@ -19,21 +19,25 @@
19
19
 
20
20
  HTTP remains the authenticated command plane for create, resize, appearance updates, restart, close, and force-kill. There is no SSE output or HTTP input compatibility path.
21
21
 
22
- `GET /api/terminal/sessions` enumerates live sessions (optionally filtered by resolved `cwd`) so clients can adopt terminals their local tab projection does not know about — another device, a new browser tab, or cleared storage. `POST /api/terminal/touch` refreshes `lastActivity` for the listed session ids; open clients call it periodically so background tabs, which hold no WebSocket attachment, are not idle-reaped while a client still shows them.
22
+ `GET /api/terminal/sessions` enumerates live sessions (optionally filtered by resolved `cwd`) so clients can adopt terminals their local tab projection does not know about — another device, a new browser tab, or cleared storage. Listings include the effective launch mode and the normalized purpose, but never the command text. `POST /api/terminal/touch` refreshes `lastActivity` for the listed session ids; open clients call it periodically so background tabs, which hold no WebSocket attachment, are not idle-reaped while a client still shows them.
23
23
 
24
24
  ## PTY Lifecycle
25
25
 
26
26
  - IDs are client-provided or generated with `randomUUID()`.
27
- - Concurrent creates for one ID are single-flight only when working directory and shell preference match. Existing IDs cannot be reused for another working directory.
27
+ - Create defaults to interactive mode. Command mode requires a non-empty trimmed command no longer than the terminal input limit and launches the shell so the PTY exits when that command exits. Each session also carries a normalized purpose. Omitted purpose means `{ type: 'terminal' }`. Project actions use `{ type: 'project-action', actionId, executionId }`, and the server validates both IDs as non-empty bounded strings. Create responses and attach snapshots echo the effective mode and purpose.
28
+ - Concurrent creates for one ID are single-flight only when working directory, shell preference, login mode, launch mode, and session purpose match. Command-mode creates must also match the command text, unless the purpose is a project action that is already running for the same resolved `(cwd, actionId)` pair. In that case the runtime returns the existing session and its existing execution identity, even when another client requested a different session ID. Existing IDs cannot be reused for another working directory or another purpose.
28
29
  - Dimensions are bounded to 1-1000 columns and 1-500 rows; input is capped at 64 KiB.
29
30
  - A client may create before its renderer has mounted. It derives an initial size from the container and font metrics (falling back to 80x24 when unavailable), then sends a resize once Ghostty reports its final dimensions. This allows shell startup and renderer initialization to overlap.
30
31
  - PTY children explicitly clear `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup.
31
32
  - PTY children also strip AppImage `ARGV0` (and other host-private shell vars such as `ELECTRON_RUN_AS_NODE`, `BASH_ENV`, `ENV`, `BASH_XTRACEFD`). An exported `ARGV0` makes zsh rewrite argv[0] for every external command, which breaks Python venv detection and other argv[0]/$0 consumers while leaving `/proc/self/exe` correct. On Linux, PTY spawn is wrapped with `env -u ARGV0` because `bun-pty` merges the native OS environ and would otherwise reintroduce `ARGV0` after a JS-only delete.
32
- - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Preference changes affect new sessions and explicit restarts, not running PTYs.
33
- - PTY data and exit callbacks enter one FIFO queue. Stale callbacks from replaced processes are ignored.
33
+ - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Interactive shells still launch as before. Command-mode launches reuse the same environment and login support, but switch argv by shell family: POSIX and Fish use interactive `-c`, Nushell uses `-c`, PowerShell uses `-Command`, and cmd uses `/d /s /c`. Preference changes affect new sessions and explicit restarts, not running PTYs.
34
+ - PTY data and exit callbacks enter one FIFO queue. The runtime wires those listeners in the same synchronous turn that receives the PTY object. `node-pty` and `bun-pty` both expose the PTY before dispatching registered callbacks. If a backend emitted exit before listener registration, this layer could not recover it, so the wiring stays adjacent to PTY creation.
34
35
  - Scrollback is retained on the server and capped at 512 KiB with UTF-8-safe trimming. Device-status, device-attribute, cursor-position reply, and color-query exchanges are removed from replay history with incomplete control sequences carried across PTY chunks; live output remains byte-for-byte unchanged.
35
- - Exited sessions remain attachable until explicit close or idle cleanup.
36
- - Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID.
36
+ - Exited sessions remain attachable until explicit close, idle cleanup, or a successful replacement of the same project action. Creating a replacement retires only exited records for the same resolved directory and action, after the new PTY starts. Failed creation preserves the old record and output. These replaced records do not exhaust the terminal capacity limit.
37
+ - Deduplicated create responses may describe another client's execution. Cancellation cleanup closes only the terminal ID allocated for the cancelled request; it never closes an adopted peer execution.
38
+ - Create and restart validate the working directory with a real `stat` and answer HTTP 400 `Invalid working directory` when it is not a directory. When the path does not exist at all (`ENOENT`/`ENOTDIR`, a worktree deleted outside OpenChamber) the body also carries `code: "TERMINAL_CWD_MISSING"`. That is the one rejection the client can recover from: the session, not the terminal, is stranded, and the shared UI moves it to its project directory and starts a terminal there. Every other rejection stays generic; the runtime never substitutes a parent directory on its own.
39
+ - Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID. Command-mode sessions reject restart with HTTP 400 instead of silently turning into interactive shells with stale action metadata.
40
+ - A delete that arrives while create is still pending leaves a cancellation tombstone. When the PTY arrives, the runtime terminates it immediately, never inserts the session into the live map, and returns a create error while the delete still succeeds.
37
41
  - Close uses SIGTERM with bounded SIGKILL escalation. Force-kill, idle cleanup, and runtime shutdown terminate process groups immediately where supported. Removal explicitly sends a fatal scoped closure and evicts client projections even when a PTY backend fails to emit `onExit`; attached terminals are not considered idle.
38
42
 
39
43
  ## Security And Relay