@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
@@ -0,0 +1,143 @@
1
+ import { getBrand } from '../brand.js';
2
+ import { ensurePhase9Store } from '../storage/fde-fallback.js';
3
+ export const ACTIVE_APPLICATION_SETTING_KEY = 'active_application_id';
4
+ export const DEFAULT_APPLICATION_ID = 'default';
5
+ const dataSources = new Map();
6
+ const agentProfiles = new Map();
7
+ const applications = new Map();
8
+ const deliverableVerifiers = new Map();
9
+ export function registerPackDataSources(packId, items) {
10
+ for (const item of items) {
11
+ if (!item.id.trim()) {
12
+ throw new Error(`[packs] dataSource in pack "${packId}" has empty id`);
13
+ }
14
+ if (dataSources.has(item.id)) {
15
+ throw new Error(`[packs] duplicate dataSource id "${item.id}" from pack "${packId}"`);
16
+ }
17
+ dataSources.set(item.id, item);
18
+ }
19
+ }
20
+ export function getRegisteredDataSource(sourceId) {
21
+ return dataSources.get(sourceId) ?? null;
22
+ }
23
+ export function listRegisteredDataSources() {
24
+ return [...dataSources.values()];
25
+ }
26
+ export function registerAgentProfiles(packId, items) {
27
+ for (const item of items) {
28
+ if (!item.id.trim()) {
29
+ throw new Error(`[packs] agentProfile in pack "${packId}" has empty id`);
30
+ }
31
+ if (agentProfiles.has(item.id)) {
32
+ throw new Error(`[packs] duplicate agentProfile id "${item.id}" from pack "${packId}"`);
33
+ }
34
+ agentProfiles.set(item.id, item);
35
+ }
36
+ }
37
+ export function getRegisteredAgentProfile(profileId) {
38
+ return agentProfiles.get(profileId) ?? null;
39
+ }
40
+ export function listRegisteredAgentProfiles() {
41
+ return [...agentProfiles.values()];
42
+ }
43
+ export function registerApplications(packId, items) {
44
+ for (const item of items) {
45
+ if (!item.id.trim() || item.id === DEFAULT_APPLICATION_ID) {
46
+ throw new Error(`[packs] invalid application id "${item.id}" in pack "${packId}" ("default" is reserved)`);
47
+ }
48
+ if (applications.has(item.id)) {
49
+ throw new Error(`[packs] duplicate application id "${item.id}" from pack "${packId}"`);
50
+ }
51
+ applications.set(item.id, item);
52
+ }
53
+ }
54
+ export function getRegisteredApplication(appId) {
55
+ return applications.get(appId) ?? null;
56
+ }
57
+ export function listRegisteredApplications() {
58
+ return [...applications.values()];
59
+ }
60
+ export function registerDeliverableVerifiers(packId, items) {
61
+ for (const item of items) {
62
+ if (!item.id.trim()) {
63
+ throw new Error(`[packs] deliverableVerifier in pack "${packId}" has empty id`);
64
+ }
65
+ if (deliverableVerifiers.has(item.id)) {
66
+ throw new Error(`[packs] duplicate deliverableVerifier id "${item.id}" from pack "${packId}"`);
67
+ }
68
+ deliverableVerifiers.set(item.id, item);
69
+ }
70
+ }
71
+ export function listDeliverableVerifiers() {
72
+ return [...deliverableVerifiers.values()];
73
+ }
74
+ export function resetPhase9PackRegistries() {
75
+ dataSources.clear();
76
+ agentProfiles.clear();
77
+ applications.clear();
78
+ deliverableVerifiers.clear();
79
+ }
80
+ export function buildDefaultApplicationShell(safeMode = false) {
81
+ const brand = getBrand();
82
+ return {
83
+ id: DEFAULT_APPLICATION_ID,
84
+ title: { en: brand.displayName, zh: brand.displayName },
85
+ defaultAgentProfileId: brand.defaultAgentId,
86
+ allowedPackIds: [],
87
+ defaultWorkbenchTabs: ['preview', 'workbench', 'terminal', 'fact_chain'],
88
+ hiddenNavItems: [],
89
+ safeMode,
90
+ customApplicationBypassed: false,
91
+ };
92
+ }
93
+ /**
94
+ * Resolves the active application shell for the current user/tenant.
95
+ *
96
+ * When `safeMode === true` (triggered by `/?safe=1`), any custom
97
+ * ApplicationManifest navigation hiding or workbench restrictions are bypassed
98
+ * so operators can always recover settings, skills, MCP, and agent management.
99
+ */
100
+ export async function resolveActiveApplication(store, options) {
101
+ const safeMode = Boolean(options?.safeMode);
102
+ const p9 = ensurePhase9Store(store);
103
+ const savedId = await p9.getCustomSetting(ACTIVE_APPLICATION_SETTING_KEY);
104
+ const envActiveId = process.env.STEERABLE_ACTIVE_APP?.trim() || null;
105
+ const effectiveId = savedId ?? envActiveId;
106
+ const selected = !effectiveId || effectiveId === DEFAULT_APPLICATION_ID
107
+ ? null
108
+ : applications.get(effectiveId) ?? null;
109
+ if (!selected) {
110
+ return buildDefaultApplicationShell(safeMode);
111
+ }
112
+ if (safeMode) {
113
+ return {
114
+ ...buildDefaultApplicationShell(true),
115
+ customApplicationBypassed: true,
116
+ };
117
+ }
118
+ return {
119
+ id: selected.id,
120
+ title: selected.title,
121
+ defaultAgentProfileId: selected.defaultAgentProfileId,
122
+ allowedPackIds: selected.allowedPackIds,
123
+ defaultWorkbenchTabs: selected.defaultWorkbenchTabs ?? ['preview', 'workbench', 'terminal'],
124
+ hiddenNavItems: selected.hiddenNavItems ?? [],
125
+ safeMode: false,
126
+ customApplicationBypassed: false,
127
+ };
128
+ }
129
+ /** Switches the active application id (or `'default'`). */
130
+ export async function setActiveApplication(store, applicationId) {
131
+ if (applicationId !== DEFAULT_APPLICATION_ID && !applications.has(applicationId)) {
132
+ throw new Error(`Unknown application id: ${applicationId}`);
133
+ }
134
+ const p9 = ensurePhase9Store(store);
135
+ await p9.setCustomSetting(ACTIVE_APPLICATION_SETTING_KEY, applicationId);
136
+ return resolveActiveApplication(store);
137
+ }
138
+ /** Resets the active application back to the built-in default shell (`steerable-cli app reset`). */
139
+ export async function resetActiveApplication(store) {
140
+ const p9 = ensurePhase9Store(store);
141
+ await p9.setCustomSetting(ACTIVE_APPLICATION_SETTING_KEY, DEFAULT_APPLICATION_ID);
142
+ return buildDefaultApplicationShell(false);
143
+ }
@@ -5,4 +5,4 @@
5
5
  *
