@openchamber/web 1.17.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +3 -0
  2. package/dist/assets/{DiagramView-CRjw8BGO.js → DiagramView-CI2JhNxs.js} +1 -1
  3. package/dist/assets/{MarkdownRendererImpl-BjjFniUt.js → MarkdownRendererImpl-Bq-wtyiF.js} +3 -3
  4. package/dist/assets/{OnboardingScreen-JuiKjRTI.js → OnboardingScreen-B6BqjJ0l.js} +1 -1
  5. package/dist/assets/{SessionSwitcherDropdown-S2EvRz-E.js → SessionSwitcherDropdown-DepVWyeA.js} +1 -1
  6. package/dist/assets/{SettingsWindow-PzqMjCEx.js → SettingsWindow-Xj4Uy_Fr.js} +1 -1
  7. package/dist/assets/{document-attachments-DZf4VoiD.js → document-attachments-C5tUWELq.js} +1 -1
  8. package/dist/assets/{es-CErIcckI.js → es-DSTFcl6A.js} +1 -1
  9. package/dist/assets/{fr-z5ORYrou.js → fr-CEeK5ifb.js} +1 -1
  10. package/dist/assets/index-DUBtXIPQ.css +1 -0
  11. package/dist/assets/{index-DMCrPMIW.js → index-Dld5wFqI.js} +3 -3
  12. package/dist/assets/{ja-ecPbYMn0.js → ja-pu3u7ZOY.js} +1 -1
  13. package/dist/assets/{ko-CASkpaQH.js → ko-CStr_CJ-.js} +1 -1
  14. package/dist/assets/{main-BTLr2DyB.js → main-DBG0rE6P.js} +36 -36
  15. package/dist/assets/{main-DQ-uX_zf.js → main-Xc2GeALp.js} +2 -2
  16. package/dist/assets/{markdownCore-C4XTgyYU.js → markdownCore-Bn8Ywh-t.js} +2 -2
  17. package/dist/assets/miniChat-D5FFElbH.js +2 -0
  18. package/dist/assets/mobile-B4K4IpE7.js +2 -0
  19. package/dist/assets/{pl-BYtGQyDI.js → pl-nD08d1Bo.js} +1 -1
  20. package/dist/assets/{pt-BR-D8dONk68.js → pt-BR-DqcoQ-nE.js} +1 -1
  21. package/dist/assets/{renderElectronMiniChatApp-Cbdusroc.js → renderElectronMiniChatApp-B-rksap7.js} +2 -2
  22. package/dist/assets/renderMobileApp-U-jxDI_G.js +16 -0
  23. package/dist/assets/runtimeEndpointReset-fpfBYOyW.js +174 -0
  24. package/dist/assets/{uk-C8z1P8tg.js → uk-DkX7DsWk.js} +1 -1
  25. package/dist/assets/{useAppFontEffects-DrLhDSC3.js → useAppFontEffects-CZdEKvZ8.js} +129 -127
  26. package/dist/assets/{vendor-.bun-DvcSrJLa.js → vendor-.bun-BzW0Lgld.js} +1 -1
  27. package/dist/assets/{zh-CN-BwJPtjKq.js → zh-CN-DlqHNM1o.js} +1 -1
  28. package/dist/assets/{zh-TW-C7FpgD-Y.js → zh-TW-DeKAHBhV.js} +1 -1
  29. package/dist/index.html +4 -4
  30. package/dist/mini-chat.html +4 -4
  31. package/dist/mobile.html +4 -4
  32. package/package.json +2 -2
  33. package/server/index.js +31 -2
  34. package/server/lib/openchamber-sessions/routes.js +30 -30
  35. package/server/lib/openchamber-sessions/routes.test.js +38 -0
  36. package/server/lib/opencode/DOCUMENTATION.md +7 -2
  37. package/server/lib/opencode/env-runtime.js +18 -0
  38. package/server/lib/opencode/env-runtime.test.js +12 -0
  39. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  40. package/server/lib/opencode/lifecycle.js +18 -6
  41. package/server/lib/opencode/lifecycle.test.js +67 -1
  42. package/server/lib/opencode/proxy.js +32 -2
  43. package/server/lib/opencode/routes-upgrade.test.js +113 -0
  44. package/server/lib/opencode/routes.js +69 -36
  45. package/server/lib/opencode/server-utils-runtime.js +2 -0
  46. package/server/lib/opencode/settings-helpers.js +3 -0
  47. package/server/lib/opencode/settings-helpers.test.js +8 -0
  48. package/server/lib/opencode/upgrade-capability.js +36 -0
  49. package/server/lib/opencode/upgrade-capability.test.js +57 -0
  50. package/server/lib/quota/providers/codex.js +18 -0
  51. package/server/lib/quota/providers/codex.test.js +28 -0
  52. package/server/lib/scheduled-tasks/runtime.js +44 -18
  53. package/server/lib/scheduled-tasks/runtime.test.js +12 -1
  54. package/server/lib/session-goal/DOCUMENTATION.md +12 -3
  55. package/server/lib/system-prompt/DOCUMENTATION.md +36 -0
  56. package/server/lib/system-prompt/runtime.js +68 -0
  57. package/server/lib/system-prompt/runtime.test.js +76 -0
  58. package/server/opencode-proxy.test.js +49 -0
  59. package/dist/assets/index-Csh1A7Eh.css +0 -1
  60. package/dist/assets/miniChat-ComIlrTa.js +0 -2
  61. package/dist/assets/mobile-DUYXEkKA.js +0 -2
  62. package/dist/assets/renderMobileApp-m9MPmIZT.js +0 -16
  63. package/dist/assets/runtimeEndpointReset-B0yQKPe0.js +0 -174
