puspa 0.1.0__py3-none-any.whl

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 (687) hide show
  1. puspa/__init__.py +1 -0
  2. puspa/__main__.py +7 -0
  3. puspa/accounts/__init__.py +31 -0
  4. puspa/accounts/ports.py +372 -0
  5. puspa/accounts/vault.py +319 -0
  6. puspa/auth/__init__.py +47 -0
  7. puspa/auth/email_link.py +96 -0
  8. puspa/auth/google_oauth.py +353 -0
  9. puspa/autonomy/__init__.py +49 -0
  10. puspa/autonomy/controls.py +485 -0
  11. puspa/autonomy/dial.py +669 -0
  12. puspa/backup/__init__.py +30 -0
  13. puspa/backup/local_state.py +174 -0
  14. puspa/backup/ports.py +85 -0
  15. puspa/billing/__init__.py +16 -0
  16. puspa/billing/config.py +264 -0
  17. puspa/billing/fixture.py +103 -0
  18. puspa/billing/ports.py +649 -0
  19. puspa/cassette/__init__.py +1 -0
  20. puspa/cassette/cassette.py +184 -0
  21. puspa/channels/__init__.py +119 -0
  22. puspa/channels/agent.py +112 -0
  23. puspa/channels/authz.py +221 -0
  24. puspa/channels/base.py +61 -0
  25. puspa/channels/cli.py +142 -0
  26. puspa/channels/config.py +256 -0
  27. puspa/channels/delivery.py +105 -0
  28. puspa/channels/discord.py +277 -0
  29. puspa/channels/engines.py +258 -0
  30. puspa/channels/engines_bailian.py +113 -0
  31. puspa/channels/engines_coze.py +192 -0
  32. puspa/channels/engines_dify.py +104 -0
  33. puspa/channels/errors.py +38 -0
  34. puspa/channels/events.py +58 -0
  35. puspa/channels/heartbeat.py +112 -0
  36. puspa/channels/inbound.py +194 -0
  37. puspa/channels/ledger.py +334 -0
  38. puspa/channels/line.py +253 -0
  39. puspa/channels/notify.py +34 -0
  40. puspa/channels/run.py +370 -0
  41. puspa/channels/slack.py +305 -0
  42. puspa/channels/telegram.py +273 -0
  43. puspa/channels/whatsapp.py +216 -0
  44. puspa/chassis/__init__.py +80 -0
  45. puspa/chassis/agent_session.py +217 -0
  46. puspa/chassis/context.py +112 -0
  47. puspa/chassis/contract.py +62 -0
  48. puspa/chassis/factory.py +213 -0
  49. puspa/chassis/hooks.py +474 -0
  50. puspa/chassis/pin.json +17 -0
  51. puspa/chassis/pin.py +235 -0
  52. puspa/chassis/registry.py +137 -0
  53. puspa/chassis/sandbox_tool.py +144 -0
  54. puspa/chassis/skill_loader.py +93 -0
  55. puspa/chassis/tools.py +600 -0
  56. puspa/check_before_buy/__init__.py +53 -0
  57. puspa/check_before_buy/answer.py +618 -0
  58. puspa/check_before_buy/classifier.py +144 -0
  59. puspa/check_before_buy/outcome.py +93 -0
  60. puspa/check_before_buy/records.py +161 -0
  61. puspa/check_before_buy/wiring.py +68 -0
  62. puspa/cli.py +977 -0
  63. puspa/computer/__init__.py +182 -0
  64. puspa/computer/allowlist.py +111 -0
  65. puspa/computer/audit.py +205 -0
  66. puspa/computer/backend.py +630 -0
  67. puspa/computer/cli.py +975 -0
  68. puspa/computer/fallback.py +534 -0
  69. puspa/computer/gating.py +65 -0
  70. puspa/computer/hands.py +1576 -0
  71. puspa/computer/input.py +669 -0
  72. puspa/computer/mcp.py +805 -0
  73. puspa/computer/safety.py +333 -0
  74. puspa/computer/screenshot.py +275 -0
  75. puspa/computer/stop.py +133 -0
  76. puspa/computer/sync.py +225 -0
  77. puspa/computer/tiers.py +99 -0
  78. puspa/computer/tree.py +241 -0
  79. puspa/computer/vision.py +390 -0
  80. puspa/computer/web.py +815 -0
  81. puspa/computer/windows.py +417 -0
  82. puspa/connectors/__init__.py +59 -0
  83. puspa/connectors/accounts.py +183 -0
  84. puspa/connectors/aggregator.py +152 -0
  85. puspa/connectors/allowlist.py +143 -0
  86. puspa/connectors/google.py +216 -0
  87. puspa/connectors/grants.py +86 -0
  88. puspa/connectors/mcp_registry.py +276 -0
  89. puspa/connectors/native.py +190 -0
  90. puspa/connectors/token_app_server.py +289 -0
  91. puspa/connectors/token_apps.py +303 -0
  92. puspa/connectors/wedges.py +346 -0
  93. puspa/consent/__init__.py +20 -0
  94. puspa/consent/account.py +110 -0
  95. puspa/consent/consent.py +116 -0
  96. puspa/consistency/__init__.py +28 -0
  97. puspa/consistency/idempotency.py +33 -0
  98. puspa/consistency/kill_drill.py +159 -0
  99. puspa/consistency/rebuild.py +84 -0
  100. puspa/consistency/reconcile.py +75 -0
  101. puspa/consistency/runner.py +206 -0
  102. puspa/consistency/worker.py +103 -0
  103. puspa/consistency/write_ahead.py +332 -0
  104. puspa/credentials/__init__.py +12 -0
  105. puspa/credentials/auth.py +460 -0
  106. puspa/credentials/pool.py +391 -0
  107. puspa/credentials/redact.py +292 -0
  108. puspa/credentials/resolver.py +536 -0
  109. puspa/credentials/scope.py +224 -0
  110. puspa/decider/__init__.py +75 -0
  111. puspa/decider/backends.py +340 -0
  112. puspa/decider/decider.py +247 -0
  113. puspa/decider/jobs.py +192 -0
  114. puspa/decider/keycheck.py +38 -0
  115. puspa/decider/log.py +93 -0
  116. puspa/decider/questions.py +251 -0
  117. puspa/diagnostics/__init__.py +35 -0
  118. puspa/diagnostics/export.py +413 -0
  119. puspa/diagnostics/redact.py +73 -0
  120. puspa/drafting/__init__.py +54 -0
  121. puspa/drafting/drafting.py +721 -0
  122. puspa/drafting/errors.py +29 -0
  123. puspa/drafting/schema.py +40 -0
  124. puspa/drafting/voice.py +382 -0
  125. puspa/eval/__init__.py +41 -0
  126. puspa/eval/attack_harness.py +390 -0
  127. puspa/eval/bm25.py +75 -0
  128. puspa/eval/corpus.py +287 -0
  129. puspa/eval/data/attack_corpus_v1.json +1 -0
  130. puspa/eval/data/benign_indonesian_v1.json +1 -0
  131. puspa/eval/data/gold_entity_identity_v1.json +1 -0
  132. puspa/eval/data/gold_orphan_numbers_v1.json +1 -0
  133. puspa/eval/data/gold_quoted_numbers_v1.json +1 -0
  134. puspa/eval/data/public_sources.md +42 -0
  135. puspa/eval/fuzz.py +165 -0
  136. puspa/eval/gold_sets.py +243 -0
  137. puspa/eval/intervals.py +54 -0
  138. puspa/eval/mutation.py +284 -0
  139. puspa/eval/reference_tasks.py +381 -0
  140. puspa/eval/replay.py +137 -0
  141. puspa/eval/retrieval_sets.py +423 -0
  142. puspa/eval/scorecard.py +349 -0
  143. puspa/evidence/__init__.py +1 -0
  144. puspa/evidence/agentbench_tasks.py +585 -0
  145. puspa/evidence/bfcl_checker.py +662 -0
  146. puspa/evidence/bfcl_tasks.py +728 -0
  147. puspa/evidence/eval_harness.py +531 -0
  148. puspa/evidence/evidence.py +174 -0
  149. puspa/evidence/outcomes.py +392 -0
  150. puspa/evidence/projections.py +134 -0
  151. puspa/evidence/proof.py +692 -0
  152. puspa/evidence/renderer.py +120 -0
  153. puspa/evidence/verifier.py +102 -0
  154. puspa/feature_flags.py +208 -0
  155. puspa/gallery/__init__.py +28 -0
  156. puspa/gallery/store.py +359 -0
  157. puspa/gallery/support.py +358 -0
  158. puspa/governor/__init__.py +96 -0
  159. puspa/governor/budgets.py +368 -0
  160. puspa/governor/compiler.py +835 -0
  161. puspa/governor/governor.py +497 -0
  162. puspa/governor/skills.py +645 -0
  163. puspa/graphs/__init__.py +58 -0
  164. puspa/graphs/fraud_patterns.py +282 -0
  165. puspa/graphs/identity.py +516 -0
  166. puspa/graphs/service.py +330 -0
  167. puspa/graphs/shared.py +527 -0
  168. puspa/graphs/temporal.py +372 -0
  169. puspa/guardrails/__init__.py +51 -0
  170. puspa/guardrails/rails.py +849 -0
  171. puspa/harness/__init__.py +139 -0
  172. puspa/harness/diff.py +282 -0
  173. puspa/harness/executor.py +466 -0
  174. puspa/harness/loop.py +834 -0
  175. puspa/harness/modes.py +191 -0
  176. puspa/harness/repo_map.py +283 -0
  177. puspa/harness/reproduce.py +284 -0
  178. puspa/harness/sandbox_profiles.py +308 -0
  179. puspa/hosting/__init__.py +29 -0
  180. puspa/hosting/errors.py +31 -0
  181. puspa/hosting/pairing.py +258 -0
  182. puspa/i18n/__init__.py +46 -0
  183. puspa/i18n/locales/en.json +64 -0
  184. puspa/i18n/locales/id.json +64 -0
  185. puspa/i18n/locales.py +111 -0
  186. puspa/i18n/server_lines.py +150 -0
  187. puspa/intent/__init__.py +62 -0
  188. puspa/intent/act_ask.py +356 -0
  189. puspa/intent/distribution.py +242 -0
  190. puspa/intent/inference.py +570 -0
  191. puspa/intent/turn_wiring.py +192 -0
  192. puspa/knowledge/__init__.py +29 -0
  193. puspa/knowledge/cli.py +149 -0
  194. puspa/knowledge/store.py +421 -0
  195. puspa/ledger/__init__.py +103 -0
  196. puspa/ledger/anchor.py +382 -0
  197. puspa/ledger/audit.py +571 -0
  198. puspa/ledger/audit_daemon.py +307 -0
  199. puspa/ledger/audit_writer.py +108 -0
  200. puspa/ledger/errors.py +16 -0
  201. puspa/ledger/export.py +227 -0
  202. puspa/ledger/kill_switch.py +304 -0
  203. puspa/ledger/ledger.py +633 -0
  204. puspa/local_data/__init__.py +64 -0
  205. puspa/local_data/language.py +214 -0
  206. puspa/local_data/money.py +289 -0
  207. puspa/local_data/rails.py +187 -0
  208. puspa/local_data/rates.py +441 -0
  209. puspa/localexec/__init__.py +30 -0
  210. puspa/localexec/executor.py +249 -0
  211. puspa/marketplace/__init__.py +185 -0
  212. puspa/marketplace/authoring.py +289 -0
  213. puspa/marketplace/cli.py +160 -0
  214. puspa/marketplace/discovery.py +950 -0
  215. puspa/marketplace/errors.py +69 -0
  216. puspa/marketplace/hub.py +744 -0
  217. puspa/marketplace/learning.py +309 -0
  218. puspa/marketplace/manifest.py +346 -0
  219. puspa/marketplace/narrowing.py +263 -0
  220. puspa/marketplace/registry.py +358 -0
  221. puspa/marketplace/share.py +103 -0
  222. puspa/marketplace/skill_creator.py +846 -0
  223. puspa/marketplace/store.py +285 -0
  224. puspa/marketplace/trust.py +216 -0
  225. puspa/mcp_server/__init__.py +33 -0
  226. puspa/mcp_server/cli.py +115 -0
  227. puspa/mcp_server/handlers.py +434 -0
  228. puspa/mcp_server/server.py +321 -0
  229. puspa/mcp_server/tools.py +274 -0
  230. puspa/meetings/__init__.py +112 -0
  231. puspa/meetings/parse.py +317 -0
  232. puspa/meetings/reminders.py +254 -0
  233. puspa/meetings/schema.py +42 -0
  234. puspa/meetings/store.py +385 -0
  235. puspa/memory/__init__.py +67 -0
  236. puspa/memory/amnesia.py +412 -0
  237. puspa/memory/background_review.py +348 -0
  238. puspa/memory/commit_turn.py +1090 -0
  239. puspa/memory/consolidate.py +301 -0
  240. puspa/memory/curator.py +358 -0
  241. puspa/memory/curriculum_guardrails.py +336 -0
  242. puspa/memory/dream.py +272 -0
  243. puspa/memory/durable.py +942 -0
  244. puspa/memory/embeddings.py +358 -0
  245. puspa/memory/episodic.py +495 -0
  246. puspa/memory/extraction.py +493 -0
  247. puspa/memory/facts.py +572 -0
  248. puspa/memory/importer.py +1617 -0
  249. puspa/memory/journal.py +126 -0
  250. puspa/memory/learning_graph.py +436 -0
  251. puspa/memory/learning_loop.py +1216 -0
  252. puspa/memory/limits.py +93 -0
  253. puspa/memory/longterm.py +734 -0
  254. puspa/memory/loop_store.py +260 -0
  255. puspa/memory/memory_export.py +803 -0
  256. puspa/memory/ontology_evolve.py +942 -0
  257. puspa/memory/ontology_review.py +375 -0
  258. puspa/memory/optimizer.py +256 -0
  259. puspa/memory/procedural.py +488 -0
  260. puspa/memory/profile.py +252 -0
  261. puspa/memory/provider.py +618 -0
  262. puspa/memory/recall.py +240 -0
  263. puspa/memory/recall_plan.py +419 -0
  264. puspa/memory/schema.py +17 -0
  265. puspa/memory/self_evolution.py +565 -0
  266. puspa/memory/skill_repair.py +649 -0
  267. puspa/memory/slices.py +109 -0
  268. puspa/memory/trust.py +212 -0
  269. puspa/memory/wiki.py +647 -0
  270. puspa/memory/working.py +419 -0
  271. puspa/memory/write_cycle.py +168 -0
  272. puspa/migrations/__init__.py +31 -0
  273. puspa/migrations/__main__.py +80 -0
  274. puspa/migrations/runner.py +272 -0
  275. puspa/migrations/versions/0001_core.sql +192 -0
  276. puspa/migrations/versions/0002_memory.sql +223 -0
  277. puspa/migrations/versions/0003_runtime.sql +174 -0
  278. puspa/migrations/versions/0004_graphs.sql +244 -0
  279. puspa/migrations/versions/0005_workflow.sql +138 -0
  280. puspa/migrations/versions/0006_world.sql +169 -0
  281. puspa/migrations/versions/0007_learning_loop.sql +70 -0
  282. puspa/migrations/versions/0008_channels.sql +38 -0
  283. puspa/migrations/versions/0009_teams.sql +21 -0
  284. puspa/migrations/versions/0010_rooms.sql +499 -0
  285. puspa/migrations/versions/0011_meetings.sql +52 -0
  286. puspa/migrations/versions/0012_drafting.sql +89 -0
  287. puspa/migrations/versions/0013_payments.sql +52 -0
  288. puspa/migrations/versions/0014_marketplace.sql +59 -0
  289. puspa/migrations/versions/0015_mockup.sql +41 -0
  290. puspa/migrations/versions/0016_model_settings.sql +28 -0
  291. puspa/migrations/versions/0017_onboarding_hints.sql +26 -0
  292. puspa/migrations/versions/0018_scheduler.sql +39 -0
  293. puspa/migrations/versions/0019_conflicts.sql +70 -0
  294. puspa/migrations/versions/0020_token_revocations.sql +61 -0
  295. puspa/migrations/versions/0021_mockup_rls_grant.sql +46 -0
  296. puspa/migrations/versions/0022_embedding_health.sql +114 -0
  297. puspa/migrations/versions/0023_memory_rights.sql +37 -0
  298. puspa/migrations/versions/0024_room_job_queue.sql +36 -0
  299. puspa/migrations/versions/0025_morning_notes.sql +31 -0
  300. puspa/migrations/versions/0026_takeover_holds.sql +70 -0
  301. puspa/migrations/versions/0027_takeover_check_dedup.sql +40 -0
  302. puspa/migrations/versions/0028_runtime_session_states.sql +58 -0
  303. puspa/migrations/versions/0029_durable_memory.sql +93 -0
  304. puspa/migrations/versions/0030_turn_commit_retries.sql +71 -0
  305. puspa/migrations/versions/0031_memory_import.sql +142 -0
  306. puspa/migrations/versions/0032_user_display_names.sql +44 -0
  307. puspa/migrations/versions/0033_voice_settings.sql +32 -0
  308. puspa/migrations/versions/0034_longterm_tiers.sql +68 -0
  309. puspa/migrations/versions/0035_artifacts.sql +67 -0
  310. puspa/migrations/versions/0036_telemetry_settings.sql +27 -0
  311. puspa/migrations/versions/0037_document_knowledge_base.sql +82 -0
  312. puspa/migrations/versions/0038_capability_routing.sql +33 -0
  313. puspa/migrations/versions/0039_instance_settings.sql +34 -0
  314. puspa/migrations/versions/0040_user_language.sql +27 -0
  315. puspa/migrations/versions/0041_team_workspaces_audit.sql +21 -0
  316. puspa/migrations/versions/0042_gallery.sql +91 -0
  317. puspa/migrations/versions/0043_creator_support.sql +63 -0
  318. puspa/migrations/versions/0044_multi_agent_teams.sql +69 -0
  319. puspa/migrations/versions/0045_missions.sql +36 -0
  320. puspa/mind/__init__.py +75 -0
  321. puspa/mind/felt_state.py +792 -0
  322. puspa/mind/metacognition.py +449 -0
  323. puspa/mind/workspace.py +360 -0
  324. puspa/missions/__init__.py +29 -0
  325. puspa/missions/missions.py +315 -0
  326. puspa/missions/runner.py +283 -0
  327. puspa/missions/webhooks.py +131 -0
  328. puspa/moat/__init__.py +2 -0
  329. puspa/moat/library.py +87 -0
  330. puspa/moat/metrics.py +167 -0
  331. puspa/moat/reliability.py +98 -0
  332. puspa/moat/report.py +90 -0
  333. puspa/mockup/__init__.py +29 -0
  334. puspa/mockup/doc.py +537 -0
  335. puspa/mockup/export.py +143 -0
  336. puspa/mockup/generate.py +388 -0
  337. puspa/mockup/render.py +310 -0
  338. puspa/mockup/store.py +149 -0
  339. puspa/mockup/templates.py +405 -0
  340. puspa/modules/__init__.py +0 -0
  341. puspa/modules/bills.py +116 -0
  342. puspa/modules/manifest.py +413 -0
  343. puspa/modules/notifications.py +29 -0
  344. puspa/modules/tables.py +176 -0
  345. puspa/modules/views.py +127 -0
  346. puspa/morning/__init__.py +18 -0
  347. puspa/morning/holidays.py +111 -0
  348. puspa/morning/notes.py +373 -0
  349. puspa/morning/prayer.py +159 -0
  350. puspa/morning/summary.py +442 -0
  351. puspa/multimodal/__init__.py +73 -0
  352. puspa/multimodal/attachments.py +371 -0
  353. puspa/multimodal/generation.py +86 -0
  354. puspa/multimodal/turns.py +189 -0
  355. puspa/multimodal/vision.py +124 -0
  356. puspa/observability/__init__.py +67 -0
  357. puspa/observability/health.py +45 -0
  358. puspa/observability/logging.py +111 -0
  359. puspa/observability/metrics.py +391 -0
  360. puspa/observability/tracing.py +274 -0
  361. puspa/onboarding/__init__.py +31 -0
  362. puspa/onboarding/hints.py +250 -0
  363. puspa/onboarding/onboarding.py +253 -0
  364. puspa/persona/__init__.py +85 -0
  365. puspa/persona/blind_test.py +128 -0
  366. puspa/persona/files.py +271 -0
  367. puspa/persona/persona.py +202 -0
  368. puspa/persona/switcher.py +405 -0
  369. puspa/plugins/__init__.py +139 -0
  370. puspa/plugins/adapters.py +180 -0
  371. puspa/plugins/api_version.py +190 -0
  372. puspa/plugins/boundary.py +234 -0
  373. puspa/plugins/builtin/__init__.py +20 -0
  374. puspa/plugins/builtin/echo.py +42 -0
  375. puspa/plugins/builtin/memory_inmemory.py +100 -0
  376. puspa/plugins/builtin/simple_context.py +130 -0
  377. puspa/plugins/catalog/acme-notes.yaml +13 -0
  378. puspa/plugins/catalog/local-llm-context.yaml +12 -0
  379. puspa/plugins/catalog/sqlite-memory.yaml +12 -0
  380. puspa/plugins/catalog.py +235 -0
  381. puspa/plugins/context.py +396 -0
  382. puspa/plugins/context_engine.py +47 -0
  383. puspa/plugins/errors.py +66 -0
  384. puspa/plugins/loader.py +489 -0
  385. puspa/plugins/mcp.py +212 -0
  386. puspa/plugins/mcp_definitions/http-fetch-mcp.json +1 -0
  387. puspa/plugins/mcp_definitions/local-files-mcp.json +1 -0
  388. puspa/plugins/mcp_definitions/sqlite-mcp.json +1 -0
  389. puspa/plugins/permissions.py +137 -0
  390. puspa/plugins/plugin_api.json +1 -0
  391. puspa/plugins/single_select.py +199 -0
  392. puspa/policy/__init__.py +260 -0
  393. puspa/policy/agent_scan.py +1070 -0
  394. puspa/policy/allowlist.py +139 -0
  395. puspa/policy/approval_cards.py +428 -0
  396. puspa/policy/approvals.py +1051 -0
  397. puspa/policy/conflicts.py +984 -0
  398. puspa/policy/gate.py +368 -0
  399. puspa/policy/gateway.py +903 -0
  400. puspa/policy/revocation.py +587 -0
  401. puspa/policy/revocations.py +226 -0
  402. puspa/policy/rules.py +301 -0
  403. puspa/policy/session_modes.py +386 -0
  404. puspa/policy/signing.py +498 -0
  405. puspa/policy/sigstore_verify.py +233 -0
  406. puspa/policy/skill_signing.py +514 -0
  407. puspa/policy/spending.py +105 -0
  408. puspa/policy/stop.py +187 -0
  409. puspa/policy/tokens.py +440 -0
  410. puspa/policy/trust_root.py +455 -0
  411. puspa/pricing/__init__.py +2 -0
  412. puspa/pricing/cache.py +70 -0
  413. puspa/pricing/catalog.py +169 -0
  414. puspa/pricing/compare.py +262 -0
  415. puspa/pricing/credits.py +69 -0
  416. puspa/pricing/readers.py +312 -0
  417. puspa/pricing/tos.py +146 -0
  418. puspa/pricing/watchlist.py +154 -0
  419. puspa/proactivity/__init__.py +45 -0
  420. puspa/proactivity/budget.py +464 -0
  421. puspa/push/__init__.py +1 -0
  422. puspa/push/ports.py +48 -0
  423. puspa/pwa/__init__.py +1 -0
  424. puspa/pwa/admin_api.py +399 -0
  425. puspa/pwa/admin_settings.py +77 -0
  426. puspa/pwa/app.py +1400 -0
  427. puspa/pwa/approval_overlay.py +599 -0
  428. puspa/pwa/approval_overlay_api.py +356 -0
  429. puspa/pwa/artifacts.py +256 -0
  430. puspa/pwa/artifacts_api.py +114 -0
  431. puspa/pwa/avatar_api.py +222 -0
  432. puspa/pwa/capability_routing.py +808 -0
  433. puspa/pwa/capability_routing_api.py +162 -0
  434. puspa/pwa/chat_cards.py +506 -0
  435. puspa/pwa/chat_cards_api.py +180 -0
  436. puspa/pwa/chat_widgets.py +898 -0
  437. puspa/pwa/chat_widgets_api.py +273 -0
  438. puspa/pwa/computer_api.py +219 -0
  439. puspa/pwa/controls_api.py +220 -0
  440. puspa/pwa/diagnostics_api.py +98 -0
  441. puspa/pwa/drafts_api.py +218 -0
  442. puspa/pwa/gallery_api.py +153 -0
  443. puspa/pwa/graph_api.py +894 -0
  444. puspa/pwa/health.py +73 -0
  445. puspa/pwa/hub_api.py +210 -0
  446. puspa/pwa/insights_api.py +58 -0
  447. puspa/pwa/knowledge_api.py +187 -0
  448. puspa/pwa/language.py +126 -0
  449. puspa/pwa/language_api.py +106 -0
  450. puspa/pwa/lite.py +277 -0
  451. puspa/pwa/live_view.py +622 -0
  452. puspa/pwa/live_view_api.py +283 -0
  453. puspa/pwa/memory_api.py +757 -0
  454. puspa/pwa/missions_api.py +231 -0
  455. puspa/pwa/mockup_api.py +317 -0
  456. puspa/pwa/model_settings.py +435 -0
  457. puspa/pwa/morning_api.py +427 -0
  458. puspa/pwa/multimodal_api.py +172 -0
  459. puspa/pwa/names_api.py +72 -0
  460. puspa/pwa/onboarding_api.py +272 -0
  461. puspa/pwa/personas_api.py +185 -0
  462. puspa/pwa/proof_api.py +193 -0
  463. puspa/pwa/provider_login_api.py +230 -0
  464. puspa/pwa/receipt_api.py +344 -0
  465. puspa/pwa/replay.py +573 -0
  466. puspa/pwa/replay_api.py +238 -0
  467. puspa/pwa/rooms_api.py +825 -0
  468. puspa/pwa/rooms_jobs.py +221 -0
  469. puspa/pwa/serve_modes.py +340 -0
  470. puspa/pwa/share_api.py +194 -0
  471. puspa/pwa/static/icon-192.png +0 -0
  472. puspa/pwa/static/puspa-logo.png +0 -0
  473. puspa/pwa/static/sw.js +55 -0
  474. puspa/pwa/stop_all.py +184 -0
  475. puspa/pwa/support_api.py +93 -0
  476. puspa/pwa/telemetry_api.py +91 -0
  477. puspa/pwa/templates/admin.html +184 -0
  478. puspa/pwa/templates/artifacts.html +11 -0
  479. puspa/pwa/templates/base.html +45 -0
  480. puspa/pwa/templates/chat.html +41 -0
  481. puspa/pwa/templates/connectors.html +22 -0
  482. puspa/pwa/templates/diagnostics.html +15 -0
  483. puspa/pwa/templates/gallery.html +60 -0
  484. puspa/pwa/templates/hub.html +95 -0
  485. puspa/pwa/templates/insights.html +6 -0
  486. puspa/pwa/templates/knowledge.html +16 -0
  487. puspa/pwa/templates/live.html +11 -0
  488. puspa/pwa/templates/login.html +10 -0
  489. puspa/pwa/templates/memory.html +128 -0
  490. puspa/pwa/templates/mockup.html +6 -0
  491. puspa/pwa/templates/modules.html +8 -0
  492. puspa/pwa/templates/morning.html +6 -0
  493. puspa/pwa/templates/office.html +23 -0
  494. puspa/pwa/templates/onboarding.html +6 -0
  495. puspa/pwa/templates/panel_evidence.html +17 -0
  496. puspa/pwa/templates/personas.html +186 -0
  497. puspa/pwa/templates/proof.html +21 -0
  498. puspa/pwa/templates/replay.html +11 -0
  499. puspa/pwa/templates/rooms.html +6 -0
  500. puspa/pwa/templates/settings.html +157 -0
  501. puspa/pwa/templates/tasks.html +24 -0
  502. puspa/pwa/templates/trial.html +39 -0
  503. puspa/pwa/templates/wiki.html +66 -0
  504. puspa/pwa/voice_api.py +482 -0
  505. puspa/pwa/voice_settings.py +509 -0
  506. puspa/pwa/weekly_report.py +192 -0
  507. puspa/pwa/wiki_api.py +138 -0
  508. puspa/py.typed +0 -0
  509. puspa/quarantine/__init__.py +6 -0
  510. puspa/quarantine/injection.py +296 -0
  511. puspa/quarantine/reader.py +120 -0
  512. puspa/receipts/__init__.py +75 -0
  513. puspa/receipts/accuracy.py +286 -0
  514. puspa/receipts/documents.py +131 -0
  515. puspa/receipts/ocr.py +185 -0
  516. puspa/receipts/parser.py +264 -0
  517. puspa/receipts/pipeline.py +167 -0
  518. puspa/retrieval/__init__.py +105 -0
  519. puspa/retrieval/canary_questions.py +142 -0
  520. puspa/retrieval/code_graph.py +832 -0
  521. puspa/retrieval/embedding_health.py +958 -0
  522. puspa/retrieval/hipporag.py +468 -0
  523. puspa/retrieval/incremental.py +516 -0
  524. puspa/retrieval/knowledge_graph.py +528 -0
  525. puspa/retrieval/modes.py +243 -0
  526. puspa/retrieval/reranker.py +669 -0
  527. puspa/retrieval/triple_filter.py +282 -0
  528. puspa/rooms/__init__.py +183 -0
  529. puspa/rooms/errors.py +58 -0
  530. puspa/rooms/memory.py +301 -0
  531. puspa/rooms/names.py +391 -0
  532. puspa/rooms/rooms.py +494 -0
  533. puspa/rooms/schema.py +65 -0
  534. puspa/rooms/tasks.py +366 -0
  535. puspa/router/__init__.py +87 -0
  536. puspa/router/chains.py +214 -0
  537. puspa/router/complete.py +662 -0
  538. puspa/router/compression.py +754 -0
  539. puspa/router/fallback.py +673 -0
  540. puspa/router/oauth.py +659 -0
  541. puspa/router/pool.py +1109 -0
  542. puspa/router/provider_login.py +2468 -0
  543. puspa/router/quota.py +375 -0
  544. puspa/router/router.py +306 -0
  545. puspa/router/translate.py +879 -0
  546. puspa/runtime/__init__.py +77 -0
  547. puspa/runtime/agents.py +133 -0
  548. puspa/runtime/budget.py +109 -0
  549. puspa/runtime/context_compression.py +533 -0
  550. puspa/runtime/handoff.py +188 -0
  551. puspa/runtime/hierarchy.py +860 -0
  552. puspa/runtime/planner.py +432 -0
  553. puspa/runtime/prompt_assembly.py +561 -0
  554. puspa/runtime/prompt_caching.py +168 -0
  555. puspa/runtime/session_store.py +231 -0
  556. puspa/runtime/subagents.py +174 -0
  557. puspa/runtime/tasks.py +637 -0
  558. puspa/scheduler/__init__.py +40 -0
  559. puspa/scheduler/claim.py +291 -0
  560. puspa/scheduler/cron.py +578 -0
  561. puspa/scheduler/curriculum.py +700 -0
  562. puspa/scheduler/due.py +84 -0
  563. puspa/scheduler/execution.py +90 -0
  564. puspa/scheduler/holds.py +119 -0
  565. puspa/scheduler/mission_triggers.py +154 -0
  566. puspa/scheduler/receipts.py +115 -0
  567. puspa/scheduler/recovery.py +100 -0
  568. puspa/scheduler/routines.py +248 -0
  569. puspa/scheduler/scheduler.py +861 -0
  570. puspa/scheduler/schedules.py +322 -0
  571. puspa/scheduler/serve.py +143 -0
  572. puspa/self/__init__.py +80 -0
  573. puspa/self/initiative.py +950 -0
  574. puspa/self/repair_loop.py +840 -0
  575. puspa/sentinel/__init__.py +154 -0
  576. puspa/sentinel/analytics.py +182 -0
  577. puspa/sentinel/decision_log.py +162 -0
  578. puspa/sentinel/detectors.py +607 -0
  579. puspa/sentinel/failure_taxonomy.py +379 -0
  580. puspa/sentinel/insights.py +269 -0
  581. puspa/sentinel/outcome_watcher.py +356 -0
  582. puspa/sentinel/scanner.py +248 -0
  583. puspa/sentinel/state.py +248 -0
  584. puspa/sentinel/thresholds.py +71 -0
  585. puspa/sentinel/traces.py +223 -0
  586. puspa/sentinel/trajectory.py +354 -0
  587. puspa/sentinel/verifier.py +162 -0
  588. puspa/service/__init__.py +5 -0
  589. puspa/service/cli.py +214 -0
  590. puspa/service/manager.py +418 -0
  591. puspa/sessions/__init__.py +88 -0
  592. puspa/sessions/assembly.py +69 -0
  593. puspa/sessions/auto_compress.py +273 -0
  594. puspa/sessions/errors.py +57 -0
  595. puspa/sessions/export.py +586 -0
  596. puspa/sessions/gateway.py +218 -0
  597. puspa/sessions/home.py +140 -0
  598. puspa/sessions/housekeeping.py +129 -0
  599. puspa/sessions/lineage.py +91 -0
  600. puspa/sessions/schema.py +210 -0
  601. puspa/sessions/single_writer.py +304 -0
  602. puspa/sessions/spawner.py +60 -0
  603. puspa/sessions/store.py +684 -0
  604. puspa/subagents/__init__.py +68 -0
  605. puspa/subagents/errors.py +89 -0
  606. puspa/subagents/handles.py +109 -0
  607. puspa/subagents/hooks.py +73 -0
  608. puspa/subagents/host.py +272 -0
  609. puspa/subagents/lifecycle.py +551 -0
  610. puspa/subagents/limits.py +87 -0
  611. puspa/subagents/records.py +42 -0
  612. puspa/subagents/results.py +70 -0
  613. puspa/subagents/runner.py +92 -0
  614. puspa/subagents/states.py +50 -0
  615. puspa/subagents/toolsets.py +69 -0
  616. puspa/teams/__init__.py +110 -0
  617. puspa/teams/conversations.py +270 -0
  618. puspa/teams/errors.py +41 -0
  619. puspa/teams/runner.py +184 -0
  620. puspa/teams/schema.py +60 -0
  621. puspa/teams/teams.py +427 -0
  622. puspa/telemetry/__init__.py +35 -0
  623. puspa/telemetry/client.py +220 -0
  624. puspa/telemetry/config.py +125 -0
  625. puspa/telemetry/settings.py +108 -0
  626. puspa/tools/__init__.py +132 -0
  627. puspa/tools/approval.py +302 -0
  628. puspa/tools/browser.py +667 -0
  629. puspa/tools/builtin.py +115 -0
  630. puspa/tools/check.py +252 -0
  631. puspa/tools/footprint.py +121 -0
  632. puspa/tools/narrowing.py +644 -0
  633. puspa/tools/registry.py +533 -0
  634. puspa/tools/toolsets.py +256 -0
  635. puspa/turns/__init__.py +114 -0
  636. puspa/turns/budget.py +120 -0
  637. puspa/turns/config.py +119 -0
  638. puspa/turns/conflict_wiring.py +65 -0
  639. puspa/turns/intercepts.py +335 -0
  640. puspa/turns/interrupt.py +128 -0
  641. puspa/turns/loop.py +1330 -0
  642. puspa/turns/messages.py +822 -0
  643. puspa/turns/todos.py +77 -0
  644. puspa/turns/turn_api.py +458 -0
  645. puspa/turns/turn_api_error.py +150 -0
  646. puspa/turns/turn_overflow.py +86 -0
  647. puspa/turns/turn_prepare.py +60 -0
  648. puspa/turns/turn_recover.py +63 -0
  649. puspa/turns/turn_truncate.py +80 -0
  650. puspa/voice/__init__.py +57 -0
  651. puspa/voice/asr.py +124 -0
  652. puspa/voice/edge_tts.py +186 -0
  653. puspa/voice/pipeline.py +169 -0
  654. puspa/voice/transcriber.py +137 -0
  655. puspa/voice/tts.py +259 -0
  656. puspa/voice/wer.py +247 -0
  657. puspa/workflow/__init__.py +0 -0
  658. puspa/workflow/approvals.py +183 -0
  659. puspa/workflow/blocks.py +306 -0
  660. puspa/workflow/composer.py +294 -0
  661. puspa/workflow/manifest.py +86 -0
  662. puspa/workflow/metrics.py +57 -0
  663. puspa/workflow/panel.py +73 -0
  664. puspa/workflow/runner.py +928 -0
  665. puspa/workflow/schema.py +41 -0
  666. puspa/workflow/templates.py +140 -0
  667. puspa/workflow/triggers.py +176 -0
  668. puspa/world/__init__.py +171 -0
  669. puspa/world/agents.py +1047 -0
  670. puspa/world/beliefs.py +250 -0
  671. puspa/world/bitemporal.py +451 -0
  672. puspa/world/causal.py +615 -0
  673. puspa/world/ignorance.py +482 -0
  674. puspa/world/model.py +1395 -0
  675. puspa/world/noisy_simulator.py +221 -0
  676. puspa/world/planner.py +319 -0
  677. puspa/world/prediction_surprise.py +420 -0
  678. puspa/world/simulator.py +195 -0
  679. puspa/world/speeds.py +323 -0
  680. puspa/world/store.py +720 -0
  681. puspa-0.1.0.dist-info/METADATA +49 -0
  682. puspa-0.1.0.dist-info/RECORD +687 -0
  683. puspa-0.1.0.dist-info/WHEEL +5 -0
  684. puspa-0.1.0.dist-info/entry_points.txt +4 -0
  685. puspa-0.1.0.dist-info/licenses/LICENSE +201 -0
  686. puspa-0.1.0.dist-info/licenses/NOTICE.md +934 -0
  687. puspa-0.1.0.dist-info/top_level.txt +1 -0
