@sanqianx/claude-ai-workbench 0.13.2 → 0.13.3

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 (120) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +156 -156
  3. package/apps/agent-terminal/app.css +636 -613
  4. package/apps/agent-terminal/app.js +125 -65
  5. package/apps/agent-terminal/conversation-composer.js +44 -0
  6. package/apps/agent-terminal/index.html +171 -170
  7. package/apps/agent-terminal/panel-host-proof.html +152 -152
  8. package/apps/agent-terminal/panel-proof-content.html +41 -41
  9. package/apps/agent-terminal/right-workspace-dock.css +187 -159
  10. package/apps/agent-terminal/right-workspace-dock.js +623 -519
  11. package/apps/ai-profile-settings-host/index.html +25 -25
  12. package/apps/ai-profile-settings-host/page.css +1 -1
  13. package/apps/ai-profile-settings-host/page.js +113 -113
  14. package/apps/minimal-test-host/README.md +15 -15
  15. package/apps/minimal-test-host/host.css +2 -2
  16. package/apps/minimal-test-host/host.js +35 -35
  17. package/apps/minimal-test-host/index.html +58 -58
  18. package/apps/minimal-test-host/optional-mock/fault-injection.js +15 -15
  19. package/docs/sdk/FILE_LAYOUT.md +31 -31
  20. package/docs/sdk/INTEGRATION.md +126 -126
  21. package/docs/sdk/README.md +21 -21
  22. package/docs/sdk/SESSION_EVENTS.md +13 -13
  23. package/docs/sdk/openapi.yaml +8 -1
  24. package/package.json +1 -1
  25. package/packages/client/README.md +29 -29
  26. package/packages/client/index.d.ts +122 -122
  27. package/packages/client/index.js +260 -260
  28. package/packages/client/package.json +2 -2
  29. package/packages/contracts/README.md +9 -9
  30. package/packages/contracts/index.d.ts +519 -517
  31. package/packages/contracts/index.js +312 -312
  32. package/packages/contracts/package.json +1 -1
  33. package/packages/core/README.md +8 -8
  34. package/packages/core/index.d.ts +76 -76
  35. package/packages/core/index.js +222 -222
  36. package/packages/core/package.json +2 -2
  37. package/packages/server/README.md +17 -17
  38. package/packages/server/bin/agent-terminal-server.js +42 -42
  39. package/packages/server/bin/claude-workbench.js +225 -225
  40. package/packages/server/index.d.ts +171 -171
  41. package/packages/server/index.js +230 -230
  42. package/packages/server/lib/agent-discovery.js +133 -133
  43. package/packages/server/lib/agent-registry.js +143 -143
  44. package/packages/server/lib/agent-spawn-env.js +17 -17
  45. package/packages/server/lib/attachment-store.js +78 -78
  46. package/packages/server/lib/bridges/app-server-bridge.js +373 -373
  47. package/packages/server/lib/bridges/opencode-server-bridge.js +506 -506
  48. package/packages/server/lib/capture-settings-store.js +35 -35
  49. package/packages/server/lib/claude-history-recovery.js +87 -87
  50. package/packages/server/lib/cli-session-recovery.js +28 -28
  51. package/packages/server/lib/context-resolver.js +55 -55
  52. package/packages/server/lib/conversation-capture.js +51 -51
  53. package/packages/server/lib/delegation-phase-store.js +357 -357
  54. package/packages/server/lib/delegation-store.js +474 -468
  55. package/packages/server/lib/diagnostics.js +32 -32
  56. package/packages/server/lib/drivers/cli-json-runner.js +974 -974
  57. package/packages/server/lib/drivers/codex-driver.js +1442 -1442
  58. package/packages/server/lib/drivers/opencode-driver.js +1554 -1554
  59. package/packages/server/lib/drivers/zcode-driver.js +1250 -1250
  60. package/packages/server/lib/drivers/zcode-profile-runtime.js +71 -71
  61. package/packages/server/lib/event-stream.js +138 -138
  62. package/packages/server/lib/folder-picker.js +623 -623
  63. package/packages/server/lib/http-handler.js +339 -339
  64. package/packages/server/lib/json-file.js +26 -26
  65. package/packages/server/lib/knowledge-context.js +33 -33
  66. package/packages/server/lib/model-detection.js +295 -295
  67. package/packages/server/lib/parent-context.js +44 -0
  68. package/packages/server/lib/profile-store.js +283 -283
  69. package/packages/server/lib/project-store.js +102 -102
  70. package/packages/server/lib/runtime-loader.js +120 -120
  71. package/packages/server/lib/session-archive-store.js +53 -53
  72. package/packages/server/lib/session-history.js +612 -612
  73. package/packages/server/lib/system-doctor.js +125 -125
  74. package/packages/server/lib/ui-preferences-store.js +48 -48
  75. package/packages/server/lib/workbench-service.js +1696 -1675
  76. package/packages/server/package.json +2 -2
  77. package/packages/ui/README.md +30 -30
  78. package/packages/ui/ai-profile-settings.d.ts +45 -45
  79. package/packages/ui/ai-profile-settings.js +283 -283
  80. package/packages/ui/claude-terminal.d.ts +31 -31
  81. package/packages/ui/claude-terminal.js +343 -343
  82. package/packages/ui/index.d.ts +18 -18
  83. package/packages/ui/index.js +51 -51
  84. package/packages/ui/package.json +2 -2
  85. package/packages/ui/theme.css +13 -13
  86. package/src/assets/claude-prompts.json +21 -21
  87. package/src/backend/http/ai-profile-routes.js +61 -61
  88. package/src/backend/http/claude-routes.js +170 -170
  89. package/src/backend/http/node-helpers.js +45 -45
  90. package/src/backend/index.js +21 -21
  91. package/src/backend/lib/ai-adapter.js +144 -144
  92. package/src/backend/lib/ai-profile-store.js +259 -259
  93. package/src/backend/lib/ai-vendor-presets.js +83 -83
  94. package/src/backend/lib/ai-workspace.js +140 -140
  95. package/src/backend/lib/automation-config.js +253 -253
  96. package/src/backend/lib/claude-cli-runner.js +2392 -2392
  97. package/src/backend/lib/data-dir.js +169 -169
  98. package/src/backend/lib/llm-client.js +176 -176
  99. package/src/backend/lib/model-context-windows.js +82 -82
  100. package/src/backend/lib/native-task-control.js +217 -217
  101. package/src/backend/lib/native-task-history-index.js +475 -475
  102. package/src/backend/lib/native-task-history-reader.js +526 -526
  103. package/src/backend/lib/native-task-messages.js +457 -457
  104. package/src/backend/lib/native-task-registry.js +325 -325
  105. package/src/backend/lib/native-task-runtime.js +242 -242
  106. package/src/backend/lib/native-task-trace.js +440 -440
  107. package/src/backend/lib/native-task-transcript.js +393 -393
  108. package/src/backend/lib/prompt-registry.js +166 -166
  109. package/src/backend/lib/runtime-config.js +121 -121
  110. package/src/backend/lib/sdk-session-stream.js +143 -143
  111. package/src/backend/lib/sdk-turn-stream.js +16 -16
  112. package/src/backend/lib/store-scope.js +131 -131
  113. package/src/backend/lib/task-identity.js +104 -104
  114. package/src/backend/lib/task-state-projection.js +58 -58
  115. package/src/index.js +7 -7
  116. package/src/sdk-wave-a.ts +1 -1
  117. package/src/sdk-wave-b.ts +1 -1
  118. package/src/sdk-wave-c.ts +1 -1
  119. package/src/sdk-wave-d.ts +1 -1
  120. package/src/sdk-wave-e.ts +1 -1