@@ -0,0 +1,36 @@
1
+ # Managed System Prompt Optimizer
2
+
3
+ ## Purpose
4
+
5
+ This module injects an opt-in OpenCode plugin only when OpenChamber launches
6
+ and owns the OpenCode process and `optimizeSystemPrompt` is enabled. The plugin
7
+ replaces OpenCode's built-in behavioral/provider prompt with a short identity
8
+ while preserving the environment, project instructions, MCP instructions,
9
+ skills, conversation history, and separately supplied tools.
10
+
11
+ ## Runtime flow
12
+
13
+ 1. Settings persist `optimizeSystemPrompt` in OpenChamber's `settings.json`.
14
+ 2. The setting is applied when managed OpenCode restarts.
15
+ 3. The runtime materializes the plugin under
16
+ `<openchamber-data-dir>/system-prompt/` and appends its `file://` URL to
17
+ `OPENCODE_CONFIG_CONTENT` without replacing existing plugin entries.
18
+ 4. The plugin tracks the selected agent through `chat.message`. The transform
19
+ runs only for sessions using the built-in `build` or `plan` agent.
20
+ 5. The transform locates OpenCode's environment boundary and removes only the
21
+ preceding text. If the boundary is absent, it leaves the prompt unchanged.
22
+
23
+ ## Limitations
24
+
25
+ OpenCode exposes the assembled prompt rather than structured sections. A custom
26
+ prompt configured by overriding the `build` or `plan` agent occupies the same
27
+ prefix as the built-in provider prompt, so the optimizer also removes that
28
+ override. Other agents are never transformed. The setting is off by default.
29
+
30
+ Plan-mode restrictions and build-mode transitions are not part of the removed
31
+ prefix. OpenCode injects those as synthetic message reminders after system
32
+ prompt transformation and separately enforces plan restrictions through tool
33
+ permissions.
34
+
35
+ The plugin is not injected for external OpenCode servers or VS Code's separate
36
+ OpenCode lifecycle.
@@ -0,0 +1,68 @@
1
+ import { parse as parseJsonc } from 'jsonc-parser';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ const PROVIDER_PROMPT_BOUNDARY = 'You are powered by the model named';
5
+ const MINIMAL_IDENTITY = 'You are OpenCode, a coding agent.';
6
+
7
+ const createPluginSource = () => String.raw`
8
+ const PROVIDER_PROMPT_BOUNDARY = ${JSON.stringify(PROVIDER_PROMPT_BOUNDARY)}
9
+ const MINIMAL_IDENTITY = ${JSON.stringify(MINIMAL_IDENTITY)}
10
+ const optimizedSessions = new Map()
11
+
12
+ export const OpenChamberSystemPromptPlugin = async () => ({
13
+ "chat.message": async (input, output) => {
14
+ if (!input.sessionID) return
15
+ const agent = output?.message?.agent ?? input.agent
16
+ if (agent === "build" || agent === "plan") {
17
+ optimizedSessions.set(input.sessionID, agent)
18
+ return
19
+ }
20
+ optimizedSessions.delete(input.sessionID)
21
+ },
22
+ event: async ({ event }) => {
23
+ if (event?.type === "session.deleted") optimizedSessions.delete(event.properties?.info?.id)
24
+ },
25
+ "experimental.chat.system.transform": async (input, output) => {
26
+ if (!input.sessionID || !optimizedSessions.has(input.sessionID)) return
27
+ const prompt = output.system.join("\n")
28
+ const boundary = prompt.indexOf(PROVIDER_PROMPT_BOUNDARY)
29
+ if (boundary < 0) return
30
+ output.system.length = 0
31
+ output.system.push(MINIMAL_IDENTITY + "\n\n" + prompt.slice(boundary))
32
+ },
33
+ })
34
+ `;
35
+
36
+ const mergePluginConfig = (rawConfig, pluginUrl) => {
37
+ const errors = [];
38
+ const parsed = typeof rawConfig === 'string' && rawConfig.trim()
39
+ ? parseJsonc(rawConfig, errors, { allowTrailingComma: true })
40
+ : {};
41
+ if (errors.length > 0 || !parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
42
+ throw new Error('OPENCODE_CONFIG_CONTENT must contain a valid JSON object before OpenChamber can inject its system prompt optimizer');
43
+ }
44
+ if (parsed.plugin !== undefined && !Array.isArray(parsed.plugin)) {
45
+ throw new Error('OPENCODE_CONFIG_CONTENT plugin must be an array before OpenChamber can inject its system prompt optimizer');
46
+ }
47
+ const configured = Array.isArray(parsed.plugin) ? parsed.plugin : [];
48
+ parsed.plugin = [
49
+ ...configured.filter((value) => value !== pluginUrl && (!Array.isArray(value) || value[0] !== pluginUrl)),
50
+ pluginUrl,
51
+ ];
52
+ return JSON.stringify(parsed);
53
+ };
54
+
55
+ export const createSystemPromptRuntime = ({ fsPromises, path, dataDir }) => {
56
+ const pluginDirectory = path.join(dataDir, 'system-prompt');
57
+ const pluginPath = path.join(pluginDirectory, 'openchamber-system-prompt-plugin.js');
58
+
59
+ const prepareManagedOpenCodeEnv = async (rawConfig) => {
60
+ await fsPromises.mkdir(pluginDirectory, { recursive: true });
61
+ await fsPromises.writeFile(pluginPath, createPluginSource(), { mode: 0o600 });
62
+ return {
63
+ OPENCODE_CONFIG_CONTENT: mergePluginConfig(rawConfig, pathToFileURL(pluginPath).href),
64
+ };
65
+ };
66
+
67
+ return { prepareManagedOpenCodeEnv };
68
+ };
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+
7
+ import { createSystemPromptRuntime } from './runtime.js';
8
+
9
+ const temporaryDirectories = [];
10
+
11
+ afterEach(async () => {
12
+ await Promise.all(temporaryDirectories.splice(0).map((directory) => fs.rm(directory, { recursive: true, force: true })));
13
+ });
14
+
15
+ describe('managed system prompt runtime', () => {
16
+ it.each(['build', 'plan'])('materializes the optimizer for the %s agent and preserves existing plugins', async (agent) => {
17
+ const dataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'openchamber-system-prompt-'));
18
+ temporaryDirectories.push(dataDir);
19
+ const runtime = createSystemPromptRuntime({ fsPromises: fs, path, dataDir });
20
+
21
+ const prepared = await runtime.prepareManagedOpenCodeEnv('{ "plugin": ["file:///existing.js"], "model": "test/model" }');
22
+ const config = JSON.parse(prepared.OPENCODE_CONFIG_CONTENT);
23
+ const pluginPath = path.join(dataDir, 'system-prompt', 'openchamber-system-prompt-plugin.js');
24
+
25
+ expect(config.model).toBe('test/model');
26
+ expect(config.plugin).toEqual(['file:///existing.js', pathToFileURL(pluginPath).href]);
27
+ const pluginModule = await import(`${pathToFileURL(pluginPath).href}?test=${Date.now()}`);
28
+ const hooks = await pluginModule.OpenChamberSystemPromptPlugin();
29
+ const output = {
30
+ system: ['Behavioral prompt\nYou are powered by the model named GPT.\n<env>kept</env>'],
31
+ };
32
+ await hooks['chat.message'](
33
+ { sessionID: 'session-1', ...(agent === 'build' ? { agent } : {}) },
34
+ { message: { agent } },
35
+ );
36
+ await hooks['experimental.chat.system.transform']({ sessionID: 'session-1' }, output);
37
+ expect(output.system).toEqual([
38
+ 'You are OpenCode, a coding agent.\n\nYou are powered by the model named GPT.\n<env>kept</env>',
39
+ ]);
40
+ });
41
+
42
+ it('leaves an unknown prompt format unchanged', async () => {
43
+ const dataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'openchamber-system-prompt-'));
44
+ temporaryDirectories.push(dataDir);
45
+ const runtime = createSystemPromptRuntime({ fsPromises: fs, path, dataDir });
46
+ await runtime.prepareManagedOpenCodeEnv('{}');
47
+ const pluginPath = path.join(dataDir, 'system-prompt', 'openchamber-system-prompt-plugin.js');
48
+ const pluginModule = await import(`${pathToFileURL(pluginPath).href}?test=${Date.now()}`);
49
+ const hooks = await pluginModule.OpenChamberSystemPromptPlugin();
50
+ const output = { system: ['Unrecognized prompt'] };
51
+ await hooks['chat.message']({ sessionID: 'session-1', agent: 'plan' });
52
+ await hooks['experimental.chat.system.transform']({ sessionID: 'session-1' }, output);
53
+ expect(output.system).toEqual(['Unrecognized prompt']);
54
+ });
55
+
56
+ it('does not transform prompts for other agents', async () => {
57
+ const dataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'openchamber-system-prompt-'));
58
+ temporaryDirectories.push(dataDir);
59
+ const runtime = createSystemPromptRuntime({ fsPromises: fs, path, dataDir });
60
+ await runtime.prepareManagedOpenCodeEnv('{}');
61
+ const pluginPath = path.join(dataDir, 'system-prompt', 'openchamber-system-prompt-plugin.js');
62
+ const pluginModule = await import(`${pathToFileURL(pluginPath).href}?test=${Date.now()}`);
63
+ const hooks = await pluginModule.OpenChamberSystemPromptPlugin();
64
+ const output = {
65
+ system: ['Custom agent prompt\nYou are powered by the model named GPT.\n<env>kept</env>'],
66
+ };
67
+
68
+ await hooks['chat.message']({ sessionID: 'session-1', agent: 'build' });
69
+ await hooks['chat.message']({ sessionID: 'session-1', agent: 'review' });
70
+ await hooks['experimental.chat.system.transform']({ sessionID: 'session-1' }, output);
71
+
72
+ expect(output.system).toEqual([
73
+ 'Custom agent prompt\nYou are powered by the model named GPT.\n<env>kept</env>',
74
+ ]);
75
+ });
76
+ });
@@ -82,6 +82,55 @@ describe('OpenCode proxy SSE forwarding', () => {
82
82
  expect(seenAuthorization).toBe('Bearer test-token');
83
83
  });