6
6
  * 契约全文与设计约束见 packages/pack-sdk/types/index.d.ts 头注释。
7
7
  */
8
- export type { ScenarioId, ToolMode, ToolExposure, PackToolContext, PackToolHandler, ToolApprovalSpec, ToolContribution, ServiceFactory, ServiceCreateContext, MigrationContribution, SkillContribution, AgentSeedIdentity, AgentSeed, HttpRouteContribution, HttpRouteRequest, MainContribution, ComponentRef, SettingsPanelContribution, RouteContribution, ChatSlotContribution, CardRendererContribution, RendererContribution, BrandSpec, PackagingSpec, CliCommandIO, CliCommandSpec, ScenarioPack, PackBackendAnyResponse, PackBackendBinaryBytesResponse, PackBackendBinaryFileResponse, PackBackendBinaryResponse, PackBackendRouteResponse, PackBackendRouteRequest, PackBackendRoute, PackTurnObserver, PackTurnHooks, } from '@steerable/pack-sdk';
8
+ export type { ScenarioId, OriginChannel, Principal, CredentialInjection, PackCredentialClient, PackDataSource, VerifierIssue, DeliverableVerificationResult, DeliverableVerifier, UiSurfaceSourceBinding, UiSurfaceActionSpec, UiSurfaceNodeSpec, UiSurfaceSpec, AgentProfileSpec, PublicAuthMethod, PublicBootstrapPayload, ApplicationManifest, ToolMode, ToolExposure, PackToolContext, PackToolHandler, ToolApprovalSpec, ToolContribution, ServiceFactory, ServiceCreateContext, MigrationContribution, SkillContribution, AgentSeedIdentity, AgentSeed, HttpRouteContribution, HttpRouteRequest, MainContribution, ComponentRef, SettingsPanelContribution, RouteContribution, ChatSlotContribution, CardRendererContribution, RendererContribution, BrandSpec, PackagingSpec, CliCommandIO, CliCommandSpec, ScenarioPack, PackBackendAnyResponse, PackBackendBinaryBytesResponse, PackBackendBinaryFileResponse, PackBackendBinaryResponse, PackBackendRouteResponse, PackBackendRouteRequest, PackBackendRoute, PackTurnObserver, PackTurnHooks, } from '@steerable/pack-sdk';
@@ -0,0 +1,28 @@
1
+ export interface SecurityPolicyConfig {
2
+ readonly approvalMode?: string;
3
+ readonly sandboxEnforced?: boolean;
4
+ readonly writableRoots?: readonly string[];
5
+ readonly allowedHosts?: readonly string[];
6
+ readonly safetyRules?: readonly string[];
7
+ /** Non-security fields allowed on merged config objects and ignored in digest. */
8
+ readonly [extraKey: string]: unknown;
9
+ }
10
+ export type DurableApprovalKind = 'allow_always' | 'deny_always';
11
+ /**
12
+ * Produces the exact same 32-hex SHA-256 prefix as Python's
13
+ * `steerable_agent_runtime.approval.compute_policy_digest`.
14
+ */
15
+ export declare function computePolicyDigest(config?: SecurityPolicyConfig): string;
16
+ /**
17
+ * File-backed durable approval grant store partitioned by `policyDigest`
18
+ * (`{"_by_policy": { [policyDigest]: { [category]: "allow_always" | "deny_always" } }}`),
19
+ * compatible with `JsonApprovalStore` in Python and Rust sidecars.
20
+ */
21
+ export declare class PolicyBoundApprovalStore {
22
+ private readonly filePath;
23
+ constructor(filePath: string);
24
+ private readRaw;
25
+ load(policyDigest: string): Record<string, DurableApprovalKind>;
26
+ get(policyDigest: string, category: string): DurableApprovalKind | null;
27
+ put(policyDigest: string, category: string, kind: DurableApprovalKind): void;
28
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Security Policy Digest & Policy-Bound Durable Approval Store (R2-2).
3
+ *
4
+ * Computes a deterministic 16-byte (32-hex) SHA-256 digest over canonical
5
+ * security-relevant fields only (`approvalMode`, `sandboxEnforced`,
6
+ * `writableRoots`, `allowedHosts`, `safetyRules`). Cosmetic or non-security
7
+ * configuration (`model`, `baseUrl`, `theme`, `locale`, `temperature`) is
8
+ * deliberately excluded so changing models or themes preserves `allow_always`
9
+ * grants, while relaxing sandbox or network boundaries invalidates stale grants.
10
+ */
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
13
+ import path from 'node:path';
14
+ function uniqueSorted(items, lowerCase = false) {
15
+ if (!items || items.length === 0)
16
+ return [];
17
+ const set = new Set();
18
+ for (const raw of items) {
19
+ if (typeof raw !== 'string')
20
+ continue;
21
+ const trimmed = raw.trim();
22
+ if (!trimmed)
23
+ continue;
24
+ set.add(lowerCase ? trimmed.toLowerCase() : trimmed);
25
+ }
26
+ return [...set].sort();
27
+ }
28
+ /**
29
+ * Produces the exact same 32-hex SHA-256 prefix as Python's
30
+ * `steerable_agent_runtime.approval.compute_policy_digest`.
31
+ */
32
+ export function computePolicyDigest(config = {}) {
33
+ const canonical = {
34
+ allowedHosts: uniqueSorted(config.allowedHosts, true),
35
+ approvalMode: String(config.approvalMode || 'host'),
36
+ safetyRules: uniqueSorted(config.safetyRules, false),
37
+ sandboxEnforced: Boolean(config.sandboxEnforced),
38
+ writableRoots: uniqueSorted(config.writableRoots, false),
39
+ };
40
+ const encoded = JSON.stringify(canonical);
41
+ return createHash('sha256').update(encoded, 'utf8').digest('hex').slice(0, 32);
42
+ }
43
+ /**
44
+ * File-backed durable approval grant store partitioned by `policyDigest`
45
+ * (`{"_by_policy": { [policyDigest]: { [category]: "allow_always" | "deny_always" } }}`),
46
+ * compatible with `JsonApprovalStore` in Python and Rust sidecars.
47
+ */
48
+ export class PolicyBoundApprovalStore {
49
+ filePath;
50
+ constructor(filePath) {
51
+ this.filePath = filePath;
52
+ }
53
+ readRaw() {
54
+ if (!existsSync(this.filePath))
55
+ return {};
56
+ try {
57
+ const parsed = JSON.parse(readFileSync(this.filePath, 'utf8'));
58
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
59
+ ? parsed
60
+ : {};
61
+ }
62
+ catch {
63
+ return {};
64
+ }
65
+ }
66
+ load(policyDigest) {
67
+ const raw = this.readRaw();
68
+ const byPolicy = raw._by_policy;
69
+ if (!byPolicy || typeof byPolicy !== 'object' || Array.isArray(byPolicy)) {
70
+ return {};
71
+ }
72
+ const bucket = byPolicy[policyDigest];
73
+ if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket)) {
74
+ return {};
75
+ }
76
+ const out = {};
77
+ for (const [k, v] of Object.entries(bucket)) {
78
+ if (v === 'allow_always' || v === 'deny_always') {
79
+ out[k] = v;
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+ get(policyDigest, category) {
85
+ return this.load(policyDigest)[category] ?? null;
86
+ }
87
+ put(policyDigest, category, kind) {
88
+ const raw = this.readRaw();
89
+ const byPolicy = raw._by_policy && typeof raw._by_policy === 'object' && !Array.isArray(raw._by_policy)
90
+ ? { ...raw._by_policy }
91
+ : {};
92
+ const existingBucket = byPolicy[policyDigest];
93
+ const bucket = existingBucket && typeof existingBucket === 'object' && !Array.isArray(existingBucket)
94
+ ? { ...existingBucket }
95
+ : {};
96
+ bucket[category] = kind;
97
+ byPolicy[policyDigest] = bucket;
98
+ const next = { ...raw, _by_policy: byPolicy };
99
+ mkdirSync(path.dirname(this.filePath), { recursive: true });
100
+ const tmpPath = `${this.filePath}.${process.pid}.tmp`;
101
+ writeFileSync(tmpPath, JSON.stringify(next, null, 1), 'utf8');
102
+ renameSync(tmpPath, this.filePath);
103
+ }
104
+ }
@@ -35,7 +35,8 @@ import { matchPackHttpRoute } from '../host/http-routes.js';
35
35
  import { getBrand } from '../brand.js';
36
36
  import { saveAttachmentFiles } from '../attachments.js';
37
37
  import { selectNativeDirectory } from '../native-folder-dialog.js';
38
- import { getAuthProvider } from '../auth/index.js';
38
+ import { LOCAL_DEFAULT_PRINCIPAL, getAuthProvider, parseOriginChannel, resolvePublicBootstrap, } from '../auth/index.js';
39
+ import { getHostActivitySnapshot } from '../local-backend/turn-security-context.js';
39
40
  import { isHostRouteAllowed } from '../host-tools.js';
40
41
  import { getResolvedHostTools } from '../host-tools-runtime.js';
41
42
  /** 与 router.handleStream 内部的路由正则保持一致——只有这些路径是流式。 */
@@ -248,7 +249,7 @@ export function createBsServer(deps) {
248
249
  return true;
249
250
  return url.searchParams.get('token') === authToken;
250
251
  }
251
- async function handleApi(req, res, pathname, principal) {
252
+ async function handleApi(req, res, pathname, principal, originChannel) {
252
253
  const isStream = req.method === 'POST' && STREAM_PATH_PATTERNS.some((p) => p.test(pathname));
253
254
  const body = req.method === 'POST' || req.method === 'PATCH' || req.method === 'PUT'
254
255
  ? await readJsonBody(req)
@@ -258,6 +259,7 @@ export function createBsServer(deps) {
258
259
  method: req.method ?? 'GET',
259
260
  path: `${pathname}${search}`,
260
261
  body,
262
+ originChannel,
261
263
  ...(principal ? { principal } : {}),
262
264
  };
263
265
  if (isStream) {
@@ -307,13 +309,17 @@ export function createBsServer(deps) {
307
309
  }
308
310
  }
309
311
  /** `/host/*`:preload direct-IPC 的 HTTP 等价物。全部 POST JSON,除标记 GET 的。 */
310
- async function handleHost(req, res, pathname) {
312
+ async function handleHost(req, res, pathname, principal, originChannel) {
311
313
  const body = asRecord(await readJsonBody(req));
312
314
  const method = req.method ?? 'GET';
313
315
  if (!isHostRouteAllowed(pathname, getResolvedHostTools())) {
314
316
  sendJson(res, 403, { detail: 'Host route is disabled for this product' });
315
317
  return;
316
318
  }
319
+ if (method === 'GET' && pathname === '/host/health/activity') {
320
+ sendJson(res, 200, getHostActivitySnapshot());
321
+ return;
322
+ }
317
323
  if (method === 'GET' && pathname === '/host/info') {
318
324
  const brand = getBrand();
319
325
  sendJson(res, 200, {
@@ -479,10 +485,13 @@ export function createBsServer(deps) {
479
485
  // host 端点目前不用 query string,query 先传空表。 ───
480
486
  const packMatch = matchPackHttpRoute(method, pathname);
481
487
  if (packMatch) {
488
+ const urlObj = new URL(req.url ?? '/', 'http://bs.local');
482
489
  sendJson(res, 200, await packMatch.route.handler({
483
490
  params: packMatch.params,
484
- query: {},
491
+ query: Object.fromEntries(urlObj.searchParams.entries()),
485
492
  body,
493
+ principal: Object.freeze({ ...(principal ?? LOCAL_DEFAULT_PRINCIPAL) }),
494
+ originChannel,
486
495
  }));
487
496
  return;
488
497
  }
@@ -554,9 +563,17 @@ export function createBsServer(deps) {
554
563
  throw new Error('BS middleware returned pass after starting a response');
555
564
  }
556
565
  }
566
+ if (pathname === '/api/v2/auth/bootstrap' && req.method === 'GET') {
567
+ const payload = await resolvePublicBootstrap(req.headers, {
568
+ ...(url.searchParams.get('safe') === '1' ? { safeMode: true } : {}),
569
+ });
570
+ sendJson(res, 200, payload);
571
+ return;
572
+ }
557
573
  // 门 2:API 与宿主能力要 Bearer token;静态资源不验(浏览器靠它
558
574
  // 拿 token),静态面不暴露任何能力。
559
575
  const needsAuth = pathname.startsWith('/api/v2/') || pathname.startsWith('/host/');
576
+ const originChannel = parseOriginChannel(req.headers['x-steerable-origin-channel'], 'web');
560
577
  let principal;
561
578
  if (needsAuth) {
562
579
  const authProvider = getAuthProvider();
@@ -578,11 +595,11 @@ export function createBsServer(deps) {
578
595
  return;
579
596
  }
580
597
  if (pathname.startsWith('/api/v2/')) {
581
- await handleApi(req, res, pathname, principal);
598
+ await handleApi(req, res, pathname, principal, originChannel);
582
599
  return;
583
600
  }
584
601
  if (pathname.startsWith('/host/')) {
585
- await handleHost(req, res, pathname);
602
+ await handleHost(req, res, pathname, principal, originChannel);
586
603
  return;
587
604
  }
588
605
  if (req.method === 'GET' || req.method === 'HEAD') {
@@ -6,6 +6,7 @@ import type { SidecarReverseHandler } from './types.js';
6
6
  export interface HostSidecarDeps {
7
7
  store: ScopedStore;
8
8
  toolRouter: ToolRouter;
9
+ broadcast?: (channel: string, payload: unknown) => void;
9
10
  /** W4-2 围栏:chatId → 项目家目录或无项目对话工作区。 */
10
11
  resolveProjectRoot: (chatId: string) => Promise<string | null>;
11
12
  /**
@@ -292,6 +292,8 @@ export async function startHostSidecar(deps) {
292
292
  // execute tools (shell / files / MCP live here, not in Python).
293
293
  supervisor.onReverseRequest('tool.invoke', createToolInvokeHandler({
294
294
  toolRouter: deps.toolRouter,
295
+ store: deps.store,
296
+ broadcast: deps.broadcast,
295
297
  onBlocked: (info) => log.warn('[sidecar tool] blocked critical shell command', info),
296
298
  // W4-2: project-mode fence on the CoreLoop path — the sidecar's
297
299
  // tool.invoke carries context.chatId; resolve it to the project
@@ -11,4 +11,4 @@
11
11
  */
12
12
  export { SidecarSupervisor } from './supervisor.js';
13
13
  export { SidecarBootError, SidecarMethodError, SidecarShutdownError, SidecarSandboxUnavailableError, } from './errors.js';
14
- export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarHealthSnapshot, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
14
+ export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarHealthSnapshot, SidecarLicenseState, SidecarLicenseStatus, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
@@ -0,0 +1,22 @@
1
+ declare const REJECTED_BEFORE_EFFECT_BRAND: unique symbol;
2
+ export declare class RejectedBeforeEffectError extends Error {
3
+ readonly [REJECTED_BEFORE_EFFECT_BRAND] = true;
4
+ readonly code: string;
5
+ readonly retryable: boolean;
6
+ private constructor();
7
+ /**
8
+ * Framework-internal factory for pre-dispatch rejections (schema validation,
9
+ * approval denial, sandbox pre-check, path confinement, reconciliation lock).
10
+ * Never exported from `@steerable/pack-sdk` so tool handlers cannot forge
11
+ * `effect: 'none'` after executing external side effects.
12
+ */
13
+ static create(code: string, message: string, retryable?: boolean): RejectedBeforeEffectError;
14
+ }
15
+ export declare function isRejectedBeforeEffectError(err: unknown): err is RejectedBeforeEffectError;
16
+ /**
17
+ * Lightweight pre-dispatch JSON Schema check for required keys and primitive
18
+ * property types so malformed LLM arguments fail BEFORE entering a non-idempotent
19
+ * pack tool handler.
20
+ */
21
+ export declare function validateArgsAgainstJsonSchema(toolName: string, schema: Record<string, unknown> | undefined, args: Record<string, unknown>): void;
22
+ export {};
@@ -0,0 +1,63 @@
1
+ const REJECTED_BEFORE_EFFECT_BRAND = Symbol('steerable.RejectedBeforeEffect');
2
+ export class RejectedBeforeEffectError extends Error {
3
+ [REJECTED_BEFORE_EFFECT_BRAND] = true;
4
+ code;
5
+ retryable;
6
+ constructor(code, message, retryable = true) {
7
+ super(message);
8
+ this.name = 'RejectedBeforeEffectError';
9
+ this.code = code;
10
+ this.retryable = retryable;
11
+ }
12
+ /**
13
+ * Framework-internal factory for pre-dispatch rejections (schema validation,
14
+ * approval denial, sandbox pre-check, path confinement, reconciliation lock).
15
+ * Never exported from `@steerable/pack-sdk` so tool handlers cannot forge
16
+ * `effect: 'none'` after executing external side effects.
17
+ */
18
+ static create(code, message, retryable = true) {
19
+ return new RejectedBeforeEffectError(code, message, retryable);
20
+ }
21
+ }
22
+ export function isRejectedBeforeEffectError(err) {
23
+ return Boolean(err &&
24
+ typeof err === 'object' &&
25
+ err[REJECTED_BEFORE_EFFECT_BRAND] === true);
26
+ }
27
+ /**
28
+ * Lightweight pre-dispatch JSON Schema check for required keys and primitive
29
+ * property types so malformed LLM arguments fail BEFORE entering a non-idempotent
30
+ * pack tool handler.
31
+ */
32
+ export function validateArgsAgainstJsonSchema(toolName, schema, args) {
33
+ if (!schema || typeof schema !== 'object')
34
+ return;
35
+ const required = schema.required;
36
+ if (Array.isArray(required)) {
37
+ for (const key of required) {
38
+ if (typeof key === 'string' && (args[key] === undefined || args[key] === null)) {
39
+ throw RejectedBeforeEffectError.create('schema_validation_failed', `invalid arguments for "${toolName}": missing required property "${key}"`, true);
40
+ }
41
+ }
42
+ }
43
+ const properties = schema.properties;
44
+ if (properties && typeof properties === 'object' && !Array.isArray(properties)) {
45
+ for (const [key, propSpec] of Object.entries(properties)) {
46
+ if (args[key] === undefined || !propSpec || typeof propSpec !== 'object')
47
+ continue;
48
+ const expectedType = propSpec.type;
49
+ if (typeof expectedType !== 'string')
50
+ continue;
51
+ const val = args[key];
52
+ const ok = (expectedType === 'string' && typeof val === 'string') ||
53
+ (expectedType === 'number' && typeof val === 'number' && Number.isFinite(val)) ||
54
+ (expectedType === 'integer' && typeof val === 'number' && Number.isInteger(val)) ||
55
+ (expectedType === 'boolean' && typeof val === 'boolean') ||
56
+ (expectedType === 'array' && Array.isArray(val)) ||
57
+ (expectedType === 'object' && Boolean(val) && typeof val === 'object' && !Array.isArray(val));
58
+ if (!ok) {
59
+ throw RejectedBeforeEffectError.create('schema_validation_failed', `invalid arguments for "${toolName}": property "${key}" expected ${expectedType}`, true);
60
+ }
61
+ }
62
+ }
63
+ }
@@ -47,6 +47,8 @@ export interface ApprovalPromptRequest {
47
47
  * blocked. Absent keeps that sentence for an older sidecar.
48
48
  */
49
49
  sandboxEnforced?: boolean;
50
+ /** `'outward'` forces per-invocation human confirmation with no remembered grants. */
51
+ checkpoint?: 'standard' | 'outward';
50
52
  }
51
53
  export interface ApprovalBridgeDeps {
52
54
  /**
@@ -16,6 +16,8 @@
16
16
  * before crossing back to the sidecar.
17
17
  */
18
18
  import { randomUUID } from 'node:crypto';
19
+ import { isRestrictedOriginChannel } from '../auth/index.js';
20
+ import { getTurnSecurityContext, touchHostActivity, } from '../local-backend/turn-security-context.js';
19
21
  /**
20
22
  * The approval algebra's decision variants (mirrors
21
23
  * `steerable_agent_runtime.approval.APPROVAL_KINDS`). `timed_out` is
@@ -47,12 +49,22 @@ export function createApprovalBridge(deps) {
47
49
  deps.onLog?.(`approval: ${toolName} matches the dangerous-command list; no card`);
48
50
  return { kind: 'allow_once', reason: '' };
49
51
  }
52
+ const requestId = randomUUID();
53
+ const chatId = typeof p.chatId === 'string' && p.chatId ? p.chatId : undefined;
54
+ const checkpoint = p.checkpoint === 'outward' ? 'outward' : undefined;
55
+ const turnSec = getTurnSecurityContext(chatId);
56
+ if (isRestrictedOriginChannel(turnSec?.originChannel) && checkpoint === 'outward') {
57
+ const workbenchHref = chatId ? `/#/agent/${encodeURIComponent(chatId)}` : '/#/agent';
58
+ deps.onLog?.(`approval: denying outward tool ${toolName} on restricted channel ${turnSec?.originChannel}`);
59
+ return deny(`outward_confirmation_required: open Web or Desktop workbench to confirm (${workbenchHref})`);
60
+ }
50
61
  if (!deps.hasWindow()) {
51
62
  deps.onLog?.(`approval: no renderer window; denying ${toolName} once`);
52
- return deny('no renderer window available to approve the call');
63
+ return deny(checkpoint === 'outward'
64
+ ? 'outward_confirmation_required: no interactive window available'
65
+ : 'no renderer window available to approve the call');
53
66
  }
54
- const requestId = randomUUID();
55
- const chatId = typeof p.chatId === 'string' && p.chatId ? p.chatId : undefined;
67
+ touchHostActivity();
56
68
  const category = typeof p.category === 'string' ? p.category : toolName;
57
69
  const categoryLabel = deps.categoryLabel?.(toolName, category);
58
70
  const fence = deps.outsideWorkspace
@@ -71,6 +83,7 @@ export function createApprovalBridge(deps) {
71
83
  ...(outsideWorkspace ? { outsideWorkspace: true } : {}),
72
84
  ...(fence === 'workspace' ? { outsideWorkspaceKind: 'workspace' } : {}),
73
85
  ...(typeof p.sandboxEnforced === 'boolean' ? { sandboxEnforced: p.sandboxEnforced } : {}),
86
+ ...(checkpoint ? { checkpoint } : {}),
74
87
  };
75
88
  deps.onLog?.(`approval: prompting for ${toolName} (${prompt.mode}/${prompt.category})`);
76
89
  return await new Promise((resolve) => {
@@ -92,11 +105,21 @@ export function createApprovalBridge(deps) {
92
105
  if (!entry)
93
106
  return { ok: false };
94
107
  pending.delete(requestId);
95
- const kind = APPROVAL_DECISION_KINDS.find((k) => k === p.kind);
96
- if (!kind) {
108
+ const rawKind = APPROVAL_DECISION_KINDS.find((k) => k === p.kind);
109
+ if (!rawKind) {
97
110
  entry.resolve(deny(`renderer returned an invalid decision kind: ${String(p.kind)}`));
98
111
  return { ok: true };
99
112
  }
113
+ touchHostActivity();
114
+ if (entry.prompt.checkpoint === 'outward' &&
115
+ (rawKind === 'allow_for_session' || rawKind === 'allow_always')) {
116
+ entry.resolve(deny('outward checkpoint forbids remembered approval grants'));
117
+ return { ok: true };
118
+ }
119
+ const turnSec = getTurnSecurityContext(entry.prompt.chatId);
120
+ const kind = isRestrictedOriginChannel(turnSec?.originChannel) && rawKind === 'allow_always'
121
+ ? 'allow_once'
122
+ : rawKind;
100
123
  const reason = typeof p.reason === 'string' ? p.reason : '';
101
124
  entry.resolve({ kind, reason });
102
125
  if (entry.prompt.toolName === 'network_egress'
@@ -6,10 +6,13 @@
6
6
  * Hard-gates critical shell commands — the TS loop only annotates them, but
7
7
  * on the CoreLoop path the framework's blocking semantics apply.
8
8
  */
9
+ import type { ScopedStore } from '../storage/scoped-store.js';
9
10
  import type { ToolRouter } from '../tool-router.js';
10
11
  import type { SidecarReverseHandler } from './types.js';
11
12
  export interface ReverseToolDeps {
12
13
  toolRouter: ToolRouter;
14
+ store?: ScopedStore;
15
+ broadcast?: (channel: string, payload: unknown) => void;
13
16
  onBlocked?: (info: {
14
17
  command: string;
15
18
  rules: string[];