@steerable/agent-shell 0.12.8 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/auth/credentials.d.ts +83 -0
  2. package/dist/auth/credentials.js +426 -0
  3. package/dist/auth/index.d.ts +33 -9
  4. package/dist/auth/index.js +85 -0
  5. package/dist/host/external-pack-loader.d.ts +40 -0
  6. package/dist/host/external-pack-loader.js +247 -0
  7. package/dist/host/http-routes.d.ts +6 -2
  8. package/dist/host/http-routes.js +5 -2
  9. package/dist/host/pack-assembly.d.ts +9 -1
  10. package/dist/host/runtime.js +54 -1
  11. package/dist/local-backend/coreloop-stream.d.ts +4 -0
  12. package/dist/local-backend/coreloop-stream.js +4 -0
  13. package/dist/local-backend/fact-chain.d.ts +38 -0
  14. package/dist/local-backend/fact-chain.js +145 -0
  15. package/dist/local-backend/router.d.ts +3 -1
  16. package/dist/local-backend/router.js +329 -35
  17. package/dist/local-backend/state-reconcile.d.ts +42 -0
  18. package/dist/local-backend/state-reconcile.js +81 -0
  19. package/dist/local-backend/title-refresh.d.ts +39 -0
  20. package/dist/local-backend/title-refresh.js +80 -0
  21. package/dist/local-backend/turn-security-context.d.ts +42 -0
  22. package/dist/local-backend/turn-security-context.js +62 -0
  23. package/dist/local-backend/ui-surface.d.ts +75 -0
  24. package/dist/local-backend/ui-surface.js +368 -0
  25. package/dist/local-executor.d.ts +3 -0
  26. package/dist/local-executor.js +40 -1
  27. package/dist/memory/authoring-candidates.d.ts +26 -0
  28. package/dist/memory/authoring-candidates.js +73 -0
  29. package/dist/memory/injector.d.ts +34 -0
  30. package/dist/memory/injector.js +111 -0
  31. package/dist/memory/routes.d.ts +16 -0
  32. package/dist/memory/routes.js +146 -0
  33. package/dist/memory/store.d.ts +176 -0
  34. package/dist/memory/store.js +623 -0
  35. package/dist/memory/tools.d.ts +83 -0
  36. package/dist/memory/tools.js +143 -0
  37. package/dist/present-files.d.ts +25 -1
  38. package/dist/present-files.js +170 -2
  39. package/dist/scenario/applications.d.ts +52 -0
  40. package/dist/scenario/applications.js +143 -0
  41. package/dist/scenario/pack.d.ts +1 -1
  42. package/dist/security/policy-digest.d.ts +28 -0
  43. package/dist/security/policy-digest.js +104 -0
  44. package/dist/server/http-server.js +23 -6
  45. package/dist/sidecar/boot.d.ts +1 -0
  46. package/dist/sidecar/boot.js +2 -0
  47. package/dist/sidecar/rejected-before-effect.d.ts +22 -0
  48. package/dist/sidecar/rejected-before-effect.js +63 -0
  49. package/dist/sidecar/reverse-approval.d.ts +2 -0
  50. package/dist/sidecar/reverse-approval.js +28 -5
  51. package/dist/sidecar/reverse-tools.d.ts +3 -0
  52. package/dist/sidecar/reverse-tools.js +129 -17
  53. package/dist/sidecar/types.d.ts +6 -0
  54. package/dist/storage/fde-fallback.d.ts +4 -0
  55. package/dist/storage/fde-fallback.js +354 -0
  56. package/dist/storage/fde-types.d.ts +215 -0
  57. package/dist/storage/fde-types.js +1 -0
  58. package/dist/storage/index.d.ts +113 -1
  59. package/dist/storage/index.js +797 -0
  60. package/dist/storage/insights-redact.d.ts +4 -1
  61. package/dist/storage/insights-redact.js +6 -1
  62. package/dist/storage/process-locks.d.ts +1 -1
  63. package/dist/storage/process-locks.js +1 -1
  64. package/dist/storage/scoped-store.d.ts +3 -1
  65. package/dist/tool-presentation.js +20 -0
  66. package/dist/tool-router.d.ts +20 -1
  67. package/dist/tool-router.js +76 -12
  68. package/package.json +5 -5
