@steerable/agent-shell 0.12.7 → 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,80 @@
1
+ /**
2
+ * Background title drift refresh via controlled `SideCallPort` guardrails (Phase 9 R7-3).
3
+ *
4
+ * Strictly preserves Phase 1 `title_source` ownership:
5
+ * - Whenever `chat.titleSource === 'user'` (manually renamed by user), returns
6
+ * immediately with ZERO sidecall invocations and NEVER overwrites the title.
7
+ * - For `chat.titleSource === 'auto'`, checks every `intervalAssistantTurns` (default 6)
8
+ * using scrubbed `2,000` head + `8,000` tail context and a `15s` hard timeout.
9
+ */
10
+ import { SecretRedactor } from '../auth/credentials.js';
11
+ export const TITLE_REFRESH_HEAD_CHARS = 2_000;
12
+ export const TITLE_REFRESH_TAIL_CHARS = 8_000;
13
+ export const TITLE_REFRESH_TIMEOUT_MS = 15_000;
14
+ export const TITLE_REFRESH_TURN_INTERVAL = 6;
15
+ export async function maybeRefreshDriftedChatTitle(options) {
16
+ const chat = await options.store.getChat(options.chatId);
17
+ if (!chat) {
18
+ return { updated: false, skippedReason: 'chat_not_found' };
19
+ }
20
+ // Invariant (T-SC-05): user-renamed chats are NEVER touched or evaluated
21
+ if (chat.titleSource === 'user') {
22
+ return { updated: false, skippedReason: 'user_locked_title', title: chat.title };
23
+ }
24
+ const messages = await options.store.listMessages(options.chatId, 200);
25
+ const assistantMessages = messages.filter((m) => m.role === 'assistant');
26
+ const interval = options.intervalAssistantTurns ?? TITLE_REFRESH_TURN_INTERVAL;
27
+ if (assistantMessages.length < interval || assistantMessages.length % interval !== 0) {
28
+ return { updated: false, skippedReason: 'below_interval', title: chat.title };
29
+ }
30
+ const firstUser = messages.find((m) => m.role === 'user')?.content ?? '';
31
+ const recentTailText = messages
32
+ .slice(-6)
33
+ .map((m) => `${m.role}: ${m.content}`)
34
+ .join('\n');
35
+ const redactor = options.redactor ?? new SecretRedactor();
36
+ const scrubbedHead = redactor.redact(firstUser.slice(0, TITLE_REFRESH_HEAD_CHARS));
37
+ const scrubbedTail = redactor.redact(recentTailText.slice(-TITLE_REFRESH_TAIL_CHARS));
38
+ const controller = new AbortController();
39
+ const timeoutMs = options.timeoutMs ?? TITLE_REFRESH_TIMEOUT_MS;
40
+ const timer = setTimeout(() => controller.abort(new Error('title_refresh_timeout')), timeoutMs);
41
+ const onParentAbort = () => controller.abort(options.parentSignal?.reason);
42
+ if (options.parentSignal) {
43
+ if (options.parentSignal.aborted) {
44
+ clearTimeout(timer);
45
+ return { updated: false, skippedReason: 'degraded', title: chat.title };
46
+ }
47
+ options.parentSignal.addEventListener('abort', onParentAbort, { once: true });
48
+ }
49
+ try {
50
+ const decision = await options.evaluateDrift({
51
+ caller: 'sidecall:title_refresh',
52
+ currentTitle: chat.title,
53
+ scrubbedHead,
54
+ scrubbedTail,
55
+ signal: controller.signal,
56
+ });
57
+ const candidate = decision.newTitle?.trim();
58
+ if (!decision.drifted || !candidate || candidate === chat.title) {
59
+ return { updated: false, skippedReason: 'no_drift', title: chat.title };
60
+ }
61
+ // Re-check chat.titleSource right before writing in case user renamed concurrently
62
+ const freshChat = await options.store.getChat(options.chatId);
63
+ if (!freshChat || freshChat.titleSource === 'user') {
64
+ return { updated: false, skippedReason: 'user_locked_title', title: freshChat?.title };
65
+ }
66
+ await options.store.updateChat(options.chatId, {
67
+ title: candidate.slice(0, 80),
68
+ titleSource: 'auto',
69
+ });
70
+ return { updated: true, title: candidate.slice(0, 80) };
71
+ }
72
+ catch {
73
+ // Guardrail #4: silent fail-safe degradation
74
+ return { updated: false, skippedReason: 'degraded', title: chat.title };
75
+ }
76
+ finally {
77
+ clearTimeout(timer);
78
+ options.parentSignal?.removeEventListener('abort', onParentAbort);
79
+ }
80
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Authoritative in-memory turn security context & host activity tracker.
3
+ *
4
+ * `Principal` and `PackCredentialClient` stay inside the trusted Node host
5
+ * process keyed by `chatId`; the sidecar/model never supplies or mutates
6
+ * `principal`, preventing prompt-injected `args.principal` escalation.
7
+ */
8
+ import type { OriginChannel, PackCredentialClient, Principal } from '@steerable/pack-sdk';
9
+ import { SecretRedactor } from '../auth/credentials.js';
10
+ import type { ScopedStore } from '../storage/scoped-store.js';
11
+ export interface ActiveTurnSecurityContext {
12
+ readonly chatId: string;
13
+ readonly principal: Principal;
14
+ readonly originChannel: OriginChannel;
15
+ readonly store: ScopedStore;
16
+ readonly redactor: SecretRedactor;
17
+ readonly credentials: PackCredentialClient;
18
+ readonly startedAtMs: number;
19
+ }
20
+ export declare function touchHostActivity(): void;
21
+ export declare function bindHostPendingCounters(counters: {
22
+ pendingApprovals: () => number;
23
+ pendingQuestions?: () => number;
24
+ }): void;
25
+ export declare function beginTurnSecurityContext(input: {
26
+ chatId: string;
27
+ principal?: Principal;
28
+ originChannel?: OriginChannel;
29
+ store: ScopedStore;
30
+ }): ActiveTurnSecurityContext;
31
+ export declare function getTurnSecurityContext(chatId: string | undefined): ActiveTurnSecurityContext | undefined;
32
+ export declare function endTurnSecurityContext(chatId: string, expected?: ActiveTurnSecurityContext): void;
33
+ export interface HostActivitySnapshot {
34
+ readonly state: 'running_turn' | 'awaiting_human' | 'idle';
35
+ readonly activeTurns: number;
36
+ readonly pendingApprovals: number;
37
+ readonly lastActivityAt: string;
38
+ }
39
+ export declare function getHostActivitySnapshot(overrides?: {
40
+ readonly pendingApprovals?: number;
41
+ readonly pendingReconciliations?: number;
42
+ }): HostActivitySnapshot;
@@ -0,0 +1,62 @@
1
+ import { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
2
+ import { SecretRedactor, defaultCredentialBroker, } from '../auth/credentials.js';
3
+ const activeTurns = new Map();
4
+ let lastActivityAtMs = Date.now();
5
+ let pendingApprovalsGetter = null;
6
+ let pendingQuestionsGetter = null;
7
+ export function touchHostActivity() {
8
+ lastActivityAtMs = Date.now();
9
+ }
10
+ export function bindHostPendingCounters(counters) {
11
+ pendingApprovalsGetter = counters.pendingApprovals;
12
+ pendingQuestionsGetter = counters.pendingQuestions ?? null;
13
+ }
14
+ export function beginTurnSecurityContext(input) {
15
+ touchHostActivity();
16
+ const principal = input.principal ?? LOCAL_DEFAULT_PRINCIPAL;
17
+ const originChannel = input.originChannel ?? 'web';
18
+ const redactor = new SecretRedactor();
19
+ const credentials = defaultCredentialBroker.createClient(input.store, principal, redactor);
20
+ const ctx = {
21
+ chatId: input.chatId,
22
+ principal,
23
+ originChannel,
24
+ store: input.store,
25
+ redactor,
26
+ credentials,
27
+ startedAtMs: Date.now(),
28
+ };
29
+ activeTurns.set(input.chatId, ctx);
30
+ return ctx;
31
+ }
32
+ export function getTurnSecurityContext(chatId) {
33
+ if (!chatId)
34
+ return undefined;
35
+ return activeTurns.get(chatId);
36
+ }
37
+ export function endTurnSecurityContext(chatId, expected) {
38
+ touchHostActivity();
39
+ const current = activeTurns.get(chatId);
40
+ if (!current)
41
+ return;
42
+ if (!expected || current === expected) {
43
+ activeTurns.delete(chatId);
44
+ }
45
+ }
46
+ export function getHostActivitySnapshot(overrides) {
47
+ const runningCount = activeTurns.size;
48
+ const approvals = (overrides?.pendingApprovals ??
49
+ (pendingApprovalsGetter?.() ?? 0) + (pendingQuestionsGetter?.() ?? 0)) +
50
+ (overrides?.pendingReconciliations ?? 0);
51
+ const state = runningCount > 0
52
+ ? 'running_turn'
53
+ : approvals > 0
54
+ ? 'awaiting_human'
55
+ : 'idle';
56
+ return {
57
+ state,
58
+ activeTurns: runningCount,
59
+ pendingApprovals: approvals,
60
+ lastActivityAt: new Date(lastActivityAtMs).toISOString(),
61
+ };
62
+ }
@@ -0,0 +1,75 @@
1
+ import type { UiSurfacePayload } from '@steerable/agent-protocol';
2
+ import { type OriginChannel, type Principal } from '../auth/index.js';
3
+ import type { ScopedStore } from '../storage/scoped-store.js';
4
+ import type { ToolRouter } from '../tool-router.js';
5
+ export declare const UI_SURFACE_RENDER_TOOL_NAME = "ui_surface_render";
6
+ export declare const MAX_UI_SURFACE_BYTES: number;
7
+ export declare const MAX_UI_SURFACE_TABLE_ROWS = 500;
8
+ export declare const ALLOWED_UI_SURFACE_COMPONENT_KINDS: Set<string>;
9
+ export declare const UI_SURFACE_RENDER_SCHEMA: {
10
+ name: string;
11
+ description: string;
12
+ mode: "ui";
13
+ inputSchema: {
14
+ type: string;
15
+ required: string[];
16
+ properties: {
17
+ surfaceId: {
18
+ type: string;
19
+ };
20
+ title: {
21
+ type: string;
22
+ };
23
+ subtitle: {
24
+ type: string;
25
+ };
26
+ placement: {
27
+ type: string;
28
+ enum: string[];
29
+ };
30
+ data: {
31
+ type: string;
32
+ };
33
+ components: {
34
+ type: string;
35
+ minItems: number;
36
+ };
37
+ actions: {
38
+ type: string;
39
+ };
40
+ };
41
+ };
42
+ };
43
+ export declare function canonicalJsonSha256(value: unknown): string;
44
+ export declare function evaluateUiSurfaceDataBindings(data: Record<string, unknown> | undefined, ctx: {
45
+ readonly principal: Principal;
46
+ readonly chatId: string;
47
+ }): Promise<{
48
+ resolvedData: Record<string, unknown>;
49
+ sourceHashes: Record<string, string>;
50
+ }>;
51
+ export declare function validateUiSurfaceRawInput(raw: Record<string, unknown>): void;
52
+ export declare function renderAndPersistUiSurface(options: {
53
+ readonly store: ScopedStore;
54
+ readonly chatId: string;
55
+ readonly principal?: Principal;
56
+ readonly raw: Record<string, unknown>;
57
+ }): Promise<UiSurfacePayload>;
58
+ export declare function refreshPersistedUiSurface(options: {
59
+ readonly store: ScopedStore;
60
+ readonly chatId: string;
61
+ readonly surfaceId: string;
62
+ readonly principal?: Principal;
63
+ }): Promise<UiSurfacePayload | null>;
64
+ export declare function dispatchUiSurfaceAction(options: {
65
+ readonly store: ScopedStore;
66
+ readonly toolRouter: ToolRouter;
67
+ readonly chatId: string;
68
+ readonly surfaceId: string;
69
+ readonly principal?: Principal;
70
+ readonly originChannel?: OriginChannel;
71
+ readonly body: Record<string, unknown>;
72
+ }): Promise<{
73
+ status: number;
74
+ data: unknown;
75
+ }>;
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Declarative `UiSurface` v1 host runtime, `$source` read-only data binding,
3
+ * canonical SHA-256 drift check (`409 UI_STALE`), and idempotent action dispatch (R4).
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { LOCAL_DEFAULT_PRINCIPAL, isRestrictedOriginChannel, } from '../auth/index.js';
7
+ import { getRegisteredDataSource } from '../scenario/applications.js';
8
+ import { RejectedBeforeEffectError } from '../sidecar/rejected-before-effect.js';
9
+ import { ensurePhase9Store } from '../storage/fde-fallback.js';
10
+ export const UI_SURFACE_RENDER_TOOL_NAME = 'ui_surface_render';
11
+ export const MAX_UI_SURFACE_BYTES = 64 * 1024;
12
+ export const MAX_UI_SURFACE_TABLE_ROWS = 500;
13
+ export const ALLOWED_UI_SURFACE_COMPONENT_KINDS = new Set([
14
+ 'table',
15
+ 'detail-card',
16
+ 'form',
17
+ 'steps',
18
+ 'kv-diff',
19
+ 'artifact-card',
20
+ ]);
21
+ export const UI_SURFACE_RENDER_SCHEMA = {
22
+ name: UI_SURFACE_RENDER_TOOL_NAME,
23
+ description: 'Render or update a structured business workbench surface (table, detail-card, form, steps, kv-diff, artifact-card) bounded to 64 KiB and 500 rows per table. Supports server-evaluated read-only `$source` bindings.',
24
+ mode: 'ui',
25
+ inputSchema: {
26
+ type: 'object',
27
+ required: ['surfaceId', 'title', 'components'],
28
+ properties: {
29
+ surfaceId: { type: 'string' },
30
+ title: { type: 'string' },
31
+ subtitle: { type: 'string' },
32
+ placement: { type: 'string', enum: ['inline', 'workbench'] },
33
+ data: { type: 'object' },
34
+ components: { type: 'array', minItems: 1 },
35
+ actions: { type: 'array' },
36
+ },
37
+ },
38
+ };
39
+ function canonicalizeValue(value) {
40
+ if (Array.isArray(value)) {
41
+ return value.map(canonicalizeValue);
42
+ }
43
+ if (value && typeof value === 'object') {
44
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
45
+ const out = {};
46
+ for (const [k, v] of entries) {
47
+ if (v !== undefined) {
48
+ out[k] = canonicalizeValue(v);
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+ return value;
54
+ }
55
+ export function canonicalJsonSha256(value) {
56
+ const serialized = JSON.stringify(canonicalizeValue(value));
57
+ return createHash('sha256').update(serialized, 'utf8').digest('hex');
58
+ }
59
+ function isSourceDescriptor(value) {
60
+ return Boolean(value &&
61
+ typeof value === 'object' &&
62
+ !Array.isArray(value) &&
63
+ typeof value.$source === 'string' &&
64
+ value.$source.trim().length > 0);
65
+ }
66
+ export async function evaluateUiSurfaceDataBindings(data, ctx) {
67
+ const resolvedData = {};
68
+ const sourceHashes = {};
69
+ if (!data || typeof data !== 'object') {
70
+ return { resolvedData, sourceHashes };
71
+ }
72
+ for (const [key, rawVal] of Object.entries(data)) {
73
+ if (isSourceDescriptor(rawVal)) {
74
+ const sourceId = rawVal.$source.trim();
75
+ const source = getRegisteredDataSource(sourceId);
76
+ if (!source || typeof source.query !== 'function') {
77
+ throw RejectedBeforeEffectError.create('unknown_data_source', `UiSurface references unregistered read-only data source "${sourceId}"`);
78
+ }
79
+ const queried = await source.query(rawVal.params ?? {}, {
80
+ principal: ctx.principal,
81
+ chatId: ctx.chatId,
82
+ });
83
+ if (Array.isArray(queried) && queried.length > MAX_UI_SURFACE_TABLE_ROWS) {
84
+ throw RejectedBeforeEffectError.create('ui_surface_row_cap_exceeded', `Data source "${sourceId}" returned ${queried.length} rows (max ${MAX_UI_SURFACE_TABLE_ROWS}). Apply server-side filtering first.`);
85
+ }
86
+ resolvedData[key] = queried;
87
+ sourceHashes[key] = canonicalJsonSha256(queried);
88
+ }
89
+ else {
90
+ resolvedData[key] = rawVal;
91
+ }
92
+ }
93
+ return { resolvedData, sourceHashes };
94
+ }
95
+ export function validateUiSurfaceRawInput(raw) {
96
+ const byteLen = Buffer.byteLength(JSON.stringify(raw), 'utf8');
97
+ if (byteLen > MAX_UI_SURFACE_BYTES) {
98
+ throw RejectedBeforeEffectError.create('ui_surface_payload_too_large', `UiSurface payload is ${byteLen} bytes (limit ${MAX_UI_SURFACE_BYTES} bytes).`);
99
+ }
100
+ const surfaceId = typeof raw.surfaceId === 'string' ? raw.surfaceId.trim() : '';
101
+ const title = typeof raw.title === 'string' ? raw.title.trim() : '';
102
+ if (!surfaceId || !title) {
103
+ throw RejectedBeforeEffectError.create('schema_validation_failed', 'UiSurface requires non-empty `surfaceId` and `title`.');
104
+ }
105
+ const components = raw.components;
106
+ if (!Array.isArray(components) || components.length === 0) {
107
+ throw RejectedBeforeEffectError.create('schema_validation_failed', 'UiSurface requires a non-empty `components` array.');
108
+ }
109
+ for (const comp of components) {
110
+ if (!comp || typeof comp !== 'object') {
111
+ throw RejectedBeforeEffectError.create('schema_validation_failed', 'Invalid UiSurface component entry.');
112
+ }
113
+ const c = comp;
114
+ const kind = typeof c.kind === 'string' ? c.kind : '';
115
+ if (!ALLOWED_UI_SURFACE_COMPONENT_KINDS.has(kind)) {
116
+ throw RejectedBeforeEffectError.create('schema_validation_failed', `Unsupported UiSurface component kind "${kind}". Allowed kinds: ${[...ALLOWED_UI_SURFACE_COMPONENT_KINDS].join(', ')}`);
117
+ }
118
+ if (kind === 'table' && Array.isArray(c.rows) && c.rows.length > MAX_UI_SURFACE_TABLE_ROWS) {
119
+ throw RejectedBeforeEffectError.create('ui_surface_row_cap_exceeded', `Table "${String(c.id ?? '')}" has ${c.rows.length} rows (max ${MAX_UI_SURFACE_TABLE_ROWS}).`);
120
+ }
121
+ }
122
+ }
123
+ export async function renderAndPersistUiSurface(options) {
124
+ validateUiSurfaceRawInput(options.raw);
125
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
126
+ const surfaceId = String(options.raw.surfaceId).trim();
127
+ const title = String(options.raw.title).trim();
128
+ const dataSpec = options.raw.data && typeof options.raw.data === 'object' && !Array.isArray(options.raw.data)
129
+ ? options.raw.data
130
+ : undefined;
131
+ const { resolvedData, sourceHashes } = await evaluateUiSurfaceDataBindings(dataSpec, {
132
+ principal,
133
+ chatId: options.chatId,
134
+ });
135
+ const p9 = ensurePhase9Store(options.store);
136
+ const stored = await p9.upsertChatUiSurface({
137
+ chatId: options.chatId,
138
+ spec: {
139
+ surfaceId,
140
+ title: { en: title, zh: title },
141
+ nodes: [],
142
+ },
143
+ state: {
144
+ rawPayload: {
145
+ ...options.raw,
146
+ surfaceId,
147
+ title,
148
+ },
149
+ resolvedData,
150
+ sourceHashes,
151
+ },
152
+ status: 'active',
153
+ });
154
+ const payload = {
155
+ ...options.raw,
156
+ surfaceId,
157
+ title,
158
+ revision: stored.revision,
159
+ resolvedData,
160
+ sourceHashes,
161
+ };
162
+ const finalBytes = Buffer.byteLength(JSON.stringify(payload), 'utf8');
163
+ if (finalBytes > MAX_UI_SURFACE_BYTES) {
164
+ throw RejectedBeforeEffectError.create('ui_surface_payload_too_large', `Resolved UiSurface payload is ${finalBytes} bytes (limit ${MAX_UI_SURFACE_BYTES} bytes).`);
165
+ }
166
+ return payload;
167
+ }
168
+ export async function refreshPersistedUiSurface(options) {
169
+ const p9 = ensurePhase9Store(options.store);
170
+ const existing = await p9.getChatUiSurface(options.chatId, options.surfaceId);
171
+ if (!existing)
172
+ return null;
173
+ const rawPayload = existing.state.rawPayload && typeof existing.state.rawPayload === 'object'
174
+ ? existing.state.rawPayload
175
+ : { surfaceId: existing.surfaceId, title: existing.title.en ?? existing.surfaceId, components: [] };
176
+ const dataSpec = rawPayload.data && typeof rawPayload.data === 'object' && !Array.isArray(rawPayload.data)
177
+ ? rawPayload.data
178
+ : undefined;
179
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
180
+ const { resolvedData, sourceHashes } = await evaluateUiSurfaceDataBindings(dataSpec, {
181
+ principal,
182
+ chatId: options.chatId,
183
+ });
184
+ const prevHashes = existing.state.sourceHashes ?? {};
185
+ const changed = JSON.stringify(prevHashes) !== JSON.stringify(sourceHashes);
186
+ const revision = changed
187
+ ? (await p9.upsertChatUiSurface({
188
+ chatId: options.chatId,
189
+ spec: existing.spec,
190
+ state: {
191
+ ...existing.state,
192
+ resolvedData,
193
+ sourceHashes,
194
+ },
195
+ status: existing.status,
196
+ })).revision
197
+ : existing.revision;
198
+ return {
199
+ ...rawPayload,
200
+ surfaceId: existing.surfaceId,
201
+ revision,
202
+ resolvedData,
203
+ sourceHashes,
204
+ };
205
+ }
206
+ export async function dispatchUiSurfaceAction(options) {
207
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
208
+ const originChannel = options.originChannel ?? 'web';
209
+ const p9 = ensurePhase9Store(options.store);
210
+ const commandId = String(options.body.commandId ?? '').trim();
211
+ const actionId = String(options.body.actionId ?? '').trim();
212
+ if (!commandId || !actionId) {
213
+ return {
214
+ status: 400,
215
+ data: { detail: 'commandId and actionId are required' },
216
+ };
217
+ }
218
+ // 1. Idempotency check on (chatId, commandId) BEFORE revision/hash/tool checks
219
+ const priorReceipts = await p9.listChatUiReceipts(options.chatId, options.surfaceId);
220
+ const existingReceipt = priorReceipts.find((r) => r.payload.__commandId === commandId);
221
+ if (existingReceipt) {
222
+ return {
223
+ status: 200,
224
+ data: {
225
+ ok: true,
226
+ deduplicated: true,
227
+ receipt: existingReceipt,
228
+ result: existingReceipt.result,
229
+ },
230
+ };
231
+ }
232
+ const surface = await p9.getChatUiSurface(options.chatId, options.surfaceId);
233
+ if (!surface) {
234
+ return { status: 404, data: { detail: 'surface not found' } };
235
+ }
236
+ // 2. Verify expectedRevision
237
+ const expectedRevision = Number(options.body.expectedRevision ?? 0);
238
+ if (expectedRevision !== surface.revision) {
239
+ return {
240
+ status: 409,
241
+ data: {
242
+ code: 'UI_STALE',
243
+ staleKeys: ['__revision__'],
244
+ currentRevision: surface.revision,
245
+ },
246
+ };
247
+ }
248
+ const rawPayload = surface.state.rawPayload && typeof surface.state.rawPayload === 'object'
249
+ ? surface.state.rawPayload
250
+ : null;
251
+ const actions = Array.isArray(rawPayload?.actions) ? rawPayload.actions : [];
252
+ const actionSpec = actions.find((a) => a.id === actionId);
253
+ if (!actionSpec) {
254
+ return { status: 404, data: { detail: `action "${actionId}" not found on surface` } };
255
+ }
256
+ // 3. Real-time re-query of all $source bindings & SHA-256 drift verification
257
+ const dataSpec = rawPayload?.data && typeof rawPayload.data === 'object'
258
+ ? rawPayload.data
259
+ : undefined;
260
+ const { resolvedData: freshData, sourceHashes: freshHashes } = await evaluateUiSurfaceDataBindings(dataSpec, {
261
+ principal,
262
+ chatId: options.chatId,
263
+ });
264
+ const clientHashes = options.body.sourceHashes &&
265
+ typeof options.body.sourceHashes === 'object' &&
266
+ !Array.isArray(options.body.sourceHashes)
267
+ ? options.body.sourceHashes
268
+ : {};
269
+ const staleKeys = [];
270
+ for (const [sourceKey, freshHash] of Object.entries(freshHashes)) {
271
+ if (clientHashes[sourceKey] !== freshHash) {
272
+ staleKeys.push(sourceKey);
273
+ }
274
+ }
275
+ if (staleKeys.length > 0) {
276
+ return {
277
+ status: 409,
278
+ data: {
279
+ code: 'UI_STALE',
280
+ staleKeys,
281
+ },
282
+ };
283
+ }
284
+ // Restricted channel check for outward actions/tools
285
+ const toolSchema = options.toolRouter.getSchemaByName(actionSpec.toolName);
286
+ const isOutward = actionSpec.checkpoint === 'outward' || toolSchema?.checkpoint === 'outward';
287
+ if (isRestrictedOriginChannel(originChannel) && isOutward) {
288
+ return {
289
+ status: 403,
290
+ data: {
291
+ code: 'outward_confirmation_required',
292
+ workbenchHref: `/#/agent/${encodeURIComponent(options.chatId)}`,
293
+ },
294
+ };
295
+ }
296
+ // 4. Authoritative row lookup strictly from server-side `freshData` (ignore forged client row objects)
297
+ const selectedRowIds = Array.isArray(options.body.selectedRowIds)
298
+ ? options.body.selectedRowIds.filter((x) => typeof x === 'string')
299
+ : [];
300
+ const selectedIdSet = new Set(selectedRowIds);
301
+ const tableComp = (rawPayload?.components ?? []).find((c) => c.kind === 'table' &&
302
+ (!actionSpec.dataKey || c.dataKey === actionSpec.dataKey));
303
+ const idField = tableComp?.rowIdField || 'id';
304
+ let authoritativeRows = [];
305
+ if (tableComp) {
306
+ const tableRows = tableComp.dataKey && Array.isArray(freshData[tableComp.dataKey])
307
+ ? freshData[tableComp.dataKey]
308
+ : Array.isArray(tableComp.rows)
309
+ ? tableComp.rows
310
+ : [];
311
+ authoritativeRows = tableRows.filter((row) => selectedIdSet.has(String(row[idField] ?? '')));
312
+ }
313
+ const formValues = options.body.formValues &&
314
+ typeof options.body.formValues === 'object' &&
315
+ !Array.isArray(options.body.formValues)
316
+ ? options.body.formValues
317
+ : {};
318
+ const kvDiffOverrides = options.body.kvDiffOverrides &&
319
+ typeof options.body.kvDiffOverrides === 'object' &&
320
+ !Array.isArray(options.body.kvDiffOverrides)
321
+ ? options.body.kvDiffOverrides
322
+ : {};
323
+ const note = typeof options.body.note === 'string' && options.body.note.trim()
324
+ ? options.body.note.trim()
325
+ : undefined;
326
+ const toolArgs = {
327
+ ...(actionSpec.staticArgs ?? {}),
328
+ ...formValues,
329
+ ...(Object.keys(kvDiffOverrides).length > 0 ? { kvDiffOverrides } : {}),
330
+ ...(note ? { note } : {}),
331
+ ...(selectedRowIds.length > 0
332
+ ? { selectedRowIds, selectedRows: authoritativeRows }
333
+ : {}),
334
+ };
335
+ const rawResult = await options.toolRouter.execute({ name: actionSpec.toolName, arguments: toolArgs }, {
336
+ chatId: options.chatId,
337
+ principal,
338
+ originChannel,
339
+ });
340
+ const resultObj = rawResult && typeof rawResult === 'object' && !Array.isArray(rawResult)
341
+ ? rawResult
342
+ : { value: rawResult };
343
+ const receipt = await p9.recordChatUiReceipt({
344
+ chatId: options.chatId,
345
+ surfaceId: options.surfaceId,
346
+ revision: surface.revision,
347
+ actionId,
348
+ toolName: actionSpec.toolName,
349
+ payload: {
350
+ __commandId: commandId,
351
+ selectedRowIds,
352
+ formValues,
353
+ ...(note ? { note } : {}),
354
+ },
355
+ sourceFingerprints: freshHashes,
356
+ result: resultObj,
357
+ actorId: principal.id,
358
+ });
359
+ return {
360
+ status: 200,
361
+ data: {
362
+ ok: true,
363
+ deduplicated: false,
364
+ receipt,
365
+ result: resultObj,
366
+ },
367
+ };
368
+ }
@@ -322,6 +322,9 @@ export declare class LocalExecutor {
322
322
  detectDangerousCommand(command: string): string | null;
323
323
  private detectDangerousCommandInternal;
324
324
  private getDefaultPatterns;
325
+ private getPrivateDeniedPaths;
326
+ private checkPrivateHostFilePath;
327
+ private detectPrivateHostDataAccess;
325
328
  private resolvePath;
326
329
  private resolveCwd;
327
330
  private resolveShell;