@vantran-se/openchamber-web 1.22.1 → 1.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/bin/cli.js +11 -1
- package/bin/cli.test.js +92 -0
- package/bin/lib/cli-startup.js +49 -0
- package/bin/lib/commands-startup.js +41 -6
- package/dist/assets/{CodeMirrorCommentWidgets-C53Q7pbX.js → CodeMirrorCommentWidgets-DFg2wnpo.js} +1 -1
- package/dist/assets/DiffView-3Dn4QHbu.js +4 -0
- package/dist/assets/DirtyBranchSwitchDialog-CwOerqVi.js +1 -0
- package/dist/assets/FilesView-BdTOpew9.js +17 -0
- package/dist/assets/GitView-Dqf9vHJh.js +6 -0
- package/dist/assets/{JsonTreeView-Bl0lp9Rs.js → JsonTreeView-BKdsjg5B.js} +1 -1
- package/dist/assets/LinearIssuesView-CmbeL7I6.js +1 -0
- package/dist/assets/MarkdownImageGallery-_5gEVr0X.js +1 -0
- package/dist/assets/MarkdownRendererImpl-wVZlx4dd.js +12 -0
- package/dist/assets/OnboardingScreen-DdP4_nuc.js +1 -0
- package/dist/assets/{PatchDiff-D6NXAfJk.js → PatchDiff-am3SAss2.js} +1 -1
- package/dist/assets/PierreDiffViewer-DCsydlKs.js +161 -0
- package/dist/assets/PlanView-BoJxdRZe.js +5 -0
- package/dist/assets/SettingsView-CcM8pF5O.js +28 -0
- package/dist/assets/{SettingsWindow-BiWDBRvb.js → SettingsWindow-DVTdDSol.js} +1 -1
- package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
- package/dist/assets/{ToolOutputDialog-BQexMQIm.js → ToolOutputDialog-BgfTbDZ4.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-C7WLk5i9.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-Dpz2ra8h.js → VirtualizedFileDiff-DcdgkH-x.js} +1 -1
- package/dist/assets/WalkthroughView-BEVUDxuw.js +4 -0
- package/dist/assets/{computeVirtualFileMetrics-DtyozJdt.js → computeVirtualFileMetrics-C8byMnRh.js} +2 -2
- package/dist/assets/contextPanelEmbeddedChat-CirXEPJq.js +1 -0
- package/dist/assets/de-C8jV7J9y.js +10 -0
- package/dist/assets/es-BI6J1M5R.js +16 -0
- package/dist/assets/fr-D6oDFt7E.js +14 -0
- package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
- package/dist/assets/{index-DmhujXbT.js → index-BB7ryz8y.js} +1 -1
- package/dist/assets/index-BqhiCmYS.js +39 -0
- package/dist/assets/index-FqSOBz0J.css +1 -0
- package/dist/assets/{isDiffPlainText-XyulMHxx.js → isDiffPlainText-45ujMPGb.js} +1 -1
- package/dist/assets/{isFilePlainText-B19Ddps1.js → isFilePlainText-Cc4KFSYi.js} +1 -1
- package/dist/assets/ja-C_4i5EQu.js +16 -0
- package/dist/assets/ko-BFbOTpbq.js +16 -0
- package/dist/assets/{main-B2a_JfKZ.js → main-C9ETLKFc.js} +2 -2
- package/dist/assets/main-CJmb2dF8.js +930 -0
- package/dist/assets/markdownCore-DVuZpnli.js +5 -0
- package/dist/assets/{miniChat-B3CSU_Ps.js → miniChat-B4Ytoq2n.js} +2 -2
- package/dist/assets/{mobile-QNcFIVCW.js → mobile-BUT6-lo1.js} +2 -2
- package/dist/assets/patchFileDiff-8j1apICU.js +13 -0
- package/dist/assets/pl-COFvT56l.js +16 -0
- package/dist/assets/pt-BR-DtVOO2Lj.js +16 -0
- package/dist/assets/renderElectronMiniChatApp-B6vUG-vF.js +2 -0
- package/dist/assets/renderMobileApp-BNgHraq6.js +25 -0
- package/dist/assets/runtimeEndpointReset-B8LYpWvr.js +17 -0
- package/dist/assets/scheduledTasksApi-GC4epIYA.js +1 -0
- package/dist/assets/{shikiHighlight-DE-OwqGw.js → shikiHighlight-BJISeZsQ.js} +1 -1
- package/dist/assets/surface-BvRzS58U.js +1 -0
- package/dist/assets/tr-B8Q0Go2l.js +7 -0
- package/dist/assets/uk-Dk4a-Fn-.js +16 -0
- package/dist/assets/{useAppFontEffects-COAeIX-D.js → useAppFontEffects-DpFNefUA.js} +153 -179
- package/dist/assets/useGitComparison-Dfxaqd0s.js +1 -0
- package/dist/assets/useInlineCommentController-CscsE4t-.js +2 -0
- package/dist/assets/useRootScrollLock-BaCvuRlT.js +1 -0
- package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-DdV8vhHn.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-BG3v1Ghq.js → vendor-codemirror-language-data-DzlSIu_W.js} +2 -2
- package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
- package/dist/assets/vendor-zod-BPAANqvH.js +39 -0
- package/dist/assets/{web-components-BNMwa0qm.js → web-components-CdGfR2XJ.js} +1 -1
- package/dist/assets/zh-CN-B_BXxG1Q.js +16 -0
- package/dist/assets/zh-TW-DLrl1SPZ.js +16 -0
- package/dist/index.html +5 -43
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +8 -5
- package/server/index.d.ts +15 -0
- package/server/index.js +82 -13
- package/server/lib/agent-tool/runtime.js +2 -19
- package/server/lib/changelog/update-notes.js +82 -0
- package/server/lib/changelog/update-notes.test.js +59 -0
- package/server/lib/data-dir-migration.js +40 -0
- package/server/lib/data-dir-migration.test.js +59 -0
- package/server/lib/dev-tunnel/DOCUMENTATION.md +13 -4
- package/server/lib/dev-tunnel/runtime.js +4 -4
- package/server/lib/dev-tunnel/tunnel.test.js +20 -0
- package/server/lib/event-stream/runtime.test.js +12 -12
- package/server/lib/fs/DOCUMENTATION.md +5 -0
- package/server/lib/fs/routes.js +63 -21
- package/server/lib/fs/routes.test.js +187 -1
- package/server/lib/git/DOCUMENTATION.md +32 -6
- package/server/lib/git/routes.js +40 -4
- package/server/lib/git/service.js +291 -215
- package/server/lib/git/service.test.js +593 -25
- package/server/lib/inherited-env.js +16 -9
- package/server/lib/inherited-env.test.js +8 -9
- package/server/lib/mcp-reconnect/DOCUMENTATION.md +55 -0
- package/server/lib/mcp-reconnect/runtime.js +122 -0
- package/server/lib/mcp-reconnect/runtime.test.js +140 -0
- package/server/lib/message-queue/DOCUMENTATION.md +161 -0
- package/server/lib/message-queue/runtime.js +870 -0
- package/server/lib/message-queue/runtime.test.js +482 -0
- package/server/lib/network-defaults.js +23 -0
- package/server/lib/network-defaults.test.js +52 -0
- package/server/lib/openchamber-sessions/routes.js +102 -0
- package/server/lib/openchamber-sessions/routes.test.js +88 -0
- package/server/lib/opencode/DOCUMENTATION.md +30 -6
- package/server/lib/opencode/bootstrap-runtime.js +2 -0
- package/server/lib/opencode/config-paths.test.js +116 -0
- package/server/lib/opencode/core-routes.js +1 -0
- package/server/lib/opencode/feature-routes-runtime.js +7 -0
- package/server/lib/opencode/input-history-scope.js +14 -0
- package/server/lib/opencode/managed-plugin-config.js +35 -0
- package/server/lib/opencode/openchamber-routes.js +64 -4
- package/server/lib/opencode/openchamber-routes.test.js +130 -3
- package/server/lib/opencode/plugins.js +2 -2
- package/server/lib/opencode/providers.js +44 -2
- package/server/lib/opencode/providers.test.js +131 -4
- package/server/lib/opencode/routes.js +9 -7
- package/server/lib/opencode/server-startup-runtime.js +1 -1
- package/server/lib/opencode/settings-files.js +214 -0
- package/server/lib/opencode/settings-helpers.js +113 -41
- package/server/lib/opencode/settings-helpers.test.js +342 -0
- package/server/lib/opencode/settings-registry.json +747 -0
- package/server/lib/opencode/settings-runtime.js +141 -20
- package/server/lib/opencode/settings-runtime.test.js +191 -4
- package/server/lib/opencode/shared.js +4 -1
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/skill-routes.js +2 -1
- package/server/lib/opencode/snippets.js +1 -2
- package/server/lib/package-manager.js +4 -29
- package/server/lib/package-manager.test.js +2 -2
- package/server/lib/project-context/DOCUMENTATION.md +25 -1
- package/server/lib/project-context/routes.http.test.js +18 -0
- package/server/lib/project-context/routes.js +15 -0
- package/server/lib/project-context/runtime.js +248 -23
- package/server/lib/project-context/runtime.test.js +106 -3
- package/server/lib/projects/DOCUMENTATION.md +76 -0
- package/server/lib/projects/project-config.js +142 -9
- package/server/lib/projects/project-id.js +17 -0
- package/server/lib/projects/project-setup.js +409 -0
- package/server/lib/projects/project-setup.test.js +557 -0
- package/server/lib/projects/routes.js +59 -0
- package/server/lib/quota/DOCUMENTATION.md +40 -2
- package/server/lib/quota/credentials/providers.js +4 -0
- package/server/lib/quota/credentials/store.js +1 -1
- package/server/lib/quota/credentials/store.test.js +4 -4
- package/server/lib/quota/index.js +1 -0
- package/server/lib/quota/providers/cline-pass.js +125 -0
- package/server/lib/quota/providers/cline-pass.test.js +103 -0
- package/server/lib/quota/providers/exe-dev.js +75 -0
- package/server/lib/quota/providers/exe-dev.test.js +47 -0
- package/server/lib/quota/providers/hyper.js +118 -0
- package/server/lib/quota/providers/hyper.test.js +126 -0
- package/server/lib/quota/providers/index.js +22 -0
- package/server/lib/quota/providers/neuralwatt.js +3 -6
- package/server/lib/quota/providers/neuralwatt.test.js +7 -7
- package/server/lib/quota/providers/ollama-cloud.js +31 -0
- package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
- package/server/lib/quota/providers/opencode-go.js +2 -1
- package/server/lib/quota/providers/opencode-go.test.js +31 -2
- package/server/lib/quota/providers/openrouter.js +119 -24
- package/server/lib/quota/providers/openrouter.test.js +330 -0
- package/server/lib/quota/routes.js +2 -0
- package/server/lib/quota/utils/auth.js +1 -1
- package/server/lib/relay/DOCUMENTATION.md +56 -1
- package/server/lib/relay/cross-compat.test.js +26 -0
- package/server/lib/relay/downstream-scheduler.js +154 -0
- package/server/lib/relay/downstream-scheduler.test.js +162 -0
- package/server/lib/relay/e2ee.js +10 -8
- package/server/lib/relay/flow-control.test.js +177 -0
- package/server/lib/relay/host-client.js +37 -8
- package/server/lib/relay/host-client.test.js +9 -1
- package/server/lib/relay/tunnel-codec.js +9 -0
- package/server/lib/relay/tunnel-host.js +69 -18
- package/server/lib/relay/tunnel-host.test.js +9 -1
- package/server/lib/security/request-security.js +21 -6
- package/server/lib/security/request-security.test.js +42 -8
- package/server/lib/session-assist/runtime.js +7 -10
- package/server/lib/session-goal/DOCUMENTATION.md +20 -7
- package/server/lib/session-goal/create.js +3 -1
- package/server/lib/session-goal/runtime.js +81 -20
- package/server/lib/session-goal/runtime.test.js +426 -0
- package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
- package/server/lib/skills-catalog/install.js +3 -2
- package/server/lib/small-model/DOCUMENTATION.md +7 -2
- package/server/lib/small-model/call.js +17 -6
- package/server/lib/small-model/call.test.js +52 -0
- package/server/lib/small-model/index.js +7 -11
- package/server/lib/small-model/routes.js +2 -1
- package/server/lib/small-model/runtime-providers.js +15 -7
- package/server/lib/small-model/runtime-providers.test.js +7 -1
- package/server/lib/system-prompt/runtime.js +2 -21
- package/server/lib/terminal/DOCUMENTATION.md +14 -10
- package/server/lib/terminal/runtime.js +190 -31
- package/server/lib/terminal/runtime.test.js +571 -37
- package/server/lib/terminal/shells.js +17 -0
- package/server/lib/terminal/shells.test.js +32 -1
- package/server/lib/ui-auth/ui-auth.js +4 -1
- package/server/lib/ui-auth/ui-auth.test.js +16 -0
- package/server/lib/walkthrough/DOCUMENTATION.md +33 -14
- package/server/lib/walkthrough/index.js +1 -0
- package/server/lib/walkthrough/model-settings.js +8 -12
- package/server/lib/walkthrough/prompt.js +3 -1
- package/server/lib/walkthrough/routes.test.js +26 -5
- package/server/lib/walkthrough/sources.js +23 -2
- package/dist/assets/CommitSection-X-f2RgYr.js +0 -1
- package/dist/assets/DiffView-Dh1ey2x9.js +0 -4
- package/dist/assets/FilesView-3ZYP72ki.js +0 -17
- package/dist/assets/GitView-CMuN7z2Z.js +0 -6
- package/dist/assets/LinearIssuesView-CQiUDU8b.js +0 -1
- package/dist/assets/MarkdownImageGallery-bA0PS-tn.js +0 -1
- package/dist/assets/MarkdownRendererImpl-BGQi2PLq.js +0 -12
- package/dist/assets/OnboardingScreen-D3kYJIb6.js +0 -1
- package/dist/assets/PierreDiffViewer-Ct2A13NO.js +0 -157
- package/dist/assets/PlanView-6AUjzNQn.js +0 -5
- package/dist/assets/SettingsView-CHI8fFaK.js +0 -28
- package/dist/assets/ToolPartDiffPreview-DPAATNn6.js +0 -8
- package/dist/assets/WalkthroughView-AX-u2pFg.js +0 -4
- package/dist/assets/contextPanelEmbeddedChat-C9EcRSDF.js +0 -1
- package/dist/assets/de-DqVn5vme.js +0 -9
- package/dist/assets/es-hj43Z53i.js +0 -15
- package/dist/assets/fr-BmkZt2mF.js +0 -13
- package/dist/assets/index-L_ncV-6H.css +0 -1
- package/dist/assets/index-qES19dlJ.js +0 -7
- package/dist/assets/ja-DioMIEGF.js +0 -15
- package/dist/assets/ko-BqPgaQJb.js +0 -15
- package/dist/assets/main-CYgSu6dx.js +0 -928
- package/dist/assets/markdownCore-CWRCqSH2.js +0 -3
- package/dist/assets/patchFileDiff-BpMQZnYu.js +0 -10
- package/dist/assets/pl-slULBF4R.js +0 -15
- package/dist/assets/pt-BR-BqH8fuCH.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-D77bmLqo.js +0 -2
- package/dist/assets/renderMobileApp-BQ3Kdm-d.js +0 -25
- package/dist/assets/runtimeEndpointReset-CRGn1gVj.js +0 -16
- package/dist/assets/scheduledTasksApi-BSRCtP6T.js +0 -1
- package/dist/assets/tr-CjEbw1Aw.js +0 -6
- package/dist/assets/uk-BkkfxbOs.js +0 -15
- package/dist/assets/useInlineCommentController-JsBboQwt.js +0 -2
- package/dist/assets/useRootScrollLock-C0N9mCwz.js +0 -1
- package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
- package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
- package/dist/assets/vendor-zod-BLfBSgBh.js +0 -39
- package/dist/assets/zh-CN-C6FMdVgv.js +0 -15
- package/dist/assets/zh-TW-CdcMjDxv.js +0 -15
|
@@ -21,13 +21,14 @@ export function registerSmallModelRoutes(app, { getSmallModelService }) {
|
|
|
21
21
|
app.post('/api/small-model/generate', async (req, res) => {
|
|
22
22
|
try {
|
|
23
23
|
const { generateSmallModelText } = await getSmallModelService();
|
|
24
|
-
const { prompt, system, maxOutputTokens, model, directory, preferredProviderID, preferredModelID, restrictToPreferredProvider } = req.body || {};
|
|
24
|
+
const { prompt, system, maxOutputTokens, model, directory, sessionID, preferredProviderID, preferredModelID, restrictToPreferredProvider } = req.body || {};
|
|
25
25
|
const result = await generateSmallModelText({
|
|
26
26
|
prompt,
|
|
27
27
|
system,
|
|
28
28
|
maxOutputTokens,
|
|
29
29
|
model,
|
|
30
30
|
directory,
|
|
31
|
+
sessionID,
|
|
31
32
|
preferredProviderID,
|
|
32
33
|
preferredModelID,
|
|
33
34
|
restrictToPreferredProvider: restrictToPreferredProvider === true,
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
//
|
|
9
9
|
// `GET /provider` is where that state becomes visible. It reports, per
|
|
10
10
|
// provider, the resolved `options.baseURL` and `options.apiKey`, and per model
|
|
11
|
-
// the wire adapter (`api.npm`) and endpoint (`api.url`).
|
|
11
|
+
// the wire adapter (`api.npm`) and endpoint (`api.url`). The provider-level
|
|
12
|
+
// endpoint remains only as a fallback when the selected model has no endpoint.
|
|
12
13
|
//
|
|
13
14
|
// What it does NOT report is `options.fetch`. OpenCode strips functions from
|
|
14
15
|
// the response, and a plugin is free to put its whole protocol in there:
|
|
@@ -61,8 +62,8 @@ export function resetOpenCodeRuntimeProviders() {
|
|
|
61
62
|
/**
|
|
62
63
|
* The boundary. Everything the `/provider` payload claims is checked here, so
|
|
63
64
|
* the rest of this module and its callers work with settled values:
|
|
64
|
-
* a credential we may use,
|
|
65
|
-
* anonymous zen case.
|
|
65
|
+
* a credential we may use, provider and model endpoints, and whether the
|
|
66
|
+
* provider is the anonymous zen case.
|
|
66
67
|
*
|
|
67
68
|
* The credential deliberately prefers `options.apiKey` over the `key` field:
|
|
68
69
|
* for a plugin provider the former is what its auth loader produced and what
|
|
@@ -82,13 +83,22 @@ function parseProviderListing(payload) {
|
|
|
82
83
|
const id = text(record(raw).id);
|
|
83
84
|
if (!id) continue;
|
|
84
85
|
const options = record(record(raw).options);
|
|
85
|
-
const
|
|
86
|
+
const models = new Map();
|
|
87
|
+
for (const [modelID, rawModel] of Object.entries(record(record(raw).models))) {
|
|
88
|
+
const model = record(rawModel);
|
|
89
|
+
const api = record(model.api);
|
|
90
|
+
const modelURL = endpoint(api.url);
|
|
91
|
+
const modelNpm = text(api.npm);
|
|
92
|
+
models.set(modelID, { api: { url: modelURL, npm: modelNpm } });
|
|
93
|
+
}
|
|
94
|
+
const firstModel = models.values().next().value;
|
|
86
95
|
const declaredKey = text(options.apiKey);
|
|
87
96
|
providers.set(id, {
|
|
88
97
|
id,
|
|
89
98
|
source: text(record(raw).source),
|
|
90
99
|
apiKey: declaredKey === ZEN_ANONYMOUS_API_KEY ? null : (declaredKey ?? text(record(raw).key)),
|
|
91
|
-
baseURL: endpoint(options.baseURL) ??
|
|
100
|
+
baseURL: endpoint(options.baseURL) ?? firstModel?.api?.url ?? null,
|
|
101
|
+
models,
|
|
92
102
|
// True only for the zen-without-login case: a provider that is present
|
|
93
103
|
// and usable through OpenCode, but that we must not call ourselves.
|
|
94
104
|
anonymousZen: declaredKey === ZEN_ANONYMOUS_API_KEY,
|
|
@@ -152,5 +162,3 @@ export async function getRuntimeProvider(providerID) {
|
|
|
152
162
|
const current = await getRuntimeProviderSnapshot();
|
|
153
163
|
return current?.providers.get(providerID) ?? null;
|
|
154
164
|
}
|
|
155
|
-
|
|
156
|
-
|
|
@@ -14,7 +14,10 @@ const providerPayload = (overrides = {}) => ({
|
|
|
14
14
|
id: 'llmapi',
|
|
15
15
|
source: 'config',
|
|
16
16
|
options: { apiKey: 'plugin-key', baseURL: 'https://api.llmapi.ai/v1/' },
|
|
17
|
-
models: {
|
|
17
|
+
models: {
|
|
18
|
+
'claude-opus-4-8': { api: { id: 'claude-opus-4-8', url: '', npm: '@ai-sdk/anthropic' } },
|
|
19
|
+
'gpt-5.6-luna': { api: { id: 'gpt-5.6-luna', url: 'https://api.llmapi.ai/v1', npm: '@ai-sdk/openai' } },
|
|
20
|
+
},
|
|
18
21
|
},
|
|
19
22
|
{
|
|
20
23
|
id: 'opencode',
|
|
@@ -59,6 +62,9 @@ describe('OpenCode runtime provider snapshot', () => {
|
|
|
59
62
|
const provider = await getRuntimeProvider('llmapi');
|
|
60
63
|
|
|
61
64
|
expect(provider).toMatchObject({ apiKey: 'plugin-key', baseURL: 'https://api.llmapi.ai/v1' });
|
|
65
|
+
expect(provider.models.get('gpt-5.6-luna')).toEqual({
|
|
66
|
+
api: { url: 'https://api.llmapi.ai/v1', npm: '@ai-sdk/openai' },
|
|
67
|
+
});
|
|
62
68
|
expect(fetchMock.mock.calls[0][0]).toBe('http://127.0.0.1:4096/provider');
|
|
63
69
|
expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ Authorization: 'Basic test' });
|
|
64
70
|
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { parse as parseJsonc } from 'jsonc-parser';
|
|
2
1
|
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { appendManagedPlugin } from '../opencode/managed-plugin-config.js';
|
|
3
3
|
|
|
4
4
|
const PROVIDER_PROMPT_BOUNDARY = 'You are powered by the model named';
|
|
5
5
|
const MINIMAL_IDENTITY = 'You are OpenCode, a coding agent.';
|
|
@@ -33,25 +33,6 @@ export const OpenChamberSystemPromptPlugin = async () => ({
|
|
|
33
33
|
})
|
|
34
34
|
`;
|
|
35
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
36
|
export const createSystemPromptRuntime = ({ fsPromises, path, dataDir }) => {
|
|
56
37
|
const pluginDirectory = path.join(dataDir, 'system-prompt');
|
|
57
38
|
const pluginPath = path.join(pluginDirectory, 'openchamber-system-prompt-plugin.js');
|
|
@@ -60,7 +41,7 @@ export const createSystemPromptRuntime = ({ fsPromises, path, dataDir }) => {
|
|
|
60
41
|
await fsPromises.mkdir(pluginDirectory, { recursive: true });
|
|
61
42
|
await fsPromises.writeFile(pluginPath, createPluginSource(), { mode: 0o600 });
|
|
62
43
|
return {
|
|
63
|
-
OPENCODE_CONFIG_CONTENT:
|
|
44
|
+
OPENCODE_CONFIG_CONTENT: appendManagedPlugin(rawConfig, pathToFileURL(pluginPath).href, 'system prompt optimizer'),
|
|
64
45
|
};
|
|
65
46
|
};
|
|
66
47
|
|
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Ownership
|
|
4
4
|
|
|
5
|
-
`runtime.js` owns terminal identity, PTY processes,
|
|
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
|
|
|
9
9
|
`/api/terminal/ws` is the only terminal data transport. It uses v3 binary JSON control frames and is opened through `openRuntimeWebSocket`, preserving direct, Electron proxy, URL-token authentication, and private-relay routing.
|
|
10
10
|
|
|
11
11
|
- `attach` registers a connection for one terminal. One socket may attach to many terminals.
|
|
12
|
-
- Every attach and reconnect begins with an authoritative `snapshot` containing bounded history and the
|
|
12
|
+
- Every attach and reconnect begins with an authoritative `snapshot` containing bounded history, the current sequence, and the PTY `cols`/`rows` the history was drawn for. The client replays the history at that size before fitting its viewport; replaying shell output at another width leaves stray fragments that the shell's own SIGWINCH redraw never clears.
|
|
13
13
|
- A current socket that closes or errors before its initial `open` invalidates its URL-scoped auth token before retrying, so retries mint a fresh token instead of backing off against a rejected upgrade. Hidden or offline clients wait 60 seconds and wake promptly on visibility/online recovery.
|
|
14
14
|
- `output`, `exit`, and `restarted` carry monotonically increasing per-terminal sequences. Output carries raw live bytes plus replay-safe bytes with terminal query exchanges removed.
|
|
15
15
|
- Attach registers before capturing the snapshot, buffers concurrent events, drops events represented by the snapshot sequence, then enters live delivery.
|
|
@@ -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
|
-
-
|
|
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
|
-
- PTY children
|
|
31
|
-
- 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
|
|
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.
|
|
31
|
+
- PTY children never inherit `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup, and an inherited value (even empty) makes Node CLIs such as opencode print `Failed to parse IPC channel number` on exit.
|
|
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 POSIX, PTY spawn is wrapped with `env -u ARGV0 -u NODE_CHANNEL_FD` (`resolvePosixPtyLaunch`) because `bun-pty` merges the native OS environ and would otherwise reintroduce both after a JS-only delete.
|
|
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
|
|
36
|
-
-
|
|
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"`. The client shows the failure without moving the session. 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
|
|
@@ -9,15 +9,77 @@ import {
|
|
|
9
9
|
} from './terminal-ws-protocol.js';
|
|
10
10
|
import { sanitizeTerminalHistoryChunk } from './history.js';
|
|
11
11
|
import { consumeTerminalThemeQueries, terminalThemeModeReport } from './theme-response.js';
|
|
12
|
-
import {
|
|
13
|
-
import { stripAppImageArgv0Leak,
|
|
12
|
+
import { buildTerminalShellLaunch, createTerminalShellResolver, normalizeTerminalShell } from './shells.js';
|
|
13
|
+
import { stripAppImageArgv0Leak, resolvePosixPtyLaunch } from '../inherited-env.js';
|
|
14
14
|
|
|
15
15
|
const MAX_SESSIONS = 20;
|
|
16
16
|
const MAX_HISTORY_BYTES = 512 * 1024;
|
|
17
17
|
const MAX_INPUT_CHARS = 65_536;
|
|
18
18
|
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
|
19
19
|
const TERMINATION_GRACE_MS = 1000;
|
|
20
|
+
const INTERACTIVE_TERMINAL_MODE = 'interactive';
|
|
21
|
+
const COMMAND_TERMINAL_MODE = 'command';
|
|
22
|
+
// Error code the create/restart routes attach when the requested cwd no longer
|
|
23
|
+
// exists. Mirrored by `TERMINAL_CWD_MISSING_CODE` in packages/ui/src/lib/terminalApi.ts.
|
|
24
|
+
const TERMINAL_CWD_MISSING_CODE = 'TERMINAL_CWD_MISSING';
|
|
25
|
+
const TERMINAL_PURPOSE = Object.freeze({ type: 'terminal' });
|
|
26
|
+
const MAX_PURPOSE_ID_CHARS = 128;
|
|
27
|
+
const OBJECT_TAG = '[object Object]';
|
|
20
28
|
const validateSize = (value, max) => Number.isInteger(value) && value >= 1 && value <= max;
|
|
29
|
+
const isString = (value) => String(value) === value;
|
|
30
|
+
const isObjectRecord = (value) => value != null && !Array.isArray(value) && Object.prototype.toString.call(value) === OBJECT_TAG;
|
|
31
|
+
const normalizeCreateMode = ({ mode, command }) => {
|
|
32
|
+
const normalizedMode = mode == null ? INTERACTIVE_TERMINAL_MODE : mode;
|
|
33
|
+
if (normalizedMode !== INTERACTIVE_TERMINAL_MODE && normalizedMode !== COMMAND_TERMINAL_MODE) throw new Error('Invalid terminal mode');
|
|
34
|
+
if (normalizedMode === INTERACTIVE_TERMINAL_MODE) {
|
|
35
|
+
if (command != null) throw new Error('Interactive terminal create does not accept a command');
|
|
36
|
+
return { mode: INTERACTIVE_TERMINAL_MODE, command: null };
|
|
37
|
+
}
|
|
38
|
+
if (!isString(command) || !command.trim()) throw new Error('Terminal command is required');
|
|
39
|
+
const trimmedCommand = command.trim();
|
|
40
|
+
if (trimmedCommand.length > MAX_INPUT_CHARS) throw new Error('Terminal command exceeds the input limit');
|
|
41
|
+
return { mode: COMMAND_TERMINAL_MODE, command: trimmedCommand };
|
|
42
|
+
};
|
|
43
|
+
const normalizePurposeId = (value, errorMessage) => {
|
|
44
|
+
if (!isString(value) || !value.trim()) throw new Error(errorMessage);
|
|
45
|
+
const normalized = value.trim();
|
|
46
|
+
if (normalized.length > MAX_PURPOSE_ID_CHARS) throw new Error(errorMessage);
|
|
47
|
+
return normalized;
|
|
48
|
+
};
|
|
49
|
+
const normalizeTerminalPurpose = (value) => {
|
|
50
|
+
if (value == null) return TERMINAL_PURPOSE;
|
|
51
|
+
if (!isObjectRecord(value)) throw new Error('Invalid terminal purpose');
|
|
52
|
+
if (value.type === 'terminal') return TERMINAL_PURPOSE;
|
|
53
|
+
if (value.type !== 'project-action') throw new Error('Invalid terminal purpose');
|
|
54
|
+
return {
|
|
55
|
+
type: 'project-action',
|
|
56
|
+
actionId: normalizePurposeId(value.actionId, 'Terminal project action id is required'),
|
|
57
|
+
executionId: normalizePurposeId(value.executionId, 'Terminal execution id is required'),
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
const getSessionPurpose = (session) => session.purpose ?? TERMINAL_PURPOSE;
|
|
61
|
+
const isPurposeActionMatch = (left, right) => {
|
|
62
|
+
if (left.type !== right.type) return false;
|
|
63
|
+
return left.type !== 'project-action' || left.actionId === right.actionId;
|
|
64
|
+
};
|
|
65
|
+
const findRunningActionSession = (sessions, resolvedCwd, purpose, path) => {
|
|
66
|
+
if (purpose.type !== 'project-action') return null;
|
|
67
|
+
for (const session of sessions.values()) {
|
|
68
|
+
if (session.status !== 'running') continue;
|
|
69
|
+
if (path.resolve(session.cwd) !== resolvedCwd) continue;
|
|
70
|
+
const sessionPurpose = getSessionPurpose(session);
|
|
71
|
+
if (sessionPurpose.type === 'project-action' && sessionPurpose.actionId === purpose.actionId) return session;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
};
|
|
75
|
+
const findPendingActionCreate = (pendingSessionCreates, resolvedCwd, purpose) => {
|
|
76
|
+
if (purpose.type !== 'project-action') return null;
|
|
77
|
+
for (const pending of pendingSessionCreates.values()) {
|
|
78
|
+
if (pending.cancelled || pending.cwd !== resolvedCwd) continue;
|
|
79
|
+
if (pending.purpose?.type === 'project-action' && pending.purpose.actionId === purpose.actionId) return pending;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
};
|
|
21
83
|
const trimHistory = (history) => {
|
|
22
84
|
const bytes = Buffer.from(history);
|
|
23
85
|
if (bytes.byteLength <= MAX_HISTORY_BYTES) return history;
|
|
@@ -54,25 +116,26 @@ export function createTerminalRuntime({
|
|
|
54
116
|
return ptyProviderPromise;
|
|
55
117
|
};
|
|
56
118
|
|
|
57
|
-
const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell }) => {
|
|
119
|
+
const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell, mode, command }) => {
|
|
58
120
|
const provider = await getPtyProvider();
|
|
59
121
|
const resolvedShell = await shellResolver.resolve(shell);
|
|
60
122
|
let lastError = null;
|
|
61
123
|
for (const executable of resolvedShell.executables) {
|
|
62
|
-
const args = loginShell ? getTerminalShellLoginArgs(executable) : [];
|
|
63
|
-
if (!args) throw new Error(`Terminal shell "${resolvedShell.id}" does not support login mode`);
|
|
64
124
|
try {
|
|
65
125
|
const env = { ...process.env, PATH: buildAugmentedPath(), TERM: 'xterm-256color', COLORTERM: 'truecolor', COLORFGBG: themeMode === 'light' ? '0;15' : '15;0' };
|
|
66
|
-
// The daemon's IPC fd is closed inside the PTY
|
|
67
|
-
//
|
|
68
|
-
env.NODE_CHANNEL_FD
|
|
126
|
+
// The daemon's IPC fd is closed inside the PTY; an inherited NODE_CHANNEL_FD
|
|
127
|
+
// (even an empty one) makes Node CLIs warn about an unparsable IPC channel.
|
|
128
|
+
delete env.NODE_CHANNEL_FD;
|
|
69
129
|
delete env.BASH_XTRACEFD; delete env.BASH_ENV; delete env.ENV; delete env.ELECTRON_RUN_AS_NODE;
|
|
70
130
|
// AppImage exports ARGV0; zsh would otherwise rewrite argv[0] for every command (#2588).
|
|
71
|
-
// bun-pty also merges the native OS environ, so wrap with `env -u ARGV0` on Linux.
|
|
72
131
|
stripAppImageArgv0Leak(env);
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
132
|
+
const shellLaunch = buildTerminalShellLaunch(executable, { mode, command, loginShell });
|
|
133
|
+
// bun-pty merges the native OS environ back in, so the POSIX launch is
|
|
134
|
+
// wrapped with `env -u` for the variables deleted above.
|
|
135
|
+
const launch = resolvePosixPtyLaunch(shellLaunch.executable, shellLaunch.args);
|
|
136
|
+
const options = { name: 'xterm-256color', cwd, cols, rows, env };
|
|
137
|
+
if (process.platform === 'win32') options.useConpty = true;
|
|
138
|
+
return { process: await provider.spawn(launch.executable, launch.args, options), backend: provider.backend, shell: resolvedShell.id, loginShell };
|
|
76
139
|
} catch (error) { lastError = error; }
|
|
77
140
|
}
|
|
78
141
|
throw lastError ?? new Error('No executable shell found');
|
|
@@ -122,7 +185,12 @@ export function createTerminalRuntime({
|
|
|
122
185
|
|
|
123
186
|
const snapshot = (session) => ({
|
|
124
187
|
t: 'snapshot', v: 3, s: session.id, q: session.sequence, history: session.history,
|
|
188
|
+
// The PTY size the history was drawn for: a client replays history at this
|
|
189
|
+
// size before fitting its own viewport, so shell output wrapped for one
|
|
190
|
+
// width never gets re-laid-out at another.
|
|
191
|
+
cols: session.cols, rows: session.rows,
|
|
125
192
|
status: session.status, exitCode: session.exitCode, signal: session.signal,
|
|
193
|
+
mode: session.mode ?? INTERACTIVE_TERMINAL_MODE, purpose: getSessionPurpose(session),
|
|
126
194
|
runtime, ptyBackend: session.backend,
|
|
127
195
|
});
|
|
128
196
|
|
|
@@ -175,11 +243,18 @@ export function createTerminalRuntime({
|
|
|
175
243
|
ptyProcess.onExit(({ exitCode, signal }) => { session.eventQueue.push({ type: 'exit', process: ptyProcess, exitCode, signal }); drainEvents(session); });
|
|
176
244
|
};
|
|
177
245
|
|
|
246
|
+
// A working directory that no longer exists (a deleted worktree) is the one
|
|
247
|
+
// rejection the client can recover from by moving the session to its
|
|
248
|
+
// project, so the response names it. Every other rejection stays generic.
|
|
249
|
+
const invalidWorkingDirectory = (code) => Object.assign(new Error('Invalid working directory'), code ? { code } : {});
|
|
178
250
|
const validateCwd = async (cwd) => {
|
|
179
251
|
if (typeof cwd !== 'string' || !cwd.trim()) throw new Error('cwd is required');
|
|
180
|
-
|
|
181
|
-
|
|
252
|
+
let stats;
|
|
253
|
+
try { stats = await fs.promises.stat(cwd); }
|
|
254
|
+
catch (error) { throw invalidWorkingDirectory(error?.code === 'ENOENT' || error?.code === 'ENOTDIR' ? TERMINAL_CWD_MISSING_CODE : undefined); }
|
|
255
|
+
if (!stats?.isDirectory()) throw invalidWorkingDirectory();
|
|
182
256
|
};
|
|
257
|
+
const errorBody = (error, fallback) => ({ error: error?.message || fallback, ...(typeof error?.code === 'string' ? { code: error.code } : {}) });
|
|
183
258
|
|
|
184
259
|
const applyAppearance = (session, { themeMode, terminalBackground, terminalForeground }) => {
|
|
185
260
|
const previous = [session.themeMode, session.terminalBackground, session.terminalForeground];
|
|
@@ -192,48 +267,87 @@ export function createTerminalRuntime({
|
|
|
192
267
|
}
|
|
193
268
|
};
|
|
194
269
|
|
|
195
|
-
const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell }, clear = true) => {
|
|
270
|
+
const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell, mode = INTERACTIVE_TERMINAL_MODE, command = null, purpose = TERMINAL_PURPOSE }, clear = true) => {
|
|
196
271
|
await validateCwd(cwd);
|
|
197
|
-
const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell });
|
|
272
|
+
const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell, mode, command });
|
|
198
273
|
if (clear) { session.history = ''; session.pendingHistoryControlSequence = ''; session.pendingThemeControlSequence = ''; session.themeModeEnabled = false; }
|
|
199
274
|
session.cwd = cwd; session.cols = cols; session.rows = rows; session.process = spawned.process;
|
|
200
275
|
session.backend = spawned.backend; session.shell = spawned.shell; session.loginShell = spawned.loginShell; session.status = 'running'; session.exitCode = null; session.signal = null;
|
|
276
|
+
session.mode = mode; session.command = mode === COMMAND_TERMINAL_MODE ? command : null;
|
|
277
|
+
session.purpose = purpose;
|
|
201
278
|
session.themeMode = themeMode === 'light' ? 'light' : 'dark'; session.terminalBackground = terminalBackground; session.terminalForeground = terminalForeground;
|
|
202
279
|
session.lastActivity = Date.now(); session.eventQueue.length = 0;
|
|
203
280
|
wire(session, spawned.process);
|
|
281
|
+
return spawned.process;
|
|
204
282
|
};
|
|
205
283
|
|
|
206
|
-
const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false }) => {
|
|
284
|
+
const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false, mode, command, purpose }) => {
|
|
207
285
|
if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
|
|
208
286
|
if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
|
|
209
287
|
const normalizedShell = normalizeTerminalShell(shell);
|
|
210
288
|
if (!normalizedShell) throw new Error('Invalid terminal shell');
|
|
289
|
+
const launchMode = normalizeCreateMode({ mode, command });
|
|
290
|
+
const normalizedPurpose = normalizeTerminalPurpose(purpose);
|
|
211
291
|
const id = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : randomUUID();
|
|
212
292
|
if (id.length > 128) throw new Error('Invalid terminal session id');
|
|
213
293
|
const existing = sessions.get(id);
|
|
214
294
|
const resolvedCwd = path.resolve(cwd);
|
|
215
295
|
if (existing?.status === 'running') {
|
|
216
296
|
if (path.resolve(existing.cwd) !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
|
|
297
|
+
if (!isPurposeActionMatch(getSessionPurpose(existing), normalizedPurpose)) throw new Error('Terminal session is already running with a different purpose');
|
|
298
|
+
if (normalizedPurpose.type === 'project-action') { applyAppearance(existing, { themeMode, terminalBackground, terminalForeground }); return existing; }
|
|
299
|
+
if ((existing.mode ?? INTERACTIVE_TERMINAL_MODE) !== launchMode.mode) throw new Error('Terminal session is already running with a different mode');
|
|
300
|
+
if (launchMode.mode === COMMAND_TERMINAL_MODE && existing.command !== launchMode.command) throw new Error('Terminal session is already running with a different command');
|
|
217
301
|
applyAppearance(existing, { themeMode, terminalBackground, terminalForeground });
|
|
218
302
|
return existing;
|
|
219
303
|
}
|
|
304
|
+
const runningActionSession = findRunningActionSession(sessions, resolvedCwd, normalizedPurpose, path);
|
|
305
|
+
if (runningActionSession) {
|
|
306
|
+
applyAppearance(runningActionSession, { themeMode, terminalBackground, terminalForeground });
|
|
307
|
+
return runningActionSession;
|
|
308
|
+
}
|
|
220
309
|
const pending = pendingSessionCreates.get(id);
|
|
221
310
|
if (pending) {
|
|
222
311
|
if (pending.cwd !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
|
|
312
|
+
if (!isPurposeActionMatch(pending.purpose, normalizedPurpose)) throw new Error('Terminal session is already being created with a different purpose');
|
|
313
|
+
if (normalizedPurpose.type === 'project-action') return pending.promise;
|
|
223
314
|
if (pending.shell !== normalizedShell) throw new Error('Terminal session is already being created with a different shell');
|
|
224
315
|
if (pending.loginShell !== loginShell) throw new Error('Terminal session is already being created with a different login mode');
|
|
316
|
+
if (pending.mode !== launchMode.mode) throw new Error('Terminal session is already being created with a different mode');
|
|
317
|
+
if (launchMode.mode === COMMAND_TERMINAL_MODE && pending.command !== launchMode.command) throw new Error('Terminal session is already being created with a different command');
|
|
225
318
|
const session = await pending.promise;
|
|
226
319
|
applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
|
|
227
320
|
return session;
|
|
228
321
|
}
|
|
229
|
-
|
|
322
|
+
const pendingActionCreate = findPendingActionCreate(pendingSessionCreates, resolvedCwd, normalizedPurpose);
|
|
323
|
+
if (pendingActionCreate) {
|
|
324
|
+
const session = await pendingActionCreate.promise;
|
|
325
|
+
applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
|
|
326
|
+
return session;
|
|
327
|
+
}
|
|
328
|
+
const superseded = normalizedPurpose.type === 'project-action'
|
|
329
|
+
? [...sessions.values()].filter((session) => session.id !== id && session.status === 'exited'
|
|
330
|
+
&& path.resolve(session.cwd) === resolvedCwd && isPurposeActionMatch(getSessionPurpose(session), normalizedPurpose))
|
|
331
|
+
: [];
|
|
332
|
+
if (!existing && sessions.size - superseded.length + pendingSessionCreates.size >= MAX_SESSIONS) throw new Error('Maximum terminal sessions reached');
|
|
333
|
+
const pendingEntry = { cwd: resolvedCwd, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose, cancelled: false, promise: null };
|
|
230
334
|
const creation = (async () => {
|
|
231
335
|
const session = existing ?? { id, sequence: 0, history: '', pendingHistoryControlSequence: '', pendingThemeControlSequence: '', eventQueue: [], draining: false, createdAt: Date.now() };
|
|
232
|
-
await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell });
|
|
336
|
+
const ptyProcess = await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose });
|
|
337
|
+
if (pendingEntry.cancelled) {
|
|
338
|
+
session.process = null;
|
|
339
|
+
await terminateProcess(ptyProcess, true);
|
|
340
|
+
throw new Error('Terminal session was closed during creation');
|
|
341
|
+
}
|
|
342
|
+
for (const previous of superseded) {
|
|
343
|
+
if (sessions.get(previous.id) !== previous || previous.status !== 'exited') continue;
|
|
344
|
+
sessions.delete(previous.id);
|
|
345
|
+
closeAttachments(previous.id, 'SUPERSEDED', 'Terminal replaced by a new action run');
|
|
346
|
+
}
|
|
233
347
|
sessions.set(id, session);
|
|
234
348
|
return session;
|
|
235
349
|
})();
|
|
236
|
-
|
|
350
|
+
pendingEntry.promise = creation;
|
|
237
351
|
pendingSessionCreates.set(id, pendingEntry);
|
|
238
352
|
try { return await creation; }
|
|
239
353
|
finally { if (pendingSessionCreates.get(id) === pendingEntry) pendingSessionCreates.delete(id); }
|
|
@@ -276,16 +390,39 @@ export function createTerminalRuntime({
|
|
|
276
390
|
|
|
277
391
|
const upgradeHandler = (req, socket, head) => {
|
|
278
392
|
if (parseRequestPathname(req.url) !== TERMINAL_WS_PATH) return;
|
|
279
|
-
|
|
393
|
+
const accept = () => {
|
|
394
|
+
if (!wsServer) { rejectWebSocketUpgrade(socket, 500, 'Terminal WebSocket unavailable'); return; }
|
|
280
395
|
try {
|
|
281
|
-
if (uiAuthController?.enabled) {
|
|
282
|
-
if (!await uiAuthController.ensureSessionToken(req, null)) { rejectWebSocketUpgrade(socket, 401, 'UI authentication required'); return; }
|
|
283
|
-
if (!await isRequestOriginAllowed(req)) { rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); return; }
|
|
284
|
-
}
|
|
285
|
-
if (!wsServer) { rejectWebSocketUpgrade(socket, 500, 'Terminal WebSocket unavailable'); return; }
|
|
286
396
|
wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit('connection', ws, req));
|
|
287
397
|
} catch { rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }
|
|
288
|
-
}
|
|
398
|
+
};
|
|
399
|
+
const checkOrigin = () => {
|
|
400
|
+
try {
|
|
401
|
+
const result = isRequestOriginAllowed(req);
|
|
402
|
+
if (!(result instanceof Promise)) {
|
|
403
|
+
if (result) accept();
|
|
404
|
+
else rejectWebSocketUpgrade(socket, 403, 'Invalid origin');
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
void result.then((allowed) => {
|
|
408
|
+
if (allowed) accept();
|
|
409
|
+
else rejectWebSocketUpgrade(socket, 403, 'Invalid origin');
|
|
410
|
+
}).catch(() => rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'));
|
|
411
|
+
} catch { rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }
|
|
412
|
+
};
|
|
413
|
+
if (!uiAuthController?.enabled) { accept(); return; }
|
|
414
|
+
try {
|
|
415
|
+
const result = uiAuthController.ensureSessionToken(req, null);
|
|
416
|
+
if (!(result instanceof Promise)) {
|
|
417
|
+
if (result) checkOrigin();
|
|
418
|
+
else rejectWebSocketUpgrade(socket, 401, 'UI authentication required');
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
void result.then((sessionToken) => {
|
|
422
|
+
if (sessionToken) checkOrigin();
|
|
423
|
+
else rejectWebSocketUpgrade(socket, 401, 'UI authentication required');
|
|
424
|
+
}).catch(() => rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'));
|
|
425
|
+
} catch { rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }
|
|
289
426
|
};
|
|
290
427
|
server.on('upgrade', upgradeHandler);
|
|
291
428
|
|
|
@@ -308,6 +445,8 @@ export function createTerminalRuntime({
|
|
|
308
445
|
cwd: session.cwd,
|
|
309
446
|
status: session.status,
|
|
310
447
|
createdAt: Number.isInteger(session.createdAt) ? session.createdAt : null,
|
|
448
|
+
mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
|
|
449
|
+
purpose: getSessionPurpose(session),
|
|
311
450
|
});
|
|
312
451
|
}
|
|
313
452
|
res.json({ sessions: list });
|
|
@@ -326,8 +465,18 @@ export function createTerminalRuntime({
|
|
|
326
465
|
res.json({ touched });
|
|
327
466
|
});
|
|
328
467
|
app.post('/api/terminal/create', async (req, res) => {
|
|
329
|
-
try {
|
|
330
|
-
|
|
468
|
+
try {
|
|
469
|
+
const session = await createSession(req.body ?? {});
|
|
470
|
+
res.json({
|
|
471
|
+
sessionId: session.id,
|
|
472
|
+
cols: session.cols,
|
|
473
|
+
rows: session.rows,
|
|
474
|
+
status: session.status,
|
|
475
|
+
mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
|
|
476
|
+
purpose: getSessionPurpose(session),
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
catch (error) { res.status(error?.message === 'Maximum terminal sessions reached' ? 429 : 400).json(errorBody(error, 'Failed to create terminal session')); }
|
|
331
480
|
});
|
|
332
481
|
app.post('/api/terminal/:sessionId/resize', (req, res) => {
|
|
333
482
|
const session = sessions.get(req.params.sessionId);
|
|
@@ -346,6 +495,7 @@ export function createTerminalRuntime({
|
|
|
346
495
|
app.post('/api/terminal/:sessionId/restart', async (req, res) => {
|
|
347
496
|
const session = sessions.get(req.params.sessionId);
|
|
348
497
|
if (!session) return res.status(404).json({ error: 'Terminal session not found' });
|
|
498
|
+
if ((session.mode ?? INTERACTIVE_TERMINAL_MODE) === COMMAND_TERMINAL_MODE) return res.status(400).json({ error: 'Command-mode terminal sessions cannot be restarted' });
|
|
349
499
|
const cwd = req.body?.cwd ?? session.cwd;
|
|
350
500
|
const cols = req.body?.cols ?? session.cols;
|
|
351
501
|
const rows = req.body?.rows ?? session.rows;
|
|
@@ -370,12 +520,21 @@ export function createTerminalRuntime({
|
|
|
370
520
|
try {
|
|
371
521
|
await restart;
|
|
372
522
|
res.json({ sessionId: session.id, cols, rows, status: session.status });
|
|
373
|
-
} catch (error) { res.status(400).json(
|
|
523
|
+
} catch (error) { res.status(400).json(errorBody(error, 'Failed to restart terminal')); }
|
|
374
524
|
finally { if (pendingSessionRestarts.get(session.id) === restart) pendingSessionRestarts.delete(session.id); }
|
|
375
525
|
});
|
|
376
526
|
app.delete('/api/terminal/:sessionId', async (req, res) => {
|
|
377
527
|
const session = sessions.get(req.params.sessionId);
|
|
378
|
-
if (!session)
|
|
528
|
+
if (!session) {
|
|
529
|
+
const pending = pendingSessionCreates.get(req.params.sessionId);
|
|
530
|
+
if (!pending) return res.status(404).json({ error: 'Terminal session not found' });
|
|
531
|
+
pending.cancelled = true;
|
|
532
|
+
try { await pending.promise; }
|
|
533
|
+
catch (error) {
|
|
534
|
+
if (error?.message !== 'Terminal session was closed during creation') throw error;
|
|
535
|
+
}
|
|
536
|
+
return res.json({ success: true });
|
|
537
|
+
}
|
|
379
538
|
sessions.delete(session.id);
|
|
380
539
|
closeAttachments(session.id, 'CLOSED', 'Terminal closed');
|
|
381
540
|
await terminateProcess(session.process);
|