@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
@@ -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,34 @@
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
+ export interface MemoryTurnInjection {
17
+ /** Immutable snapshot block for the session's initial user prefix (empty if no memory). */
18
+ readonly anchoredPrefixNote: string;
19
+ /** Tail delta lines for mid-session edits/withdrawals since last turn (empty on turn 1). */
20
+ readonly tailDeltaNotice: string;
21
+ /** True if any non-empty memory entered this chat session. */
22
+ readonly memoryContributed: boolean;
23
+ }
24
+ export declare function buildMemoryTurnInjection(options: {
25
+ readonly memoryStore: MemoryStore;
26
+ readonly chatId: string;
27
+ readonly principal?: Principal;
28
+ readonly workspaceId?: string;
29
+ readonly compactionEpoch?: number;
30
+ readonly nowMs?: number;
31
+ }): Promise<MemoryTurnInjection>;
32
+ export declare function recordMidSessionMemoryDelta(chatId: string | undefined, deltaSummary: string): void;
33
+ export declare function didChatContributeMemory(chatId: string): boolean;
34
+ export declare function resetMemorySnapshotsForTests(): void;
@@ -0,0 +1,111 @@
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 { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
15
+ import { TENANT_INJECT_BUDGET_BYTES, USER_INJECT_BUDGET_BYTES, WORKSPACE_INJECT_BUDGET_BYTES, } from './store.js';
16
+ const sessionMemoryMap = new Map();
17
+ export async function buildMemoryTurnInjection(options) {
18
+ const mode = await options.memoryStore.getPermissionMode();
19
+ const epoch = options.compactionEpoch ?? 0;
20
+ const existing = sessionMemoryMap.get(options.chatId);
21
+ if (mode === 'off') {
22
+ return {
23
+ anchoredPrefixNote: '',
24
+ tailDeltaNotice: '',
25
+ memoryContributed: existing?.memoryContributed ?? false,
26
+ };
27
+ }
28
+ // Reuse frozen snapshot mid-session unless CompactionBoundary bumped `compactionEpoch`
29
+ if (existing && existing.compactionEpoch === epoch) {
30
+ const deltas = existing.pendingDeltas.splice(0, existing.pendingDeltas.length);
31
+ const tailDeltaNotice = deltas.length > 0 ? deltas.join('\n') : '';
32
+ return {
33
+ anchoredPrefixNote: existing.snapshotBlock,
34
+ tailDeltaNotice,
35
+ memoryContributed: existing.memoryContributed,
36
+ };
37
+ }
38
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
39
+ const workspaceId = options.workspaceId || 'default';
40
+ const [tenantMd, workspaceMd, userMd] = await Promise.all([
41
+ options.memoryStore.renderVisibleMarkdownForScope({
42
+ scope: 'tenant',
43
+ scopeId: principal.tenantId,
44
+ principal,
45
+ budgetBytes: TENANT_INJECT_BUDGET_BYTES,
46
+ nowMs: options.nowMs,
47
+ }),
48
+ options.memoryStore.renderVisibleMarkdownForScope({
49
+ scope: 'workspace',
50
+ scopeId: workspaceId,
51
+ principal,
52
+ budgetBytes: WORKSPACE_INJECT_BUDGET_BYTES,
53
+ nowMs: options.nowMs,
54
+ }),
55
+ options.memoryStore.renderVisibleMarkdownForScope({
56
+ scope: 'user',
57
+ scopeId: principal.id,
58
+ principal,
59
+ budgetBytes: USER_INJECT_BUDGET_BYTES,
60
+ nowMs: options.nowMs,
61
+ }),
62
+ ]);
63
+ const sections = [];
64
+ if (tenantMd)
65
+ sections.push(`## Tenant shared rules\n${tenantMd}`);
66
+ if (workspaceMd)
67
+ sections.push(`## Workspace memory\n${workspaceMd}`);
68
+ if (userMd)
69
+ sections.push(`## Personal preferences\n${userMd}`);
70
+ const snapshotBlock = sections.length > 0
71
+ ? `<untrusted_memory_note trust="untrusted">\n${sections.join('\n\n')}\n</untrusted_memory_note>`
72
+ : '';
73
+ const contributed = Boolean(snapshotBlock) || (existing?.memoryContributed ?? false);
74
+ sessionMemoryMap.set(options.chatId, {
75
+ snapshotBlock,
76
+ compactionEpoch: epoch,
77
+ pendingDeltas: [],
78
+ memoryContributed: contributed,
79
+ });
80
+ return {
81
+ anchoredPrefixNote: snapshotBlock,
82
+ tailDeltaNotice: '',
83
+ memoryContributed: contributed,
84
+ };
85
+ }
86
+ export function recordMidSessionMemoryDelta(chatId, deltaSummary) {
87
+ if (!chatId)
88
+ return;
89
+ const entry = sessionMemoryMap.get(chatId);
90
+ const formatted = deltaSummary.startsWith('[memory delta]')
91
+ ? deltaSummary
92
+ : `[memory delta] ${deltaSummary}`;
93
+ if (entry) {
94
+ entry.pendingDeltas.push(formatted);
95
+ entry.memoryContributed = true;
96
+ }
97
+ else {
98
+ sessionMemoryMap.set(chatId, {
99
+ snapshotBlock: '',
100
+ compactionEpoch: 0,
101
+ pendingDeltas: [formatted],
102
+ memoryContributed: true,
103
+ });
104
+ }
105
+ }
106
+ export function didChatContributeMemory(chatId) {
107
+ return sessionMemoryMap.get(chatId)?.memoryContributed === true;
108
+ }
109
+ export function resetMemorySnapshotsForTests() {
110
+ sessionMemoryMap.clear();
111
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * HTTP route handlers for `/api/v2/memory*` (Phase 9 R8-4).
3
+ */
4
+ import { type Principal } from '../auth/index.js';
5
+ import type { ScopedStore } from '../storage/scoped-store.js';
6
+ export declare function handleMemoryHttpRoute(options: {
7
+ readonly method: string;
8
+ readonly pathname: string;
9
+ readonly searchParams: URLSearchParams;
10
+ readonly body: Record<string, unknown>;
11
+ readonly store: ScopedStore;
12
+ readonly principal?: Principal;
13
+ }): Promise<{
14
+ status: number;
15
+ data: unknown;
16
+ } | null>;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * HTTP route handlers for `/api/v2/memory*` (Phase 9 R8-4).
3
+ */
4
+ import { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
5
+ import { recordMidSessionMemoryDelta } from './injector.js';
6
+ import { MemoryAccessDeniedError, MemoryBaseHashConflictError, MemoryStore, } from './store.js';
7
+ function parseScope(raw) {
8
+ if (raw === 'workspace' || raw === 'tenant')
9
+ return raw;
10
+ return 'user';
11
+ }
12
+ export async function handleMemoryHttpRoute(options) {
13
+ const { method, pathname, searchParams, body } = options;
14
+ if (!pathname.startsWith('/api/v2/memory'))
15
+ return null;
16
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
17
+ const memoryStore = new MemoryStore(options.store);
18
+ try {
19
+ if (pathname === '/api/v2/memory' && method === 'GET') {
20
+ const scope = parseScope(searchParams.get('scope'));
21
+ const scopeId = searchParams.get('scopeId') ?? undefined;
22
+ const permissionMode = await memoryStore.getPermissionMode();
23
+ const doc = await memoryStore.readDocument({ scope, scopeId, principal });
24
+ return {
25
+ status: 200,
26
+ data: {
27
+ permissionMode,
28
+ ...doc,
29
+ },
30
+ };
31
+ }
32
+ if (pathname === '/api/v2/memory' && method === 'PUT') {
33
+ if (body.permissionMode === 'off' ||
34
+ body.permissionMode === 'ask' ||
35
+ body.permissionMode === 'auto') {
36
+ await memoryStore.setPermissionMode(body.permissionMode);
37
+ if (body.contentMarkdown === undefined) {
38
+ return {
39
+ status: 200,
40
+ data: { permissionMode: body.permissionMode },
41
+ };
42
+ }
43
+ }
44
+ const scope = parseScope(body.scope ?? searchParams.get('scope'));
45
+ const scopeId = typeof body.scopeId === 'string'
46
+ ? body.scopeId
47
+ : searchParams.get('scopeId') ?? undefined;
48
+ const contentMarkdown = String(body.contentMarkdown ?? '');
49
+ const baseHash = typeof body.baseHash === 'string' ? body.baseHash : undefined;
50
+ const chatId = typeof body.chatId === 'string' ? body.chatId : undefined;
51
+ const saved = await memoryStore.writeDocument({
52
+ scope,
53
+ scopeId,
54
+ principal,
55
+ contentMarkdown,
56
+ baseHash,
57
+ sourceChatId: chatId ?? null,
58
+ isHumanEdit: true,
59
+ });
60
+ if (chatId) {
61
+ recordMidSessionMemoryDelta(chatId, `updated ${scope} MEMORY.md`);
62
+ }
63
+ return {
64
+ status: 200,
65
+ data: saved,
66
+ };
67
+ }
68
+ if (pathname === '/api/v2/memory/propose' && method === 'POST') {
69
+ const scope = parseScope(body.scope);
70
+ const scopeId = typeof body.scopeId === 'string' ? body.scopeId : undefined;
71
+ const chatId = typeof body.chatId === 'string' ? body.chatId : 'local';
72
+ const turnId = typeof body.turnId === 'string' ? body.turnId : 'manual_turn';
73
+ const content = String(body.content ?? '').trim();
74
+ const res = await memoryStore.proposeRefinement({
75
+ scope,
76
+ scopeId,
77
+ principal,
78
+ content,
79
+ evidence: {
80
+ chatId,
81
+ turnId,
82
+ ...(typeof body.toolCallId === 'string' ? { toolCallId: body.toolCallId } : {}),
83
+ },
84
+ });
85
+ if (res.accepted) {
86
+ recordMidSessionMemoryDelta(chatId, `saved ${scope} paragraph ${res.meta.id}`);
87
+ }
88
+ return {
89
+ status: 200,
90
+ data: res,
91
+ };
92
+ }
93
+ const refActionMatch = pathname.match(/^\/api\/v2\/memory\/refinements\/([^/]+)\/(renew|convert|withdraw)$/);
94
+ if (refActionMatch && method === 'POST') {
95
+ const refinementId = decodeURIComponent(refActionMatch[1]);
96
+ const action = refActionMatch[2];
97
+ const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : undefined;
98
+ const chatId = typeof body.chatId === 'string' ? body.chatId : undefined;
99
+ let updated = null;
100
+ if (action === 'renew') {
101
+ updated = await memoryStore.renewRefinement({ refinementId, principal, workspaceId });
102
+ }
103
+ else if (action === 'convert') {
104
+ updated = await memoryStore.convertRefinementToOrdinary({
105
+ refinementId,
106
+ principal,
107
+ workspaceId,
108
+ });
109
+ }
110
+ else {
111
+ updated = await memoryStore.withdrawRefinement({
112
+ refinementId,
113
+ principal,
114
+ workspaceId,
115
+ });
116
+ if (updated && chatId) {
117
+ recordMidSessionMemoryDelta(chatId, `withdrawn paragraph ${refinementId}`);
118
+ }
119
+ }
120
+ if (!updated)
121
+ return { status: 404, data: { detail: 'refinement not found' } };
122
+ return { status: 200, data: { refinement: updated } };
123
+ }
124
+ const revokedMatch = pathname.match(/^\/api\/v2\/memory\/revoked\/([^/]+)$/);
125
+ if (revokedMatch && method === 'DELETE') {
126
+ const hash = decodeURIComponent(revokedMatch[1]);
127
+ const scope = parseScope(searchParams.get('scope'));
128
+ const scopeId = searchParams.get('scopeId') ?? undefined;
129
+ const removed = await memoryStore.unrevokeHash({ scope, scopeId, hash, principal });
130
+ return { status: 200, data: { removed } };
131
+ }
132
+ return null;
133
+ }
134
+ catch (err) {
135
+ if (err instanceof MemoryAccessDeniedError) {
136
+ return { status: 403, data: { code: err.code, detail: err.message } };
137
+ }
138
+ if (err instanceof MemoryBaseHashConflictError) {
139
+ return {
140
+ status: 409,
141
+ data: { code: err.code, currentHash: err.currentHash, detail: err.message },
142
+ };
143
+ }
144
+ throw err;
145
+ }
146
+ }
@@ -0,0 +1,176 @@
1
+ import { type Principal } from '../auth/index.js';
2
+ import type { MemoryScopeKind } from '../storage/fde-types.js';
3
+ import type { ScopedStore } from '../storage/scoped-store.js';
4
+ export declare const MAX_MEMORY_INDEX_BYTES: number;
5
+ export declare const MAX_MEMORY_INDEX_LINES = 200;
6
+ export declare const MAX_MEMORY_TOPIC_BYTES: number;
7
+ export declare const MAX_MEMORY_TOTAL_BYTES: number;
8
+ export declare const TENANT_INJECT_BUDGET_BYTES: number;
9
+ export declare const WORKSPACE_INJECT_BUDGET_BYTES: number;
10
+ export declare const USER_INJECT_BUDGET_BYTES: number;
11
+ export declare const RSI_TTL_MS: number;
12
+ export declare const MEMORY_PERMISSION_SETTING_KEY = "memory_permission_mode";
13
+ export type MemoryPermissionMode = 'off' | 'ask' | 'auto';
14
+ export interface RefinementEvidence {
15
+ readonly chatId: string;
16
+ readonly turnId: string;
17
+ readonly toolCallId?: string;
18
+ }
19
+ export interface RefinementParagraphMeta {
20
+ readonly id: string;
21
+ readonly normalizedHash: string;
22
+ readonly scope: MemoryScopeKind;
23
+ readonly scopeId: string;
24
+ readonly content: string;
25
+ readonly evidence: RefinementEvidence;
26
+ readonly humanEdited: boolean;
27
+ readonly status: 'active' | 'ordinary' | 'withdrawn';
28
+ readonly createdAt: string;
29
+ readonly expiresAt: string | null;
30
+ }
31
+ export interface MemoryConflictDraft {
32
+ readonly id: string;
33
+ readonly targetRefinementId: string;
34
+ readonly proposedContent: string;
35
+ readonly createdAt: string;
36
+ }
37
+ export declare class MemoryAccessDeniedError extends Error {
38
+ readonly status = 403;
39
+ readonly code = "memory_access_denied";
40
+ constructor(message: string);
41
+ }
42
+ export declare class MemoryBaseHashConflictError extends Error {
43
+ readonly status = 409;
44
+ readonly code = "MEMORY_BASE_HASH_CONFLICT";
45
+ readonly currentHash: string;
46
+ constructor(currentHash: string);
47
+ }
48
+ export declare function getHostMemoryRootDir(): string;
49
+ export declare function hashWorkspaceScopeId(workspacePathOrId: string): string;
50
+ export declare function sha256Text(text: string): string;
51
+ export declare function normalizeMemoryParagraphHash(raw: string): string;
52
+ export declare function extractRefinementBlocks(markdown: string): Map<string, string>;
53
+ export declare class MemoryStore {
54
+ private readonly store;
55
+ constructor(store: ScopedStore);
56
+ private get p9();
57
+ getPermissionMode(): Promise<MemoryPermissionMode>;
58
+ setPermissionMode(mode: MemoryPermissionMode): Promise<void>;
59
+ private metaKey;
60
+ private revokedKey;
61
+ private topicsKey;
62
+ private conflictsKey;
63
+ private loadMetaList;
64
+ private saveMetaList;
65
+ private loadRevokedSet;
66
+ private saveRevokedSet;
67
+ private loadTopicsMap;
68
+ private saveTopicsMap;
69
+ listConflicts(scope: MemoryScopeKind, requestedScopeId: string | undefined, principal?: Principal): Promise<MemoryConflictDraft[]>;
70
+ private appendConflict;
71
+ private mirrorToHostPrivateDisk;
72
+ readDocument(options: {
73
+ readonly scope: MemoryScopeKind;
74
+ readonly scopeId?: string;
75
+ readonly principal?: Principal;
76
+ }): Promise<{
77
+ readonly scope: MemoryScopeKind;
78
+ readonly scopeId: string;
79
+ readonly contentMarkdown: string;
80
+ readonly contentSha256: string;
81
+ readonly bytesUsed: number;
82
+ readonly maxBytes: number;
83
+ readonly linesUsed: number;
84
+ readonly maxLines: number;
85
+ readonly refinements: RefinementParagraphMeta[];
86
+ readonly revokedHashes: string[];
87
+ readonly topics: string[];
88
+ readonly conflicts: MemoryConflictDraft[];
89
+ }>;
90
+ writeDocument(options: {
91
+ readonly scope: MemoryScopeKind;
92
+ readonly scopeId?: string;
93
+ readonly principal?: Principal;
94
+ readonly contentMarkdown: string;
95
+ readonly baseHash?: string;
96
+ readonly sourceChatId?: string | null;
97
+ readonly isHumanEdit?: boolean;
98
+ }): Promise<{
99
+ readonly contentMarkdown: string;
100
+ readonly contentSha256: string;
101
+ readonly bytesUsed: number;
102
+ readonly linesUsed: number;
103
+ }>;
104
+ writeTopic(options: {
105
+ readonly scope: MemoryScopeKind;
106
+ readonly scopeId?: string;
107
+ readonly principal?: Principal;
108
+ readonly topicName: string;
109
+ readonly contentMarkdown: string;
110
+ }): Promise<void>;
111
+ readTopic(options: {
112
+ readonly scope: MemoryScopeKind;
113
+ readonly scopeId?: string;
114
+ readonly principal?: Principal;
115
+ readonly topicName: string;
116
+ }): Promise<string | null>;
117
+ search(options: {
118
+ readonly query: string;
119
+ readonly workspaceId?: string;
120
+ readonly principal?: Principal;
121
+ }): Promise<Array<{
122
+ scope: MemoryScopeKind;
123
+ source: string;
124
+ snippet: string;
125
+ }>>;
126
+ proposeRefinement(options: {
127
+ readonly id?: string;
128
+ readonly scope: MemoryScopeKind;
129
+ readonly scopeId?: string;
130
+ readonly principal?: Principal;
131
+ readonly content: string;
132
+ readonly evidence: RefinementEvidence;
133
+ readonly nowMs?: number;
134
+ }): Promise<{
135
+ readonly accepted: true;
136
+ readonly meta: RefinementParagraphMeta;
137
+ } | {
138
+ readonly accepted: false;
139
+ readonly reason: 'user_revoked' | 'human_edited_conflict';
140
+ readonly conflictDraft?: MemoryConflictDraft;
141
+ }>;
142
+ private findRefinementAcrossScopes;
143
+ renewRefinement(options: {
144
+ readonly refinementId: string;
145
+ readonly principal?: Principal;
146
+ readonly workspaceId?: string;
147
+ readonly nowMs?: number;
148
+ }): Promise<RefinementParagraphMeta | null>;
149
+ convertRefinementToOrdinary(options: {
150
+ readonly refinementId: string;
151
+ readonly principal?: Principal;
152
+ readonly workspaceId?: string;
153
+ }): Promise<RefinementParagraphMeta | null>;
154
+ withdrawRefinement(options: {
155
+ readonly refinementId: string;
156
+ readonly principal?: Principal;
157
+ readonly workspaceId?: string;
158
+ }): Promise<RefinementParagraphMeta | null>;
159
+ unrevokeHash(options: {
160
+ readonly scope: MemoryScopeKind;
161
+ readonly scopeId?: string;
162
+ readonly hash: string;
163
+ readonly principal?: Principal;
164
+ }): Promise<boolean>;
165
+ /**
166
+ * Renders active, non-expired, non-revoked markdown for a single scope within
167
+ * `budgetBytes`, preserving original source text on disk even when expired.
168
+ */
169
+ renderVisibleMarkdownForScope(options: {
170
+ readonly scope: MemoryScopeKind;
171
+ readonly scopeId: string;
172
+ readonly principal: Principal;
173
+ readonly budgetBytes: number;
174
+ readonly nowMs?: number;
175
+ }): Promise<string>;
176
+ }