@agent-native/core 0.114.6 → 0.114.7

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 (141) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +6 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/cli/mcp-config-writers.ts +6 -4
  5. package/corpus/core/src/cli/mcp.ts +124 -0
  6. package/corpus/core/src/cli/skills-content/help.ts +4 -3
  7. package/corpus/core/src/cli/skills-content/index.ts +1 -0
  8. package/corpus/core/src/cli/skills-content/rewind-skill.ts +52 -0
  9. package/corpus/core/src/cli/skills.ts +115 -13
  10. package/corpus/core/src/mcp/screen-memory-stdio.ts +1360 -104
  11. package/corpus/core/src/mcp-client/index.ts +9 -0
  12. package/corpus/core/src/mcp-client/screen-memory-local.ts +847 -13
  13. package/corpus/templates/clips/actions/apply-rewind-extension.ts +195 -0
  14. package/corpus/templates/clips/actions/delete-agent-recording-if-unpromoted.ts +64 -0
  15. package/corpus/templates/clips/actions/get-rewind-extension-request.ts +22 -0
  16. package/corpus/templates/clips/actions/get-screen-memory-status.ts +18 -2
  17. package/corpus/templates/clips/actions/list-rewind-extension-requests.ts +52 -0
  18. package/corpus/templates/clips/actions/make-recording-private-for-rewind.ts +55 -0
  19. package/corpus/templates/clips/actions/query-screen-memory-context.ts +4 -4
  20. package/corpus/templates/clips/actions/request-rewind-extension.ts +81 -0
  21. package/corpus/templates/clips/actions/update-rewind-extension-request.ts +47 -0
  22. package/corpus/templates/clips/app/components/editor/editor-layout.tsx +25 -0
  23. package/corpus/templates/clips/app/components/editor/editor-toolbar.tsx +36 -0
  24. package/corpus/templates/clips/app/components/editor/rewind-extension-dialog.tsx +338 -0
  25. package/corpus/templates/clips/app/components/editor/stitch-manager.tsx +1 -16
  26. package/corpus/templates/clips/app/components/editor/timeline.tsx +26 -0
  27. package/corpus/templates/clips/app/i18n/en-US.ts +18 -0
  28. package/corpus/templates/clips/app/lib/ffmpeg-export.ts +19 -12
  29. package/corpus/templates/clips/app/lib/rewind-visibility.ts +31 -0
  30. package/corpus/templates/clips/app/lib/timestamp-mapping.ts +7 -0
  31. package/corpus/templates/clips/app/lib/upload-file-client.ts +17 -0
  32. package/corpus/templates/clips/changelog/2026-07-14-rewind-keeps-recent-screen-context-local-and-turns-it-into-clips.md +6 -0
  33. package/corpus/templates/clips/changelog/2026-07-17-active-clips-keep-rewind-stable-and-settings-clear.md +12 -0
  34. package/corpus/templates/clips/changelog/2026-07-17-clicking-the-clips-icon-during-a-recording-now-opens-the-app.md +6 -0
  35. package/corpus/templates/clips/changelog/2026-07-17-default-mic-now-uses-the-mac-default-and-transcription-shares-one-capture.md +6 -0
  36. package/corpus/templates/clips/changelog/2026-07-17-full-screen-clips-finalize-even-when-screencapturekit-stop-hangs.md +6 -0
  37. package/corpus/templates/clips/changelog/2026-07-17-normal-full-screen-clips-no-longer-stop-immediately-after-th.md +6 -0
  38. package/corpus/templates/clips/changelog/2026-07-17-rewind-can-hand-one-bounded-private-clip-to-your-agent.md +12 -0
  39. package/corpus/templates/clips/changelog/2026-07-17-rewind-home-can-copy-a-local-agent-prompt.md +6 -0
  40. package/corpus/templates/clips/changelog/2026-07-17-rewind-now-has-a-calm-home-status-focused-first-run-consent-.md +6 -0
  41. package/corpus/templates/clips/changelog/2026-07-17-rewind-settings-are-smaller-clearer-and-agent-first.md +6 -0
  42. package/corpus/templates/clips/changelog/2026-07-17-the-full-clips-interface-stays-available-while-recording.md +6 -0
  43. package/corpus/templates/clips/changelog/2026-07-18-rewind-organizes-recent-work-into-local-searchable-chapters.md +8 -0
  44. package/corpus/templates/clips/changelog/2026-07-18-searchable-rewind-chapters.md +6 -0
  45. package/corpus/templates/clips/changelog/2026-07-19-rewind-backed-recordings-now-start-immediately-after-the-cou.md +6 -0
  46. package/corpus/templates/clips/changelog/2026-07-20-rewind-can-set-up-your-local-agent-once-so-future-requests-w.md +6 -0
  47. package/corpus/templates/clips/desktop/package.json +1 -0
  48. package/corpus/templates/clips/desktop/scripts/sign-macos-local.ts +12 -1
  49. package/corpus/templates/clips/desktop/src/app.tsx +2498 -239
  50. package/corpus/templates/clips/desktop/src/components/ReadinessPanel.tsx +21 -1
  51. package/corpus/templates/clips/desktop/src/components/Switch.tsx +3 -0
  52. package/corpus/templates/clips/desktop/src/hooks/useMeetingTranscription.ts +156 -24
  53. package/corpus/templates/clips/desktop/src/lib/native-recording-warm.ts +6 -7
  54. package/corpus/templates/clips/desktop/src/lib/recorder.ts +1763 -1160
  55. package/corpus/templates/clips/desktop/src/lib/rewind-agent-prompt.ts +9 -0
  56. package/corpus/templates/clips/desktop/src/lib/rewind-recording-start.ts +20 -0
  57. package/corpus/templates/clips/desktop/src/main.tsx +3 -0
  58. package/corpus/templates/clips/desktop/src/overlays/countdown.tsx +14 -14
  59. package/corpus/templates/clips/desktop/src/overlays/onboarding.tsx +4 -4
  60. package/corpus/templates/clips/desktop/src/overlays/preparing.tsx +13 -0
  61. package/corpus/templates/clips/desktop/src/overlays/toolbar.tsx +27 -2
  62. package/corpus/templates/clips/desktop/src/shared/config.ts +16 -0
  63. package/corpus/templates/clips/desktop/src/styles.css +956 -134
  64. package/corpus/templates/clips/desktop/src-tauri/Cargo.toml +5 -0
  65. package/corpus/templates/clips/desktop/src-tauri/build.rs +69 -1
  66. package/corpus/templates/clips/desktop/src-tauri/src/accessibility.rs +386 -12
  67. package/corpus/templates/clips/desktop/src-tauri/src/capture_audio_bus.rs +382 -0
  68. package/corpus/templates/clips/desktop/src-tauri/src/capture_graph.rs +777 -0
  69. package/corpus/templates/clips/desktop/src-tauri/src/clips/mod.rs +249 -22
  70. package/corpus/templates/clips/desktop/src-tauri/src/config.rs +148 -1
  71. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +58 -4
  72. package/corpus/templates/clips/desktop/src-tauri/src/logfile.rs +13 -1
  73. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/custom_capture.rs +1505 -51
  74. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/live_upload.rs +124 -0
  75. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +1006 -95
  76. package/corpus/templates/clips/desktop/src-tauri/src/rewind_capture_suspension.rs +165 -0
  77. package/corpus/templates/clips/desktop/src-tauri/src/rewind_chapters.rs +2434 -0
  78. package/corpus/templates/clips/desktop/src-tauri/src/rewind_clip.rs +1650 -0
  79. package/corpus/templates/clips/desktop/src-tauri/src/rewind_egress.rs +643 -0
  80. package/corpus/templates/clips/desktop/src-tauri/src/rewind_local_ask.rs +803 -0
  81. package/corpus/templates/clips/desktop/src-tauri/src/rewind_meeting_history.rs +595 -0
  82. package/corpus/templates/clips/desktop/src-tauri/src/screen_memory.rs +2900 -91
  83. package/corpus/templates/clips/desktop/src-tauri/src/screen_memory_ocr.rs +360 -0
  84. package/corpus/templates/clips/desktop/src-tauri/src/screen_memory_transcript.rs +408 -0
  85. package/corpus/templates/clips/desktop/src-tauri/src/shortcuts.rs +114 -33
  86. package/corpus/templates/clips/desktop/src-tauri/src/state.rs +2 -2
  87. package/corpus/templates/clips/desktop/src-tauri/src/system_audio.rs +13 -3
  88. package/corpus/templates/clips/desktop/src-tauri/src/tray.rs +4 -1
  89. package/corpus/templates/clips/desktop/src-tauri/src/util.rs +7 -13
  90. package/corpus/templates/clips/desktop/src-tauri/src/whisper_speech.rs +198 -11
  91. package/corpus/templates/clips/desktop/src-tauri/tauri.alpha.conf.json +17 -0
  92. package/dist/cli/mcp-config-writers.d.ts +2 -2
  93. package/dist/cli/mcp-config-writers.d.ts.map +1 -1
  94. package/dist/cli/mcp-config-writers.js +6 -6
  95. package/dist/cli/mcp-config-writers.js.map +1 -1
  96. package/dist/cli/mcp.d.ts +14 -0
  97. package/dist/cli/mcp.d.ts.map +1 -1
  98. package/dist/cli/mcp.js +79 -0
  99. package/dist/cli/mcp.js.map +1 -1
  100. package/dist/cli/skills-content/help.d.ts +1 -1
  101. package/dist/cli/skills-content/help.d.ts.map +1 -1
  102. package/dist/cli/skills-content/help.js +4 -3
  103. package/dist/cli/skills-content/help.js.map +1 -1
  104. package/dist/cli/skills-content/index.d.ts +1 -0
  105. package/dist/cli/skills-content/index.d.ts.map +1 -1
  106. package/dist/cli/skills-content/index.js +1 -0
  107. package/dist/cli/skills-content/index.js.map +1 -1
  108. package/dist/cli/skills-content/rewind-skill.d.ts +2 -0
  109. package/dist/cli/skills-content/rewind-skill.d.ts.map +1 -0
  110. package/dist/cli/skills-content/rewind-skill.js +53 -0
  111. package/dist/cli/skills-content/rewind-skill.js.map +1 -0
  112. package/dist/cli/skills.d.ts +6 -0
  113. package/dist/cli/skills.d.ts.map +1 -1
  114. package/dist/cli/skills.js +90 -14
  115. package/dist/cli/skills.js.map +1 -1
  116. package/dist/mcp/screen-memory-stdio.d.ts +365 -0
  117. package/dist/mcp/screen-memory-stdio.d.ts.map +1 -1
  118. package/dist/mcp/screen-memory-stdio.js +1014 -91
  119. package/dist/mcp/screen-memory-stdio.js.map +1 -1
  120. package/dist/mcp-client/index.d.ts +1 -1
  121. package/dist/mcp-client/index.d.ts.map +1 -1
  122. package/dist/mcp-client/index.js +1 -1
  123. package/dist/mcp-client/index.js.map +1 -1
  124. package/dist/mcp-client/screen-memory-local.d.ts +90 -0
  125. package/dist/mcp-client/screen-memory-local.d.ts.map +1 -1
  126. package/dist/mcp-client/screen-memory-local.js +590 -12
  127. package/dist/mcp-client/screen-memory-local.js.map +1 -1
  128. package/dist/notifications/routes.d.ts +3 -3
  129. package/dist/observability/routes.d.ts +1 -1
  130. package/dist/provider-api/actions/provider-api.d.ts +4 -4
  131. package/dist/resources/handlers.d.ts +1 -1
  132. package/package.json +1 -1
  133. package/src/cli/mcp-config-writers.ts +6 -4
  134. package/src/cli/mcp.ts +124 -0
  135. package/src/cli/skills-content/help.ts +4 -3
  136. package/src/cli/skills-content/index.ts +1 -0
  137. package/src/cli/skills-content/rewind-skill.ts +52 -0
  138. package/src/cli/skills.ts +115 -13
  139. package/src/mcp/screen-memory-stdio.ts +1360 -104
  140. package/src/mcp-client/index.ts +9 -0
  141. package/src/mcp-client/screen-memory-local.ts +847 -13