84
84
 
85
+ it('closes downstream SSE when the OpenCode upstream stalls despite proxy heartbeats', async () => {
86
+ let stallTimeoutReads = 0;
87
+ const upstream = express();
88
+ upstream.get('/global/event', (_req, res) => {
89
+ res.setHeader('Content-Type', 'text/event-stream');
90
+ res.flushHeaders();
91
+ setTimeout(() => res.write(':upstream-alive\n\n'), 40);
92
+ setTimeout(() => res.write('data: still-alive\n\n'), 80);
93
+ });
94
+ upstreamServer = await listen(upstream);
95
+ const upstreamPort = upstreamServer.address().port;
96
+
97
+ const app = express();
98
+ registerOpenCodeProxy(app, {
99
+ fs: {},
100
+ os: {},
101
+ path,
102
+ OPEN_CODE_READY_GRACE_MS: 0,
103
+ SSE_HEARTBEAT_INTERVAL_MS: 10,
104
+ getSseUpstreamStallTimeoutMs: () => {
105
+ stallTimeoutReads += 1;
106
+ return stallTimeoutReads === 1 ? 50 : 100;
107
+ },
108
+ getRuntime: () => ({
109
+ openCodePort: upstreamPort,
110
+ isOpenCodeReady: true,
111
+ openCodeNotReadySince: 0,
112
+ isRestartingOpenCode: false,
113
+ }),
114
+ getOpenCodeAuthHeaders: () => ({}),
115
+ buildOpenCodeUrl: (requestPath) => `http://127.0.0.1:${upstreamPort}${requestPath}`,
116
+ ensureOpenCodeApiPrefix: () => {},
117
+ });
118
+ proxyServer = await listen(app);
119
+ const proxyPort = proxyServer.address().port;
120
+
121
+ const response = await fetch(`http://127.0.0.1:${proxyPort}/api/global/event`, {
122
+ headers: { Accept: 'text/event-stream' },
123
+ signal: AbortSignal.timeout(2000),
124
+ });
125
+
126
+ expect(response.status).toBe(200);
127
+ const body = await response.text();
128
+ expect(body).toContain(':heartbeat\n\n');
129
+ expect(body).toContain(':upstream-alive\n\n');
130
+ expect(body).toContain('data: still-alive\n\n');
131
+ expect(stallTimeoutReads).toBeGreaterThanOrEqual(3);
132
+ });
133
+
85
134
  it('holds a request through OpenCode warmup and succeeds once ready (no 503/backoff)', async () => {
86
135
  const upstream = express();
87
136
  upstream.get('/config/providers', (_req, res) => {