@steerable/agent-shell 0.12.8 → 0.14.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.
Files changed (77) hide show
  1. package/dist/attachments/image-normalizer.d.ts +39 -0
  2. package/dist/attachments/image-normalizer.js +131 -0
  3. package/dist/auth/credentials.d.ts +83 -0
  4. package/dist/auth/credentials.js +426 -0
  5. package/dist/auth/index.d.ts +33 -9
  6. package/dist/auth/index.js +85 -0
  7. package/dist/host/external-pack-loader.d.ts +40 -0
  8. package/dist/host/external-pack-loader.js +247 -0
  9. package/dist/host/http-routes.d.ts +6 -2
  10. package/dist/host/http-routes.js +5 -2
  11. package/dist/host/pack-assembly.d.ts +9 -1
  12. package/dist/host/runtime.js +54 -1
  13. package/dist/image-attachment.js +10 -5
  14. package/dist/local-backend/coreloop-stream.d.ts +4 -0
  15. package/dist/local-backend/coreloop-stream.js +4 -0
  16. package/dist/local-backend/fact-chain.d.ts +38 -0
  17. package/dist/local-backend/fact-chain.js +145 -0
  18. package/dist/local-backend/router.d.ts +3 -1
  19. package/dist/local-backend/router.js +602 -45
  20. package/dist/local-backend/state-reconcile.d.ts +42 -0
  21. package/dist/local-backend/state-reconcile.js +81 -0
  22. package/dist/local-backend/title-refresh.d.ts +39 -0
  23. package/dist/local-backend/title-refresh.js +80 -0
  24. package/dist/local-backend/turn-security-context.d.ts +42 -0
  25. package/dist/local-backend/turn-security-context.js +62 -0
  26. package/dist/local-backend/ui-surface.d.ts +75 -0
  27. package/dist/local-backend/ui-surface.js +368 -0
  28. package/dist/local-executor.d.ts +3 -0
  29. package/dist/local-executor.js +40 -1
  30. package/dist/memory/authoring-candidates.d.ts +26 -0
  31. package/dist/memory/authoring-candidates.js +73 -0
  32. package/dist/memory/injector.d.ts +38 -0
  33. package/dist/memory/injector.js +122 -0
  34. package/dist/memory/routes.d.ts +16 -0
  35. package/dist/memory/routes.js +146 -0
  36. package/dist/memory/store.d.ts +176 -0
  37. package/dist/memory/store.js +623 -0
  38. package/dist/memory/tools.d.ts +83 -0
  39. package/dist/memory/tools.js +143 -0
  40. package/dist/present-files.d.ts +25 -1
  41. package/dist/present-files.js +170 -2
  42. package/dist/raster-image.d.ts +7 -1
  43. package/dist/raster-image.js +34 -0
  44. package/dist/scenario/applications.d.ts +52 -0
  45. package/dist/scenario/applications.js +143 -0
  46. package/dist/scenario/pack.d.ts +1 -1
  47. package/dist/security/policy-digest.d.ts +28 -0
  48. package/dist/security/policy-digest.js +104 -0
  49. package/dist/server/http-server.js +23 -6
  50. package/dist/sidecar/boot.d.ts +1 -0
  51. package/dist/sidecar/boot.js +2 -0
  52. package/dist/sidecar/index.d.ts +1 -1
  53. package/dist/sidecar/rejected-before-effect.d.ts +22 -0
  54. package/dist/sidecar/rejected-before-effect.js +63 -0
  55. package/dist/sidecar/reverse-approval.d.ts +2 -0
  56. package/dist/sidecar/reverse-approval.js +28 -5
  57. package/dist/sidecar/reverse-tools.d.ts +3 -0
  58. package/dist/sidecar/reverse-tools.js +146 -18
  59. package/dist/sidecar/supervisor.d.ts +31 -1
  60. package/dist/sidecar/supervisor.js +47 -0
  61. package/dist/sidecar/types.d.ts +72 -0
  62. package/dist/storage/fde-fallback.d.ts +4 -0
  63. package/dist/storage/fde-fallback.js +354 -0
  64. package/dist/storage/fde-types.d.ts +215 -0
  65. package/dist/storage/fde-types.js +1 -0
  66. package/dist/storage/index.d.ts +113 -1
  67. package/dist/storage/index.js +797 -0
  68. package/dist/storage/insights-redact.d.ts +4 -1
  69. package/dist/storage/insights-redact.js +6 -1
  70. package/dist/storage/process-locks.d.ts +1 -1
  71. package/dist/storage/process-locks.js +1 -1
  72. package/dist/storage/reliability-summary.d.ts +1 -1
  73. package/dist/storage/scoped-store.d.ts +3 -1
  74. package/dist/tool-presentation.js +20 -0
  75. package/dist/tool-router.d.ts +20 -1
  76. package/dist/tool-router.js +76 -12
  77. package/package.json +5 -5
@@ -1,14 +1,21 @@
1
1
  /**
2
- * Product-neutral authenticated identity attached to one local-backend request.
2
+ * Product-neutral authenticated identity, origin channel, and unauthenticated
3
+ * bootstrap discovery contracts.
3
4
  */
