@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,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
@@ -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[];
@@ -6,9 +6,14 @@
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 { createHash } from 'node:crypto';
9
10
  import { classifyShellCommand } from './safety-patterns.js';
11
+ import { isRejectedBeforeEffectError } from './rejected-before-effect.js';
10
12
  import { compactToolResultJson } from '../local-backend/context-compactor.js';
11
13
  import { normalizeToolPolicy } from '../local-backend/agent-capability.js';
14
+ import { getTurnSecurityContext, touchHostActivity, } from '../local-backend/turn-security-context.js';
15
+ import { LOCAL_DEFAULT_PRINCIPAL, isRestrictedOriginChannel, } from '../auth/index.js';
16
+ import { ensurePhase9Store } from '../storage/fde-fallback.js';
12
17
  /**
13
18
  * 模型上下文硬顶:喂给 sidecar 的工具结果必须待在框架逐项 10k token 断言线
14
19
  * 以下(2026-08-28 E2E 录制实锤:local_exec_shell 对 node_modules 跑
@@ -45,7 +50,7 @@ export function createToolInvokeHandler(deps) {
45
50
  const name = typeof p.name === 'string' ? p.name : '';
46
51
  const toolArgs = p.arguments ?? {};
47
52
  if (!name) {
48
- return { success: false, error: 'missing tool name', needsFollowup: false };
53
+ return { success: false, error: 'missing tool name', effect: 'none', retryable: false, needsFollowup: false };
49
54
  }
50
55
  // Plan mode is enforced at the execution layer too, not just by tool
51
56
  // advertisement — a pseudo-recovered call could name a write tool that
@@ -56,6 +61,8 @@ export function createToolInvokeHandler(deps) {
56
61
  return {
57
62
  success: false,
58
63
  error: `blocked by plan mode: ${name} is a write tool`,
64
+ effect: 'none',
65
+ retryable: false,
59
66
  needsFollowup: false,
60
67
  };
61
68
  }
@@ -87,6 +94,8 @@ export function createToolInvokeHandler(deps) {
87
94
  return {
88
95
  success: false,
89
96
  error: `blocked by shell safety policy (critical): ${classification.matchedRules.join(', ')}`,
97
+ effect: 'none',
98
+ retryable: false,
90
99
  needsFollowup: false,
91
100
  };
92
101
  }
@@ -97,32 +106,135 @@ export function createToolInvokeHandler(deps) {
97
106
  ? normalizeToolPolicy(p.context.toolPolicy)
98
107
  : null;
99
108
  const toolPolicy = normalizedPolicy && normalizedPolicy.mode !== 'all' ? normalizedPolicy : null;
100
- const execContext = projectRoot ||
101
- additionalReadRoots.length > 0 ||
102
- additionalWriteRoots.length > 0 ||
103
- p.context?.chatId ||
104
- toolPolicy
105
- ? {
106
- projectRoot,
107
- chatId: p.context?.chatId,
108
- // 4.6a:chatId 随上下文透传——task_run/status/result 与
109
- // worktree_* 工具按它把任务绑定到来源对话。
110
- ...(toolPolicy ? { toolPolicy } : {}),
111
- ...(additionalReadRoots.length > 0 ? { additionalReadRoots } : {}),
112
- ...(additionalWriteRoots.length > 0 ? { additionalWriteRoots } : {}),
109
+ const chatId = p.context?.chatId;
110
+ const turnSec = getTurnSecurityContext(chatId);
111
+ const activeStore = turnSec?.store ?? deps.store;
112
+ const principal = turnSec?.principal ?? LOCAL_DEFAULT_PRINCIPAL;
113
+ const originChannel = turnSec?.originChannel ?? 'web';
114
+ const schema = deps.toolRouter.getSchemaByName?.(name);
115
+ if (chatId && activeStore) {
116
+ const allForChat = await ensurePhase9Store(activeStore).listPendingReconciliations(chatId, { includeResolved: true });
117
+ const latestForTool = allForChat.find((item) => item.toolName === name);
118
+ if (latestForTool &&
119
+ (latestForTool.status === 'pending' || latestForTool.status === 'confirmed_executed')) {
120
+ const reason = latestForTool.status === 'confirmed_executed'
121
+ ? `reconciliation_committed: previous call to "${name}" was confirmed_succeeded (reconciliationId=${latestForTool.id}); automatic re-execution is locked.`
122
+ : `reconciliation_required: previous call to "${name}" ended with outcome_unknown (reconciliationId=${latestForTool.id}). Confirm whether external side effects occurred before retrying.`;
123
+ return {
124
+ success: false,
125
+ error: reason,
126
+ effect: 'none',
127
+ retryable: false,
128
+ reconciliationId: latestForTool.id,
129
+ needsFollowup: false,
130
+ };
131
+ }
132
+ }
133
+ if (isRestrictedOriginChannel(originChannel) && schema?.checkpoint === 'outward') {
134
+ const workbenchHref = chatId ? `/#/agent/${encodeURIComponent(chatId)}` : '/#/agent';
135
+ return {
136
+ success: false,
137
+ error: `outward_confirmation_required: tool "${name}" requires interactive confirmation in the Web or Desktop workbench (${workbenchHref})`,
138
+ effect: 'none',
139
+ retryable: true,
140
+ needsFollowup: false,
141
+ workbenchHref,
142
+ };
143
+ }
144
+ if (schema?.inputSchema && typeof schema.inputSchema === 'object') {
145
+ const schemaObj = schema.inputSchema;
146
+ if (Array.isArray(schemaObj.required)) {
147
+ for (const reqKey of schemaObj.required) {
148
+ if (typeof reqKey === 'string' && toolArgs[reqKey] === undefined) {
149
+ return {
150
+ success: false,
151
+ error: `schema_validation_failed: missing required argument "${reqKey}" for tool "${name}"`,
152
+ effect: 'none',
153
+ retryable: true,
154
+ needsFollowup: true,
155
+ };
156
+ }
157
+ }
113
158
  }
114
- : undefined;
159
+ }
160
+ touchHostActivity();
161
+ const execContext = {
162
+ projectRoot,
163
+ chatId,
164
+ principal,
165
+ originChannel,
166
+ ...(turnSec?.credentials ? { credentials: turnSec.credentials } : {}),
167
+ ...(toolPolicy ? { toolPolicy } : {}),
168
+ ...(additionalReadRoots.length > 0 ? { additionalReadRoots } : {}),
169
+ ...(additionalWriteRoots.length > 0 ? { additionalWriteRoots } : {}),
170
+ };
171
+ const isNonIdempotent = schema?.idempotent === false;
172
+ const recordUnknownOutcome = async (errorText) => {
173
+ const rawArgsJson = JSON.stringify(toolArgs);
174
+ const safeArgsJson = turnSec?.redactor.hasSecrets
175
+ ? turnSec.redactor.redactString(rawArgsJson)
176
+ : rawArgsJson;
177
+ const argsDigest = createHash('sha256').update(safeArgsJson).digest('hex').slice(0, 16);
178
+ let reconciliationId;
179
+ if (chatId && activeStore) {
180
+ const rec = await ensurePhase9Store(activeStore).createPendingReconciliation({
181
+ chatId,
182
+ toolName: name,
183
+ argsDigest,
184
+ argsPreview: safeArgsJson.slice(0, 300),
185
+ errorDetail: errorText.slice(0, 500),
186
+ });
187
+ reconciliationId = rec.id;
188
+ deps.broadcast?.('reconciliation:updated', { chatId, reconciliation: rec });
189
+ }
190
+ return {
191
+ success: false,
192
+ error: errorText.startsWith('outcome_unknown') ? errorText : `outcome_unknown: ${errorText}`,
193
+ effect: 'unknown',
194
+ outcomeUnknown: true,
195
+ retryable: false,
196
+ ...(reconciliationId ? { reconciliationId } : {}),
197
+ needsFollowup: true,
198
+ };
199
+ };
115
200
  try {
116
- const out = await deps.toolRouter.execute({ name, arguments: toolArgs }, execContext);
201
+ const rawOut = await deps.toolRouter.execute({ name, arguments: toolArgs }, execContext);
202
+ const out = turnSec?.redactor.hasSecrets
203
+ ? turnSec.redactor.redactUnknown(rawOut)
204
+ : rawOut;
205
+ if (out &&
206
+ typeof out === 'object' &&
207
+ out.outcomeUnknown === true) {
208
+ const msg = String(out.error ??
209
+ `tool "${name}" returned an unknown side-effect outcome`);
210
+ return await recordUnknownOutcome(msg);
211
+ }
117
212
  if (out && typeof out === 'object' && 'success' in out) {
118
213
  return capResultForModelContext(out);
119
214
  }
120
215
  return capResultForModelContext({ success: true, data: { value: out } });
121
216
  }
122
217
  catch (err) {
218
+ const rawMsg = err instanceof Error ? err.message : String(err);
219
+ const safeMsg = turnSec?.redactor.hasSecrets
220
+ ? turnSec.redactor.redactString(rawMsg)
221
+ : rawMsg;
222
+ if (isRejectedBeforeEffectError(err)) {
223
+ return {
224
+ success: false,
225
+ error: safeMsg,
226
+ effect: 'none',
227
+ retryable: err.retryable,
228
+ needsFollowup: err.retryable,
229
+ };
230
+ }
231
+ const explicitUnknown = Boolean(err && typeof err === 'object' && err.outcomeUnknown === true);
232
+ if (isNonIdempotent || explicitUnknown) {
233
+ return await recordUnknownOutcome(safeMsg);
234
+ }
123
235
  return {
124
236
  success: false,
125
- error: err instanceof Error ? err.message : String(err),
237
+ error: safeMsg,
126
238
  needsFollowup: true,
127
239
  };
128
240
  }
@@ -518,6 +518,12 @@ export interface SidecarChatStreamRequest {
518
518
  * starts with `..`.
519
519
  */
520
520
  pathBase?: string;
521
+ /**
522
+ * Authoritative host map of unresolved `outcome_unknown` tool locks
523
+ * (`toolName -> reconciliationId`), synced before opening a new turn.
524
+ */
525
+ pendingReconciliations?: Record<string, string>;
526
+ policyDigest?: string;
521
527
  };
522
528
  }
523
529
  /**
@@ -0,0 +1,4 @@
1
+ import type { ScopedStore } from './scoped-store.js';
2
+ import type { Phase9ScopedStore } from './fde-types.js';
3
+ export declare function resetPhase9FallbackState(): void;
4
+ export declare function ensurePhase9Store(store: ScopedStore): ScopedStore & Phase9ScopedStore;