@@ -1 +1 @@
1
- {"version":3,"file":"screen-memory-local.js","sourceRoot":"","sources":["../../src/mcp-client/screen-memory-local.ts"],"names":[],"mappings":"AA0DA,MAAM,cAAc,GAAuB;IACzC,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,KAAK;IACb,cAAc,EAAE,EAAE;IAClB,QAAQ,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI;IACjC,cAAc,EAAE,CAAC,GAAG,EAAE;IACtB,qBAAqB,EAAE,EAAE;CAC1B,CAAC;AAEF,MAAM,WAAW,GAAG;IAClB,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,qBAAqB;CACtB,CAAC;AAEF,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAChE,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,QAAgB;IACtD,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACjE,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC;AACnE,CAAC;AAED,SAAS,YAAY,CAAC,KAAc,EAAE,QAAiB;IACrD,OAAO,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;AACvD,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,IA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AM,EAAE,IAAI,CAAC,MAAM;QACnB,UAAU,EAAE,IAAI,CAAC,IAAI;QACrB,YAAY,EAAE,IAAI,CAAC,MAAM;QACzB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK;QACnB,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,YAAY;QACZ,eAAe,EAAE,MAAM;QACvB,eAAe,EAAE,MAAM;QACvB,IAAI,EACF,KAAK,KAAK,UAAU;YAClB,CAAC,CAAC,2HAA2H;YAC7H,CAAC,CAAC,KAAK,KAAK,OAAO;gBACjB,CAAC,CAAC,sEAAsE;gBACxE,CAAC,CAAC,gDAAgD;KACzD,CAAC;AACJ,CAAC","sourcesContent":["export interface ScreenMemoryConfig {\n enabled: boolean;\n paused: boolean;\n retentionHours: number;\n maxBytes: number;\n segmentSeconds: number;\n sampleIntervalSeconds: number;\n}\n\nexport interface ScreenMemoryStatus {\n feature: \"screen-memory\";\n localOnly: true;\n enabled: boolean;\n paused: boolean;\n state: \"disabled\" | \"paused\" | \"ready\" | \"empty\" | \"unavailable\";\n config: ScreenMemoryConfig;\n configPath: string | null;\n configSource: \"feature-config\" | \"standalone\" | \"default\";\n dataDirs: string[];\n contextFiles: string[];\n captureCount: number;\n storageBytes: number;\n oldestCaptureAt: string | null;\n newestCaptureAt: string | null;\n note: string;\n}\n\nexport interface ScreenMemoryContextItem {\n capturedAt: string | null;\n appName: string | null;\n windowTitle: string | null;\n bundleId: string | null;\n url: string | null;\n title: string | null;\n source: string | null;\n text: string;\n sourceFile: string;\n}\n\nexport interface ScreenMemoryQueryResult {\n feature: \"screen-memory\";\n localOnly: true;\n enabled: boolean;\n paused: boolean;\n query: string | null;\n sinceMinutes: number | null;\n count: number;\n items: ScreenMemoryContextItem[];\n contextFiles: string[];\n note: string;\n}\n\nexport interface ScreenMemoryLocalOptions {\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n homeDir?: string;\n}\n\nconst DEFAULT_CONFIG: ScreenMemoryConfig = {\n enabled: false,\n paused: false,\n retentionHours: 24,\n maxBytes: 20 * 1024 * 1024 * 1024,\n segmentSeconds: 5 * 60,\n sampleIntervalSeconds: 10,\n};\n\nconst JSONL_NAMES = [\n \"context.jsonl\",\n \"events.jsonl\",\n \"snapshots.jsonl\",\n \"screen-memory.jsonl\",\n];\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction positiveNumber(value: unknown, fallback: number): number {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nfunction booleanValue(value: unknown, fallback: boolean): boolean {\n return typeof value === \"boolean\" ? value : fallback;\n}\n\nfunction normalizeConfig(value: unknown): ScreenMemoryConfig {\n const raw = asRecord(value) ?? {};\n return {\n enabled: booleanValue(raw.enabled, DEFAULT_CONFIG.enabled),\n paused: booleanValue(raw.paused, DEFAULT_CONFIG.paused),\n retentionHours: positiveNumber(\n raw.retentionHours,\n DEFAULT_CONFIG.retentionHours,\n ),\n maxBytes: positiveNumber(raw.maxBytes, DEFAULT_CONFIG.maxBytes),\n segmentSeconds: positiveNumber(\n raw.segmentSeconds,\n DEFAULT_CONFIG.segmentSeconds,\n ),\n sampleIntervalSeconds: positiveNumber(\n raw.sampleIntervalSeconds,\n DEFAULT_CONFIG.sampleIntervalSeconds,\n ),\n };\n}\n\nasync function nodeModules() {\n const [fs, path, os] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n import(\"node:os\"),\n ]);\n return { fs, path, os };\n}\n\nasync function exists(pathname: string): Promise<boolean> {\n const { fs } = await nodeModules();\n try {\n await fs.stat(pathname);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readJson(pathname: string): Promise<unknown | null> {\n const { fs } = await nodeModules();\n try {\n return JSON.parse(await fs.readFile(pathname, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nasync function writeJson(pathname: string, value: unknown): Promise<void> {\n const { fs, path } = await nodeModules();\n await fs.mkdir(path.dirname(pathname), { recursive: true });\n await fs.writeFile(pathname, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n\nasync function resolvePaths(options: ScreenMemoryLocalOptions = {}): Promise<{\n featureConfigPaths: string[];\n standaloneConfigPath: string;\n dataDirs: string[];\n}> {\n const { path, os } = await nodeModules();\n const env = options.env ?? process.env;\n const platform = options.platform ?? process.platform;\n const home = options.homeDir ?? os.homedir();\n\n const appDataBase =\n platform === \"darwin\"\n ? path.join(home, \"Library\", \"Application Support\")\n : platform === \"win32\"\n ? env.APPDATA || path.join(home, \"AppData\", \"Roaming\")\n : env.XDG_DATA_HOME || path.join(home, \".local\", \"share\");\n const appConfigBase =\n platform === \"darwin\" || platform === \"win32\"\n ? appDataBase\n : env.XDG_CONFIG_HOME || path.join(home, \".config\");\n const clipsDataDir = path.join(appDataBase, \"com.clips.tray\");\n const clipsConfigDir = path.join(appConfigBase, \"com.clips.tray\");\n const fallbackDir = path.join(home, \".agent-native\", \"screen-memory\");\n const envDir =\n env.AGENT_NATIVE_SCREEN_MEMORY_DIR ?? env.CLIPS_SCREEN_MEMORY_DIR;\n const envConfig = env.AGENT_NATIVE_SCREEN_MEMORY_CONFIG;\n\n const dataDirs = [\n ...(envDir ? [envDir] : []),\n path.join(clipsDataDir, \"screen-memory\"),\n ...(clipsConfigDir === clipsDataDir\n ? []\n : [path.join(clipsConfigDir, \"screen-memory\")]),\n fallbackDir,\n ];\n\n return {\n featureConfigPaths: [\n ...(envConfig ? [envConfig] : []),\n path.join(clipsDataDir, \"feature-config.json\"),\n ...(clipsConfigDir === clipsDataDir\n ? []\n : [path.join(clipsConfigDir, \"feature-config.json\")]),\n ],\n standaloneConfigPath: path.join(fallbackDir, \"config.json\"),\n dataDirs,\n };\n}\n\nasync function readConfigInfo(options: ScreenMemoryLocalOptions = {}): Promise<{\n config: ScreenMemoryConfig;\n path: string | null;\n source: ScreenMemoryStatus[\"configSource\"];\n raw: Record<string, unknown> | null;\n nested: boolean;\n}> {\n const paths = await resolvePaths(options);\n for (const pathname of paths.featureConfigPaths) {\n const raw = asRecord(await readJson(pathname));\n if (!raw) continue;\n const nested = asRecord(raw.screenMemory);\n if (nested) {\n return {\n config: normalizeConfig(nested),\n path: pathname,\n source: \"feature-config\",\n raw,\n nested: true,\n };\n }\n if (\n \"enabled\" in raw ||\n \"paused\" in raw ||\n \"retentionHours\" in raw ||\n \"maxBytes\" in raw\n ) {\n return {\n config: normalizeConfig(raw),\n path: pathname,\n source: \"standalone\",\n raw,\n nested: false,\n };\n }\n }\n\n const standalone = asRecord(await readJson(paths.standaloneConfigPath));\n if (standalone) {\n return {\n config: normalizeConfig(standalone),\n path: paths.standaloneConfigPath,\n source: \"standalone\",\n raw: standalone,\n nested: false,\n };\n }\n\n return {\n config: { ...DEFAULT_CONFIG },\n path: null,\n source: \"default\",\n raw: null,\n nested: false,\n };\n}\n\nexport async function configureScreenMemory(\n patch: Partial<ScreenMemoryConfig>,\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryStatus> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const next = normalizeConfig({ ...info.config, ...patch });\n const targetPath = info.path ?? paths.standaloneConfigPath;\n\n if (info.raw && info.nested) {\n await writeJson(targetPath, { ...info.raw, screenMemory: next });\n } else {\n await writeJson(targetPath, next);\n }\n\n return readScreenMemoryStatus(options);\n}\n\nasync function contextFilesFor(\n dataDirs: string[],\n): Promise<{ files: string[]; storageBytes: number }> {\n const { fs, path } = await nodeModules();\n const files: string[] = [];\n let storageBytes = 0;\n\n for (const dir of dataDirs) {\n if (!(await exists(dir))) continue;\n for (const name of JSONL_NAMES) {\n const candidate = path.join(dir, name);\n try {\n const stat = await fs.stat(candidate);\n if (stat.isFile()) {\n files.push(candidate);\n storageBytes += stat.size;\n }\n } catch {\n // ignore missing candidate files\n }\n }\n }\n\n return { files, storageBytes };\n}\n\nfunction firstString(\n raw: Record<string, unknown>,\n keys: string[],\n): string | null {\n for (const key of keys) {\n const value = raw[key];\n if (typeof value === \"string\" && value.trim()) return value;\n }\n return null;\n}\n\nfunction normalizeContextItem(\n value: unknown,\n sourceFile: string,\n): ScreenMemoryContextItem | null {\n const raw = asRecord(value);\n if (!raw) return null;\n const text =\n firstString(raw, [\n \"text\",\n \"ocrText\",\n \"visibleText\",\n \"summary\",\n \"caption\",\n ]) ?? \"\";\n const capturedAt = firstString(raw, [\n \"capturedAt\",\n \"timestamp\",\n \"time\",\n \"createdAt\",\n ]);\n return {\n capturedAt,\n appName: firstString(raw, [\"appName\", \"application\", \"bundleName\"]),\n windowTitle: firstString(raw, [\"windowTitle\", \"window\", \"activeWindow\"]),\n bundleId: firstString(raw, [\"bundleId\", \"appBundleId\"]),\n url: firstString(raw, [\"url\", \"pageUrl\"]),\n title: firstString(raw, [\"title\", \"pageTitle\"]),\n source: firstString(raw, [\"source\", \"kind\"]),\n text,\n sourceFile,\n };\n}\n\nfunction itemTime(item: ScreenMemoryContextItem): number {\n if (!item.capturedAt) return 0;\n const parsed = Date.parse(item.capturedAt);\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\nasync function readItems(files: string[]): Promise<ScreenMemoryContextItem[]> {\n const { fs } = await nodeModules();\n const items: ScreenMemoryContextItem[] = [];\n\n for (const file of files) {\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch {\n continue;\n }\n const lines = text.split(/\\r?\\n/).filter(Boolean).slice(-10_000);\n for (const line of lines) {\n try {\n const item = normalizeContextItem(JSON.parse(line), file);\n if (item) items.push(item);\n } catch {\n // Keep one malformed row from hiding the rest of the local context.\n }\n }\n }\n\n return items.sort((a, b) => itemTime(b) - itemTime(a));\n}\n\nexport async function queryScreenMemoryContext(\n args: {\n query?: string | null;\n limit?: number | null;\n sinceMinutes?: number | null;\n } = {},\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryQueryResult> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const { files } = await contextFilesFor(paths.dataDirs);\n const query = args.query?.trim() || null;\n const limit = Math.min(Math.max(Math.trunc(args.limit ?? 10), 1), 50);\n const sinceMinutes =\n typeof args.sinceMinutes === \"number\" && Number.isFinite(args.sinceMinutes)\n ? Math.max(args.sinceMinutes, 0)\n : null;\n const cutoff =\n sinceMinutes === null ? null : Date.now() - sinceMinutes * 60 * 1000;\n\n const needle = query?.toLowerCase() ?? null;\n const items = (await readItems(files)).filter((item) => {\n if (cutoff !== null) {\n const time = itemTime(item);\n if (!time || time < cutoff) return false;\n }\n if (!needle) return true;\n return JSON.stringify(item).toLowerCase().includes(needle);\n });\n\n return {\n feature: \"screen-memory\",\n localOnly: true,\n enabled: info.config.enabled,\n paused: info.config.paused,\n query,\n sinceMinutes,\n count: items.length,\n items: items.slice(0, limit),\n contextFiles: files,\n note:\n files.length === 0\n ? \"No local Screen Memory context files were found. Enable Screen Memory in Clips desktop and keep the local MCP capability connected.\"\n : \"Local Screen Memory context only. Do not treat this as shared, hosted, or exhaustive.\",\n };\n}\n\nexport async function readScreenMemoryStatus(\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryStatus> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const { files, storageBytes } = await contextFilesFor(paths.dataDirs);\n const items = await readItems(files);\n const times = items.map(itemTime).filter(Boolean);\n const oldest = times.length\n ? new Date(Math.min(...times)).toISOString()\n : null;\n const newest = times.length\n ? new Date(Math.max(...times)).toISOString()\n : null;\n const state = !info.config.enabled\n ? \"disabled\"\n : info.config.paused\n ? \"paused\"\n : files.length === 0\n ? \"empty\"\n : \"ready\";\n\n return {\n feature: \"screen-memory\",\n localOnly: true,\n enabled: info.config.enabled,\n paused: info.config.paused,\n state,\n config: info.config,\n configPath: info.path,\n configSource: info.source,\n dataDirs: paths.dataDirs,\n contextFiles: files,\n captureCount: items.length,\n storageBytes,\n oldestCaptureAt: oldest,\n newestCaptureAt: newest,\n note:\n state === \"disabled\"\n ? \"Screen Memory is disabled by default. Turn it on from Clips desktop Settings before agents can use recent screen context.\"\n : state === \"empty\"\n ? \"Screen Memory is enabled, but no local context files were found yet.\"\n : \"Screen Memory status is local to this machine.\",\n };\n}\n"]}
1
+ {"version":3,"file":"screen-memory-local.js","sourceRoot":"","sources":["../../src/mcp-client/screen-memory-local.ts"],"names":[],"mappings":"AA0JA,MAAM,cAAc,GAAuB;IACzC,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,KAAK;IACb,cAAc,EAAE,CAAC;IACjB,QAAQ,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI;IACjC,cAAc,EAAE,CAAC,GAAG,EAAE;IACtB,qBAAqB,EAAE,EAAE;IACzB,WAAW,EAAE,SAAS;IACtB,mBAAmB,EAAE,IAAI;IACzB,kBAAkB,EAAE,SAAS;IAC7B,iBAAiB,EAAE;QACjB,yBAAyB;QACzB,4BAA4B;QAC5B,uBAAuB;QACvB,uBAAuB;QACvB,uBAAuB;KACxB;IACD,qBAAqB,EAAE,KAAK;CAC7B,CAAC;AAEF,MAAM,WAAW,GAAG;IAClB,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,qBAAqB;CACtB,CAAC;AACF,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAQzC,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAChE,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,QAAgB;IACtD,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KA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OAAO,CAAC;IAEhB,OAAO;QACL,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,IAAI;QACf,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;QAC5B,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM;QAC1B,KAAK;QACL,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,UAAU,EAAE,IAAI,CAAC,IAAI;QACrB,YAAY,EAAE,IAAI,CAAC,MAAM;QACzB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK;QACnB,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,YAAY;QACZ,eAAe,EAAE,MAAM;QACvB,eAAe,EAAE,MAAM;QACvB,IAAI,EACF,KAAK,KAAK,UAAU;YAClB,CAAC,CAAC,2HAA2H;YAC7H,CAAC,CAAC,KAAK,KAAK,OAAO;gBACjB,CAAC,CAAC,sEAAsE;gBACxE,CAAC,CAAC,gDAAgD;KACzD,CAAC;AACJ,CAAC","sourcesContent":["export interface ScreenMemoryConfig {\n enabled: boolean;\n paused: boolean;\n retentionHours: number;\n maxBytes: number;\n segmentSeconds: number;\n sampleIntervalSeconds: number;\n captureMode: \"visuals\" | \"visuals-audio\";\n reviewBeforeSending: boolean;\n agentClipRetention: \"forever\" | \"24-hours\" | \"7-days\" | \"30-days\";\n excludedBundleIds: string[];\n excludePrivateWindows: boolean;\n}\n\nexport interface ScreenMemoryStatus {\n feature: \"screen-memory\";\n localOnly: true;\n enabled: boolean;\n paused: boolean;\n state: \"disabled\" | \"paused\" | \"ready\" | \"empty\" | \"unavailable\";\n config: ScreenMemoryConfig;\n configPath: string | null;\n configSource: \"feature-config\" | \"standalone\" | \"default\";\n dataDirs: string[];\n contextFiles: string[];\n captureCount: number;\n storageBytes: number;\n oldestCaptureAt: string | null;\n newestCaptureAt: string | null;\n note: string;\n}\n\nexport interface ScreenMemoryContextItem {\n capturedAt: string | null;\n appName: string | null;\n windowTitle: string | null;\n bundleId: string | null;\n url: string | null;\n title: string | null;\n source: string | null;\n text: string;\n sourceFile: string;\n}\n\nexport type ScreenMemoryEvidenceSourceType =\n | \"app-context\"\n | \"transcript\"\n | \"ocr\";\n\nexport interface ScreenMemoryTimeRange {\n startedAt: string | null;\n endedAt: string;\n}\n\nexport interface ScreenMemoryCoverageGap {\n startedAt: string | null;\n endedAt: string | null;\n reason:\n | \"no-context-files\"\n | \"no-evidence-in-requested-range\"\n | \"missing-before-first-evidence\"\n | \"capture-stale\"\n | \"timestamps-unavailable\"\n | \"index-pending\"\n | \"index-failed\"\n | \"index-skipped\"\n | \"privacy-excluded-or-unretained\";\n}\n\nexport interface ScreenMemorySegmentReference {\n id: string;\n startedAt: string | null;\n endedAt: string | null;\n}\n\nexport interface ScreenMemoryEvidenceItem {\n id: string;\n momentId: string;\n capturedAt: string | null;\n sourceType: ScreenMemoryEvidenceSourceType;\n excerpt: string;\n excerptTruncated: boolean;\n appName: string | null;\n windowTitle: string | null;\n bundleId: string | null;\n url: string | null;\n title: string | null;\n segmentRefs: ScreenMemorySegmentReference[];\n jumpTarget: {\n kind: \"screen-memory-moment\";\n momentId: string;\n capturedAt: string | null;\n segmentId: string | null;\n };\n}\n\nexport interface ScreenMemoryRetrievalCoverage {\n requestedRange: ScreenMemoryTimeRange;\n coveredRange: { startedAt: string | null; endedAt: string | null };\n gaps: ScreenMemoryCoverageGap[];\n}\n\nexport interface ScreenMemoryTruncation {\n itemLimit: number;\n returnedItems: number;\n omittedItems: number;\n maxExcerptChars: number;\n excerptsTruncated: number;\n sourceRowsReadLimit: number;\n sourceRowsReadTruncated: boolean;\n}\n\nexport interface ScreenMemoryQueryResult {\n feature: \"screen-memory\";\n localOnly: true;\n enabled: boolean;\n paused: boolean;\n query: string | null;\n sinceMinutes: number | null;\n count: number;\n items: ScreenMemoryContextItem[];\n /** Stable, bounded local retrieval contract. `items` remains for legacy callers. */\n evidence: ScreenMemoryEvidenceItem[];\n coverage: ScreenMemoryRetrievalCoverage;\n truncation: ScreenMemoryTruncation;\n contextFiles: string[];\n note: string;\n}\n\nexport interface ScreenMemoryLocalOptions {\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n homeDir?: string;\n /** Test-only clock injection; retrieval never reads network time. */\n now?: () => Date;\n}\n\nexport interface ScreenMemoryAgentQueryResult extends ScreenMemoryQueryResult {\n egress: {\n requestId: string;\n packet: {\n question: string;\n evidence: Array<{\n id: string;\n momentId: string;\n sourceType: ScreenMemoryEvidenceSourceType;\n capturedAt: string | null;\n excerpt: string;\n }>;\n };\n note: string;\n };\n}\n\nconst DEFAULT_CONFIG: ScreenMemoryConfig = {\n enabled: false,\n paused: false,\n retentionHours: 8,\n maxBytes: 20 * 1024 * 1024 * 1024,\n segmentSeconds: 5 * 60,\n sampleIntervalSeconds: 10,\n captureMode: \"visuals\",\n reviewBeforeSending: true,\n agentClipRetention: \"forever\",\n excludedBundleIds: [\n \"com.1password.1password\",\n \"com.agilebits.onepassword7\",\n \"com.bitwarden.desktop\",\n \"com.dashlane.dashlane\",\n \"com.lastpass.lastpass\",\n ],\n excludePrivateWindows: false,\n};\n\nconst JSONL_NAMES = [\n \"context.jsonl\",\n \"events.jsonl\",\n \"snapshots.jsonl\",\n \"screen-memory.jsonl\",\n];\nconst MAX_SOURCE_ROWS = 10_000;\nconst MAX_EXCERPT_CHARS = 1_200;\nconst MAX_TRANSCRIPT_JOIN_GAP_MS = 2_000;\ntype ScreenMemoryOcrIndexState =\n | \"pending\"\n | \"indexing\"\n | \"ready\"\n | \"failed\"\n | \"skipped\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction positiveNumber(value: unknown, fallback: number): number {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nfunction booleanValue(value: unknown, fallback: boolean): boolean {\n return typeof value === \"boolean\" ? value : fallback;\n}\n\nfunction enumValue<const T extends string>(\n value: unknown,\n allowed: readonly T[],\n fallback: T,\n): T {\n return typeof value === \"string\" && allowed.includes(value as T)\n ? (value as T)\n : fallback;\n}\n\nfunction bundleIds(value: unknown, fallback: string[]): string[] {\n if (!Array.isArray(value)) return [...fallback];\n return [\n ...new Set(\n value\n .filter((item): item is string => typeof item === \"string\")\n .map((item) => item.trim().toLowerCase())\n .filter(Boolean),\n ),\n ].sort();\n}\n\nfunction normalizeConfig(value: unknown): ScreenMemoryConfig {\n const raw = asRecord(value) ?? {};\n return {\n enabled: booleanValue(raw.enabled, DEFAULT_CONFIG.enabled),\n paused: booleanValue(raw.paused, DEFAULT_CONFIG.paused),\n retentionHours: Math.min(\n positiveNumber(raw.retentionHours, DEFAULT_CONFIG.retentionHours),\n 24,\n ),\n maxBytes: positiveNumber(raw.maxBytes, DEFAULT_CONFIG.maxBytes),\n segmentSeconds: positiveNumber(\n raw.segmentSeconds,\n DEFAULT_CONFIG.segmentSeconds,\n ),\n sampleIntervalSeconds: positiveNumber(\n raw.sampleIntervalSeconds,\n DEFAULT_CONFIG.sampleIntervalSeconds,\n ),\n captureMode: enumValue(\n raw.captureMode,\n [\"visuals\", \"visuals-audio\"],\n DEFAULT_CONFIG.captureMode,\n ),\n reviewBeforeSending:\n typeof raw.reviewBeforeSending === \"boolean\"\n ? raw.reviewBeforeSending\n : DEFAULT_CONFIG.reviewBeforeSending,\n agentClipRetention: enumValue(\n raw.agentClipRetention,\n [\"forever\", \"24-hours\", \"7-days\", \"30-days\"],\n DEFAULT_CONFIG.agentClipRetention,\n ),\n excludedBundleIds: bundleIds(\n raw.excludedBundleIds,\n DEFAULT_CONFIG.excludedBundleIds,\n ),\n excludePrivateWindows:\n typeof raw.excludePrivateWindows === \"boolean\"\n ? raw.excludePrivateWindows\n : DEFAULT_CONFIG.excludePrivateWindows,\n };\n}\n\nasync function nodeModules() {\n const [fs, path, os] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n import(\"node:os\"),\n ]);\n return { fs, path, os };\n}\n\nasync function exists(pathname: string): Promise<boolean> {\n const { fs } = await nodeModules();\n try {\n await fs.stat(pathname);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readJson(pathname: string): Promise<unknown | null> {\n const { fs } = await nodeModules();\n try {\n return JSON.parse(await fs.readFile(pathname, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nasync function writeJson(pathname: string, value: unknown): Promise<void> {\n const { fs, path } = await nodeModules();\n await fs.mkdir(path.dirname(pathname), { recursive: true });\n await fs.writeFile(pathname, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n\nasync function resolvePaths(options: ScreenMemoryLocalOptions = {}): Promise<{\n featureConfigPaths: string[];\n standaloneConfigPath: string;\n dataDirs: string[];\n}> {\n const { path, os } = await nodeModules();\n const env = options.env ?? process.env;\n const platform = options.platform ?? process.platform;\n const home = options.homeDir ?? os.homedir();\n\n const appDataBase =\n platform === \"darwin\"\n ? path.join(home, \"Library\", \"Application Support\")\n : platform === \"win32\"\n ? env.APPDATA || path.join(home, \"AppData\", \"Roaming\")\n : env.XDG_DATA_HOME || path.join(home, \".local\", \"share\");\n const appConfigBase =\n platform === \"darwin\" || platform === \"win32\"\n ? appDataBase\n : env.XDG_CONFIG_HOME || path.join(home, \".config\");\n const clipsDataDir = path.join(appDataBase, \"com.clips.tray\");\n const clipsConfigDir = path.join(appConfigBase, \"com.clips.tray\");\n const fallbackDir = path.join(home, \".agent-native\", \"screen-memory\");\n const envDir =\n env.AGENT_NATIVE_SCREEN_MEMORY_DIR ?? env.CLIPS_SCREEN_MEMORY_DIR;\n const envConfig = env.AGENT_NATIVE_SCREEN_MEMORY_CONFIG;\n\n const dataDirs = [\n ...(envDir ? [envDir] : []),\n path.join(clipsDataDir, \"screen-memory\"),\n ...(clipsConfigDir === clipsDataDir\n ? []\n : [path.join(clipsConfigDir, \"screen-memory\")]),\n fallbackDir,\n ];\n\n return {\n featureConfigPaths: [\n ...(envConfig ? [envConfig] : []),\n path.join(clipsDataDir, \"feature-config.json\"),\n ...(clipsConfigDir === clipsDataDir\n ? []\n : [path.join(clipsConfigDir, \"feature-config.json\")]),\n ],\n standaloneConfigPath: path.join(fallbackDir, \"config.json\"),\n dataDirs,\n };\n}\n\nasync function readConfigInfo(options: ScreenMemoryLocalOptions = {}): Promise<{\n config: ScreenMemoryConfig;\n path: string | null;\n source: ScreenMemoryStatus[\"configSource\"];\n raw: Record<string, unknown> | null;\n nested: boolean;\n}> {\n const paths = await resolvePaths(options);\n for (const pathname of paths.featureConfigPaths) {\n const raw = asRecord(await readJson(pathname));\n if (!raw) continue;\n const nested = asRecord(raw.screenMemory);\n if (nested) {\n return {\n config: normalizeConfig(nested),\n path: pathname,\n source: \"feature-config\",\n raw,\n nested: true,\n };\n }\n if (\n \"enabled\" in raw ||\n \"paused\" in raw ||\n \"retentionHours\" in raw ||\n \"maxBytes\" in raw\n ) {\n return {\n config: normalizeConfig(raw),\n path: pathname,\n source: \"standalone\",\n raw,\n nested: false,\n };\n }\n }\n\n const standalone = asRecord(await readJson(paths.standaloneConfigPath));\n if (standalone) {\n return {\n config: normalizeConfig(standalone),\n path: paths.standaloneConfigPath,\n source: \"standalone\",\n raw: standalone,\n nested: false,\n };\n }\n\n return {\n config: { ...DEFAULT_CONFIG },\n path: null,\n source: \"default\",\n raw: null,\n nested: false,\n };\n}\n\nexport async function configureScreenMemory(\n patch: Partial<ScreenMemoryConfig>,\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryStatus> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const next = normalizeConfig({ ...info.config, ...patch });\n const targetPath = info.path ?? paths.standaloneConfigPath;\n\n if (info.raw && info.nested) {\n await writeJson(targetPath, { ...info.raw, screenMemory: next });\n } else {\n await writeJson(targetPath, next);\n }\n\n return readScreenMemoryStatus(options);\n}\n\nasync function contextFilesFor(\n dataDirs: string[],\n): Promise<{ files: string[]; storageBytes: number }> {\n const { fs, path } = await nodeModules();\n const files: string[] = [];\n let storageBytes = 0;\n\n for (const dir of dataDirs) {\n if (!(await exists(dir))) continue;\n for (const name of JSONL_NAMES) {\n const candidate = path.join(dir, name);\n try {\n const stat = await fs.stat(candidate);\n if (stat.isFile()) {\n files.push(candidate);\n storageBytes += stat.size;\n }\n } catch {\n // ignore missing candidate files\n }\n }\n try {\n const names = await fs.readdir(dir);\n for (const name of names.filter(\n (entry) =>\n entry.endsWith(\".ocr.jsonl\") || entry.endsWith(\".transcript.jsonl\"),\n )) {\n const candidate = path.join(dir, name);\n const stat = await fs.stat(candidate);\n if (stat.isFile()) {\n files.push(candidate);\n storageBytes += stat.size;\n }\n }\n } catch {\n // ignore unavailable local directories\n }\n }\n\n return { files, storageBytes };\n}\n\nfunction firstString(\n raw: Record<string, unknown>,\n keys: string[],\n): string | null {\n for (const key of keys) {\n const value = raw[key];\n if (typeof value === \"string\" && value.trim()) return value;\n }\n return null;\n}\n\nfunction firstFiniteNumber(\n raw: Record<string, unknown>,\n keys: string[],\n): number | null {\n for (const key of keys) {\n const value = raw[key];\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n }\n return null;\n}\n\nfunction firstBoolean(\n raw: Record<string, unknown>,\n keys: string[],\n): boolean | null {\n for (const key of keys) {\n const value = raw[key];\n if (typeof value === \"boolean\") return value;\n }\n return null;\n}\n\nfunction normalizeContextItem(\n value: unknown,\n sourceFile: string,\n): ScreenMemoryContextItem | null {\n const raw = asRecord(value);\n if (!raw) return null;\n const text =\n firstString(raw, [\n \"text\",\n \"ocrText\",\n \"visibleText\",\n \"summary\",\n \"caption\",\n ]) ?? \"\";\n const capturedAt = firstString(raw, [\n \"capturedAt\",\n \"timestamp\",\n \"time\",\n \"createdAt\",\n ]);\n return {\n capturedAt,\n appName: firstString(raw, [\"appName\", \"application\", \"bundleName\"]),\n windowTitle: firstString(raw, [\"windowTitle\", \"window\", \"activeWindow\"]),\n bundleId: firstString(raw, [\"bundleId\", \"appBundleId\"]),\n url: firstString(raw, [\"url\", \"pageUrl\"]),\n title: firstString(raw, [\"title\", \"pageTitle\"]),\n source: firstString(raw, [\"source\", \"kind\"]),\n text,\n sourceFile,\n };\n}\n\nfunction itemTime(item: ScreenMemoryContextItem): number {\n if (!item.capturedAt) return 0;\n const parsed = Date.parse(item.capturedAt);\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\ninterface LocalContextRow {\n item: ScreenMemoryContextItem;\n raw: Record<string, unknown>;\n}\n\nfunction isPrivacyExcludedRow(\n row: LocalContextRow,\n config: ScreenMemoryConfig,\n): boolean {\n const bundleId = row.item.bundleId?.trim().toLowerCase();\n if (\n bundleId &&\n config.excludedBundleIds.some(\n (excluded) => excluded.trim().toLowerCase() === bundleId,\n )\n ) {\n return true;\n }\n\n if (!config.excludePrivateWindows) return false;\n if (\n firstBoolean(row.raw, [\n \"isPrivate\",\n \"is_private\",\n \"privateWindow\",\n \"private_window\",\n \"incognito\",\n ]) === true\n ) {\n return true;\n }\n const title = row.item.windowTitle?.toLowerCase() ?? \"\";\n return [\"incognito\", \"inprivate\", \"private browsing\", \"private window\"].some(\n (marker) => title.includes(marker),\n );\n}\n\nfunction rowTimeRange(\n rows: LocalContextRow[],\n fallback: ScreenMemoryTimeRange,\n): ScreenMemoryTimeRange {\n const times = rows\n .map(({ item }) => itemTime(item))\n .filter((time) => time > 0);\n if (times.length === 0) return fallback;\n return {\n startedAt: new Date(Math.min(...times)).toISOString(),\n endedAt: new Date(Math.max(...times)).toISOString(),\n };\n}\n\ninterface LocalTranscriptSpan {\n row: LocalContextRow;\n segmentId: string;\n source: string;\n startMs: number;\n endMs: number;\n}\n\ninterface LocalSegment {\n id: string;\n startedAt: string | null;\n endedAt: string | null;\n clean: boolean;\n}\n\nfunction stableId(prefix: string, value: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return `${prefix}-${(hash >>> 0).toString(36)}`;\n}\n\nfunction boundedExcerpt(value: string): {\n excerpt: string;\n excerptTruncated: boolean;\n} {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= MAX_EXCERPT_CHARS) {\n return { excerpt: normalized, excerptTruncated: false };\n }\n return {\n excerpt: `${normalized.slice(0, MAX_EXCERPT_CHARS - 1)}…`,\n excerptTruncated: true,\n };\n}\n\nfunction redactCredentialText(value: string): string {\n return value\n .replace(\n /\\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{12,}|AKIA[A-Z0-9]{16})\\b/g,\n \"[REDACTED CREDENTIAL]\",\n )\n .replace(/\\bBearer\\s+[A-Za-z0-9._~+\\/-]{8,}/gi, \"Bearer [REDACTED]\")\n .replace(\n /\\b(api[_-]?key|access[_-]?token|password|secret)\\s*[:=]\\s*([^\\s,;]{4,})/gi,\n \"$1=[REDACTED]\",\n );\n}\n\nfunction sourceTexts(\n raw: Record<string, unknown>,\n fallback: string,\n): Array<{ sourceType: ScreenMemoryEvidenceSourceType; text: string }> {\n const localTranscriptText =\n firstString(raw, [\"text\"]) &&\n firstString(raw, [\"segmentId\", \"segment_id\"]) &&\n (typeof raw.startMs === \"number\" || typeof raw.start_ms === \"number\")\n ? firstString(raw, [\"text\"])\n : null;\n const values: Array<{\n sourceType: ScreenMemoryEvidenceSourceType;\n keys: string[];\n }> = [\n { sourceType: \"transcript\", keys: [\"transcript\", \"transcriptText\"] },\n { sourceType: \"ocr\", keys: [\"ocrText\", \"visibleText\", \"ocr\"] },\n ];\n const evidence = values.flatMap(({ sourceType, keys }) => {\n const text = firstString(raw, keys);\n return text ? [{ sourceType, text }] : [];\n });\n if (localTranscriptText) {\n evidence.unshift({\n sourceType: \"transcript\",\n text: localTranscriptText,\n });\n }\n return evidence.length > 0\n ? evidence\n : fallback\n ? [{ sourceType: \"app-context\", text: fallback }]\n : [];\n}\n\nfunction segmentReferences(\n raw: Record<string, unknown>,\n capturedAt: string | null,\n segments: LocalSegment[],\n): ScreenMemorySegmentReference[] {\n const directId = firstString(raw, [\"segmentId\", \"segment_id\"]);\n const matched = directId\n ? segments.filter((segment) => segment.id === directId)\n : capturedAt\n ? segments.filter((segment) => {\n const moment = Date.parse(capturedAt);\n const started = segment.startedAt\n ? Date.parse(segment.startedAt)\n : NaN;\n const ended = segment.endedAt ? Date.parse(segment.endedAt) : NaN;\n return moment >= started && moment <= ended;\n })\n : [];\n return matched.slice(0, 3).map((segment) => ({\n id: segment.id,\n startedAt: segment.startedAt,\n endedAt: segment.endedAt,\n }));\n}\n\nfunction normalizeEvidence(\n row: LocalContextRow,\n segments: LocalSegment[],\n): ScreenMemoryEvidenceItem[] {\n const refs = segmentReferences(row.raw, row.item.capturedAt, segments);\n const base = [\n row.item.sourceFile,\n row.item.capturedAt ?? \"unknown-time\",\n row.item.appName ?? \"\",\n row.item.windowTitle ?? \"\",\n ].join(\"|\");\n const momentId =\n firstString(row.raw, [\"momentId\", \"moment_id\", \"eventId\", \"captureId\"]) ??\n stableId(\"moment\", base);\n const appContext =\n row.item.text ||\n [row.item.appName, row.item.windowTitle, row.item.title, row.item.url]\n .filter((value): value is string => Boolean(value))\n .join(\" — \");\n return sourceTexts(row.raw, appContext).map(({ sourceType, text }) => {\n const { excerpt, excerptTruncated } = boundedExcerpt(text);\n const id =\n firstString(row.raw, [\"evidenceId\", \"evidence_id\"]) ??\n stableId(\"evidence\", `${momentId}|${sourceType}|${text}`);\n return {\n id,\n momentId,\n capturedAt: row.item.capturedAt,\n sourceType,\n excerpt,\n excerptTruncated,\n appName: row.item.appName,\n windowTitle: row.item.windowTitle,\n bundleId: row.item.bundleId,\n url: row.item.url,\n title: row.item.title,\n segmentRefs: refs,\n jumpTarget: {\n kind: \"screen-memory-moment\",\n momentId,\n capturedAt: row.item.capturedAt,\n segmentId: refs[0]?.id ?? null,\n },\n };\n });\n}\n\nfunction transcriptSpan(row: LocalContextRow): LocalTranscriptSpan | null {\n const segmentId = firstString(row.raw, [\"segmentId\", \"segment_id\"]);\n const source = firstString(row.raw, [\"source\", \"kind\"]);\n const startMs = firstFiniteNumber(row.raw, [\"startMs\", \"start_ms\"]);\n const endMs = firstFiniteNumber(row.raw, [\"endMs\", \"end_ms\"]);\n if (\n !segmentId ||\n !source ||\n startMs === null ||\n endMs === null ||\n endMs <= startMs ||\n !firstString(row.raw, [\"text\"])\n ) {\n return null;\n }\n return { row, segmentId, source, startMs, endMs };\n}\n\n/**\n * Whisper emits phrase-sized rows, which can split an ordinary sentence in\n * the middle. Join only rows that are demonstrably continuous in the same\n * finalized segment and audio source. Stored sidecars remain untouched, and a\n * real pause, source switch, segment boundary, or excerpt bound starts a new\n * evidence item.\n */\nfunction coalesceTranscriptRows(rows: LocalContextRow[]): LocalContextRow[] {\n const passthrough: LocalContextRow[] = [];\n const groups = new Map<string, LocalTranscriptSpan[]>();\n\n for (const row of rows) {\n const span = transcriptSpan(row);\n if (!span) {\n passthrough.push(row);\n continue;\n }\n const key = [row.item.sourceFile, span.segmentId, span.source].join(\"\\0\");\n const group = groups.get(key) ?? [];\n group.push(span);\n groups.set(key, group);\n }\n\n const joined = [...groups.values()].flatMap((group) => {\n const ordered = group.sort((a, b) => a.startMs - b.startMs);\n const output: LocalContextRow[] = [];\n let current: LocalTranscriptSpan | null = null;\n\n for (const next of ordered) {\n const currentText = current\n ? (firstString(current.row.raw, [\"text\"]) ?? \"\")\n : \"\";\n const nextText = firstString(next.row.raw, [\"text\"]) ?? \"\";\n const gapMs = current ? next.startMs - current.endMs : Infinity;\n const combinedText = [currentText, nextText].filter(Boolean).join(\" \");\n const canJoin =\n current !== null &&\n gapMs >= 0 &&\n gapMs <= MAX_TRANSCRIPT_JOIN_GAP_MS &&\n combinedText.length <= MAX_EXCERPT_CHARS;\n\n if (!current || !canJoin) {\n if (current) output.push(current.row);\n current = {\n ...next,\n row: {\n item: { ...next.row.item },\n raw: { ...next.row.raw },\n },\n };\n continue;\n }\n\n current.endMs = next.endMs;\n current.row.item.text = combinedText;\n current.row.raw.text = combinedText;\n if (\"end_ms\" in current.row.raw) current.row.raw.end_ms = next.endMs;\n else current.row.raw.endMs = next.endMs;\n }\n if (current) output.push(current.row);\n return output;\n });\n\n return [...passthrough, ...joined].sort(\n (a, b) => itemTime(b.item) - itemTime(a.item),\n );\n}\n\nasync function readRows(files: string[]): Promise<{\n rows: LocalContextRow[];\n sourceRowsReadTruncated: boolean;\n}> {\n const { fs } = await nodeModules();\n const rows: LocalContextRow[] = [];\n let sourceRowsReadTruncated = false;\n\n for (const file of files) {\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch {\n continue;\n }\n const allLines = text.split(/\\r?\\n/).filter(Boolean);\n if (allLines.length > MAX_SOURCE_ROWS) sourceRowsReadTruncated = true;\n const lines = allLines.slice(-MAX_SOURCE_ROWS);\n for (const line of lines) {\n try {\n const raw = asRecord(JSON.parse(line));\n const item = raw ? normalizeContextItem(raw, file) : null;\n if (item && raw) rows.push({ item, raw });\n } catch {\n // Keep one malformed row from hiding the rest of the local context.\n }\n }\n }\n\n return {\n rows: coalesceTranscriptRows(rows),\n sourceRowsReadTruncated,\n };\n}\n\nasync function readItems(files: string[]): Promise<ScreenMemoryContextItem[]> {\n const { rows } = await readRows(files);\n return rows.map(({ item }) => item);\n}\n\nasync function readSegments(dataDirs: string[]): Promise<LocalSegment[]> {\n const { fs, path } = await nodeModules();\n const segments: LocalSegment[] = [];\n for (const dir of dataDirs) {\n let names: string[] = [];\n try {\n names = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const name of names.filter((candidate) =>\n candidate.endsWith(\".json\"),\n )) {\n const raw = asRecord(await readJson(path.join(dir, name)));\n const id = raw && firstString(raw, [\"id\"]);\n if (!raw || !id) continue;\n const mediaPath = firstString(raw, [\"path\"]);\n let retained = true;\n if (mediaPath) {\n try {\n await fs.access(mediaPath);\n } catch {\n retained = false;\n }\n }\n segments.push({\n id,\n startedAt: firstString(raw, [\"startedAt\"]),\n endedAt: firstString(raw, [\"endedAt\"]),\n clean:\n retained &&\n raw.exclusionTainted !== true &&\n raw.corrupt !== true &&\n !firstString(raw, [\"error\"]),\n });\n }\n }\n return segments;\n}\n\nasync function readOcrIndexStates(\n dataDirs: string[],\n): Promise<Array<{ segmentId: string; state: ScreenMemoryOcrIndexState }>> {\n const { fs, path } = await nodeModules();\n const states: Array<{ segmentId: string; state: ScreenMemoryOcrIndexState }> =\n [];\n for (const dir of dataDirs) {\n let names: string[] = [];\n try {\n names = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const name of names.filter(\n (entry) =>\n entry.endsWith(\".ocr-status.json\") ||\n entry.endsWith(\".transcript-status.json\"),\n )) {\n const raw = asRecord(await readJson(path.join(dir, name)));\n const rawState = String(raw?.state);\n const state = rawState === \"transcribing\" ? \"indexing\" : rawState;\n const suffix = name.endsWith(\".ocr-status.json\")\n ? \".ocr-status.json\"\n : \".transcript-status.json\";\n const segmentId = name.slice(0, -suffix.length);\n if (\n [\"pending\", \"indexing\", \"ready\", \"failed\", \"skipped\"].includes(\n String(state),\n )\n ) {\n states.push({ segmentId, state: state as ScreenMemoryOcrIndexState });\n }\n }\n }\n return states;\n}\n\nexport async function queryScreenMemoryContext(\n args: {\n query?: string | null;\n limit?: number | null;\n sinceMinutes?: number | null;\n } = {},\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryQueryResult> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const { files } = await contextFilesFor(paths.dataDirs);\n const query = args.query?.trim() || null;\n const limit = Math.min(Math.max(Math.trunc(args.limit ?? 10), 1), 50);\n const sinceMinutes =\n typeof args.sinceMinutes === \"number\" && Number.isFinite(args.sinceMinutes)\n ? Math.max(args.sinceMinutes, 0)\n : null;\n const now = options.now?.() ?? new Date();\n const cutoff =\n sinceMinutes === null ? null : now.getTime() - sinceMinutes * 60 * 1000;\n\n const needle = query?.toLowerCase() ?? null;\n const source = await readRows(files);\n const rangeRows = source.rows.filter((row) => {\n const { item } = row;\n if (cutoff !== null) {\n const time = itemTime(item);\n if (!time || time < cutoff) return false;\n }\n return true;\n });\n const privacyExcludedRows = rangeRows.filter((row) =>\n isPrivacyExcludedRow(row, info.config),\n );\n const candidateRows = rangeRows.filter((row) => {\n if (isPrivacyExcludedRow(row, info.config)) return false;\n if (!needle) return true;\n const { item } = row;\n return JSON.stringify({ item, raw: row.raw })\n .toLowerCase()\n .includes(needle);\n });\n const segments = await readSegments(paths.dataDirs);\n const cleanSegments = segments.filter((segment) => segment.clean);\n // Modern stores bind every evidence row to retained segment metadata. Once\n // segment metadata exists, refuse rows that only point at tainted, corrupt,\n // or pruned media. Legacy context-only stores (no segment metadata at all)\n // remain readable for backwards compatibility.\n const rows =\n segments.length === 0\n ? candidateRows\n : candidateRows.filter(\n (row) =>\n segmentReferences(row.raw, row.item.capturedAt, cleanSegments)\n .length > 0,\n );\n const items = rows.map(({ item }) => item);\n const ocrIndexStates = await readOcrIndexStates(paths.dataDirs);\n const evidence = rows.flatMap((row) => normalizeEvidence(row, cleanSegments));\n const returnedEvidence = evidence.slice(0, limit);\n const evidenceTimes = evidence\n .map((item) => (item.capturedAt ? Date.parse(item.capturedAt) : NaN))\n .filter(Number.isFinite);\n const coveredRange = evidenceTimes.length\n ? {\n startedAt: new Date(Math.min(...evidenceTimes)).toISOString(),\n endedAt: new Date(Math.max(...evidenceTimes)).toISOString(),\n }\n : { startedAt: null, endedAt: null };\n const requestedRange = {\n startedAt: cutoff === null ? null : new Date(cutoff).toISOString(),\n endedAt: now.toISOString(),\n };\n const gaps: ScreenMemoryCoverageGap[] = [];\n if (privacyExcludedRows.length > 0) {\n gaps.push({\n ...rowTimeRange(privacyExcludedRows, requestedRange),\n reason: \"privacy-excluded-or-unretained\",\n });\n }\n if (candidateRows.length > rows.length) {\n gaps.push({\n ...requestedRange,\n reason: \"privacy-excluded-or-unretained\",\n });\n }\n for (const index of ocrIndexStates) {\n if (index.state === \"ready\") continue;\n const segment = segments.find(\n (candidate) => candidate.id === index.segmentId,\n );\n const reason =\n index.state === \"failed\"\n ? \"index-failed\"\n : index.state === \"skipped\"\n ? \"index-skipped\"\n : \"index-pending\";\n gaps.push({\n startedAt: segment?.startedAt ?? null,\n endedAt: segment?.endedAt ?? null,\n reason,\n });\n }\n if (files.length === 0) {\n gaps.push({ ...requestedRange, reason: \"no-context-files\" });\n } else if (evidence.length === 0) {\n gaps.push({ ...requestedRange, reason: \"no-evidence-in-requested-range\" });\n } else {\n if (evidence.some((item) => !item.capturedAt)) {\n gaps.push({\n startedAt: null,\n endedAt: null,\n reason: \"timestamps-unavailable\",\n });\n }\n if (\n requestedRange.startedAt &&\n coveredRange.startedAt &&\n coveredRange.startedAt > requestedRange.startedAt\n ) {\n gaps.push({\n startedAt: requestedRange.startedAt,\n endedAt: coveredRange.startedAt,\n reason: \"missing-before-first-evidence\",\n });\n }\n const staleAfterMs = Math.max(\n info.config.sampleIntervalSeconds * 3 * 1000,\n 2 * 60 * 1000,\n );\n if (\n coveredRange.endedAt &&\n Date.parse(coveredRange.endedAt) < now.getTime() - staleAfterMs\n ) {\n gaps.push({\n startedAt: coveredRange.endedAt,\n endedAt: requestedRange.endedAt,\n reason: \"capture-stale\",\n });\n }\n }\n\n return {\n feature: \"screen-memory\",\n localOnly: true,\n enabled: info.config.enabled,\n paused: info.config.paused,\n query,\n sinceMinutes,\n count: items.length,\n items: items.slice(0, limit),\n evidence: returnedEvidence,\n coverage: { requestedRange, coveredRange, gaps },\n truncation: {\n itemLimit: limit,\n returnedItems: returnedEvidence.length,\n omittedItems: Math.max(evidence.length - returnedEvidence.length, 0),\n maxExcerptChars: MAX_EXCERPT_CHARS,\n excerptsTruncated: returnedEvidence.filter(\n (item) => item.excerptTruncated,\n ).length,\n sourceRowsReadLimit: MAX_SOURCE_ROWS,\n sourceRowsReadTruncated: source.sourceRowsReadTruncated,\n },\n contextFiles: files,\n note:\n files.length === 0\n ? \"No local Screen Memory context files were found. Enable Screen Memory in Clips desktop and keep the local MCP capability connected.\"\n : \"Local Screen Memory context only. Do not treat this as shared, hosted, or exhaustive.\",\n };\n}\n\n/**\n * Agent-facing retrieval boundary. Asking an agent to search Rewind is the\n * authorization. This removes filesystem paths, redacts obvious\n * credential-shaped text, and records a content-free activity receipt before\n * it is returned to an action caller.\n */\nexport async function queryScreenMemoryForAgent(\n args: {\n query?: string | null;\n limit?: number | null;\n sinceMinutes?: number | null;\n } = {},\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryAgentQueryResult> {\n const result = await queryScreenMemoryContext(args, options);\n const items = result.items.map((item) => ({\n ...item,\n text: redactCredentialText(item.text),\n sourceFile: \"local-screen-memory\",\n }));\n const evidence = result.evidence.map((item) => ({\n ...item,\n excerpt: redactCredentialText(item.excerpt),\n }));\n const packet = {\n question: redactCredentialText(\n args.query?.trim().slice(0, 4_000) || \"Recent Screen Memory context\",\n ),\n evidence: evidence.slice(0, 20).map((item) => ({\n id: item.id,\n momentId: item.momentId,\n sourceType: item.sourceType,\n capturedAt: item.capturedAt,\n excerpt: item.excerpt.slice(0, MAX_EXCERPT_CHARS),\n })),\n };\n const paths = await resolvePaths(options);\n const { fs, path } = await nodeModules();\n const storeDir = paths.dataDirs[0];\n await fs.mkdir(storeDir, { recursive: true, mode: 0o700 });\n await fs.chmod(storeDir, 0o700);\n const logPath = path.join(storeDir, \"egress.jsonl\");\n if (await exists(logPath)) {\n const sanitized = (await fs.readFile(logPath, \"utf8\"))\n .split(\"\\n\")\n .filter(Boolean)\n .flatMap((line) => {\n try {\n const event = JSON.parse(line) as Record<string, unknown>;\n const packet = event.packet as\n | { evidence?: Array<Record<string, unknown>> }\n | null\n | undefined;\n if (!event.receipt && Array.isArray(packet?.evidence)) {\n event.receipt = {\n evidence: packet.evidence.map((item) => ({\n id: item.id,\n momentId: item.momentId,\n sourceType: item.sourceType,\n capturedAt: item.capturedAt ?? null,\n })),\n };\n }\n delete event.packet;\n delete event.reason;\n event.packetBytes =\n typeof event.packetBytes === \"number\" ? event.packetBytes : 0;\n return [JSON.stringify(event)];\n } catch {\n return [];\n }\n });\n const temporaryPath = `${logPath}.sanitize-${process.pid}`;\n await fs.writeFile(\n temporaryPath,\n sanitized.length > 0 ? `${sanitized.join(\"\\n\")}\\n` : \"\",\n { encoding: \"utf8\", mode: 0o600 },\n );\n await fs.rename(temporaryPath, logPath);\n }\n const requestId = `egress-action-${Date.now()}-${process.pid}`;\n const prepared = {\n requestId,\n occurredAt: new Date().toISOString(),\n state: \"prepared\",\n operation: \"agent-query\",\n receipt: {\n evidence: packet.evidence.map(\n ({ id, momentId, sourceType, capturedAt }) => ({\n id,\n momentId,\n sourceType,\n capturedAt,\n }),\n ),\n },\n evidenceCount: packet.evidence.length,\n packetBytes: 0,\n error: null,\n };\n const completed = {\n ...prepared,\n occurredAt: new Date().toISOString(),\n state: \"completed\",\n receipt: null,\n };\n await fs.appendFile(\n logPath,\n `${JSON.stringify(prepared)}\\n${JSON.stringify(completed)}\\n`,\n { encoding: \"utf8\", mode: 0o600 },\n );\n await fs.chmod(logPath, 0o600);\n return {\n ...result,\n items,\n evidence,\n contextFiles: [],\n egress: {\n requestId,\n packet,\n note: \"A content-free local activity receipt was recorded before this bounded text packet was returned.\",\n },\n };\n}\n\nexport async function readScreenMemoryStatus(\n options: ScreenMemoryLocalOptions = {},\n): Promise<ScreenMemoryStatus> {\n const info = await readConfigInfo(options);\n const paths = await resolvePaths(options);\n const { files, storageBytes } = await contextFilesFor(paths.dataDirs);\n const items = await readItems(files);\n const times = items.map(itemTime).filter(Boolean);\n const oldest = times.length\n ? new Date(Math.min(...times)).toISOString()\n : null;\n const newest = times.length\n ? new Date(Math.max(...times)).toISOString()\n : null;\n const state = !info.config.enabled\n ? \"disabled\"\n : info.config.paused\n ? \"paused\"\n : files.length === 0\n ? \"empty\"\n : \"ready\";\n\n return {\n feature: \"screen-memory\",\n localOnly: true,\n enabled: info.config.enabled,\n paused: info.config.paused,\n state,\n config: info.config,\n configPath: info.path,\n configSource: info.source,\n dataDirs: paths.dataDirs,\n contextFiles: files,\n captureCount: items.length,\n storageBytes,\n oldestCaptureAt: oldest,\n newestCaptureAt: newest,\n note:\n state === \"disabled\"\n ? \"Screen Memory is disabled by default. Turn it on from Clips desktop Settings before agents can use recent screen context.\"\n : state === \"empty\"\n ? \"Screen Memory is enabled, but no local context files were found yet.\"\n : \"Screen Memory status is local to this machine.\",\n };\n}\n"]}
@@ -13,13 +13,13 @@
13
13
  export declare function createNotificationsHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<"" | import("./types.js").Notification[] | {
14
14
  count: number;
15
15
  updated?: undefined;
16
- error?: undefined;
17
16
  ok?: undefined;
17
+ error?: undefined;
18
18
  } | {
19
19
  count?: undefined;
20
20
  updated: number;
21
- error?: undefined;
22
21
  ok?: undefined;
22
+ error?: undefined;
23
23
  } | {
24
24
  count?: undefined;
25
25
  updated?: undefined;
@@ -28,7 +28,7 @@ export declare function createNotificationsHandler(): import("h3").EventHandlerW
28
28
  } | {
29
29
  count?: undefined;
30
30
  updated?: undefined;
31
- error?: undefined;
32
31
  ok: boolean;
32
+ error?: undefined;
33
33
  }>>;
