@ouro.bot/cli 0.1.0-alpha.51 → 0.1.0-alpha.511

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 (372) hide show
  1. package/README.md +133 -19
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  4. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  5. package/changelog.json +3253 -0
  6. package/dist/arc/attention-types.js +8 -0
  7. package/dist/arc/cares.js +140 -0
  8. package/dist/arc/episodes.js +117 -0
  9. package/dist/arc/intentions.js +133 -0
  10. package/dist/arc/json-store.js +117 -0
  11. package/dist/arc/obligations.js +237 -0
  12. package/dist/arc/packets.js +193 -0
  13. package/dist/arc/presence.js +185 -0
  14. package/dist/arc/task-lifecycle.js +65 -0
  15. package/dist/heart/active-work.js +867 -35
  16. package/dist/heart/agent-entry.js +58 -3
  17. package/dist/heart/attachments/image-normalize.js +194 -0
  18. package/dist/heart/attachments/materialize.js +97 -0
  19. package/dist/heart/attachments/originals.js +88 -0
  20. package/dist/heart/attachments/render.js +29 -0
  21. package/dist/heart/attachments/sources/adapter.js +2 -0
  22. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  23. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  24. package/dist/heart/attachments/sources/index.js +16 -0
  25. package/dist/heart/attachments/store.js +103 -0
  26. package/dist/heart/attachments/types.js +93 -0
  27. package/dist/heart/auth/auth-flow.js +426 -0
  28. package/dist/heart/background-operations.js +281 -0
  29. package/dist/heart/bundle-state.js +168 -0
  30. package/dist/heart/commitments.js +111 -0
  31. package/dist/heart/config-registry.js +304 -0
  32. package/dist/heart/config.js +119 -129
  33. package/dist/heart/core.js +878 -244
  34. package/dist/heart/cross-chat-delivery.js +131 -0
  35. package/dist/heart/daemon/agent-config-check.js +490 -0
  36. package/dist/heart/daemon/agent-discovery.js +79 -3
  37. package/dist/heart/daemon/agent-service.js +360 -0
  38. package/dist/heart/daemon/agentic-repair.js +216 -0
  39. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  40. package/dist/heart/daemon/cadence.js +70 -0
  41. package/dist/heart/daemon/cli-defaults.js +640 -0
  42. package/dist/heart/daemon/cli-exec.js +7241 -0
  43. package/dist/heart/daemon/cli-help.js +493 -0
  44. package/dist/heart/daemon/cli-parse.js +1536 -0
  45. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  46. package/dist/heart/daemon/cli-render.js +561 -0
  47. package/dist/heart/daemon/cli-types.js +8 -0
  48. package/dist/heart/daemon/connect-bay.js +323 -0
  49. package/dist/heart/daemon/daemon-cli.js +29 -1631
  50. package/dist/heart/daemon/daemon-entry.js +345 -3
  51. package/dist/heart/daemon/daemon-health.js +141 -0
  52. package/dist/heart/daemon/daemon-runtime-sync.js +190 -12
  53. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  54. package/dist/heart/daemon/daemon.js +677 -58
  55. package/dist/heart/daemon/dns-workflow.js +394 -0
  56. package/dist/heart/daemon/doctor-types.js +8 -0
  57. package/dist/heart/daemon/doctor.js +750 -0
  58. package/dist/heart/daemon/health-monitor.js +92 -1
  59. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  60. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  61. package/dist/heart/daemon/http-health-probe.js +80 -0
  62. package/dist/heart/daemon/human-command-screens.js +234 -0
  63. package/dist/heart/daemon/human-readiness.js +114 -0
  64. package/dist/heart/daemon/inner-status.js +89 -0
  65. package/dist/heart/daemon/interactive-repair.js +394 -0
  66. package/dist/heart/daemon/launchd.js +25 -5
  67. package/dist/heart/daemon/log-tailer.js +82 -12
  68. package/dist/heart/daemon/logs-prune.js +110 -0
  69. package/dist/heart/daemon/message-router.js +2 -2
  70. package/dist/heart/daemon/os-cron-deps.js +134 -0
  71. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  72. package/dist/heart/daemon/ouro-entry.js +3 -1
  73. package/dist/heart/daemon/process-manager.js +214 -0
  74. package/dist/heart/daemon/provider-discovery.js +137 -0
  75. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  76. package/dist/heart/daemon/pulse.js +475 -0
  77. package/dist/heart/daemon/readiness-repair.js +365 -0
  78. package/dist/heart/daemon/run-hooks.js +2 -0
  79. package/dist/heart/daemon/runtime-logging.js +67 -16
  80. package/dist/heart/daemon/runtime-metadata.js +73 -0
  81. package/dist/heart/daemon/runtime-mode.js +67 -0
  82. package/dist/heart/daemon/safe-mode.js +161 -0
  83. package/dist/heart/daemon/sense-manager.js +178 -37
  84. package/dist/heart/daemon/session-id-resolver.js +131 -0
  85. package/dist/heart/daemon/skill-management-installer.js +94 -0
  86. package/dist/heart/daemon/socket-client.js +109 -4
  87. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  88. package/dist/heart/daemon/startup-tui.js +264 -0
  89. package/dist/heart/daemon/task-scheduler.js +3 -25
  90. package/dist/heart/daemon/terminal-ui.js +499 -0
  91. package/dist/heart/daemon/thoughts.js +162 -17
  92. package/dist/heart/daemon/up-progress.js +366 -0
  93. package/dist/heart/daemon/vault-items.js +56 -0
  94. package/dist/heart/delegation.js +1 -1
  95. package/dist/heart/habits/habit-migration.js +189 -0
  96. package/dist/heart/habits/habit-parser.js +140 -0
  97. package/dist/heart/habits/habit-runtime-state.js +100 -0
  98. package/dist/heart/habits/habit-scheduler.js +372 -0
  99. package/dist/heart/{daemon → hatch}/hatch-flow.js +52 -117
  100. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  101. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  102. package/dist/heart/{daemon → hatch}/specialist-tools.js +35 -12
  103. package/dist/heart/identity.js +205 -66
  104. package/dist/heart/kept-notes.js +357 -0
  105. package/dist/heart/kicks.js +1 -1
  106. package/dist/heart/machine-identity.js +161 -0
  107. package/dist/heart/mail-import-discovery.js +353 -0
  108. package/dist/heart/mcp/mcp-server.js +653 -0
  109. package/dist/heart/migrate-config.js +100 -0
  110. package/dist/heart/model-capabilities.js +19 -0
  111. package/dist/heart/outlook/outlook-http-hooks.js +66 -0
  112. package/dist/heart/outlook/outlook-http-response.js +7 -0
  113. package/dist/heart/outlook/outlook-http-routes.js +244 -0
  114. package/dist/heart/outlook/outlook-http-static.js +103 -0
  115. package/dist/heart/outlook/outlook-http-transport.js +116 -0
  116. package/dist/heart/outlook/outlook-http.js +99 -0
  117. package/dist/heart/outlook/outlook-read.js +31 -0
  118. package/dist/heart/outlook/outlook-types.js +27 -0
  119. package/dist/heart/outlook/outlook-view.js +195 -0
  120. package/dist/heart/outlook/readers/agent-machine.js +382 -0
  121. package/dist/heart/outlook/readers/continuity-readers.js +336 -0
  122. package/dist/heart/outlook/readers/mail.js +362 -0
  123. package/dist/heart/outlook/readers/runtime-readers.js +644 -0
  124. package/dist/heart/outlook/readers/sessions.js +232 -0
  125. package/dist/heart/outlook/readers/shared.js +111 -0
  126. package/dist/heart/platform.js +81 -0
  127. package/dist/heart/provider-attempt.js +134 -0
  128. package/dist/heart/provider-binding-resolver.js +255 -0
  129. package/dist/heart/provider-credentials.js +424 -0
  130. package/dist/heart/provider-failover.js +301 -0
  131. package/dist/heart/provider-models.js +81 -0
  132. package/dist/heart/provider-ping.js +262 -0
  133. package/dist/heart/provider-state.js +216 -0
  134. package/dist/heart/provider-visibility.js +188 -0
  135. package/dist/heart/providers/anthropic-token.js +131 -0
  136. package/dist/heart/providers/anthropic.js +139 -52
  137. package/dist/heart/providers/azure.js +97 -13
  138. package/dist/heart/providers/error-classification.js +127 -0
  139. package/dist/heart/providers/github-copilot.js +145 -0
  140. package/dist/heart/providers/minimax-vlm.js +189 -0
  141. package/dist/heart/providers/minimax.js +26 -8
  142. package/dist/heart/providers/openai-codex.js +55 -40
  143. package/dist/heart/runtime-capability-check.js +170 -0
  144. package/dist/heart/runtime-credentials.js +260 -0
  145. package/dist/heart/sense-truth.js +11 -4
  146. package/dist/heart/session-activity.js +43 -22
  147. package/dist/heart/session-events.js +1150 -0
  148. package/dist/heart/session-playback-cli-main.js +5 -0
  149. package/dist/heart/session-playback-cli.js +36 -0
  150. package/dist/heart/session-playback.js +231 -0
  151. package/dist/heart/session-stats-cli-main.js +5 -0
  152. package/dist/heart/session-stats.js +182 -0
  153. package/dist/heart/session-transcript.js +167 -0
  154. package/dist/heart/start-of-turn-packet.js +345 -0
  155. package/dist/heart/streaming.js +44 -27
  156. package/dist/heart/sync.js +332 -0
  157. package/dist/heart/target-resolution.js +127 -0
  158. package/dist/heart/tempo.js +93 -0
  159. package/dist/heart/temporal-view.js +41 -0
  160. package/dist/heart/tool-activity-callbacks.js +36 -0
  161. package/dist/heart/tool-description.js +135 -0
  162. package/dist/heart/tool-friction.js +55 -0
  163. package/dist/heart/tool-loop.js +200 -0
  164. package/dist/heart/turn-context.js +372 -0
  165. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
  166. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  167. package/dist/heart/versioning/ouro-path-installer.js +425 -0
  168. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  169. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  170. package/dist/heart/{daemon → versioning}/update-checker.js +5 -1
  171. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  172. package/dist/mailroom/attention.js +167 -0
  173. package/dist/mailroom/autonomy.js +209 -0
  174. package/dist/mailroom/blob-store.js +606 -0
  175. package/dist/mailroom/body-cache.js +61 -0
  176. package/dist/mailroom/core.js +672 -0
  177. package/dist/mailroom/entry.js +160 -0
  178. package/dist/mailroom/file-store.js +426 -0
  179. package/dist/mailroom/mbox-import.js +382 -0
  180. package/dist/mailroom/outbound.js +380 -0
  181. package/dist/mailroom/policy.js +263 -0
  182. package/dist/mailroom/reader.js +219 -0
  183. package/dist/mailroom/search-cache.js +182 -0
  184. package/dist/mailroom/search-relevance.js +319 -0
  185. package/dist/mailroom/smtp-ingress.js +176 -0
  186. package/dist/mailroom/source-state.js +176 -0
  187. package/dist/mailroom/thread.js +109 -0
  188. package/dist/mailroom/travel-extract.js +89 -0
  189. package/dist/mind/bundle-manifest.js +7 -1
  190. package/dist/mind/context.js +165 -101
  191. package/dist/mind/diary-integrity.js +60 -0
  192. package/dist/mind/{memory.js → diary.js} +74 -93
  193. package/dist/mind/embedding-provider.js +60 -0
  194. package/dist/mind/file-state.js +179 -0
  195. package/dist/mind/friends/channel.js +30 -0
  196. package/dist/mind/friends/group-context.js +144 -0
  197. package/dist/mind/friends/resolver.js +54 -2
  198. package/dist/mind/friends/store-file.js +39 -3
  199. package/dist/mind/friends/trust-explanation.js +74 -0
  200. package/dist/mind/friends/types.js +2 -2
  201. package/dist/mind/journal-index.js +161 -0
  202. package/dist/mind/note-search.js +268 -0
  203. package/dist/mind/obligation-steering.js +221 -0
  204. package/dist/mind/pending.js +4 -0
  205. package/dist/mind/prompt-refresh.js +3 -2
  206. package/dist/mind/prompt.js +940 -111
  207. package/dist/mind/provenance-trust.js +26 -0
  208. package/dist/mind/scrutiny.js +173 -0
  209. package/dist/nerves/cli-logging.js +7 -1
  210. package/dist/nerves/coverage/audit-rules.js +15 -6
  211. package/dist/nerves/coverage/audit.js +28 -2
  212. package/dist/nerves/coverage/cli.js +1 -1
  213. package/dist/nerves/coverage/contract.js +5 -5
  214. package/dist/nerves/coverage/file-completeness.js +114 -5
  215. package/dist/nerves/coverage/run-artifacts.js +1 -1
  216. package/dist/nerves/event-buffer.js +111 -0
  217. package/dist/nerves/index.js +224 -4
  218. package/dist/nerves/observation.js +20 -0
  219. package/dist/nerves/redact.js +79 -0
  220. package/dist/nerves/review/cli-main.js +5 -0
  221. package/dist/nerves/review/cli.js +156 -0
  222. package/dist/nerves/review/core.js +152 -0
  223. package/dist/nerves/runtime.js +5 -1
  224. package/dist/outlook-ui/assets/index-BPr5vNuM.css +1 -0
  225. package/dist/outlook-ui/assets/index-Cm51CY9W.js +61 -0
  226. package/dist/outlook-ui/index.html +15 -0
  227. package/dist/repertoire/ado-client.js +15 -56
  228. package/dist/repertoire/ado-semantic.js +11 -10
  229. package/dist/repertoire/api-client.js +97 -0
  230. package/dist/repertoire/bitwarden-store.js +774 -0
  231. package/dist/repertoire/bundle-templates.js +72 -0
  232. package/dist/repertoire/bw-installer.js +180 -0
  233. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  234. package/dist/repertoire/coding/context-pack.js +330 -0
  235. package/dist/repertoire/coding/feedback.js +197 -30
  236. package/dist/repertoire/coding/manager.js +158 -9
  237. package/dist/repertoire/coding/spawner.js +55 -9
  238. package/dist/repertoire/coding/tools.js +170 -7
  239. package/dist/repertoire/commerce-errors.js +109 -0
  240. package/dist/repertoire/commerce-self-test.js +156 -0
  241. package/dist/repertoire/credential-access.js +111 -0
  242. package/dist/repertoire/duffel-client.js +185 -0
  243. package/dist/repertoire/github-client.js +14 -55
  244. package/dist/repertoire/graph-client.js +11 -52
  245. package/dist/repertoire/guardrails.js +396 -0
  246. package/dist/repertoire/mcp-client.js +255 -0
  247. package/dist/repertoire/mcp-manager.js +305 -0
  248. package/dist/repertoire/mcp-tools.js +63 -0
  249. package/dist/repertoire/shell-sessions.js +133 -0
  250. package/dist/repertoire/skills.js +15 -24
  251. package/dist/repertoire/stripe-client.js +131 -0
  252. package/dist/repertoire/tasks/board.js +31 -5
  253. package/dist/repertoire/tasks/fix.js +182 -0
  254. package/dist/repertoire/tasks/index.js +16 -4
  255. package/dist/repertoire/tasks/lifecycle.js +2 -2
  256. package/dist/repertoire/tasks/parser.js +3 -2
  257. package/dist/repertoire/tasks/scanner.js +194 -37
  258. package/dist/repertoire/tasks/transitions.js +16 -78
  259. package/dist/repertoire/tool-results.js +29 -0
  260. package/dist/repertoire/tools-attachments.js +317 -0
  261. package/dist/repertoire/tools-base.js +46 -955
  262. package/dist/repertoire/tools-bluebubbles.js +1 -0
  263. package/dist/repertoire/tools-bridge.js +141 -0
  264. package/dist/repertoire/tools-bundle.js +984 -0
  265. package/dist/repertoire/tools-config.js +185 -0
  266. package/dist/repertoire/tools-continuity.js +248 -0
  267. package/dist/repertoire/tools-credential.js +381 -0
  268. package/dist/repertoire/tools-files.js +342 -0
  269. package/dist/repertoire/tools-flight.js +224 -0
  270. package/dist/repertoire/tools-flow.js +105 -0
  271. package/dist/repertoire/tools-github.js +1 -7
  272. package/dist/repertoire/tools-mail.js +1477 -0
  273. package/dist/repertoire/tools-notes.js +376 -0
  274. package/dist/repertoire/tools-session.js +749 -0
  275. package/dist/repertoire/tools-shell.js +120 -0
  276. package/dist/repertoire/tools-stripe.js +180 -0
  277. package/dist/repertoire/tools-surface.js +243 -0
  278. package/dist/repertoire/tools-teams.js +9 -39
  279. package/dist/repertoire/tools-travel.js +125 -0
  280. package/dist/repertoire/tools-trip.js +422 -0
  281. package/dist/repertoire/tools-user-profile.js +144 -0
  282. package/dist/repertoire/tools-vault.js +40 -0
  283. package/dist/repertoire/tools.js +107 -100
  284. package/dist/repertoire/travel-api-client.js +360 -0
  285. package/dist/repertoire/user-profile.js +131 -0
  286. package/dist/repertoire/vault-setup.js +246 -0
  287. package/dist/repertoire/vault-unlock.js +561 -0
  288. package/dist/scripts/claude-code-hook.js +41 -0
  289. package/dist/scripts/claude-code-stop-hook.js +47 -0
  290. package/dist/senses/attention-queue.js +116 -0
  291. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  292. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  293. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +219 -18
  294. package/dist/senses/bluebubbles/entry.js +73 -0
  295. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  296. package/dist/senses/bluebubbles/index.js +1881 -0
  297. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -70
  298. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  299. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  300. package/dist/senses/bluebubbles/processed-log.js +111 -0
  301. package/dist/senses/bluebubbles/replay.js +129 -0
  302. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +2 -2
  303. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  304. package/dist/senses/cli/bracketed-paste.js +82 -0
  305. package/dist/senses/cli/image-paste.js +287 -0
  306. package/dist/senses/cli/image-ref-navigation.js +75 -0
  307. package/dist/senses/cli/ink-app.js +156 -0
  308. package/dist/senses/cli/inline-diff.js +64 -0
  309. package/dist/senses/cli/input-keys.js +174 -0
  310. package/dist/senses/cli/kill-ring.js +86 -0
  311. package/dist/senses/cli/message-list.js +51 -0
  312. package/dist/senses/cli/ouro-tui.js +605 -0
  313. package/dist/senses/cli/spinner-imperative.js +135 -0
  314. package/dist/senses/cli/spinner.js +101 -0
  315. package/dist/senses/cli/status-line.js +60 -0
  316. package/dist/senses/cli/streaming-markdown.js +526 -0
  317. package/dist/senses/cli/tool-display.js +83 -0
  318. package/dist/senses/cli/tool-render.js +85 -0
  319. package/dist/senses/cli/tui-store.js +240 -0
  320. package/dist/senses/cli/virtual-list.js +35 -0
  321. package/dist/senses/cli-entry.js +60 -8
  322. package/dist/senses/cli-layout.js +187 -0
  323. package/dist/senses/cli.js +511 -209
  324. package/dist/senses/commands.js +66 -3
  325. package/dist/senses/habit-turn-message.js +108 -0
  326. package/dist/senses/inner-dialog-worker.js +175 -21
  327. package/dist/senses/inner-dialog.js +330 -27
  328. package/dist/senses/mail-entry.js +66 -0
  329. package/dist/senses/mail.js +379 -0
  330. package/dist/senses/pipeline.js +573 -164
  331. package/dist/senses/proactive-content-guard.js +51 -0
  332. package/dist/senses/shared-turn.js +248 -0
  333. package/dist/senses/surface-tool.js +68 -0
  334. package/dist/senses/teams-entry.js +60 -8
  335. package/dist/senses/teams.js +405 -170
  336. package/dist/senses/trust-gate.js +100 -5
  337. package/dist/trips/core.js +138 -0
  338. package/dist/trips/store.js +146 -0
  339. package/package.json +37 -7
  340. package/skills/agent-commerce.md +106 -0
  341. package/skills/browser-navigation.md +117 -0
  342. package/skills/commerce-setup-guide.md +116 -0
  343. package/skills/commerce-setup.md +84 -0
  344. package/skills/configure-dev-tools.md +101 -0
  345. package/skills/travel-planning.md +138 -0
  346. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  347. package/dist/heart/daemon/subagent-installer.js +0 -166
  348. package/dist/heart/session-recall.js +0 -116
  349. package/dist/mind/associative-recall.js +0 -209
  350. package/dist/senses/bluebubbles-entry.js +0 -13
  351. package/dist/senses/bluebubbles.js +0 -1142
  352. package/dist/senses/debug-activity.js +0 -148
  353. package/subagents/README.md +0 -86
  354. package/subagents/work-doer.md +0 -237
  355. package/subagents/work-merger.md +0 -618
  356. package/subagents/work-planner.md +0 -390
  357. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  358. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  359. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  360. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  361. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  362. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  363. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  364. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  365. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  366. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  367. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  368. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  369. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  370. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  371. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  372. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -0,0 +1,774 @@
