@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,113 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import express from 'express';
3
+ import request from 'supertest';
4
+ import { registerOpenCodeRoutes } from './routes.js';
5
+
6
+ const originalFetch = globalThis.fetch;
7
+
8
+ afterEach(() => {
9
+ globalThis.fetch = originalFetch;
10
+ });
11
+
12
+ const createApp = (overrides = {}) => {
13
+ const app = express();
14
+ app.use(express.json());
15
+ const dependencies = {
16
+ getOpenCodeUpgradeCapability: () => ({
17
+ supported: false,
18
+ manager: 'openchamber',
19
+ reason: 'bundled',
20
+ }),
21
+ buildOpenCodeUrl: (pathname) => `http://127.0.0.1:4096${pathname}`,
22
+ getOpenCodeAuthHeaders: () => ({}),
23
+ refreshOpenCodeAfterConfigChange: vi.fn(async () => {}),
24
+ ...overrides,
25
+ };
26
+ registerOpenCodeRoutes(app, dependencies);
27
+ return { app, dependencies };
28
+ };
29
+
30
+ describe('OpenCode upgrade routes', () => {
31
+ it('fails closed without contacting the bundled OpenCode updater', async () => {
32
+ globalThis.fetch = vi.fn();
33
+ const { app } = createApp();
34
+
35
+ await request(app)
36
+ .post('/api/opencode/upgrade')
37
+ .send({})
38
+ .expect(409, {
39
+ success: false,
40
+ code: 'OPENCODE_UPGRADE_MANAGED_BY_OPENCHAMBER',
41
+ error: 'OpenCode is bundled with OpenChamber Desktop and updates with the app.',
42
+ });
43
+
44
+ expect(globalThis.fetch).not.toHaveBeenCalled();
45
+ });
46
+
47
+ it('reports bundled update ownership through the capability contract', async () => {
48
+ globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({ healthy: true, version: '1.18.8' }), {
49
+ status: 200,
50
+ headers: { 'Content-Type': 'application/json' },
51
+ }));
52
+ const { app } = createApp();
53
+
54
+ const response = await request(app)
55
+ .get('/api/opencode/upgrade-status')
56
+ .expect(200);
57
+
58
+ expect(response.body).toEqual({
59
+ available: false,
60
+ currentVersion: '1.18.8',
61
+ latestVersion: null,
62
+ upgrade: {
63
+ supported: false,
64
+ manager: 'openchamber',
65
+ reason: 'bundled',
66
+ },
67
+ });
68
+ });
69
+
70
+ it('serializes supported upgrades and preserves the in-flight lock', async () => {
71
+ let releaseUpgrade;
72
+ const upstreamResponse = new Promise((resolve) => {
73
+ releaseUpgrade = () => resolve(new Response(JSON.stringify({ success: true, version: '1.18.9' }), {
74
+ status: 200,
75
+ headers: { 'Content-Type': 'application/json' },
76
+ }));
77
+ });
78
+ globalThis.fetch = vi.fn(() => upstreamResponse);
79
+ const { app, dependencies } = createApp({
80
+ getOpenCodeUpgradeCapability: () => ({
81
+ supported: true,
82
+ manager: 'opencode',
83
+ reason: null,
84
+ }),
85
+ });
86
+
87
+ const first = request(app)
88
+ .post('/api/opencode/upgrade')
89
+ .send({})
90
+ .expect(200, {
91
+ success: true,
92
+ version: '1.18.9',
93
+ restarted: true,
94
+ })
95
+ .then((response) => response);
96
+ await vi.waitFor(() => {
97
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
98
+ });
99
+
100
+ await request(app)
101
+ .post('/api/opencode/upgrade')
102
+ .send({})
103
+ .expect(409, {
104
+ success: false,
105
+ code: 'OPENCODE_UPGRADE_IN_PROGRESS',
106
+ error: 'An OpenCode upgrade is already in progress.',
107
+ });
108
+
109
+ releaseUpgrade();
110
+ await first;
111
+ expect(dependencies.refreshOpenCodeAfterConfigChange).toHaveBeenCalledTimes(1);
112
+ });
113
+ });
@@ -8,6 +8,7 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
8
8
  crypto,