@@ -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 根)。凡运行时"会写进去、模型需要读回来"的目录都必须可读;
@@ -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;
@@ -126,6 +126,10 @@ export function toTurnTool(schema) {
126
126
  const category = schema.approval?.category;
127
127
  if (category)
128
128
  tool.approvalCategory = category;
129
+ if (schema.idempotent !== undefined)
130
+ tool.idempotent = schema.idempotent;
131
+ if (schema.checkpoint)
132
+ tool.checkpoint = schema.checkpoint;
129
133
  return tool;
130
134
  }
131
135
  /**
@@ -0,0 +1,38 @@
1
+ import type { ScopedStore } from '../storage/scoped-store.js';
2
+ export interface FactChainGraphDto {
3
+ readonly chatId: string;
4
+ readonly targetKind: 'message' | 'tool' | 'deliverable';
5
+ readonly targetId: string;
6
+ readonly requestNode: {
7
+ readonly status: 'recorded' | 'gap';
8
+ readonly model?: string;
9
+ readonly policyDigest?: string;
10
+ readonly systemPromptSummary?: string;
11
+ readonly attachmentHashes?: readonly string[];
12
+ readonly gapReason?: string;
13
+ };
14
+ readonly evidenceStatus: 'recorded' | 'no_tool_evidence' | 'gap';
15
+ readonly toolNodes: readonly {
16
+ readonly id: string;
17
+ readonly toolName: string;
18
+ readonly argsSummary: string;
19
+ readonly status: 'executed' | 'outcome_unknown' | 'failed';
20
+ readonly durationMs?: number;
21
+ }[];
22
+ readonly deliverableNode?: {
23
+ readonly id: string;
24
+ readonly fileName: string;
25
+ readonly filePath: string;
26
+ readonly verificationStatus: 'verified' | 'warnings' | 'failed' | 'unverified';
27
+ readonly verifierSummary?: string | null;
28
+ readonly snapshotSha256: string;
29
+ readonly workspaceState: 'unchanged' | 'modified' | 'deleted';
30
+ readonly snapshotDownloadUrl?: string | null;
31
+ } | null;
32
+ }
33
+ export declare function assembleFactChainGraph(options: {
34
+ readonly store: ScopedStore;
35
+ readonly chatId: string;
36
+ readonly targetKind: 'message' | 'tool' | 'deliverable';
37
+ readonly targetId: string;
38
+ }): Promise<FactChainGraphDto>;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Read-only Execution Provenance (`FactChainGraph`) assembler (R5-2).
3
+ *
4
+ * Reconstructs `requestNode -> toolNodes[] -> deliverableNode` strictly from
5
+ * authoritative host/ledger records without fabricating citations from assistant
6
+ * prose:
7
+ * - Missing request snapshot (e.g., imported legacy transcript) -> `status: 'gap'`
8
+ * - Zero tool calls in the turn -> `evidenceStatus: 'no_tool_evidence'`
9
+ * - Verified deliverable -> compares live workspace file SHA-256 against archived
10
+ * `snapshotSha256` to report `'unchanged' | 'modified' | 'deleted'`.
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import fs from 'node:fs/promises';
14
+ import { ensurePhase9Store } from '../storage/fde-fallback.js';
15
+ async function computeFileSha256OrNull(filePath) {
16
+ try {
17
+ const bytes = await fs.readFile(filePath);
18
+ return createHash('sha256').update(bytes).digest('hex');
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ async function buildDeliverableNode(chatId, deliv) {
25
+ const liveHash = await computeFileSha256OrNull(deliv.filePath);
26
+ const workspaceState = liveHash === null
27
+ ? 'deleted'
28
+ : liveHash === deliv.sha256
29
+ ? 'unchanged'
30
+ : 'modified';
31
+ return {
32
+ id: deliv.id,
33
+ fileName: deliv.fileName,
34
+ filePath: deliv.filePath,
35
+ verificationStatus: deliv.verificationStatus,
36
+ verifierSummary: deliv.summary,
37
+ snapshotSha256: deliv.sha256,
38
+ workspaceState,
39
+ snapshotDownloadUrl: deliv.reportPath
40
+ ? `/api/v2/chats/${encodeURIComponent(chatId)}/deliverables/${encodeURIComponent(deliv.id)}/snapshot`
41
+ : null,
42
+ };
43
+ }
44
+ export async function assembleFactChainGraph(options) {
45
+ const p9 = ensurePhase9Store(options.store);
46
+ const messages = await options.store.listMessages(options.chatId, 200);
47
+ const deliverables = await p9.listChatDeliverables(options.chatId);
48
+ let matchedDeliverable;
49
+ if (options.targetKind === 'deliverable') {
50
+ matchedDeliverable = deliverables.find((d) => d.id === options.targetId);
51
+ }
52
+ let matchedMessage = options.targetKind === 'message'
53
+ ? messages.find((m) => m.id === options.targetId)
54
+ : matchedDeliverable?.messageId
55
+ ? messages.find((m) => m.id === matchedDeliverable.messageId)
56
+ : undefined;
57
+ if (!matchedMessage && options.targetKind === 'tool') {
58
+ matchedMessage = messages.find((m) => {
59
+ if (!m.messageMetadata)
60
+ return false;
61
+ return m.messageMetadata.includes(options.targetId);
62
+ });
63
+ }
64
+ if (!matchedMessage) {
65
+ matchedMessage = messages.find((m) => m.role === 'assistant');
66
+ }
67
+ if (!matchedDeliverable && matchedMessage) {
68
+ matchedDeliverable =
69
+ deliverables.find((d) => d.messageId === matchedMessage.id) ?? deliverables[0];
70
+ }
71
+ let meta = null;
72
+ if (matchedMessage?.messageMetadata) {
73
+ try {
74
+ const parsed = JSON.parse(matchedMessage.messageMetadata);
75
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
76
+ meta = parsed;
77
+ }
78
+ }
79
+ catch {
80
+ meta = null;
81
+ }
82
+ }
83
+ const importedWithoutSnapshot = !meta ||
84
+ meta.imported === true ||
85
+ (meta.model === undefined &&
86
+ meta.traceId === undefined &&
87
+ meta.executedActions === undefined &&
88
+ meta.policyDigest === undefined);
89
+ const requestNode = importedWithoutSnapshot
90
+ ? {
91
+ status: 'gap',
92
+ gapReason: 'imported_without_request_snapshot',
93
+ }
94
+ : {
95
+ status: 'recorded',
96
+ ...(typeof meta?.model === 'string' ? { model: meta.model } : {}),
97
+ ...(typeof meta?.policyDigest === 'string'
98
+ ? { policyDigest: meta.policyDigest }
99
+ : {}),
100
+ ...(Array.isArray(meta?.attachmentHashes)
101
+ ? {
102
+ attachmentHashes: meta.attachmentHashes.filter((h) => typeof h === 'string'),
103
+ }
104
+ : {}),
105
+ };
106
+ const rawActions = Array.isArray(meta?.executedActions)
107
+ ? meta.executedActions
108
+ : [];
109
+ const toolNodes = rawActions.map((act, idx) => {
110
+ const id = typeof act.id === 'string' && act.id ? act.id : `tool_${idx + 1}`;
111
+ const toolName = String(act.tool ?? act.name ?? 'unknown');
112
+ const argsSummary = act.arguments ? JSON.stringify(act.arguments).slice(0, 200) : '';
113
+ const isUnknown = act.outcomeUnknown === true ||
114
+ (typeof act.error === 'string' && act.error.includes('outcome_unknown'));
115
+ const status = isUnknown
116
+ ? 'outcome_unknown'
117
+ : act.success === false
118
+ ? 'failed'
119
+ : 'executed';
120
+ return {
121
+ id,
122
+ toolName,
123
+ argsSummary,
124
+ status,
125
+ ...(typeof act.durationMs === 'number' ? { durationMs: act.durationMs } : {}),
126
+ };
127
+ });
128
+ const evidenceStatus = importedWithoutSnapshot && toolNodes.length === 0
129
+ ? 'gap'
130
+ : toolNodes.length === 0
131
+ ? 'no_tool_evidence'
132
+ : 'recorded';
133
+ const deliverableNode = matchedDeliverable
134
+ ? await buildDeliverableNode(options.chatId, matchedDeliverable)
135
+ : null;
136
+ return {
137
+ chatId: options.chatId,
138
+ targetKind: options.targetKind,
139
+ targetId: options.targetId,
140
+ requestNode,
141
+ evidenceStatus,
142
+ toolNodes,
143
+ deliverableNode,
144
+ };
145
+ }