1
+ "use strict";
2
+ /**
3
+ * Bitwarden CLI credential store — wraps `bw` CLI for the agent's own vault.
4
+ *
5
+ * This store authenticates directly as the agent using its own master password.
6
+ * The agent owns the vault, so no human-in-the-loop is needed.
7
+ *
8
+ * Requires the `bw` CLI to be installed. Session tokens are cached process-local.
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.BitwardenCredentialStore = void 0;
45
+ exports.sanitizeCredentialErrorDetail = sanitizeCredentialErrorDetail;
46
+ const node_child_process_1 = require("node:child_process");
47
+ const fs = __importStar(require("node:fs"));
48
+ const path = __importStar(require("node:path"));
49
+ const runtime_1 = require("../nerves/runtime");
50
+ const bw_installer_1 = require("./bw-installer");
51
+ const MAX_ERROR_DETAIL_LENGTH = 500;
52
+ const LONG_ENCODED_TOKEN_PATTERN = /[A-Za-z0-9+/=]{32,}/g;
53
+ function uniqueSecrets(secrets) {
54
+ return [...new Set(secrets.filter((value) => typeof value === "string" && value.length >= 4))].sort((left, right) => right.length - left.length);
55
+ }
56
+ function sanitizeCredentialErrorDetail(message, options = {}) {
57
+ const filtered = message
58
+ .split(/\r?\n/)
59
+ .filter((line) => {
60
+ const trimmed = line.trim();
61
+ if (trimmed.startsWith("Command failed:"))
62
+ return false;
63
+ if (trimmed.includes("[input is hidden]"))
64
+ return false;
65
+ return true;
66
+ })
67
+ .join("\n")
68
+ .trim();
69
+ let sanitized = filtered || "command failed";
70
+ for (const secret of uniqueSecrets(options.secrets ?? [])) {
71
+ sanitized = sanitized.split(secret).join("[redacted]");
72
+ }
73
+ sanitized = sanitized.replace(LONG_ENCODED_TOKEN_PATTERN, "[redacted]");
74
+ if (sanitized.replace(/\[redacted\]/g, "").trim().length === 0) {
75
+ return "command failed";
76
+ }
77
+ return sanitized.slice(0, MAX_ERROR_DETAIL_LENGTH);
78
+ }
79
+ // ---------------------------------------------------------------------------
80
+ // bw CLI wrapper
81
+ // ---------------------------------------------------------------------------
82
+ function isBwSessionUnavailableMessage(message) {
83
+ return (/master password/i.test(message) ||
84
+ /vault is locked/i.test(message) ||
85
+ /not logged in/i.test(message) ||
86
+ /session key/i.test(message) ||
87
+ /local bitwarden session/i.test(message));
88
+ }
89
+ function isBwInvalidUnlockSecretMessage(message) {
90
+ return /invalid master password/i.test(message) || /saved vault unlock secret/i.test(message);
91
+ }
92
+ function isBwTimeoutError(err) {
93
+ const timeoutErr = err;
94
+ const message = err.message.toLowerCase();
95
+ return (timeoutErr.code === "ETIMEDOUT" ||
96
+ timeoutErr.killed === true ||
97
+ timeoutErr.signal === "SIGTERM" ||
98
+ message.includes("timed out"));
99
+ }
100
+ function formatBwOperation(args) {
101
+ const [command, target] = args;
102
+ /* v8 ignore next -- defensive: all execBw call sites pass a concrete bw subcommand @preserve */
103
+ if (!command)
104
+ return "bw command";
105
+ return [command, target].filter(Boolean).join(" ");
106
+ }
107
+ function sanitizeBwErrorDetail(message) {
108
+ if (isBwInvalidUnlockSecretMessage(message)) {
109
+ return "bw CLI rejected the saved vault unlock secret for this machine";
110
+ }
111
+ if (isBwSessionUnavailableMessage(message)) {
112
+ return "bw CLI could not use the local Bitwarden session because it is locked, missing, or expired";
113
+ }
114
+ return sanitizeCredentialErrorDetail(message);
115
+ }
116
+ function formatBwCliError(err, stderr = "", args = []) {
117
+ const operation = formatBwOperation(args);
118
+ if (isBwTimeoutError(err)) {
119
+ return new Error(`bw CLI error: ${operation} timed out -- usually resolves on retry. If it persists, check network connectivity to the vault server.`);
120
+ }
121
+ const detail = sanitizeBwErrorDetail(stderr.trim() || err.message);
122
+ if (detail === "command failed") {
123
+ return new Error(`bw CLI error: ${operation} failed without error detail`);
124
+ }
125
+ return new Error(`bw CLI error: ${detail}`);
126
+ }
127
+ function isBwSessionAuthError(err) {
128
+ return isBwSessionUnavailableMessage(err.message) || isBwInvalidUnlockSecretMessage(err.message);
129
+ }
130
+ function isBwConfigLogoutRequired(err) {
131
+ const message = err.message.toLowerCase();
132
+ return message.includes("logout") && message.includes("required");
133
+ }
134
+ function shouldPreferExactItemLookup(domain) {
135
+ return domain.includes("/");
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // Cross-process bw CLI lock
139
+ // ---------------------------------------------------------------------------
140
+ // The bw CLI cannot handle concurrent access to the same app data directory.
141
+ // Two processes (e.g. daemon worker + ouro up CLI) hitting the same dir
142
+ // simultaneously corrupt bw's local state, producing empty/garbled output.
143
+ //
144
+ // We use two layers:
145
+ // 1. In-process async mutex: a Map<string, Promise<void>> keyed by appDataDir
146
+ // serializes calls within a single Node.js process.
147
+ // 2. Cross-process file lock: fs.openSync(lockPath, 'wx') with PID stale
148
+ // detection serializes across processes.
149
+ // ---------------------------------------------------------------------------
150
+ const BW_LOCK_FILENAME = ".ouro-bw.lock";
151
+ const BW_LOCK_TIMEOUT_MS = 30_000;
152
+ const BW_LOCK_POLL_MS = 100;
153
+ const BW_DATA_FILENAME = "data.json";
154
+ const BW_SYNC_MARKER_FILENAME = ".ouro-last-sync";
155
+ const BW_SYNC_FRESH_MS = 60_000;
156
+ /** In-process async mutex keyed by appDataDir. */
157
+ const inProcessLocks = new Map();
158
+ function isPidAlive(pid) {
159
+ try {
160
+ process.kill(pid, 0);
161
+ return true;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ async function acquireFileLock(lockPath) {
168
+ const content = `${process.pid}\n`;
169
+ const deadline = Date.now() + BW_LOCK_TIMEOUT_MS;
170
+ while (true) {
171
+ try {
172
+ const fd = fs.openSync(lockPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL);
173
+ fs.writeSync(fd, content);
174
+ fs.closeSync(fd);
175
+ return;
176
+ }
177
+ catch (err) {
178
+ if (err.code !== "EEXIST") {
179
+ throw err;
180
+ }
181
+ // Lock file exists -- check for stale lock
182
+ try {
183
+ const existing = fs.readFileSync(lockPath, "utf8").trim();
184
+ const pid = parseInt(existing, 10);
185
+ if (!isNaN(pid) && !isPidAlive(pid)) {
186
+ // Stale lock -- remove and retry immediately
187
+ try {
188
+ fs.unlinkSync(lockPath);
189
+ }
190
+ catch { /* race with another cleaner is fine */ }
191
+ continue;
192
+ }
193
+ }
194
+ catch { /* v8 ignore next -- race: lock file disappeared between openSync and readFileSync @preserve */
195
+ continue;
196
+ }
197
+ if (Date.now() >= deadline) {
198
+ throw new Error(`bw CLI lock timeout: could not acquire ${lockPath} within ${BW_LOCK_TIMEOUT_MS}ms`);
199
+ }
200
+ // Yield to the event loop before retrying
201
+ await delay(BW_LOCK_POLL_MS);
202
+ }
203
+ }
204
+ }
205
+ function releaseFileLock(lockPath) {
206
+ try {
207
+ fs.unlinkSync(lockPath);
208
+ }
209
+ catch {
210
+ // Already removed or never created -- safe to ignore
211
+ }
212
+ }
213
+ async function withBwLock(appDataDir, fn) {
214
+ if (!appDataDir) {
215
+ // No appDataDir means the default bw data location. Still need in-process
216
+ // serialization but cannot do cross-process file lock without a dir.
217
+ return fn();
218
+ }
219
+ const lockKey = appDataDir;
220
+ const lockPath = path.join(appDataDir, BW_LOCK_FILENAME);
221
+ // In-process serialization: chain onto the previous promise for this key
222
+ const previous = inProcessLocks.get(lockKey) ?? Promise.resolve();
223
+ let releaseLock;
224
+ const current = new Promise((resolve) => { releaseLock = resolve; });
225
+ inProcessLocks.set(lockKey, current);
226
+ await previous;
227
+ let fileLockAcquired = false;
228
+ try {
229
+ // Cross-process file lock
230
+ await acquireFileLock(lockPath);
231
+ fileLockAcquired = true;
232
+ return await fn();
233
+ }
234
+ finally {
235
+ if (fileLockAcquired) {
236
+ releaseFileLock(lockPath);
237
+ }
238
+ releaseLock();
239
+ // Clean up the map entry if we are the latest
240
+ if (inProcessLocks.get(lockKey) === current) {
241
+ inProcessLocks.delete(lockKey);
242
+ }
243
+ }
244
+ }
245
+ function execBw(args, sessionToken, appDataDir, stdin, bwBinaryPath = "bw") {
246
+ const env = {
247
+ ...process.env,
248
+ ...(sessionToken ? { BW_SESSION: sessionToken } : {}),
249
+ ...(appDataDir ? { BITWARDENCLI_APPDATA_DIR: appDataDir } : {}),
250
+ };
251
+ const runCommand = () => new Promise((resolve, reject) => {
252
+ const child = (0, node_child_process_1.execFile)(bwBinaryPath, args, { timeout: 30_000, env }, (err, stdout, stderr) => {
253
+ if (err) {
254
+ if (isBwNotInstalled(err)) {
255
+ reject(new Error("bw CLI not found. Install from https://bitwarden.com/help/cli/"));
256
+ return;
257
+ }
258
+ reject(formatBwCliError(err, stderr, args));
259
+ return;
260
+ }
261
+ resolve(stdout);
262
+ });
263
+ if (stdin !== undefined) {
264
+ child?.stdin?.end(stdin);
265
+ }
266
+ });
267
+ return withBwLock(appDataDir, runCommand);
268
+ }
269
+ /** Check if the error indicates the bw CLI binary is not installed. */
270
+ function isBwNotInstalled(err) {
271
+ const msg = err.message.toLowerCase();
272
+ const code = err.code;
273
+ return code === "ENOENT" || /\bspawn\b.*\benoent\b/.test(msg) || msg.includes("command not found");
274
+ }
275
+ /** Check if the error is transient (network/timeout) and worth retrying. */
276
+ function isTransientError(err) {
277
+ const msg = err.message.toLowerCase();
278
+ return (msg.includes("econnrefused") ||
279
+ msg.includes("etimedout") ||
280
+ msg.includes("enotfound") ||
281
+ msg.includes("socket hang up") ||
282
+ msg.includes("503") ||
283
+ msg.includes("server unavailable") ||
284
+ msg.includes("timed out"));
285
+ }
286
+ const MAX_RETRIES = 3;
287
+ const BASE_BACKOFF_MS = 1000;
288
+ const TRANSIENT_MAX_RETRIES = 3;
289
+ const TRANSIENT_RETRY_BASE_MS = 500;
290
+ function delay(ms) {
291
+ return new Promise((resolve) => setTimeout(resolve, ms));
292
+ }
293
+ function isBwLoginItem(value) {
294
+ if (!value || typeof value !== "object" || Array.isArray(value))
295
+ return false;
296
+ const item = value;
297
+ if (typeof item.id !== "string" || item.id.trim().length === 0)
298
+ return false;
299
+ if (typeof item.name !== "string" || item.name.trim().length === 0)
300
+ return false;
301
+ if (item.login !== undefined) {
302
+ if (!item.login || typeof item.login !== "object" || Array.isArray(item.login))
303
+ return false;
304
+ const login = item.login;
305
+ if (login.username !== undefined && typeof login.username !== "string")
306
+ return false;
307
+ if (login.password !== undefined && typeof login.password !== "string")
308
+ return false;
309
+ if (login.uris !== undefined) {
310
+ if (!Array.isArray(login.uris))
311
+ return false;
312
+ for (const uri of login.uris) {
313
+ if (!uri || typeof uri !== "object" || Array.isArray(uri))
314
+ return false;
315
+ const uriRecord = uri;
316
+ if (uriRecord.uri !== undefined && typeof uriRecord.uri !== "string")
317
+ return false;
318
+ }
319
+ }
320
+ }
321
+ if (item.notes !== undefined && item.notes !== null && typeof item.notes !== "string")
322
+ return false;
323
+ if (item.revisionDate !== undefined && typeof item.revisionDate !== "string")
324
+ return false;
325
+ return true;
326
+ }
327
+ function parseBwItems(stdout, context) {
328
+ let parsed;
329
+ try {
330
+ parsed = JSON.parse(stdout);
331
+ if (!Array.isArray(parsed)) {
332
+ throw new Error("expected item array");
333
+ }
334
+ const items = parsed;
335
+ if (!items.every(isBwLoginItem)) {
336
+ throw new Error("expected login items");
337
+ }
338
+ return items;
339
+ }
340
+ catch {
341
+ if (Array.isArray(parsed)) {
342
+ throw new Error(`bw CLI error: invalid item from ${context}`);
343
+ }
344
+ throw new Error(`bw CLI error: invalid JSON from ${context}`);
345
+ }
346
+ }
347
+ function parseBwItem(stdout, context) {
348
+ let parsed;
349
+ try {
350
+ parsed = JSON.parse(stdout);
351
+ if (!isBwLoginItem(parsed)) {
352
+ throw new Error("expected login item");
353
+ }
354
+ return parsed;
355
+ }
356
+ catch {
357
+ if (parsed !== undefined) {
358
+ throw new Error(`bw CLI error: invalid item from ${context}`);
359
+ }
360
+ throw new Error(`bw CLI error: invalid JSON from ${context}`);
361
+ }
362
+ }
363
+ function parseBwItemId(stdout) {
364
+ try {
365
+ const parsed = JSON.parse(stdout);
366
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
367
+ return null;
368
+ const id = parsed.id;
369
+ return typeof id === "string" && id.trim().length > 0 ? id : null;
370
+ }
371
+ catch {
372
+ return null;
373
+ }
374
+ }
375
+ // ---------------------------------------------------------------------------
376
+ // BitwardenCredentialStore
377
+ // ---------------------------------------------------------------------------
378
+ class BitwardenCredentialStore {
379
+ serverUrl;
380
+ email;
381
+ masterPassword;
382
+ appDataDir;
383
+ sessionToken = null;
384
+ bwBinaryPath = "bw";
385
+ structuredItemCache = null;
386
+ constructor(serverUrl, email, masterPassword, options = {}) {
387
+ this.serverUrl = serverUrl;
388
+ this.email = email;
389
+ this.masterPassword = masterPassword;
390
+ this.appDataDir = options.appDataDir;
391
+ }
392
+ isReady() {
393
+ return true;
394
+ }
395
+ execBw(args, sessionToken, stdin) {
396
+ return execBw(args, sessionToken, this.appDataDir, stdin, this.bwBinaryPath);
397
+ }
398
+ /**
399
+ * Ensure the bw CLI is authenticated and unlocked.
400
+ * Handles three states: logged out → login, locked → unlock, already unlocked → no-op.
401
+ * Retries transient failures (network/timeout) up to MAX_RETRIES with exponential backoff.
402
+ */
403
+ async login() {
404
+ // Ensure bw CLI is installed before any bw commands
405
+ this.bwBinaryPath = await (0, bw_installer_1.ensureBwCli)();
406
+ if (this.appDataDir) {
407
+ fs.mkdirSync(this.appDataDir, { recursive: true, mode: 0o700 });
408
+ }
409
+ let lastError;
410
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
411
+ try {
412
+ await this.loginAttempt();
413
+ return;
414
+ }
415
+ catch (err) {
416
+ /* v8 ignore next -- defensive: loginAttempt always throws Error instances @preserve */
417
+ lastError = err instanceof Error ? err : new Error(String(err));
418
+ // Don't retry non-transient errors (auth failures, bw not installed)
419
+ if (!isTransientError(lastError)) {
420
+ throw lastError;
421
+ }
422
+ // Don't retry after final attempt
423
+ if (attempt === MAX_RETRIES - 1)
424
+ break;
425
+ const backoffMs = BASE_BACKOFF_MS * Math.pow(2, attempt);
426
+ (0, runtime_1.emitNervesEvent)({
427
+ event: "repertoire.bw_login_retry",
428
+ component: "repertoire",
429
+ message: `bw login attempt ${attempt + 1} failed, retrying in ${backoffMs}ms`,
430
+ meta: { attempt: attempt + 1, backoffMs, reason: lastError.message },
431
+ });
432
+ await delay(backoffMs);
433
+ }
434
+ }
435
+ throw lastError;
436
+ }
437
+ /** Single login attempt — called by login() retry loop. */
438
+ async loginAttempt() {
439
+ // Check current status
440
+ let status = {};
441
+ try {
442
+ const raw = await this.execBw(["status"]);
443
+ status = JSON.parse(raw);
444
+ }
445
+ catch (err) {
446
+ // If bw CLI is not installed or a transient error, propagate it for retry
447
+ if (err instanceof Error && (isBwNotInstalled(err) || isTransientError(err))) {
448
+ throw err;
449
+ }
450
+ // CLI not configured or broken — proceed with full setup
451
+ }
452
+ // Configure server URL if needed (only works when logged out)
453
+ if (status.status === "unauthenticated" || !status.serverUrl) {
454
+ try {
455
+ await this.execBw(["config", "server", this.serverUrl]);
456
+ }
457
+ catch (error) {
458
+ const err = error;
459
+ // "Logout required" means already logged in — that's fine, skip config.
460
+ if (!isBwConfigLogoutRequired(err)) {
461
+ throw err;
462
+ }
463
+ }
464
+ }
465
+ if (status.status === "locked") {
466
+ // Already logged in, just needs unlock
467
+ const unlockOutput = await this.execBw(["unlock", this.masterPassword, "--raw"]);
468
+ this.sessionToken = unlockOutput.trim();
469
+ }
470
+ else if (status.status === "unauthenticated" || !status.status) {
471
+ // Not logged in — full login
472
+ const loginOutput = await this.execBw(["login", this.email, this.masterPassword, "--raw"]);
473
+ try {
474
+ const parsed = JSON.parse(loginOutput);
475
+ this.sessionToken = parsed.access_token ?? loginOutput.trim();
476
+ }
477
+ catch {
478
+ this.sessionToken = loginOutput.trim();
479
+ }
480
+ }
481
+ else {
482
+ // Status is "unlocked" — already good, just need the session token
483
+ const unlockOutput = await this.execBw(["unlock", this.masterPassword, "--raw"]);
484
+ this.sessionToken = unlockOutput.trim();
485
+ }
486
+ if (this.shouldSyncVaultAfterSession(status)) {
487
+ /* v8 ignore next -- defensive: loginAttempt always sets sessionToken before sync @preserve */
488
+ await this.execBw(["sync"], this.sessionToken ?? undefined);
489
+ this.writeSyncMarker();
490
+ }
491
+ else {
492
+ (0, runtime_1.emitNervesEvent)({
493
+ event: "repertoire.bw_sync_skipped",
494
+ component: "repertoire",
495
+ message: "skipping bw sync because local vault cache is still fresh",
496
+ meta: { email: this.email, serverUrl: this.serverUrl, freshnessWindowMs: BW_SYNC_FRESH_MS },
497
+ });
498
+ }
499
+ }
500
+ async ensureSession() {
501
+ if (!this.sessionToken) {
502
+ await this.login();
503
+ }
504
+ /* v8 ignore next -- defensive: login() always sets sessionToken on success @preserve */
505
+ return this.sessionToken ?? undefined;
506
+ }
507
+ async withSessionRetry(operation) {
508
+ let attemptedFreshSession = false;
509
+ while (true) {
510
+ const session = await this.ensureSession();
511
+ try {
512
+ return await operation(session);
513
+ }
514
+ catch (error) {
515
+ const err = error;
516
+ if (attemptedFreshSession || !isBwSessionAuthError(err)) {
517
+ throw err;
518
+ }
519
+ this.sessionToken = null;
520
+ this.structuredItemCache = null;
521
+ attemptedFreshSession = true;
522
+ }
523
+ }
524
+ }
525
+ async withTransientRetry(operation) {
526
+ let lastError;
527
+ for (let attempt = 0; attempt < TRANSIENT_MAX_RETRIES; attempt++) {
528
+ try {
529
+ return await operation();
530
+ }
531
+ catch (err) {
532
+ /* v8 ignore next -- defensive: operation always throws Error instances @preserve */
533
+ lastError = err instanceof Error ? err : new Error(String(err));
534
+ if (!isTransientError(lastError)) {
535
+ throw lastError;
536
+ }
537
+ if (attempt === TRANSIENT_MAX_RETRIES - 1)
538
+ break;
539
+ const backoffMs = TRANSIENT_RETRY_BASE_MS * Math.pow(2, attempt);
540
+ (0, runtime_1.emitNervesEvent)({
541
+ event: "repertoire.bw_transient_retry",
542
+ component: "repertoire",
543
+ message: `transient bw error, retrying in ${backoffMs}ms`,
544
+ meta: { attempt: attempt + 1, backoffMs, reason: lastError.message },
545
+ });
546
+ await delay(backoffMs);
547
+ }
548
+ }
549
+ throw lastError;
550
+ }
551
+ async get(domain) {
552
+ (0, runtime_1.emitNervesEvent)({
553
+ event: "repertoire.bw_credential_get_start",
554
+ component: "repertoire",
555
+ message: `getting credential via bw for ${domain}`,
556
+ meta: { domain, backend: "bitwarden" },
557
+ });
558
+ const item = await this.withTransientRetry(() => this.withSessionRetry((session) => this.findItemByDomain(domain, session)));
559
+ if (!item) {
560
+ (0, runtime_1.emitNervesEvent)({
561
+ event: "repertoire.bw_credential_get_end",
562
+ component: "repertoire",
563
+ message: `no bw credential for ${domain}`,
564
+ meta: { domain, found: false, backend: "bitwarden" },
565
+ });
566
+ return null;
567
+ }
568
+ (0, runtime_1.emitNervesEvent)({
569
+ event: "repertoire.bw_credential_get_end",
570
+ component: "repertoire",
571
+ message: `bw credential found for ${domain}`,
572
+ meta: { domain, found: true, backend: "bitwarden" },
573
+ });
574
+ return {
575
+ domain: item.name,
576
+ username: item.login?.username,
577
+ notes: item.notes ?? undefined,
578
+ createdAt: item.revisionDate ?? new Date().toISOString(),
579
+ };
580
+ }
581
+ async getRawSecret(domain, field) {
582
+ const item = await this.withTransientRetry(() => this.withSessionRetry((session) => this.findItemByDomain(domain, session)));
583
+ if (!item) {
584
+ throw new Error(`no credential found for domain "${domain}"`);
585
+ }
586
+ // Map common field names to bw item structure
587
+ let value;
588
+ if (field === "password") {
589
+ value = item.login?.password;
590
+ }
591
+ else if (field === "username") {
592
+ value = item.login?.username;
593
+ }
594
+ else {
595
+ value = item[field];
596
+ }
597
+ if (value === undefined || value === null) {
598
+ throw new Error(`field "${field}" not found for domain "${domain}"`);
599
+ }
600
+ return String(value);
601
+ }
602
+ async store(domain, data) {
603
+ (0, runtime_1.emitNervesEvent)({
604
+ event: "repertoire.bw_credential_store_start",
605
+ component: "repertoire",
606
+ message: `storing credential via bw for ${domain}`,
607
+ meta: { domain, backend: "bitwarden" },
608
+ });
609
+ await this.withSessionRetry(async (session) => {
610
+ const existing = await this.findItemByDomain(domain, session);
611
+ const item = {
612
+ ...(existing ?? {}),
613
+ type: 1, // Login type
614
+ name: domain,
615
+ login: {
616
+ username: data.username ?? "",
617
+ password: data.password,
618
+ uris: [{ match: null, uri: `https://${domain}` }],
619
+ },
620
+ notes: data.notes ?? null,
621
+ };
622
+ const encoded = Buffer.from(JSON.stringify(item)).toString("base64");
623
+ this.structuredItemCache = null;
624
+ let savedItem;
625
+ if (existing) {
626
+ const stdout = await this.execBw(["edit", "item", existing.id], session, encoded);
627
+ const savedItemId = parseBwItemId(stdout) ?? existing.id;
628
+ savedItem = await this.findItemById(savedItemId, session);
629
+ }
630
+ else {
631
+ const stdout = await this.execBw(["create", "item"], session, encoded);
632
+ const savedItemId = parseBwItemId(stdout);
633
+ savedItem = savedItemId
634
+ ? await this.findItemById(savedItemId, session)
635
+ : await this.findItemByDomain(domain, session);
636
+ }
637
+ this.assertStoredCredentialMatches(domain, data, savedItem);
638
+ });
639
+ this.structuredItemCache = null;
640
+ (0, runtime_1.emitNervesEvent)({
641
+ event: "repertoire.bw_credential_store_end",
642
+ component: "repertoire",
643
+ message: `credential stored via bw for ${domain}`,
644
+ meta: { domain, backend: "bitwarden" },
645
+ });
646
+ }
647
+ async list() {
648
+ (0, runtime_1.emitNervesEvent)({
649
+ event: "repertoire.bw_credential_list_start",
650
+ component: "repertoire",
651
+ message: "listing bw credentials",
652
+ meta: { backend: "bitwarden" },
653
+ });
654
+ const stdout = await this.withTransientRetry(() => this.withSessionRetry((session) => this.execBw(["list", "items"], session)));
655
+ const items = parseBwItems(stdout, "bw list items");
656
+ const results = items.map((item) => ({
657
+ domain: item.name,
658
+ username: item.login?.username,
659
+ notes: item.notes ?? undefined,
660
+ createdAt: item.revisionDate ?? new Date().toISOString(),
661
+ }));
662
+ (0, runtime_1.emitNervesEvent)({
663
+ event: "repertoire.bw_credential_list_end",
664
+ component: "repertoire",
665
+ message: "bw credentials listed",
666
+ meta: { backend: "bitwarden", count: results.length },
667
+ });
668
+ return results;
669
+ }
670
+ async delete(domain) {
671
+ (0, runtime_1.emitNervesEvent)({
672
+ event: "repertoire.bw_credential_delete_start",
673
+ component: "repertoire",
674
+ message: `deleting credential via bw for ${domain}`,
675
+ meta: { domain, backend: "bitwarden" },
676
+ });
677
+ const item = await this.withSessionRetry((session) => this.findItemByDomain(domain, session));
678
+ if (!item) {
679
+ (0, runtime_1.emitNervesEvent)({
680
+ event: "repertoire.bw_credential_delete_end",
681
+ component: "repertoire",
682
+ message: `no bw credential to delete for ${domain}`,
683
+ meta: { domain, deleted: false, backend: "bitwarden" },
684
+ });
685
+ return false;
686
+ }
687
+ await this.withSessionRetry((session) => this.execBw(["delete", "item", item.id], session));
688
+ this.structuredItemCache = null;
689
+ (0, runtime_1.emitNervesEvent)({
690
+ event: "repertoire.bw_credential_delete_end",
691
+ component: "repertoire",
692
+ message: `credential deleted via bw for ${domain}`,
693
+ meta: { domain, deleted: true, backend: "bitwarden" },
694
+ });
695
+ return true;
696
+ }
697
+ // --- Private ---
698
+ async findItemByDomain(domain, session) {
699
+ if (shouldPreferExactItemLookup(domain)) {
700
+ const items = await this.readStructuredItemCache(session);
701
+ return items.get(domain) ?? null;
702
+ }
703
+ const stdout = await this.execBw(["list", "items", "--search", domain], session);
704
+ const items = parseBwItems(stdout, "bw list items --search");
705
+ // Find exact match by name
706
+ return items.find((item) => item.name === domain) ?? null;
707
+ }
708
+ shouldSyncVaultAfterSession(status) {
709
+ if (status.status === "unauthenticated" || !status.status)
710
+ return true;
711
+ if (!this.appDataDir)
712
+ return true;
713
+ const freshnessTimestamp = this.latestLocalSyncTimestamp();
714
+ if (freshnessTimestamp !== null) {
715
+ return Date.now() - freshnessTimestamp > BW_SYNC_FRESH_MS;
716
+ }
717
+ return true;
718
+ }
719
+ latestLocalSyncTimestamp() {
720
+ const files = [BW_SYNC_MARKER_FILENAME, BW_DATA_FILENAME];
721
+ let latest = null;
722
+ for (const name of files) {
723
+ try {
724
+ const mtimeMs = fs.statSync(path.join(this.appDataDir, name)).mtimeMs;
725
+ latest = latest === null ? mtimeMs : Math.max(latest, mtimeMs);
726
+ }
727
+ catch {
728
+ // Missing freshness file is fine; use any other available timestamp.
729
+ }
730
+ }
731
+ return latest;
732
+ }
733
+ writeSyncMarker() {
734
+ if (!this.appDataDir)
735
+ return;
736
+ try {
737
+ fs.writeFileSync(path.join(this.appDataDir, BW_SYNC_MARKER_FILENAME), `${Date.now()}\n`, { mode: 0o600 });
738
+ }
739
+ catch {
740
+ // If the marker cannot be written, fall back to syncing next time.
741
+ }
742
+ }
743
+ async readStructuredItemCache(session) {
744
+ if (this.structuredItemCache)
745
+ return this.structuredItemCache;
746
+ const stdout = await this.execBw(["list", "items"], session);
747
+ const items = parseBwItems(stdout, "bw list items");
748
+ this.structuredItemCache = new Map(items.map((item) => [item.name, item]));
749
+ return this.structuredItemCache;
750
+ }
751
+ async findItemById(id, session) {
752
+ const stdout = await this.execBw(["get", "item", id], session);
753
+ return parseBwItem(stdout, "bw get item");
754
+ }
755
+ assertStoredCredentialMatches(domain, data, item) {
756
+ if (!item) {
757
+ throw new Error(`bw CLI error: credential save verification failed for ${domain}: saved item could not be read back after write`);
758
+ }
759
+ const mismatches = [];
760
+ if (item.name !== domain)
761
+ mismatches.push("name");
762
+ if ((item.login?.username ?? "") !== (data.username ?? ""))
763
+ mismatches.push("username");
764
+ if ((item.login?.password ?? "") !== data.password)
765
+ mismatches.push("password");
766
+ if ((item.notes ?? null) !== (data.notes ?? null))
767
+ mismatches.push("notes");
768
+ if (mismatches.length > 0) {
769
+ const label = mismatches.length === 1 ? "field" : "fields";
770
+ throw new Error(`bw CLI error: credential save verification failed for ${domain}: saved item did not match requested ${label} ${mismatches.join(", ")}`);
771
+ }
772
+ }
773
+ }
774
+ exports.BitwardenCredentialStore = BitwardenCredentialStore;