9
9
  clientReloadDelayMs,
10
10
  getOpenCodeResolutionSnapshot,
11
+ getOpenCodeUpgradeCapability,
11
12
  formatSettingsResponse,
12
13
  readSettingsFromDisk,
13
14
  readSettingsFromDiskMigrated,
@@ -41,12 +42,6 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
41
42
  return trimmed || null;
42
43
  };
43
44
 
44
- const isBundledOpenCodeBinaryActive = async () => {
45
- const settings = await readSettingsFromDiskMigrated();
46
- const resolution = await getOpenCodeResolutionSnapshot(settings);
47
- return resolution?.source === 'bundled' || resolution?.detectedSourceNow === 'bundled';
48
- };
49
-
50
45
  const readOpenCodeCurrentVersion = async () => {
51
46
  const healthResponse = await fetch(buildOpenCodeUrl('/global/health', ''), {
52
47
  method: 'GET',
@@ -153,48 +148,84 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
153
148
  }
154
149
  });
155
150
 
151
+ let openCodeUpgradePromise = null;
152
+
156
153
  app.post('/api/opencode/upgrade', async (req, res) => {
157
154
  try {
158
- if (await isBundledOpenCodeBinaryActive()) {
155
+ const capability = getOpenCodeUpgradeCapability();
156
+ if (!capability.supported) {
159
157
  return res.status(409).json({
160
158
  success: false,
161
- error: 'OpenCode is bundled with OpenChamber Desktop and cannot be upgraded separately.',
159
+ code: capability.reason === 'bundled'
160
+ ? 'OPENCODE_UPGRADE_MANAGED_BY_OPENCHAMBER'
161
+ : 'OPENCODE_UPGRADE_UNSUPPORTED',
162
+ error: capability.reason === 'bundled'
163
+ ? 'OpenCode is bundled with OpenChamber Desktop and updates with the app.'
164
+ : 'This OpenCode runtime cannot be upgraded by OpenChamber.',
165
+ });
166
+ }
167
+ if (openCodeUpgradePromise) {
168
+ return res.status(409).json({
169
+ success: false,
170
+ code: 'OPENCODE_UPGRADE_IN_PROGRESS',
171
+ error: 'An OpenCode upgrade is already in progress.',
162
172
  });
163
173
  }
164
174
 
165
175
  const target = typeof req.body?.target === 'string' && req.body.target.trim().length > 0
166
176
  ? req.body.target.trim()
167
177
  : undefined;
168
- const response = await fetch(buildOpenCodeUrl('/global/upgrade', ''), {
169
- method: 'POST',
170
- headers: {
171
- 'Content-Type': 'application/json',
172
- Accept: 'application/json',
173
- ...getOpenCodeAuthHeaders(),
174
- },
175
- body: JSON.stringify(target ? { target } : {}),
176
- });
177
- const payload = await response.json().catch(() => null);
178
- if (!response.ok) {
179
- return res.status(response.status).json({
180
- success: false,
181
- error: payload?.error || response.statusText || 'Failed to upgrade OpenCode',
178
+ const upgradeOperation = (async () => {
179
+ const response = await fetch(buildOpenCodeUrl('/global/upgrade', ''), {
180
+ method: 'POST',
181
+ headers: {
182
+ 'Content-Type': 'application/json',
183
+ Accept: 'application/json',
184
+ ...getOpenCodeAuthHeaders(),
185
+ },
186
+ body: JSON.stringify(target ? { target } : {}),
182
187
  });
183
- }
188
+ const payload = await response.json().catch(() => null);
189
+ if (!response.ok) {
190
+ return {
191
+ status: response.status,
192
+ body: {
193
+ success: false,
194
+ error: payload?.error || response.statusText || 'Failed to upgrade OpenCode',
195
+ },
196
+ };
197
+ }
198
+
199
+ try {
200
+ await refreshOpenCodeAfterConfigChange('OpenCode upgrade');
201
+ } catch (restartError) {
202
+ return {
203
+ status: 500,
204
+ body: {
205
+ success: false,
206
+ upgraded: true,
207
+ error: restartError instanceof Error
208
+ ? `OpenCode upgraded, but restart failed: ${restartError.message}`
209
+ : 'OpenCode upgraded, but restart failed',
210
+ },
211
+ };
212
+ }
213
+
214
+ return {
215
+ status: 200,
216
+ body: { ...(payload ?? { success: true }), restarted: true },
217
+ };
218
+ })();
219
+ openCodeUpgradePromise = upgradeOperation;
184
220
 
185
221
  try {
186
- await refreshOpenCodeAfterConfigChange('OpenCode upgrade');
187
- } catch (restartError) {
188
- return res.status(500).json({
189
- success: false,
190
- upgraded: true,
191
- error: restartError instanceof Error
192
- ? `OpenCode upgraded, but restart failed: ${restartError.message}`
193
- : 'OpenCode upgraded, but restart failed',
194
- });
222
+ const result = await upgradeOperation;
223
+ return res.status(result.status).json(result.body);
224
+ } finally {
225
+ if (openCodeUpgradePromise === upgradeOperation) {
226
+ openCodeUpgradePromise = null;
227
+ }
195
228
  }
196
-
197
- return res.json({ ...(payload ?? { success: true }), restarted: true });
198
229
  } catch (error) {
199
230
  console.error('Failed to upgrade OpenCode:', error);
200
231
  return res.status(500).json({
@@ -206,13 +237,14 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
206
237
 
207
238
  app.get('/api/opencode/upgrade-status', async (_req, res) => {
208
239
  try {
209
- if (await isBundledOpenCodeBinaryActive()) {
240
+ const capability = getOpenCodeUpgradeCapability();
241
+ if (!capability.supported) {
210
242
  const current = await readOpenCodeCurrentVersion().catch(() => ({ ok: false, currentVersion: null }));
211
243
  return res.json({
212
244
  available: false,
213
245
  currentVersion: current.ok ? current.currentVersion : null,
214
246
  latestVersion: null,
215
- source: 'bundled',
247
+ upgrade: capability,
216
248
  });
217
249
  }
218
250
 
@@ -239,6 +271,7 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
239
271
  available,
240
272
  currentVersion,
241
273
  latestVersion,
274
+ upgrade: capability,
242
275
  });
243
276
  } catch (error) {
244
277
  return res.status(500).json({
@@ -13,6 +13,7 @@ export const createServerUtilsRuntime = (dependencies) => {
13
13
  getOpenCodeAuthHeaders,
14
14
  buildOpenCodeUrl,
15
15
  ensureOpenCodeApiPrefix,
16
+ getUpstreamStallTimeoutMs,
16
17
  getUiNotificationClients,
17
18
  getOpenCodePort,
18
19
  setOpenCodePortState,
@@ -212,6 +213,7 @@ export const createServerUtilsRuntime = (dependencies) => {
212
213
  getOpenCodeAuthHeaders,
213
214
  buildOpenCodeUrl,
214
215
  ensureOpenCodeApiPrefix,
216
+ getSseUpstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
215
217
  getUiNotificationClients,
216
218
  });
217
219
  };
@@ -494,6 +494,9 @@ export const createSettingsHelpers = (dependencies) => {
494
494
  if (typeof candidate.agentControlToolEnabled === 'boolean') {
495
495
  result.agentControlToolEnabled = candidate.agentControlToolEnabled;
496
496
  }
497
+ if (typeof candidate.optimizeSystemPrompt === 'boolean') {
498
+ result.optimizeSystemPrompt = candidate.optimizeSystemPrompt;
499
+ }
497
500
  if (typeof candidate.openCodeUpdateToastDismissedVersion === 'string') {
498
501
  const version = candidate.openCodeUpdateToastDismissedVersion.trim();
499
502
  result.openCodeUpdateToastDismissedVersion = version.slice(0, VERSION_STRING_MAX_LENGTH);
@@ -409,6 +409,14 @@ describe('settings helpers', () => {
409
409
  expect(helpers.sanitizeSettingsUpdate({ recentEfforts: { 'anthropic/claude-opus-4': [123, ''] } })).toEqual({});
410
410
  });
411
411
 
412
+ it('persists only boolean system prompt optimization values', () => {
413
+ const helpers = createTestHelpersWithRealSanitizers();
414
+
415
+ expect(helpers.sanitizeSettingsUpdate({ optimizeSystemPrompt: true })).toEqual({ optimizeSystemPrompt: true });
416
+ expect(helpers.sanitizeSettingsUpdate({ optimizeSystemPrompt: false })).toEqual({ optimizeSystemPrompt: false });
417
+ expect(helpers.sanitizeSettingsUpdate({ optimizeSystemPrompt: 'true' })).toEqual({});
418
+ });
419
+
412
420
  it('survives a full settings.json payload containing all four previously-dropped fields (regression)', () => {
413
421
  const helpers = createTestHelpersWithRealSanitizers();
414
422
  const payload = {
@@ -0,0 +1,36 @@
1
+ export const resolveOpenCodeUpgradeCapability = ({
2
+ isExternal,
3
+ hasManagedProcess,
4
+ activeBinary,
5
+ isBundledBinary,
6
+ }) => {
7
+ if (isExternal) {
8
+ return {
9
+ supported: false,
10
+ manager: 'external',
11
+ reason: 'external',
12
+ };
13
+ }
14
+
15
+ if (!hasManagedProcess || !activeBinary) {
16
+ return {
17
+ supported: false,
18
+ manager: null,
19
+ reason: 'unavailable',
20
+ };
21
+ }
22
+
23
+ if (isBundledBinary(activeBinary)) {
24
+ return {
25
+ supported: false,
26
+ manager: 'openchamber',
27
+ reason: 'bundled',
28
+ };
29
+ }
30
+
31
+ return {
32
+ supported: true,
33
+ manager: 'opencode',
34
+ reason: null,
35
+ };
36
+ };
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { resolveOpenCodeUpgradeCapability } from './upgrade-capability.js';
3
+
4
+ describe('OpenCode upgrade capability', () => {
5
+ it('assigns bundled binaries to the OpenChamber updater', () => {
6
+ const isBundledBinary = vi.fn(() => true);
7
+
8
+ expect(resolveOpenCodeUpgradeCapability({
9
+ isExternal: false,
10
+ hasManagedProcess: true,
11
+ activeBinary: '/Applications/OpenChamber.app/Contents/Resources/opencode-cli/opencode',
12
+ isBundledBinary,
13
+ })).toEqual({
14
+ supported: false,
15
+ manager: 'openchamber',
16
+ reason: 'bundled',
17
+ });
18
+ });
19
+
20
+ it('never upgrades external or unresolved runtimes', () => {
21
+ const isBundledBinary = vi.fn(() => false);
22
+
23
+ expect(resolveOpenCodeUpgradeCapability({
24
+ isExternal: true,
25
+ hasManagedProcess: false,
26
+ activeBinary: null,
27
+ isBundledBinary,
28
+ })).toEqual({
29
+ supported: false,
30
+ manager: 'external',
31
+ reason: 'external',
32
+ });
33
+ expect(resolveOpenCodeUpgradeCapability({
34
+ isExternal: false,
35
+ hasManagedProcess: false,
36
+ activeBinary: '/usr/local/bin/opencode',
37
+ isBundledBinary,
38
+ })).toEqual({
39
+ supported: false,
40
+ manager: null,
41
+ reason: 'unavailable',
42
+ });
43
+ });
44
+
45
+ it('allows OpenCode to upgrade a managed non-bundled binary', () => {
46
+ expect(resolveOpenCodeUpgradeCapability({
47
+ isExternal: false,
48
+ hasManagedProcess: true,
49
+ activeBinary: '/Users/alice/.opencode/bin/opencode',
50
+ isBundledBinary: () => false,
51
+ })).toEqual({
52
+ supported: true,
53
+ manager: 'opencode',
54
+ reason: null,
55
+ });
56
+ });
57
+ });
@@ -97,6 +97,24 @@ export const fetchQuota = async () => {
97
97
  });
98
98
  }
99
99
 
100
+ // Business/enterprise accounts expose a dollar spend cap under
101
+ // `spend_control.individual_limit`. Surface it as an additive `credits`
102
+ // window so existing consumers keep working.
103
+ if (payload?.spend_control?.individual_limit) {
104
+ const spendLimit = payload.spend_control.individual_limit;
105
+ const used = toNumber(spendLimit.used);
106
+ const limit = toNumber(spendLimit.limit);
107
+ const valueLabel = used !== null && limit !== null
108
+ ? `${used.toFixed(0)} / ${limit.toFixed(0)} used`
109
+ : null;
110
+ windows.credits = toUsageWindow({
111
+ usedPercent: toNumber(spendLimit.used_percent),
112
+ windowSeconds: null,
113
+ resetAt: null,
114
+ valueLabel
115
+ });
116
+ }
117
+
100
118
  return buildResult({
101
119
  providerId,
102
120
  providerName,
@@ -45,4 +45,32 @@ describe('Codex quota windows', () => {
45
45
  expect(result.usage.windows['5h'].usedPercent).toBe(10);
46
46
  expect(result.usage.windows.weekly.usedPercent).toBe(20);
47
47
  });
48
+
49
+ it('surfaces spend_control individual limit for business accounts', async () => {
50
+ const fetchMock = vi.fn().mockResolvedValue({
51
+ ok: true,
52
+ json: async () => ({
53
+ plan_type: 'business',
54
+ rate_limit: null,
55
+ credits: { has_credits: true, unlimited: false, balance: null },
56
+ spend_control: {
57
+ individual_limit: {
58
+ limit: '7500',
59
+ used: '2674.8724080324173',
60
+ remaining: '4825.127591967583',
61
+ used_percent: 36,
62
+ remaining_percent: 64
63
+ }
64
+ }
65
+ })
66
+ });
67
+ vi.stubGlobal('fetch', fetchMock);
68
+
69
+ const result = await fetchQuota();
70
+
71
+ expect(result.ok).toBe(true);
72
+ expect(result.usage.windows.credits.usedPercent).toBe(36);
73
+ expect(result.usage.windows.credits.valueLabel).toBe('2675 / 7500 used');
74
+ expect(fetchMock).toHaveBeenCalled();
75
+ });
48
76
  });
@@ -94,6 +94,32 @@ export const parseScheduledCommandPrompt = (prompt) => {
94
94
  };
95
95
  };
96
96
 
97
+ export const expandCommandGoalObjective = (template, argumentsText) => {
98
+ if (typeof template !== 'string' || !template.trim()) {
99
+ return null;
100
+ }
101
+
102
+ const rawArguments = String(argumentsText ?? '');
103
+ if (template.includes('$ARGUMENTS')) {
104
+ return template.replaceAll('$ARGUMENTS', rawArguments);
105
+ }
106
+
107
+ const positions = [...template.matchAll(/\$(\d+)/g)].map((match) => Number(match[1]));
108
+ if (positions.length > 0) {
109
+ const parsedArguments = [...rawArguments.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)]
110
+ .map((match) => match[1] ?? match[2] ?? match[3] ?? '');
111
+ const lastPosition = Math.max(...positions);
112
+ return template.replace(/\$(\d+)/g, (_match, value) => {
113
+ const position = Number(value);
114
+ return position === lastPosition
115
+ ? parsedArguments.slice(position - 1).join(' ')
116
+ : (parsedArguments[position - 1] ?? '');
117
+ });
118
+ }
119
+
120
+ return rawArguments ? `${template}\n\n${rawArguments}` : template;
121
+ };
122
+
97
123
  export const computeNextRunAt = (task, nowMs = Date.now()) => {
98
124
  if (!task?.enabled) {
99
125
  return null;
@@ -445,10 +471,10 @@ export const createScheduledTasksRuntime = (deps) => {
445
471
  }
446
472
  };
447
473
 
448
- const runScheduledCommandIfApplicable = async ({ client, projectPath, sessionID, task }) => {
474
+ const resolveScheduledCommand = async ({ client, projectPath, task }) => {
449
475
  const parsed = parseScheduledCommandPrompt(task?.execution?.prompt);
450
476
  if (!parsed) {
451
- return false;
477
+ return null;
452
478
  }
453
479
 
454
480
  let commands = [];
@@ -456,25 +482,24 @@ export const createScheduledTasksRuntime = (deps) => {
456
482
  const response = await client.command.list({ directory: projectPath });
457
483
  commands = Array.isArray(response?.data) ? response.data : [];
458
484
  } catch {
459
- return false;
485
+ return null;
460
486
  }
461
487
 
462
- const hasMatchingCommand = commands.some((command) => command?.name === parsed.command);
463
- if (!hasMatchingCommand) {
464
- return false;
465
- }
488
+ const command = commands.find((candidate) => candidate?.name === parsed.command);
489
+ return command ? { ...parsed, template: command.template } : null;
490
+ };
466
491
 
492
+ const runScheduledCommand = async ({ client, projectPath, sessionID, task, command }) => {
467
493
  await client.session.command({
468
494
  sessionID,
469
495
  directory: projectPath,
470
- command: parsed.command,
471
- arguments: parsed.arguments,
496
+ command: command.command,
497
+ arguments: command.arguments,
472
498
  ...(task.execution.agent ? { agent: task.execution.agent } : {}),
473
499
  model: `${task.execution.providerID}/${task.execution.modelID}`,
474
500
  ...(task.execution.variant ? { variant: task.execution.variant } : {}),
475
501
  });
476
502
 
477
- return true;
478
503
  };
479
504
 
480
505
  const runTaskWithWatchdog = async (projectID, task, reason) => {
@@ -527,13 +552,18 @@ export const createScheduledTasksRuntime = (deps) => {
527
552
  }
528
553
  }
529
554
 
555
+ const scheduledCommand = await resolveScheduledCommand({ client, projectPath, task });
556
+
530
557
  if (task.execution.goalEnabled) {
558
+ const commandObjective = scheduledCommand
559
+ ? expandCommandGoalObjective(scheduledCommand.template, scheduledCommand.arguments)
560
+ : null;
531
561
  await createSessionGoal({
532
562
  baseUrl,
533
563
  authHeaders,
534
564
  sessionID,
535
565
  directory: projectPath,
536
- objective: expandSnippets(task.execution.prompt, projectPath),
566
+ objective: commandObjective ?? expandSnippets(task.execution.prompt, projectPath),
537
567
  tokenBudget: task.execution.goalTokenBudget,
538
568
  providerID: task.execution.providerID,
539
569
  modelID: task.execution.modelID,
@@ -541,13 +571,9 @@ export const createScheduledTasksRuntime = (deps) => {
541
571
  });
542
572
  }
543
573
 
544
- const executedAsCommand = await runScheduledCommandIfApplicable({
545
- client,
546
- projectPath,
547
- sessionID,
548
- task,
549
- });
550
- if (!executedAsCommand) {
574
+ if (scheduledCommand) {
575
+ await runScheduledCommand({ client, projectPath, sessionID, task, command: scheduledCommand });
576
+ } else {
551
577
  await runPromptAsync({
552
578
  baseUrl,
553
579
  authHeaders,
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { computeNextRunAt, formatScheduledSessionTitle, parseScheduledCommandPrompt } from './runtime.js';
2
+ import { computeNextRunAt, expandCommandGoalObjective, formatScheduledSessionTitle, parseScheduledCommandPrompt } from './runtime.js';
3
3
 
4
4
  describe('scheduled-tasks runtime helpers', () => {
5
5
  it('computes next daily run in timezone', () => {
@@ -97,4 +97,15 @@ describe('scheduled-tasks runtime helpers', () => {
97
97
  expect(parseScheduledCommandPrompt('Summarize open issues')).toBeNull();
98
98
  expect(parseScheduledCommandPrompt('/')).toBeNull();
99
99
  });
100
+
101
+ it('expands command arguments into the goal objective', () => {
102
+ expect(expandCommandGoalObjective(
103
+ 'Run the issue pipeline for $ARGUMENTS. Verify $ARGUMENTS is represented by the PR.',
104
+ 'LIN-123 --draft',
105
+ )).toBe('Run the issue pipeline for LIN-123 --draft. Verify LIN-123 --draft is represented by the PR.');
106
+ expect(expandCommandGoalObjective(undefined, 'LIN-123')).toBeNull();
107
+ expect(expandCommandGoalObjective('Move $1 to $2', '"src old" dist extra')).toBe('Move src old to dist extra');
108
+ expect(expandCommandGoalObjective('Review the requested scope.', 'auth module'))
109
+ .toBe('Review the requested scope.\n\nauth module');
110
+ });
100
111
  });
@@ -160,6 +160,12 @@ sees only that final turn, so the report is its evidence.
160
160
  colors/labels shared across surfaces.
161
161
  - `stores/useSessionGoalArmStore.ts` — the "next prompt starts a goal" flag,
162
162
  consumed by `sendMessage` in `sync/session-ui-store.ts` (works for drafts).
163
+ Armed slash commands resolve their authoritative command template and apply
164
+ OpenCode argument expansion (`$ARGUMENTS`, positional placeholders, or the
165
+ implicit argument suffix) for the audit objective before goal metadata is
166
+ written and before `session.command` dispatch. If command details cannot be
167
+ loaded, the raw invocation remains the objective rather than blocking command
168
+ execution.
163
169
  - `hooks/useSessionGoal.ts` — live goal state.
164
170
  - `components/chat/SessionGoalButton.tsx` — composer target button
165
171
  (arm / status color / cancel confirm); `SessionGoalRow.tsx` — goal strip
@@ -172,7 +178,8 @@ sees only that final turn, so the report is its evidence.
172
178
  Scheduled tasks can run as goals: `execution.goalEnabled` (+ optional
173
179
  `execution.goalTokenBudget`) on a task makes the scheduled-tasks runtime
174
180
  stamp `metadata.openchamber.goal` onto the fresh session (objective = the
175
- expanded task prompt) and attach the goal-mode intro part to the prompt.
181
+ expanded task prompt, or the argument-expanded command template for a slash
182
+ command) and attach the goal-mode intro part to normal prompts.
176
183
  The loop here picks it up from session events like any other goal.
177
184
 
178
185
  ## CLI-created goals
@@ -183,8 +190,10 @@ session, fits and stores the expanded prompt as its objective, patches active
183
190
  goal metadata, appends the synthetic goal reminder, and only then dispatches
184
191
  the prompt. `--goal-token-budget` applies the same optional budget contract as
185
192
  scheduled goals. Slash commands retain command dispatch semantics and cannot
186
- carry the synthetic prompt part; the goal metadata is still installed before
187
- the command runs.
193
+ carry the synthetic prompt part. Their command template with OpenCode argument
194
+ expansion becomes the audit objective; goal metadata
195
+ is still installed before the command runs. A missing command template falls
196
+ back to the raw invocation.
188
197
 
189
198
  `openchamber session send --goal` and `openchamber session fork --goal` use
190
199
  the same server-owned prompt orchestration. Send installs a fresh goal on the