4
- export interface Principal {
5
- id: string;
6
- tenantId: string;
7
- displayName: string;
8
- email: string | null;
9
- roles: readonly string[];
10
- isAdmin: boolean;
11
- }
5
+ import type { OriginChannel, Principal, PublicBootstrapPayload } from '@steerable/pack-sdk';
6
+ export type { OriginChannel, Principal, PublicAuthMethod, PublicBootstrapPayload, } from '@steerable/pack-sdk';
7
+ /**
8
+ * Default local identity injected when running in single-user desktop, CLI,
9
+ * or loopback BS mode without an external AuthProvider.
10
+ */
11
+ export declare const LOCAL_DEFAULT_PRINCIPAL: Principal;
12
+ /**
13
+ * Normalizes an incoming channel hint from request headers, IPC metadata, or
14
+ * CLI options, falling back to `fallback` ('web' by default).
15
+ */
16
+ export declare function parseOriginChannel(value: unknown, fallback?: OriginChannel): OriginChannel;
17
+ /** True when a channel cannot host rich interactive approvals or workbenches. */
18
+ export declare function isRestrictedOriginChannel(channel: OriginChannel | undefined): boolean;
12
19
  export type AuthDecision = {
13
20
  ok: true;
14
21
  principal: Principal;
@@ -27,7 +34,13 @@ export interface AuthProvider {
27
34
  readonly id: string;
28
35
  authenticate(headers: Readonly<Record<string, string | string[] | undefined>>): Promise<AuthDecision>;
29
36
  describeSelf(principal: Principal): Promise<unknown>;
37
+ /**
38
+ * Optional public bootstrap descriptor returned before authentication by
39
+ * `GET /api/v2/auth/bootstrap`. Must never include secrets or private user data.
40
+ */
41
+ describeBootstrap?(headers: Readonly<Record<string, string | string[] | undefined>>): Promise<Partial<PublicBootstrapPayload>> | Partial<PublicBootstrapPayload>;
30
42
  }
43
+ export type PublicBootstrapResolver = (headers: Readonly<Record<string, string | string[] | undefined>>) => Promise<Partial<PublicBootstrapPayload>> | Partial<PublicBootstrapPayload>;
31
44
  /**
32
45
  * Registers the process-wide provider before the BS host starts.
33
46
  *
@@ -36,3 +49,14 @@ export interface AuthProvider {
36
49
  export declare function registerAuthProvider(provider: AuthProvider): () => void;
37
50
  /** Returns the provider registered by the product composition root, if any. */
38
51
  export declare function getAuthProvider(): AuthProvider | null;
52
+ /**
53
+ * Registers an optional override for `GET /api/v2/auth/bootstrap`.
54
+ */
55
+ export declare function registerBootstrapProvider(resolver: PublicBootstrapResolver): () => void;
56
+ /** Resets bootstrap override in tests. */
57
+ export declare function resetBootstrapProvider(): void;
58
+ /**
59
+ * Computes the unauthenticated `PublicBootstrapPayload` for login gates and
60
+ * preflight checks (`GET /api/v2/auth/bootstrap`).
61
+ */
62
+ export declare function resolvePublicBootstrap(headers?: Readonly<Record<string, string | string[] | undefined>>, extras?: Partial<PublicBootstrapPayload>): Promise<PublicBootstrapPayload>;
@@ -1,4 +1,42 @@
1
+ import { getBrand } from '../brand.js';
2
+ /**
3
+ * Default local identity injected when running in single-user desktop, CLI,
4
+ * or loopback BS mode without an external AuthProvider.
5
+ */
6
+ export const LOCAL_DEFAULT_PRINCIPAL = Object.freeze({
7
+ id: 'local',
8
+ tenantId: 'local',
9
+ displayName: 'Local User',
10
+ email: null,
11
+ roles: Object.freeze(['owner']),
12
+ isAdmin: true,
13
+ });
14
+ const VALID_ORIGIN_CHANNELS = new Set([
15
+ 'desktop',
16
+ 'web',
17
+ 'cli',
18
+ 'im',
19
+ 'webhook',
20
+ ]);
21
+ /**
22
+ * Normalizes an incoming channel hint from request headers, IPC metadata, or
23
+ * CLI options, falling back to `fallback` ('web' by default).
24
+ */
25
+ export function parseOriginChannel(value, fallback = 'web') {
26
+ const raw = Array.isArray(value) ? value[0] : value;
27
+ if (typeof raw === 'string') {
28
+ const trimmed = raw.trim().toLowerCase();
29
+ if (VALID_ORIGIN_CHANNELS.has(trimmed))
30
+ return trimmed;
31
+ }
32
+ return fallback;
33
+ }
34
+ /** True when a channel cannot host rich interactive approvals or workbenches. */
35
+ export function isRestrictedOriginChannel(channel) {
36
+ return channel === 'im' || channel === 'webhook';
37
+ }
1
38
  let activeProvider = null;
39
+ let bootstrapResolver = null;
2
40
  /**
3
41
  * Registers the process-wide provider before the BS host starts.
4
42
  *
@@ -18,3 +56,50 @@ export function registerAuthProvider(provider) {
18
56
  export function getAuthProvider() {
19
57
  return activeProvider;
20
58
  }
59
+ /**
60
+ * Registers an optional override for `GET /api/v2/auth/bootstrap`.
61
+ */
62
+ export function registerBootstrapProvider(resolver) {
63
+ bootstrapResolver = resolver;
64
+ return () => {
65
+ if (bootstrapResolver === resolver)
66
+ bootstrapResolver = null;
67
+ };
68
+ }
69
+ /** Resets bootstrap override in tests. */
70
+ export function resetBootstrapProvider() {
71
+ bootstrapResolver = null;
72
+ }
73
+ /**
74
+ * Computes the unauthenticated `PublicBootstrapPayload` for login gates and
75
+ * preflight checks (`GET /api/v2/auth/bootstrap`).
76
+ */
77
+ export async function resolvePublicBootstrap(headers = {}, extras) {
78
+ const brand = getBrand();
79
+ const fromProvider = activeProvider?.describeBootstrap
80
+ ? await activeProvider.describeBootstrap(headers)
81
+ : undefined;
82
+ const fromOverride = bootstrapResolver
83
+ ? await bootstrapResolver(headers)
84
+ : undefined;
85
+ const merged = {
86
+ ...fromProvider,
87
+ ...fromOverride,
88
+ ...extras,
89
+ };
90
+ const authRequired = merged.authRequired ?? Boolean(activeProvider);
91
+ const authMethods = merged.authMethods ??
92
+ (authRequired
93
+ ? [{ kind: 'password', showTenantSlugInput: true }]
94
+ : []);
95
+ return {
96
+ productName: merged.productName ?? brand.displayName,
97
+ authRequired,
98
+ authMethods,
99
+ ...(merged.iamMode !== undefined ? { iamMode: merged.iamMode } : {}),
100
+ ...(merged.defaultApplicationId !== undefined
101
+ ? { defaultApplicationId: merged.defaultApplicationId }
102
+ : {}),
103
+ ...(merged.safeMode !== undefined ? { safeMode: merged.safeMode } : {}),
104
+ };
105
+ }
@@ -0,0 +1,40 @@
1
+ import type { ScenarioPack } from '@steerable/pack-sdk';
2
+ export declare const EXIT_PACK_INTEGRITY_FAILED = 78;
3
+ export interface SignedPackManifest {
4
+ readonly formatVersion: 1;
5
+ readonly packId: string;
6
+ readonly version: string;
7
+ readonly steerableApiRange: string;
8
+ readonly entry: string;
9
+ readonly files: Readonly<Record<string, string>>;
10
+ readonly signatureHex?: string;
11
+ }
12
+ export declare class ExternalPackIntegrityError extends Error {
13
+ readonly exitCode = 78;
14
+ readonly code: string;
15
+ constructor(code: string, message: string);
16
+ }
17
+ export declare function generatePackSigningKeypair(): {
18
+ readonly publicKeyDerHex: string;
19
+ readonly privateKeyDerHex: string;
20
+ };
21
+ export declare function satisfiesSimpleApiRange(hostVersion: string, range: string): boolean;
22
+ export declare function bundleSignedPack(options: {
23
+ readonly packDir: string;
24
+ readonly outFile: string;
25
+ readonly privateKeyDerHex?: string;
26
+ }): SignedPackManifest;
27
+ export declare function verifyUnpackedPackDirectory(options: {
28
+ readonly dir: string;
29
+ readonly publicKeyDerHex?: string;
30
+ readonly hostVersion?: string;
31
+ }): SignedPackManifest;
32
+ export declare function loadVerifiedExternalPacks(options: {
33
+ readonly packPaths: readonly string[];
34
+ readonly publicKeyDerHex?: string;
35
+ readonly hostVersion?: string;
36
+ readonly extractParentDir?: string;
37
+ }): Promise<{
38
+ readonly packs: ScenarioPack[];
39
+ readonly cleanup: () => void;
40
+ }>;
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Out-of-tree signed `.spack.tgz` pack bundler, Ed25519 signature verifier,
3
+ * symlink guard, and `STEERABLE_PACK_DIRS` startup loader (Phase 9 R6).
4
+ *
5
+ * Fail-closed contract (`T-FDE-02` & `T-FDE-03`):
6
+ * - Any symlink inside a pack archive/directory is rejected.
7
+ * - Any file SHA-256 mismatch against `manifest.sig.json` is rejected.
8
+ * - When `STEERABLE_PACK_PUBLIC_KEY` (or `publicKeyHex`) is set, missing or invalid
9
+ * Ed25519 signatures are rejected.
10
+ * - Incompatible `steerableApiRange` is rejected.
11
+ * - Startup integrity failures surface exit code `78` (`EX_CONFIG`).
12
+ */
13
+ import { execFileSync } from 'node:child_process';
14
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify, } from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { pathToFileURL } from 'node:url';
19
+ export const EXIT_PACK_INTEGRITY_FAILED = 78;
20
+ export class ExternalPackIntegrityError extends Error {
21
+ exitCode = EXIT_PACK_INTEGRITY_FAILED;
22
+ code;
23
+ constructor(code, message) {
24
+ super(message);
25
+ this.name = 'ExternalPackIntegrityError';
26
+ this.code = code;
27
+ }
28
+ }
29
+ export function generatePackSigningKeypair() {
30
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
31
+ return {
32
+ publicKeyDerHex: publicKey.export({ type: 'spki', format: 'der' }).toString('hex'),
33
+ privateKeyDerHex: privateKey.export({ type: 'pkcs8', format: 'der' }).toString('hex'),
34
+ };
35
+ }
36
+ function canonicalManifestPayload(manifest) {
37
+ const sortedFiles = Object.fromEntries(Object.entries(manifest.files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
38
+ return JSON.stringify({
39
+ formatVersion: manifest.formatVersion,
40
+ packId: manifest.packId,
41
+ version: manifest.version,
42
+ steerableApiRange: manifest.steerableApiRange,
43
+ entry: manifest.entry,
44
+ files: sortedFiles,
45
+ });
46
+ }
47
+ function scanDirectoryNoSymlinks(rootDir, relPrefix = '') {
48
+ const files = {};
49
+ const entries = fs.readdirSync(rootDir, { withFileTypes: true });
50
+ for (const entry of entries) {
51
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'manifest.sig.json') {
52
+ continue;
53
+ }
54
+ const full = path.join(rootDir, entry.name);
55
+ const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
56
+ const lstat = fs.lstatSync(full);
57
+ if (lstat.isSymbolicLink()) {
58
+ throw new ExternalPackIntegrityError('pack_symlink_forbidden', `Symlink "${rel}" is forbidden inside a signed scenario pack.`);
59
+ }
60
+ if (lstat.isDirectory()) {
61
+ Object.assign(files, scanDirectoryNoSymlinks(full, rel));
62
+ }
63
+ else if (lstat.isFile()) {
64
+ const bytes = fs.readFileSync(full);
65
+ files[rel] = createHash('sha256').update(bytes).digest('hex');
66
+ }
67
+ }
68
+ return files;
69
+ }
70
+ export function satisfiesSimpleApiRange(hostVersion, range) {
71
+ const trimmed = range.trim();
72
+ if (!trimmed || trimmed === '*')
73
+ return true;
74
+ const parseSemver = (v) => {
75
+ const m = v.trim().replace(/^v/, '').match(/^(\d+)\.(\d+)\.(\d+)/);
76
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
77
+ };
78
+ const hv = parseSemver(hostVersion);
79
+ if (!hv)
80
+ return false;
81
+ const cmp = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
82
+ if (trimmed.startsWith('^')) {
83
+ const rv = parseSemver(trimmed.slice(1));
84
+ if (!rv)
85
+ return false;
86
+ if (rv[0] === 0) {
87
+ return hv[0] === 0 && hv[1] === rv[1] && hv[2] >= rv[2];
88
+ }
89
+ return hv[0] === rv[0] && cmp(hv, rv) >= 0;
90
+ }
91
+ if (trimmed.startsWith('>=')) {
92
+ const rv = parseSemver(trimmed.slice(2));
93
+ return rv ? cmp(hv, rv) >= 0 : false;
94
+ }
95
+ const exact = parseSemver(trimmed);
96
+ return exact ? cmp(hv, exact) === 0 : false;
97
+ }
98
+ export function bundleSignedPack(options) {
99
+ const pkgPath = path.join(options.packDir, 'package.json');
100
+ if (!fs.existsSync(pkgPath)) {
101
+ throw new ExternalPackIntegrityError('missing_package_json', `Pack directory "${options.packDir}" is missing package.json`);
102
+ }
103
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
104
+ const packId = pkg.steerablePack?.id || pkg.name || path.basename(options.packDir);
105
+ const version = pkg.version || '0.1.0';
106
+ const steerableApiRange = pkg.steerablePack?.steerableApiRange || '^0.12.0';
107
+ const entry = pkg.steerablePack?.entry || pkg.main || 'dist/index.js';
108
+ const files = scanDirectoryNoSymlinks(options.packDir);
109
+ if (!files[entry]) {
110
+ throw new ExternalPackIntegrityError('missing_pack_entry', `Pack entry "${entry}" was not found in "${options.packDir}" (build the pack before bundling).`);
111
+ }
112
+ const unsigned = {
113
+ formatVersion: 1,
114
+ packId,
115
+ version,
116
+ steerableApiRange,
117
+ entry,
118
+ files,
119
+ };
120
+ let signatureHex;
121
+ if (options.privateKeyDerHex) {
122
+ const privKey = createPrivateKey({
123
+ key: Buffer.from(options.privateKeyDerHex, 'hex'),
124
+ format: 'der',
125
+ type: 'pkcs8',
126
+ });
127
+ const payloadBuf = Buffer.from(canonicalManifestPayload(unsigned), 'utf8');
128
+ signatureHex = sign(null, payloadBuf, privKey).toString('hex');
129
+ }
130
+ const manifest = {
131
+ ...unsigned,
132
+ ...(signatureHex ? { signatureHex } : {}),
133
+ };
134
+ const stageDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spack-bundle-'));
135
+ try {
136
+ for (const rel of Object.keys(files)) {
137
+ const src = path.join(options.packDir, rel);
138
+ const dst = path.join(stageDir, rel);
139
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
140
+ fs.copyFileSync(src, dst);
141
+ }
142
+ fs.writeFileSync(path.join(stageDir, 'manifest.sig.json'), JSON.stringify(manifest, null, 2), 'utf8');
143
+ fs.mkdirSync(path.dirname(path.resolve(options.outFile)), { recursive: true });
144
+ execFileSync('tar', ['-czf', path.resolve(options.outFile), '-C', stageDir, '.']);
145
+ }
146
+ finally {
147
+ fs.rmSync(stageDir, { recursive: true, force: true });
148
+ }
149
+ return manifest;
150
+ }
151
+ export function verifyUnpackedPackDirectory(options) {
152
+ const sigPath = path.join(options.dir, 'manifest.sig.json');
153
+ if (!fs.existsSync(sigPath)) {
154
+ throw new ExternalPackIntegrityError('missing_manifest_sig', `External pack "${options.dir}" is missing manifest.sig.json`);
155
+ }
156
+ const manifest = JSON.parse(fs.readFileSync(sigPath, 'utf8'));
157
+ if (options.hostVersion && !satisfiesSimpleApiRange(options.hostVersion, manifest.steerableApiRange)) {
158
+ throw new ExternalPackIntegrityError('api_range_mismatch', `Pack "${manifest.packId}" requires steerableApiRange "${manifest.steerableApiRange}", incompatible with host "${options.hostVersion}"`);
159
+ }
160
+ if (options.publicKeyDerHex) {
161
+ if (!manifest.signatureHex) {
162
+ throw new ExternalPackIntegrityError('missing_signature', `Pack "${manifest.packId}" is unsigned, but STEERABLE_PACK_PUBLIC_KEY requires Ed25519 signature verification`);
163
+ }
164
+ const pubKey = createPublicKey({
165
+ key: Buffer.from(options.publicKeyDerHex, 'hex'),
166
+ format: 'der',
167
+ type: 'spki',
168
+ });
169
+ const payloadBuf = Buffer.from(canonicalManifestPayload(manifest), 'utf8');
170
+ const ok = verify(null, payloadBuf, pubKey, Buffer.from(manifest.signatureHex, 'hex'));
171
+ if (!ok) {
172
+ throw new ExternalPackIntegrityError('invalid_signature', `Ed25519 signature verification failed for pack "${manifest.packId}"`);
173
+ }
174
+ }
175
+ // Scan actual unpacked files (enforces zero symlinks + exact file set + exact SHA-256!)
176
+ const actualFiles = scanDirectoryNoSymlinks(options.dir);
177
+ const expectedKeys = Object.keys(manifest.files).sort();
178
+ const actualKeys = Object.keys(actualFiles).sort();
179
+ if (expectedKeys.join('\n') !== actualKeys.join('\n')) {
180
+ throw new ExternalPackIntegrityError('file_inventory_mismatch', `Pack "${manifest.packId}" file list differs from signed manifest`);
181
+ }
182
+ for (const rel of expectedKeys) {
183
+ if (actualFiles[rel] !== manifest.files[rel]) {
184
+ throw new ExternalPackIntegrityError('file_hash_mismatch', `File "${rel}" in pack "${manifest.packId}" failed SHA-256 integrity check`);
185
+ }
186
+ }
187
+ return manifest;
188
+ }
189
+ export async function loadVerifiedExternalPacks(options) {
190
+ const tempDirs = [];
191
+ const packs = [];
192
+ try {
193
+ for (const rawTarget of options.packPaths) {
194
+ const target = rawTarget.trim();
195
+ if (!target)
196
+ continue;
197
+ if (!fs.existsSync(target)) {
198
+ throw new ExternalPackIntegrityError('pack_not_found', `External pack path does not exist: "${target}"`);
199
+ }
200
+ let mountDir = target;
201
+ const st = fs.lstatSync(target);
202
+ if (st.isSymbolicLink()) {
203
+ throw new ExternalPackIntegrityError('pack_symlink_forbidden', `External pack path "${target}" must not be a symlink`);
204
+ }
205
+ if (st.isFile() && (target.endsWith('.spack.tgz') || target.endsWith('.tgz'))) {
206
+ // Pre-scan tar entries for symlinks or path traversal (`..`) before extracting
207
+ const listing = execFileSync('tar', ['-tvzf', target], { encoding: 'utf8' });
208
+ for (const line of listing.split('\n')) {
209
+ if (!line.trim())
210
+ continue;
211
+ if (line.startsWith('l') || line.includes(' -> ') || /(?:^|\/)\.\.(?:\/|$)/.test(line)) {
212
+ throw new ExternalPackIntegrityError('pack_symlink_or_traversal', `Archive "${target}" contains forbidden symlink or path traversal entry: ${line}`);
213
+ }
214
+ }
215
+ mountDir = fs.mkdtempSync(path.join(options.extractParentDir ?? os.tmpdir(), 'spack-mount-'));
216
+ tempDirs.push(mountDir);
217
+ execFileSync('tar', ['-xzf', target, '-C', mountDir]);
218
+ }
219
+ const manifest = verifyUnpackedPackDirectory({
220
+ dir: mountDir,
221
+ publicKeyDerHex: options.publicKeyDerHex,
222
+ hostVersion: options.hostVersion,
223
+ });
224
+ const entryPath = path.join(mountDir, manifest.entry);
225
+ const mod = (await import(pathToFileURL(entryPath).href));
226
+ const loaded = mod.default ?? mod.pack;
227
+ if (!loaded || typeof loaded.id !== 'string') {
228
+ throw new ExternalPackIntegrityError('invalid_pack_export', `Pack "${manifest.packId}" entry "${manifest.entry}" did not export a valid ScenarioPack`);
229
+ }
230
+ packs.push(loaded);
231
+ }
232
+ return {
233
+ packs,
234
+ cleanup: () => {
235
+ for (const d of tempDirs) {
236
+ fs.rmSync(d, { recursive: true, force: true });
237
+ }
238
+ },
239
+ };
240
+ }
241
+ catch (err) {
242
+ for (const d of tempDirs) {
243
+ fs.rmSync(d, { recursive: true, force: true });
244
+ }
245
+ throw err;
246
+ }
247
+ }
@@ -6,7 +6,7 @@
6
6
  * 按注册顺序精确/段参数匹配。路径必须带 `/host/<packId>/` 前缀——与 IPC
7
7
  * 通道的 `<packId>:` 前缀同一命名空间纪律。
8
8
  */
9
- import type { HttpRouteContribution, HttpRouteRequest } from '../scenario/pack.js';
9
+ import type { HttpRouteContribution, HttpRouteRequest, OriginChannel, Principal } from '../scenario/pack.js';
10
10
  export type { HttpRouteContribution, HttpRouteRequest };
11
11
  /** 注册包 HTTP 路由;路径越出包前缀直接抛错(组装期失败,不进运行时)。 */
12
12
  export declare function registerPackHttpRoutes(packId: string, routes: readonly HttpRouteContribution[]): void;
@@ -14,7 +14,11 @@ export declare function registerPackHttpRoutes(packId: string, routes: readonly
14
14
  * 进程内路由器调用包的 `/host/<packId>/*` 路由。
15
15
  * 处理器直接返回数据,这里包成 `{ status, data }`。
16
16
  */
17
- export declare function invokePackHttpRoute(method: string, pathname: string, body: unknown): Promise<{
17
+ export declare function invokePackHttpRoute(method: string, pathname: string, body: unknown, context?: {
18
+ principal?: Principal;
19
+ originChannel?: OriginChannel;
20
+ query?: Record<string, string>;
21
+ }): Promise<{
18
22
  status: number;
19
23
  data: unknown;
20
24
  } | null>;
@@ -6,6 +6,7 @@
6
6
  * 按注册顺序精确/段参数匹配。路径必须带 `/host/<packId>/` 前缀——与 IPC
7
7
  * 通道的 `<packId>:` 前缀同一命名空间纪律。
8
8
  */
9
+ import { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
9
10
  const packHttpRoutes = [];
10
11
  function assertPackRoutePath(packId, path) {
11
12
  if (!path.startsWith(`/host/${packId}/`)) {
@@ -26,14 +27,16 @@ export function registerPackHttpRoutes(packId, routes) {
26
27
  * 进程内路由器调用包的 `/host/<packId>/*` 路由。
27
28
  * 处理器直接返回数据,这里包成 `{ status, data }`。
28
29
  */
29
- export async function invokePackHttpRoute(method, pathname, body) {
30
+ export async function invokePackHttpRoute(method, pathname, body, context) {
30
31
  const match = matchPackHttpRoute(method, pathname);
31
32
  if (!match)
32
33
  return null;
33
34
  const data = await match.route.handler({
34
35
  params: match.params,
35
- query: {},
36
+ query: context?.query ?? {},
36
37
  body,
38
+ principal: Object.freeze({ ...(context?.principal ?? LOCAL_DEFAULT_PRINCIPAL) }),
39
+ originChannel: context?.originChannel ?? 'web',
37
40
  });
38
41
  return { status: 200, data };
39
42
  }
@@ -13,7 +13,7 @@
13
13
  * server/index.ts 消费 handle.httpRoutes——包的入口面贡献由宿主循环驱动,
14
14
  * 宿主代码里不出现任何包名。
15
15
  */
16
- import type { HttpRouteContribution, ToolContribution } from '../scenario/pack.js';
16
+ import type { AgentProfileSpec, ApplicationManifest, DeliverableVerifier, HttpRouteContribution, PackDataSource, ToolContribution } from '../scenario/pack.js';
17
17
  import type { PackDbAccess } from '../storage/driver.js';
18
18
  /** 宿主注入包的装配能力面。包不 import 宿主装配模块,全部经回调注入。 */
19
19
  export interface PackAssemblyDeps {
@@ -34,6 +34,14 @@ export interface PackAssemblyDeps {
34
34
  readonly broadcast: (channel: string, payload: unknown) => void;
35
35
  /** 工具贡献注册口(toolRouter.registerToolContributions 的收窄面)。 */
36
36
  readonly registerTools: (tools: readonly ToolContribution[]) => void;
37
+ /** 外部数据源声明注册口(R1)。 */
38
+ readonly registerDataSources?: (items: readonly PackDataSource[]) => void;
39
+ /** 交付物质检钩子注册口(R5)。 */
40
+ readonly registerDeliverableVerifiers?: (items: readonly DeliverableVerifier[]) => void;
41
+ /** Agent Profile 注册口(R3)。 */
42
+ readonly registerAgentProfiles?: (items: readonly AgentProfileSpec[]) => void;
43
+ /** Application 应用形态注册口(R3)。 */
44
+ readonly registerApplications?: (items: readonly ApplicationManifest[]) => void;
37
45
  /** 用量归因(包的独立流不经 router 记账路径,不注入会静默漏账)。 */
38
46
  readonly recordUsage: (input: {
39
47
  chatId: string;
@@ -44,6 +44,9 @@ import { llmService } from '../llm/index.js';
44
44
  import { isProductLlmLocked, resolveRuntimeLlmSettings } from '../host-tools-runtime.js';
45
45
  import { getPackAssemblies, } from './pack-assembly.js';
46
46
  import { registerPackHttpRoutes } from './http-routes.js';
47
+ import { registerAgentProfiles, registerApplications, registerDeliverableVerifiers, registerPackDataSources, } from '../scenario/applications.js';
48
+ import { bindHostPendingCounters } from '../local-backend/turn-security-context.js';
49
+ import { ExternalPackIntegrityError, loadVerifiedExternalPacks, } from './external-pack-loader.js';
47
50
  /**
48
51
  * spill 目录作为只读根:工具输出超过内联上限时 sidecar 会把全文落到
49
52
  * ``STEERABLE_SPILL_DIR``(BS 宿主由 run-bs-server.mjs 设为
@@ -177,7 +180,14 @@ export async function createHostRuntime(options) {
177
180
  // 单例求值)——构造时注册表尚空,此处(装配前)补上已注册包迁移。
178
181
  // 幂等(按包 id 去重),注册表为空时零开销。
179
182
  for (const [packId, assemble] of getPackAssemblies()) {
180
- const handle = assemble(packDeps);
183
+ const scopedDeps = {
184
+ ...packDeps,
185
+ registerDataSources: (items) => registerPackDataSources(packId, items),
186
+ registerDeliverableVerifiers: (items) => registerDeliverableVerifiers(packId, items),
187
+ registerAgentProfiles: (items) => registerAgentProfiles(packId, items),
188
+ registerApplications: (items) => registerApplications(packId, items),
189
+ };
190
+ const handle = assemble(scopedDeps);
181
191
  if (handle)
182
192
  packHandles.set(packId, handle);
183
193
  }
@@ -187,6 +197,44 @@ export async function createHostRuntime(options) {
187
197
  if (routes && routes.length > 0)
188
198
  registerPackHttpRoutes(packId, routes);
189
199
  }
200
+ const externalPackDirsRaw = process.env.STEERABLE_PACK_DIRS?.trim();
201
+ if (externalPackDirsRaw) {
202
+ const paths = externalPackDirsRaw
203
+ .split(process.platform === 'win32' ? ';' : ':')
204
+ .map((s) => s.trim())
205
+ .filter(Boolean);
206
+ try {
207
+ const mounted = await loadVerifiedExternalPacks({
208
+ packPaths: paths,
209
+ publicKeyDerHex: process.env.STEERABLE_PACK_PUBLIC_KEY?.trim() || undefined,
210
+ });
211
+ for (const extPack of mounted.packs) {
212
+ if (extPack.main?.tools)
213
+ toolRouter.registerToolContributions(extPack.main.tools);
214
+ if (extPack.main?.dataSources)
215
+ registerPackDataSources(extPack.id, extPack.main.dataSources);
216
+ if (extPack.main?.deliverableVerifiers) {
217
+ registerDeliverableVerifiers(extPack.id, extPack.main.deliverableVerifiers);
218
+ }
219
+ if (extPack.main?.agentProfiles) {
220
+ registerAgentProfiles(extPack.id, extPack.main.agentProfiles);
221
+ }
222
+ if (extPack.main?.applications) {
223
+ registerApplications(extPack.id, extPack.main.applications);
224
+ }
225
+ if (extPack.main?.httpRoutes) {
226
+ registerPackHttpRoutes(extPack.id, extPack.main.httpRoutes);
227
+ }
228
+ }
229
+ }
230
+ catch (err) {
231
+ if (err instanceof ExternalPackIntegrityError) {
232
+ onLog(`[packs] FATAL integrity failure (${err.code}): ${err.message}`);
233
+ process.exit(err.exitCode);
234
+ }
235
+ throw err;
236
+ }
237
+ }
190
238
  const worktreeService = new WorktreeService({ resolveProject: resolveChatProjectRoot });
191
239
  const taskService = new TaskService({
192
240
  store: () => localBackendRouter?.activeStore ?? defaultStore,
@@ -269,6 +317,10 @@ export async function createHostRuntime(options) {
269
317
  onLog: (line) => onLog(line),
270
318
  });
271
319
  localBackendRouter.setAskReplay((chatId) => askUserBridge.takeResolved(chatId));
320
+ bindHostPendingCounters({
321
+ pendingApprovals: () => approvalBridge.pending().length,
322
+ pendingQuestions: () => askUserBridge.pending().length,
323
+ });
272
324
  let started = false;
273
325
  let instanceLease = null;
274
326
  let warmTimer = null;
@@ -304,6 +356,7 @@ export async function createHostRuntime(options) {
304
356
  await startHostSidecar({
305
357
  store: defaultStore,
306
358
  toolRouter,
359
+ broadcast,
307
360
  resolveProjectRoot: async (chatId) => localBackendRouter.resolveChatWorkspaceRoot(chatId),
308
361
  // 读:附件目录、源文件夹、包声明的可写根,以及只读参考面(技能根 /
309
362
  // spill 根)。凡运行时"会写进去、模型需要读回来"的目录都必须可读;
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { readFileSync, statSync } from 'fs';
22
22
  import { basename, extname } from 'path';
23
+ import { MODEL_IMAGE_JPEG_QUALITY, MODEL_IMAGE_REENCODE_THRESHOLD_BYTES, } from './attachments/image-normalizer.js';
23
24
  import { builtinRasterSupports, createRasterImageDecoder } from './raster-image.js';
24
25
  /** Refuse to read source files larger than this (10 MB). */
25
26
  export const IMAGE_MAX_SOURCE_BYTES = 10 * 1024 * 1024;
@@ -153,9 +154,11 @@ export function processViewImage(input, decoder) {
153
154
  const outputFormat = input.format ?? (['.jpg', '.jpeg'].includes(sourceExt) ? 'jpeg' : 'png');
154
155
  let mediaType = outputFormat === 'jpeg' ? 'image/jpeg' : 'image/png';
155
156
  let buffer = outputFormat === 'jpeg' ? rendered.toJPEG(85) : rendered.toPNG();
156
- if (buffer.length > IMAGE_MAX_ENCODED_BYTES && input.format == null && outputFormat === 'png') {
157
+ if (buffer.length > MODEL_IMAGE_REENCODE_THRESHOLD_BYTES &&
158
+ input.format == null &&
159
+ outputFormat === 'png') {
157
160
  mediaType = 'image/jpeg';
158
- buffer = rendered.toJPEG(80);
161
+ buffer = rendered.toJPEG(MODEL_IMAGE_JPEG_QUALITY);
159
162
  }
160
163
  if (buffer.length > IMAGE_MAX_ENCODED_BYTES) {
161
164
  return {
@@ -343,13 +346,15 @@ export function processImageAttachments(files, decoder) {
343
346
  const rendered = target.resized
344
347
  ? image.resize({ width: target.width, height: target.height, quality: 'good' })
345
348
  : image;
346
- // PNG for graphics/screenshots (lossless), JPEG for photos (smaller).
349
+ // PNG for compact graphics/screenshots, JPEG for photos or PNGs over 512 KiB
350
+ // so Retina/4K screenshots never blow the 4 MiB gateway request ceiling while
351
+ // keeping the original file on disk completely untouched (R2 dual-track).
347
352
  const preferJpeg = ['.jpg', '.jpeg'].includes(extname(file.path).toLowerCase());
348
353
  let mediaType = preferJpeg ? 'image/jpeg' : 'image/png';
349
354
  let buffer = preferJpeg ? rendered.toJPEG(85) : rendered.toPNG();
350
- if (buffer.length > IMAGE_MAX_ENCODED_BYTES && mediaType !== 'image/jpeg') {
355
+ if (buffer.length > MODEL_IMAGE_REENCODE_THRESHOLD_BYTES && mediaType !== 'image/jpeg') {
351
356
  mediaType = 'image/jpeg';
352
- buffer = rendered.toJPEG(80);
357
+ buffer = rendered.toJPEG(MODEL_IMAGE_JPEG_QUALITY);
353
358
  }
354
359
  if (buffer.length > IMAGE_MAX_ENCODED_BYTES) {
355
360
  notes.push(`- ${label}:压缩后仍超过 ${formatMb(IMAGE_MAX_ENCODED_BYTES)}MB,未附加`);
@@ -127,6 +127,8 @@ export interface TurnToolWire {
127
127
  inputSchema: unknown;
128
128
  mode?: string;
129
129
  approvalCategory?: string;
130
+ idempotent?: boolean;
131
+ checkpoint?: 'standard' | 'outward';
130
132
  }
131
133
  /**
132
134
  * 把宿主工具 schema 收成线协议上的一项。未声明审批类别时不带 `approvalCategory`,
@@ -140,6 +142,8 @@ export declare function toTurnTool(schema: {
140
142
  approval?: {
141
143
  category?: string;
142
144
  } | null;
145
+ idempotent?: boolean;
146
+ checkpoint?: 'standard' | 'outward';
143
147
  }): TurnToolWire;
144
148
  export interface StreamCoreLoopTurnOptions {
145
149
  supervisor: SidecarSupervisor;