puspa/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Paket Puspa — Fase 0 MVP."""
puspa/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Allow ``python -m puspa`` (the npm shim's fallback when the pip
2
+ console script is not on PATH)."""
3
+
4
+ from puspa.cli import main
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
@@ -0,0 +1,31 @@
1
+ """Public part of Puspa accounts: the local encrypted vault.
2
+
3
+ Split Step 1: the multi-user account code (``users.py``,
4
+ ``user_sessions.py``, ``access.py``, ``rls.py``) moved private with
5
+ the hosted accounts. What stays public is the vault only — per-user
6
+ connector tokens encrypted with a master key from the environment.
7
+ The session / user names (``create_session``, ``validate_session``,
8
+ ``create_user``, ``delete_user``, ``resolve_dsn`` and friends) move
9
+ to the SessionStore port in Step 3; they are deliberately NOT
10
+ re-exported here.
11
+ """
12
+
13
+ from .vault import VaultError
14
+ from .vault import delete as vault_delete
15
+ from .vault import derive_user_key as vault_derive_user_key
16
+ from .vault import get as vault_get
17
+ from .vault import list_names as vault_list_names
18
+ from .vault import put as vault_put
19
+ from .vault import rekey_all as vault_rekey_all
20
+ from .vault import rotate_entry as vault_rotate_entry
21
+
22
+ __all__ = [
23
+ "VaultError",
24
+ "vault_delete",
25
+ "vault_derive_user_key",
26
+ "vault_get",
27
+ "vault_list_names",
28
+ "vault_put",
29
+ "vault_rekey_all",
30
+ "vault_rotate_entry",
31
+ ]
@@ -0,0 +1,372 @@
1
+ """Local account ports: DSN resolution and the single-operator session store.
2
+
3
+ This module is the public side of the accounts boundary. It defines
4
+ the two ports the hosted service implements against its own user
5
+ registry and that the local install implements against its own
6
+ Postgres database:
7
+
8
+ - :func:`resolve_dsn` — the canonical DSN resolution (explicit
9
+ argument, then ``PUSPA_DSN`` / ``PUSPA_TEST_DSN``, then the local
10
+ peer-auth default). Every other ``resolve_dsn`` copy in the public
11
+ tree delegates to this one, so there is exactly one resolution
12
+ order to keep correct.
13
+ - the session store — :func:`create_user`, :func:`delete_user`,
14
+ :func:`create_session`, :func:`validate_session`,
15
+ :func:`list_sessions`, :func:`revoke_session`,
16
+ :func:`revoke_all_sessions`, :func:`register_agent`,
17
+ :func:`owner_of`, :func:`owner_of_token`,
18
+ :func:`create_agent_schema`, :func:`create_account_schema`.
19
+
20
+ The local implementations operate on Postgres through
21
+ :func:`resolve_dsn` (the same test database the rest of the suite
22
+ uses). The SQLite backend is a separate future workstream: when it
23
+ lands, these functions gain a SQLite implementation behind the same
24
+ names; nothing here pretends SQLite is live today.
25
+
26
+ Safety properties kept from the original implementation:
27
+
28
+ - Passwords are never stored raw, only as Argon2id hashes; email
29
+ is normalized (strip + lower) and unique.
30
+ - Only the SHA-256 of a session token is stored, never the token
31
+ itself, so a leaked sessions table yields no usable token.
32
+ - ``delete_user`` removes the user row, their sessions, and their
33
+ vault, but never touches the append-only ledger (``events``).
34
+ - ``register_agent`` is idempotent for the same owner and refuses
35
+ with :class:`AccessDeniedError` when an agent already belongs to
36
+ someone else, so an agent cannot be hijacked by re-registering it.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import hashlib
42
+ import os
43
+ import secrets
44
+
45
+ import psycopg
46
+ from argon2 import PasswordHasher
47
+ from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
48
+ from psycopg import errors as pg_errors
49
+
50
+ DEFAULT_DSN = "dbname=puspa_test user=root host=/var/run/postgresql"
51
+
52
+ __all__ = [
53
+ "DEFAULT_DSN",
54
+ "AccessDeniedError",
55
+ "AuthError",
56
+ "DuplicateEmailError",
57
+ "SessionError",
58
+ "authenticate",
59
+ "create_account_schema",
60
+ "create_agent_schema",
61
+ "create_session",
62
+ "create_user",
63
+ "delete_user",
64
+ "list_sessions",
65
+ "owner_of",
66
+ "owner_of_token",
67
+ "register_agent",
68
+ "resolve_dsn",
69
+ "revoke_all_sessions",
70
+ "revoke_session",
71
+ "revoke_session_by_id",
72
+ "validate_session",
73
+ ]
74
+
75
+
76
+ class AuthError(Exception):
77
+ """Unknown email or wrong password."""
78
+
79
+
80
+ class DuplicateEmailError(Exception):
81
+ """Email already registered."""
82
+
83
+
84
+ class SessionError(Exception):
85
+ """Session token invalid or revoked."""
86
+
87
+
88
+ class AccessDeniedError(Exception):
89
+ """Reader is not the owner of the data. Always used for ownership
90
+ refusals — never replaced with KeyError/SessionError, so callers
91
+ can tell "data exists but is not yours" from "data does not
92
+ exist"."""
93
+
94
+
95
+ _PASSWORD_HASHER = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)
96
+
97
+
98
+ def resolve_dsn(dsn: str | None = None) -> str:
99
+ """Postgres DSN: explicit argument, then env ``PUSPA_DSN`` /
100
+ ``PUSPA_TEST_DSN``, then the local peer-auth default."""
101
+ return dsn or os.environ.get("PUSPA_DSN") or os.environ.get("PUSPA_TEST_DSN") or DEFAULT_DSN
102
+
103
+
104
+ def _connect(dsn=None):
105
+ return psycopg.connect(resolve_dsn(dsn))
106
+
107
+
108
+ def _normalize_email(email):
109
+ if not isinstance(email, str):
110
+ raise ValueError("email must be a string")
111
+ return email.strip().lower()
112
+
113
+
114
+ def create_user(email, password, dsn=None):
115
+ """Create a user; return the user id (str UUID).
116
+
117
+ Raise DuplicateEmailError when the (normalized) email already
118
+ exists.
119
+ """
120
+ email_n = _normalize_email(email)
121
+ if not email_n:
122
+ raise ValueError("email is empty")
123
+ if not password:
124
+ raise ValueError("password is empty")
125
+ password_hash = _PASSWORD_HASHER.hash(password)
126
+ with _connect(dsn) as conn:
127
+ with conn.cursor() as cur:
128
+ try:
129
+ cur.execute(
130
+ "INSERT INTO users (email, password_hash) VALUES (%s, %s) RETURNING id",
131
+ (email_n, password_hash),
132
+ )
133
+ user_id = cur.fetchone()[0]
134
+ except pg_errors.UniqueViolation as err:
135
+ raise DuplicateEmailError(f"email already registered: {email_n}") from err
136
+ conn.commit()
137
+ return str(user_id)
138
+
139
+
140
+ def authenticate(email, password, dsn=None):
141
+ """Check email + password; return the user id (str UUID).
142
+
143
+ Raise AuthError for an unknown email or a wrong password. The
144
+ message is deliberately the same for both, so it never leaks
145
+ which one was wrong.
146
+ """
147
+ email_n = _normalize_email(email)
148
+ with _connect(dsn) as conn, conn.cursor() as cur:
149
+ cur.execute(
150
+ "SELECT id, password_hash FROM users WHERE email = %s",
151
+ (email_n,),
152
+ )
153
+ row = cur.fetchone()
154
+ if row is None:
155
+ raise AuthError("email or password is wrong")
156
+ user_id, password_hash = row
157
+ try:
158
+ _PASSWORD_HASHER.verify(password_hash, password)
159
+ except (VerifyMismatchError, VerificationError, InvalidHash) as err:
160
+ raise AuthError("email or password is wrong") from err
161
+ return str(user_id)
162
+
163
+
164
+ def delete_user(user_id, dsn=None):
165
+ """Delete a user: the user row + all sessions + the whole vault.
166
+
167
+ Ledger events are NOT deleted (append-only audit) — the
168
+ ``events`` table is never touched here.
169
+ """
170
+ with _connect(dsn) as conn:
171
+ with conn.cursor() as cur:
172
+ cur.execute("DELETE FROM vault WHERE user_id = %s", (user_id,))
173
+ cur.execute("DELETE FROM sessions WHERE user_id = %s", (user_id,))
174
+ cur.execute("DELETE FROM users WHERE id = %s", (user_id,))
175
+ conn.commit()
176
+
177
+
178
+ def _token_hash(token):
179
+ return hashlib.sha256(token.encode()).hexdigest()
180
+
181
+
182
+ def create_session(user_id, device_label, dsn=None):
183
+ """Create a session for a user; return the raw token (str).
184
+
185
+ The raw token is returned exactly once here — the caller must
186
+ store it safely; the database only keeps its hash.
187
+ """
188
+ token = secrets.token_urlsafe(32)
189
+ with _connect(dsn) as conn:
190
+ with conn.cursor() as cur:
191
+ cur.execute(
192
+ "INSERT INTO sessions (user_id, token_hash, device_label) VALUES (%s, %s, %s)",
193
+ (user_id, _token_hash(token), device_label),
194
+ )
195
+ conn.commit()
196
+ return token
197
+
198
+
199
+ def validate_session(token, dsn=None):
200
+ """Check a token; return the user id (str UUID) while it is valid.
201
+
202
+ Raise SessionError when the token is unknown or revoked. A
203
+ session that validates successfully refreshes ``last_seen_at``.
204
+ """
205
+ token_h = _token_hash(token)
206
+ with _connect(dsn) as conn:
207
+ with conn.cursor() as cur:
208
+ cur.execute(
209
+ "SELECT user_id FROM sessions WHERE token_hash = %s AND NOT revoked",
210
+ (token_h,),
211
+ )
212
+ row = cur.fetchone()
213
+ if row is None:
214
+ raise SessionError("session is invalid or revoked")
215
+ cur.execute(
216
+ "UPDATE sessions SET last_seen_at = now() WHERE token_hash = %s",
217
+ (token_h,),
218
+ )
219
+ conn.commit()
220
+ return str(row[0])
221
+
222
+
223
+ def owner_of_token(token, dsn=None):
224
+ """Return the user id owning a token, WITHOUT side effects.
225
+
226
+ Same as :func:`validate_session` but does NOT refresh
227
+ ``last_seen_at``: use this for ownership checks, so a token
228
+ presented by the wrong user leaves no trace on the owner's
229
+ session. Raise SessionError when the token is unknown or
230
+ revoked.
231
+ """
232
+ token_h = _token_hash(token)
233
+ with _connect(dsn) as conn, conn.cursor() as cur:
234
+ cur.execute(
235
+ "SELECT user_id FROM sessions WHERE token_hash = %s AND NOT revoked",
236
+ (token_h,),
237
+ )
238
+ row = cur.fetchone()
239
+ if row is None:
240
+ raise SessionError("session is invalid or revoked")
241
+ return str(row[0])
242
+
243
+
244
+ def revoke_session(token, dsn=None):
245
+ """Revoke one session (log out that device). Idempotent."""
246
+ with _connect(dsn) as conn:
247
+ with conn.cursor() as cur:
248
+ cur.execute(
249
+ "UPDATE sessions SET revoked = true WHERE token_hash = %s",
250
+ (_token_hash(token),),
251
+ )
252
+ conn.commit()
253
+
254
+
255
+ def revoke_session_by_id(session_id, user_id, dsn=None):
256
+ """Revoke one session by its row id. Returns True when a
257
+ session of this user was revoked, False when no such session
258
+ exists. An unknown id and another user's id read the same
259
+ (False), so one user's ids cannot probe another user's
260
+ sessions. Idempotent: revoking an already-revoked session
261
+ still returns True. A malformed id raises the database's
262
+ error, which the caller maps to "no such session"."""
263
+ with _connect(dsn) as conn:
264
+ with conn.cursor() as cur:
265
+ cur.execute(
266
+ "UPDATE sessions SET revoked = true WHERE id = %s AND user_id = %s",
267
+ (session_id, user_id),
268
+ )
269
+ revoked = cur.rowcount > 0
270
+ conn.commit()
271
+ return revoked
272
+
273
+
274
+ def revoke_all_sessions(user_id, dsn=None):
275
+ """Revoke all sessions of a user (log out every device)."""
276
+ with _connect(dsn) as conn:
277
+ with conn.cursor() as cur:
278
+ cur.execute(
279
+ "UPDATE sessions SET revoked = true WHERE user_id = %s",
280
+ (user_id,),
281
+ )
282
+ conn.commit()
283
+
284
+
285
+ def list_sessions(user_id, dsn=None):
286
+ """List all sessions of a user (revoked ones included, with the
287
+ ``revoked`` flag), newest first."""
288
+ with _connect(dsn) as conn, conn.cursor() as cur:
289
+ cur.execute(
290
+ "SELECT id, device_label, created_at, last_seen_at, revoked "
291
+ "FROM sessions WHERE user_id = %s ORDER BY created_at DESC",
292
+ (user_id,),
293
+ )
294
+ rows = cur.fetchall()
295
+ return [
296
+ {
297
+ "id": str(r[0]),
298
+ "device_label": r[1],
299
+ "created_at": r[2],
300
+ "last_seen_at": r[3],
301
+ "revoked": r[4],
302
+ }
303
+ for r in rows
304
+ ]
305
+
306
+
307
+ def create_agent_schema(dsn=None):
308
+ """Apply the agent registry table (migration 0001_core).
309
+
310
+ The ``agents`` table comes from the migration, not from a schema
311
+ file. Idempotent; safe to call before every test.
312
+ """
313
+ from puspa.migrations import apply_migrations
314
+
315
+ apply_migrations(resolve_dsn(dsn), target="0001")
316
+
317
+
318
+ def create_account_schema(dsn=None):
319
+ """Apply the account tables (migration 0001_core).
320
+
321
+ The tables (users, sessions, vault, agents) come from the
322
+ migration, not from a schema file. Idempotent; safe to call
323
+ before every test.
324
+ """
325
+ from puspa.migrations import apply_migrations
326
+
327
+ apply_migrations(resolve_dsn(dsn), target="0001")
328
+
329
+
330
+ def register_agent(agent_id, user_id, dsn=None):
331
+ """Register an agent to its owner. Idempotent when the agent is
332
+ already registered to the same user.
333
+
334
+ Raise AccessDeniedError when the agent id is already registered
335
+ to a DIFFERENT user (an agent cannot be hijacked or moved by
336
+ re-registering it). Raise ValueError for an empty agent_id or
337
+ user_id.
338
+ """
339
+ if not isinstance(agent_id, str) or not agent_id.strip():
340
+ raise ValueError("agent_id must be a non-empty string")
341
+ if not isinstance(user_id, str) or not user_id.strip():
342
+ raise ValueError("user_id must be a non-empty string")
343
+ agent_id = agent_id.strip()
344
+ user_id = user_id.strip()
345
+ with psycopg.connect(resolve_dsn(dsn)) as conn:
346
+ with conn.cursor() as cur:
347
+ cur.execute("SELECT user_id FROM agents WHERE agent_id = %s", (agent_id,))
348
+ row = cur.fetchone()
349
+ if row is not None:
350
+ if str(row[0]) != user_id:
351
+ raise AccessDeniedError(
352
+ f"agent {agent_id!r} is already registered to another user"
353
+ )
354
+ return # already registered to the same owner: no-op
355
+ cur.execute(
356
+ "INSERT INTO agents (agent_id, user_id) VALUES (%s, %s)",
357
+ (agent_id, user_id),
358
+ )
359
+ conn.commit()
360
+
361
+
362
+ def owner_of(agent_id, dsn=None):
363
+ """Return the user id (str UUID) owning an agent, or None when
364
+ the agent is not registered. None means the owner is unknown,
365
+ which owned readers treat as fail-closed (never as owned by
366
+ anyone)."""
367
+ if not isinstance(agent_id, str) or not agent_id.strip():
368
+ return None
369
+ with psycopg.connect(resolve_dsn(dsn)) as conn, conn.cursor() as cur:
370
+ cur.execute("SELECT user_id FROM agents WHERE agent_id = %s", (agent_id.strip(),))
371
+ row = cur.fetchone()
372
+ return str(row[0]) if row is not None else None