openpond 0.2.56 → 0.2.58

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 (73) hide show
  1. package/dist/app-server.d.ts +1 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-server-evaluations-GJPFWIDA.js → app-server-evaluations-K52NAQLP.js} +1 -1
  4. package/dist/chunks/{app-server-harness-services-IH4G6POY.js → app-server-harness-services-QMUOEYOA.js} +1 -1
  5. package/dist/chunks/{app-server-runtime-DVKOZ5B6.js → app-server-runtime-ISGGLQHU.js} +1 -1
  6. package/dist/chunks/{chunk-XTFPDQMH.js → chunk-4EQA2M7K.js} +1 -1
  7. package/dist/chunks/chunk-5IPFI25K.js +2 -0
  8. package/dist/chunks/{chunk-3K4VVB7S.js → chunk-65PL62KH.js} +1 -1
  9. package/dist/chunks/{chunk-OGDADQGH.js → chunk-6UDGARFC.js} +1 -1
  10. package/dist/chunks/{chunk-2QUCCP6Z.js → chunk-7SC46OFC.js} +1 -1
  11. package/dist/chunks/{chunk-L6K7ERG5.js → chunk-APB4O67E.js} +1 -1
  12. package/dist/chunks/{chunk-S5ESN275.js → chunk-H4QHIHMK.js} +1 -1
  13. package/dist/chunks/{chunk-PPAPVGJP.js → chunk-HDGTHRY7.js} +1 -1
  14. package/dist/chunks/{chunk-XXYGGNVM.js → chunk-HPBQ4VTW.js} +1 -1
  15. package/dist/chunks/{chunk-FY5KHLMW.js → chunk-I3HZKJB3.js} +1 -1
  16. package/dist/chunks/{chunk-QHWGQ3A4.js → chunk-I3VVWNUW.js} +1 -1
  17. package/dist/chunks/{chunk-KUERKVEU.js → chunk-IIZ4CWBX.js} +1 -1
  18. package/dist/chunks/{chunk-SH5CBAFC.js → chunk-JAJ46T5X.js} +1 -1
  19. package/dist/chunks/{chunk-QEFHOJFE.js → chunk-JE7RJZOA.js} +1 -1
  20. package/dist/chunks/{chunk-GWCHDF2C.js → chunk-JUHZ5S3R.js} +1 -1
  21. package/dist/chunks/{chunk-PUZQU66L.js → chunk-L3KCP52O.js} +1 -1
  22. package/dist/chunks/{chunk-EQFGBL3O.js → chunk-NC27T4AB.js} +1 -1
  23. package/dist/chunks/{chunk-7HPDGZOR.js → chunk-NH6UUX5S.js} +1 -1
  24. package/dist/chunks/{chunk-QOTVNQDI.js → chunk-QL4OIPEZ.js} +1 -1
  25. package/dist/chunks/{chunk-ZFSHBFG5.js → chunk-RNQF63ZR.js} +1 -1
  26. package/dist/chunks/chunk-ROGF26KV.js +2 -0
  27. package/dist/chunks/{chunk-HDL5YSAA.js → chunk-RWWE5OXU.js} +1 -1
  28. package/dist/chunks/{chunk-YOBN7KTF.js → chunk-TJ6GVTYB.js} +1 -1
  29. package/dist/chunks/{chunk-3RCRSMWZ.js → chunk-TTVS6JMC.js} +1 -1
  30. package/dist/chunks/{chunk-WMKYHXVM.js → chunk-VVCKLCF3.js} +1 -1
  31. package/dist/chunks/{chunk-OIUTWU6K.js → chunk-X2HIHF2I.js} +1 -1
  32. package/dist/chunks/{chunk-J2TWKFML.js → chunk-XX6SMFDY.js} +4 -4
  33. package/dist/chunks/{chunk-GZ7M5XBP.js → chunk-YNH3NMPF.js} +1 -1
  34. package/dist/chunks/{chunk-YCJO3YVD.js → chunk-ZTNHW2K7.js} +3 -3
  35. package/dist/chunks/{cli-X25RSO2X.js → cli-XZENDZ7Z.js} +1 -1
  36. package/dist/chunks/{connected-app-executor-IVLGQP65.js → connected-app-executor-LQNIU5NR.js} +1 -1
  37. package/dist/chunks/host-profile-evaluation-tools-JOFBL5OF.js +2 -0
  38. package/dist/chunks/{hosted-app-server-composition-BCOO5ANF.js → hosted-app-server-composition-T5IWGOTA.js} +1 -1
  39. package/dist/chunks/{hosted-experiment-improvement-NFSVS5TU.js → hosted-experiment-improvement-HVMDGS75.js} +1 -1
  40. package/dist/chunks/{hosted-harness-runtime-723S5ZSH.js → hosted-harness-runtime-YCKB6NBI.js} +1 -1
  41. package/dist/chunks/{hosted-profile-candidate-2S5LFUWD.js → hosted-profile-candidate-EXNN6MVN.js} +1 -1
  42. package/dist/chunks/{hosted-profile-compiler-2DQIFSXW.js → hosted-profile-compiler-IYLLHCRY.js} +1 -1
  43. package/dist/chunks/{hosted-profile-evaluation-control-76BTRTYD.js → hosted-profile-evaluation-control-TJVER3NW.js} +1 -1
  44. package/dist/chunks/{hosted-profile-evaluation-inspection-V6Z3A5XJ.js → hosted-profile-evaluation-inspection-ZUANDYZ6.js} +1 -1
  45. package/dist/chunks/{hosted-profile-evaluation-preparation-IDJYREW3.js → hosted-profile-evaluation-preparation-ORVZ6MBD.js} +1 -1
  46. package/dist/chunks/{local-harness-improvement-runtime-JIQ6ZVDW.js → local-harness-improvement-runtime-QRFGPFRM.js} +1 -1
  47. package/dist/chunks/{local-harness-taskset-review-XVYTGAGK.js → local-harness-taskset-review-HR7KLY4B.js} +1 -1
  48. package/dist/chunks/{project-action-payload-7VGL7OER.js → project-action-payload-JDS6OQAW.js} +1 -1
  49. package/dist/chunks/{published-experiment-source-DZFENAQA.js → published-experiment-source-HVP5IGRH.js} +1 -1
  50. package/dist/chunks/{refiner-profile-service-UUIWFJVT.js → refiner-profile-service-FDTQKY33.js} +1 -1
  51. package/dist/chunks/{saved-work-6BMBFP43.js → saved-work-SHEEDZ6Z.js} +1 -1
  52. package/dist/chunks/{src-LMC3K6LH.js → src-DZL5T2MT.js} +1 -1
  53. package/dist/chunks/{src-CJM6HY5Y.js → src-R36AGJY7.js} +103 -103
  54. package/dist/chunks/{store-continual-support-reviews-HHA6NX7K.js → store-continual-support-reviews-LJPNG4SP.js} +1 -1
  55. package/dist/chunks/{store-create-improve-QV54XIZW.js → store-create-improve-SW5FTBTL.js} +1 -1
  56. package/dist/chunks/{store-datasets-RXJ33SUN.js → store-datasets-WMA7AJKN.js} +1 -1
  57. package/dist/chunks/{store-evaluation-results-3F3P527G.js → store-evaluation-results-ZO6R653G.js} +1 -1
  58. package/dist/chunks/{store-human-review-RAH7WMIP.js → store-human-review-7QQ7ZQ6P.js} +1 -1
  59. package/dist/chunks/{store-learned-preference-migration-validation-4CI2IRUF.js → store-learned-preference-migration-validation-NADPXOTG.js} +1 -1
  60. package/dist/chunks/{store-local-experiments-5LUJR7GI.js → store-local-experiments-SAULQSBN.js} +1 -1
  61. package/dist/chunks/{store-model-batch-review-YEGX327M.js → store-model-batch-review-VKLDYGH3.js} +1 -1
  62. package/dist/chunks/{store-model-configuration-5ZURQATB.js → store-model-configuration-BYRJUR3C.js} +1 -1
  63. package/dist/chunks/{store-task-inbox-JJTBW76C.js → store-task-inbox-QPE44OSS.js} +11 -11
  64. package/dist/chunks/{store-task-inventory-OB3F2APC.js → store-task-inventory-I3RDRI52.js} +1 -1
  65. package/dist/chunks/{store-taskset-drafts-EKQWWFYQ.js → store-taskset-drafts-2IULRV2W.js} +1 -1
  66. package/dist/chunks/{store-training-G6YLFSIR.js → store-training-B2TW2MLA.js} +1 -1
  67. package/dist/chunks/{store-training-jobs-RC46YBF6.js → store-training-jobs-VBNG23RL.js} +1 -1
  68. package/dist/chunks/{store-training-models-6BA43IPP.js → store-training-models-OMV5FIC4.js} +1 -1
  69. package/dist/cli.js +1 -1
  70. package/package.json +1 -1
  71. package/dist/chunks/chunk-UHFZHBGW.js +0 -2
  72. package/dist/chunks/chunk-YY7LEQGP.js +0 -2
  73. package/dist/chunks/host-profile-evaluation-tools-JJQWJUBT.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{A as t,z as s}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as r}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var d=class extends r{static{n(this,"SqliteContinualBenchReviewStore")}async saveContinualLearningDailyBatch(i){let e=s.parse(i),a=await this.getContinualLearningDailyBatch(e.id);if(a&&(a.seriesId!==e.seriesId||a.scheduleEntryId!==e.scheduleEntryId||a.dayOrdinal!==e.dayOrdinal||JSON.stringify(a.sourceTaskset)!==JSON.stringify(e.sourceTaskset)||e.revision!==a.revision+1)){if(JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("A daily learning batch update must preserve its intake identity and use the next revision.")}return await this.upsertPayload(`INSERT INTO continual_learning_daily_batches
2
+ import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{A as t,z as s}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as r}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var d=class extends r{static{n(this,"SqliteContinualBenchReviewStore")}async saveContinualLearningDailyBatch(i){let e=s.parse(i),a=await this.getContinualLearningDailyBatch(e.id);if(a&&(a.seriesId!==e.seriesId||a.scheduleEntryId!==e.scheduleEntryId||a.dayOrdinal!==e.dayOrdinal||JSON.stringify(a.sourceTaskset)!==JSON.stringify(e.sourceTaskset)||e.revision!==a.revision+1)){if(JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("A daily learning batch update must preserve its intake identity and use the next revision.")}return await this.upsertPayload(`INSERT INTO continual_learning_daily_batches
3
3
  (id, series_id, schedule_entry_id, day_ordinal, status, revision, payload, created_at, updated_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  ON CONFLICT(id) DO UPDATE SET status = excluded.status, revision = excluded.revision, payload = excluded.payload, updated_at = excluded.updated_at`,[e.id,e.seriesId,e.scheduleEntryId,e.dayOrdinal,e.status,e.revision,JSON.stringify(e),e.createdAt,e.updatedAt]),e}async getContinualLearningDailyBatch(i){return this.getParsedPayload("SELECT payload FROM continual_learning_daily_batches WHERE id = ?",[i],s.parse)}async listContinualLearningDailyBatches(i={}){return i.seriesId?this.listParsedPayloads("SELECT payload FROM continual_learning_daily_batches WHERE series_id = ? ORDER BY day_ordinal ASC",[i.seriesId],s.parse):this.listParsedPayloads("SELECT payload FROM continual_learning_daily_batches ORDER BY series_id, day_ordinal ASC",[],s.parse)}async saveContinualBenchIssueReview(i){let e=t.parse(i),a=await this.getContinualBenchIssueReview(e.id);if(a&&(a.seriesId!==e.seriesId||a.passLabel!==e.passLabel||a.packet.contentHash!==e.packet.contentHash||e.revision!==a.revision+1)){if(JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("A Continual Support review update must preserve its sealed packet and use the next revision.")}return await this.upsertPayload(`INSERT INTO continual_bench_issue_reviews (id, series_id, pass_label, status, revision, payload, created_at, updated_at)
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import{h as d}from"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as c}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as p}from"./chunk-FTQLQJQV.js";var l=class extends c{static{p(this,"SqliteCreateImproveStore")}async getCreateImproveRun(e){await this.ready,await this.writeQueue;let t=await this.get("SELECT payload FROM create_improve_runs WHERE id = ?",[e]);return t?d.parse(JSON.parse(t.payload)):null}async listCreateImproveRuns(e={}){await this.ready,await this.writeQueue;let t=[],a=[];e.profileId&&(t.push("profile_id = ?"),a.push(e.profileId)),e.conversationId&&(t.push("conversation_id = ?"),a.push(e.conversationId)),e.targetKind&&(t.push("target_kind = ?"),a.push(e.targetKind)),e.targetId&&(t.push("target_id = ?"),a.push(e.targetId));let o=Array.isArray(e.state)?e.state:e.state?[e.state]:[];o.length>0&&(t.push(`state IN (${o.map(()=>"?").join(", ")})`),a.push(...o));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250)));return a.push(s),(await this.all(`SELECT payload
2
+ import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import{h as d}from"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as c}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as p}from"./chunk-FTQLQJQV.js";var l=class extends c{static{p(this,"SqliteCreateImproveStore")}async getCreateImproveRun(e){await this.ready,await this.writeQueue;let t=await this.get("SELECT payload FROM create_improve_runs WHERE id = ?",[e]);return t?d.parse(JSON.parse(t.payload)):null}async listCreateImproveRuns(e={}){await this.ready,await this.writeQueue;let t=[],a=[];e.profileId&&(t.push("profile_id = ?"),a.push(e.profileId)),e.conversationId&&(t.push("conversation_id = ?"),a.push(e.conversationId)),e.targetKind&&(t.push("target_kind = ?"),a.push(e.targetKind)),e.targetId&&(t.push("target_id = ?"),a.push(e.targetId));let o=Array.isArray(e.state)?e.state:e.state?[e.state]:[];o.length>0&&(t.push(`state IN (${o.map(()=>"?").join(", ")})`),a.push(...o));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250)));return a.push(s),(await this.all(`SELECT payload
3
3
  FROM create_improve_runs
4
4
  ${t.length>0?`WHERE ${t.join(" AND ")}`:""}
5
5
  ORDER BY updated_at DESC
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{d as l}from"./chunk-KG325WTN.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{d as i}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as u}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{o as r,w as o}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var c=class extends u{static{n(this,"SqliteDatasetStore")}async listDatasetCatalogTasksets(e){return await this.ready,await this.writeQueue,(await this.all(`SELECT
2
+ import{d as l}from"./chunk-KG325WTN.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{d as i}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as u}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{o as r,w as o}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var c=class extends u{static{n(this,"SqliteDatasetStore")}async listDatasetCatalogTasksets(e){return await this.ready,await this.writeQueue,(await this.all(`SELECT
3
3
  id AS taskset_id,
4
4
  CAST(json_extract(payload, '$.revision') AS INTEGER) AS taskset_revision,
5
5
  json_extract(payload, '$.datasetArtifact.id') AS artifact_id,
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as m}from"./chunk-O6ULLQJ6.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import{o as f}from"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as k}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import{Hb as E,Ib as O,O as v,Ob as h,Pb as C,Q as y,f as R,h as p,m as H}from"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import{C as _,w as P}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as s,n as c}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as g}from"./chunk-FTQLQJQV.js";var w=class extends k{static{g(this,"SqliteEvaluationResultStore")}async saveProfileEvaluationGrade(a){let e=P.parse(a);c(e,"Profile evaluation grade");let n=await this.getProfileEvaluationGrade(e.contentHash);return n||(await this.upsertPayload("INSERT INTO profile_evaluation_grades (content_hash, payload) VALUES (?, ?) ON CONFLICT(content_hash) DO NOTHING",[e.contentHash,JSON.stringify(e)]),e)}async getProfileEvaluationGrade(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_grades WHERE content_hash = ?",[a],P.parse)}async saveProfileEvaluationReceipt(a){let e=R.parse(a);H(e);let n=await this.getProfileEvaluationReceipt(e.id);if(n){if(n.contentHash!==e.contentHash)throw new Error(`Profile evaluation receipt ${e.id} is immutable.`);return n}return await this.upsertPayload("INSERT INTO profile_evaluation_receipts (id, run_id, payload) VALUES (?, ?, ?)",[e.id,e.runManifest.id,JSON.stringify(e)]),e}async getProfileEvaluationReceipt(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_receipts WHERE id = ?",[a],R.parse)}async saveProfileEvaluationRun(a){let e=m.parse(a);c(e,"Profile evaluation run"),c(e.manifest,"Profile evaluation run manifest"),_(e.metric);let n=e.manifest.profileEvaluation;if(!n||n.profileId!==e.profileRef.profileId||e.metric.runManifest.id!==e.manifest.id||e.metric.runManifest.contentHash!==e.manifest.contentHash||s(e.receiptRefs)!==s(e.metric.receiptRefs))throw new Error("Profile evaluation run differs from its manifest or metric receipts.");if(e.receiptRefs.length!==e.manifest.population.length||e.gradeRefs.length!==e.receiptRefs.length)throw new Error("Profile evaluation run has an incomplete receipt or grade population.");for(let[t,u]of e.manifest.population.entries()){let d=e.receiptRefs[t],r=await this.getProfileEvaluationReceipt(d.id);if(!r||r.contentHash!==d.contentHash||r.runManifest.id!==e.manifest.id||r.runManifest.contentHash!==e.manifest.contentHash||r.id!==u.receiptId||r.taskId!==u.taskId||r.seed!==u.seed)throw new Error("Profile evaluation run references a missing or mismatched receipt.");let l=e.gradeRefs[t],o=await this.getProfileEvaluationGrade(l.contentHash);if(!o||o.contentHash!==l.contentHash||!r.graderEvidenceRefs.some(S=>S.id===l.id&&S.contentHash===l.contentHash))throw new Error("Profile evaluation run references a missing or mismatched grade.")}let i=await this.getProfileEvaluationRun(e.manifest.id);if(i){if(i.contentHash!==e.contentHash)throw new Error(`Profile evaluation run ${e.manifest.id} is immutable.`);return i}return await this.upsertPayload("INSERT INTO profile_evaluation_runs (id, profile_key, taskset_id, payload, created_at) VALUES (?, ?, ?, ?, ?)",[e.manifest.id,s(e.profileRef),e.manifest.tasksetRelease.id,JSON.stringify(e),e.completedAt]),e}async getProfileEvaluationRun(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_runs WHERE id = ?",[a],m.parse)}async listProfileEvaluationRuns(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_runs WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],m.parse)}async saveProfileEvaluationComparison(a,e){let n=f.parse(a),i=E.parse(e);c(i,"Profile evaluation comparison");let t=[];for(let d of i.members){let r=await this.getProfileEvaluationRun(d.runManifest.id);if(!r||s(r.profileRef)!==s(n)||r.manifest.contentHash!==d.runManifest.contentHash||r.metric.contentHash!==d.metricResultHash)throw new Error("Profile evaluation comparison references a missing or mismatched run.");t.push({manifest:r.manifest,result:r.metric})}if(O({id:i.id,members:t,createdAt:i.createdAt}).contentHash!==i.contentHash)throw new Error("Profile evaluation comparison differs from retained run evidence.");let u=await this.getProfileEvaluationComparison(i.id);if(u){if(u.contentHash!==i.contentHash)throw new Error(`Profile evaluation comparison ${i.id} is immutable.`);return u}return await this.upsertPayload("INSERT INTO profile_evaluation_comparisons (id, profile_key, payload, created_at) VALUES (?, ?, ?, ?)",[i.id,s(n),JSON.stringify(i),i.createdAt]),i}async getProfileEvaluationComparison(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_comparisons WHERE id = ?",[a],E.parse)}async listProfileEvaluationComparisons(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_comparisons WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],E.parse)}async saveProfileEvaluationSuiteRun(a,e,n){let i=f.parse(a),t=h.parse(n);c(t,"Profile evaluation suite run");let u=[];for(let l of t.members){let o=await this.getProfileEvaluationRun(l.runManifest.id);if(!o||s(o.profileRef)!==s(i)||o.manifest.contentHash!==l.runManifest.contentHash||o.contentHash!==l.runHash||o.passed!==l.passed||o.metric.value!==l.score)throw new Error("Profile evaluation suite references a missing or mismatched run.");u.push({definitionId:l.definitionId,manifest:o.manifest,runHash:o.contentHash,passed:o.passed,score:o.metric.value})}if(C({id:t.id,suiteId:t.suiteId,catalog:e,members:u,createdAt:t.createdAt,completedAt:t.completedAt}).contentHash!==t.contentHash)throw new Error("Profile evaluation suite differs from retained run evidence.");let r=await this.getProfileEvaluationSuiteRun(t.id);if(r){if(r.contentHash!==t.contentHash)throw new Error(`Profile evaluation suite run ${t.id} is immutable.`);return r}return await this.upsertPayload("INSERT INTO profile_evaluation_suite_runs (id, profile_key, payload, created_at) VALUES (?, ?, ?, ?)",[t.id,s(i),JSON.stringify(t),t.createdAt]),t}async getProfileEvaluationSuiteRun(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_suite_runs WHERE id = ?",[a],h.parse)}async listProfileEvaluationSuiteRuns(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_suite_runs WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],h.parse)}async saveBenchmarkRun(a){let e=v.parse(a.run);return c(e,"Benchmark run"),await this.upsertPayload(`INSERT INTO benchmark_runs (id, taskset_id, phase, payload, created_at)
2
+ import{a as m}from"./chunk-O6ULLQJ6.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import{o as f}from"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as k}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import{Hb as E,Ib as O,O as v,Ob as h,Pb as C,Q as y,f as R,h as p,m as H}from"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import{C as _,w as P}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as s,n as c}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as g}from"./chunk-FTQLQJQV.js";var w=class extends k{static{g(this,"SqliteEvaluationResultStore")}async saveProfileEvaluationGrade(a){let e=P.parse(a);c(e,"Profile evaluation grade");let n=await this.getProfileEvaluationGrade(e.contentHash);return n||(await this.upsertPayload("INSERT INTO profile_evaluation_grades (content_hash, payload) VALUES (?, ?) ON CONFLICT(content_hash) DO NOTHING",[e.contentHash,JSON.stringify(e)]),e)}async getProfileEvaluationGrade(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_grades WHERE content_hash = ?",[a],P.parse)}async saveProfileEvaluationReceipt(a){let e=R.parse(a);H(e);let n=await this.getProfileEvaluationReceipt(e.id);if(n){if(n.contentHash!==e.contentHash)throw new Error(`Profile evaluation receipt ${e.id} is immutable.`);return n}return await this.upsertPayload("INSERT INTO profile_evaluation_receipts (id, run_id, payload) VALUES (?, ?, ?)",[e.id,e.runManifest.id,JSON.stringify(e)]),e}async getProfileEvaluationReceipt(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_receipts WHERE id = ?",[a],R.parse)}async saveProfileEvaluationRun(a){let e=m.parse(a);c(e,"Profile evaluation run"),c(e.manifest,"Profile evaluation run manifest"),_(e.metric);let n=e.manifest.profileEvaluation;if(!n||n.profileId!==e.profileRef.profileId||e.metric.runManifest.id!==e.manifest.id||e.metric.runManifest.contentHash!==e.manifest.contentHash||s(e.receiptRefs)!==s(e.metric.receiptRefs))throw new Error("Profile evaluation run differs from its manifest or metric receipts.");if(e.receiptRefs.length!==e.manifest.population.length||e.gradeRefs.length!==e.receiptRefs.length)throw new Error("Profile evaluation run has an incomplete receipt or grade population.");for(let[t,u]of e.manifest.population.entries()){let d=e.receiptRefs[t],r=await this.getProfileEvaluationReceipt(d.id);if(!r||r.contentHash!==d.contentHash||r.runManifest.id!==e.manifest.id||r.runManifest.contentHash!==e.manifest.contentHash||r.id!==u.receiptId||r.taskId!==u.taskId||r.seed!==u.seed)throw new Error("Profile evaluation run references a missing or mismatched receipt.");let l=e.gradeRefs[t],o=await this.getProfileEvaluationGrade(l.contentHash);if(!o||o.contentHash!==l.contentHash||!r.graderEvidenceRefs.some(S=>S.id===l.id&&S.contentHash===l.contentHash))throw new Error("Profile evaluation run references a missing or mismatched grade.")}let i=await this.getProfileEvaluationRun(e.manifest.id);if(i){if(i.contentHash!==e.contentHash)throw new Error(`Profile evaluation run ${e.manifest.id} is immutable.`);return i}return await this.upsertPayload("INSERT INTO profile_evaluation_runs (id, profile_key, taskset_id, payload, created_at) VALUES (?, ?, ?, ?, ?)",[e.manifest.id,s(e.profileRef),e.manifest.tasksetRelease.id,JSON.stringify(e),e.completedAt]),e}async getProfileEvaluationRun(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_runs WHERE id = ?",[a],m.parse)}async listProfileEvaluationRuns(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_runs WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],m.parse)}async saveProfileEvaluationComparison(a,e){let n=f.parse(a),i=E.parse(e);c(i,"Profile evaluation comparison");let t=[];for(let d of i.members){let r=await this.getProfileEvaluationRun(d.runManifest.id);if(!r||s(r.profileRef)!==s(n)||r.manifest.contentHash!==d.runManifest.contentHash||r.metric.contentHash!==d.metricResultHash)throw new Error("Profile evaluation comparison references a missing or mismatched run.");t.push({manifest:r.manifest,result:r.metric})}if(O({id:i.id,members:t,createdAt:i.createdAt}).contentHash!==i.contentHash)throw new Error("Profile evaluation comparison differs from retained run evidence.");let u=await this.getProfileEvaluationComparison(i.id);if(u){if(u.contentHash!==i.contentHash)throw new Error(`Profile evaluation comparison ${i.id} is immutable.`);return u}return await this.upsertPayload("INSERT INTO profile_evaluation_comparisons (id, profile_key, payload, created_at) VALUES (?, ?, ?, ?)",[i.id,s(n),JSON.stringify(i),i.createdAt]),i}async getProfileEvaluationComparison(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_comparisons WHERE id = ?",[a],E.parse)}async listProfileEvaluationComparisons(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_comparisons WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],E.parse)}async saveProfileEvaluationSuiteRun(a,e,n){let i=f.parse(a),t=h.parse(n);c(t,"Profile evaluation suite run");let u=[];for(let l of t.members){let o=await this.getProfileEvaluationRun(l.runManifest.id);if(!o||s(o.profileRef)!==s(i)||o.manifest.contentHash!==l.runManifest.contentHash||o.contentHash!==l.runHash||o.passed!==l.passed||o.metric.value!==l.score)throw new Error("Profile evaluation suite references a missing or mismatched run.");u.push({definitionId:l.definitionId,manifest:o.manifest,runHash:o.contentHash,passed:o.passed,score:o.metric.value})}if(C({id:t.id,suiteId:t.suiteId,catalog:e,members:u,createdAt:t.createdAt,completedAt:t.completedAt}).contentHash!==t.contentHash)throw new Error("Profile evaluation suite differs from retained run evidence.");let r=await this.getProfileEvaluationSuiteRun(t.id);if(r){if(r.contentHash!==t.contentHash)throw new Error(`Profile evaluation suite run ${t.id} is immutable.`);return r}return await this.upsertPayload("INSERT INTO profile_evaluation_suite_runs (id, profile_key, payload, created_at) VALUES (?, ?, ?, ?)",[t.id,s(i),JSON.stringify(t),t.createdAt]),t}async getProfileEvaluationSuiteRun(a){return this.getParsedPayload("SELECT payload FROM profile_evaluation_suite_runs WHERE id = ?",[a],h.parse)}async listProfileEvaluationSuiteRuns(a){return this.listParsedPayloads("SELECT payload FROM profile_evaluation_suite_runs WHERE profile_key = ? ORDER BY created_at DESC, id ASC",[s(f.parse(a))],h.parse)}async saveBenchmarkRun(a){let e=v.parse(a.run);return c(e,"Benchmark run"),await this.upsertPayload(`INSERT INTO benchmark_runs (id, taskset_id, phase, payload, created_at)
3
3
  VALUES (?, ?, ?, ?, ?)
4
4
  ON CONFLICT(id) DO NOTHING`,[e.id,a.tasksetId,e.phase,JSON.stringify(e),e.createdAt]),e}async listBenchmarkRuns(a){return this.listParsedPayloads("SELECT payload FROM benchmark_runs WHERE taskset_id = ? ORDER BY created_at DESC, id ASC",[a],v.parse)}async saveBenchmarkComparison(a){let e=y.parse(a.comparison);return c(e,"Benchmark comparison"),await this.upsertPayload(`INSERT INTO benchmark_comparisons (id, taskset_id, payload, created_at)
5
5
  VALUES (?, ?, ?, ?)
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as h,b as d,c as p,h as N}from"./chunk-GWCHDF2C.js";import"./chunk-EQFGBL3O.js";import"./chunk-GZ7M5XBP.js";import"./chunk-F74GBN6K.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as T}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import{P as u,h as I}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as l}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";function L(o,e){let i=d(o,e.scope,e.executionId);if(i.ownerActorId!==e.actorId||!i.completedAt)throw new Error("human_local_publication_source_denied");return o.exec("CREATE TABLE IF NOT EXISTS human_local_publications(scope TEXT NOT NULL,actor_id TEXT NOT NULL,execution_id TEXT NOT NULL,operation_id TEXT NOT NULL,execution_hash TEXT NOT NULL,publication TEXT NOT NULL,PRIMARY KEY(scope,actor_id,execution_id,operation_id))"),i}c(L,"setup");function w(o,e){if(L(o,e).executionHash!==e.executionHash)throw new Error("human_local_publication_source_changed");let t=o.get("SELECT publication,execution_hash FROM human_local_publications WHERE scope=? AND actor_id=? AND execution_id=? AND operation_id=?",[e.scope,e.actorId,e.executionId,e.operationId]);if(t){if(t.execution_hash!==e.executionHash||l(JSON.parse(t.publication))!==l(e.publication))throw new Error("human_local_publication_operation_conflict");return}o.run("INSERT INTO human_local_publications VALUES(?,?,?,?,?,?)",[e.scope,e.actorId,e.executionId,e.operationId,e.executionHash,JSON.stringify(e.publication)])}c(w,"retainHumanLocalPublication");function O(o,e){let i=L(o,e);return o.all("SELECT publication,execution_hash FROM human_local_publications WHERE scope=? AND actor_id=? AND execution_id=? ORDER BY operation_id LIMIT 1001",[e.scope,e.actorId,e.executionId]).map(t=>{if(t.execution_hash!==i.executionHash)throw new Error("human_local_publication_source_changed");return JSON.parse(t.publication)})}c(O,"readHumanLocalPublications");function _(o,e){let i=d(o,e.teamId,e.executionId);if(i.ownerActorId!==e.actorId)throw new Error("live_agent_account_denied");let t=o.get("SELECT owner_id FROM local_experiment_executions WHERE team_id=? AND id=?",[e.teamId,e.executionId]),n=p(o,e.teamId,e.executionId).find(g=>g.receiptId===e.receiptId);if(!n||n.admission.request.model.providerId!=="claude-code")throw new Error("live_agent_case_denied");let a=o.get("SELECT payload FROM local_experiment_events WHERE team_id=? AND execution_id=? AND case_id=? AND type='external.start' ORDER BY sequence LIMIT 1",[e.teamId,e.executionId,e.receiptId]);if(!a||JSON.parse(a.payload).sessionId!==e.sessionId)throw new Error("live_agent_session_stale");o.exec("CREATE TABLE IF NOT EXISTS human_live_controls(team_id TEXT NOT NULL,actor_id TEXT NOT NULL,operation_id TEXT NOT NULL,request_hash TEXT NOT NULL,state TEXT NOT NULL,PRIMARY KEY(team_id,actor_id,operation_id))");let{phase:r,ownerId:R,...E}=e,m=l(E),s=o.get("SELECT request_hash,state FROM human_live_controls WHERE team_id=? AND actor_id=? AND operation_id=?",[e.teamId,e.actorId,e.operationId]);if(s&&s.request_hash!==m)throw new Error("live_agent_operation_conflict");if(e.phase==="inspect")return s?{replay:!0,state:s.state}:null;if(N(o,e.ownerId),t?.owner_id!==e.ownerId)throw new Error("live_agent_execution_lease_lost");if(e.phase==="acknowledge"){if(!s)throw new Error("live_agent_operation_missing");return s.state==="acknowledged"?{replay:!0,state:"acknowledged"}:(v(o,e,"external.control_receipt",{sessionId:e.sessionId,operationId:e.operationId,action:e.action,transport:"process_stdin",state:"acknowledged",occurredAt:new Date().toISOString()}),o.run("UPDATE human_live_controls SET state='acknowledged' WHERE team_id=? AND actor_id=? AND operation_id=?",[e.teamId,e.actorId,e.operationId]),{replay:!1,state:"acknowledged"})}if(s)return{replay:!0,state:s.state};if(o.get("SELECT c.operation_id FROM human_live_controls c JOIN local_experiment_events e ON e.team_id=c.team_id AND json_extract(e.payload,'$.actorId')=c.actor_id AND json_extract(e.payload,'$.operationId')=c.operation_id WHERE c.team_id=? AND c.actor_id=? AND c.state='prepared' AND e.execution_id=? AND e.case_id=? AND e.type='external.human_intervention' LIMIT 1",[e.teamId,e.actorId,e.executionId,e.receiptId]))throw new Error("live_agent_prior_delivery_unknown");if(n.status!=="running"||i.completedAt)throw new Error("live_agent_already_sealed");return o.run("INSERT INTO human_live_controls VALUES(?,?,?,?,'prepared')",[e.teamId,e.actorId,e.operationId,m]),v(o,e,"external.human_intervention",{...E,occurredAt:new Date().toISOString()}),{replay:!1,state:"prepared"}}c(_,"writeHumanLiveControl");function v(o,e,i,t){let n=JSON.stringify(t),a=Buffer.byteLength(n),r=o.get("SELECT event_count,byte_count FROM local_experiment_trace_budgets WHERE team_id=? AND execution_id=?",[e.teamId,e.executionId]);if(a>1048576||(r?.event_count??0)>=2e4||(r?.byte_count??0)+a>67108864)throw new Error("live_agent_control_too_large");o.run("INSERT INTO local_experiment_events(team_id,execution_id,case_id,type,payload) VALUES(?,?,?,?,?)",[e.teamId,e.executionId,e.receiptId,i,n]),o.run("INSERT INTO local_experiment_trace_budgets(team_id,execution_id,event_count,byte_count) VALUES(?,?,1,?) ON CONFLICT(team_id,execution_id) DO UPDATE SET event_count=event_count+1,byte_count=byte_count+excluded.byte_count",[e.teamId,e.executionId,a])}c(v,"appendControlEvent");var y=`
2
+ import{a as h,b as d,c as p,h as N}from"./chunk-JUHZ5S3R.js";import"./chunk-NC27T4AB.js";import"./chunk-YNH3NMPF.js";import"./chunk-F74GBN6K.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as T}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import{P as u,h as I}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as l}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";function L(o,e){let i=d(o,e.scope,e.executionId);if(i.ownerActorId!==e.actorId||!i.completedAt)throw new Error("human_local_publication_source_denied");return o.exec("CREATE TABLE IF NOT EXISTS human_local_publications(scope TEXT NOT NULL,actor_id TEXT NOT NULL,execution_id TEXT NOT NULL,operation_id TEXT NOT NULL,execution_hash TEXT NOT NULL,publication TEXT NOT NULL,PRIMARY KEY(scope,actor_id,execution_id,operation_id))"),i}c(L,"setup");function w(o,e){if(L(o,e).executionHash!==e.executionHash)throw new Error("human_local_publication_source_changed");let t=o.get("SELECT publication,execution_hash FROM human_local_publications WHERE scope=? AND actor_id=? AND execution_id=? AND operation_id=?",[e.scope,e.actorId,e.executionId,e.operationId]);if(t){if(t.execution_hash!==e.executionHash||l(JSON.parse(t.publication))!==l(e.publication))throw new Error("human_local_publication_operation_conflict");return}o.run("INSERT INTO human_local_publications VALUES(?,?,?,?,?,?)",[e.scope,e.actorId,e.executionId,e.operationId,e.executionHash,JSON.stringify(e.publication)])}c(w,"retainHumanLocalPublication");function O(o,e){let i=L(o,e);return o.all("SELECT publication,execution_hash FROM human_local_publications WHERE scope=? AND actor_id=? AND execution_id=? ORDER BY operation_id LIMIT 1001",[e.scope,e.actorId,e.executionId]).map(t=>{if(t.execution_hash!==i.executionHash)throw new Error("human_local_publication_source_changed");return JSON.parse(t.publication)})}c(O,"readHumanLocalPublications");function _(o,e){let i=d(o,e.teamId,e.executionId);if(i.ownerActorId!==e.actorId)throw new Error("live_agent_account_denied");let t=o.get("SELECT owner_id FROM local_experiment_executions WHERE team_id=? AND id=?",[e.teamId,e.executionId]),n=p(o,e.teamId,e.executionId).find(g=>g.receiptId===e.receiptId);if(!n||n.admission.request.model.providerId!=="claude-code")throw new Error("live_agent_case_denied");let a=o.get("SELECT payload FROM local_experiment_events WHERE team_id=? AND execution_id=? AND case_id=? AND type='external.start' ORDER BY sequence LIMIT 1",[e.teamId,e.executionId,e.receiptId]);if(!a||JSON.parse(a.payload).sessionId!==e.sessionId)throw new Error("live_agent_session_stale");o.exec("CREATE TABLE IF NOT EXISTS human_live_controls(team_id TEXT NOT NULL,actor_id TEXT NOT NULL,operation_id TEXT NOT NULL,request_hash TEXT NOT NULL,state TEXT NOT NULL,PRIMARY KEY(team_id,actor_id,operation_id))");let{phase:r,ownerId:R,...E}=e,m=l(E),s=o.get("SELECT request_hash,state FROM human_live_controls WHERE team_id=? AND actor_id=? AND operation_id=?",[e.teamId,e.actorId,e.operationId]);if(s&&s.request_hash!==m)throw new Error("live_agent_operation_conflict");if(e.phase==="inspect")return s?{replay:!0,state:s.state}:null;if(N(o,e.ownerId),t?.owner_id!==e.ownerId)throw new Error("live_agent_execution_lease_lost");if(e.phase==="acknowledge"){if(!s)throw new Error("live_agent_operation_missing");return s.state==="acknowledged"?{replay:!0,state:"acknowledged"}:(v(o,e,"external.control_receipt",{sessionId:e.sessionId,operationId:e.operationId,action:e.action,transport:"process_stdin",state:"acknowledged",occurredAt:new Date().toISOString()}),o.run("UPDATE human_live_controls SET state='acknowledged' WHERE team_id=? AND actor_id=? AND operation_id=?",[e.teamId,e.actorId,e.operationId]),{replay:!1,state:"acknowledged"})}if(s)return{replay:!0,state:s.state};if(o.get("SELECT c.operation_id FROM human_live_controls c JOIN local_experiment_events e ON e.team_id=c.team_id AND json_extract(e.payload,'$.actorId')=c.actor_id AND json_extract(e.payload,'$.operationId')=c.operation_id WHERE c.team_id=? AND c.actor_id=? AND c.state='prepared' AND e.execution_id=? AND e.case_id=? AND e.type='external.human_intervention' LIMIT 1",[e.teamId,e.actorId,e.executionId,e.receiptId]))throw new Error("live_agent_prior_delivery_unknown");if(n.status!=="running"||i.completedAt)throw new Error("live_agent_already_sealed");return o.run("INSERT INTO human_live_controls VALUES(?,?,?,?,'prepared')",[e.teamId,e.actorId,e.operationId,m]),v(o,e,"external.human_intervention",{...E,occurredAt:new Date().toISOString()}),{replay:!1,state:"prepared"}}c(_,"writeHumanLiveControl");function v(o,e,i,t){let n=JSON.stringify(t),a=Buffer.byteLength(n),r=o.get("SELECT event_count,byte_count FROM local_experiment_trace_budgets WHERE team_id=? AND execution_id=?",[e.teamId,e.executionId]);if(a>1048576||(r?.event_count??0)>=2e4||(r?.byte_count??0)+a>67108864)throw new Error("live_agent_control_too_large");o.run("INSERT INTO local_experiment_events(team_id,execution_id,case_id,type,payload) VALUES(?,?,?,?,?)",[e.teamId,e.executionId,e.receiptId,i,n]),o.run("INSERT INTO local_experiment_trace_budgets(team_id,execution_id,event_count,byte_count) VALUES(?,?,1,?) ON CONFLICT(team_id,execution_id) DO UPDATE SET event_count=event_count+1,byte_count=byte_count+excluded.byte_count",[e.teamId,e.executionId,a])}c(v,"appendControlEvent");var y=`
3
3
  CREATE TABLE IF NOT EXISTS human_review_revisions(scope TEXT NOT NULL,id TEXT NOT NULL,revision INTEGER NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(scope,id,revision));
4
4
  CREATE TABLE IF NOT EXISTS human_reviews(scope TEXT NOT NULL,id TEXT NOT NULL,revision INTEGER NOT NULL,project_id TEXT NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(scope,id));
5
5
  CREATE INDEX IF NOT EXISTS human_reviews_project_idx ON human_reviews(scope,project_id,id);
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{B as d}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as s}from"./chunk-FTQLQJQV.js";function f(e){if(Array.isArray(e)){let r=!1,n=e.map(c=>{let t=f(c);return r||=t.changed,t.value});return{value:r?n:e,changed:r}}if(!u(e))return{value:e,changed:!1};let o=!1,i={};for(let[r,n]of Object.entries(e)){if(r==="learnedPreference"&&n!==null){let t=u(n)?Object.fromEntries(Object.entries(n).filter(([l])=>l!=="qualificationKind")):n,a=d.safeParse(t);i[r]=a.success?a.data:null,o||=!a.success||t!==n;continue}let c=f(n);i[r]=c.value,o||=c.changed}return{value:o?i:e,changed:o}}s(f,"sanitizeUnverifiableLearnedPreferenceBindings");function u(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}s(u,"isRecord");export{f as sanitizeUnverifiableLearnedPreferenceBindings};
2
+ import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{B as d}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as s}from"./chunk-FTQLQJQV.js";function f(e){if(Array.isArray(e)){let r=!1,n=e.map(c=>{let t=f(c);return r||=t.changed,t.value});return{value:r?n:e,changed:r}}if(!u(e))return{value:e,changed:!1};let o=!1,i={};for(let[r,n]of Object.entries(e)){if(r==="learnedPreference"&&n!==null){let t=u(n)?Object.fromEntries(Object.entries(n).filter(([l])=>l!=="qualificationKind")):n,a=d.safeParse(t);i[r]=a.success?a.data:null,o||=!a.success||t!==n;continue}let c=f(n);i[r]=c.value,o||=c.changed}return{value:o?i:e,changed:o}}s(f,"sanitizeUnverifiableLearnedPreferenceBindings");function u(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}s(u,"isRecord");export{f as sanitizeUnverifiableLearnedPreferenceBindings};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as y,c as M}from"./chunk-XVDFJ3ZF.js";import{a as N,b as E,c as v,d as m,e as w,f as D,g as P,h as x,i as j}from"./chunk-GWCHDF2C.js";import{a as s}from"./chunk-EQFGBL3O.js";import"./chunk-GZ7M5XBP.js";import"./chunk-F74GBN6K.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{bb as f,eb as h,hb as O,ib as F}from"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as W}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{la as L}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{h as R}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as d}from"./chunk-KGNCKIFP.js";import{b as I}from"./chunk-ES2ISFJC.js";import{a as u}from"./chunk-FTQLQJQV.js";function J(c,e){let t=c.all(`SELECT e.id,e.payload,
2
+ import{a as y,c as M}from"./chunk-XVDFJ3ZF.js";import{a as N,b as E,c as v,d as m,e as w,f as D,g as P,h as x,i as j}from"./chunk-JUHZ5S3R.js";import{a as s}from"./chunk-NC27T4AB.js";import"./chunk-YNH3NMPF.js";import"./chunk-F74GBN6K.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{bb as f,eb as h,hb as O,ib as F}from"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as W}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{la as L}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{h as R}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as d}from"./chunk-KGNCKIFP.js";import{b as I}from"./chunk-ES2ISFJC.js";import{a as u}from"./chunk-FTQLQJQV.js";function J(c,e){let t=c.all(`SELECT e.id,e.payload,
3
3
  COALESCE(json_extract(c.payload,'$.configuration.request.name'),json_extract(d.payload,'$.configuration.request.name')) AS name,
4
4
  count(*) OVER () AS total FROM local_experiment_executions e
5
5
  LEFT JOIN local_experiment_configurations c ON c.team_id=e.team_id AND c.execution_id=e.id
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as B}from"./chunk-QIKWJ2AA.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as E}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{b as k,l as v,m as y}from"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{ua as M}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{x as u}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{O as R,ba as g}from"./chunk-VYLGI3IH.js";import{h as s}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as d}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as p}from"./chunk-FTQLQJQV.js";var T=class extends E{static{p(this,"SqliteModelBatchReviewStore")}async findModelBatchReview(t,r){return this.modelBatchReviewTransaction(t,r)}async beginModelBatchReview(t,r,o){let e=await this.modelBatchReviewTransaction(t,r,o);if(!e)throw new Error("Model batch review was not created.");return e}async modelBatchReviewTransaction(t,r,o){let e=k.parse(r);await this.ready;let l=this.writeQueue.then(async()=>{let a=this.db;if(!a)throw new Error("Model review store is closed.");a.exec("BEGIN IMMEDIATE");let w=!0,h=B(a,t,()=>{if(!w)throw new Error("Model review transaction is closed.")});try{let i=a.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[e.modelId,t]);if(!i)throw new s("model_not_found",404);let n=u.parse(JSON.parse(i.payload)),m=await v(h,e);if(m||!o)return a.exec("COMMIT"),m;if(n.revision!==e.expectedModelRevision||!n.trainingSetup.tasksetRef||!R(n.trainingSetup.tasksetRef,e.tasksetRef))throw new s("model_revision_conflict",409);let f=a.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND profile_id = ?",[e.tasksetRef.id,e.tasksetRef.revision,t]),c=f?M.parse(JSON.parse(f.payload)):null;if(!c||c.contentHash!==e.tasksetRef.contentHash||d(c.metadata.learning)!==d(g(o.taskset)))throw new s("model_review_package_mismatch",409);let _=await y(h,{scope:t,request:e,package:o,now:new Date().toISOString()});return a.exec("COMMIT"),_}catch(i){throw a.exec("ROLLBACK"),i}finally{w=!1}});return this.writeQueue=l.then(()=>{},()=>{}),l}};export{T as SqliteModelBatchReviewStore};
2
+ import{b as B}from"./chunk-QIKWJ2AA.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as E}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{b as k,l as v,m as y}from"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{ua as M}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{x as u}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{O as R,ba as g}from"./chunk-VYLGI3IH.js";import{h as s}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as d}from"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as p}from"./chunk-FTQLQJQV.js";var T=class extends E{static{p(this,"SqliteModelBatchReviewStore")}async findModelBatchReview(t,r){return this.modelBatchReviewTransaction(t,r)}async beginModelBatchReview(t,r,o){let e=await this.modelBatchReviewTransaction(t,r,o);if(!e)throw new Error("Model batch review was not created.");return e}async modelBatchReviewTransaction(t,r,o){let e=k.parse(r);await this.ready;let l=this.writeQueue.then(async()=>{let a=this.db;if(!a)throw new Error("Model review store is closed.");a.exec("BEGIN IMMEDIATE");let w=!0,h=B(a,t,()=>{if(!w)throw new Error("Model review transaction is closed.")});try{let i=a.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[e.modelId,t]);if(!i)throw new s("model_not_found",404);let n=u.parse(JSON.parse(i.payload)),m=await v(h,e);if(m||!o)return a.exec("COMMIT"),m;if(n.revision!==e.expectedModelRevision||!n.trainingSetup.tasksetRef||!R(n.trainingSetup.tasksetRef,e.tasksetRef))throw new s("model_revision_conflict",409);let f=a.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND profile_id = ?",[e.tasksetRef.id,e.tasksetRef.revision,t]),c=f?M.parse(JSON.parse(f.payload)):null;if(!c||c.contentHash!==e.tasksetRef.contentHash||d(c.metadata.learning)!==d(g(o.taskset)))throw new s("model_review_package_mismatch",409);let _=await y(h,{scope:t,request:e,package:o,now:new Date().toISOString()});return a.exec("COMMIT"),_}catch(i){throw a.exec("ROLLBACK"),i}finally{w=!1}});return this.writeQueue=l.then(()=>{},()=>{}),l}};export{T as SqliteModelBatchReviewStore};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ie,b as Q,c as W,d as ye,e as Te,f as Ee}from"./chunk-SDXFLO7J.js";import"./chunk-GLDYJM7O.js";import{a as Se,d as F,e as C,g as Pe,h as J,j as Me}from"./chunk-HCYX6RHP.js";import{a as ke}from"./chunk-SDAUS5PY.js";import{a as b}from"./chunk-I2NXNMRZ.js";import{d as me,e as he,f as ge,i as we,j as ve,k as B}from"./chunk-O72BSKSO.js";import{b as ce}from"./chunk-DBK66CJP.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as fe}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import{B as ne,D as de,d as ae,e as oe,k as se}from"./chunk-FTEOCCPB.js";import{Fb as le,Gb as pe,Ib as ue,O as ee,Q as L,T as te,W as re,ua as ie,xa as x}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{E as Y,K as Z,i as k,n as N,t as X,x as v}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{N as g,O as R,Q as G,d as V,ib as K}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import{b as I}from"./chunk-ES2ISFJC.js";import{a as f}from"./chunk-FTQLQJQV.js";import Ae from"node:path";import{createHash as be}from"node:crypto";function j(o){let{request:a,resolved:r}=C(o.request,o.package),{starter:t,...n}=r,e=a.rewardBindingRef&&!R(a.rewardBindingRef,g(r.rewardBinding));if(e&&(!o.rewardSelection||!R(a.rewardBindingRef,g(o.rewardSelection.rewardBinding))))throw new Error("The selected starter Reward is unavailable for package preparation.");let s=re({owner:{scopeId:a.profileId,modelId:a.modelId},source:n,...e?o.rewardSelection:{rewardBinding:n.rewardBinding,rewards:n.rewards,assets:n.assets}}),{taskset:i,taskDefinition:p,rewardBinding:l,rewards:d,assets:h}=s;if(o.source.profileId!==a.profileId||o.source.sourceHash!==t.contentHash)throw new Error("Starter source must belong to this Profile and pin the catalog package.");let u=s.execution!==void 0,y=i.environment.kind==="text"&&i.environment.entrypoint==="openpond.text.v1"&&!i.environment.stateful&&(!i.environmentRelease&&!i.verifierSetRelease||s.executionResources!==void 0)&&!i.capabilities.length&&!i.tools.length;if(!["sft","grpo"].includes(a.method)||p.harness||!y&&!u||i.tasks.some(c=>c.artifactRefs.length)||i.graders.some(c=>c.kind==="model_judge"&&(!c.model||c.calibrationStatus!=="passed")))throw new Error("This starter requires an additional training or environment adapter before preparation.");let w=new Set(o.approvedTrainingTaskIds);if(w.size!==o.approvedTrainingTaskIds.length)throw new Error("Starter training approvals must be unique.");for(let c of w){let P=i.tasks.find(H=>H.id===c);if(!P||P.split!=="train")throw new Error(`Starter approval must reference a training task: ${c}.`);if(a.method==="sft"&&P.expectedOutput===null)throw new Error(`SFT starter approval requires a reviewed target: ${c}.`)}if(a.method==="grpo"&&i.tasks.some(c=>c.split==="train"&&!w.has(c.id)))throw new Error("GRPO starter preparation requires approval of every training task.");for(let c of o.fixtures){if(!i.tasks.some(P=>P.id===c.taskId))throw new Error(`Starter fixture references an unknown task: ${c.taskId}.`);u&&!c.infrastructureError&&ee.parse(c.metadata.toolScript)}let E=i.id,m=ne({profileId:a.profileId,id:`${E}-draft`,name:t.name,now:o.createdAt}),S=[];for(let c of i.graders){if(c.kind!=="custom_verifier")continue;let P=h.find(D=>D.id===c.verifierRef.id);if(!P)throw new Error(`Starter verifier asset is missing: ${c.id}.`);let H=pe(c.verifierRef.contentHash);S.some(D=>D.path===H)||S.push({path:H,role:"verifier",content:V(P,c.verifierRef)})}let _=se.parse({...m,objective:p.instructions,metrics:i.metrics??m.metrics,sourceRefs:[o.source],policy:i.policy,environment:{...m.environment,kind:u?"agent":"chat",entrypoint:i.environment.entrypoint,stateful:i.environment.stateful,toolNames:i.tools.map(c=>c.name),deterministicSeeds:i.environment.deterministicSeeds,defaultTimeoutMs:i.environment.defaultTimeoutMs,networkPolicy:i.environment.networkPolicy,metadata:{portableEnvironment:i.environment,portableTools:i.tools,...s.executionResources?{portableExecutionResources:s.executionResources}:s.execution?{portableExecutionResources:{environment:s.execution.environment,verifierSet:s.execution.verifierSet}}:{}}},output:{mode:"structured_json",jsonSchema:p.outputSchema,renderer:null},capabilities:{...m.capabilities,taskKind:u?"single_agent":"chat",requiresTools:u,requiresState:u,supportedSignals:a.method==="grpo"?["reward"]:["demonstration"],compatibleMethods:[a.method],rewardKinds:[...new Set(i.graders.map(c=>c.kind==="human"?"human":c.kind==="model_judge"?"model_judge":"deterministic"))],requiresPrivilegedGrading:!0,environmentPlacements:["local","remote"]},tasks:i.tasks.map(({artifactRefs:c,...P})=>({...P,schemaVersion:"openpond.taskData.v1",sourceRefs:[o.source.id],metadata:{exampleOrigin:"curated_starter",starter:g(t),portableTaskRecord:{...P,artifactRefs:[]}}})),graders:le(l,d,h),graderFixtures:o.fixtures,learningSignals:{...m.learningSignals,rewards:a.method==="grpo"?i.tasks.filter(c=>w.has(c.id)).map(c=>({kind:"reward",id:`starter-reward-${c.id}`,taskId:c.id,task:p.instructions,rules:[{id:l.id,points:1,condition:"Execute the published Reward binding with its declared normalization, weights and required gates."}],otherwisePoints:0,executable:!0,approved:!0,confidence:1,sourceRefs:[o.source.id],artifactRef:l.id,metadata:{starter:g(t),rewardBinding:g(l),approvalOrigin:"catalog_publication"}})):[],demonstrations:a.method==="sft"?i.tasks.filter(c=>w.has(c.id)).map(c=>({kind:"demonstration",id:`starter-target-${c.id}`,taskId:c.id,sourceRefs:[o.source.id],artifactRef:i.id,approved:!0,confidence:1,prompt:null,response:JSON.stringify(c.expectedOutput),metadata:{starter:g(t),approvalOrigin:"catalog_publication"}})):[]},metadata:{starter:g(t),starterTasksetRelease:g(i),taskDefinition:g(p),rewardBinding:g(l),rewardExecution:{binding:l,rewards:d},portableCapabilities:i.capabilities,derivedPortableMetadata:i.metadata,modelTasksetDerivation:i.metadata.modelTasksetDerivation}}),M=de({draft:_,now:o.createdAt,tasksetId:E,sourcePackageHash:i.contentHash});return M.metrics=i.metrics,M.contentHash=x(M),{draft:_,taskset:M,generatedFiles:S,resources:s}}f(j,"prepareModelStarterTaskset");function O(o,a){let r=F(a),t=o.get("SELECT request_hash, payload FROM model_starter_creation_operations WHERE profile_id = ? AND operation_id = ?",[r.profileId,r.operationId]);if(!t)return null;if(t.request_hash!==je(r))throw new Error("Starter creation operation was already used with different configuration.");return v.parse(JSON.parse(t.payload))}f(O,"findModelStarterCreation");async function Re(o,a){let r=F(a.request);if(r.learning)throw new Error("Create this Model in a hosted workspace to enable continual learning.");let t=O(o,r);if(t)return t;let{taskset:n,resources:e}=j(a),s=Pe(a.package),i=await Y({id:r.modelId,profileId:r.profileId,name:r.name,objective:s.taskDefinition.instructions,defaultBaseModel:r.startingModel,defaultDestinationId:null,trainingSetup:Se({package:e,setup:X.parse({tasksetRef:g(n),rewardBindingRef:g(e.rewardBinding),baseModel:r.startingModel,method:r.method,managedRolloutPlacement:"remote"})})},0);o.exec("BEGIN IMMEDIATE");try{let p=O(o,r);if(p)return o.exec("COMMIT"),p;if(o.get("SELECT id FROM tasksets WHERE id = ?",[n.id])||o.get("SELECT id FROM model_projects WHERE id = ?",[r.modelId]))throw new Error("Starter creation requires a new Model and Taskset identity.");let l=[...e.executionResources??e.execution?[{kind:"asset",resource:te(e.executionResources??e.execution)}]:[],...s.execution?[{kind:"asset",resource:L(s.execution)}]:[],...s.assets.map(u=>({kind:"asset",resource:u})),...s.rewards.map(u=>({kind:"reward",resource:u})),{kind:"binding",resource:s.rewardBinding},{kind:"definition",resource:s.taskDefinition},{kind:"package",resource:s.taskset},...e.taskset.contentHash===s.taskset.contentHash?[]:[{kind:"definition",resource:e.taskDefinition},{kind:"package",resource:e.taskset},...e.execution?[{kind:"asset",resource:L(e.execution)}]:[]]];for(let{kind:u,resource:y}of l)Ie(o,r.profileId,u,y);let d=JSON.stringify(n);o.run("INSERT INTO tasksets (id, profile_id, status, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",[n.id,n.profileId,n.status,d,n.createdAt,n.updatedAt]),o.run("INSERT INTO taskset_revisions (taskset_id, revision, content_hash, profile_id, status, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[n.id,n.revision,n.contentHash,n.profileId,n.status,d,n.createdAt,n.updatedAt]);let h=Te(o,i);return o.run("INSERT INTO model_starter_creation_operations (profile_id, operation_id, request_hash, payload) VALUES (?, ?, ?, ?)",[r.profileId,r.operationId,je(r),JSON.stringify(h)]),o.exec("COMMIT"),h}catch(p){throw o.exec("ROLLBACK"),p}}f(Re,"commitModelStarterCreation");function je(o){return be("sha256").update(k(o)).digest("hex")}f(je,"requestHash");function q(o,a,r,t,n){let e=v.parse(r);o.exec("BEGIN IMMEDIATE");try{let s=o.get("SELECT payload FROM model_projects WHERE id = ?",[e.id]),i=s?v.parse(JSON.parse(s.payload)):null;i&&i.profileId!==e.profileId&&T("Model ownership changed during hosted synchronization.");let p;if(t)k(i)!==k(a)&&T("Model changed while its hosted configuration was loading. Refresh before applying it."),p=e;else{(!i||!a||a.id!==e.id||a.profileId!==e.profileId)&&T("Model is no longer available for hosted synchronization."),i.hosted?.teamId!==a.hosted?.teamId&&i.hosted?.teamId!==e.hosted?.teamId&&T("Model hosting team changed during synchronization.");let l=e.hosted,d=i.hosted,h=d;if(l){d?.apiOrigin&&d.apiOrigin!==l.apiOrigin&&T("Model hosting API changed during synchronization.");let u=d?.apiOrigin===l.apiOrigin&&d?.teamId===l.teamId&&d.projectId===l.projectId;u&&d.revision===l.revision&&d.etag!==l.etag&&T("Hosted Model receipts disagree about the same revision."),h={...u&&d.revision>l.revision?d:l,tasksets:u?Oe(d.tasksets,l.tasksets,w=>`${w.localTasksetId}:${w.releaseHash}`,w=>w.syncedAt):l.tasksets}}p=v.parse({...i,hosted:h,tasksetSyncs:Oe(i.tasksetSyncs,e.tasksetSyncs,u=>u.localTasksetId,u=>u.lastAttemptAt)})}return n?.(),o.run(`INSERT INTO model_projects (id, profile_id, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
2
+ import{a as Ie,b as Q,c as W,d as ye,e as Te,f as Ee}from"./chunk-SDXFLO7J.js";import"./chunk-GLDYJM7O.js";import{a as Se,d as F,e as C,g as Pe,h as J,j as Me}from"./chunk-HCYX6RHP.js";import{a as ke}from"./chunk-SDAUS5PY.js";import{a as b}from"./chunk-I2NXNMRZ.js";import{d as me,e as he,f as ge,i as we,j as ve,k as B}from"./chunk-O72BSKSO.js";import{b as ce}from"./chunk-DBK66CJP.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as fe}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import{B as ne,D as de,d as ae,e as oe,k as se}from"./chunk-FTEOCCPB.js";import{Fb as le,Gb as pe,Ib as ue,O as ee,Q as L,T as te,W as re,ua as ie,xa as x}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{E as Y,K as Z,i as k,n as N,t as X,x as v}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{N as g,O as R,Q as G,d as V,ib as K}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import{b as I}from"./chunk-ES2ISFJC.js";import{a as f}from"./chunk-FTQLQJQV.js";import Ae from"node:path";import{createHash as be}from"node:crypto";function j(o){let{request:a,resolved:r}=C(o.request,o.package),{starter:t,...n}=r,e=a.rewardBindingRef&&!R(a.rewardBindingRef,g(r.rewardBinding));if(e&&(!o.rewardSelection||!R(a.rewardBindingRef,g(o.rewardSelection.rewardBinding))))throw new Error("The selected starter Reward is unavailable for package preparation.");let s=re({owner:{scopeId:a.profileId,modelId:a.modelId},source:n,...e?o.rewardSelection:{rewardBinding:n.rewardBinding,rewards:n.rewards,assets:n.assets}}),{taskset:i,taskDefinition:p,rewardBinding:l,rewards:d,assets:h}=s;if(o.source.profileId!==a.profileId||o.source.sourceHash!==t.contentHash)throw new Error("Starter source must belong to this Profile and pin the catalog package.");let u=s.execution!==void 0,y=i.environment.kind==="text"&&i.environment.entrypoint==="openpond.text.v1"&&!i.environment.stateful&&(!i.environmentRelease&&!i.verifierSetRelease||s.executionResources!==void 0)&&!i.capabilities.length&&!i.tools.length;if(!["sft","grpo"].includes(a.method)||p.harness||!y&&!u||i.tasks.some(c=>c.artifactRefs.length)||i.graders.some(c=>c.kind==="model_judge"&&(!c.model||c.calibrationStatus!=="passed")))throw new Error("This starter requires an additional training or environment adapter before preparation.");let w=new Set(o.approvedTrainingTaskIds);if(w.size!==o.approvedTrainingTaskIds.length)throw new Error("Starter training approvals must be unique.");for(let c of w){let P=i.tasks.find(H=>H.id===c);if(!P||P.split!=="train")throw new Error(`Starter approval must reference a training task: ${c}.`);if(a.method==="sft"&&P.expectedOutput===null)throw new Error(`SFT starter approval requires a reviewed target: ${c}.`)}if(a.method==="grpo"&&i.tasks.some(c=>c.split==="train"&&!w.has(c.id)))throw new Error("GRPO starter preparation requires approval of every training task.");for(let c of o.fixtures){if(!i.tasks.some(P=>P.id===c.taskId))throw new Error(`Starter fixture references an unknown task: ${c.taskId}.`);u&&!c.infrastructureError&&ee.parse(c.metadata.toolScript)}let E=i.id,m=ne({profileId:a.profileId,id:`${E}-draft`,name:t.name,now:o.createdAt}),S=[];for(let c of i.graders){if(c.kind!=="custom_verifier")continue;let P=h.find(D=>D.id===c.verifierRef.id);if(!P)throw new Error(`Starter verifier asset is missing: ${c.id}.`);let H=pe(c.verifierRef.contentHash);S.some(D=>D.path===H)||S.push({path:H,role:"verifier",content:V(P,c.verifierRef)})}let _=se.parse({...m,objective:p.instructions,metrics:i.metrics??m.metrics,sourceRefs:[o.source],policy:i.policy,environment:{...m.environment,kind:u?"agent":"chat",entrypoint:i.environment.entrypoint,stateful:i.environment.stateful,toolNames:i.tools.map(c=>c.name),deterministicSeeds:i.environment.deterministicSeeds,defaultTimeoutMs:i.environment.defaultTimeoutMs,networkPolicy:i.environment.networkPolicy,metadata:{portableEnvironment:i.environment,portableTools:i.tools,...s.executionResources?{portableExecutionResources:s.executionResources}:s.execution?{portableExecutionResources:{environment:s.execution.environment,verifierSet:s.execution.verifierSet}}:{}}},output:{mode:"structured_json",jsonSchema:p.outputSchema,renderer:null},capabilities:{...m.capabilities,taskKind:u?"single_agent":"chat",requiresTools:u,requiresState:u,supportedSignals:a.method==="grpo"?["reward"]:["demonstration"],compatibleMethods:[a.method],rewardKinds:[...new Set(i.graders.map(c=>c.kind==="human"?"human":c.kind==="model_judge"?"model_judge":"deterministic"))],requiresPrivilegedGrading:!0,environmentPlacements:["local","remote"]},tasks:i.tasks.map(({artifactRefs:c,...P})=>({...P,schemaVersion:"openpond.taskData.v1",sourceRefs:[o.source.id],metadata:{exampleOrigin:"curated_starter",starter:g(t),portableTaskRecord:{...P,artifactRefs:[]}}})),graders:le(l,d,h),graderFixtures:o.fixtures,learningSignals:{...m.learningSignals,rewards:a.method==="grpo"?i.tasks.filter(c=>w.has(c.id)).map(c=>({kind:"reward",id:`starter-reward-${c.id}`,taskId:c.id,task:p.instructions,rules:[{id:l.id,points:1,condition:"Execute the published Reward binding with its declared normalization, weights and required gates."}],otherwisePoints:0,executable:!0,approved:!0,confidence:1,sourceRefs:[o.source.id],artifactRef:l.id,metadata:{starter:g(t),rewardBinding:g(l),approvalOrigin:"catalog_publication"}})):[],demonstrations:a.method==="sft"?i.tasks.filter(c=>w.has(c.id)).map(c=>({kind:"demonstration",id:`starter-target-${c.id}`,taskId:c.id,sourceRefs:[o.source.id],artifactRef:i.id,approved:!0,confidence:1,prompt:null,response:JSON.stringify(c.expectedOutput),metadata:{starter:g(t),approvalOrigin:"catalog_publication"}})):[]},metadata:{starter:g(t),starterTasksetRelease:g(i),taskDefinition:g(p),rewardBinding:g(l),rewardExecution:{binding:l,rewards:d},portableCapabilities:i.capabilities,derivedPortableMetadata:i.metadata,modelTasksetDerivation:i.metadata.modelTasksetDerivation}}),M=de({draft:_,now:o.createdAt,tasksetId:E,sourcePackageHash:i.contentHash});return M.metrics=i.metrics,M.contentHash=x(M),{draft:_,taskset:M,generatedFiles:S,resources:s}}f(j,"prepareModelStarterTaskset");function O(o,a){let r=F(a),t=o.get("SELECT request_hash, payload FROM model_starter_creation_operations WHERE profile_id = ? AND operation_id = ?",[r.profileId,r.operationId]);if(!t)return null;if(t.request_hash!==je(r))throw new Error("Starter creation operation was already used with different configuration.");return v.parse(JSON.parse(t.payload))}f(O,"findModelStarterCreation");async function Re(o,a){let r=F(a.request);if(r.learning)throw new Error("Create this Model in a hosted workspace to enable continual learning.");let t=O(o,r);if(t)return t;let{taskset:n,resources:e}=j(a),s=Pe(a.package),i=await Y({id:r.modelId,profileId:r.profileId,name:r.name,objective:s.taskDefinition.instructions,defaultBaseModel:r.startingModel,defaultDestinationId:null,trainingSetup:Se({package:e,setup:X.parse({tasksetRef:g(n),rewardBindingRef:g(e.rewardBinding),baseModel:r.startingModel,method:r.method,managedRolloutPlacement:"remote"})})},0);o.exec("BEGIN IMMEDIATE");try{let p=O(o,r);if(p)return o.exec("COMMIT"),p;if(o.get("SELECT id FROM tasksets WHERE id = ?",[n.id])||o.get("SELECT id FROM model_projects WHERE id = ?",[r.modelId]))throw new Error("Starter creation requires a new Model and Taskset identity.");let l=[...e.executionResources??e.execution?[{kind:"asset",resource:te(e.executionResources??e.execution)}]:[],...s.execution?[{kind:"asset",resource:L(s.execution)}]:[],...s.assets.map(u=>({kind:"asset",resource:u})),...s.rewards.map(u=>({kind:"reward",resource:u})),{kind:"binding",resource:s.rewardBinding},{kind:"definition",resource:s.taskDefinition},{kind:"package",resource:s.taskset},...e.taskset.contentHash===s.taskset.contentHash?[]:[{kind:"definition",resource:e.taskDefinition},{kind:"package",resource:e.taskset},...e.execution?[{kind:"asset",resource:L(e.execution)}]:[]]];for(let{kind:u,resource:y}of l)Ie(o,r.profileId,u,y);let d=JSON.stringify(n);o.run("INSERT INTO tasksets (id, profile_id, status, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",[n.id,n.profileId,n.status,d,n.createdAt,n.updatedAt]),o.run("INSERT INTO taskset_revisions (taskset_id, revision, content_hash, profile_id, status, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[n.id,n.revision,n.contentHash,n.profileId,n.status,d,n.createdAt,n.updatedAt]);let h=Te(o,i);return o.run("INSERT INTO model_starter_creation_operations (profile_id, operation_id, request_hash, payload) VALUES (?, ?, ?, ?)",[r.profileId,r.operationId,je(r),JSON.stringify(h)]),o.exec("COMMIT"),h}catch(p){throw o.exec("ROLLBACK"),p}}f(Re,"commitModelStarterCreation");function je(o){return be("sha256").update(k(o)).digest("hex")}f(je,"requestHash");function q(o,a,r,t,n){let e=v.parse(r);o.exec("BEGIN IMMEDIATE");try{let s=o.get("SELECT payload FROM model_projects WHERE id = ?",[e.id]),i=s?v.parse(JSON.parse(s.payload)):null;i&&i.profileId!==e.profileId&&T("Model ownership changed during hosted synchronization.");let p;if(t)k(i)!==k(a)&&T("Model changed while its hosted configuration was loading. Refresh before applying it."),p=e;else{(!i||!a||a.id!==e.id||a.profileId!==e.profileId)&&T("Model is no longer available for hosted synchronization."),i.hosted?.teamId!==a.hosted?.teamId&&i.hosted?.teamId!==e.hosted?.teamId&&T("Model hosting team changed during synchronization.");let l=e.hosted,d=i.hosted,h=d;if(l){d?.apiOrigin&&d.apiOrigin!==l.apiOrigin&&T("Model hosting API changed during synchronization.");let u=d?.apiOrigin===l.apiOrigin&&d?.teamId===l.teamId&&d.projectId===l.projectId;u&&d.revision===l.revision&&d.etag!==l.etag&&T("Hosted Model receipts disagree about the same revision."),h={...u&&d.revision>l.revision?d:l,tasksets:u?Oe(d.tasksets,l.tasksets,w=>`${w.localTasksetId}:${w.releaseHash}`,w=>w.syncedAt):l.tasksets}}p=v.parse({...i,hosted:h,tasksetSyncs:Oe(i.tasksetSyncs,e.tasksetSyncs,u=>u.localTasksetId,u=>u.lastAttemptAt)})}return n?.(),o.run(`INSERT INTO model_projects (id, profile_id, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
3
3
  ON CONFLICT(id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at`,[p.id,p.profileId,JSON.stringify(p),p.createdAt,p.updatedAt]),o.exec("COMMIT"),p}catch(s){throw o.exec("ROLLBACK"),s}}f(q,"commitModelProjectHosting");function Oe(o,a,r,t){let n=new Map(o.map(e=>[r(e),e]));for(let e of a){let s=n.get(r(e));(!s||Date.parse(t(e))>=Date.parse(t(s)))&&n.set(r(e),e)}return[...n.values()]}f(Oe,"mergeLatest");function T(o){throw new Z(409,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_hosting_conflict",message:o,retryable:!1,requestId:null,details:{}})}f(T,"conflict");function z(o,a){let{request:r,resolved:t}=C(a.request,a.package),n=r.rewardBindingRef;if(!n||R(n,g(t.rewardBinding)))return a;function e(l,d){let h=o.get("SELECT payload FROM learning_revisions WHERE scope = ? AND kind = ? AND id = ? AND revision = ?",[r.profileId,l,d.id,d.revision]);if(!h)throw new Error(`The selected starter ${l} is unavailable in this Profile.`);let u=K[l].parse(JSON.parse(h.payload));if(G(u),d.contentHash&&d.contentHash!==u.contentHash)throw new Error("The selected starter Reward differs from its immutable reference.");return u}f(e,"read");let s=e("binding",n),i=[...new Map(s.sources.map(l=>[k(l.reward),e("reward",l.reward)])).values()],p=new Map(t.assets.map(l=>[l.id,l]));for(let l of i){let d=l.implementation;for(let h of[...l.assets,..."verifierRef"in d?[d.verifierRef]:[],..."rubricRef"in d?[d.rubricRef]:[],..."inputContract"in d?[d.inputContract]:[]])p.has(h.id)||p.set(h.id,e("asset",{id:h.id,revision:1}))}return{...a,rewardSelection:{rewardBinding:s,rewards:i,assets:[...p.values()]}}}f(z,"resolveModelStarterSelection");import Ce from"node:path";async function $(o,a,r){let t=r.project.trainingSetup.tasksetRef;if(!t)return;let n=o.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ?",[t.id,t.revision]);if(!n)return;let e=ie.parse(JSON.parse(n.payload));if(e.profileId!==r.project.profileId||e.contentHash!==t.contentHash)return;let s=o.get("SELECT payload FROM model_projects WHERE id = ?",[r.project.id]),i=s?v.parse(JSON.parse(s.payload)):null;if(i&&(i.profileId!==r.project.profileId||i.revision!==r.expectedRevision))return;let p=i?.hosted?.tasksets.find(m=>m.localTasksetId===e.id&&m.localTasksetHash===e.contentHash),l=typeof e.metadata.importedPackageHash=="string"?e.metadata.importedPackageHash:p?.packageHash;if(!l){if(e.metadata.learning!==void 0||e.metadata.taskDefinition!==void 0||e.metadata.rewardBinding!==void 0)return;let m=r.project.trainingSetup,S=m.baseModel??r.project.defaultBaseModel,_=m.method??(e.authoringProvenance.buildIntent==="verifiable_reward"?"grpo":null);if(!m.rewardBindingRef&&(_!=="grpo"||m.recipe||!S?.revision||!S.tokenizerRevision||!S.chatTemplateHash))return;if(x(e)!==t.contentHash)throw new Error("Selected Taskset differs from its immutable content hash.");let M=ue({taskset:e,adapterId:me(e)});return ke({storeDir:a,taskset:e,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:M.tasksetRelease,environment:M.environmentRelease,verifierSet:M.verifierSetRelease}})}let d=await ve(a,l);if(d.taskset.id!==(p?.releaseId??t.id)||d.taskset.revision!==(p?.releaseRevision??t.revision))throw new Error("Cached package differs from its selected Taskset revision.");let{files:h,contentHash:u,...y}=d,w=he(d,typeof e.metadata.importedPackageHash=="string"),E=await ge({root:Ce.join(a,"training","tasksets",b(e)),content:y,sources:h.filter(m=>!w.has(m.asset.id)).map(m=>({asset:m.asset,sourcePath:e.tasks.flatMap(S=>S.assets??[]).find(S=>S.id===m.asset.id)?.artifactRef??m.asset.path})),fileOrder:h.map(m=>m.asset.id)});if(E.contentHash!==d.contentHash)throw new Error("Imported package bytes changed before the Reward edit.");return E}f($,"loadModelTasksetPackage");var{package:yt,evaluationPackage:Tt,...qe}=ae.shape,A=I.object({apiOrigin:I.string().url().refine(o=>new URL(o).origin===o),teamId:I.string().min(1),project:v,localTaskset:N,localEvaluation:N.optional(),evaluationPackageHash:I.string().regex(/^[a-f0-9]{64}$/).optional(),packageHash:I.string().regex(/^[a-f0-9]{64}$/),request:I.object(qe).strict()}).strict().refine(o=>!!o.localEvaluation==!!o.evaluationPackageHash,"Evaluation bytes and local identity must be captured together.");function U(o,a){let r=o.get("SELECT payload FROM model_project_package_operations WHERE profile_id = ? AND model_id = ? AND state = 'pending'",[a.profileId,a.modelId]),t=r?A.parse(JSON.parse(r.payload)):null;if(t&&(t.apiOrigin!==a.apiOrigin||t.teamId!==a.teamId))throw new Error("Finish the pending package publication in its original API and workspace before changing hosting.");return t}f(U,"pendingModelPackageOperation");function _e(o,a){let r=A.parse(a);o.exec("BEGIN IMMEDIATE");try{let t=U(o,{profileId:r.project.profileId,modelId:r.project.id,apiOrigin:r.apiOrigin,teamId:r.teamId});if(t)return o.exec("COMMIT"),t;let n=o.get("SELECT payload FROM model_projects WHERE id = ?",[r.project.id]),e=n?v.parse(JSON.parse(n.payload)):null;if(k(e)!==k(r.project))throw new Error("Model changed while its package was being prepared. Retry the push.");let s=o.get("SELECT payload, state FROM model_project_package_operations WHERE operation_id = ?",[r.request.operationId]);if(s){let i=A.parse(JSON.parse(s.payload));if(k({...i,project:r.project})!==k(r))throw new Error("Package operation identity was reused with different publication content.");if(s.state==="committed")return o.exec("COMMIT"),i;o.run("UPDATE model_project_package_operations SET state = 'pending', payload = ? WHERE operation_id = ? AND state = 'rejected'",[JSON.stringify(r),r.request.operationId])}else o.run("INSERT INTO model_project_package_operations (operation_id, profile_id, model_id, api_origin, team_id, state, payload, created_at) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)",[r.request.operationId,r.project.profileId,r.project.id,r.apiOrigin,r.teamId,JSON.stringify(r),new Date().toISOString()]);return o.exec("COMMIT"),r}catch(t){throw o.exec("ROLLBACK"),t}}f(_e,"prepareModelPackageOperation");function He(o,a,r){let t=oe.parse(r),n=o.get("SELECT payload, receipt FROM model_project_package_operations WHERE operation_id = ?",[a]);if(!n)throw new Error("Package push has no durable local intent.");let e=A.parse(JSON.parse(n.payload));if(n.receipt&&k(JSON.parse(n.receipt))!==k(t))throw new Error("Package push retry returned a different receipt.");if(t.operationId!==a||t.teamId!==e.teamId||t.packageHash!==e.packageHash||t.modelProjectId!==e.request.modelProjectId)throw new Error("Package push receipt differs from its local intent.");if(e.evaluationPackageHash&&(!t.evaluation||t.evaluation.packageHash!==e.evaluationPackageHash||k(t.evaluation.taskset)!==k(e.request.modelConfiguration?.trainingSetup.evaluationTasksetRef)))throw new Error("Evaluation package receipt differs from its local intent.");let s=e.project,i=t.project;if(e.request.selection==="select"&&!i)throw new Error("Selected package receipt is missing Model configuration.");if(!i&&!s.hosted)throw new Error("Historical package receipt has no existing hosted Model.");let p=new Date().toISOString(),l=v.parse({...s,hosted:{schemaVersion:"openpond.hostedModelProjectLink.v1",apiOrigin:e.apiOrigin,teamId:e.teamId,projectId:i?.id??s.hosted.projectId,portableProjectId:s.id,revision:i?.revision??s.hosted.revision,etag:t.projectEtag,syncedSourceRevision:e.request.selection==="select"?s.revision:s.hosted.syncedSourceRevision,syncedAt:p,tasksets:[...(s.hosted?.tasksets??[]).filter(d=>d.releaseHash!==t.taskset.contentHash&&d.releaseHash!==t.evaluation?.taskset.contentHash),{localTasksetId:e.localTaskset.id,localTasksetHash:e.localTaskset.contentHash,releaseId:t.taskset.id,releaseRevision:t.taskset.revision,releaseHash:t.taskset.contentHash,packageHash:t.packageHash,hostedTasksetId:t.hostedTasksetId,syncedAt:p},...e.localEvaluation&&t.evaluation?[{localTasksetId:e.localEvaluation.id,localTasksetHash:e.localEvaluation.contentHash,releaseId:t.evaluation.taskset.id,releaseRevision:t.evaluation.taskset.revision,releaseHash:t.evaluation.taskset.contentHash,packageHash:t.evaluation.packageHash,hostedTasksetId:t.evaluation.hostedTasksetId,syncedAt:p}]:[]]},tasksetSyncs:[...s.tasksetSyncs.filter(d=>d.localTasksetId!==e.localTaskset.id&&d.localTasksetId!==e.localEvaluation?.id),{localTasksetId:e.localTaskset.id,releaseId:t.taskset.id,releaseRevision:t.taskset.revision,releaseHash:t.taskset.contentHash,state:"synced",hostedTasksetId:t.hostedTasksetId,lastAttemptAt:p,syncedAt:p,lastError:null},...e.localEvaluation&&t.evaluation?[{localTasksetId:e.localEvaluation.id,releaseId:t.evaluation.taskset.id,releaseRevision:t.evaluation.taskset.revision,releaseHash:t.evaluation.taskset.contentHash,state:"synced",hostedTasksetId:t.evaluation.hostedTasksetId,lastAttemptAt:p,syncedAt:p,lastError:null}]:[]]});return q(o,s,l,!1,()=>{o.run("UPDATE model_project_package_operations SET state = 'committed', receipt = ? WHERE operation_id = ?",[JSON.stringify(t),a])})}f(He,"completeModelPackageOperation");var xe=class extends fe{static{f(this,"SqliteModelConfigurationStore")}async pendingModelPackagePush(a){if(await this.ready,await this.writeQueue,!this.db)throw new Error("Package push store is closed.");return U(this.db,a)}async prepareModelPackagePush(a){await this.ready;let r=this.writeQueue.then(()=>{if(!this.db)throw new Error("Package push store is closed.");return _e(this.db,a)});return this.writeQueue=r.then(()=>{},()=>{}),r}async completeModelPackagePush(a,r){await this.ready;let t=this.writeQueue.then(()=>{if(!this.db)throw new Error("Package push store is closed.");return He(this.db,a,r)});return this.writeQueue=t.then(()=>{},()=>{}),t}async rejectModelPackagePush(a){await this.ready;let r=this.writeQueue.then(()=>{if(!this.db)throw new Error("Package push store is closed.");this.db.run("UPDATE model_project_package_operations SET state = 'rejected' WHERE operation_id = ? AND state = 'pending'",[a])});return this.writeQueue=r.then(()=>{},()=>{}),r}async findModelProjectConfigurationSave(a){if(await this.ready,await this.writeQueue,!this.db)throw new Error("Model check failed because the local store is closed.");return W(this.db,a)}async saveModelProjectConfiguration(a){await this.ready;let r=this.writeQueue.then(async()=>{if(!this.db)throw new Error("Model save failed because the local store is closed.");let t=W(this.db,a);if(t)return t;let n=await $(this.db,this.home,a),e=Q(this.db,a,!0,n);if(e?.imported)await B({home:this.home,...e.imported});else if(e){let s=Ae.join(this.home,"training","tasksets",b(e.source));await J(this.home,e,e.directoryId,{source:{directory:s,packageHash:await ce(s)},verify:f(i=>Me(i,e.taskset),"verify")}),this.db.run("UPDATE model_project_taskset_preparations SET state = 'materialized' WHERE profile_id = ? AND operation_id = ?",[a.project.profileId,a.operationId])}return ye(this.db,a,e,n?.modelResources?{...n.modelResources,taskset:n.taskset,executionResources:{environment:n.environment,verifierSet:n.verifierSet}}:n)});return this.writeQueue=r.then(()=>{},()=>{}),r}async previewModelProjectTasksetSave(a){if(await this.ready,await this.writeQueue,!this.db)throw new Error("Model check failed because the local store is closed.");return Q(this.db,a,!1,await $(this.db,this.home,a))?.taskset??null}async findModelStarterCreation(a){if(await this.ready,await this.writeQueue,!this.db)throw new Error("Starter lookup failed because the local store is closed.");return O(this.db,a)}async saveModelStarterCreation(a){await this.ready;let r=this.writeQueue.then(async()=>{if(!this.db)throw new Error("Starter creation failed because the local store is closed.");let t=O(this.db,a.request);if(t)return t;let n=z(this.db,a),e=j(n);return await J(this.home,e,e.taskset.id),Re(this.db,n)});return this.writeQueue=r.then(()=>{},()=>{}),r}async prepareModelStarterCreation(a){if(await this.ready,await this.writeQueue,!this.db)throw new Error("Starter check failed because the local store is closed.");return j(z(this.db,a))}async saveModelProjectHosting(a,r,t=!1,n=[]){await this.ready;let e=this.writeQueue.then(async()=>{if(!this.db)throw new Error("Model synchronization failed because the local store is closed.");if(n.length&&!t)throw new Error("Package import requires an atomic Model replacement.");for(let s of n){if(s.taskset.profileId!==r.profileId)throw new Error("Imported package belongs to another Profile.");s.reuseExisting?await we(this.home,s.package):await B({home:this.home,...s})}return q(this.db,a,r,t,()=>{for(let s of n)Ee(this.db,s)})});return this.writeQueue=e.then(()=>{},()=>{}),e}};export{xe as SqliteModelConfigurationStore};
@@ -1,11 +1,11 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as J,e as Ee,f as ge,i as he,j as ye}from"./chunk-YY7LEQGP.js";import{A as m,B as ue,D as ce,E as k,F as le,b as W,f as oe,t as H,u as ae,w as de,x as pe}from"./chunk-3RCRSMWZ.js";import{c as _e}from"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import{a as se,c as x}from"./chunk-PSGGOZFM.js";import{Da as C,Ea as g,Fa as F,G as q,H as ee,Sa as ne,Ta as ie,Ua as L,Wa as re,Xa as O,b as A,rb as U,sa as te}from"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import{p as E,q as Z}from"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as G}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.js";import{z as b}from"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import{b as D}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{createPublicKey as Ae,verify as Ce}from"node:crypto";var me=`CREATE TABLE IF NOT EXISTS remote_device_authority (id INTEGER PRIMARY KEY CHECK(id=1), payload TEXT NOT NULL);
2
+ import{a as Ee,b as ge,c as he,e as U,h as ye,i as me,l as Se,m as Te}from"./chunk-5IPFI25K.js";import{A as m,B as ue,D as ce,E as f,F as le,b as W,f as se,t as oe,u as ae,w as de,x as pe}from"./chunk-TTVS6JMC.js";import{c as _e}from"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import{a as re,c as N}from"./chunk-PSGGOZFM.js";import{Da as A,Ea as g,Fa as b,G as q,H as Z,Sa as te,Ta as ne,Ua as L,Wa as ie,Xa as O,b as C,rb as F,sa as ee}from"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import{p as E,q as G}from"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as z}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.js";import{z as M}from"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import{b as D}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{createPublicKey as We,verify as He}from"node:crypto";var Re=`CREATE TABLE IF NOT EXISTS remote_device_authority (id INTEGER PRIMARY KEY CHECK(id=1), payload TEXT NOT NULL);
3
3
  CREATE TABLE IF NOT EXISTS remote_device_receipts (id TEXT PRIMARY KEY, payload_hash TEXT NOT NULL, command TEXT NOT NULL, receipt TEXT NOT NULL);
4
4
  CREATE TABLE IF NOT EXISTS remote_device_approval_claims (approval_id TEXT PRIMARY KEY, command_id TEXT NOT NULL UNIQUE);
5
- CREATE TABLE IF NOT EXISTS remote_device_cancellations (id TEXT PRIMARY KEY,payload_hash TEXT NOT NULL,device_id TEXT NOT NULL);`;function P(s,e,t){let n=s.get("SELECT payload_hash FROM remote_device_cancellations WHERE id=?",[e.id]);if(n)throw new Error(n.payload_hash===e.payloadHash?"remote_command_cancelled":"remote_command_identity_changed");let i=s.get("SELECT payload FROM remote_device_authority WHERE id=1");if(!i)throw new Error("remote_authority_unavailable");let r=JSON.parse(i.payload),o=Date.now();if(e.actor!=="remote-human"||r.deviceId!==e.deviceId||r.fence!==e.fence||r.grantRevision!==e.grantRevision||!(Date.parse(r.leaseExpiresAt)>o)||!(Date.parse(e.deadline)>o)||!(Date.parse(e.permit.expiresAt)>o))throw new Error("remote_authority_expired_or_changed");let a=se.parse(r.owner);if(q(e.scope)!==q({installationId:a.installationId,profileId:a.profileId,ownerUserId:a.ownerUserId,teamId:a.teamId})||!x(t,a))throw new Error("remote_task_not_owned");let d=r.publicKeys.find(I=>I.keyId===e.permit.keyId),{permit:p,...c}=e;if(!d||!Ce(null,Buffer.from(ee(c,p.expiresAt,p.keyId)),Ae(d.publicKey),Buffer.from(p.signature,"base64")))throw new Error("remote_permit_invalid");if(e.action==="start"){let I=t.metadata?.remoteStarterSourceSessionId,T=typeof I=="string"?s.get("SELECT payload FROM sessions WHERE id=?",[I]):null,l=T?JSON.parse(T.payload):null,N=W(t);if(!l||!x(l,a)||l.archived||l.status==="closed"||e.payload.projectId!==l.localProjectId||e.payload.starterRevision!==J(l)||e.expectedRevision!==J(l)||N?.operationId!==e.id||N.payloadHash!==e.payloadHash)throw new Error("remote_starter_changed");return}let _=s.get("SELECT id FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[t.id]),w=Number.parseInt(H(t,_?.id??null).slice(0,13),16);if(e.localSessionId!==t.id||w!==e.expectedRevision)throw new Error("remote_target_changed")}u(P,"assertRemoteAdmission");import{isDeepStrictEqual as Le}from"node:util";function S(s){return L.parse({...JSON.parse(s.payload),sequence:s.sequence})}u(S,"inputFromRow");function R(s,e){let t=s.get("SELECT sequence, payload FROM task_inputs WHERE id = ?",[e]);return t?S(t):null}u(R,"readTaskInput");function h(s,e){let t=L.parse(e);return s.run("UPDATE task_inputs SET kind = ?, state = ?, turn_id = ?, payload = ? WHERE id = ?",[t.kind,t.state,t.turnId,JSON.stringify(t),t.id]),t}u(h,"writeTaskInput");function y(s,e){return s.get("SELECT * FROM task_inbox_turns WHERE session_id = ?",[e])}u(y,"readInboxOwner");function f(s,e,t,n){let i=y(s,e);if(!i||i.turn_id!==t||i.owner_id!==n||i.lease_until<=Date.now())throw new Error("Task execution ownership was lost. Stop before dispatching more work.");return i}u(f,"requireInboxOwner");function j(s,e,t){let n=y(s,e),i=t?s.get("SELECT status FROM turns WHERE id = ? AND session_id = ?",[t,e]):null;if(!t||!n||n.turn_id!==t||!n.accepting||n.paused||n.lease_until<=Date.now()||i?.status!=="in_progress")throw new Error("The expected turn is no longer accepting input. Your text was not sent to a different turn; send it as a follow-up instead.")}u(j,"assertSteerTarget");function B(s,e){let t=`${e.senderKind}:${e.senderSessionId??"user"}`,n=s.get("SELECT sequence, payload, admission FROM task_inputs WHERE session_id = ? AND sender_key = ? AND idempotency_key = ?",[e.sessionId,t,e.idempotencyKey]);if(n){let _=S(n),w=JSON.parse(n.admission);if(["kind","body","payload","replyTo","expectedTurnId"].some(T=>!Le(w[T],e[T])))throw new Error("This input identity was already used with different content.");return _}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[e.sessionId]),r=i?JSON.parse(i.payload):null;if(!r||r.status==="closed"||r.archived)throw new Error("The recipient task is unavailable.");if(e.payload.remoteDevice!==void 0){if(e.senderKind!=="user"||e.senderSessionId!==null)throw new Error("remote_human_input_required");P(s,e.payload.remoteDevice,r)}if(e.senderKind==="ponder"||e.payload.ponderDesktop!==void 0){let _=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[e.sessionId]);le(s,e,r,_?.id??null)}let o=e.payload.localManagedMessage;if(o&&typeof o=="object"){let _=o.targetRevision,w=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[e.sessionId]);if(typeof _!="string"||_!==oe(r,w?.id??null))throw new ge("The managed target changed before message admission. Refresh and review the message before sending.")}let a=y(s,e.sessionId);if(e.kind==="steer"&&j(s,e.sessionId,e.expectedTurnId),e.kind==="steer"&&K(s,e.expectedTurnId,e.body),s.get("SELECT count(*) AS count FROM task_inputs WHERE session_id = ? AND state = 'pending'",[e.sessionId]).count>=ne)throw new Error("The task inbox is full. Wait for delivery before sending more input.");let p=new Date().toISOString(),c=L.parse({...e,sequence:0,revision:1,state:"pending",requestIds:[],error:null,payload:{...e.payload,...e.payload.remoteDevice?{remoteDeviceExecution:de(r)}:{}},turnId:e.kind!=="queued"&&e.kind!=="followup"&&a?.accepting&&!a.paused&&a.lease_until>Date.now()?a.turn_id:null,createdAt:p,updatedAt:p});return s.run("INSERT INTO task_inputs (id, session_id, sender_key, idempotency_key, kind, state, turn_id, payload, admission) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[c.id,c.sessionId,t,c.idempotencyKey,c.kind,c.state,c.turnId,JSON.stringify(c),JSON.stringify(e)]),R(s,c.id)}u(B,"admitTaskInput");function v(s,e,t){return s.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND state = 'pending'
5
+ CREATE TABLE IF NOT EXISTS remote_device_cancellations (id TEXT PRIMARY KEY,payload_hash TEXT NOT NULL,device_id TEXT NOT NULL);`;function P(s,e,t){if(e.payload.resume===!0&&e.action!=="follow_up")throw new Error("remote_resume_action_invalid");let n=s.get("SELECT payload_hash FROM remote_device_cancellations WHERE id=?",[e.id]);if(n)throw new Error(n.payload_hash===e.payloadHash?"remote_command_cancelled":"remote_command_identity_changed");let i=s.get("SELECT payload FROM remote_device_authority WHERE id=1");if(!i)throw new Error("remote_authority_unavailable");let r=JSON.parse(i.payload),o=Date.now();if(e.actor!=="remote-human"||r.deviceId!==e.deviceId||r.fence!==e.fence||r.grantRevision!==e.grantRevision||!(Date.parse(r.leaseExpiresAt)>o)||!(Date.parse(e.deadline)>o)||!(Date.parse(e.permit.expiresAt)>o))throw new Error("remote_authority_expired_or_changed");let a=re.parse(r.owner);if(q(e.scope)!==q({installationId:a.installationId,profileId:a.profileId,ownerUserId:a.ownerUserId,teamId:a.teamId})||!N(t,a))throw new Error("remote_task_not_owned");let d=r.publicKeys.find(I=>I.keyId===e.permit.keyId),{permit:p,...c}=e;if(!d||!He(null,Buffer.from(Z(c,p.expiresAt,p.keyId)),We(d.publicKey),Buffer.from(p.signature,"base64")))throw new Error("remote_permit_invalid");if(e.action==="start"){let I=t.metadata?.remoteStarterSourceSessionId,T=typeof I=="string"?s.get("SELECT payload FROM sessions WHERE id=?",[I]):null,_=T?JSON.parse(T.payload):null,x=W(t);if(!_||!N(_,a)||_.archived||_.status==="closed"||e.payload.projectId!==_.localProjectId||e.payload.starterRevision!==U(_)||e.expectedRevision!==U(_)||x?.operationId!==e.id||x.payloadHash!==e.payloadHash)throw new Error("remote_starter_changed");return}let l=s.get("SELECT id FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[t.id]),w=Ee(t,l?.id??null,ge(s,t.id));if(e.localSessionId!==t.id||w!==e.expectedRevision)throw new Error("remote_target_changed")}u(P,"assertRemoteAdmission");import{isDeepStrictEqual as Me}from"node:util";function S(s){return L.parse({...JSON.parse(s.payload),sequence:s.sequence})}u(S,"inputFromRow");function R(s,e){let t=s.get("SELECT sequence, payload FROM task_inputs WHERE id = ?",[e]);return t?S(t):null}u(R,"readTaskInput");function h(s,e){let t=L.parse(e);return s.run("UPDATE task_inputs SET kind = ?, state = ?, turn_id = ?, payload = ? WHERE id = ?",[t.kind,t.state,t.turnId,JSON.stringify(t),t.id]),t}u(h,"writeTaskInput");function y(s,e){return s.get("SELECT * FROM task_inbox_turns WHERE session_id = ?",[e])}u(y,"readInboxOwner");function k(s,e,t,n){let i=y(s,e);if(!i||i.turn_id!==t||i.owner_id!==n||i.lease_until<=Date.now())throw new Error("Task execution ownership was lost. Stop before dispatching more work.");return i}u(k,"requireInboxOwner");function J(s,e,t){let n=y(s,e),i=t?s.get("SELECT status FROM turns WHERE id = ? AND session_id = ?",[t,e]):null;if(!t||!n||n.turn_id!==t||!n.accepting||n.paused||n.lease_until<=Date.now()||i?.status!=="in_progress")throw new Error("The expected turn is no longer accepting input. Your text was not sent to a different turn; send it as a follow-up instead.")}u(J,"assertSteerTarget");function j(s,e){let t=`${e.senderKind}:${e.senderSessionId??"user"}`,n=s.get("SELECT sequence, payload, admission FROM task_inputs WHERE session_id = ? AND sender_key = ? AND idempotency_key = ?",[e.sessionId,t,e.idempotencyKey]);if(n){let l=S(n),w=JSON.parse(n.admission);if(["kind","body","payload","replyTo","expectedTurnId"].some(T=>!Me(w[T],e[T])))throw new Error("This input identity was already used with different content.");return l}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[e.sessionId]),r=i?JSON.parse(i.payload):null;if(!r||r.status==="closed"||r.archived)throw new Error("The recipient task is unavailable.");if(e.payload.remoteDevice!==void 0){if(e.senderKind!=="user"||e.senderSessionId!==null)throw new Error("remote_human_input_required");P(s,e.payload.remoteDevice,r)}if(e.senderKind==="ponder"||e.payload.ponderDesktop!==void 0){let l=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[e.sessionId]);le(s,e,r,l?.id??null)}let o=e.payload.localManagedMessage;if(o&&typeof o=="object"){let l=o.targetRevision,w=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[e.sessionId]);if(typeof l!="string"||l!==se(r,w?.id??null))throw new me("The managed target changed before message admission. Refresh and review the message before sending.")}let a=y(s,e.sessionId);if(e.kind==="steer"&&J(s,e.sessionId,e.expectedTurnId),e.kind==="steer"&&B(s,e.expectedTurnId,e.body),s.get("SELECT count(*) AS count FROM task_inputs WHERE session_id = ? AND state = 'pending'",[e.sessionId]).count>=te)throw new Error("The task inbox is full. Wait for delivery before sending more input.");let p=new Date().toISOString(),c=L.parse({...e,sequence:0,revision:1,state:"pending",requestIds:[],error:null,payload:{...e.payload,...e.payload.remoteDevice?{remoteDeviceExecution:de(r)}:{}},turnId:e.kind!=="queued"&&e.kind!=="followup"&&a?.accepting&&!a.paused&&a.lease_until>Date.now()?a.turn_id:null,createdAt:p,updatedAt:p});if(e.payload.remoteDevice!==void 0){let l=e.payload.remoteDevice;if(l.payload.resume===!0&&(e.kind!=="queued"||e.expectedTurnId!==l.expectedTurnId))throw new Error("remote_resume_input_invalid");he(s,l)}return s.run("INSERT INTO task_inputs (id, session_id, sender_key, idempotency_key, kind, state, turn_id, payload, admission) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[c.id,c.sessionId,t,c.idempotencyKey,c.kind,c.state,c.turnId,JSON.stringify(c),JSON.stringify(e)]),R(s,c.id)}u(j,"admitTaskInput");function v(s,e,t){return s.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND state = 'pending'
6
6
  AND ((turn_id = ?) OR (turn_id IS NULL AND kind NOT IN ('queued', 'followup', 'steer')))
7
- ORDER BY sequence`,[e,t]).map(S)}u(v,"pendingTaskInputs");function K(s,e,t){if(s.get(`SELECT COALESCE(SUM(length(json_extract(payload, '$.body'))), 0) AS size
8
- FROM task_inputs WHERE turn_id = ? AND kind = 'steer' AND state NOT IN ('rejected', 'cancelled')`,[e]).size+t.length>64e3)throw new Error("This turn's correction history is full. Finish it or send the additional instructions in a new turn.")}u(K,"assertCorrectionBudget");function Se(s,e){let t=s.all("SELECT session_id, turn_id FROM task_inbox_turns WHERE owner_id <> ? AND lease_until > 0",[e]),n=new Date().toISOString();for(let i of t){let r=s.get("SELECT status FROM turns WHERE id = ?",[i.turn_id]);s.run("UPDATE task_inbox_turns SET accepting = 0, paused = ?, lease_until = 0 WHERE session_id = ?",[r?1:0,i.session_id]);let o=s.all("SELECT sequence, payload FROM task_inputs WHERE turn_id = ? AND state IN ('pending', 'included')",[i.turn_id]);for(let a of o){let d=S(a);h(s,{...d,updatedAt:n,...d.state==="included"?{error:"Execution owner stopped after inclusion. The provider outcome is uncertain; review before retrying."}:d.kind==="steer"?{state:"rejected",error:"The interrupted execution did not include this correction. Send it as a follow-up."}:{turnId:null}})}s.run("UPDATE task_input_requests SET state = 'failed' WHERE turn_id = ? AND state = 'included'",[i.turn_id]);for(let a of s.all("SELECT id, payload FROM task_waits WHERE turn_id = ? AND state = 'waiting'",[i.turn_id])){let d=O.parse(JSON.parse(a.payload));s.run("UPDATE task_waits SET state = 'unavailable', payload = ? WHERE id = ?",[JSON.stringify({...d,state:"unavailable",updatedAt:n}),a.id])}}return t.map(i=>({sessionId:i.session_id,turnId:i.turn_id}))}u(Se,"recoverTaskInboxOwners");function Te(s,e,t){if(m(e),e.intent.action!=="create"||!e.claimId||e.receipt||!["dispatching","attention"].includes(e.state))return null;let n=ue(e.id),i=s.get("SELECT payload FROM sessions WHERE id = ?",[n]);if(!i||s.get("SELECT id FROM task_inputs WHERE session_id = ? LIMIT 1",[n])||s.get("SELECT id FROM turns WHERE session_id = ? LIMIT 1",[n]))return null;let r=E.parse(JSON.parse(i.payload)),o=W(r),a=s.get("SELECT payload FROM ponder_desktop_authority WHERE id = 1");if(!a||!o||!x(r,t)||r.archived||r.status!=="idle")return null;let d=C.parse(JSON.parse(a.payload));return d.state!=="attached"||Date.parse(d.leaseExpiresAt)<=Date.now()||d.authorizationRevision!==e.origin.authorizationRevision||!Object.entries(e.origin.scope).every(([p,c])=>d.scope[p]===c)||o.operationId!==e.id||o.payloadHash!==e.payloadHash||o.sessionRevision!==H(r,null)||o.executionRevision!==ae(r)?null:te.parse({sessionId:n,creationHash:o.creationHash,sessionRevision:o.sessionRevision,executionRevision:o.executionRevision})}u(Te,"readPonderDesktopReservationResume");var Re=D.object({operation:g,receipt:g.shape.receipt.unwrap()}).strict();function M(s,e){let t=s.get("SELECT payload FROM ponder_desktop_stops WHERE operation_id = ?",[e]);return t?Re.parse(JSON.parse(t.payload)):null}u(M,"readPonderDesktopStop");function Ie(s,e){if(e=g.parse(e),m(e),e.intent.action!=="stop")throw new Error("ponder_desktop_stop_intent_invalid");let t=M(s,e.id);if(t){if(t.operation.payloadHash!==e.payloadHash)throw new Error("ponder_desktop_stop_identity_reused");return t}let n=s.get("SELECT payload FROM sessions WHERE id = ?",[e.intent.targetId]);if(!n)throw new Error("ponder_desktop_stop_target_unavailable");let i=E.parse(JSON.parse(n.payload)),r=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[i.id]);k(s,e,i,r?.id??null,e.intent.targetRevision);let o=y(s,i.id),a=s.get("SELECT status FROM turns WHERE id = ? AND session_id = ?",[e.intent.expectedTurnId,i.id]);if(!o||o.turn_id!==e.intent.expectedTurnId||o.lease_until<=Date.now()||a?.status!=="in_progress")throw new Error("ponder_desktop_stop_target_changed");let d=Re.parse({operation:e,receipt:{sessionId:i.id,sessionTitle:i.title,inputId:null,turnId:e.intent.expectedTurnId,state:"stop_requested"}});return s.run("INSERT INTO ponder_desktop_stops (operation_id, payload_hash, payload) VALUES (?, ?, ?)",[e.id,e.payloadHash,JSON.stringify(d)]),d}u(Ie,"admitPonderDesktopStop");function we(s,e,t){let n=M(s,e);if(!n)throw new Error("ponder_desktop_stop_not_found");if(n.receipt.state!=="stop_requested")return n;let i={...n,receipt:{...n.receipt,state:t}};return s.run("UPDATE ponder_desktop_stops SET payload = ? WHERE operation_id = ?",[JSON.stringify(i),e]),i}u(we,"settlePonderDesktopStop");import{createHash as We}from"node:crypto";function Oe(s){return We("sha256").update(A("POST","/ponder/desktop/result",s)).digest("hex")}u(Oe,"hash");function Y(s,e,t){let n=s.get("SELECT payload, payload_hash FROM ponder_desktop_results WHERE operation_id = ? AND turn_id = ?",[e,t]);if(!n)return null;let i=F.parse(JSON.parse(n.payload));if(i.operationId!==e||i.turnId!==t||Oe(i)!==n.payload_hash)throw new Error("ponder_desktop_committed_result_invalid");return i}u(Y,"readPonderDesktopResult");function ke(s,e){let t=F.parse(e),n=Y(s,t.operationId,t.turnId);return n||(s.run("INSERT INTO ponder_desktop_results (operation_id, turn_id, payload_hash, payload) VALUES (?, ?, ?, ?)",[t.operationId,t.turnId,Oe(t),JSON.stringify(t)]),t)}u(ke,"commitPonderDesktopResult");var fe=D.object({operation:g,receipt:g.shape.receipt.unwrap()}).strict();function Q(s,e){let t=s.get("SELECT payload, payload_hash FROM ponder_desktop_observations WHERE operation_id = ?",[e]);if(!t)return null;let n=fe.parse(JSON.parse(t.payload));if(m(n.operation),n.operation.id!==e||n.operation.payloadHash!==t.payload_hash||n.operation.intent.action!=="observe"||n.receipt.turnId!==n.operation.intent.expectedTurnId||n.receipt.sessionId!==n.operation.intent.targetId||n.receipt.inputId!==null)throw new Error("ponder_desktop_observation_record_invalid");return n}u(Q,"readPonderDesktopObservation");function De(s,e){let t=g.parse(e);if(m(t),t.intent.action!=="observe")throw new Error("ponder_desktop_observation_intent_invalid");let n=Q(s,t.id);if(n){if(n.operation.payloadHash!==t.payloadHash)throw new Error("ponder_desktop_observation_identity_reused");return n}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[t.intent.targetId]);if(!i)throw new Error("ponder_desktop_observation_target_unavailable");let r=E.parse(JSON.parse(i.payload)),o=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[r.id]);k(s,t,r,o?.id??null,t.intent.targetRevision);let a=s.get("SELECT id FROM turns WHERE id = ? AND session_id = ?",[t.intent.expectedTurnId,r.id]);if(!a||o?.id!==a.id)throw new Error("ponder_desktop_observation_target_changed");let d=fe.parse({operation:t,receipt:{sessionId:r.id,sessionTitle:r.title,inputId:null,turnId:a.id,state:"observing"}});return s.run("INSERT INTO ponder_desktop_observations (operation_id, payload_hash, payload) VALUES (?, ?, ?)",[t.id,t.payloadHash,JSON.stringify(d)]),d}u(De,"admitPonderDesktopObservation");import{createHash as He}from"node:crypto";var ve=D.object({operation:g,receipt:g.shape.receipt.unwrap(),inspection:U}).strict();function Ne(s){return He("sha256").update(A("POST","/ponder/desktop/inspection",s)).digest("hex")}u(Ne,"snapshotHash");function V(s,e){let t=s.get("SELECT payload, payload_hash, snapshot_hash FROM ponder_desktop_inspections WHERE operation_id = ?",[e]);if(!t)return null;let n=ve.parse(JSON.parse(t.payload));m(n.operation);let{operation:i,receipt:r,inspection:o}=n;if(i.intent.action!=="inspect"||i.id!==e||i.payloadHash!==t.payload_hash||Ne(n)!==t.snapshot_hash||o.operationId!==e||o.payloadHash!==i.payloadHash||o.sessionId!==i.intent.targetId||o.turnId!==i.intent.expectedTurnId||r.sessionId!==o.sessionId||r.turnId!==o.turnId||r.inputId!==null||r.state!=="inspected")throw new Error("ponder_desktop_inspection_record_invalid");return n}u(V,"readPonderDesktopInspection");function xe(s,e){let t=g.parse(e);if(m(t),t.intent.action!=="inspect")throw new Error("ponder_desktop_inspection_intent_invalid");let n=V(s,t.id);if(n){if(n.operation.payloadHash!==t.payloadHash)throw new Error("ponder_desktop_inspection_identity_reused");return n}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[t.intent.targetId]);if(!i)throw new Error("ponder_desktop_inspection_target_unavailable");let r=E.parse(JSON.parse(i.payload)),o=r.localProjectId??r.workspaceId??r.cwd;if(r.archived||r.systemKind||r.hiddenFromDefaultSidebar||r.status==="closed"||r.experience==="development"||["sandbox","sandbox_template","sandbox_app"].includes(r.workspaceKind??"")||t.target.kind!=="session"||t.target.id!==r.id||t.target.revision!==t.intent.targetRevision||t.target.workspaceId!==o||t.target.providerId!==r.provider||t.target.modelId!==(r.modelRef?.modelId??null))throw new Error("ponder_desktop_inspection_target_changed");let a=s.get("SELECT id, payload FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[r.id]);if(k(s,t,r,a?.id??null,t.intent.targetRevision),!a||a.id!==t.intent.expectedTurnId)throw new Error("ponder_desktop_inspection_target_changed");let d=Z.parse(JSON.parse(a.payload));if(d.sessionId!==r.id||d.id!==a.id)throw new Error("ponder_desktop_inspection_turn_invalid");let p=s.all(`
7
+ ORDER BY sequence`,[e,t]).map(S)}u(v,"pendingTaskInputs");function B(s,e,t){if(s.get(`SELECT COALESCE(SUM(length(json_extract(payload, '$.body'))), 0) AS size
8
+ FROM task_inputs WHERE turn_id = ? AND kind = 'steer' AND state NOT IN ('rejected', 'cancelled')`,[e]).size+t.length>64e3)throw new Error("This turn's correction history is full. Finish it or send the additional instructions in a new turn.")}u(B,"assertCorrectionBudget");function Ie(s,e){let t=s.all("SELECT session_id, turn_id FROM task_inbox_turns WHERE owner_id <> ? AND lease_until > 0",[e]),n=new Date().toISOString();for(let i of t){let r=s.get("SELECT status FROM turns WHERE id = ?",[i.turn_id]);s.run("UPDATE task_inbox_turns SET accepting = 0, paused = ?, lease_until = 0 WHERE session_id = ?",[r?1:0,i.session_id]);let o=s.all("SELECT sequence, payload FROM task_inputs WHERE turn_id = ? AND state IN ('pending', 'included')",[i.turn_id]);for(let a of o){let d=S(a);h(s,{...d,updatedAt:n,...d.state==="included"?{error:"Execution owner stopped after inclusion. The provider outcome is uncertain; review before retrying."}:d.kind==="steer"?{state:"rejected",error:"The interrupted execution did not include this correction. Send it as a follow-up."}:{turnId:null}})}s.run("UPDATE task_input_requests SET state = 'failed' WHERE turn_id = ? AND state = 'included'",[i.turn_id]);for(let a of s.all("SELECT id, payload FROM task_waits WHERE turn_id = ? AND state = 'waiting'",[i.turn_id])){let d=O.parse(JSON.parse(a.payload));s.run("UPDATE task_waits SET state = 'unavailable', payload = ? WHERE id = ?",[JSON.stringify({...d,state:"unavailable",updatedAt:n}),a.id])}}return t.map(i=>({sessionId:i.session_id,turnId:i.turn_id}))}u(Ie,"recoverTaskInboxOwners");function we(s,e,t){if(m(e),e.intent.action!=="create"||!e.claimId||e.receipt||!["dispatching","attention"].includes(e.state))return null;let n=ue(e.id),i=s.get("SELECT payload FROM sessions WHERE id = ?",[n]);if(!i||s.get("SELECT id FROM task_inputs WHERE session_id = ? LIMIT 1",[n])||s.get("SELECT id FROM turns WHERE session_id = ? LIMIT 1",[n]))return null;let r=E.parse(JSON.parse(i.payload)),o=W(r),a=s.get("SELECT payload FROM ponder_desktop_authority WHERE id = 1");if(!a||!o||!N(r,t)||r.archived||r.status!=="idle")return null;let d=A.parse(JSON.parse(a.payload));return d.state!=="attached"||Date.parse(d.leaseExpiresAt)<=Date.now()||d.authorizationRevision!==e.origin.authorizationRevision||!Object.entries(e.origin.scope).every(([p,c])=>d.scope[p]===c)||o.operationId!==e.id||o.payloadHash!==e.payloadHash||o.sessionRevision!==oe(r,null)||o.executionRevision!==ae(r)?null:ee.parse({sessionId:n,creationHash:o.creationHash,sessionRevision:o.sessionRevision,executionRevision:o.executionRevision})}u(we,"readPonderDesktopReservationResume");var Oe=D.object({operation:g,receipt:g.shape.receipt.unwrap()}).strict();function H(s,e){let t=s.get("SELECT payload FROM ponder_desktop_stops WHERE operation_id = ?",[e]);return t?Oe.parse(JSON.parse(t.payload)):null}u(H,"readPonderDesktopStop");function fe(s,e){if(e=g.parse(e),m(e),e.intent.action!=="stop")throw new Error("ponder_desktop_stop_intent_invalid");let t=H(s,e.id);if(t){if(t.operation.payloadHash!==e.payloadHash)throw new Error("ponder_desktop_stop_identity_reused");return t}let n=s.get("SELECT payload FROM sessions WHERE id = ?",[e.intent.targetId]);if(!n)throw new Error("ponder_desktop_stop_target_unavailable");let i=E.parse(JSON.parse(n.payload)),r=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[i.id]);f(s,e,i,r?.id??null,e.intent.targetRevision);let o=y(s,i.id),a=s.get("SELECT status FROM turns WHERE id = ? AND session_id = ?",[e.intent.expectedTurnId,i.id]);if(!o||o.turn_id!==e.intent.expectedTurnId||o.lease_until<=Date.now()||a?.status!=="in_progress")throw new Error("ponder_desktop_stop_target_changed");let d=Oe.parse({operation:e,receipt:{sessionId:i.id,sessionTitle:i.title,inputId:null,turnId:e.intent.expectedTurnId,state:"stop_requested"}});return s.run("INSERT INTO ponder_desktop_stops (operation_id, payload_hash, payload) VALUES (?, ?, ?)",[e.id,e.payloadHash,JSON.stringify(d)]),d}u(fe,"admitPonderDesktopStop");function ke(s,e,t){let n=H(s,e);if(!n)throw new Error("ponder_desktop_stop_not_found");if(n.receipt.state!=="stop_requested")return n;let i={...n,receipt:{...n.receipt,state:t}};return s.run("UPDATE ponder_desktop_stops SET payload = ? WHERE operation_id = ?",[JSON.stringify(i),e]),i}u(ke,"settlePonderDesktopStop");import{createHash as qe}from"node:crypto";function De(s){return qe("sha256").update(C("POST","/ponder/desktop/result",s)).digest("hex")}u(De,"hash");function K(s,e,t){let n=s.get("SELECT payload, payload_hash FROM ponder_desktop_results WHERE operation_id = ? AND turn_id = ?",[e,t]);if(!n)return null;let i=b.parse(JSON.parse(n.payload));if(i.operationId!==e||i.turnId!==t||De(i)!==n.payload_hash)throw new Error("ponder_desktop_committed_result_invalid");return i}u(K,"readPonderDesktopResult");function ve(s,e){let t=b.parse(e),n=K(s,t.operationId,t.turnId);return n||(s.run("INSERT INTO ponder_desktop_results (operation_id, turn_id, payload_hash, payload) VALUES (?, ?, ?, ?)",[t.operationId,t.turnId,De(t),JSON.stringify(t)]),t)}u(ve,"commitPonderDesktopResult");var xe=D.object({operation:g,receipt:g.shape.receipt.unwrap()}).strict();function Y(s,e){let t=s.get("SELECT payload, payload_hash FROM ponder_desktop_observations WHERE operation_id = ?",[e]);if(!t)return null;let n=xe.parse(JSON.parse(t.payload));if(m(n.operation),n.operation.id!==e||n.operation.payloadHash!==t.payload_hash||n.operation.intent.action!=="observe"||n.receipt.turnId!==n.operation.intent.expectedTurnId||n.receipt.sessionId!==n.operation.intent.targetId||n.receipt.inputId!==null)throw new Error("ponder_desktop_observation_record_invalid");return n}u(Y,"readPonderDesktopObservation");function Ne(s,e){let t=g.parse(e);if(m(t),t.intent.action!=="observe")throw new Error("ponder_desktop_observation_intent_invalid");let n=Y(s,t.id);if(n){if(n.operation.payloadHash!==t.payloadHash)throw new Error("ponder_desktop_observation_identity_reused");return n}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[t.intent.targetId]);if(!i)throw new Error("ponder_desktop_observation_target_unavailable");let r=E.parse(JSON.parse(i.payload)),o=s.get("SELECT id FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[r.id]);f(s,t,r,o?.id??null,t.intent.targetRevision);let a=s.get("SELECT id FROM turns WHERE id = ? AND session_id = ?",[t.intent.expectedTurnId,r.id]);if(!a||o?.id!==a.id)throw new Error("ponder_desktop_observation_target_changed");let d=xe.parse({operation:t,receipt:{sessionId:r.id,sessionTitle:r.title,inputId:null,turnId:a.id,state:"observing"}});return s.run("INSERT INTO ponder_desktop_observations (operation_id, payload_hash, payload) VALUES (?, ?, ?)",[t.id,t.payloadHash,JSON.stringify(d)]),d}u(Ne,"admitPonderDesktopObservation");import{createHash as be}from"node:crypto";var Pe=D.object({operation:g,receipt:g.shape.receipt.unwrap(),inspection:F}).strict();function Ce(s){return be("sha256").update(C("POST","/ponder/desktop/inspection",s)).digest("hex")}u(Ce,"snapshotHash");function Q(s,e){let t=s.get("SELECT payload, payload_hash, snapshot_hash FROM ponder_desktop_inspections WHERE operation_id = ?",[e]);if(!t)return null;let n=Pe.parse(JSON.parse(t.payload));m(n.operation);let{operation:i,receipt:r,inspection:o}=n;if(i.intent.action!=="inspect"||i.id!==e||i.payloadHash!==t.payload_hash||Ce(n)!==t.snapshot_hash||o.operationId!==e||o.payloadHash!==i.payloadHash||o.sessionId!==i.intent.targetId||o.turnId!==i.intent.expectedTurnId||r.sessionId!==o.sessionId||r.turnId!==o.turnId||r.inputId!==null||r.state!=="inspected")throw new Error("ponder_desktop_inspection_record_invalid");return n}u(Q,"readPonderDesktopInspection");function Ae(s,e){let t=g.parse(e);if(m(t),t.intent.action!=="inspect")throw new Error("ponder_desktop_inspection_intent_invalid");let n=Q(s,t.id);if(n){if(n.operation.payloadHash!==t.payloadHash)throw new Error("ponder_desktop_inspection_identity_reused");return n}let i=s.get("SELECT payload FROM sessions WHERE id = ?",[t.intent.targetId]);if(!i)throw new Error("ponder_desktop_inspection_target_unavailable");let r=E.parse(JSON.parse(i.payload)),o=r.localProjectId??r.workspaceId??r.cwd;if(r.archived||r.systemKind||r.hiddenFromDefaultSidebar||r.status==="closed"||r.experience==="development"||["sandbox","sandbox_template","sandbox_app"].includes(r.workspaceKind??"")||t.target.kind!=="session"||t.target.id!==r.id||t.target.revision!==t.intent.targetRevision||t.target.workspaceId!==o||t.target.providerId!==r.provider||t.target.modelId!==(r.modelRef?.modelId??null))throw new Error("ponder_desktop_inspection_target_changed");let a=s.get("SELECT id, payload FROM turns WHERE session_id = ? ORDER BY sort_index DESC LIMIT 1",[r.id]);if(f(s,t,r,a?.id??null,t.intent.targetRevision),!a||a.id!==t.intent.expectedTurnId)throw new Error("ponder_desktop_inspection_target_changed");let d=G.parse(JSON.parse(a.payload));if(d.sessionId!==r.id||d.id!==a.id)throw new Error("ponder_desktop_inspection_turn_invalid");let p=s.all(`
9
9
  SELECT sequence, substr(json_extract(payload, '$.id'), 1, 201) AS id,
10
10
  substr(json_extract(payload, '$.timestamp'), 1, 101) AS timestamp, name AS kind,
11
11
  substr(json_extract(payload, '$.output'), 1, 4001) AS text,
@@ -17,17 +17,17 @@ import{b as J,e as Ee,f as ge,i as he,j as ye}from"./chunk-YY7LEQGP.js";import{A
17
17
  AND name IN ('assistant.delta', 'tool.started', 'tool.completed')
18
18
  AND coalesce(json_extract(payload, '$.data.retainedHistory'), 0) <> 1
19
19
  AND coalesce(json_extract(payload, '$.data.phase'), '') NOT IN ('reasoning', 'analysis')
20
- ORDER BY sequence DESC LIMIT 101`,[d.id,r.id]),c=16e3,_=!1,w=p.slice(0,100).map(l=>{let N=l.text??"",$=Math.min(4e3,c),z=N.slice(0,$);return c-=z.length,_||=N.length>$,{id:l.id,sequence:l.sequence,timestamp:l.timestamp,kind:l.kind,text:z,action:l.action,status:l.status,messageId:l.message_id,messageSnapshot:l.message_snapshot===1}}).reverse(),I=U.parse({operationId:t.id,payloadHash:t.payloadHash,sessionId:r.id,sessionTitle:r.title.slice(0,300),turnId:d.id,workspaceId:o,providerId:d.modelRef?.providerId??t.target.providerId,modelId:d.modelRef?.modelId??t.target.modelId,capturedAt:new Date().toISOString(),taskStatus:d.status,taskCompletedAt:d.completedAt?new Date(d.completedAt).toISOString():null,error:d.error?.slice(0,2e3)??null,events:w,coverage:{olderEventsOmitted:p.length>100,textTruncated:_,textLimit:16e3,eventLimit:100}}),T=ve.parse({operation:t,inspection:I,receipt:{sessionId:r.id,sessionTitle:I.sessionTitle,inputId:null,turnId:d.id,state:"inspected"}});return k(s,t,r,a.id,t.intent.targetRevision),s.run("INSERT INTO ponder_desktop_inspections (operation_id, payload_hash, snapshot_hash, payload) VALUES (?, ?, ?, ?)",[t.id,t.payloadHash,Ne(T),JSON.stringify(T)]),T}u(xe,"admitPonderDesktopInspection");var X=9e4,Pe=class extends G{static{u(this,"SqliteTaskInboxStore")}async initializeRemoteDeviceStore(){return this.inboxWrite(e=>{e.exec(me),e.run("DELETE FROM remote_device_authority")})}async setRemoteDeviceAuthority(e){return this.inboxWrite(t=>{e?t.run("INSERT INTO remote_device_authority(id,payload) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload",[JSON.stringify(e)]):t.run("DELETE FROM remote_device_authority")})}async getRemoteDeviceReceipt(e){await this.ready,await this.writeQueue;let t=this.database.get("SELECT receipt FROM remote_device_receipts WHERE id=?",[e]);return t?JSON.parse(t.receipt):null}async getRemoteDeviceCancellation(e){return await this.ready,await this.writeQueue,this.database.get("SELECT payload_hash,device_id FROM remote_device_cancellations WHERE id=?",[e])}async cancelRemoteDeviceCommand(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e]);if(i){if(i.payload_hash!==t)throw new Error("remote_command_identity_changed");return{receipt:JSON.parse(i.receipt),cancelled:!1}}let r=R(n,`remote-input:${e}`);if(r){let p=r.payload.remoteDevice;if(p.payloadHash!==t)throw new Error("remote_command_identity_changed");return{receipt:{id:e,deviceId:p.deviceId,payloadHash:t,action:p.action,targetId:p.targetId,localSessionId:r.sessionId,inputId:r.id,state:"admitted",revision:2,createdAt:r.createdAt,expiresAt:p.deadline},cancelled:!1}}let o=n.get("SELECT payload FROM remote_device_authority WHERE id=1");if(!o)throw new Error("remote_authority_unavailable");let a=JSON.parse(o.payload);if(!(Date.parse(a.leaseExpiresAt)>Date.now()))throw new Error("remote_authority_unavailable");let d=n.get("SELECT payload_hash FROM remote_device_cancellations WHERE id=?",[e]);if(d&&d.payload_hash!==t)throw new Error("remote_command_identity_changed");return n.run("INSERT INTO remote_device_cancellations(id,payload_hash,device_id) VALUES(?,?,?) ON CONFLICT(id) DO NOTHING",[e,t,a.deviceId]),{receipt:null,cancelled:!0}})}async saveRemoteDeviceReceipt(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload_hash FROM remote_device_receipts WHERE id=?",[e.id]);if(i&&i.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");n.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET receipt=excluded.receipt",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(t)])})}async admitRemoteDeviceStop(e){return this.inboxWrite(t=>{let n=t.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e.id]);if(n){if(n.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");return JSON.parse(n.receipt)}let i=t.get("SELECT payload FROM sessions WHERE id=?",[e.localSessionId]);if(!i)throw new Error("remote_task_unavailable");let r=E.parse(JSON.parse(i.payload));P(t,e,r);let o=t.get("SELECT id,status FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[e.localSessionId]);if(!e.expectedTurnId||o?.id!==e.expectedTurnId||o.status!=="in_progress")throw new Error("remote_turn_changed");let a={id:e.id,deviceId:e.deviceId,payloadHash:e.payloadHash,action:e.action,targetId:e.targetId,localSessionId:r.id,turnId:o.id,state:"admitted",revision:2,createdAt:new Date().toISOString(),expiresAt:e.deadline};return t.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?)",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(a)]),a})}async admitRemoteDeviceApproval(e){return this.inboxWrite(t=>{let n=t.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e.id]);if(n){if(n.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");return JSON.parse(n.receipt)}let i=t.get("SELECT payload FROM sessions WHERE id=?",[e.localSessionId]);if(!i)throw new Error("remote_task_unavailable");let r=E.parse(JSON.parse(i.payload));P(t,e,r);let o=t.get("SELECT id,payload FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[r.id]),a=o?JSON.parse(o.payload):null;if(!a||a.id!==e.expectedTurnId||a.status!=="in_progress")throw new Error("remote_turn_changed");let d=t.get("SELECT payload FROM approvals WHERE id=?",[e.expectedApprovalId]),p=d?JSON.parse(d.payload):null;if(!p||p.status!=="pending"||p.sessionId!==r.id||!p.turnId||p.turnId!==a.id&&p.turnId!==a.providerTurnId||!Ee(p))throw new Error("remote_approval_changed_or_unsupported");if(t.get("SELECT command_id FROM remote_device_approval_claims WHERE approval_id=?",[p.id]))throw new Error("remote_approval_already_claimed");t.run("INSERT INTO remote_device_approval_claims(approval_id,command_id) VALUES(?,?)",[p.id,e.id]);let _={id:e.id,deviceId:e.deviceId,payloadHash:e.payloadHash,action:e.action,targetId:e.targetId,localSessionId:r.id,approvalId:p.id,turnId:a.id,state:"admitted",revision:2,createdAt:new Date().toISOString(),expiresAt:e.deadline};return t.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?)",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(_)]),_})}async admitPonderDesktopInspection(e){return this.inboxWrite(t=>xe(t,e))}async getPonderDesktopInspection(e){return await this.ready,await this.writeQueue,V(this.database,e)}async setPonderProjectSharing(e){return this.inboxWrite(t=>he(t,e))}async readPonderProjectSharing(e){return await this.ready,await this.writeQueue,ye(this.database,e)}async getPonderDesktopReservationResume(e,t){return this.inboxWrite(n=>Te(n,e,t))}async admitPonderDesktopObservation(e){return this.inboxWrite(t=>De(t,e))}async getPonderDesktopObservation(e){return await this.ready,await this.writeQueue,Q(this.database,e)}async getPonderDesktopResult(e,t){return await this.ready,await this.writeQueue,Y(this.database,e,t)}async commitPonderDesktopResult(e){return this.inboxWrite(t=>ke(t,e))}async inboxWrite(e){await this.ready;let t=this.writeQueue.then(()=>{let n=this.database;n.exec("BEGIN IMMEDIATE");try{let i=e(n);return n.exec("COMMIT"),i}catch(i){throw n.exec("ROLLBACK"),i}});return this.writeQueue=t.then(()=>{},()=>{}),t}async setPonderDesktopAuthority(e){let t=C.parse(e);if(t.state!=="attached"||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("ponder_desktop_local_authority_invalid");return this.inboxWrite(n=>{n.run("INSERT INTO ponder_desktop_authority (id, runtime_id, payload) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET runtime_id = excluded.runtime_id, payload = excluded.payload",[t.runtimeId,JSON.stringify(t)])})}async clearPonderDesktopAuthority(e){return this.inboxWrite(t=>{e?t.run("DELETE FROM ponder_desktop_authority WHERE runtime_id = ?",[e]):t.run("DELETE FROM ponder_desktop_authority")})}async admitPonderDesktopStop(e){return this.inboxWrite(t=>Ie(t,e))}async getPonderDesktopStop(e){return await this.ready,await this.writeQueue,M(this.database,e)}async settlePonderDesktopStop(e,t){return this.inboxWrite(n=>we(n,e,t))}async recoverTaskInboxOwners(e){return this.inboxWrite(t=>Se(t,e))}async hasTaskCompletion(e){return await this.ready,await this.writeQueue,!!this.database.get("SELECT turn_id FROM task_completion_outbox WHERE turn_id = ?",[e])}async taskInboxSnapshot(e){await this.ready,await this.writeQueue;let t=y(this.database,e),n=t&&t.lease_until>Date.now()&&this.database.get("SELECT status FROM turns WHERE id = ?",[t.turn_id])?.status==="in_progress",i=this.database.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND (state IN ('pending', 'included')
21
- OR sequence IN (SELECT sequence FROM task_inputs WHERE session_id = ? ORDER BY sequence DESC LIMIT 30)) ORDER BY sequence`,[e,e]);return{sessionId:e,activeTurnId:n?t.turn_id:null,acceptingInput:!!(n&&t.accepting&&!t.paused),paused:!!t?.paused,inputs:i.map(S),waits:await this.taskWaitsForSession(e)}}async declareTaskWork(e,t,n,i){return this.inboxWrite(r=>{f(r,e,t,n),r.run("INSERT INTO task_work_claims (session_id, turn_id, work_areas) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id, work_areas = excluded.work_areas",[e,t,JSON.stringify(i)])})}async taskWorkAreas(e){await this.ready,await this.writeQueue;let t=this.database.get("SELECT c.work_areas FROM task_work_claims c JOIN task_inbox_turns t ON c.session_id = t.session_id AND c.turn_id = t.turn_id WHERE c.session_id = ? AND t.lease_until > ?",[e,Date.now()]);return t?JSON.parse(t.work_areas):[]}async admitTaskInput(e){return this.inboxWrite(t=>B(t,e))}async admitTaskInputs(e){return this.inboxWrite(t=>e.map(n=>B(t,n)))}async rejectTaskInput(e,t,n){return this.inboxWrite(i=>{let r=R(i,e);if(r?.state==="pending"){let o=n&&r.senderKind==="ponder"?i.get("SELECT id FROM turns WHERE id = ? AND session_id = ? AND json_extract(payload, '$.metadata.taskInputId') = ?",[n,r.sessionId,r.id]):null;h(i,{...r,state:"rejected",error:t,...o?{turnId:o.id}:{},updatedAt:new Date().toISOString()})}})}async getTaskInput(e){return await this.ready,await this.writeQueue,R(this.database,e)}async taskInputsForSession(e,t={}){return await this.ready,await this.writeQueue,this.database.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND sequence > ?
22
- ${t.pendingOnly?"AND state = 'pending'":""} ORDER BY sequence LIMIT ?`,[e,t.afterSequence??0,Math.max(1,Math.min(500,t.limit??128))]).map(S)}async mutateTaskInput(e,t,n){let i=re.parse(n);return this.inboxWrite(r=>{let o=R(r,t);if(!o||o.sessionId!==e||o.senderKind!=="user")throw new Error("Queued user input not found.");if(o.state!=="pending"||o.revision!==i.expectedRevision||o.turnId)throw new Error("This input changed or has already been admitted. Refresh the queue before editing it.");if(i.action==="resume"){if(o.kind!=="queued")throw new Error("Only the user queue can be resumed here.");let a=y(r,e);if(a&&a.lease_until>Date.now())throw new Error("This task is already running.");r.run("UPDATE task_inbox_turns SET paused = 0 WHERE session_id = ?",[e])}return i.action==="steer"&&(j(r,e,i.expectedTurnId),K(r,i.expectedTurnId,o.body)),h(r,{...o,revision:o.revision+1,updatedAt:new Date().toISOString(),...i.action==="cancel"?{state:"cancelled"}:{},...i.action==="edit"?{body:i.body,payload:{...o.payload,prompt:i.body}}:{},...i.action==="steer"?{kind:"steer",expectedTurnId:i.expectedTurnId,turnId:i.expectedTurnId}:{}})})}async openTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{let r=y(i,e);if(r&&r.lease_until>Date.now()&&(r.turn_id!==t||r.owner_id!==n))throw new Error("A turn is already running for this task.");i.run(`INSERT INTO task_inbox_turns (session_id, turn_id, owner_id, generation, accepting, paused, lease_until)
20
+ ORDER BY sequence DESC LIMIT 101`,[d.id,r.id]),c=16e3,l=!1,w=p.slice(0,100).map(_=>{let x=_.text??"",X=Math.min(4e3,c),$=x.slice(0,X);return c-=$.length,l||=x.length>X,{id:_.id,sequence:_.sequence,timestamp:_.timestamp,kind:_.kind,text:$,action:_.action,status:_.status,messageId:_.message_id,messageSnapshot:_.message_snapshot===1}}).reverse(),I=F.parse({operationId:t.id,payloadHash:t.payloadHash,sessionId:r.id,sessionTitle:r.title.slice(0,300),turnId:d.id,workspaceId:o,providerId:d.modelRef?.providerId??t.target.providerId,modelId:d.modelRef?.modelId??t.target.modelId,capturedAt:new Date().toISOString(),taskStatus:d.status,taskCompletedAt:d.completedAt?new Date(d.completedAt).toISOString():null,error:d.error?.slice(0,2e3)??null,events:w,coverage:{olderEventsOmitted:p.length>100,textTruncated:l,textLimit:16e3,eventLimit:100}}),T=Pe.parse({operation:t,inspection:I,receipt:{sessionId:r.id,sessionTitle:I.sessionTitle,inputId:null,turnId:d.id,state:"inspected"}});return f(s,t,r,a.id,t.intent.targetRevision),s.run("INSERT INTO ponder_desktop_inspections (operation_id, payload_hash, snapshot_hash, payload) VALUES (?, ?, ?, ?)",[t.id,t.payloadHash,Ce(T),JSON.stringify(T)]),T}u(Ae,"admitPonderDesktopInspection");var V=9e4,Le=class extends z{static{u(this,"SqliteTaskInboxStore")}async initializeRemoteDeviceStore(){return this.inboxWrite(e=>{e.exec(Re),e.run("DELETE FROM remote_device_authority")})}async setRemoteDeviceAuthority(e){return this.inboxWrite(t=>{e?t.run("INSERT INTO remote_device_authority(id,payload) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload",[JSON.stringify(e)]):t.run("DELETE FROM remote_device_authority")})}async getRemoteDeviceReceipt(e){await this.ready,await this.writeQueue;let t=this.database.get("SELECT receipt FROM remote_device_receipts WHERE id=?",[e]);return t?JSON.parse(t.receipt):null}async getRemoteDeviceCancellation(e){return await this.ready,await this.writeQueue,this.database.get("SELECT payload_hash,device_id FROM remote_device_cancellations WHERE id=?",[e])}async cancelRemoteDeviceCommand(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e]);if(i){if(i.payload_hash!==t)throw new Error("remote_command_identity_changed");return{receipt:JSON.parse(i.receipt),cancelled:!1}}let r=R(n,`remote-input:${e}`);if(r){let p=r.payload.remoteDevice;if(p.payloadHash!==t)throw new Error("remote_command_identity_changed");return{receipt:{id:e,deviceId:p.deviceId,payloadHash:t,action:p.action,targetId:p.targetId,localSessionId:r.sessionId,inputId:r.id,state:"admitted",revision:2,createdAt:r.createdAt,expiresAt:p.deadline},cancelled:!1}}let o=n.get("SELECT payload FROM remote_device_authority WHERE id=1");if(!o)throw new Error("remote_authority_unavailable");let a=JSON.parse(o.payload);if(!(Date.parse(a.leaseExpiresAt)>Date.now()))throw new Error("remote_authority_unavailable");let d=n.get("SELECT payload_hash FROM remote_device_cancellations WHERE id=?",[e]);if(d&&d.payload_hash!==t)throw new Error("remote_command_identity_changed");return n.run("INSERT INTO remote_device_cancellations(id,payload_hash,device_id) VALUES(?,?,?) ON CONFLICT(id) DO NOTHING",[e,t,a.deviceId]),{receipt:null,cancelled:!0}})}async saveRemoteDeviceReceipt(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload_hash FROM remote_device_receipts WHERE id=?",[e.id]);if(i&&i.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");n.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET receipt=excluded.receipt",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(t)])})}async admitRemoteDeviceStop(e){return this.inboxWrite(t=>{let n=t.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e.id]);if(n){if(n.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");return JSON.parse(n.receipt)}let i=t.get("SELECT payload FROM sessions WHERE id=?",[e.localSessionId]);if(!i)throw new Error("remote_task_unavailable");let r=E.parse(JSON.parse(i.payload));P(t,e,r);let o=t.get("SELECT id,status FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[e.localSessionId]);if(!e.expectedTurnId||o?.id!==e.expectedTurnId||o.status!=="in_progress")throw new Error("remote_turn_changed");let a={id:e.id,deviceId:e.deviceId,payloadHash:e.payloadHash,action:e.action,targetId:e.targetId,localSessionId:r.id,turnId:o.id,state:"admitted",revision:2,createdAt:new Date().toISOString(),expiresAt:e.deadline};return t.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?)",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(a)]),a})}async admitRemoteDeviceApproval(e){return this.inboxWrite(t=>{let n=t.get("SELECT payload_hash,receipt FROM remote_device_receipts WHERE id=?",[e.id]);if(n){if(n.payload_hash!==e.payloadHash)throw new Error("remote_command_identity_changed");return JSON.parse(n.receipt)}let i=t.get("SELECT payload FROM sessions WHERE id=?",[e.localSessionId]);if(!i)throw new Error("remote_task_unavailable");let r=E.parse(JSON.parse(i.payload));P(t,e,r);let o=t.get("SELECT id,payload FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[r.id]),a=o?JSON.parse(o.payload):null;if(!a||a.id!==e.expectedTurnId||a.status!=="in_progress")throw new Error("remote_turn_changed");let d=t.get("SELECT payload FROM approvals WHERE id=?",[e.expectedApprovalId]),p=d?JSON.parse(d.payload):null;if(!p||p.status!=="pending"||p.sessionId!==r.id||!p.turnId||p.turnId!==a.id&&p.turnId!==a.providerTurnId||!ye(p))throw new Error("remote_approval_changed_or_unsupported");if(t.get("SELECT command_id FROM remote_device_approval_claims WHERE approval_id=?",[p.id]))throw new Error("remote_approval_already_claimed");t.run("INSERT INTO remote_device_approval_claims(approval_id,command_id) VALUES(?,?)",[p.id,e.id]);let l={id:e.id,deviceId:e.deviceId,payloadHash:e.payloadHash,action:e.action,targetId:e.targetId,localSessionId:r.id,approvalId:p.id,turnId:a.id,state:"admitted",revision:2,createdAt:new Date().toISOString(),expiresAt:e.deadline};return t.run("INSERT INTO remote_device_receipts(id,payload_hash,command,receipt) VALUES(?,?,?,?)",[e.id,e.payloadHash,JSON.stringify(e),JSON.stringify(l)]),l})}async admitPonderDesktopInspection(e){return this.inboxWrite(t=>Ae(t,e))}async getPonderDesktopInspection(e){return await this.ready,await this.writeQueue,Q(this.database,e)}async setPonderProjectSharing(e){return this.inboxWrite(t=>Se(t,e))}async readPonderProjectSharing(e){return await this.ready,await this.writeQueue,Te(this.database,e)}async getPonderDesktopReservationResume(e,t){return this.inboxWrite(n=>we(n,e,t))}async admitPonderDesktopObservation(e){return this.inboxWrite(t=>Ne(t,e))}async getPonderDesktopObservation(e){return await this.ready,await this.writeQueue,Y(this.database,e)}async getPonderDesktopResult(e,t){return await this.ready,await this.writeQueue,K(this.database,e,t)}async commitPonderDesktopResult(e){return this.inboxWrite(t=>ve(t,e))}async inboxWrite(e){await this.ready;let t=this.writeQueue.then(()=>{let n=this.database;n.exec("BEGIN IMMEDIATE");try{let i=e(n);return n.exec("COMMIT"),i}catch(i){throw n.exec("ROLLBACK"),i}});return this.writeQueue=t.then(()=>{},()=>{}),t}async setPonderDesktopAuthority(e){let t=A.parse(e);if(t.state!=="attached"||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("ponder_desktop_local_authority_invalid");return this.inboxWrite(n=>{n.run("INSERT INTO ponder_desktop_authority (id, runtime_id, payload) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET runtime_id = excluded.runtime_id, payload = excluded.payload",[t.runtimeId,JSON.stringify(t)])})}async clearPonderDesktopAuthority(e){return this.inboxWrite(t=>{e?t.run("DELETE FROM ponder_desktop_authority WHERE runtime_id = ?",[e]):t.run("DELETE FROM ponder_desktop_authority")})}async admitPonderDesktopStop(e){return this.inboxWrite(t=>fe(t,e))}async getPonderDesktopStop(e){return await this.ready,await this.writeQueue,H(this.database,e)}async settlePonderDesktopStop(e,t){return this.inboxWrite(n=>ke(n,e,t))}async recoverTaskInboxOwners(e){return this.inboxWrite(t=>Ie(t,e))}async hasTaskCompletion(e){return await this.ready,await this.writeQueue,!!this.database.get("SELECT turn_id FROM task_completion_outbox WHERE turn_id = ?",[e])}async taskInboxSnapshot(e){await this.ready,await this.writeQueue;let t=y(this.database,e),n=t&&t.lease_until>Date.now()&&this.database.get("SELECT status FROM turns WHERE id = ?",[t.turn_id])?.status==="in_progress",i=this.database.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND (state IN ('pending', 'included')
21
+ OR sequence IN (SELECT sequence FROM task_inputs WHERE session_id = ? ORDER BY sequence DESC LIMIT 30)) ORDER BY sequence`,[e,e]);return{sessionId:e,activeTurnId:n?t.turn_id:null,acceptingInput:!!(n&&t.accepting&&!t.paused),paused:!!t?.paused,inputs:i.map(S),waits:await this.taskWaitsForSession(e)}}async declareTaskWork(e,t,n,i){return this.inboxWrite(r=>{k(r,e,t,n),r.run("INSERT INTO task_work_claims (session_id, turn_id, work_areas) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id, work_areas = excluded.work_areas",[e,t,JSON.stringify(i)])})}async taskWorkAreas(e){await this.ready,await this.writeQueue;let t=this.database.get("SELECT c.work_areas FROM task_work_claims c JOIN task_inbox_turns t ON c.session_id = t.session_id AND c.turn_id = t.turn_id WHERE c.session_id = ? AND t.lease_until > ?",[e,Date.now()]);return t?JSON.parse(t.work_areas):[]}async admitTaskInput(e){return this.inboxWrite(t=>j(t,e))}async admitTaskInputs(e){return this.inboxWrite(t=>e.map(n=>j(t,n)))}async rejectTaskInput(e,t,n){return this.inboxWrite(i=>{let r=R(i,e);if(r?.state==="pending"){let o=n&&r.senderKind==="ponder"?i.get("SELECT id FROM turns WHERE id = ? AND session_id = ? AND json_extract(payload, '$.metadata.taskInputId') = ?",[n,r.sessionId,r.id]):null;h(i,{...r,state:"rejected",error:t,...o?{turnId:o.id}:{},updatedAt:new Date().toISOString()})}})}async getTaskInput(e){return await this.ready,await this.writeQueue,R(this.database,e)}async taskInputsForSession(e,t={}){return await this.ready,await this.writeQueue,this.database.all(`SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND sequence > ?
22
+ ${t.pendingOnly?"AND state = 'pending'":""} ORDER BY sequence LIMIT ?`,[e,t.afterSequence??0,Math.max(1,Math.min(500,t.limit??128))]).map(S)}async mutateTaskInput(e,t,n){let i=ie.parse(n);return this.inboxWrite(r=>{let o=R(r,t);if(!o||o.sessionId!==e||o.senderKind!=="user")throw new Error("Queued user input not found.");if(o.state!=="pending"||o.revision!==i.expectedRevision||o.turnId)throw new Error("This input changed or has already been admitted. Refresh the queue before editing it.");if(i.action==="resume"){if(o.kind!=="queued")throw new Error("Only the user queue can be resumed here.");let a=y(r,e);if(a&&a.lease_until>Date.now())throw new Error("This task is already running.");r.run("UPDATE task_inbox_turns SET paused = 0 WHERE session_id = ?",[e])}return i.action==="steer"&&(J(r,e,i.expectedTurnId),B(r,i.expectedTurnId,o.body)),h(r,{...o,revision:o.revision+1,updatedAt:new Date().toISOString(),...i.action==="cancel"?{state:"cancelled"}:{},...i.action==="edit"?{body:i.body,payload:{...o.payload,prompt:i.body}}:{},...i.action==="steer"?{kind:"steer",expectedTurnId:i.expectedTurnId,turnId:i.expectedTurnId}:{}})})}async openTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{let r=y(i,e);if(r&&r.lease_until>Date.now()&&(r.turn_id!==t||r.owner_id!==n))throw new Error("A turn is already running for this task.");i.run(`INSERT INTO task_inbox_turns (session_id, turn_id, owner_id, generation, accepting, paused, lease_until)
23
23
  VALUES (?, ?, ?, ?, 1, 0, ?) ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id,
24
- owner_id = excluded.owner_id, generation = excluded.generation, accepting = 1, paused = 0, lease_until = excluded.lease_until`,[e,t,n,(r?.generation??0)+1,Date.now()+X])})}async renewTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{f(i,e,t,n),i.run("UPDATE task_inbox_turns SET lease_until = ? WHERE session_id = ?",[Date.now()+X,e])})}async pendingTaskInputs(e,t){return await this.ready,await this.writeQueue,v(this.database,e,t)}async taskAssignmentInputs(e){return await this.ready,await this.writeQueue,this.database.all("SELECT sequence, payload FROM task_inputs WHERE turn_id = ? AND kind = 'steer' AND state IN ('included', 'resolved') ORDER BY sequence",[e]).map(S)}async pauseTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{f(i,e,t,n),i.run("UPDATE task_inbox_turns SET accepting = 0, paused = 1 WHERE session_id = ?",[e])})}async includeTaskInputs(e,t,n,i){return this.inboxWrite(r=>{f(r,e,t,n);let o=r.get("SELECT input_ids FROM task_input_requests WHERE request_id = ?",[i]);if(o)return JSON.parse(o.input_ids).map(p=>R(r,p));let a=ie,d=[];for(let p of v(r,e,t)){if(p.body.length>a||d.length>=32)break;a-=p.body.length,d.push(h(r,{...p,state:"included",turnId:t,requestIds:[...p.requestIds,i],updatedAt:new Date().toISOString()}))}return r.run("INSERT INTO task_input_requests (request_id, session_id, turn_id, input_ids, state, created_at) VALUES (?, ?, ?, ?, 'included', ?)",[i,e,t,JSON.stringify(d.map(p=>p.id)),new Date().toISOString()]),d})}async settleTaskInputRequest(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT input_ids FROM task_input_requests WHERE request_id = ?",[e]);if(i){n.run("UPDATE task_input_requests SET state = ? WHERE request_id = ?",[t,e]);for(let r of JSON.parse(i.input_ids)){let o=R(n,r);!o||o.state!=="included"||h(n,{...o,state:t==="resolved"?"resolved":t==="replaced"?"pending":"included",error:t==="failed"?"Provider request failed after input inclusion; receipt is not evidence of a reply.":null,updatedAt:new Date().toISOString()})}}})}async sealTaskInboxTurn(e,t,n){return this.inboxWrite(i=>(f(i,e,t,n),v(i,e,t).length?!1:(i.run("UPDATE task_inbox_turns SET accepting = 0 WHERE session_id = ?",[e]),!0)))}async sealNativeTaskInboxTurn(e,t,n){return this.inboxWrite(i=>(f(i,e,t,n),i.run("UPDATE task_inbox_turns SET accepting = 0 WHERE session_id = ?",[e]),v(i,e,t).map(r=>h(i,{...r,updatedAt:new Date().toISOString(),...r.kind==="steer"?{state:"rejected",error:"The agent finished before this correction could be dispatched. Send it as a follow-up."}:{turnId:null}}))))}async closeTaskInboxTurn(e,t,n,i){return this.inboxWrite(r=>{let o=y(r,e);if(!(!o||o.turn_id!==t||o.owner_id!==n)){r.run("UPDATE task_inbox_turns SET accepting = 0, paused = CASE WHEN ? = 1 THEN 1 ELSE paused END, lease_until = 0 WHERE session_id = ?",[i==="completed"?0:1,e]);for(let a of v(r,e,t))a.kind==="steer"?h(r,{...a,state:"rejected",error:`Turn ${i} before this correction was included. Send it as a follow-up.`,updatedAt:new Date().toISOString()}):a.turnId===t&&h(r,{...a,turnId:null,updatedAt:new Date().toISOString()})}})}async taskInboxPaused(e){return await this.ready,await this.writeQueue,!!y(this.database,e)?.paused}async reserveTaskFollowup(e,t,n){return this.inboxWrite(i=>{let r=y(i,e);if(r?.paused||r&&r.lease_until>Date.now())return null;let o=i.all("SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND state = 'pending' AND turn_id IS NULL AND kind IN ('queued', 'followup') ORDER BY sequence",[e]),a=null;for(let d of o){let p=S(d);if(p.senderKind==="ponder"||p.payload.remoteDevice!==void 0){let c=i.get("SELECT payload FROM sessions WHERE id = ?",[e]);try{if(!c)throw new Error("The original local task no longer exists.");ce(p,E.parse(JSON.parse(c.payload))),pe(p,E.parse(JSON.parse(c.payload)))}catch(_){return h(i,{...p,state:"rejected",error:String(_),updatedAt:new Date().toISOString()})}}a=p;break}return a?(i.run(`INSERT INTO task_inbox_turns (session_id, turn_id, owner_id, generation, accepting, paused, lease_until)
24
+ owner_id = excluded.owner_id, generation = excluded.generation, accepting = 1, paused = 0, lease_until = excluded.lease_until`,[e,t,n,(r?.generation??0)+1,Date.now()+V])})}async renewTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{k(i,e,t,n),i.run("UPDATE task_inbox_turns SET lease_until = ? WHERE session_id = ?",[Date.now()+V,e])})}async pendingTaskInputs(e,t){return await this.ready,await this.writeQueue,v(this.database,e,t)}async taskAssignmentInputs(e){return await this.ready,await this.writeQueue,this.database.all("SELECT sequence, payload FROM task_inputs WHERE turn_id = ? AND kind = 'steer' AND state IN ('included', 'resolved') ORDER BY sequence",[e]).map(S)}async pauseTaskInboxTurn(e,t,n){return this.inboxWrite(i=>{k(i,e,t,n),i.run("UPDATE task_inbox_turns SET accepting = 0, paused = 1 WHERE session_id = ?",[e])})}async includeTaskInputs(e,t,n,i){return this.inboxWrite(r=>{k(r,e,t,n);let o=r.get("SELECT input_ids FROM task_input_requests WHERE request_id = ?",[i]);if(o)return JSON.parse(o.input_ids).map(p=>R(r,p));let a=ne,d=[];for(let p of v(r,e,t)){if(p.body.length>a||d.length>=32)break;a-=p.body.length,d.push(h(r,{...p,state:"included",turnId:t,requestIds:[...p.requestIds,i],updatedAt:new Date().toISOString()}))}return r.run("INSERT INTO task_input_requests (request_id, session_id, turn_id, input_ids, state, created_at) VALUES (?, ?, ?, ?, 'included', ?)",[i,e,t,JSON.stringify(d.map(p=>p.id)),new Date().toISOString()]),d})}async settleTaskInputRequest(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT input_ids FROM task_input_requests WHERE request_id = ?",[e]);if(i){n.run("UPDATE task_input_requests SET state = ? WHERE request_id = ?",[t,e]);for(let r of JSON.parse(i.input_ids)){let o=R(n,r);!o||o.state!=="included"||h(n,{...o,state:t==="resolved"?"resolved":t==="replaced"?"pending":"included",error:t==="failed"?"Provider request failed after input inclusion; receipt is not evidence of a reply.":null,updatedAt:new Date().toISOString()})}}})}async sealTaskInboxTurn(e,t,n){return this.inboxWrite(i=>(k(i,e,t,n),v(i,e,t).length?!1:(i.run("UPDATE task_inbox_turns SET accepting = 0 WHERE session_id = ?",[e]),!0)))}async sealNativeTaskInboxTurn(e,t,n){return this.inboxWrite(i=>(k(i,e,t,n),i.run("UPDATE task_inbox_turns SET accepting = 0 WHERE session_id = ?",[e]),v(i,e,t).map(r=>h(i,{...r,updatedAt:new Date().toISOString(),...r.kind==="steer"?{state:"rejected",error:"The agent finished before this correction could be dispatched. Send it as a follow-up."}:{turnId:null}}))))}async closeTaskInboxTurn(e,t,n,i){return this.inboxWrite(r=>{let o=y(r,e);if(!(!o||o.turn_id!==t||o.owner_id!==n)){r.run("UPDATE task_inbox_turns SET accepting = 0, paused = CASE WHEN ? = 1 THEN 1 ELSE paused END, lease_until = 0 WHERE session_id = ?",[i==="completed"?0:1,e]);for(let a of v(r,e,t))a.kind==="steer"?h(r,{...a,state:"rejected",error:`Turn ${i} before this correction was included. Send it as a follow-up.`,updatedAt:new Date().toISOString()}):a.turnId===t&&h(r,{...a,turnId:null,updatedAt:new Date().toISOString()})}})}async taskInboxPaused(e){return await this.ready,await this.writeQueue,!!y(this.database,e)?.paused}async reserveTaskFollowup(e,t,n){return this.inboxWrite(i=>{let r=y(i,e);if(r?.paused||r&&r.lease_until>Date.now())return null;let o=i.all("SELECT sequence, payload FROM task_inputs WHERE session_id = ? AND state = 'pending' AND turn_id IS NULL AND kind IN ('queued', 'followup') ORDER BY sequence",[e]),a=null;for(let d of o){let p=S(d);if(p.senderKind==="ponder"||p.payload.remoteDevice!==void 0){let c=i.get("SELECT payload FROM sessions WHERE id = ?",[e]);try{if(!c)throw new Error("The original local task no longer exists.");ce(p,E.parse(JSON.parse(c.payload))),pe(p,E.parse(JSON.parse(c.payload)))}catch(l){return h(i,{...p,state:"rejected",error:String(l),updatedAt:new Date().toISOString()})}}a=p;break}return a?(i.run(`INSERT INTO task_inbox_turns (session_id, turn_id, owner_id, generation, accepting, paused, lease_until)
25
25
  VALUES (?, ?, ?, ?, 1, 0, ?) ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id,
26
- owner_id = excluded.owner_id, generation = excluded.generation, accepting = 1, paused = 0, lease_until = excluded.lease_until`,[e,t,n,(r?.generation??0)+1,Date.now()+X]),h(i,{...a,turnId:t,updatedAt:new Date().toISOString()})):null})}async taskInboxWakeTargets(){return await this.ready,await this.writeQueue,this.database.all(`SELECT DISTINCT i.session_id FROM task_inputs i LEFT JOIN task_inbox_turns t ON t.session_id = i.session_id
26
+ owner_id = excluded.owner_id, generation = excluded.generation, accepting = 1, paused = 0, lease_until = excluded.lease_until`,[e,t,n,(r?.generation??0)+1,Date.now()+V]),h(i,{...a,turnId:t,updatedAt:new Date().toISOString()})):null})}async taskInboxWakeTargets(){return await this.ready,await this.writeQueue,this.database.all(`SELECT DISTINCT i.session_id FROM task_inputs i LEFT JOIN task_inbox_turns t ON t.session_id = i.session_id
27
27
  WHERE i.state = 'pending' AND i.turn_id IS NULL AND i.kind IN ('queued', 'followup')
28
28
  AND COALESCE(t.paused, 0) = 0 AND COALESCE(t.lease_until, 0) <= ?`,[Date.now()]).map(e=>e.session_id)}async createTaskWait(e){let t=O.parse(e);return this.inboxWrite(n=>{let i=n.get("SELECT payload FROM task_waits WHERE id = ?",[t.id]);if(i)return O.parse(JSON.parse(i.payload));if(t.targetSessionId===t.sessionId)throw new Error("A task cannot wait for itself.");if(t.targetSessionId&&n.get(`WITH RECURSIVE dependencies(session_id) AS (
29
29
  SELECT target_session_id FROM task_waits WHERE session_id = ? AND state = 'waiting'
30
30
  UNION SELECT w.target_session_id FROM task_waits w JOIN dependencies d ON w.session_id = d.session_id WHERE w.state = 'waiting'
31
- ) SELECT session_id FROM dependencies WHERE session_id = ? LIMIT 1`,[t.targetSessionId,t.sessionId]))throw new Error("This dependency would create a task wait cycle. Coordinate a different order.");return n.run("INSERT INTO task_waits (id, session_id, turn_id, target_session_id, target_turn_id, state, deadline, payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.sessionId,t.turnId,t.targetSessionId,t.targetTurnId,t.state,t.deadline,JSON.stringify(t)]),t})}async settleTaskWait(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload FROM task_waits WHERE id = ?",[e]);if(!i)throw new Error("Task wait not found.");let r=O.parse(JSON.parse(i.payload));if(r.state!=="waiting")return r;let o={...r,state:t,updatedAt:new Date().toISOString()};return n.run("UPDATE task_waits SET state = ?, payload = ? WHERE id = ?",[t,JSON.stringify(o),e]),o})}async taskWaitsForSession(e){return await this.ready,await this.writeQueue,this.database.all("SELECT payload FROM task_waits WHERE session_id = ? AND state = 'waiting'",[e]).map(t=>O.parse(JSON.parse(t.payload)))}async commitSubagentCompletion(e,t){let n=b.parse(e);return this.inboxWrite(i=>{let r=new Date().toISOString();i.run(`INSERT INTO subagent_runs (id, parent_session_id, parent_turn_id, child_session_id, role_id, status, payload, created_at, updated_at)
31
+ ) SELECT session_id FROM dependencies WHERE session_id = ? LIMIT 1`,[t.targetSessionId,t.sessionId]))throw new Error("This dependency would create a task wait cycle. Coordinate a different order.");return n.run("INSERT INTO task_waits (id, session_id, turn_id, target_session_id, target_turn_id, state, deadline, payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.sessionId,t.turnId,t.targetSessionId,t.targetTurnId,t.state,t.deadline,JSON.stringify(t)]),t})}async settleTaskWait(e,t){return this.inboxWrite(n=>{let i=n.get("SELECT payload FROM task_waits WHERE id = ?",[e]);if(!i)throw new Error("Task wait not found.");let r=O.parse(JSON.parse(i.payload));if(r.state!=="waiting")return r;let o={...r,state:t,updatedAt:new Date().toISOString()};return n.run("UPDATE task_waits SET state = ?, payload = ? WHERE id = ?",[t,JSON.stringify(o),e]),o})}async taskWaitsForSession(e){return await this.ready,await this.writeQueue,this.database.all("SELECT payload FROM task_waits WHERE session_id = ? AND state = 'waiting'",[e]).map(t=>O.parse(JSON.parse(t.payload)))}async commitSubagentCompletion(e,t){let n=M.parse(e);return this.inboxWrite(i=>{let r=new Date().toISOString();i.run(`INSERT INTO subagent_runs (id, parent_session_id, parent_turn_id, child_session_id, role_id, status, payload, created_at, updated_at)
32
32
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET status = excluded.status,
33
- payload = excluded.payload, updated_at = excluded.updated_at`,_e(n,r)),i.run("INSERT INTO task_completion_outbox (turn_id, run_id, payload, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(turn_id) DO NOTHING",[t,n.id,JSON.stringify(n),r])})}async pendingTaskCompletions(e=""){return await this.ready,await this.writeQueue,this.database.all("SELECT turn_id, payload FROM task_completion_outbox WHERE input_id IS NULL AND turn_id > ? ORDER BY turn_id LIMIT 100",[e]).map(t=>({turnId:t.turn_id,run:b.parse(JSON.parse(t.payload))}))}async settleTaskCompletion(e,t){return this.inboxWrite(n=>{if(!R(n,t))throw new Error("Completion delivery has no durable input receipt.");n.run("UPDATE task_completion_outbox SET input_id = ? WHERE turn_id = ? AND input_id IS NULL",[t,e])})}};export{Pe as SqliteTaskInboxStore};
33
+ payload = excluded.payload, updated_at = excluded.updated_at`,_e(n,r)),i.run("INSERT INTO task_completion_outbox (turn_id, run_id, payload, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(turn_id) DO NOTHING",[t,n.id,JSON.stringify(n),r])})}async pendingTaskCompletions(e=""){return await this.ready,await this.writeQueue,this.database.all("SELECT turn_id, payload FROM task_completion_outbox WHERE input_id IS NULL AND turn_id > ? ORDER BY turn_id LIMIT 100",[e]).map(t=>({turnId:t.turn_id,run:M.parse(JSON.parse(t.payload))}))}async settleTaskCompletion(e,t){return this.inboxWrite(n=>{if(!R(n,t))throw new Error("Completion delivery has no durable input receipt.");n.run("UPDATE task_completion_outbox SET input_id = ? WHERE turn_id = ? AND input_id IS NULL",[t,e])})}};export{Le as SqliteTaskInboxStore};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{$ as m}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as O}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import{a as R,b as S,c as k,d as L}from"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{E as I}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as f}from"./chunk-KGNCKIFP.js";import{b as h}from"./chunk-ES2ISFJC.js";import{a as y}from"./chunk-FTQLQJQV.js";var A=h.object({scope:h.string(),key:h.string(),ordinal:h.number().int().nonnegative()}).strict(),g=`
2
+ import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{$ as m}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as O}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import{a as R,b as S,c as k,d as L}from"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{E as I}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as f}from"./chunk-KGNCKIFP.js";import{b as h}from"./chunk-ES2ISFJC.js";import{a as y}from"./chunk-FTQLQJQV.js";var A=h.object({scope:h.string(),key:h.string(),ordinal:h.number().int().nonnegative()}).strict(),g=`
3
3
  CREATE TABLE IF NOT EXISTS task_inventory_sources (source_key TEXT NOT NULL, profile_id TEXT NOT NULL, source_hash TEXT NOT NULL, metadata TEXT NOT NULL, PRIMARY KEY(profile_id, source_key));
4
4
  CREATE TABLE IF NOT EXISTS task_inventory_rows (profile_id TEXT NOT NULL, source_key TEXT NOT NULL, source_hash TEXT NOT NULL, task_id TEXT NOT NULL, ordinal INTEGER NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL, split TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY(profile_id, source_key, source_hash, ordinal));
5
5
  CREATE UNIQUE INDEX IF NOT EXISTS task_inventory_task_identity ON task_inventory_rows(profile_id, source_key, source_hash, task_id);