@@ -1,102 +1,102 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const crypto = require('crypto');
6
- const { normalizeProject } = require('../../contracts');
7
- const { readJson, writeJson } = require('./json-file');
8
-
9
- const SCHEMA = 'agent-terminal-projects/v1';
10
-
11
- // Registry of user-created workspaces. Each project binds a display name to
12
- // an absolute local directory; its projectId doubles as the ContextResolver
13
- // workspaceRef so sessions inherit project ownership for free.
14
- class ProjectStore {
15
- constructor(options = {}) {
16
- if (!options.dataDir) throw new Error('ProjectStore dataDir is required');
17
- this.projectFile = options.projectFile || path.join(options.dataDir, 'projects.v1.json');
18
- }
19
-
20
- _read() { return readJson(this.projectFile, { schema: SCHEMA, projects: [] }); }
21
- _write(cfg) { writeJson(this.projectFile, cfg); }
22
-
23
- list() {
24
- return this._read().projects
25
- .slice()
26
- .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
27
- }
28
-
29
- get(id) {
30
- return this._read().projects.find(item => item.id === id) || null;
31
- }
32
-
33
- create(input = {}) {
34
- const cfg = this._read();
35
- const rootPath = resolveExistingDirectory(input.rootPath);
36
- const project = normalizeProject({ ...input, rootPath }, generateProjectId(cfg));
37
- cfg.projects.push(project);
38
- this._write(cfg);
39
- return project;
40
- }
41
-
42
- rename(id, name) {
43
- return this.update(id, { name });
44
- }
45
-
46
- update(id, input = {}) {
47
- const cfg = this._read();
48
- const index = cfg.projects.findIndex(item => item.id === id);
49
- if (index < 0) throw Object.assign(new Error('project not found'), { status: 404 });
50
- const current = cfg.projects[index];
51
- const next = normalizeProject({
52
- ...current,
53
- ...Object.fromEntries(['name', 'defaultAiProfileId', 'defaultModel', 'defaultAgentId']
54
- .filter(key => Object.prototype.hasOwnProperty.call(input, key)).map(key => [key, input[key]])),
55
- rootPath: current.rootPath, createdAt: current.createdAt,
56
- }, current.id);
57
- next.updatedAt = new Date().toISOString();
58
- cfg.projects[index] = next;
59
- this._write(cfg);
60
- return next;
61
- }
62
-
63
- remove(id) {
64
- const cfg = this._read();
65
- if (!cfg.projects.some(item => item.id === id)) return false;
66
- cfg.projects = cfg.projects.filter(item => item.id !== id);
67
- this._write(cfg);
68
- return true;
69
- }
70
-
71
- toWorkspaceMap() {
72
- const map = {};
73
- for (const project of this.list()) map[project.id] = project.rootPath;
74
- return map;
75
- }
76
- }
77
-
78
- function generateProjectId(cfg) {
79
- const taken = new Set(cfg.projects.map(item => item.id));
80
- for (let attempt = 0; attempt < 32; attempt += 1) {
81
- const id = `prj-${crypto.randomBytes(5).toString('hex')}`;
82
- if (!taken.has(id)) return id;
83
- }
84
- throw new Error('unable to allocate a project id');
85
- }
86
-
87
- function resolveExistingDirectory(rootPath) {
88
- const value = String(rootPath || '').trim();
89
- if (!value) throw Object.assign(new Error('project rootPath is required'), { status: 400 });
90
- let real;
91
- try {
92
- real = fs.realpathSync(path.resolve(value));
93
- } catch {
94
- throw Object.assign(new Error(`project directory does not exist: ${value}`), { status: 400 });
95
- }
96
- if (!fs.statSync(real).isDirectory()) {
97
- throw Object.assign(new Error(`project rootPath is not a directory: ${value}`), { status: 400 });
98
- }
99
- return real;
100
- }
101
-
102
- module.exports = { ProjectStore };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+ const { normalizeProject } = require('../../contracts');
7
+ const { readJson, writeJson } = require('./json-file');
8
+
9
+ const SCHEMA = 'agent-terminal-projects/v1';
10
+
11
+ // Registry of user-created workspaces. Each project binds a display name to
12
+ // an absolute local directory; its projectId doubles as the ContextResolver
13
+ // workspaceRef so sessions inherit project ownership for free.
14
+ class ProjectStore {
15
+ constructor(options = {}) {
16
+ if (!options.dataDir) throw new Error('ProjectStore dataDir is required');
17
+ this.projectFile = options.projectFile || path.join(options.dataDir, 'projects.v1.json');
18
+ }
19
+
20
+ _read() { return readJson(this.projectFile, { schema: SCHEMA, projects: [] }); }
21
+ _write(cfg) { writeJson(this.projectFile, cfg); }
22
+
23
+ list() {
24
+ return this._read().projects
25
+ .slice()
26
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
27
+ }
28
+
29
+ get(id) {
30
+ return this._read().projects.find(item => item.id === id) || null;
31
+ }
32
+
33
+ create(input = {}) {
34
+ const cfg = this._read();
35
+ const rootPath = resolveExistingDirectory(input.rootPath);
36
+ const project = normalizeProject({ ...input, rootPath }, generateProjectId(cfg));
37
+ cfg.projects.push(project);
38
+ this._write(cfg);
39
+ return project;
40
+ }
41
+
42
+ rename(id, name) {
43
+ return this.update(id, { name });
44
+ }
45
+
46
+ update(id, input = {}) {
47
+ const cfg = this._read();
48
+ const index = cfg.projects.findIndex(item => item.id === id);
49
+ if (index < 0) throw Object.assign(new Error('project not found'), { status: 404 });
50
+ const current = cfg.projects[index];
51
+ const next = normalizeProject({
52
+ ...current,
53
+ ...Object.fromEntries(['name', 'defaultAiProfileId', 'defaultModel', 'defaultAgentId']
54
+ .filter(key => Object.prototype.hasOwnProperty.call(input, key)).map(key => [key, input[key]])),
55
+ rootPath: current.rootPath, createdAt: current.createdAt,
56
+ }, current.id);
57
+ next.updatedAt = new Date().toISOString();
58
+ cfg.projects[index] = next;
59
+ this._write(cfg);
60
+ return next;
61
+ }
62
+
63
+ remove(id) {
64
+ const cfg = this._read();
65
+ if (!cfg.projects.some(item => item.id === id)) return false;
66
+ cfg.projects = cfg.projects.filter(item => item.id !== id);
67
+ this._write(cfg);
68
+ return true;
69
+ }
70
+
71
+ toWorkspaceMap() {
72
+ const map = {};
73
+ for (const project of this.list()) map[project.id] = project.rootPath;
74
+ return map;
75
+ }
76
+ }
77
+
78
+ function generateProjectId(cfg) {
79
+ const taken = new Set(cfg.projects.map(item => item.id));
80
+ for (let attempt = 0; attempt < 32; attempt += 1) {
81
+ const id = `prj-${crypto.randomBytes(5).toString('hex')}`;
82
+ if (!taken.has(id)) return id;
83
+ }
84
+ throw new Error('unable to allocate a project id');
85
+ }
86
+
87
+ function resolveExistingDirectory(rootPath) {
88
+ const value = String(rootPath || '').trim();
89
+ if (!value) throw Object.assign(new Error('project rootPath is required'), { status: 400 });
90
+ let real;
91
+ try {
92
+ real = fs.realpathSync(path.resolve(value));
93
+ } catch {
94
+ throw Object.assign(new Error(`project directory does not exist: ${value}`), { status: 400 });
95
+ }
96
+ if (!fs.statSync(real).isDirectory()) {
97
+ throw Object.assign(new Error(`project rootPath is not a directory: ${value}`), { status: 400 });
98
+ }
99
+ return real;
100
+ }
101
+
102
+ module.exports = { ProjectStore };
@@ -1,120 +1,120 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
-
6
- // Loading boundary between the packaged server and the legacy runtime tree
7
- // (src/backend/lib) it must run. Exactly one of two legal layouts is allowed:
8
- //
9
- // source layout — this module lives at <root>/packages/server/lib and the
10
- // same distribution root carries <root>/src/backend/lib. That root is only
11
- // accepted when it is verifiably THIS project's root: the package must sit
12
- // in a packages/ directory whose parent manifest is named as the workbench
13
- // root. An installed server package therefore can never borrow src/ code
14
- // from a consumer project or from an unrelated node_modules tree.
15
- //
16
- // sdk-bundle layout — a standalone packed server package carries its own
17
- // legacy tree at <package>/legacy/src/backend/lib. pack-sdk.js stamps the
18
- // STAGED manifest with runtimeLayout='sdk-bundle'; older packages without
19
- // the marker are recognized by the legacy tree itself. Once the bundle
20
- // layout is established it is locked: a missing file, or a missing legacy
21
- // tree entirely, fails the load. There is no fallback to source code
22
- // outside the package, so a broken artifact can never appear to work.
23
- //
24
- // Module names are restricted to plain lowercase identifiers — no path
25
- // separators, no extension, no traversal — and every resolution stays
26
- // inside the chosen legacy directory. This module deliberately requires
27
- // nothing from the server itself (no index.js, no Service), so loading the
28
- // runtime can never become a require cycle.
29
-
30
- const SERVER_PACKAGE_DIR = path.join(__dirname, '..');
31
- const SERVER_PACKAGE_NAME = '@claude-ai-workbench/server';
32
- const SOURCE_ROOT_PACKAGE_NAME = '@sanqianx/claude-ai-workbench';
33
- const RUNTIME_LAYOUT_MARKER = 'sdk-bundle';
34
- const MODULE_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
35
-
36
- function fail(code, message) {
37
- const error = new Error(message);
38
- error.code = code;
39
- throw error;
40
- }
41
-
42
- function isRealDirectory(candidate) {
43
- try { return fs.statSync(candidate).isDirectory(); } catch { return false; }
44
- }
45
-
46
- function readManifest(dir) {
47
- let parsed;
48
- try {
49
- parsed = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
50
- } catch (error) {
51
- fail('RUNTIME_PACKAGE_MANIFEST_INVALID', `package manifest at ${dir} is missing or unreadable: ${error.message}`);
52
- }
53
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
54
- fail('RUNTIME_PACKAGE_MANIFEST_INVALID', `package manifest at ${dir} is not a JSON object`);
55
- }
56
- return parsed;
57
- }
58
-
59
- // Resolves to { kind: 'source' | 'sdk-bundle', legacyDir, marker } or throws
60
- // RUNTIME_LAYOUT_UNKNOWN. It never guesses: anything that cannot be proven
61
- // from the package's own bytes is an error, not a fallback.
62
- function resolveRuntimeLayout(serverPackageDir) {
63
- const pkgDir = serverPackageDir || SERVER_PACKAGE_DIR;
64
- const manifest = readManifest(pkgDir);
65
- const bundleLegacyDir = path.join(pkgDir, 'legacy', 'src', 'backend', 'lib');
66
- if (manifest.runtimeLayout !== undefined) {
67
- if (manifest.runtimeLayout !== RUNTIME_LAYOUT_MARKER) {
68
- fail('RUNTIME_LAYOUT_UNKNOWN', `package manifest declares unsupported runtimeLayout '${String(manifest.runtimeLayout)}'`);
69
- }
70
- return { kind: 'sdk-bundle', legacyDir: bundleLegacyDir, marker: true };
71
- }
72
- if (isRealDirectory(bundleLegacyDir)) {
73
- return { kind: 'sdk-bundle', legacyDir: bundleLegacyDir, marker: false };
74
- }
75
- if (manifest.name !== SERVER_PACKAGE_NAME) {
76
- fail('RUNTIME_LAYOUT_UNKNOWN', `package manifest must be named ${SERVER_PACKAGE_NAME} to use the source layout`);
77
- }
78
- if (path.basename(path.dirname(pkgDir)) !== 'packages') {
79
- fail('RUNTIME_LAYOUT_UNKNOWN', 'server package does not sit inside a packages/ directory of a project root; refusing to look for source code elsewhere');
80
- }
81
- const rootDir = path.dirname(path.dirname(pkgDir));
82
- let rootManifest;
83
- try {
84
- rootManifest = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json'), 'utf8'));
85
- } catch {
86
- fail('RUNTIME_LAYOUT_UNKNOWN', 'no readable project root manifest above packages/; refusing to look for source code elsewhere');
87
- }
88
- if (!rootManifest || rootManifest.name !== SOURCE_ROOT_PACKAGE_NAME) {
89
- fail('RUNTIME_LAYOUT_UNKNOWN', `project root manifest is not ${SOURCE_ROOT_PACKAGE_NAME}; refusing to borrow its source tree`);
90
- }
91
- const sourceLegacyDir = path.join(rootDir, 'src', 'backend', 'lib');
92
- if (!isRealDirectory(sourceLegacyDir)) {
93
- fail('RUNTIME_LAYOUT_UNKNOWN', `verified ${SOURCE_ROOT_PACKAGE_NAME} root has no src/backend/lib runtime tree`);
94
- }
95
- return { kind: 'source', legacyDir: sourceLegacyDir, marker: false };
96
- }
97
-
98
- function loadLegacyRuntime(name) {
99
- if (typeof name !== 'string' || !MODULE_NAME_PATTERN.test(name)) {
100
- fail('RUNTIME_MODULE_NAME_INVALID', 'legacy runtime module name must be a plain lowercase identifier (no path, extension or traversal)');
101
- }
102
- const layout = resolveRuntimeLayout();
103
- const resolved = path.resolve(layout.legacyDir, `${name}.js`);
104
- if (!resolved.startsWith(`${layout.legacyDir}${path.sep}`)) {
105
- fail('RUNTIME_MODULE_NAME_INVALID', 'legacy runtime module name escapes the runtime directory');
106
- }
107
- if (!fs.existsSync(resolved)) {
108
- const where = layout.kind === 'sdk-bundle'
109
- ? 'this sdk bundle ships its own legacy tree and must fail on gaps instead of borrowing source code'
110
- : 'the verified source tree does not contain it';
111
- fail('RUNTIME_MODULE_MISSING', `legacy runtime module '${name}' is not available: expected ${resolved} (${where})`);
112
- }
113
- return require(resolved);
114
- }
115
-
116
- module.exports = {
117
- loadLegacyRuntime,
118
- resolveRuntimeLayout,
119
- RUNTIME_LAYOUT_MARKER,
120
- };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ // Loading boundary between the packaged server and the legacy runtime tree
7
+ // (src/backend/lib) it must run. Exactly one of two legal layouts is allowed:
8
+ //
9
+ // source layout — this module lives at <root>/packages/server/lib and the
10
+ // same distribution root carries <root>/src/backend/lib. That root is only
11
+ // accepted when it is verifiably THIS project's root: the package must sit
12
+ // in a packages/ directory whose parent manifest is named as the workbench
13
+ // root. An installed server package therefore can never borrow src/ code
14
+ // from a consumer project or from an unrelated node_modules tree.
15
+ //
16
+ // sdk-bundle layout — a standalone packed server package carries its own
17
+ // legacy tree at <package>/legacy/src/backend/lib. pack-sdk.js stamps the
18
+ // STAGED manifest with runtimeLayout='sdk-bundle'; older packages without
19
+ // the marker are recognized by the legacy tree itself. Once the bundle
20
+ // layout is established it is locked: a missing file, or a missing legacy
21
+ // tree entirely, fails the load. There is no fallback to source code
22
+ // outside the package, so a broken artifact can never appear to work.
23
+ //
24
+ // Module names are restricted to plain lowercase identifiers — no path
25
+ // separators, no extension, no traversal — and every resolution stays
26
+ // inside the chosen legacy directory. This module deliberately requires
27
+ // nothing from the server itself (no index.js, no Service), so loading the
28
+ // runtime can never become a require cycle.
29
+
30
+ const SERVER_PACKAGE_DIR = path.join(__dirname, '..');
31
+ const SERVER_PACKAGE_NAME = '@claude-ai-workbench/server';
32
+ const SOURCE_ROOT_PACKAGE_NAME = '@sanqianx/claude-ai-workbench';
33
+ const RUNTIME_LAYOUT_MARKER = 'sdk-bundle';
34
+ const MODULE_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
35
+
36
+ function fail(code, message) {
37
+ const error = new Error(message);
38
+ error.code = code;
39
+ throw error;
40
+ }
41
+
42
+ function isRealDirectory(candidate) {
43
+ try { return fs.statSync(candidate).isDirectory(); } catch { return false; }
44
+ }
45
+
46
+ function readManifest(dir) {
47
+ let parsed;
48
+ try {
49
+ parsed = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
50
+ } catch (error) {
51
+ fail('RUNTIME_PACKAGE_MANIFEST_INVALID', `package manifest at ${dir} is missing or unreadable: ${error.message}`);
52
+ }
53
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
54
+ fail('RUNTIME_PACKAGE_MANIFEST_INVALID', `package manifest at ${dir} is not a JSON object`);
55
+ }
56
+ return parsed;
57
+ }
58
+
59
+ // Resolves to { kind: 'source' | 'sdk-bundle', legacyDir, marker } or throws
60
+ // RUNTIME_LAYOUT_UNKNOWN. It never guesses: anything that cannot be proven
61
+ // from the package's own bytes is an error, not a fallback.
62
+ function resolveRuntimeLayout(serverPackageDir) {
63
+ const pkgDir = serverPackageDir || SERVER_PACKAGE_DIR;
64
+ const manifest = readManifest(pkgDir);
65
+ const bundleLegacyDir = path.join(pkgDir, 'legacy', 'src', 'backend', 'lib');
66
+ if (manifest.runtimeLayout !== undefined) {
67
+ if (manifest.runtimeLayout !== RUNTIME_LAYOUT_MARKER) {
68
+ fail('RUNTIME_LAYOUT_UNKNOWN', `package manifest declares unsupported runtimeLayout '${String(manifest.runtimeLayout)}'`);
69
+ }
70
+ return { kind: 'sdk-bundle', legacyDir: bundleLegacyDir, marker: true };
71
+ }
72
+ if (isRealDirectory(bundleLegacyDir)) {
73
+ return { kind: 'sdk-bundle', legacyDir: bundleLegacyDir, marker: false };
74
+ }
75
+ if (manifest.name !== SERVER_PACKAGE_NAME) {
76
+ fail('RUNTIME_LAYOUT_UNKNOWN', `package manifest must be named ${SERVER_PACKAGE_NAME} to use the source layout`);
77
+ }
78
+ if (path.basename(path.dirname(pkgDir)) !== 'packages') {
79
+ fail('RUNTIME_LAYOUT_UNKNOWN', 'server package does not sit inside a packages/ directory of a project root; refusing to look for source code elsewhere');
80
+ }
81
+ const rootDir = path.dirname(path.dirname(pkgDir));
82
+ let rootManifest;
83
+ try {
84
+ rootManifest = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json'), 'utf8'));
85
+ } catch {
86
+ fail('RUNTIME_LAYOUT_UNKNOWN', 'no readable project root manifest above packages/; refusing to look for source code elsewhere');
87
+ }
88
+ if (!rootManifest || rootManifest.name !== SOURCE_ROOT_PACKAGE_NAME) {
89
+ fail('RUNTIME_LAYOUT_UNKNOWN', `project root manifest is not ${SOURCE_ROOT_PACKAGE_NAME}; refusing to borrow its source tree`);
90
+ }
91
+ const sourceLegacyDir = path.join(rootDir, 'src', 'backend', 'lib');
92
+ if (!isRealDirectory(sourceLegacyDir)) {
93
+ fail('RUNTIME_LAYOUT_UNKNOWN', `verified ${SOURCE_ROOT_PACKAGE_NAME} root has no src/backend/lib runtime tree`);
94
+ }
95
+ return { kind: 'source', legacyDir: sourceLegacyDir, marker: false };
96
+ }
97
+
98
+ function loadLegacyRuntime(name) {
99
+ if (typeof name !== 'string' || !MODULE_NAME_PATTERN.test(name)) {
100
+ fail('RUNTIME_MODULE_NAME_INVALID', 'legacy runtime module name must be a plain lowercase identifier (no path, extension or traversal)');
101
+ }
102
+ const layout = resolveRuntimeLayout();
103
+ const resolved = path.resolve(layout.legacyDir, `${name}.js`);
104
+ if (!resolved.startsWith(`${layout.legacyDir}${path.sep}`)) {
105
+ fail('RUNTIME_MODULE_NAME_INVALID', 'legacy runtime module name escapes the runtime directory');
106
+ }
107
+ if (!fs.existsSync(resolved)) {
108
+ const where = layout.kind === 'sdk-bundle'
109
+ ? 'this sdk bundle ships its own legacy tree and must fail on gaps instead of borrowing source code'
110
+ : 'the verified source tree does not contain it';
111
+ fail('RUNTIME_MODULE_MISSING', `legacy runtime module '${name}' is not available: expected ${resolved} (${where})`);
112
+ }
113
+ return require(resolved);
114
+ }
115
+
116
+ module.exports = {
117
+ loadLegacyRuntime,
118
+ resolveRuntimeLayout,
119
+ RUNTIME_LAYOUT_MARKER,
120
+ };
@@ -1,53 +1,53 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const { readJson, writeJson } = require('./json-file');
5
-
6
- const SCHEMA = 'agent-terminal-session-archive/v1';
7
-
8
- // Sidecar marking sessions the user archived. Session records themselves stay
9
- // owned by the runner, so archiving never rewrites runner history — it only
10
- // flips visibility in listings and can be undone at any time.
11
- class SessionArchiveStore {
12
- constructor(options = {}) {
13
- if (!options.dataDir) throw new Error('SessionArchiveStore dataDir is required');
14
- this.archiveFile = options.archiveFile || path.join(options.dataDir, 'archived-sessions.v1.json');
15
- }
16
-
17
- _read() { return readJson(this.archiveFile, { schema: SCHEMA, sessions: {} }); }
18
- _write(cfg) { writeJson(this.archiveFile, cfg); }
19
-
20
- isArchived(sessionId) { return Boolean(this._read().sessions[sessionId]); }
21
- // Marks older than maxAgeMs. Entries without a parseable archivedAt never
22
- // expire — deleting what cannot be dated is not a safe default.
23
- expired(maxAgeMs, now = Date.now()) {
24
- const cfg = this._read();
25
- const ids = [];
26
- for (const [sessionId, meta] of Object.entries(cfg.sessions)) {
27
- const archivedAt = Date.parse(meta && meta.archivedAt);
28
- if (Number.isFinite(archivedAt) && now - archivedAt > maxAgeMs) ids.push(sessionId);
29
- }
30
- return ids;
31
- }
32
-
33
- archive(sessionId) {
34
- const cfg = this._read();
35
- if (!cfg.sessions[sessionId]) {
36
- cfg.sessions[sessionId] = { archivedAt: new Date().toISOString() };
37
- this._write(cfg);
38
- }
39
- return cfg.sessions[sessionId];
40
- }
41
-
42
- restore(sessionId) {
43
- const cfg = this._read();
44
- if (!cfg.sessions[sessionId]) return false;
45
- delete cfg.sessions[sessionId];
46
- this._write(cfg);
47
- return true;
48
- }
49
-
50
- forget(sessionId) { this.restore(sessionId); }
51
- }
52
-
53
- module.exports = { SessionArchiveStore };
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { readJson, writeJson } = require('./json-file');
5
+
6
+ const SCHEMA = 'agent-terminal-session-archive/v1';
7
+
8
+ // Sidecar marking sessions the user archived. Session records themselves stay
9
+ // owned by the runner, so archiving never rewrites runner history — it only
10
+ // flips visibility in listings and can be undone at any time.
11
+ class SessionArchiveStore {
12
+ constructor(options = {}) {
13
+ if (!options.dataDir) throw new Error('SessionArchiveStore dataDir is required');
14
+ this.archiveFile = options.archiveFile || path.join(options.dataDir, 'archived-sessions.v1.json');
15
+ }
16
+
17
+ _read() { return readJson(this.archiveFile, { schema: SCHEMA, sessions: {} }); }
18
+ _write(cfg) { writeJson(this.archiveFile, cfg); }
19
+
20
+ isArchived(sessionId) { return Boolean(this._read().sessions[sessionId]); }
21
+ // Marks older than maxAgeMs. Entries without a parseable archivedAt never
22
+ // expire — deleting what cannot be dated is not a safe default.
23
+ expired(maxAgeMs, now = Date.now()) {
24
+ const cfg = this._read();
25
+ const ids = [];
26
+ for (const [sessionId, meta] of Object.entries(cfg.sessions)) {
27
+ const archivedAt = Date.parse(meta && meta.archivedAt);
28
+ if (Number.isFinite(archivedAt) && now - archivedAt > maxAgeMs) ids.push(sessionId);
29
+ }
30
+ return ids;
31
+ }
32
+
33
+ archive(sessionId) {
34
+ const cfg = this._read();
35
+ if (!cfg.sessions[sessionId]) {
36
+ cfg.sessions[sessionId] = { archivedAt: new Date().toISOString() };
37
+ this._write(cfg);
38
+ }
39
+ return cfg.sessions[sessionId];
40
+ }
41
+
42
+ restore(sessionId) {
43
+ const cfg = this._read();
44
+ if (!cfg.sessions[sessionId]) return false;
45
+ delete cfg.sessions[sessionId];
46
+ this._write(cfg);
47
+ return true;
48
+ }
49
+
50
+ forget(sessionId) { this.restore(sessionId); }
51
+ }
52
+
53
+ module.exports = { SessionArchiveStore };