34
34
  //# sourceMappingURL=routes.d.ts.map
@@ -62,7 +62,7 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
62
62
  summary?: undefined;
63
63
  spans?: undefined;
64
64
  id?: undefined;
65
- error?: undefined;
66
65
  ok: boolean;
66
+ error?: undefined;
67
67
  }>>;
68
68
  //# sourceMappingURL=routes.d.ts.map
@@ -328,8 +328,8 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
328
328
  id?: undefined;
329
329
  message?: undefined;
330
330
  deleted?: undefined;
331
- providers?: undefined;
332
331
  count?: undefined;
332
+ providers?: undefined;
333
333
  found: boolean;
334
334
  provider: import("../custom-registry.js").CustomProviderConfig;
335
335
  registered?: undefined;
@@ -337,8 +337,8 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
337
337
  } | {
338
338
  message?: undefined;
339
339
  deleted?: undefined;
340
- providers?: undefined;
341
340
  count?: undefined;
341
+ providers?: undefined;
342
342
  provider?: undefined;
343
343
  found: boolean;
344
344
  id: string;
@@ -346,8 +346,8 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
346
346
  label?: undefined;
347
347
  } | {
348
348
  message?: undefined;
349
- providers?: undefined;
350
349
  count?: undefined;
350
+ providers?: undefined;
351
351
  provider?: undefined;
352
352
  found?: undefined;
353
353
  deleted: boolean;
@@ -356,8 +356,8 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
356
356
  label?: undefined;
357
357
  } | {
358
358
  deleted?: undefined;
359
- providers?: undefined;
360
359
  count?: undefined;
360
+ providers?: undefined;
361
361
  provider?: undefined;
362
362
  found?: undefined;
363
363
  registered: boolean;
@@ -49,8 +49,8 @@ export declare function handleUpdateResource(event: any): Promise<import("./stor
49
49
  }>;
50
50
  /** DELETE /_agent-native/resources/:id — delete a resource */
51
51
  export declare function handleDeleteResource(event: any): Promise<{
52
- ok?: undefined;
53
52
  error: string;
53
+ ok?: undefined;
54
54
  } | {
55
55
  error?: undefined;
56
56
  ok: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.114.6",
3
+ "version": "0.114.7",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {
@@ -123,12 +123,13 @@ export function buildLocalMcpEntryForClient(
123
123
  client: ClientId,
124
124
  args: string[],
125
125
  env?: Record<string, string>,
126
+ command = "agent-native",
126
127
  ): Record<string, unknown> {
127
128
  const cleanEnv = env ? Object.fromEntries(Object.entries(env)) : {};
128
129
  if (client === "opencode") {
129
130
  return {
130
131
  type: "local",
131
- command: ["agent-native", ...args],
132
+ command: [command, ...args],
132
133
  enabled: true,
133
134
  ...(Object.keys(cleanEnv).length ? { environment: cleanEnv } : {}),
134
135
  };
@@ -136,13 +137,13 @@ export function buildLocalMcpEntryForClient(
136
137
  if (client === "github-copilot") {
137
138
  return {
138
139
  type: "stdio",
139
- command: "agent-native",
140
+ command,
140
141
  args,
141
142
  ...(Object.keys(cleanEnv).length ? { env: cleanEnv } : {}),
142
143
  };
143
144
  }
144
145
  return {
145
- command: "agent-native",
146
+ command,
146
147
  args,
147
148
  ...(Object.keys(cleanEnv).length ? { env: cleanEnv } : {}),
148
149
  };
@@ -543,9 +544,10 @@ export function buildCodexLocalBlock(
543
544
  name: string,
544
545
  args: string[],
545
546
  env?: Record<string, string>,
547
+ command = "agent-native",
546
548
  ): string {
547
549
  const lines: string[] = [codexMcpHeader(name)];
548
- lines.push(`command = "agent-native"`);
550
+ lines.push(`command = ${tomlQuote(command)}`);
549
551
  lines.push(`args = [${args.map(tomlQuote).join(", ")}]`);
550
552
  const cleanEnv = env ? Object.fromEntries(Object.entries(env)) : {};
551
553
  if (Object.keys(cleanEnv).length) {
package/src/cli/mcp.ts CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  import crypto from "node:crypto";
17
17
  import fs from "node:fs";
18
+ import os from "node:os";
18
19
  import path from "node:path";
19
20
 
20
21
  import { MCP_PUBLIC_ROUTE_PREFIX } from "../mcp/route-paths.js";
@@ -42,6 +43,7 @@ import {
42
43
  } from "./mcp-config-writers.js";
43
44
 
44
45
  const SERVER_NAME_PREFIX = "agent-native";
46
+ const SCREEN_MEMORY_SERVER_NAME = "clips-screen-memory";
45
47
 
46
48
  interface ParsedArgs {
47
49
  _: string[];
@@ -83,6 +85,58 @@ function logOut(msg: string): void {
83
85
  process.stdout.write(`${msg}\n`);
84
86
  }
85
87
 
88
+ export interface ScreenMemoryStoreResolutionOptions {
89
+ explicitDir?: string;
90
+ env?: NodeJS.ProcessEnv;
91
+ platform?: NodeJS.Platform;
92
+ homeDir?: string;
93
+ }
94
+
95
+ /**
96
+ * Resolve the active Clips store without asking people to find an app-data
97
+ * path. Environment overrides remain the unambiguous escape hatch; otherwise
98
+ * the most recently touched installed Clips/Clips Alpha store wins.
99
+ */
100
+ export function resolveScreenMemoryStoreDir(
101
+ options: ScreenMemoryStoreResolutionOptions = {},
102
+ ): string | undefined {
103
+ if (options.explicitDir) return path.resolve(options.explicitDir);
104
+ const env = options.env ?? process.env;
105
+ const override =
106
+ env.CLIPS_SCREEN_MEMORY_DIR || env.AGENT_NATIVE_SCREEN_MEMORY_DIR;
107
+ if (override) return path.resolve(override);
108
+
109
+ const platform = options.platform ?? process.platform;
110
+ const home = options.homeDir ?? os.homedir();
111
+ const appDataRoot =
112
+ platform === "darwin"
113
+ ? path.join(home, "Library", "Application Support")
114
+ : platform === "win32"
115
+ ? env.APPDATA || path.join(home, "AppData", "Roaming")
116
+ : env.XDG_DATA_HOME || path.join(home, ".local", "share");
117
+ return ["com.clips.tray", "com.clips.tray.alpha"]
118
+ .map((bundleId) => path.join(appDataRoot, bundleId, "screen-memory"))
119
+ .filter((candidate) => fs.existsSync(candidate))
120
+ .map((candidate) => ({
121
+ candidate,
122
+ modifiedAt: Math.max(
123
+ fs.statSync(candidate).mtimeMs,
124
+ ...["feature-config.json", "chapters.json"]
125
+ .map((name) =>
126
+ name === "feature-config.json"
127
+ ? path.join(path.dirname(candidate), name)
128
+ : path.join(candidate, name),
129
+ )
130
+ .filter((file) => fs.existsSync(file))
131
+ .map((file) => fs.statSync(file).mtimeMs),
132
+ ),
133
+ }))
134
+ .sort(
135
+ (a, b) =>
136
+ b.modifiedAt - a.modifiedAt || a.candidate.localeCompare(b.candidate),
137
+ )[0]?.candidate;
138
+ }
139
+
86
140
  // ---------------------------------------------------------------------------
87
141
  // .env token provisioning (local dev) — hand-rolled idempotent upsert
88
142
  // ---------------------------------------------------------------------------
@@ -343,6 +397,38 @@ function installForClient(
343
397
  return file;
344
398
  }
345
399
 
400
+ export function installScreenMemoryForClient(
401
+ client: ClientId,
402
+ storeDir: string,
403
+ cwd: string,
404
+ scope: string | undefined,
405
+ ): string {
406
+ const file = configPathFor(client, cwd, scope);
407
+ const args = [
408
+ "-y",
409
+ "@agent-native/core@latest",
410
+ "mcp",
411
+ "screen-memory",
412
+ "--dir",
413
+ path.resolve(storeDir),
414
+ ];
415
+ if (client === "codex") {
416
+ writeCodexBlock(
417
+ file,
418
+ SCREEN_MEMORY_SERVER_NAME,
419
+ buildCodexLocalBlock(SCREEN_MEMORY_SERVER_NAME, args, {}, "npx"),
420
+ );
421
+ } else {
422
+ writeJsonMcpEntryForClient(
423
+ client,
424
+ file,
425
+ SCREEN_MEMORY_SERVER_NAME,
426
+ buildLocalMcpEntryForClient(client, args, {}, "npx"),
427
+ );
428
+ }
429
+ return file;
430
+ }
431
+
346
432
  function uninstallForClient(
347
433
  client: ClientId,
348
434
  appId: string,
@@ -454,6 +540,36 @@ async function cmdInstall(p: ParsedArgs): Promise<void> {
454
540
  logOut(` Restart ${client} to pick up the new MCP server.`);
455
541
  }
456
542
 
543
+ function cmdInstallScreenMemory(p: ParsedArgs): void {
544
+ const client = normalizeClientId(p.client);
545
+ if (!client) {
546
+ logErr(
547
+ `Usage: npx @agent-native/core@latest mcp install-screen-memory --client ${SELECTABLE_CLIENTS.join("|")} [--dir <path>] [--scope user|project]`,
548
+ );
549
+ process.exit(1);
550
+ }
551
+ const screenMemoryDir = resolveScreenMemoryStoreDir({
552
+ explicitDir: p.screenMemoryDir,
553
+ });
554
+ if (!screenMemoryDir) {
555
+ logErr(
556
+ "No local Clips Screen Memory store was found. Turn Rewind on in Clips, or pass --dir <path>.",
557
+ );
558
+ process.exit(1);
559
+ }
560
+ const file = installScreenMemoryForClient(
561
+ client,
562
+ screenMemoryDir,
563
+ process.cwd(),
564
+ p.scope,
565
+ );
566
+ logOut(`Installed \"${SCREEN_MEMORY_SERVER_NAME}\" for ${client} → ${file}`);
567
+ logOut(" Store: current local Clips Rewind memory");
568
+ logOut(
569
+ ` Restart ${client} to pick up the repaired Screen Memory MCP server.`,
570
+ );
571
+ }
572
+
457
573
  function cmdUninstall(p: ParsedArgs): void {
458
574
  const client = normalizeClientId(p.client);
459
575
  if (!client) {
@@ -544,6 +660,11 @@ Usage:
544
660
  Run the local Clips Screen Memory stdio server.
545
661
  Defaults to the Clips app-data screen-memory folder.
546
662
 
663
+ npx @agent-native/core@latest mcp install-screen-memory --client <c> [--dir <path>] [--scope user|project]
664
+ Install or repair the dedicated local Screen Memory MCP. The active Clips
665
+ or Clips Alpha store is discovered automatically; --dir is an override.
666
+ Clients: claude-code, codex, cowork, cursor, opencode, github-copilot
667
+
547
668
  npx @agent-native/core@latest mcp install --client <c> [--app <id>] [--scope user|project]
548
669
  Provision a token and write the client's MCP config (idempotent).
549
670
  Clients: claude-code, codex, cowork, cursor, opencode, github-copilot
@@ -571,6 +692,9 @@ export async function runMcp(args: string[]): Promise<void> {
571
692
  case "install":
572
693
  await cmdInstall(p);
573
694
  return;
695
+ case "install-screen-memory":
696
+ cmdInstallScreenMemory(p);
697
+ return;
574
698
  case "uninstall":
575
699
  cmdUninstall(p);
576
700
  return;
@@ -2,13 +2,14 @@ export const HELP = `npx @agent-native/core@latest skills
2
2
 
3
3
  Usage:
4
4
  npx @agent-native/core@latest skills list
5
- npx @agent-native/core@latest skills status [assets|content|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray|scaffold] [--client codex|claude-code|pi|all] [--scope user|project] [--json]
6
- npx @agent-native/core@latest skills update [assets|content|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray|scaffold] [--client codex|claude-code|pi|all] [--scope user|project] [--dry-run] [--json]
7
- npx @agent-native/core@latest skills add assets|content|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray [--client codex|claude-code|cowork|cursor|opencode|github-copilot|all] [--scope user|project] [--mode hosted|local-files|self-hosted] [--mcp-url <url>] [--no-connect] [--with-github-action] [--yes] [--dry-run] [--json]
5
+ npx @agent-native/core@latest skills status [assets|content|rewind|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray|scaffold] [--client codex|claude-code|pi|all] [--scope user|project] [--json]
6
+ npx @agent-native/core@latest skills update [assets|content|rewind|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray|scaffold] [--client codex|claude-code|pi|all] [--scope user|project] [--dry-run] [--json]
7
+ npx @agent-native/core@latest skills add assets|content|rewind|design-exploration|visual-edit|visual-plan|visual-recap|visualize-repo|context-xray [--client codex|claude-code|cowork|cursor|opencode|github-copilot|all] [--scope user|project] [--mode hosted|local-files|self-hosted] [--mcp-url <url>] [--no-connect] [--with-github-action] [--yes] [--dry-run] [--json]
8
8
  npx @agent-native/core@latest skills add <manifest-or-app-dir|skill-repo> [--skill <name>] [--client ...] [--yes]
9
9
 
10
10
  Examples:
11
11
  npx @agent-native/core@latest skills add assets
12
+ npx @agent-native/core@latest skills add rewind --client codex --scope user --yes
12
13
  npx @agent-native/core@latest skills add content --mode local-files
13
14
  npx @agent-native/core@latest skills add design-exploration
14
15
  npx @agent-native/core@latest skills add visual-edit
@@ -8,6 +8,7 @@
8
8
  export * from "./help.js";
9
9
  export * from "./assets-skill.js";
10
10
  export * from "./content-skill.js";
11
+ export * from "./rewind-skill.js";
11
12
  export * from "./design-exploration-skill.js";
12
13
  export * from "./design-visual-edit-skill.js";
13
14
  export * from "./plan-setup-auth.js";
@@ -0,0 +1,52 @@
1
+ export const REWIND_SKILL_MD = `---
2
+ name: rewind
3
+ description: >-
4
+ Retrieve recent local Clips Rewind context when the user says "Look at
5
+ Rewind," asks what just happened, or refers to something they recently said
6
+ or saw.
7
+ metadata:
8
+ visibility: exported
9
+ ---
10
+
11
+ # Rewind
12
+
13
+ Use Clips Rewind as local screen memory. Start broad enough to find the right
14
+ moment, then read only the smallest relevant range.
15
+
16
+ ## Retrieval Flow
17
+
18
+ 1. Call \`screen_memory_status\` first. If the newest segment is still open,
19
+ wait for it to finalize rather than substituting an older segment.
20
+ 2. Search \`screen_memory_search_chapters\` before requesting raw recent
21
+ context. Use the user's words, the visible app or project, and the likely
22
+ time range as clues.
23
+ 3. If several chapters plausibly match, show the candidates and ask which one
24
+ the user means. Do not blend separate workstreams together.
25
+ 4. Read the smallest useful range with \`screen_memory_recent_context\`.
26
+ Restate what you recovered before acting, and flag transcription or coverage
27
+ uncertainty.
28
+ 5. Use \`screen_memory_frame_at\` for one exact visual moment or
29
+ \`screen_memory_contact_sheet\` to scan a bounded range. Prefer local frames
30
+ before escalating to cloud processing.
31
+ 6. Request the smallest relevant timestamp range through Clips' bounded private
32
+ Clip handoff only when local text and frames are insufficient, such as
33
+ garbled speech, important motion, dense analysis, or a Clip the user wants
34
+ to keep and query later.
35
+
36
+ ## Boundaries
37
+
38
+ - Rewind recordings, screenshots, audio, transcripts, OCR, and indexes remain
39
+ local unless the user explicitly asks for a bounded Clip handoff.
40
+ - Do not reveal archive filesystem paths, crawl Clips' app-data folders, or
41
+ bypass the Screen Memory MCP broker.
42
+ - Do not upload frames returned by local Screen Memory tools.
43
+ - Treat foreground apps and chapter labels as evidence, not proof of intent.
44
+ - If the Screen Memory MCP is missing, explain that the one-time setup needs to
45
+ be repaired with:
46
+
47
+ \`npx -y @agent-native/core@latest skills add rewind --client <client> --scope user --yes\`
48
+
49
+ Replace \`<client>\` with the current compatible host: \`codex\`,
50
+ \`claude-code\`, \`cursor\`, \`opencode\`, \`github-copilot\`, or \`cowork\`.
51
+ Ask the user to restart the host if it cannot reload MCP servers in place.
52
+ `;