@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,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;
@@ -1,4 +1,4 @@
1
- import { shellOpenExternal, shellOpenPath } from './runtime.js';
1
+ import { getUserDataDir, shellOpenExternal, shellOpenPath } from './runtime.js';
2
2
  import { access, mkdir, readFile, rename, stat, writeFile } from 'fs/promises';
3
3
  import os from 'os';
4
4
  import path from 'path';
@@ -380,6 +380,10 @@ export class LocalExecutor {
380
380
  return { success: false, error: 'command is required' };
381
381
  }
382
382
  command = rewriteExeCommandIfNeeded(command);
383
+ const privateShellDeny = this.detectPrivateHostDataAccess(command);
384
+ if (privateShellDeny) {
385
+ return { success: false, error: privateShellDeny, exitCode: 1, platform: process.platform };
386
+ }
383
387
  const dangerousReason = this.detectDangerousCommand(command);
384
388
  if (dangerousReason) {
385
389
  return { success: false, error: `Blocked dangerous command: ${dangerousReason}` };
@@ -643,6 +647,9 @@ export class LocalExecutor {
643
647
  async readLocalFile(request, projectRoot, additionalReadRoots) {
644
648
  try {
645
649
  const filePath = this.resolvePath(request.path, projectRoot);
650
+ const privateDeny = this.checkPrivateHostFilePath(filePath);
651
+ if (privateDeny)
652
+ return { success: false, error: privateDeny };
646
653
  if (projectRoot) {
647
654
  const root = this.resolvePath(projectRoot);
648
655
  const inAdditionalRoot = (additionalReadRoots ?? []).some((r) => isPathWithinRoot(filePath, this.resolvePath(r)));
@@ -678,6 +685,9 @@ export class LocalExecutor {
678
685
  }
679
686
  async writeLocalFile(request, projectRoot, additionalWriteRoots) {
680
687
  const filePath = this.resolvePath(request.path, projectRoot);
688
+ const privateDeny = this.checkPrivateHostFilePath(filePath);
689
+ if (privateDeny)
690
+ return { success: false, error: privateDeny };
681
691
  const violation = writableFenceViolation(filePath, writableFenceRoots(projectRoot, additionalWriteRoots));
682
692
  if (violation)
683
693
  return { success: false, error: violation };
@@ -739,6 +749,9 @@ export class LocalExecutor {
739
749
  */
740
750
  async editLocalFile(request, projectRoot, additionalWriteRoots) {
741
751
  const filePath = this.resolvePath(request.path, projectRoot);
752
+ const privateDeny = this.checkPrivateHostFilePath(filePath);
753
+ if (privateDeny)
754
+ return { success: false, error: privateDeny };
742
755
  const violation = writableFenceViolation(filePath, writableFenceRoots(projectRoot, additionalWriteRoots));
743
756
  if (violation)
744
757
  return { success: false, error: violation };
@@ -1099,6 +1112,32 @@ export class LocalExecutor {
1099
1112
  return new RegExp(d.pattern, flags);
1100
1113
  });
1101
1114
  }
1115
+ getPrivateDeniedPaths() {
1116
+ const rawUserDir = path.resolve(getUserDataDir());
1117
+ const realUserDir = this.resolvePath(getUserDataDir());
1118
+ const roots = new Set([rawUserDir, realUserDir]);
1119
+ const out = [];
1120
+ for (const userDir of roots) {
1121
+ out.push(path.join(userDir, 'memory'), path.join(userDir, 'authoring-candidates'), path.join(userDir, 'credential-master-key.bin'));
1122
+ }
1123
+ return out;
1124
+ }
1125
+ checkPrivateHostFilePath(resolvedFilePath) {
1126
+ for (const denied of this.getPrivateDeniedPaths()) {
1127
+ if (resolvedFilePath === denied || isPathWithinRoot(resolvedFilePath, denied)) {
1128
+ return `Access denied: ${resolvedFilePath} is inside host-isolated private storage (${denied}). Use memory_read / memory_propose instead.`;
1129
+ }
1130
+ }
1131
+ return null;
1132
+ }
1133
+ detectPrivateHostDataAccess(command) {
1134
+ for (const denied of this.getPrivateDeniedPaths()) {
1135
+ if (command.includes(denied)) {
1136
+ return `Blocked by sandbox private-deny policy: direct shell access to host private path "${denied}" is forbidden.`;
1137
+ }
1138
+ }
1139
+ return null;
1140
+ }
1102
1141
  resolvePath(inputPath, baseDir) {
1103
1142
  return resolveFencePath(inputPath, baseDir);
1104
1143
  }
@@ -0,0 +1,26 @@
1
+ export interface AuthoringCandidateRecord {
2
+ readonly id: string;
3
+ readonly name: string;
4
+ readonly candidateHash: string;
5
+ readonly reviewHash: string;
6
+ readonly createdAt: string;
7
+ readonly sourceChatId: string;
8
+ readonly staticCheckPassed: boolean;
9
+ readonly staticViolations: readonly string[];
10
+ }
11
+ export declare function getAuthoringCandidatesDir(): string;
12
+ export declare function runCandidateSkillStaticCheck(skillMarkdown: string): string[];
13
+ export declare function stageAuthoringCandidate(input: {
14
+ readonly name: string;
15
+ readonly skillMarkdown: string;
16
+ readonly reviewSummary: string;
17
+ readonly sourceChatId: string;
18
+ }): Promise<AuthoringCandidateRecord>;
19
+ export declare function promoteAuthoringCandidate(input: {
20
+ readonly id: string;
21
+ readonly expectedCandidateHash: string;
22
+ readonly expectedReviewHash: string;
23
+ readonly targetSkillsRoot?: string;
24
+ }): Promise<{
25
+ installedPath: string;
26
+ }>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Dual-hash quarantine sandbox for auto-distilled `SKILL.md` authoring candidates (Phase 9 R8-3).
3
+ *
4
+ * Candidate skills land under `<userDataDir>/authoring-candidates/<id>/` (outside any
5
+ * active skill discovery path), undergo static safety validation, and require an
6
+ * explicit human approval binding BOTH `(candidateHash, reviewHash)` before installation.
7
+ */
8
+ import { createHash, randomBytes } from 'node:crypto';
9
+ import fs from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { getUserDataDir } from '../runtime.js';
12
+ export function getAuthoringCandidatesDir() {
13
+ return path.join(getUserDataDir(), 'authoring-candidates');
14
+ }
15
+ function sha256(text) {
16
+ return createHash('sha256').update(text, 'utf8').digest('hex');
17
+ }
18
+ const FORBIDDEN_SKILL_PATTERNS = [
19
+ { code: 'credential_master_key_ref', re: /STEERABLE_CREDENTIAL_MASTER_KEY/ },
20
+ { code: 'curl_pipe_shell', re: /curl\s+[^\n|]+\|\s*(?:ba)?sh/i },
21
+ { code: 'host_memory_path_ref', re: /\/memory\/workspaces\// },
22
+ ];
23
+ export function runCandidateSkillStaticCheck(skillMarkdown) {
24
+ const violations = [];
25
+ for (const { code, re } of FORBIDDEN_SKILL_PATTERNS) {
26
+ if (re.test(skillMarkdown)) {
27
+ violations.push(code);
28
+ }
29
+ }
30
+ return violations;
31
+ }
32
+ export async function stageAuthoringCandidate(input) {
33
+ const id = `cand_${randomBytes(6).toString('hex')}`;
34
+ const dir = path.join(getAuthoringCandidatesDir(), id);
35
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
36
+ const violations = runCandidateSkillStaticCheck(input.skillMarkdown);
37
+ const candidateHash = sha256(input.skillMarkdown);
38
+ const reviewHash = sha256(`${candidateHash}:${input.reviewSummary.trim()}`);
39
+ const record = {
40
+ id,
41
+ name: input.name.replace(/[^a-zA-Z0-9_-]/g, '-'),
42
+ candidateHash,
43
+ reviewHash,
44
+ createdAt: new Date().toISOString(),
45
+ sourceChatId: input.sourceChatId,
46
+ staticCheckPassed: violations.length === 0,
47
+ staticViolations: violations,
48
+ };
49
+ await fs.writeFile(path.join(dir, 'SKILL.md'), input.skillMarkdown, { mode: 0o600 });
50
+ await fs.writeFile(path.join(dir, 'meta.json'), JSON.stringify(record, null, 2), { mode: 0o600 });
51
+ return record;
52
+ }
53
+ export async function promoteAuthoringCandidate(input) {
54
+ const dir = path.join(getAuthoringCandidatesDir(), input.id);
55
+ const metaRaw = await fs.readFile(path.join(dir, 'meta.json'), 'utf8');
56
+ const meta = JSON.parse(metaRaw);
57
+ const skillMarkdown = await fs.readFile(path.join(dir, 'SKILL.md'), 'utf8');
58
+ const liveCandidateHash = sha256(skillMarkdown);
59
+ if (liveCandidateHash !== meta.candidateHash ||
60
+ liveCandidateHash !== input.expectedCandidateHash ||
61
+ meta.reviewHash !== input.expectedReviewHash) {
62
+ throw new Error('authoring_candidate_hash_mismatch');
63
+ }
64
+ if (!meta.staticCheckPassed || runCandidateSkillStaticCheck(skillMarkdown).length > 0) {
65
+ throw new Error('authoring_candidate_failed_static_check');
66
+ }
67
+ const destRoot = input.targetSkillsRoot ?? path.join(getUserDataDir(), 'skills');
68
+ const destDir = path.join(destRoot, meta.name);
69
+ await fs.mkdir(destDir, { recursive: true });
70
+ const installedPath = path.join(destDir, 'SKILL.md');
71
+ await fs.writeFile(installedPath, skillMarkdown, 'utf8');
72
+ return { installedPath };
73
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Snapshot-anchored memory injector (Phase 9 R8-2).
3
+ *
4
+ * Prefix KV-cache invariants:
5
+ * 1. `system` prompt bytes remain 100% static — memory NEVER enters `system`.
6
+ * 2. A `<untrusted_memory_note trust="untrusted">` snapshot is captured ONLY at
7
+ * session Turn 1 and immediately after a `CompactionBoundary` rewrite (`compactionEpoch` bump).
8
+ * 3. Mid-session writes, renewals, or withdrawals NEVER mutate the anchored turn-1
9
+ * snapshot message; instead, they append a single `[memory delta] ...` line
10
+ * immediately before the latest user message on the next turn.
11
+ * 4. Tracks `memoryContributed` per chat so `insights` telemetry automatically
12
+ * strips free-text transcripts whenever private memory entered a session.
13
+ */
14
+ import { type Principal } from '../auth/index.js';
15
+ import { MemoryStore } from './store.js';
16
+ /** Read the current compaction epoch for a chat session (default 0). */
17
+ export declare function getSessionCompactionEpoch(chatId: string): number;
18
+ /** Increment and return the compaction epoch after a CompactionBoundary rewrite. */
19
+ export declare function bumpSessionCompactionEpoch(chatId: string): number;
20
+ export interface MemoryTurnInjection {
21
+ /** Immutable snapshot block for the session's initial user prefix (empty if no memory). */
22
+ readonly anchoredPrefixNote: string;
23
+ /** Tail delta lines for mid-session edits/withdrawals since last turn (empty on turn 1). */
24
+ readonly tailDeltaNotice: string;
25
+ /** True if any non-empty memory entered this chat session. */
26
+ readonly memoryContributed: boolean;
27
+ }
28
+ export declare function buildMemoryTurnInjection(options: {
29
+ readonly memoryStore: MemoryStore;
30
+ readonly chatId: string;
31
+ readonly principal?: Principal;
32
+ readonly workspaceId?: string;
33
+ readonly compactionEpoch?: number;
34
+ readonly nowMs?: number;
35
+ }): Promise<MemoryTurnInjection>;
36
+ export declare function recordMidSessionMemoryDelta(chatId: string | undefined, deltaSummary: string): void;
37
+ export declare function didChatContributeMemory(chatId: string): boolean;
38
+ export declare function resetMemorySnapshotsForTests(): void;