openpond 0.2.57 → 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 (71) 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-VCRNCNX2.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-6FDWRG55.js → chunk-ROGF26KV.js} +1 -1
  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-MULXCKG7.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-NRLXL2S5.js → host-profile-evaluation-tools-JOFBL5OF.js} +1 -1
  38. package/dist/chunks/{hosted-app-server-composition-HPL3CRXN.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-INHPJ63Z.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-YY7LEQGP.js +0 -2
@@ -3061,6 +3061,7 @@ declare const RemoteCommandInputSchema: z.ZodObject<{
3061
3061
  expiresAt: z.ZodOptional<z.ZodString>;
3062
3062
  payload: z.ZodObject<{
3063
3063
  text: z.ZodOptional<z.ZodString>;
3064
+ resume: z.ZodOptional<z.ZodBoolean>;
3064
3065
  response: z.ZodOptional<z.ZodEnum<{
3065
3066
  approve: "approve";
3066
3067
  reject: "reject";
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{m as r}from"./chunks/chunk-MULXCKG7.js";import"./chunks/chunk-D74JEERO.js";import"./chunks/chunk-JDEEWOD7.js";import"./chunks/chunk-OGDADQGH.js";import{b as p}from"./chunks/chunk-4NESNOK5.js";import"./chunks/chunk-BLXEAZCQ.js";import"./chunks/chunk-UCPGRPWY.js";import"./chunks/chunk-L6K7ERG5.js";import"./chunks/chunk-J2TWKFML.js";import"./chunks/chunk-773TH7FN.js";import"./chunks/chunk-HDL5YSAA.js";import"./chunks/chunk-ZFSHBFG5.js";import"./chunks/chunk-AN525SPP.js";import"./chunks/chunk-SYUKES6H.js";import"./chunks/chunk-HIOKCIL7.js";import"./chunks/chunk-GW766ZSO.js";import"./chunks/chunk-UKMA4R6X.js";import"./chunks/chunk-OQKJGTTO.js";import"./chunks/chunk-KVTBX2UP.js";import"./chunks/chunk-IZ6DLEVY.js";import"./chunks/chunk-A6USMRWK.js";import"./chunks/chunk-PCSIOUHF.js";import"./chunks/chunk-7KWD2I6W.js";import"./chunks/chunk-GPVCOEUH.js";import"./chunks/chunk-OLLLZVHF.js";import"./chunks/chunk-7PXZ4X4P.js";import"./chunks/chunk-N73MU2C3.js";import"./chunks/chunk-ZGTOK7ZK.js";import"./chunks/chunk-XW6HGSIT.js";import"./chunks/chunk-KG325WTN.js";import"./chunks/chunk-3RCRSMWZ.js";import"./chunks/chunk-UGL7WF3W.js";import"./chunks/chunk-DMFUEUAZ.js";import"./chunks/chunk-PSGGOZFM.js";import"./chunks/chunk-FUOEIDMA.js";import"./chunks/chunk-NHQ36THU.js";import{l as e}from"./chunks/chunk-VRIEKBBH.js";import"./chunks/chunk-QNG27G3T.js";import"./chunks/chunk-EIRYMSEG.js";import"./chunks/chunk-QOTVNQDI.js";import"./chunks/chunk-OQPJ7FJF.js";import"./chunks/chunk-WJ43MJ3F.js";import"./chunks/chunk-Q4TBTRIG.js";import"./chunks/chunk-T5AACNJI.js";import"./chunks/chunk-QOGJAQDO.js";import"./chunks/chunk-EYPCBBMS.js";import"./chunks/chunk-DIO5CB6U.js";import"./chunks/chunk-7ED24PP6.js";import"./chunks/chunk-RNIAFXMB.js";import"./chunks/chunk-2IHO4GDJ.js";import"./chunks/chunk-KCJVFLBB.js";import"./chunks/chunk-N4FFQPLR.js";import"./chunks/chunk-AY64VY4E.js";import"./chunks/chunk-GJ2ZJFDD.js";import"./chunks/chunk-BFKYRQMA.js";import"./chunks/chunk-6QSSIT62.js";import"./chunks/chunk-3QIB5FXI.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-DDMZSZFL.js";import"./chunks/chunk-W45RKGM6.js";import"./chunks/chunk-3VUATFZD.js";import"./chunks/chunk-4EPSHPZL.js";import"./chunks/chunk-H6IW2R22.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-MQULU465.js";import"./chunks/chunk-PRGBLQVH.js";import"./chunks/chunk-7E6T7GP5.js";import"./chunks/chunk-DZUAT3TP.js";import"./chunks/chunk-XDQMGUWL.js";import"./chunks/chunk-FTEOCCPB.js";import"./chunks/chunk-25MBPJVY.js";import"./chunks/chunk-WN3V6KDN.js";import"./chunks/chunk-523TE4BI.js";import"./chunks/chunk-ZCHXGRRU.js";import"./chunks/chunk-QDC4OW3S.js";import"./chunks/chunk-ZZWAQBA2.js";import"./chunks/chunk-YR5ID2SS.js";import"./chunks/chunk-YBT2NB32.js";import"./chunks/chunk-74ZXXBGN.js";import"./chunks/chunk-APB2STJK.js";import"./chunks/chunk-I7AQMAQI.js";import"./chunks/chunk-Z4Z5UOZM.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-Y4OWBBDD.js";import"./chunks/chunk-6ZFPQYHG.js";import"./chunks/chunk-JFXWI3EN.js";import"./chunks/chunk-FFRFSDBM.js";import"./chunks/chunk-VYLGI3IH.js";import"./chunks/chunk-ACYFMLWG.js";import"./chunks/chunk-TVQAPBLZ.js";import"./chunks/chunk-KGNCKIFP.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
2
+ import{m as r}from"./chunks/chunk-ZTNHW2K7.js";import"./chunks/chunk-D74JEERO.js";import"./chunks/chunk-JDEEWOD7.js";import"./chunks/chunk-6UDGARFC.js";import{b as p}from"./chunks/chunk-4NESNOK5.js";import"./chunks/chunk-BLXEAZCQ.js";import"./chunks/chunk-UCPGRPWY.js";import"./chunks/chunk-APB4O67E.js";import"./chunks/chunk-XX6SMFDY.js";import"./chunks/chunk-773TH7FN.js";import"./chunks/chunk-RWWE5OXU.js";import"./chunks/chunk-RNQF63ZR.js";import"./chunks/chunk-AN525SPP.js";import"./chunks/chunk-SYUKES6H.js";import"./chunks/chunk-HIOKCIL7.js";import"./chunks/chunk-GW766ZSO.js";import"./chunks/chunk-UKMA4R6X.js";import"./chunks/chunk-OQKJGTTO.js";import"./chunks/chunk-KVTBX2UP.js";import"./chunks/chunk-IZ6DLEVY.js";import"./chunks/chunk-A6USMRWK.js";import"./chunks/chunk-PCSIOUHF.js";import"./chunks/chunk-7KWD2I6W.js";import"./chunks/chunk-GPVCOEUH.js";import"./chunks/chunk-OLLLZVHF.js";import"./chunks/chunk-7PXZ4X4P.js";import"./chunks/chunk-N73MU2C3.js";import"./chunks/chunk-ZGTOK7ZK.js";import"./chunks/chunk-XW6HGSIT.js";import"./chunks/chunk-KG325WTN.js";import"./chunks/chunk-TTVS6JMC.js";import"./chunks/chunk-UGL7WF3W.js";import"./chunks/chunk-DMFUEUAZ.js";import"./chunks/chunk-PSGGOZFM.js";import"./chunks/chunk-FUOEIDMA.js";import"./chunks/chunk-NHQ36THU.js";import{l as e}from"./chunks/chunk-VRIEKBBH.js";import"./chunks/chunk-QNG27G3T.js";import"./chunks/chunk-EIRYMSEG.js";import"./chunks/chunk-QL4OIPEZ.js";import"./chunks/chunk-OQPJ7FJF.js";import"./chunks/chunk-WJ43MJ3F.js";import"./chunks/chunk-Q4TBTRIG.js";import"./chunks/chunk-T5AACNJI.js";import"./chunks/chunk-QOGJAQDO.js";import"./chunks/chunk-EYPCBBMS.js";import"./chunks/chunk-DIO5CB6U.js";import"./chunks/chunk-7ED24PP6.js";import"./chunks/chunk-RNIAFXMB.js";import"./chunks/chunk-2IHO4GDJ.js";import"./chunks/chunk-KCJVFLBB.js";import"./chunks/chunk-N4FFQPLR.js";import"./chunks/chunk-AY64VY4E.js";import"./chunks/chunk-GJ2ZJFDD.js";import"./chunks/chunk-BFKYRQMA.js";import"./chunks/chunk-6QSSIT62.js";import"./chunks/chunk-3QIB5FXI.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-DDMZSZFL.js";import"./chunks/chunk-W45RKGM6.js";import"./chunks/chunk-3VUATFZD.js";import"./chunks/chunk-4EPSHPZL.js";import"./chunks/chunk-H6IW2R22.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-MQULU465.js";import"./chunks/chunk-PRGBLQVH.js";import"./chunks/chunk-7E6T7GP5.js";import"./chunks/chunk-DZUAT3TP.js";import"./chunks/chunk-XDQMGUWL.js";import"./chunks/chunk-FTEOCCPB.js";import"./chunks/chunk-25MBPJVY.js";import"./chunks/chunk-WN3V6KDN.js";import"./chunks/chunk-523TE4BI.js";import"./chunks/chunk-ZCHXGRRU.js";import"./chunks/chunk-QDC4OW3S.js";import"./chunks/chunk-ZZWAQBA2.js";import"./chunks/chunk-YR5ID2SS.js";import"./chunks/chunk-YBT2NB32.js";import"./chunks/chunk-74ZXXBGN.js";import"./chunks/chunk-APB2STJK.js";import"./chunks/chunk-I7AQMAQI.js";import"./chunks/chunk-Z4Z5UOZM.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-Y4OWBBDD.js";import"./chunks/chunk-6ZFPQYHG.js";import"./chunks/chunk-JFXWI3EN.js";import"./chunks/chunk-FFRFSDBM.js";import"./chunks/chunk-VYLGI3IH.js";import"./chunks/chunk-ACYFMLWG.js";import"./chunks/chunk-TVQAPBLZ.js";import"./chunks/chunk-KGNCKIFP.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Y,b as Z}from"./chunk-KUERKVEU.js";import{c as K,d as Q,e as X}from"./chunk-QHWGQ3A4.js";import"./chunk-PPAPVGJP.js";import"./chunk-GZ7M5XBP.js";import{c as L,d as W,e as C,h as z}from"./chunk-3Z47M3YY.js";import{a as P}from"./chunk-ABD5M2D2.js";import"./chunk-TRQQNFMO.js";import"./chunk-FEAKTSRS.js";import"./chunk-F74GBN6K.js";import"./chunk-SDAUS5PY.js";import"./chunk-I2NXNMRZ.js";import"./chunk-O72BSKSO.js";import{a as V,b as $}from"./chunk-OPNRWESL.js";import{b as G,c as B}from"./chunk-2QUCCP6Z.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-DBK66CJP.js";import{c as U}from"./chunk-D74JEERO.js";import{a as F}from"./chunk-UCPGRPWY.js";import"./chunk-773TH7FN.js";import"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{I as R}from"./chunk-VRIEKBBH.js";import"./chunk-QNG27G3T.js";import{s as k,u as J}from"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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{n as N}from"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.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{d as j}from"./chunk-VYLGI3IH.js";import{l as M}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as S}from"./chunk-KGNCKIFP.js";import{b as s}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";import{createHash as le}from"node:crypto";function q(d,o){if(o.environment.kind!=="javascript")throw new Error("experiment_environment_required");let{definition:t,asset:f}=o.environment,l=j(f,t.module),p=le("sha256").update(o.id).digest("hex"),x=0;return async i=>{if(i.signal?.throwIfAborted(),i.source!==l)throw new Error("experiment_environment_source_mismatch");let c=i.value.action,n=t.executionServices?.filter(y=>y.operation===i.operation&&(i.operation!=="step"||y.toolName===c?.name))??[];if(S(i.executionServices??[])!==S(n))throw new Error("experiment_environment_services_mismatch");let m=x++,h=await d.request({contractVersion:R,requestId:`environment-${p}-${m}`,operation:"experiment/environment",params:{caseId:o.id,admissionHash:o.admissionHash,definitionHash:t.contentHash,ordinal:m,operation:i.operation,value:i.value,timeoutMs:i.timeoutMs}},3e5);return i.signal?.throwIfAborted(),M(h,1572864),N.parse(h)}}r(q,"createHostExperimentEnvironment");import{createHash as pe}from"node:crypto";var ce=s.object({text:s.string().max(262144),toolCalls:s.array(s.object({id:s.string().min(1).max(200),name:s.string().min(1).max(64),arguments:s.record(s.string(),s.unknown())}).strict()).max(200)}).strict();function H(d,o){let t=0;return async({messages:f,tools:l,signal:p})=>{p.throwIfAborted();let x=t++,i=await d.request({contractVersion:R,requestId:`experiment-${pe("sha256").update(o.id).digest("hex")}-${x}`,operation:"experiment/policy",params:{caseId:o.id,admissionHash:o.admissionHash,ordinal:x,messages:f.map(c=>({...c})),tools:l.map(c=>({...c}))}},Math.min(o.timeoutMs,3e5));return p.throwIfAborted(),ce.parse(i)}}r(H,"createHostExperimentPolicy");function ee(d,o,t){let f=H(d,o);return async function*(l){let p=o.model;if(!l.signal||l.model!==p.modelId||l.maxTokens!==p.maxOutputTokens||l.temperature!==p.temperature||l.topP!==p.topP)throw new Error("Native Experiment policy request differs from its admitted model configuration.");let x=l.messages.map(n=>{if(n.images?.length||n.continuation)throw new Error("The owner policy capability does not admit multimodal or caller-supplied continuation inputs.");if(n.role==="tool")return{role:"tool",callId:s.string().min(1).max(200).parse(n.tool_call_id),name:s.string().min(1).max(64).parse(n.name),observation:me(n.content??"")};if(n.role==="assistant")return{role:"assistant",text:n.content??"",toolCalls:(n.tool_calls??[]).map(m=>({id:s.string().min(1).max(200).parse(m.id),name:s.string().min(1).max(64).parse(m.function?.name),arguments:s.record(s.string(),s.unknown()).parse(JSON.parse(s.string().parse(m.function?.arguments)))}))};if(n.role!=="user"&&n.role!=="system")throw new Error("Native Experiment message role is not admitted.");return{role:n.role,text:n.content??""}}),i=(l.tools??[]).map(n=>{if(n.type!=="function"||!n.function)throw new Error("Native Experiment requires declared function tools.");let m=t.find(h=>h.name===n.function.name);if(!m||S(n.function.parameters)!==m.inputSchemaHash)throw new Error("Native Experiment requested an undeclared or changed tool.");return m});if(i.length!==t.length||new Set(i.map(n=>n.name)).size!==i.length)throw new Error("Native Experiment changed its admitted tool inventory.");let c=await f({messages:x,tools:i,signal:l.signal});l.signal.throwIfAborted(),c.text&&(yield{type:"text_delta",text:c.text,raw:null}),c.toolCalls.length&&(yield{type:"tool_call_delta",toolCalls:c.toolCalls.map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),raw:null}),yield{type:"finish",finishReason:c.toolCalls.length?"tool_calls":"stop",raw:null}}}r(ee,"createHostExperimentNativeStream");function me(d){try{let o=JSON.parse(d);return o&&typeof o=="object"&&!Array.isArray(o)?o:{output:o}}catch{return{output:d}}}r(me,"observation");function Qe(d){let{options:o,store:t,storeDir:f,explicitProfileRelease:l,externalDataset:p,isolatedProfileTools:x,selectedEvaluationProfile:i,listProfileWorkflows:c,createSessionWithAutoTitle:n,turnRunner:m,streamOpenPondHostedChatTurn:h,publishedExperimentSource:y,standaloneExperimentOwner:D}=d,w=new AbortController,oe=K({resolveExternalDataset:p?.resolveExternalDataset,admitSession:x?.admitSession,settleSession:x?.settleSession,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),store:t,storeDir:f,selectedProfile:i,createSession:n,sendTurn:m.sendTurn,interruptSessionTurn:m.interruptSessionTurn}),T=r((e,a)=>oe(e,a?AbortSignal.any([a,w.signal]):w.signal),"executeProfileEvaluationCase"),I=z({privateGradingPreflight:r(e=>L(e,!1),"privateGradingPreflight"),resolveExternalDataset:p?.resolveExternalDataset,sourceCandidate:p?.sourceCandidate,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),selectedWorkflows:c,loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),modelConfigurationHash:r(async(e,a)=>{if(!o.profileSource||e.providerId!=="openpond"||!a.hostModelConfigurationHash)throw new Error("Hosted Profile evaluation requires an explicit source and trusted OpenPond model configuration receipt.");return a.hostModelConfigurationHash},"modelConfigurationHash"),placement:"remote"}),te=Q({loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),privateGrading:r(async(e,a,v)=>W({manifest:e,packageValue:a,signal:v,authorize:r(async()=>{let u=await i(),E=e.profileEvaluation;if(!u||!E||u.ref.profileId!==E.profileId||u.sourceRevision!==E.sourceRevision)throw new Error("The current private Profile source changed.");p&&await p.authorize({bindingHash:E.externalDatasetBinding.contentHash,manifestHash:e.contentHash});let O=await P({ref:u.ref,sourceRevision:u.sourceRevision,harnessRelease:E.harnessRelease,store:t});if(!E.externalDatasetBinding&&O.catalogHash!==E.catalogHash)throw new Error("The current private evaluation catalog changed.")},"authorize")}),"privateGrading"),resolveExternalDataset:p?.resolveExternalDataset,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),store:t,selectedProfile:i,executeCase:T}),A=r((e,a)=>te(e,a?AbortSignal.any([a,w.signal]):w.signal),"executeProfileEvaluationRun"),re=X({loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),store:t,selectedWorkflows:c,prepareRun:I,executeRun:A}),b=Y({...y&&o.experimentPolicyClient?{executeHarness:r(async(e,a)=>{if(!e.harness||!D)throw new Error("Standalone Experiment source owner is unavailable.");return(await D.execute({executionId:e.id,request:e,source:e.harness,stream:ee(o.experimentPolicyClient,e,F(y.release)),signal:a,maxOutputBytes:262144})).attempt},"executeHarness")}:{},...o.experimentPolicyClient?{resolveEnvironment:r(async e=>q(o.experimentPolicyClient,e),"resolveEnvironment")}:{},resolvePolicy:r(async e=>o.experimentPolicyClient?H(o.experimentPolicyClient,e):Z({request:e,stream:h}),"resolvePolicy"),executeProfile:r(e=>{if(o.experimentPolicyClient)throw new Error("A model-case owner cannot execute a Profile.");return T(e)},"executeProfile")});return{listProfileEvaluations:r(async e=>{if(e&&typeof e=="object"&&!Array.isArray(e)&&"runId"in e){let _=G.parse(e),g=await i();if(!g)throw new Error("Select a Profile before inspecting an evaluation run.");return B({store:t,profileRef:g.ref,..._})}if(o.profileSource&&l){let _=await P({store:t,ref:{source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId},sourceRevision:o.profileSource.sourceRevision,harnessRelease:{id:l.harnessRelease.id,contentHash:l.harnessRelease.contentHash}}),[g,ae,se]=await Promise.all([t.listProfileEvaluationRuns({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId}),t.listProfileEvaluationComparisons({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId}),t.listProfileEvaluationSuiteRuns({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId})]);return{..._,runs:g,comparisons:ae,suiteRuns:se}}let[a,v]=await Promise.all([J(),k()]);if(!a.lastUsed)throw new Error("Select a Profile before loading its evaluations.");let u=await U({store:t,storeDir:f,ref:a.lastUsed,profile:v,reloadProfile:k}),E=await P({store:t,ref:u.profileRef,sourceRevision:u.sourceRevision,harnessRelease:u.harnessRelease}),[O,ne,ie]=await Promise.all([t.listProfileEvaluationRuns(u.profileRef),t.listProfileEvaluationComparisons(u.profileRef),t.listProfileEvaluationSuiteRuns(u.profileRef)]);return{...E,runs:O,comparisons:ne,suiteRuns:ie}},"listProfileEvaluations"),executeProfileEvaluationCase:T,executeExperimentCase:b.execute,cancelExperimentCase:r(e=>Promise.resolve(b.cancel(s.object({id:s.string().min(1)}).strict().parse(e).id)),"cancelExperimentCase"),executeProfileEvaluationRun:A,prepareProfileEvaluationRun:I,runPreparedProfileEvaluation:r(async e=>A(await I(e,{requireExpectedManifestHash:!0})),"runPreparedProfileEvaluation"),runProfileEvaluationSuite:re,compareProfileEvaluationRuns:V({store:t,selectedProfile:i}),buildProfileEvaluationReport:r(async e=>{let a=await i();if(!a)throw new Error("Select a Profile before building an evaluation report.");return $({store:t,profileRef:a.ref,request:e})},"buildProfileEvaluationReport"),async close(){w.abort(new Error("Evaluation runtime closed")),await b.close()}}}r(Qe,"createAppServerEvaluations");export{Qe as createAppServerEvaluations};
2
+ import{a as Y,b as Z}from"./chunk-IIZ4CWBX.js";import{c as K,d as Q,e as X}from"./chunk-I3VVWNUW.js";import"./chunk-HDGTHRY7.js";import"./chunk-YNH3NMPF.js";import{c as L,d as W,e as C,h as z}from"./chunk-3Z47M3YY.js";import{a as P}from"./chunk-ABD5M2D2.js";import"./chunk-TRQQNFMO.js";import"./chunk-FEAKTSRS.js";import"./chunk-F74GBN6K.js";import"./chunk-SDAUS5PY.js";import"./chunk-I2NXNMRZ.js";import"./chunk-O72BSKSO.js";import{a as V,b as $}from"./chunk-OPNRWESL.js";import{b as G,c as B}from"./chunk-7SC46OFC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-DBK66CJP.js";import{c as U}from"./chunk-D74JEERO.js";import{a as F}from"./chunk-UCPGRPWY.js";import"./chunk-773TH7FN.js";import"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{I as R}from"./chunk-VRIEKBBH.js";import"./chunk-QNG27G3T.js";import{s as k,u as J}from"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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{n as N}from"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.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{d as j}from"./chunk-VYLGI3IH.js";import{l as M}from"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m as S}from"./chunk-KGNCKIFP.js";import{b as s}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";import{createHash as le}from"node:crypto";function q(d,o){if(o.environment.kind!=="javascript")throw new Error("experiment_environment_required");let{definition:t,asset:f}=o.environment,l=j(f,t.module),p=le("sha256").update(o.id).digest("hex"),x=0;return async i=>{if(i.signal?.throwIfAborted(),i.source!==l)throw new Error("experiment_environment_source_mismatch");let c=i.value.action,n=t.executionServices?.filter(y=>y.operation===i.operation&&(i.operation!=="step"||y.toolName===c?.name))??[];if(S(i.executionServices??[])!==S(n))throw new Error("experiment_environment_services_mismatch");let m=x++,h=await d.request({contractVersion:R,requestId:`environment-${p}-${m}`,operation:"experiment/environment",params:{caseId:o.id,admissionHash:o.admissionHash,definitionHash:t.contentHash,ordinal:m,operation:i.operation,value:i.value,timeoutMs:i.timeoutMs}},3e5);return i.signal?.throwIfAborted(),M(h,1572864),N.parse(h)}}r(q,"createHostExperimentEnvironment");import{createHash as pe}from"node:crypto";var ce=s.object({text:s.string().max(262144),toolCalls:s.array(s.object({id:s.string().min(1).max(200),name:s.string().min(1).max(64),arguments:s.record(s.string(),s.unknown())}).strict()).max(200)}).strict();function H(d,o){let t=0;return async({messages:f,tools:l,signal:p})=>{p.throwIfAborted();let x=t++,i=await d.request({contractVersion:R,requestId:`experiment-${pe("sha256").update(o.id).digest("hex")}-${x}`,operation:"experiment/policy",params:{caseId:o.id,admissionHash:o.admissionHash,ordinal:x,messages:f.map(c=>({...c})),tools:l.map(c=>({...c}))}},Math.min(o.timeoutMs,3e5));return p.throwIfAborted(),ce.parse(i)}}r(H,"createHostExperimentPolicy");function ee(d,o,t){let f=H(d,o);return async function*(l){let p=o.model;if(!l.signal||l.model!==p.modelId||l.maxTokens!==p.maxOutputTokens||l.temperature!==p.temperature||l.topP!==p.topP)throw new Error("Native Experiment policy request differs from its admitted model configuration.");let x=l.messages.map(n=>{if(n.images?.length||n.continuation)throw new Error("The owner policy capability does not admit multimodal or caller-supplied continuation inputs.");if(n.role==="tool")return{role:"tool",callId:s.string().min(1).max(200).parse(n.tool_call_id),name:s.string().min(1).max(64).parse(n.name),observation:me(n.content??"")};if(n.role==="assistant")return{role:"assistant",text:n.content??"",toolCalls:(n.tool_calls??[]).map(m=>({id:s.string().min(1).max(200).parse(m.id),name:s.string().min(1).max(64).parse(m.function?.name),arguments:s.record(s.string(),s.unknown()).parse(JSON.parse(s.string().parse(m.function?.arguments)))}))};if(n.role!=="user"&&n.role!=="system")throw new Error("Native Experiment message role is not admitted.");return{role:n.role,text:n.content??""}}),i=(l.tools??[]).map(n=>{if(n.type!=="function"||!n.function)throw new Error("Native Experiment requires declared function tools.");let m=t.find(h=>h.name===n.function.name);if(!m||S(n.function.parameters)!==m.inputSchemaHash)throw new Error("Native Experiment requested an undeclared or changed tool.");return m});if(i.length!==t.length||new Set(i.map(n=>n.name)).size!==i.length)throw new Error("Native Experiment changed its admitted tool inventory.");let c=await f({messages:x,tools:i,signal:l.signal});l.signal.throwIfAborted(),c.text&&(yield{type:"text_delta",text:c.text,raw:null}),c.toolCalls.length&&(yield{type:"tool_call_delta",toolCalls:c.toolCalls.map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),raw:null}),yield{type:"finish",finishReason:c.toolCalls.length?"tool_calls":"stop",raw:null}}}r(ee,"createHostExperimentNativeStream");function me(d){try{let o=JSON.parse(d);return o&&typeof o=="object"&&!Array.isArray(o)?o:{output:o}}catch{return{output:d}}}r(me,"observation");function Qe(d){let{options:o,store:t,storeDir:f,explicitProfileRelease:l,externalDataset:p,isolatedProfileTools:x,selectedEvaluationProfile:i,listProfileWorkflows:c,createSessionWithAutoTitle:n,turnRunner:m,streamOpenPondHostedChatTurn:h,publishedExperimentSource:y,standaloneExperimentOwner:D}=d,w=new AbortController,oe=K({resolveExternalDataset:p?.resolveExternalDataset,admitSession:x?.admitSession,settleSession:x?.settleSession,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),store:t,storeDir:f,selectedProfile:i,createSession:n,sendTurn:m.sendTurn,interruptSessionTurn:m.interruptSessionTurn}),T=r((e,a)=>oe(e,a?AbortSignal.any([a,w.signal]):w.signal),"executeProfileEvaluationCase"),I=z({privateGradingPreflight:r(e=>L(e,!1),"privateGradingPreflight"),resolveExternalDataset:p?.resolveExternalDataset,sourceCandidate:p?.sourceCandidate,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),selectedWorkflows:c,loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),modelConfigurationHash:r(async(e,a)=>{if(!o.profileSource||e.providerId!=="openpond"||!a.hostModelConfigurationHash)throw new Error("Hosted Profile evaluation requires an explicit source and trusted OpenPond model configuration receipt.");return a.hostModelConfigurationHash},"modelConfigurationHash"),placement:"remote"}),te=Q({loadTasksetPackage:r((e,a,v)=>C({store:t,storeDir:f,definition:e,profileId:a,harnessRelease:v}),"loadTasksetPackage"),privateGrading:r(async(e,a,v)=>W({manifest:e,packageValue:a,signal:v,authorize:r(async()=>{let u=await i(),E=e.profileEvaluation;if(!u||!E||u.ref.profileId!==E.profileId||u.sourceRevision!==E.sourceRevision)throw new Error("The current private Profile source changed.");p&&await p.authorize({bindingHash:E.externalDatasetBinding.contentHash,manifestHash:e.contentHash});let O=await P({ref:u.ref,sourceRevision:u.sourceRevision,harnessRelease:E.harnessRelease,store:t});if(!E.externalDatasetBinding&&O.catalogHash!==E.catalogHash)throw new Error("The current private evaluation catalog changed.")},"authorize")}),"privateGrading"),resolveExternalDataset:p?.resolveExternalDataset,loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),store:t,selectedProfile:i,executeCase:T}),A=r((e,a)=>te(e,a?AbortSignal.any([a,w.signal]):w.signal),"executeProfileEvaluationRun"),re=X({loadCatalog:r(e=>P({...e,store:t}),"loadCatalog"),store:t,selectedWorkflows:c,prepareRun:I,executeRun:A}),b=Y({...y&&o.experimentPolicyClient?{executeHarness:r(async(e,a)=>{if(!e.harness||!D)throw new Error("Standalone Experiment source owner is unavailable.");return(await D.execute({executionId:e.id,request:e,source:e.harness,stream:ee(o.experimentPolicyClient,e,F(y.release)),signal:a,maxOutputBytes:262144})).attempt},"executeHarness")}:{},...o.experimentPolicyClient?{resolveEnvironment:r(async e=>q(o.experimentPolicyClient,e),"resolveEnvironment")}:{},resolvePolicy:r(async e=>o.experimentPolicyClient?H(o.experimentPolicyClient,e):Z({request:e,stream:h}),"resolvePolicy"),executeProfile:r(e=>{if(o.experimentPolicyClient)throw new Error("A model-case owner cannot execute a Profile.");return T(e)},"executeProfile")});return{listProfileEvaluations:r(async e=>{if(e&&typeof e=="object"&&!Array.isArray(e)&&"runId"in e){let _=G.parse(e),g=await i();if(!g)throw new Error("Select a Profile before inspecting an evaluation run.");return B({store:t,profileRef:g.ref,..._})}if(o.profileSource&&l){let _=await P({store:t,ref:{source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId},sourceRevision:o.profileSource.sourceRevision,harnessRelease:{id:l.harnessRelease.id,contentHash:l.harnessRelease.contentHash}}),[g,ae,se]=await Promise.all([t.listProfileEvaluationRuns({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId}),t.listProfileEvaluationComparisons({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId}),t.listProfileEvaluationSuiteRuns({source:"openpond_git",repositoryId:o.profileSource.repositoryId,profileId:o.profileSource.profileId})]);return{..._,runs:g,comparisons:ae,suiteRuns:se}}let[a,v]=await Promise.all([J(),k()]);if(!a.lastUsed)throw new Error("Select a Profile before loading its evaluations.");let u=await U({store:t,storeDir:f,ref:a.lastUsed,profile:v,reloadProfile:k}),E=await P({store:t,ref:u.profileRef,sourceRevision:u.sourceRevision,harnessRelease:u.harnessRelease}),[O,ne,ie]=await Promise.all([t.listProfileEvaluationRuns(u.profileRef),t.listProfileEvaluationComparisons(u.profileRef),t.listProfileEvaluationSuiteRuns(u.profileRef)]);return{...E,runs:O,comparisons:ne,suiteRuns:ie}},"listProfileEvaluations"),executeProfileEvaluationCase:T,executeExperimentCase:b.execute,cancelExperimentCase:r(e=>Promise.resolve(b.cancel(s.object({id:s.string().min(1)}).strict().parse(e).id)),"cancelExperimentCase"),executeProfileEvaluationRun:A,prepareProfileEvaluationRun:I,runPreparedProfileEvaluation:r(async e=>A(await I(e,{requireExpectedManifestHash:!0})),"runPreparedProfileEvaluation"),runProfileEvaluationSuite:re,compareProfileEvaluationRuns:V({store:t,selectedProfile:i}),buildProfileEvaluationReport:r(async e=>{let a=await i();if(!a)throw new Error("Select a Profile before building an evaluation report.");return $({store:t,profileRef:a.ref,request:e})},"buildProfileEvaluationReport"),async close(){w.abort(new Error("Evaluation runtime closed")),await b.close()}}}r(Qe,"createAppServerEvaluations");export{Qe as createAppServerEvaluations};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as H,c as m,d as k}from"./chunk-QEFHOJFE.js";import"./chunk-3K4VVB7S.js";import{d,f as p,g as f,h as w}from"./chunk-FY5KHLMW.js";import"./chunk-773TH7FN.js";import"./chunk-AN525SPP.js";import"./chunk-IZ6DLEVY.js";import"./chunk-ZGTOK7ZK.js";import"./chunk-XW6HGSIT.js";import"./chunk-KG325WTN.js";import{c as R}from"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import"./chunk-QNG27G3T.js";import"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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"./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"./chunk-H7IWJN7L.js";import{a as t}from"./chunk-FTQLQJQV.js";function b(i){let{store:n,storeDir:s,backgroundReview:r,harnessEvaluationEnabled:o,harnessTasksetReview:c}=i,v=new AbortController,u=t(e=>{let g=e.signal?AbortSignal.any([e.signal,v.signal]):v.signal;return i.harnessEvaluationReviewStream({...e,signal:g})},"harnessEvaluationReviewStream"),l=m({store:n,storeDir:s,evaluationReviewStream:u});return{inspectHarness:t(()=>k(n),"inspectHarness"),reviewHarnessProposal:a(r,"Harness review",l.reviewHarnessProposalPayload),reviewHarness:a(o,"Harness evaluation",e=>H({store:n,request:e,stream:u,continuation:{storeDir:s,stream:u}})),acceptHarnessEvaluationReview:a(o,"Tasksets",e=>c.acceptEvaluationReview(e)),materializeHarnessEvaluationTaskset:a(o,"Tasksets",e=>c.materializeEvaluationTaskset(e)),runHarnessEvaluationBaseline:a(o,"Tasksets",e=>c.runEvaluationBaseline(e)),validateHarness:t(async()=>{let e=await R(n);return e?{valid:!0,workspaceId:e.workspaceId,harnessRelease:e.harnessRelease,agentSnapshot:e.agentSnapshot}:{valid:!1,reason:"No app-server Harness release is selected."}},"validateHarness"),updateHarnessBackgroundReview:a(r,"Background review",l.updateHarnessBackgroundReviewPayload),diffHarness:l.harnessDiffPayload,rollbackHarness:l.rollbackHarnessPayload,inspectRefiner:a(r,"Refiner",()=>d(s)),updateRefiner:a(r,"Refiner",e=>p(s,e)),activateRefiner:a(r,"Refiner",e=>f(s,e)),rollbackRefiner:a(r,"Refiner",e=>w(s,e)),async close(){v.abort(new Error("Harness runtime closed"))}}}t(b,"createAppServerHarnessServices");function a(i,n,s){return async(...r)=>{if(!i)throw new Error(`${n} is disabled in this app-server deployment.`);return s(...r)}}t(a,"guardService");export{b as createAppServerHarnessServices};
2
+ import{a as H,c as m,d as k}from"./chunk-JE7RJZOA.js";import"./chunk-65PL62KH.js";import{d,f as p,g as f,h as w}from"./chunk-I3HZKJB3.js";import"./chunk-773TH7FN.js";import"./chunk-AN525SPP.js";import"./chunk-IZ6DLEVY.js";import"./chunk-ZGTOK7ZK.js";import"./chunk-XW6HGSIT.js";import"./chunk-KG325WTN.js";import{c as R}from"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import"./chunk-QNG27G3T.js";import"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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"./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"./chunk-H7IWJN7L.js";import{a as t}from"./chunk-FTQLQJQV.js";function b(i){let{store:n,storeDir:s,backgroundReview:r,harnessEvaluationEnabled:o,harnessTasksetReview:c}=i,v=new AbortController,u=t(e=>{let g=e.signal?AbortSignal.any([e.signal,v.signal]):v.signal;return i.harnessEvaluationReviewStream({...e,signal:g})},"harnessEvaluationReviewStream"),l=m({store:n,storeDir:s,evaluationReviewStream:u});return{inspectHarness:t(()=>k(n),"inspectHarness"),reviewHarnessProposal:a(r,"Harness review",l.reviewHarnessProposalPayload),reviewHarness:a(o,"Harness evaluation",e=>H({store:n,request:e,stream:u,continuation:{storeDir:s,stream:u}})),acceptHarnessEvaluationReview:a(o,"Tasksets",e=>c.acceptEvaluationReview(e)),materializeHarnessEvaluationTaskset:a(o,"Tasksets",e=>c.materializeEvaluationTaskset(e)),runHarnessEvaluationBaseline:a(o,"Tasksets",e=>c.runEvaluationBaseline(e)),validateHarness:t(async()=>{let e=await R(n);return e?{valid:!0,workspaceId:e.workspaceId,harnessRelease:e.harnessRelease,agentSnapshot:e.agentSnapshot}:{valid:!1,reason:"No app-server Harness release is selected."}},"validateHarness"),updateHarnessBackgroundReview:a(r,"Background review",l.updateHarnessBackgroundReviewPayload),diffHarness:l.harnessDiffPayload,rollbackHarness:l.rollbackHarnessPayload,inspectRefiner:a(r,"Refiner",()=>d(s)),updateRefiner:a(r,"Refiner",e=>p(s,e)),activateRefiner:a(r,"Refiner",e=>f(s,e)),rollbackRefiner:a(r,"Refiner",e=>w(s,e)),async close(){v.abort(new Error("Harness runtime closed"))}}}t(b,"createAppServerHarnessServices");function a(i,n,s){return async(...r)=>{if(!i)throw new Error(`${n} is disabled in this app-server deployment.`);return s(...r)}}t(a,"guardService");export{b as createAppServerHarnessServices};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{l as c,m as d}from"./chunk-MULXCKG7.js";import"./chunk-D74JEERO.js";import"./chunk-JDEEWOD7.js";import"./chunk-OGDADQGH.js";import{b}from"./chunk-4NESNOK5.js";import"./chunk-BLXEAZCQ.js";import"./chunk-UCPGRPWY.js";import"./chunk-L6K7ERG5.js";import"./chunk-J2TWKFML.js";import"./chunk-773TH7FN.js";import"./chunk-HDL5YSAA.js";import"./chunk-ZFSHBFG5.js";import"./chunk-AN525SPP.js";import"./chunk-SYUKES6H.js";import"./chunk-HIOKCIL7.js";import"./chunk-GW766ZSO.js";import"./chunk-UKMA4R6X.js";import"./chunk-OQKJGTTO.js";import"./chunk-KVTBX2UP.js";import"./chunk-IZ6DLEVY.js";import"./chunk-A6USMRWK.js";import"./chunk-PCSIOUHF.js";import"./chunk-7KWD2I6W.js";import"./chunk-GPVCOEUH.js";import"./chunk-OLLLZVHF.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import"./chunk-ZGTOK7ZK.js";import"./chunk-XW6HGSIT.js";import"./chunk-KG325WTN.js";import"./chunk-3RCRSMWZ.js";import"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import"./chunk-PSGGOZFM.js";import"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{l as a}from"./chunk-VRIEKBBH.js";import"./chunk-QNG27G3T.js";import"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-BFKYRQMA.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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-QDC4OW3S.js";import"./chunk-ZZWAQBA2.js";import"./chunk-YR5ID2SS.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.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"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
2
+ import{l as c,m as d}from"./chunk-ZTNHW2K7.js";import"./chunk-D74JEERO.js";import"./chunk-JDEEWOD7.js";import"./chunk-6UDGARFC.js";import{b}from"./chunk-4NESNOK5.js";import"./chunk-BLXEAZCQ.js";import"./chunk-UCPGRPWY.js";import"./chunk-APB4O67E.js";import"./chunk-XX6SMFDY.js";import"./chunk-773TH7FN.js";import"./chunk-RWWE5OXU.js";import"./chunk-RNQF63ZR.js";import"./chunk-AN525SPP.js";import"./chunk-SYUKES6H.js";import"./chunk-HIOKCIL7.js";import"./chunk-GW766ZSO.js";import"./chunk-UKMA4R6X.js";import"./chunk-OQKJGTTO.js";import"./chunk-KVTBX2UP.js";import"./chunk-IZ6DLEVY.js";import"./chunk-A6USMRWK.js";import"./chunk-PCSIOUHF.js";import"./chunk-7KWD2I6W.js";import"./chunk-GPVCOEUH.js";import"./chunk-OLLLZVHF.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import"./chunk-ZGTOK7ZK.js";import"./chunk-XW6HGSIT.js";import"./chunk-KG325WTN.js";import"./chunk-TTVS6JMC.js";import"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import"./chunk-PSGGOZFM.js";import"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{l as a}from"./chunk-VRIEKBBH.js";import"./chunk-QNG27G3T.js";import"./chunk-EIRYMSEG.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"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-BFKYRQMA.js";import"./chunk-6QSSIT62.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-H6IW2R22.js";import"./chunk-L3KS6MOV.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-QDC4OW3S.js";import"./chunk-ZZWAQBA2.js";import"./chunk-YR5ID2SS.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-I7AQMAQI.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"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
2
  import{j as l,n as c}from"./chunk-QNG27G3T.js";import{z as n}from"./chunk-EIRYMSEG.js";import{a as t}from"./chunk-FTQLQJQV.js";import{mkdir as f}from"node:fs/promises";import p from"node:path";import a from"node:path";function d(e,o){let i=a.resolve(e),r=a.resolve(o);return r===i||r.startsWith(`${i}${a.sep}`)}t(d,"isHostedProfileSourceWithinRepo");async function u(e){if(!p.isAbsolute(e.repoPath)||!p.isAbsolute(e.outputDir)||!/^[a-f0-9]{40,64}$/.test(e.sourceRevision)||!e.workspaceId.trim()||!e.repositoryId.trim()||!e.profileId.trim())throw new Error("Hosted Profile compile request is invalid.");let o=await n({repoPath:e.repoPath,profileId:e.profileId});if(o.error||o.mode!=="local"||o.activeProfile!==e.profileId||!o.sourcePath||!d(e.repoPath,o.sourcePath))throw new Error("Hosted Profile source is unavailable.");await f(e.outputDir,{recursive:!0});let i=await l({storeDir:e.outputDir,workspaceId:e.workspaceId,name:e.profileId,profile:o,sourceRevision:e.sourceRevision,repositoryId:e.repositoryId}),r=i.harnessRelease.metadata.profile;if(!r||typeof r!="object"||r.id!==e.profileId||r.sourceRevision!==e.sourceRevision||r.repositoryId!==e.repositoryId)throw new Error("Hosted Profile release provenance is invalid.");let s=await c({storeDir:e.outputDir,workspaceId:e.workspaceId,compiled:i,createdAt:new Date().toISOString()});return{workspaceId:e.workspaceId,sourceRevision:s.sourceRevision,harnessRelease:s.harnessRelease,agentSnapshot:s.agentSnapshot,bundlePath:s.bundlePath}}t(u,"compileHostedProfileRelease");async function H(e){if(e.length!==1||e[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(e[0]))throw new Error("Hosted Profile compile argument is invalid.");let o=JSON.parse(Buffer.from(e[0],"base64url").toString("utf8")),i=await u(o);process.stdout.write(`${JSON.stringify(i)}
3
- `)}t(H,"runHostedProfileCompilerCli");async function y(e){await(await import("./hosted-profile-evaluation-preparation-IDJYREW3.js")).runHostedProfileEvaluationCli(e)}t(y,"runHostedProfileEvaluationCli");async function k(e){await(await import("./hosted-profile-evaluation-inspection-V6Z3A5XJ.js")).runHostedProfileInspectionCli(e)}t(k,"runHostedProfileInspectionCli");export{u as a,H as b,y as c,k as d};
3
+ `)}t(H,"runHostedProfileCompilerCli");async function y(e){await(await import("./hosted-profile-evaluation-preparation-ORVZ6MBD.js")).runHostedProfileEvaluationCli(e)}t(y,"runHostedProfileEvaluationCli");async function k(e){await(await import("./hosted-profile-evaluation-inspection-ZUANDYZ6.js")).runHostedProfileInspectionCli(e)}t(k,"runHostedProfileInspectionCli");export{u as a,H as b,y as c,k as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{e as v,t as x}from"./chunk-TTVS6JMC.js";import{a as l,c as j}from"./chunk-PSGGOZFM.js";import{Da as y,G as P,b as g,sb as E,ya as p}from"./chunk-QL4OIPEZ.js";import{v as w}from"./chunk-WJ43MJ3F.js";import{m as f}from"./chunk-3QIB5FXI.js";import{b as s}from"./chunk-ES2ISFJC.js";import{q as S}from"./chunk-H7IWJN7L.js";import{a as n}from"./chunk-FTQLQJQV.js";function z(e){if(e.kind==="command"||e.kind==="file_change")return!0;if(e.kind!=="permissions")return!1;try{let o=JSON.parse(e.detail);return!o.questions&&Array.isArray(o.options)&&o.options.some(r=>r.kind==="allow_once")&&o.options.some(r=>r.kind==="reject_once")}catch{return!1}}n(z,"remoteApprovalSupported");import{createHash as A}from"node:crypto";import{realpath as R,stat as O}from"node:fs/promises";var k=n(e=>A("sha256").update(g("POST","/local/ponder-project",e)).digest("hex"),"hash"),_=s.object({projectId:s.string().min(1).max(200),name:s.string().min(1).max(300),cwd:s.string().min(1).max(8192),sourceFolders:s.array(s.object({path:s.string().min(1).max(8192),realpath:s.string().min(1).max(8192)}).strict()).min(1).max(1e3),configurationHash:s.string().regex(/^[a-f0-9]{64}$/),revision:s.string().regex(/^[a-f0-9]{64}$/)}).strict();function X(e){let o=Object.values(S(e,"saved_local_projects"));if(o.length>p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");return o.map(r=>f.parse(r.value))}n(X,"readPonderLocalProjects");async function Y(e){if(e.hiddenFromDefaultSidebar)throw new Error("ponder_desktop_project_unavailable");let o=[...new Set([...e.sourceFolders??[e.path],e.path,...e.repoPath?[e.repoPath]:[]])];if(!o.length||o.length>1e3)throw new Error("ponder_desktop_project_folder_limit_exceeded");let r=await R(e.workspacePath);if(!(await O(r)).isDirectory())throw new Error("ponder_desktop_project_unavailable");let t=[];for(let c of o){let i=await R(c);if(!(await O(i)).isDirectory())throw new Error("ponder_desktop_project_unavailable");t.push({path:c,realpath:i})}let a={projectId:e.id,name:e.name,cwd:r,sourceFolders:t,configurationHash:k({id:e.id,name:e.name,path:e.path,workspacePath:e.workspacePath,repoPath:e.repoPath,sourceFolders:e.sourceFolders??null,hiddenFromDefaultSidebar:e.hiddenFromDefaultSidebar??!1})};return _.parse({...a,revision:k(a)})}n(Y,"capturePonderProjectSnapshot");import{createHash as D}from"node:crypto";var I=E,m=s.object({revision:s.number().int().positive(),owner:l,authority:I,project:_,shared:s.boolean(),updatedAt:s.string().datetime()}).strict(),b=m.omit({revision:!0}),h=n(e=>D("sha256").update(JSON.stringify(l.parse(e))).digest("hex"),"ownerKey");function N(e,o,r){let t=l.parse(o),a=I.parse(r),c=e.get("SELECT payload FROM ponder_desktop_authority WHERE id = 1"),i=c?y.parse(JSON.parse(c.payload)):null;if(!i||i.state!=="attached"||Date.parse(i.leaseExpiresAt)<=Date.now()||i.authorizationRevision!==a.authorizationRevision||!Object.entries(a.scope).every(([d,u])=>i.scope[d]===u)||i.scope.installationId!==t.installationId||i.scope.profileId!==t.profileId||i.scope.ownerUserId!==t.ownerUserId||i.scope.teamId!==t.teamId)throw new Error("ponder_desktop_project_authority_changed")}n(N,"assertAuthority");function ne(e,o){let r=b.parse(o);N(e,r.owner,r.authority);let t=h(r.owner),a=e.get("SELECT payload FROM ponder_project_sharing WHERE owner_key = ? AND project_id = ?",[t,r.project.projectId]);if(!a&&(e.get("SELECT count(*) AS count FROM ponder_project_sharing WHERE owner_key = ?",[t])?.count??0)>=p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");let c=a?m.parse(JSON.parse(a.payload)):null,i=c&&c.shared===r.shared&&c.project.revision===r.project.revision&&c.authority.authorizationRevision===r.authority.authorizationRevision&&Object.entries(r.authority.scope).every(([u,L])=>c.authority.scope[u]===L),d=m.parse({...r,revision:c?c.revision+(i?0:1):1});return e.run("INSERT INTO ponder_project_sharing (owner_key, project_id, payload) VALUES (?, ?, ?) ON CONFLICT(owner_key, project_id) DO UPDATE SET payload = excluded.payload",[t,r.project.projectId,JSON.stringify(d)]),d}n(ne,"setPonderProjectSharing");function ae(e,o){let r=e.all("SELECT payload FROM ponder_project_sharing WHERE owner_key = ? ORDER BY project_id LIMIT ?",[h(o),p+1]);if(r.length>p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");return r.map(t=>{let a=m.parse(JSON.parse(t.payload));if(h(a.owner)!==h(o))throw new Error("ponder_desktop_project_owner_changed");return a})}n(ae,"readPonderProjectSharing");function ie(e,o){return e.shared&&e.authority.authorizationRevision===o.authorizationRevision&&Object.entries(o.scope).every(([r,t])=>e.authority.scope[r]===t)}n(ie,"projectSharingMatchesAuthority");import{createHash as F}from"node:crypto";function ue(e,o,r){let t=F("sha256").update(JSON.stringify({ownership:x(e,o),paused:r.paused,activeTurnId:r.activeTurnId})).digest("hex");return Number.parseInt(t.slice(0,13),16)}n(ue,"remoteCommandTargetRevision");function le(e,o){let r=e.get("SELECT turn_id,paused,lease_until FROM task_inbox_turns WHERE session_id=?",[o]),t=r&&r.lease_until>Date.now()&&e.get("SELECT status FROM turns WHERE id=?",[r.turn_id])?.status==="in_progress";return{paused:!!r?.paused,activeTurnId:t?r.turn_id:null}}n(le,"readRemoteCommandTargetState");function he(e,o){if(o.payload.resume!==!0)return;if(o.action!=="follow_up")throw new Error("remote_resume_action_invalid");let r=e.get("SELECT turn_id,paused,lease_until FROM task_inbox_turns WHERE session_id=?",[o.localSessionId]),t=e.get("SELECT id,status FROM turns WHERE session_id=? ORDER BY sort_index DESC LIMIT 1",[o.localSessionId]);if(!o.expectedTurnId||t?.id!==o.expectedTurnId||r?.turn_id!==o.expectedTurnId||!r.paused||r.lease_until>Date.now()||!["completed","failed","interrupted"].includes(t.status))throw new Error("remote_resume_target_changed");e.run("UPDATE task_inbox_turns SET paused=0 WHERE session_id=?",[o.localSessionId])}n(he,"resumeRemoteTaskInput");import{createHash as M}from"node:crypto";function T(e){return w.parse({provider:e.provider,cwd:e.cwd,localProjectId:e.localProjectId,workspaceId:e.workspaceId,workspaceKind:e.workspaceKind,workspaceName:e.workspaceName,...e.modelRef?{modelRef:e.modelRef}:{},currentProfile:e.currentProfile,experience:e.experience,profileWorkflowBinding:e.profileWorkflowBinding,profileComponentBinding:e.profileComponentBinding,openPondCommandAccessMode:e.openPondCommandAccessMode})}n(T,"remoteStarterPayload");function q(e){return Number.parseInt(M("sha256").update(P({payload:T(e),owner:e.metadata?.ponderLocalOwner})).digest("hex").slice(0,13),16)}n(q,"remoteStarterRevision");function H(e,o){let r=new Map;for(let t of e){if(!j(t,o)||!t.localProjectId||!t.cwd||t.archived||t.status==="closed"||t.systemKind||t.hiddenFromDefaultSidebar||t.metadata?.nativeHistoryProjection||!v(t.provider)||["sandbox","sandbox_template","sandbox_app"].includes(t.workspaceKind??""))continue;try{T(t)}catch{continue}let a=`starter:${t.id}`;r.set(a,{source:t,target:{id:a,projectId:t.localProjectId,projectLabel:t.workspaceName??"Local project",title:`New ${t.provider} task in ${t.workspaceName??"local project"}`,revision:q(t)}})}return r}n(H,"captureRemoteStarters");function Pe(e){return async o=>{let r=await e.current();if(!r)throw new Error("remote_account_unavailable");let t=[];for(let c of await e.store.sessionShells()){let i=await e.store.getSession(c.id);i&&t.push(i)}let a=H(t,r.owner).get(o.localStarterId);if(!a||a.target.revision!==o.expectedRevision||a.target.projectId!==o.payload.projectId||a.target.revision!==o.payload.starterRevision)throw new Error("remote_starter_changed");return a.source}}n(Pe,"createRemoteStarterResolver");var C=class extends Error{constructor(r,t=409){super(r);this.status=t;this.name="LocalManagedMessageError"}status;static{n(this,"LocalManagedMessageError")}};export{ue as a,le as b,he as c,T as d,q as e,H as f,Pe as g,z as h,C as i,X as j,Y as k,ne as l,ae as m,ie as n};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{e as ye}from"./chunk-FY5KHLMW.js";import{a as we}from"./chunk-IZ6DLEVY.js";import{a as ve,c as Re}from"./chunk-NHQ36THU.js";import{t as he}from"./chunk-QOTVNQDI.js";import{a as B}from"./chunk-7ED24PP6.js";import{a as de,b as G,h as V,i as z,j as Y}from"./chunk-N4FFQPLR.js";import{k as le}from"./chunk-GJ2ZJFDD.js";import{m as ue,n as me,o as pe,p as fe,q as ge}from"./chunk-74ZXXBGN.js";import{m as E}from"./chunk-KGNCKIFP.js";import{a as i}from"./chunk-FTQLQJQV.js";function q(e){let t=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(e.replaceAll("\\","/"));if(!t)throw new Error(`Invalid Harness memory target: ${e}.`);return t[1]}i(q,"memoryKeyFromTarget");function Z(e,t){let r=e.metadata.expectedMemory;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Memory proposal is missing its expected revision snapshot.");let n=r;if(n.key!==q(t))throw new Error("Memory proposal expected revision targets a different key.");if(n.revision!==null&&(!Number.isInteger(n.revision)||Number(n.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(n.contentHash!==null&&typeof n.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(n.status!==null&&n.status!=="active"&&n.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");return{revision:n.revision,contentHash:n.contentHash,status:n.status}}i(Z,"expectedMemoryRevision");function ee(e){return{id:e.id,runRef:e.runRef,turnId:e.turnId,reason:e.reason,suggestedRoutes:e.suggestedRoutes,boundary:e.boundary}}i(ee,"boundedTriggerEvidence");function te(e){return{id:e.id,kind:e.kind,state:e.state,tool:e.tool?.name??null,deterministicClass:e.deterministicClass,summary:e.summary}}i(te,"boundedObservationEvidence");function re(e){let t=new Map;for(let r of e)for(let n of r.eventRefs){let o=Ne(r,n);t.set(`${o.kind}:${o.id}`,o)}return[...t.values()]}i(re,"proposalEvidence");function Ne(e,t){return{kind:e.kind==="recovery"?"recovery":e.kind==="validation"?"validation":e.kind==="user_turn"?"user_turn":"tool_event",id:t.id,contentHash:t.contentHash}}i(Ne,"observationEvidence");function j(e){let t=new Map;for(let r of e)for(let n of r.eventRefs)t.set(n.id,n);return[...t.values()]}i(j,"uniqueEventRefs");function U(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}i(U,"sameOverlayRef");function D(e){return{id:e.id,revision:e.revision,contentHash:e.contentHash}}i(D,"overlayRef");function ne(e,t){return e.revision===t.workspace.revision&&e.sourceRevision===t.workspace.sourceRevision&&e.currentChannel.revision===t.workspace.channelRevision&&e.currentChannel.release?.id===t.baseHarnessRelease.id&&e.currentChannel.release.contentHash===t.baseHarnessRelease.contentHash}i(ne,"sameWorkspaceRevision");function R(e,t){return`${e}-${E(t).slice(0,24)}`}i(R,"stableId");import{execFile as Fe}from"node:child_process";import{promises as N}from"node:fs";import x from"node:path";import{promisify as We}from"node:util";var Ve=36e3,ke=10,He=20*1024*1024,X=40,ze=24e3,Be=3,je=3,be=6,Te=["turn.started","assistant.delta","tool.started","tool.completed","skill.loaded","workspace_action_result","diagnostic","turn.completed","turn.failed","turn.interrupted"],Ue=We(Fe);async function Ee(e,t,r,n,o){let[a,s,l,g,m]=await Promise.all([e.getSession(t.runRef),e.getTurn(t.turnId),e.runtimeEventsForTurn(t.turnId,{names:Te}),e.turnsForSession(t.runRef,1e3),e.listModelUsageRecords({turnId:t.turnId,limit:1e4})]),d=[...g].sort((c,h)=>c.startedAt.localeCompare(h.startedAt)),y=d.findIndex(c=>c.id===t.turnId),u=y>0?d[y-1]:null,p=d.slice(Math.max(0,y-Be),Math.max(0,y)),b=new Map(await Promise.all(p.map(async c=>[c.id,await e.runtimeEventsForTurn(c.id,{names:["assistant.delta"]})]))),k=new Map(r.flatMap(c=>c.eventRefs.map(h=>[h.id,h]))),H=l.filter(c=>k.has(c.id));if(!o?.allowMissingRuntimeEvents)for(let[c,h]of k){let I=H.find(Le=>Le.id===c);if(!I||E(I)!==h.contentHash)throw new Error(`Refiner runtime event ${c} is unavailable or hash-mismatched.`)}let f=rt({events:l,exactEvents:H,turnId:t.turnId,boundarySequence:t.boundary.eventSequence,limit:t.policy.maxEvidenceEvents}),O=J(l,t.turnId),_=r.map(c=>c.kind),C=Ye(l,t.turnId),S={modelRequestCount:m.length||C.modelRequestCount,promptTokens:m.reduce((c,h)=>c+(h.promptTokens??0),0)||C.promptTokens,completionTokens:m.reduce((c,h)=>c+(h.completionTokens??0),0)||C.completionTokens,totalTokens:m.reduce((c,h)=>c+(h.totalTokens??0),0)||C.totalTokens},M={modelRequestCount:S.modelRequestCount,failedModelRequestCount:m.filter(c=>c.status==="failed"||c.status==="interrupted").length,promptTokens:S.promptTokens,completionTokens:S.completionTokens,totalTokens:S.totalTokens,toolFailureCount:_.filter(c=>c==="tool_failure").length,retryCount:_.filter(c=>c==="retry").length,recoveryCount:_.filter(c=>c==="recovery").length},F=await Ze(a?.cwd),L=l.filter(c=>c.turnId===t.turnId&&ot(c)&&(c.sequence===void 0||c.sequence<=t.boundary.eventSequence)).sort($),P=Ke(L),W=p.map(c=>Xe(c,b.get(c.id)??[])),v=n?await Je({store:e,workspaceId:n,trigger:t,observations:r}):[];return{task:{prompt:s?.prompt?T(s.prompt,8e3):null,assistantOutput:O,assistantOutputLinkCount:Se(O),previousAssistantOutput:u?J(b.get(u.id)??[],u.id):null},artifactDiagnostics:F,executionProfile:M,eventExcerpts:f.map(c=>{let h=A(c.data),I=A(h.result);return{id:c.id,name:c.name,action:c.action??(typeof h.tool=="string"?h.tool:null),status:c.status??null,command:w(I.command,3e3),error:w(c.error,2e3),output:w(I.output,2e3)??w(c.output,2e3),exitCode:typeof I.exitCode=="number"?I.exitCode:null,timedOut:I.timedOut===!0,stderr:w(I.stderr,3e3),stdout:w(I.stdout,3e3)}}),reviewPacket:{currentTurn:{id:t.turnId,status:s?.status??null,error:s?.error?T(s.error,2e3):null,prompt:s?.prompt?T(s.prompt,8e3):null,assistantOutput:O,assistantOutputLinkCount:Se(O)},priorConversation:W,timeline:P,artifacts:Ce(l,t.turnId),artifactDiagnostics:F,executionProfile:M,priorIncidents:v,truncation:{timelineEventCount:L.length,includedTimelineEventCount:P.length,timelineTruncated:P.length<L.length}}}}i(Ee,"loadBoundedRefinerContext");function Xe(e,t){return{turnId:e.id,status:e.status,prompt:e.prompt?T(e.prompt,3e3):null,assistantOutput:J(t,e.id,3e3)}}i(Xe,"conversationTurn");function Ke(e){let t=e.map(_e);if(t.length<=X)return Ie(t);let r=t.filter(a=>a.status==="failed"||a.name==="turn.completed"||a.name==="turn.failed"||a.name==="turn.interrupted"||a.name==="skill.loaded"||a.name==="validation.completed"||a.name==="diagnostic"),n=new Set(r.map(xe)),o=t.filter(a=>!n.has(xe(a))).slice(-(X-Math.min(r.length,X)));return Ie([...r.slice(-X),...o].sort((a,s)=>Number(a.sequence??0)-Number(s.sequence??0)))}i(Ke,"boundedReviewTimeline");function Ie(e){let t=[],r=0;for(let n of e){let o=JSON.stringify(n).length;r+o>ze||(t.push(n),r+=o)}return t}i(Ie,"fitTimelineToCharacterBudget");function _e(e){let t=A(e.data),r=A(t.result);return{sequence:e.sequence??null,timestamp:e.timestamp,name:e.name,action:e.action??(typeof t.tool=="string"?t.tool:null),status:e.status??null,args:Ge(e.args,1500),command:w(r.command,2e3),error:w(e.error,2e3),output:w(r.output,2e3)??w(e.output,2e3),exitCode:typeof r.exitCode=="number"?r.exitCode:null,timedOut:r.timedOut===!0,stderr:w(r.stderr,2e3),stdout:w(r.stdout,2e3)}}i(_e,"reviewTimelineEntry");function xe(e){return`${e.sequence??"none"}:${e.name??"unknown"}:${e.action??"none"}`}i(xe,"timelineEntryKey");function Ce(e,t){let r=new Map;for(let n of e)if(n.turnId===t)for(let o of oe(n.data))r.set(`${o.id}:${o.revision}`,o);return[...r.values()].sort((n,o)=>n.title.localeCompare(o.title)||n.revision-o.revision).slice(0,30).map(n=>({id:n.id,title:n.title,revision:n.revision,contentType:n.contentType,sizeBytes:n.sizeBytes,sha256:n.sha256,locationKind:n.location.kind,validation:n.validation.map(o=>({kind:o.kind,status:o.status,label:o.label,detail:o.detail??null}))}))}i(Ce,"fileOutputInventory");function oe(e,t=0){if(t>8)return[];let r=he.safeParse(e);return r.success?[r.data]:Array.isArray(e)?e.flatMap(n=>oe(n,t+1)):!e||typeof e!="object"?[]:Object.values(e).flatMap(n=>oe(n,t+1))}i(oe,"findFileOutputRefs");async function Je(e){let t=new Set(e.observations.flatMap(s=>s.deterministicClass?[s.deterministicClass]:[])),r=new Set(e.observations.flatMap(s=>s.tool?[s.tool.name]:[]));if(t.size===0&&r.size===0)return[];let n=(await e.store.listHarnessImprovementArtifacts(e.workspaceId,"observation",200)).filter(s=>s.runRef!==e.trigger.runRef&&s.turnId!==e.trigger.turnId&&(s.deterministicClass!==null&&t.has(s.deterministicClass)||s.tool!==null&&r.has(s.tool.name))).sort((s,l)=>l.createdAt.localeCompare(s.createdAt)),o=new Map;for(let s of n){let l=`${s.runRef}:${s.turnId}`,g=o.get(l)??[];g.push(s),o.set(l,g)}let a=[];for(let s of o.values()){if(a.length>=je)break;let l=s[0],[g,m]=await Promise.all([e.store.getTurn(l.turnId),e.store.runtimeEventsForTurn(l.turnId,{names:Te})]);if(!g)continue;let d=[...new Set(s.flatMap(p=>p.deterministicClass&&t.has(p.deterministicClass)?[p.deterministicClass]:[]))],y=[...new Set(s.flatMap(p=>p.tool&&r.has(p.tool.name)?[p.tool.name]:[]))],u=Qe(m.filter(p=>p.turnId===g.id));a.push({runRef:l.runRef,turnId:l.turnId,createdAt:l.createdAt,matchedBy:{deterministicClasses:d,tools:y},observations:s.slice(0,4).map(p=>({kind:p.kind,state:p.state,deterministicClass:p.deterministicClass,summary:p.summary})),prompt:g.prompt?T(g.prompt,1200):null,assistantOutput:J(m,g.id,1200),timeline:u,artifacts:Ce(m,g.id).slice(0,5)})}return a}i(Je,"loadRelevantPriorIncidentPackets");function Qe(e){let t=new Set(["turn.completed","turn.failed","turn.interrupted"]),r=e.filter(a=>{if(t.has(a.name))return!0;let s=JSON.stringify({error:a.error,output:a.output,data:a.data});return a.status==="failed"||/"ok"\s*:\s*false|failed|denied|unavailable|timed?\s*out|exception|traceback/i.test(s)}).sort($).map(a=>{let s=_e(a);return{sequence:s.sequence,name:s.name,action:s.action,status:s.status,error:w(s.error,800),output:w(s.output,800),exitCode:s.exitCode,timedOut:s.timedOut}}),n=new Map;for(let a of r){let s=JSON.stringify({name:a.name,action:a.action,status:a.status,error:a.error,output:a.output,exitCode:a.exitCode,timedOut:a.timedOut}),l=n.get(s);if(l){l.occurrenceCount+=1;continue}n.set(s,{...a,occurrenceCount:1})}let o=[...n.values()];return o.length<=be?o:[...o.slice(0,be-2),...o.slice(-2)]}i(Qe,"priorIncidentTimeline");function Ge(e,t){if(e===void 0)return null;try{let r=T(JSON.stringify(e),t);return JSON.parse(r.endsWith(`
2
+ import{e as ye}from"./chunk-I3HZKJB3.js";import{a as we}from"./chunk-IZ6DLEVY.js";import{a as ve,c as Re}from"./chunk-NHQ36THU.js";import{t as he}from"./chunk-QL4OIPEZ.js";import{a as B}from"./chunk-7ED24PP6.js";import{a as de,b as G,h as V,i as z,j as Y}from"./chunk-N4FFQPLR.js";import{k as le}from"./chunk-GJ2ZJFDD.js";import{m as ue,n as me,o as pe,p as fe,q as ge}from"./chunk-74ZXXBGN.js";import{m as E}from"./chunk-KGNCKIFP.js";import{a as i}from"./chunk-FTQLQJQV.js";function q(e){let t=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(e.replaceAll("\\","/"));if(!t)throw new Error(`Invalid Harness memory target: ${e}.`);return t[1]}i(q,"memoryKeyFromTarget");function Z(e,t){let r=e.metadata.expectedMemory;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Memory proposal is missing its expected revision snapshot.");let n=r;if(n.key!==q(t))throw new Error("Memory proposal expected revision targets a different key.");if(n.revision!==null&&(!Number.isInteger(n.revision)||Number(n.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(n.contentHash!==null&&typeof n.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(n.status!==null&&n.status!=="active"&&n.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");return{revision:n.revision,contentHash:n.contentHash,status:n.status}}i(Z,"expectedMemoryRevision");function ee(e){return{id:e.id,runRef:e.runRef,turnId:e.turnId,reason:e.reason,suggestedRoutes:e.suggestedRoutes,boundary:e.boundary}}i(ee,"boundedTriggerEvidence");function te(e){return{id:e.id,kind:e.kind,state:e.state,tool:e.tool?.name??null,deterministicClass:e.deterministicClass,summary:e.summary}}i(te,"boundedObservationEvidence");function re(e){let t=new Map;for(let r of e)for(let n of r.eventRefs){let o=Ne(r,n);t.set(`${o.kind}:${o.id}`,o)}return[...t.values()]}i(re,"proposalEvidence");function Ne(e,t){return{kind:e.kind==="recovery"?"recovery":e.kind==="validation"?"validation":e.kind==="user_turn"?"user_turn":"tool_event",id:t.id,contentHash:t.contentHash}}i(Ne,"observationEvidence");function j(e){let t=new Map;for(let r of e)for(let n of r.eventRefs)t.set(n.id,n);return[...t.values()]}i(j,"uniqueEventRefs");function U(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}i(U,"sameOverlayRef");function D(e){return{id:e.id,revision:e.revision,contentHash:e.contentHash}}i(D,"overlayRef");function ne(e,t){return e.revision===t.workspace.revision&&e.sourceRevision===t.workspace.sourceRevision&&e.currentChannel.revision===t.workspace.channelRevision&&e.currentChannel.release?.id===t.baseHarnessRelease.id&&e.currentChannel.release.contentHash===t.baseHarnessRelease.contentHash}i(ne,"sameWorkspaceRevision");function R(e,t){return`${e}-${E(t).slice(0,24)}`}i(R,"stableId");import{execFile as Fe}from"node:child_process";import{promises as N}from"node:fs";import x from"node:path";import{promisify as We}from"node:util";var Ve=36e3,ke=10,He=20*1024*1024,X=40,ze=24e3,Be=3,je=3,be=6,Te=["turn.started","assistant.delta","tool.started","tool.completed","skill.loaded","workspace_action_result","diagnostic","turn.completed","turn.failed","turn.interrupted"],Ue=We(Fe);async function Ee(e,t,r,n,o){let[a,s,l,g,m]=await Promise.all([e.getSession(t.runRef),e.getTurn(t.turnId),e.runtimeEventsForTurn(t.turnId,{names:Te}),e.turnsForSession(t.runRef,1e3),e.listModelUsageRecords({turnId:t.turnId,limit:1e4})]),d=[...g].sort((c,h)=>c.startedAt.localeCompare(h.startedAt)),y=d.findIndex(c=>c.id===t.turnId),u=y>0?d[y-1]:null,p=d.slice(Math.max(0,y-Be),Math.max(0,y)),b=new Map(await Promise.all(p.map(async c=>[c.id,await e.runtimeEventsForTurn(c.id,{names:["assistant.delta"]})]))),k=new Map(r.flatMap(c=>c.eventRefs.map(h=>[h.id,h]))),H=l.filter(c=>k.has(c.id));if(!o?.allowMissingRuntimeEvents)for(let[c,h]of k){let I=H.find(Le=>Le.id===c);if(!I||E(I)!==h.contentHash)throw new Error(`Refiner runtime event ${c} is unavailable or hash-mismatched.`)}let f=rt({events:l,exactEvents:H,turnId:t.turnId,boundarySequence:t.boundary.eventSequence,limit:t.policy.maxEvidenceEvents}),O=J(l,t.turnId),_=r.map(c=>c.kind),C=Ye(l,t.turnId),S={modelRequestCount:m.length||C.modelRequestCount,promptTokens:m.reduce((c,h)=>c+(h.promptTokens??0),0)||C.promptTokens,completionTokens:m.reduce((c,h)=>c+(h.completionTokens??0),0)||C.completionTokens,totalTokens:m.reduce((c,h)=>c+(h.totalTokens??0),0)||C.totalTokens},M={modelRequestCount:S.modelRequestCount,failedModelRequestCount:m.filter(c=>c.status==="failed"||c.status==="interrupted").length,promptTokens:S.promptTokens,completionTokens:S.completionTokens,totalTokens:S.totalTokens,toolFailureCount:_.filter(c=>c==="tool_failure").length,retryCount:_.filter(c=>c==="retry").length,recoveryCount:_.filter(c=>c==="recovery").length},F=await Ze(a?.cwd),L=l.filter(c=>c.turnId===t.turnId&&ot(c)&&(c.sequence===void 0||c.sequence<=t.boundary.eventSequence)).sort($),P=Ke(L),W=p.map(c=>Xe(c,b.get(c.id)??[])),v=n?await Je({store:e,workspaceId:n,trigger:t,observations:r}):[];return{task:{prompt:s?.prompt?T(s.prompt,8e3):null,assistantOutput:O,assistantOutputLinkCount:Se(O),previousAssistantOutput:u?J(b.get(u.id)??[],u.id):null},artifactDiagnostics:F,executionProfile:M,eventExcerpts:f.map(c=>{let h=A(c.data),I=A(h.result);return{id:c.id,name:c.name,action:c.action??(typeof h.tool=="string"?h.tool:null),status:c.status??null,command:w(I.command,3e3),error:w(c.error,2e3),output:w(I.output,2e3)??w(c.output,2e3),exitCode:typeof I.exitCode=="number"?I.exitCode:null,timedOut:I.timedOut===!0,stderr:w(I.stderr,3e3),stdout:w(I.stdout,3e3)}}),reviewPacket:{currentTurn:{id:t.turnId,status:s?.status??null,error:s?.error?T(s.error,2e3):null,prompt:s?.prompt?T(s.prompt,8e3):null,assistantOutput:O,assistantOutputLinkCount:Se(O)},priorConversation:W,timeline:P,artifacts:Ce(l,t.turnId),artifactDiagnostics:F,executionProfile:M,priorIncidents:v,truncation:{timelineEventCount:L.length,includedTimelineEventCount:P.length,timelineTruncated:P.length<L.length}}}}i(Ee,"loadBoundedRefinerContext");function Xe(e,t){return{turnId:e.id,status:e.status,prompt:e.prompt?T(e.prompt,3e3):null,assistantOutput:J(t,e.id,3e3)}}i(Xe,"conversationTurn");function Ke(e){let t=e.map(_e);if(t.length<=X)return Ie(t);let r=t.filter(a=>a.status==="failed"||a.name==="turn.completed"||a.name==="turn.failed"||a.name==="turn.interrupted"||a.name==="skill.loaded"||a.name==="validation.completed"||a.name==="diagnostic"),n=new Set(r.map(xe)),o=t.filter(a=>!n.has(xe(a))).slice(-(X-Math.min(r.length,X)));return Ie([...r.slice(-X),...o].sort((a,s)=>Number(a.sequence??0)-Number(s.sequence??0)))}i(Ke,"boundedReviewTimeline");function Ie(e){let t=[],r=0;for(let n of e){let o=JSON.stringify(n).length;r+o>ze||(t.push(n),r+=o)}return t}i(Ie,"fitTimelineToCharacterBudget");function _e(e){let t=A(e.data),r=A(t.result);return{sequence:e.sequence??null,timestamp:e.timestamp,name:e.name,action:e.action??(typeof t.tool=="string"?t.tool:null),status:e.status??null,args:Ge(e.args,1500),command:w(r.command,2e3),error:w(e.error,2e3),output:w(r.output,2e3)??w(e.output,2e3),exitCode:typeof r.exitCode=="number"?r.exitCode:null,timedOut:r.timedOut===!0,stderr:w(r.stderr,2e3),stdout:w(r.stdout,2e3)}}i(_e,"reviewTimelineEntry");function xe(e){return`${e.sequence??"none"}:${e.name??"unknown"}:${e.action??"none"}`}i(xe,"timelineEntryKey");function Ce(e,t){let r=new Map;for(let n of e)if(n.turnId===t)for(let o of oe(n.data))r.set(`${o.id}:${o.revision}`,o);return[...r.values()].sort((n,o)=>n.title.localeCompare(o.title)||n.revision-o.revision).slice(0,30).map(n=>({id:n.id,title:n.title,revision:n.revision,contentType:n.contentType,sizeBytes:n.sizeBytes,sha256:n.sha256,locationKind:n.location.kind,validation:n.validation.map(o=>({kind:o.kind,status:o.status,label:o.label,detail:o.detail??null}))}))}i(Ce,"fileOutputInventory");function oe(e,t=0){if(t>8)return[];let r=he.safeParse(e);return r.success?[r.data]:Array.isArray(e)?e.flatMap(n=>oe(n,t+1)):!e||typeof e!="object"?[]:Object.values(e).flatMap(n=>oe(n,t+1))}i(oe,"findFileOutputRefs");async function Je(e){let t=new Set(e.observations.flatMap(s=>s.deterministicClass?[s.deterministicClass]:[])),r=new Set(e.observations.flatMap(s=>s.tool?[s.tool.name]:[]));if(t.size===0&&r.size===0)return[];let n=(await e.store.listHarnessImprovementArtifacts(e.workspaceId,"observation",200)).filter(s=>s.runRef!==e.trigger.runRef&&s.turnId!==e.trigger.turnId&&(s.deterministicClass!==null&&t.has(s.deterministicClass)||s.tool!==null&&r.has(s.tool.name))).sort((s,l)=>l.createdAt.localeCompare(s.createdAt)),o=new Map;for(let s of n){let l=`${s.runRef}:${s.turnId}`,g=o.get(l)??[];g.push(s),o.set(l,g)}let a=[];for(let s of o.values()){if(a.length>=je)break;let l=s[0],[g,m]=await Promise.all([e.store.getTurn(l.turnId),e.store.runtimeEventsForTurn(l.turnId,{names:Te})]);if(!g)continue;let d=[...new Set(s.flatMap(p=>p.deterministicClass&&t.has(p.deterministicClass)?[p.deterministicClass]:[]))],y=[...new Set(s.flatMap(p=>p.tool&&r.has(p.tool.name)?[p.tool.name]:[]))],u=Qe(m.filter(p=>p.turnId===g.id));a.push({runRef:l.runRef,turnId:l.turnId,createdAt:l.createdAt,matchedBy:{deterministicClasses:d,tools:y},observations:s.slice(0,4).map(p=>({kind:p.kind,state:p.state,deterministicClass:p.deterministicClass,summary:p.summary})),prompt:g.prompt?T(g.prompt,1200):null,assistantOutput:J(m,g.id,1200),timeline:u,artifacts:Ce(m,g.id).slice(0,5)})}return a}i(Je,"loadRelevantPriorIncidentPackets");function Qe(e){let t=new Set(["turn.completed","turn.failed","turn.interrupted"]),r=e.filter(a=>{if(t.has(a.name))return!0;let s=JSON.stringify({error:a.error,output:a.output,data:a.data});return a.status==="failed"||/"ok"\s*:\s*false|failed|denied|unavailable|timed?\s*out|exception|traceback/i.test(s)}).sort($).map(a=>{let s=_e(a);return{sequence:s.sequence,name:s.name,action:s.action,status:s.status,error:w(s.error,800),output:w(s.output,800),exitCode:s.exitCode,timedOut:s.timedOut}}),n=new Map;for(let a of r){let s=JSON.stringify({name:a.name,action:a.action,status:a.status,error:a.error,output:a.output,exitCode:a.exitCode,timedOut:a.timedOut}),l=n.get(s);if(l){l.occurrenceCount+=1;continue}n.set(s,{...a,occurrenceCount:1})}let o=[...n.values()];return o.length<=be?o:[...o.slice(0,be-2),...o.slice(-2)]}i(Qe,"priorIncidentTimeline");function Ge(e,t){if(e===void 0)return null;try{let r=T(JSON.stringify(e),t);return JSON.parse(r.endsWith(`
3
3
  [truncated]`)?JSON.stringify(r):r)}catch{return T(String(e),t)}}i(Ge,"boundedUnknown");function Ye(e,t){let r={modelRequestCount:0,promptTokens:0,completionTokens:0,totalTokens:0},n=[...e].reverse().find(o=>o.turnId===t&&o.name==="diagnostic"&&o.action==="taskset_grade"&&typeof o.output=="string");if(!n?.output)return r;try{let o=A(JSON.parse(n.output)),a=A(o.attempt),s=A(a.usage);return{modelRequestCount:K(a.modelRequestCount),promptTokens:K(s.promptTokens),completionTokens:K(s.completionTokens),totalTokens:K(s.totalTokens)}}catch{return r}}i(Ye,"tasksetGradeExecutionProfile");function K(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):0}i(K,"nonnegativeInteger");async function Ze(e){if(!e)return[];let t=[];for(let r of[e,x.join(e,"outputs")]){let n=await N.readdir(r,{withFileTypes:!0}).catch(()=>[]);for(let o of n)if(!(!o.isFile()||!o.name.toLowerCase().endsWith(".pdf"))&&(t.push({filename:x.join(r,o.name),displayPath:x.relative(e,x.join(r,o.name)).replaceAll(x.sep,"/")}),t.length>=ke))break;if(t.length>=ke)break}return Promise.all(t.map(async({filename:r,displayPath:n})=>{try{if((await N.stat(r)).size>He)return{path:n,mediaType:"application/pdf",check:"pdf_text_bounds",status:"unavailable",reason:`artifact exceeds ${He} byte inspection bound`};let{stdout:a}=await Ue("pdftotext",["-bbox",r,"-"],{env:{...process.env,PATH:we()},maxBuffer:8*1024*1024,timeout:15e3});return et(n,a)}catch(o){return{path:n,mediaType:"application/pdf",check:"pdf_text_bounds",status:"unavailable",reason:o instanceof Error?o.message.slice(0,500):String(o).slice(0,500)}}}))}i(Ze,"inspectBoundedPdfArtifactDiagnostics");function et(e,t){let r=[],n=0;for(let o of t.matchAll(/<page\s+width="([^"]+)"\s+height="([^"]+)"[^>]*>([\s\S]*?)<\/page>/g)){n+=1;let a=Number(o[1]),s=Number(o[2]);for(let l of o[3].matchAll(/<word\s+xMin="([^"]+)"\s+yMin="([^"]+)"\s+xMax="([^"]+)"\s+yMax="([^"]+)"[^>]*>([\s\S]*?)<\/word>/g)){let[g,m,d,y]=l.slice(1,5).map(Number);g>=0&&m>=0&&d<=a&&y<=s||r.push({page:n,text:tt(l[5]).slice(0,120),xMin:g,yMin:m,xMax:d,yMax:y,pageWidth:a,pageHeight:s})}}return{path:e,mediaType:"application/pdf",check:"pdf_text_bounds",status:r.length>0?"failed":"passed",pages:n,clippedTextCount:r.length,examples:r.slice(0,10)}}i(et,"pdfTextBoundsDiagnostic");function tt(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'")}i(tt,"decodeXmlText");function Se(e){return e?e.match(/https?:\/\/[^\s<>)\]}"']+/gi)?.length??0:0}i(Se,"countAbsoluteLinks");function J(e,t,r=8e3){let n=e.filter(o=>o.turnId===t&&o.name==="assistant.delta"&&typeof o.output=="string").sort($).map(o=>o.output).join("");return n?T(n,r):null}i(J,"assistantOutputForTurn");async function Ae(e,t,r){let n=await e.listHarnessImprovementArtifacts(t,"observation",1e3),o=new Map(n.map(a=>{let s=de.parse(a);return[s.contentHash,s]}));return r.observations.map(a=>{let s=o.get(a.contentHash);if(!s||s.id!==a.id)throw new Error(`Refiner observation ${a.id} is unavailable or hash-mismatched.`);return s})}i(Ae,"loadExactObservations");async function se(e,t,r={}){let n=st(t),o=r.forceUnloaded!==!0,a=i((u,p)=>o&&(u==="instruction"||u==="skill"&&n.has(at(p))),"wasLoaded"),s=x.resolve(e,"source"),l=B.parse(JSON.parse(await N.readFile(x.join(s,"harness.json"),"utf8"))),g=Ve,m=[],d=l.files.filter(u=>["instruction","skill","agent"].includes(u.kind)&&u.visibility==="policy").map(u=>({path:u.path,kind:u.kind,loaded:a(u.kind,u.path)})),y=l.files.slice().sort((u,p)=>{let b=["instruction","skill","agent"].includes(u.kind)&&a(u.kind,u.path),k=["instruction","skill","agent"].includes(p.kind)&&a(p.kind,p.path);if(b!==k)return b?-1:1;let H=i(f=>f==="instruction"?0:f==="skill"?1:2,"rank");return H(u.kind)-H(p.kind)||u.path.localeCompare(p.path)});for(let u of y){if(!["instruction","skill","agent"].includes(u.kind)||u.visibility!=="policy"||!["text/markdown","text/plain","text/javascript"].includes(u.mediaType))continue;let p=it(s,u.path),b=await N.lstat(p);if(!b.isFile()||b.isSymbolicLink())continue;let k=await N.readFile(p);k.byteLength>g||(m.push({path:u.path,kind:u.kind,content:k.toString("utf8"),loaded:a(u.kind,u.path)}),g-=k.byteLength)}return{manifest:l,files:m,catalog:d}}i(se,"readBoundedRefinerSource");function rt(e){let t=[...e.exactEvents].sort($),r=e.events.filter(l=>l.turnId===e.turnId&&nt(l)&&(l.sequence===void 0||l.sequence<=e.boundarySequence)).sort($);if(r.length<=e.limit)return r;let n=new Set(t.map(l=>l.id)),o=t.slice(0,e.limit),a=e.limit-o.length;if(a<=0)return o;let s=r.filter(l=>!n.has(l.id)).slice(-a);return[...o,...s].sort($)}i(rt,"selectRefinerEvidenceWindow");function nt(e){return["tool.completed","workspace_action_result","skill.loaded","validation.completed","diagnostic"].includes(e.name)}i(nt,"isRefinerEvidenceEvent");function ot(e){return["turn.completed","turn.failed","turn.interrupted","tool.completed","workspace_action_result","skill.loaded","validation.completed","diagnostic"].includes(e.name)}i(ot,"isRefinerReviewTimelineEvent");function $(e,t){return(e.sequence??Number.MAX_SAFE_INTEGER)-(t.sequence??Number.MAX_SAFE_INTEGER)}i($,"compareRuntimeEvents");function w(e,t){return typeof e=="string"?T(e,t):null}i(w,"textField");function T(e,t){let r=e.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [redacted]").replace(/\b(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]");return r.length<=t?r:`${r.slice(0,t)}
4
4
  [truncated]`}i(T,"redactAndBoundRefinerText");function st(e){let t=e.metadata.loadedSkillNames;return Array.isArray(t)?new Set(t.filter(r=>typeof r=="string"&&r.trim().length>0)):new Set}i(st,"loadedSkillNamesFromTrigger");function at(e){return/^skills\/([^/]+)\/SKILL\.md$/.exec(e.replaceAll("\\","/"))?.[1]??""}i(at,"skillNameFromPath");function it(e,t){let r=x.resolve(e,...t.replaceAll("\\","/").split("/")),n=x.relative(e,r);if(!n||n.startsWith("..")||x.isAbsolute(n))throw new Error(`Harness source path escapes its immutable bundle: ${t}`);return r}i(it,"containedSourcePath");function A(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(A,"asRecord");async function Oe(e){let t=e.rebasedOntoCurrent?e.workspace.currentChannel.release:e.overlay.baseHarnessRelease;if(!t)throw new Error("Queued Refiner trigger references a Harness workspace without a current release.");let r=await e.store.getHarnessReleaseRecord(t.contentHash);if(!r||r.harnessRelease.id!==t.id||r.workspaceId!==e.workspace.id)throw new Error("Queued Refiner trigger references an unavailable effective Harness release.");let n=await se(r.bundlePath,e.trigger,{forceUnloaded:e.rebasedOntoCurrent}),o=e.rebasedOntoCurrent?await e.store.getHarnessReleaseRecord(e.overlay.baseHarnessRelease.contentHash):r;if(!o||o.harnessRelease.id!==e.overlay.baseHarnessRelease.id||o.workspaceId!==e.workspace.id)throw new Error("Queued Refiner trigger references an unavailable admitted Harness release.");return{admittedSource:e.rebasedOntoCurrent?await se(o.bundlePath,e.trigger):n,effectiveReleaseRef:t,release:r,source:n}}i(Oe,"loadRefinerReleaseContext");function Me(e,t){if(t.requestId!==e.requestId||t.evidenceHash!==e.evidenceHash||t.admittedRelease.id!==e.harness.admittedRelease.id||t.admittedRelease.contentHash!==e.harness.admittedRelease.contentHash||t.currentRelease.id!==e.harness.currentRelease.id||t.currentRelease.contentHash!==e.harness.currentRelease.contentHash)throw new Error("Managed Harness Refiner response binding does not match the request.")}i(Me,"assertHostedResponseBinding");function Q(e){return{id:e.id,contentHash:e.contentHash,coreHash:e.coreHash,profileHash:e.profileHash}}i(Q,"refinerReleaseMetadata");async function Pe(e,t,r){return(await e.listHarnessImprovementArtifacts(t,"refiner_outcome",1e3)).find(o=>o.trigger.id===r.id&&o.trigger.contentHash===r.contentHash)??null}i(Pe,"findRefinerOutcome");async function ae(e,t,r){return(await e.listHarnessImprovementArtifacts(t,"proposal",1e3)).find(o=>o.id===r)??null}i(ae,"findProposal");async function qe(e,t,r){let n=await ae(e,t,R("proposal",r.contentHash)),o=n?.metadata.trigger;return o?.id===r.id&&o.contentHash===r.contentHash?n:null}i(qe,"findProposalByTrigger");async function ie(e,t,r){return(await e.listHarnessImprovementArtifacts(t,"targeted_validation",1e3)).filter(o=>o.proposal.id===r.id&&o.proposal.contentHash===r.contentHash)}i(ie,"findProposalValidations");var De=new WeakMap;async function zt(e){let t=G.parse(e.trigger).contentHash,r=De.get(e.store);r||(r=new Map,De.set(e.store,r));let n=r.get(t);if(n)return n;let o=ct(e);r.set(t,o);try{return await o}finally{r.get(t)===o&&r.delete(t)}}i(zt,"runLocalHarnessRefinerWorker");async function ct(e){let t=G.parse(e.trigger);if(t.decision!=="queue_refiner")throw new Error("The model-backed Refiner only accepts queue_refiner decisions.");if(!t.overlay)throw new Error("A queued Local Harness Refiner decision requires a run overlay.");let r=await e.store.getHarnessRunOverlay(t.runRef);if(!r||!U(r,t.overlay))throw new Error("Queued Refiner trigger does not match the durable run overlay.");let n=await e.store.getHarnessWorkspace(r.workspace.workspaceId);if(!n||n.location!==e.store.harnessStoragePlacement)throw new Error("Harness Refiner workspace does not match the admitted storage placement.");let o=await Pe(e.store,n.id,t);if(o){let v=o.proposal?await ae(e.store,n.id,o.proposal.id):null;return{outcome:o,overlay:await e.store.getHarnessRunOverlay(t.runRef)??r,proposal:v,validations:v?await ie(e.store,n.id,v):[],workspace:await e.store.getHarnessWorkspace(n.id)??n,advanceReceipt:null,applyReceipt:null}}let a=await Ae(e.store,n.id,t),s=!ne(n,r);if(r.status!=="active"){let v=await qe(e.store,n.id,t);return v&&U(r,v.overlay)?$e({...e,trigger:t,workspace:n,overlay:r,proposal:v,observations:a}):ce({store:e.store,workspace:n,overlay:r,trigger:t,observations:a,reason:`The run overlay is ${r.status} and has no recoverable proposal for this trigger.`,now:e.now})}let{admittedSource:l,effectiveReleaseRef:g,release:m,source:d}=await Oe({store:e.store,workspace:n,overlay:r,trigger:t,rebasedOntoCurrent:s}),y=(await e.store.listHarnessMemories(n.id)).slice(0,100).map(v=>({path:`memory/${v.key}`,kind:"memory",content:v.content,loaded:!0}));d.catalog.push(...y.map(({path:v,kind:c,loaded:h})=>({path:v,kind:c,loaded:h}))),d.files.push(...y);let u=await Ee(e.store,t,a,n.id,{allowMissingRuntimeEvents:e.reviewScope==="cross_run_candidate"}),p={memory:!0,prompt:!0,skill:!0,agent:!1},b=[...a.map(v=>v.id),...u.reviewPacket.priorIncidents.flatMap(v=>typeof v.id=="string"&&v.id.trim()?[v.id.trim()]:[])],k={capabilities:p,trigger:ee(t),observations:a.map(te),admissibleEvidenceIds:b,reviewPacket:u.reviewPacket,runtimeActivation:{admittedRelease:r.baseHarnessRelease,currentRelease:g,rebasedOntoCurrent:s,admittedSourceFiles:l.files,admittedSourceCatalog:l.catalog},sourceFiles:d.files,sourceCatalog:d.catalog,additionalEvidence:e.additionalEvidence??null},H=await(e.loadActiveRefinerRelease?e.loadActiveRefinerRelease():ye(e.storeDir)),f;if(e.stream)f=await ue({evidence:k,stream:e.stream,signal:e.signal,timeoutMs:e.timeoutMs,reviewProfile:H.profile});else if(e.refine){let v=fe.parse({schemaVersion:"openpond.hostedHarnessRefinerRequest.v2",requestId:t.id,idempotencyKey:t.contentHash,evidenceHash:E(k),harness:{admittedRelease:r.baseHarnessRelease,currentRelease:g,overlay:D(r),workspace:{id:n.id,revision:n.revision,sourceRevision:n.sourceRevision,channelRevision:n.currentChannel.revision},capabilities:p},evidence:k}),c=ge.parse(await e.refine({request:v,signal:e.signal}));Me(v,c),f=c.decision}else throw new Error("Harness Refiner requires a public model stream or managed adapter.");if(f=pe({decision:f,evidence:k}),f=me(f,H.profile),f.decision==="no_action")return ce({store:e.store,workspace:n,overlay:r,trigger:t,observations:a,reason:f.reason,metadata:{refinerRelease:Q(H)},now:e.now});if(f.decision==="route")return dt({store:e.store,workspace:n,overlay:r,trigger:t,observations:a,decision:f,refinerRelease:Q(H),now:e.now});ut(f,d.catalog,d.files);let O=mt(f,d.files),_=f.route==="memory"?await e.store.getHarnessMemory(n.id,q(f.target)):null,C=(e.now??(()=>new Date().toISOString()))(),S=gt(f),M=ft({trigger:t,decision:f,materializedContent:O,manifest:d.manifest,effects:S}),F=R("proposal",t.contentHash),L=R("targeted-check",{trigger:t.contentHash,route:f.route,target:f.target}),P=re(a),W=await e.store.freezeHarnessRunOverlayWithProposalAtomically({runId:t.runRef,expectedRevision:r.revision,edits:M,updatedAt:C,buildProposal:i(v=>le({schemaVersion:"openpond.harnessImprovementProposal.v1",id:F,overlay:D(v),baseHarnessRelease:{id:m.harnessRelease.id,contentHash:m.harnessRelease.contentHash},expectedWorkspace:{workspaceId:n.id,revision:n.revision,sourceRevision:n.sourceRevision,channelRevision:n.currentChannel.revision},requestedScope:"personal",route:f.route,risk:f.operation==="delete"||S.some(c=>!["text_instruction","memory","dependency_selection"].includes(c))?"review":"low",effects:S,evidence:P,edits:M,validationPlan:vt({decision:f,evidence:P,validationId:L,effects:S}),expectedOutcome:f.expectedOutcome,createdAt:C,metadata:{refinerRelease:Q(H),trigger:{id:t.id,contentHash:t.contentHash},reason:f.reason,evidenceBasis:f.evidenceBasis,generatedManifestEditId:M.find(c=>c.target==="harness.json")?.id??null,rebasedFromHarnessRelease:s?r.baseHarnessRelease:null,expectedMemory:f.route==="memory"?{key:q(f.target),revision:_?.revision??null,contentHash:_?.contentHash??null,status:_?.status??null}:null}}),"buildProposal")});return $e({...e,trigger:t,workspace:n,overlay:W.overlay,proposal:W.proposal,observations:a})}i(ct,"executeLocalHarnessRefinerWorker");async function $e(e){let t=(e.now??(()=>new Date().toISOString()))(),r=await ie(e.store,e.workspace.id,e.proposal);if(r.length===0){r=await Re({storeDir:e.storeDir,workspace:e.workspace,proposal:e.proposal,now:i(()=>t,"now")});for(let l of r)await e.store.saveHarnessImprovementArtifact(e.workspace.id,"targeted_validation",l)}if(e.proposal.route==="memory")return lt({...e,validations:r,timestamp:t});let n=await ve({store:e.store,storeDir:e.storeDir,overlay:e.overlay,proposal:e.proposal,validations:r,receiptId:R("harness-advance",e.proposal.contentHash),now:i(()=>t,"now")}),o=V({schemaVersion:"openpond.improvementRouteDecision.v1",id:R("route",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},route:e.proposal.route,authority:"refiner_model",automatic:n.receipt.decision==="advanced",reason:n.receipt.reason,createdAt:t,metadata:{proposalId:e.proposal.id}});await e.store.saveHarnessImprovementArtifact(e.workspace.id,"route_decision",o);let a=Y({schemaVersion:"openpond.improvementApplyReceipt.v1",id:R("apply",e.proposal.contentHash),proposal:{id:e.proposal.id,contentHash:e.proposal.contentHash},beforeOverlay:e.trigger.overlay,afterOverlay:n.receipt.decision==="advanced"?D(e.overlay):null,decision:n.receipt.decision==="advanced"?"applied":"retained",boundary:e.trigger.boundary,validationRefs:r.map(l=>({id:l.id,contentHash:l.contentHash})),outcomeEvidenceRefs:j(e.observations),rollbackOf:null,createdAt:t,metadata:{workspaceAdvanceDecision:n.receipt.decision}});await e.store.saveHarnessImprovementArtifact(e.workspace.id,"apply_receipt",a);let s=z({schemaVersion:"openpond.harnessRefinerOutcome.v1",id:R("refiner-outcome",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},decision:"proposed",proposal:{id:e.proposal.id,contentHash:e.proposal.contentHash},reason:n.receipt.reason,evidenceRefs:e.trigger.observations,estimatedCostUsd:e.trigger.estimatedMaxCostUsd,createdAt:t,metadata:{refinerRelease:e.proposal.metadata.refinerRelease??null,validationStatuses:r.map(l=>l.status),workspaceAdvanceReceipt:{id:n.receipt.id,contentHash:n.receipt.contentHash}}});return await e.store.saveHarnessImprovementArtifact(e.workspace.id,"refiner_outcome",s),{outcome:s,overlay:e.overlay,proposal:e.proposal,validations:r,workspace:n.workspace,advanceReceipt:n.receipt,applyReceipt:a}}i($e,"finishPersistedProposal");async function lt(e){let t=e.proposal.validationPlan.filter(m=>m.required).every(m=>e.validations.some(d=>d.validationId===m.id&&d.status==="passed")),r=e.proposal.edits.find(m=>m.route==="memory");if(!r)throw new Error("Memory proposal has no memory edit.");let n=Z(e.proposal,r.target),o=t&&r.operation!=="delete";o&&await e.store.writeHarnessMemory({workspaceId:e.workspace.id,key:q(r.target),content:r.content,expectedRevision:n.revision,sourceRunId:e.trigger.runRef,sourceProposal:{id:e.proposal.id,contentHash:e.proposal.contentHash},createdAt:e.timestamp});let a=o?"Validated low-risk Personal memory applied at the safe turn boundary.":r.operation==="delete"?"Memory deletion requires explicit review.":"Required memory validation did not pass.",s=V({schemaVersion:"openpond.improvementRouteDecision.v1",id:R("route",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},route:"memory",authority:"refiner_model",automatic:o,reason:a,createdAt:e.timestamp,metadata:{proposalId:e.proposal.id}});await e.store.saveHarnessImprovementArtifact(e.workspace.id,"route_decision",s);let l=Y({schemaVersion:"openpond.improvementApplyReceipt.v1",id:R("apply",e.proposal.contentHash),proposal:{id:e.proposal.id,contentHash:e.proposal.contentHash},beforeOverlay:e.trigger.overlay,afterOverlay:o?D(e.overlay):null,decision:o?"applied":"retained",boundary:e.trigger.boundary,validationRefs:e.validations.map(m=>({id:m.id,contentHash:m.contentHash})),outcomeEvidenceRefs:j(e.observations),rollbackOf:null,createdAt:e.timestamp,metadata:{externalState:"harness_memory"}});await e.store.saveHarnessImprovementArtifact(e.workspace.id,"apply_receipt",l);let g=z({schemaVersion:"openpond.harnessRefinerOutcome.v1",id:R("refiner-outcome",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},decision:"proposed",proposal:{id:e.proposal.id,contentHash:e.proposal.contentHash},reason:a,evidenceRefs:e.trigger.observations,estimatedCostUsd:e.trigger.estimatedMaxCostUsd,createdAt:e.timestamp,metadata:{refinerRelease:e.proposal.metadata.refinerRelease??null,validationStatuses:e.validations.map(m=>m.status)}});return await e.store.saveHarnessImprovementArtifact(e.workspace.id,"refiner_outcome",g),{outcome:g,overlay:e.overlay,proposal:e.proposal,validations:e.validations,workspace:e.workspace,advanceReceipt:null,applyReceipt:l}}i(lt,"finishMemoryProposal");async function ce(e){let t=(e.now??(()=>new Date().toISOString()))(),r=z({schemaVersion:"openpond.harnessRefinerOutcome.v1",id:R("refiner-outcome",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},decision:"no_action",proposal:null,reason:e.reason,evidenceRefs:e.trigger.observations,estimatedCostUsd:e.trigger.estimatedMaxCostUsd,createdAt:t,metadata:e.metadata??{}});return await e.store.saveHarnessImprovementArtifact(e.workspace.id,"refiner_outcome",r),{outcome:r,overlay:e.overlay,proposal:null,validations:[],workspace:e.workspace,advanceReceipt:null,applyReceipt:null}}i(ce,"persistNoAction");async function dt(e){let t=(e.now??(()=>new Date().toISOString()))(),r=V({schemaVersion:"openpond.improvementRouteDecision.v1",id:R("route",e.trigger.contentHash),trigger:{id:e.trigger.id,contentHash:e.trigger.contentHash},route:e.decision.route,authority:"refiner_model",automatic:!1,reason:e.decision.reason,createdAt:t,metadata:{summary:e.decision.summary,expectedOutcome:e.decision.expectedOutcome,evidenceBasis:e.decision.evidenceBasis,refinerRelease:e.refinerRelease}});return await e.store.saveHarnessImprovementArtifact(e.workspace.id,"route_decision",r),ce({store:e.store,workspace:e.workspace,overlay:e.overlay,trigger:e.trigger,observations:e.observations,reason:`Routed to ${e.decision.route}: ${e.decision.summary}`,metadata:{routed:!0,route:e.decision.route,routeDecision:{id:r.id,contentHash:r.contentHash},expectedOutcome:e.decision.expectedOutcome,evidenceBasis:e.decision.evidenceBasis,refinerRelease:e.refinerRelease},now:i(()=>t,"now")})}i(dt,"persistExternalRoute");function ut(e,t,r){let n=e.route==="memory"?"memory":e.route==="skill"?"skill":e.route==="agent"?"agent":"instruction",o=t.find(s=>s.path===e.target);if(e.operation==="create"){if(o)throw new Error(`Refiner create target already exists: ${e.target}.`);if(!pt(e.route,e.target))throw new Error(`Refiner create target is not a safe ${e.route} component path: ${e.target}.`);return}if(!o)throw new Error(`Refiner targeted an unlisted source file: ${e.target}.`);if(o.kind!==n)throw new Error(`Refiner route ${e.route} cannot ${e.operation} ${o.kind} file ${o.path}.`);let a=r.find(s=>s.path===e.target);if(e.operation==="update"&&!a)throw new Error(`Refiner update target ${e.target} exceeded the bounded source budget.`)}i(ut,"assertSafeDecision");function mt(e,t){if(e.operation==="delete")return null;if(e.operation==="create"){if(e.createContent===null)throw new Error("Refiner create proposal is missing bounded component content.");return e.createContent}let r=t.find(a=>a.path===e.target);if(!r)throw new Error(`Refiner update target ${e.target} exceeded the bounded source budget.`);if(e.find===null||e.replace===null)throw new Error("Refiner update proposal is missing its exact find/replace edit.");let n=r.content.split(e.find).length-1;if(n!==1)throw new Error(`Refiner update find text must occur exactly once in ${e.target}; found ${n}.`);let o=r.content.replace(e.find,e.replace);if(o===r.content)throw new Error("Refiner proposal does not change the selected source file.");return o}i(mt,"materializeDecisionContent");function pt(e,t){let r=t.replaceAll("\\","/");return e==="memory"?/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(r):e==="prompt"?/^instructions\/refinements\/[a-z0-9][a-z0-9-]*\.md$/.test(r):e==="skill"?/^skills\/[a-z0-9][a-z0-9-]*\/SKILL\.md$/.test(r):/^agents\/[a-z0-9][a-z0-9-]*\/agent\.ts$/.test(r)}i(pt,"safeCreatedComponentPath");function ft(e){let{decision:t}=e,r={id:R("overlay-edit",{trigger:e.trigger.contentHash,operation:t.operation,target:t.target,content:e.materializedContent}),route:t.route,operation:t.operation,target:t.target,summary:t.summary,content:e.materializedContent,contentHash:e.materializedContent===null?null:E(e.materializedContent),effects:e.effects};if(t.route==="memory")return[r];if(t.operation==="update")return[r];let n=e.manifest.files.find(d=>d.path===t.target),o=new Set,a=[],s=e.manifest.files;if(t.operation==="create"){let d=t.route==="skill"?"skill":t.route==="agent"?"agent":"instruction";s=[...s,{id:R(d,t.target),kind:d,path:t.target,parentId:null,mediaType:t.route==="agent"?"text/javascript":"text/markdown",visibility:"policy",portability:"portable"}]}else{if(!n)throw new Error(`Refiner delete target is not declared: ${t.target}.`);o.add(n.id);for(let d of e.manifest.files)d.parentId===n.id&&(o.add(d.id),a.push({id:R("overlay-edit",{trigger:e.trigger.contentHash,operation:"delete",target:d.path}),route:t.route,operation:"delete",target:d.path,summary:`Remove resource ${d.path} with ${t.target}.`,content:null,contentHash:null,effects:e.effects}));s=s.filter(d=>!o.has(d.id))}let l=B.parse({...e.manifest,files:s}),g=`${JSON.stringify(l,null,2)}
5
5
  `,m={id:R("overlay-edit",{trigger:e.trigger.contentHash,operation:"update",target:"harness.json",content:g}),route:t.route,operation:"update",target:"harness.json",summary:`${t.operation==="create"?"Register":"Remove"} Harness component ${t.target}.`,content:g,contentHash:E(g),effects:e.effects};return[r,...a,m]}i(ft,"buildProposalEdits");function gt(e){if(e.route==="agent")return["executable_code"];if(e.route==="memory")return["memory"];let t=[e.summary,e.expectedOutcome,e.createContent??"",e.find??"",e.replace??""].join(`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{t as Vo}from"./chunk-BLXEAZCQ.js";import{b as Kl}from"./chunk-UCPGRPWY.js";import{f as Ll,g as Ul,h as ms,j as fs}from"./chunk-HDL5YSAA.js";import{A as vl,B as kl,C as yl,D as Sl,F as Rl,G as us,H as Il,I as Tl,J as xl,K as Pl,L as ds,N as Cl,a as Ya,b as Za,c as el,d as tl,e as nl,f as ol,g as ns,k as rl,l as sl,m as il,n as al,o as ll,p as ul,q as dl,r as zo,t as is,u as as,v as gl,w as hl,x as wl,y as ls,z as bl}from"./chunk-ZFSHBFG5.js";import{b as it,c as fl,d as ss}from"./chunk-AN525SPP.js";import{c as Vl}from"./chunk-GW766ZSO.js";import{a as ts,i as An}from"./chunk-UKMA4R6X.js";import{h as gs}from"./chunk-OQKJGTTO.js";import{a as Hn}from"./chunk-KVTBX2UP.js";import{a as zl,b as Go}from"./chunk-A6USMRWK.js";import{b as Ln}from"./chunk-PCSIOUHF.js";import{a as Hl}from"./chunk-N73MU2C3.js";import{b as ml,j as rs}from"./chunk-ZGTOK7ZK.js";import{B as pl,b as Y,j as cl}from"./chunk-XW6HGSIT.js";import{c as os,d as Q,e as te,g as D}from"./chunk-KG325WTN.js";import{C as Bl,D as Wl,a as Al,b as cs,c as _l,g as Ol,h as Fl,i as jl,j as _n,k as Nl,t as $l,u as ql,x as ps}from"./chunk-3RCRSMWZ.js";import{a as Dl}from"./chunk-DMFUEUAZ.js";import{a as El,d as Ml,e as Ko}from"./chunk-PSGGOZFM.js";import{$ as an,Q as Fa,S as ja,T as Na,W as $a,X as qa,Y as Ba,Z as Wa,aa as Lo,b as Ji,c as Xi,e as sn,f as Yr,h as _a,j as Ea,k as Ma,l as Ho,m as Oa}from"./chunk-VRIEKBBH.js";import{f as Aa}from"./chunk-QNG27G3T.js";import{B as xa}from"./chunk-EIRYMSEG.js";import{A as es,B as Va,Ra as Ga,Ua as Ja,Va as Xa,Wa as Qa,Za as Cn,_a as $t,c as Da,d as Ha,r as za,s as fe,t as Kt,w as Ka,x as st}from"./chunk-QOTVNQDI.js";import{a as ya,c as Sa,g as Ra,h as Ia,k as Jr,m as Ta,n as Xr}from"./chunk-OQPJ7FJF.js";import{C as Ua,K as Uo,a as La,n as Nt,v as Zr,y as ln}from"./chunk-WJ43MJ3F.js";import{c as Do,e as ka,m as Qr,n as Pa,o as Ca}from"./chunk-3QIB5FXI.js";import{C as ca,E as ga,F as ha,c as Wn,e as ea,f as Fo,fa as wa,ha as ba,ia as va,v as qo,x as Bo}from"./chunk-I7AQMAQI.js";import{A as ia,B as on,C as rn,E as jo,I as Gr,J as aa,L as la,O as No,V as ua,W as $o,X as Dn,Z as da,c as ta,f as na,h as oa,j as ra,w as sa,y as Ge,z as be}from"./chunk-Z4Z5UOZM.js";import{e as Bn}from"./chunk-FFRFSDBM.js";import{n as Oo}from"./chunk-ACYFMLWG.js";import{m as jt}from"./chunk-KGNCKIFP.js";import{b as U}from"./chunk-ES2ISFJC.js";import{b as Qi,c as Pn,e as Yi,f as Zi,h as nn,i as Vr,p as pa,q as ma,r as Wo,s as fa}from"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";function Gl(e){let t,n,o=new Set;function s(i){if(n)return Promise.reject(new Error("Runtime service is closing"));t??=Promise.resolve().then(e);let a=t.then(l=>{if(n)throw new Error("Runtime service is closing");return i(l)});return o.add(a),a.then(()=>o.delete(a),()=>o.delete(a)),a}return r(s,"use"),{use:s,methods(i){return Object.fromEntries(i.map(a=>[a,(...l)=>s(p=>p[a].apply(p,l))]))},close(){return n??=Promise.resolve().then(async()=>{try{await(await t?.catch(()=>{}))?.close()}finally{await Promise.allSettled([...o])}})}}}r(Gl,"lazyRuntimeService");function Xl(e){let t=Im();for(let n of e)t.accept(n);return t.values()}r(Xl,"activeFileOutputRefs");function Im(e=Number.POSITIVE_INFINITY){let t=new Map,n=new Set;function o(s){let i=un(s.data);if(t.size+n.size+i.length>e)throw new Error("remote_output_reference_limit");if(s.action==="work_output_delete"&&s.status==="completed"){for(let a of i){let l=Jl(a);n.add(l),t.delete(l)}return}if(s.action!=="work_output_read")for(let a of i){let l=Jl(a);n.has(l)||t.set(l,a)}}return r(o,"accept"),{accept:o,values:r(()=>[...t.values()],"values")}}r(Im,"createOutputReferenceAccumulator");function Jl(e){return`${e.sourceTaskId}:${e.id}:${e.revision}`}r(Jl,"fileOutputRevisionKey");function un(e,t=0){if(t>8||e==null)return[];let n=Kt.safeParse(e);if(n.success)return[n.data];if(Array.isArray(e))return e.flatMap(s=>un(s,t+1));let o=Tm(e);return Object.values(o).flatMap(s=>un(s,t+1))}r(un,"fileOutputRefs");function Tm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Tm,"asRecord");import{createHash as zn,randomUUID as Zl}from"node:crypto";import{promises as Ze}from"node:fs";import ke from"node:path";function Un(e){return!!(e.experience==="work"&&!e.workspaceKind&&!e.localProjectId&&!e.cloudProjectId&&e.metadata?.workspaceTarget==="local"&&e.cwd)}r(Un,"isManagedLocalWorkSession");function Tv(e){let t=ke.join(e.storeDir,"work","outputs"),n=e.sandboxRequest??Vo;async function o(w){let x=Jo(w.suggestedName);if(w.bytes.byteLength>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let j=es[ke.extname(x).toLowerCase()];if(!j)throw new Error(`${x} is not an advertised Work output format. Save it as a supported file type or keep it in scratch space.`);let k=Am({bytes:w.bytes,contentType:j,title:x,supplied:w.validation,policy:w.validationPolicy}),C=await Ql({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:w.session.id,title:x,...e.managedPersistence?{firstId:`hosted-${zn("sha256").update(`${w.session.id}\0${x}`).digest("hex")}`}:{}});if(e.managedPersistence){let c=await e.managedPersistence.sourceTurnStartedAt(w.session.id,w.sourceTurnId),A={id:C.id,title:x,contentType:j,sizeBytes:w.bytes.byteLength,sha256:zn("sha256").update(w.bytes).digest("hex"),sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:C.revision,createdAt:new Date(c).toISOString(),validation:k};return e.managedPersistence.save({sessionId:w.session.id,turnId:w.sourceTurnId,identity:A,bytes:w.bytes})}let y=ke.join(t,Xo(w.session.id));await Ze.mkdir(y,{recursive:!0,mode:448});let m=ke.join(y,`${String(C.revision).padStart(3,"0")}-${Xo(C.id)}-${x}`),g=ke.join(y,`.${ke.basename(m)}.${Zl()}.tmp`);await Ze.writeFile(g,w.bytes,{mode:384,flag:"wx"});try{await Ze.rename(g,m)}catch(c){throw await Ze.rm(g,{force:!0}),c}return{outputRef:Kt.parse({kind:"file",id:C.id,title:x,contentType:j,sizeBytes:w.bytes.byteLength,sha256:zn("sha256").update(w.bytes).digest("hex"),sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:C.revision,createdAt:new Date().toISOString(),location:{kind:"local",path:m,deviceId:e.deviceId},validation:k}),artifact:{artifactRef:m,path:m,title:x,contentType:j,sizeBytes:w.bytes.byteLength}}}r(o,"persistWorkOutputBytes");async function s(w){if(w.session.experience!=="work")throw new Error("Only Work tasks can save Work outputs.");if(w.session.workspaceKind!=="sandbox"||!w.session.workspaceId)throw new Error("A running Work sandbox is required to save an output.");let x=Om(w.sandboxPath),j=En(await n({type:"download_file",sandboxId:w.session.workspaceId,payload:{path:x,maxBytes:st}})),k=En(j.file);if(k.truncated===!0)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let C=typeof k.contentsBase64=="string"?k.contentsBase64:"";if(!C)throw new Error("Sandbox output download did not return file contents.");let y=Buffer.from(C,"base64"),m=Yl(k.totalSizeBytes)??Yl(k.sizeBytes);if(y.byteLength>st||m!==null&&m>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);if(m!==null&&y.byteLength!==m)throw new Error("Sandbox output download was incomplete.");return o({session:w.session,sourceTurnId:w.sourceTurnId,suggestedName:w.suggestedName||ke.posix.basename(x),bytes:y,validation:w.validation??[],validationPolicy:w.validationPolicy??"strict"})}r(s,"saveWorkOutput");async function i(w){if(!Un(w.session)||!w.session.cwd)throw new Error("A managed local Work task is required to save a local output.");let x=await Ze.realpath(w.session.cwd),j=ke.isAbsolute(w.localPath)?ke.resolve(w.localPath):ke.resolve(x,w.localPath),k=await Ze.realpath(j);if(!eu(x,k))throw new Error("Local Work outputs must stay inside the managed task workspace.");let C=await Ze.stat(k);if(!C.isFile())throw new Error("A local Work output must be a file.");if(C.size>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let y=await Ze.readFile(k);return o({session:w.session,sourceTurnId:w.sourceTurnId,suggestedName:w.suggestedName??ke.basename(k),bytes:y,validation:[],validationPolicy:"preserve"})}r(i,"saveLocalWorkOutput");async function a(w){if(Un(w.session))return l(w);if(w.session.experience!=="work"||w.session.workspaceKind!=="sandbox"||!w.session.workspaceId)return[];let x=En(await n({type:"list_files",sandboxId:w.session.workspaceId,payload:{path:"outputs",recursive:!0,maxEntries:500}})),j=Array.isArray(x.files)?x.files:[],k=await e.runtimeEventsForSession(w.session.id),C=new Set(un(k).filter(m=>m.sourceTurnId===w.sourceTurnId).map(m=>m.title)),y=[];for(let m of j){let g=En(m);if(g.type!=="file"||typeof g.path!="string")continue;let R=g.path.replace(/^\/workspace\//,""),c=Jo(ke.posix.basename(R));if(!C.has(c)){if(e.managedPersistence){let A=await Ql({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:w.session.id,title:c,firstId:`hosted-${zn("sha256").update(`${w.session.id}\0${c}`).digest("hex")}`}),E=await e.managedPersistence.sourceTurnStartedAt(w.session.id,w.sourceTurnId);y.push(await e.managedPersistence.saveSandboxFile({sessionId:w.session.id,turnId:w.sourceTurnId,identity:{id:A.id,title:c,sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:A.revision,createdAt:new Date(E).toISOString(),validation:[]},sandboxPath:R}))}else y.push(await s({session:w.session,sourceTurnId:w.sourceTurnId,sandboxPath:R,suggestedName:c,validationPolicy:"preserve"}));C.add(c)}}return y}r(a,"saveAllWorkOutputs");async function l(w){if(!w.session.cwd)return[];let x=await e.runtimeEventsForSession(w.session.id),j=x.filter(m=>m.turnId===w.sourceTurnId&&m.name==="assistant.delta"&&typeof m.output=="string").map(m=>m.output??"").join(""),k=await xm({assistantText:j,workspaceRoot:w.session.cwd}),C=new Set(un(x).filter(m=>m.sourceTurnId===w.sourceTurnId).map(m=>m.title)),y=[];for(let m of k){let g=Jo(ke.basename(m));C.has(g)||(y.push(await i({session:w.session,sourceTurnId:w.sourceTurnId,localPath:m,suggestedName:g})),C.add(g))}return y}r(l,"saveReferencedLocalWorkOutputs");async function p(w){if(w.experience!=="work")return[];let x=await e.runtimeEventsForSession(w.id),j=new Map;for(let k of un(x)){if(k.location.kind!=="local")continue;let C=j.get(k.title);(!C||k.revision>C.revision)&&j.set(k.title,k)}return[...j.values()].map(k=>({localPath:k.location.kind==="local"?k.location.path:"",storageName:`${Xo(k.id)}-${Jo(k.title)}`,sha256:k.sha256,sizeBytes:k.sizeBytes}))}r(p,"workInputsForSession");async function d(w){let x=await Promise.all(w.filter(j=>j.experience==="work").map(async j=>Xl(await e.runtimeEventsForSession(j.id))));return Ka.parse({outputs:x.flat().sort((j,k)=>k.createdAt.localeCompare(j.createdAt))})}r(d,"listWorkOutputs");async function u(w){if(w.session.experience!=="work")throw new Error("Only Work tasks can access Work outputs.");let x=w.outputId.trim();if(!x)throw new Error("A Work output id is required.");let j=await e.runtimeEventsForSession(w.session.id),k=ws(j,x,w.revision);if(!k)throw new Error("Work output not found.");return f(w.session,k)}r(u,"resolveLocalOutput");function f(w,x){if(w.experience!=="work"||x.sourceTaskId!==w.id||x.location.kind!=="local")throw new Error("This Work output is not stored on this device.");let j=ke.resolve(t,Xo(w.id)),k=ke.resolve(x.location.path);if(k===j||!k.startsWith(`${j}${ke.sep}`))throw new Error("Work output path is outside managed local storage.");return{outputRef:x,target:k}}r(f,"localOutputTarget");async function h(w){let{outputRef:x,target:j}=await u(w),k=await Ze.rm(j).then(()=>!0).catch(C=>{if(C.code==="ENOENT")return!1;throw C});return{outputRef:x,deleted:k}}r(h,"deleteWorkOutput");async function v(w){let{outputRef:x}=await u(w);return b(w.session,x)}r(v,"readWorkOutput");async function b(w,x){let{target:j}=f(w,x),k=await Ze.stat(j);if(k.size>st||k.size!==x.sizeBytes)throw new Error("The saved Work output no longer matches its OutputRef.");let C=await Ze.readFile(j);if(C.byteLength>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let y=zn("sha256").update(C).digest("hex");if(C.byteLength!==x.sizeBytes||y!==x.sha256)throw new Error("The saved Work output no longer matches its OutputRef.");return{outputRef:x,contentsBase64:C.toString("base64")}}return r(b,"readQualifiedWorkOutput"),{outputRoot:t,deleteWorkOutput:h,listWorkOutputs:d,readWorkOutput:v,readQualifiedWorkOutput:b,saveAllWorkOutputs:a,saveLocalWorkOutput:i,saveOwnedOutputBytes:o,saveWorkOutput:s,workInputsForSession:p}}r(Tv,"createWorkOutputService");async function xm(e){let t=await Ze.realpath(e.workspaceRoot),n=new Set;for(let o of Pm(e.assistantText)){let s=Cm(o);if(!s)continue;let i=ke.isAbsolute(s)?ke.resolve(s):ke.resolve(t,s),a;try{if(a=await Ze.realpath(i),!(await Ze.stat(a)).isFile())continue}catch{continue}if(eu(t,a)&&es[ke.extname(a).toLowerCase()]&&(n.add(a),n.size>=100))break}return[...n]}r(xm,"resolveReferencedLocalFiles");function Pm(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n]==="!"?n+1:n;if(e[o]!=="[")continue;let s=e.indexOf("]",o+1);if(s<0||e[s+1]!=="(")continue;let i=s+2;if(e[i]==="<"){let l=e.indexOf(">",i+1);l>=0&&e[l+1]===")"&&(t.push(e.slice(i+1,l)),n=l+1);continue}let a=0;for(let l=i;l<e.length;l+=1){let p=e[l];if(p==="\\"){l+=1;continue}if(p==="("){a+=1;continue}if(p!==")")continue;if(a>0){a-=1;continue}let d=e.slice(i,l).trim();d&&t.push(d),n=l;break}}return t}r(Pm,"markdownLinkTargets");function Cm(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!t||/^(?:https?|data|mailto):/i.test(t))return null;if(t=t.replace(/^(?:workspace|sandbox):file:/i,""),/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}else try{t=decodeURIComponent(t)}catch{}return t.replace(/:\d+(?::\d+)?$/,"")}r(Cm,"normalizeLocalFileReference");function eu(e,t){let n=ke.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${ke.sep}`)&&!ke.isAbsolute(n)}r(eu,"isPathInside");function Am(e){let t=Va(e.contentType);if(!t)return e.supplied;let n=_m(e);if(n.status!=="passed")throw new Error(`Work output failed structural validation: ${n.detail}`);let o=[n,...e.supplied],s=t.validation.flatMap(i=>i==="visual"?["visual"]:i==="playback"||i==="browser"?["test"]:[]);for(let i of s)if(!o.some(a=>a.kind===i&&a.status==="passed")){if(e.policy==="strict")throw new Error(`${e.title} requires passed ${i} validation evidence before it can be saved as a completed Work output.`);o.push({kind:i,status:"not_run",label:`${e.title} ${i} validation was not run before automatic preservation`,detail:"The file was preserved automatically at turn completion; review this revision before relying on presentation or playback quality."})}return o}r(Am,"validateWorkOutput");function _m(e){let t=Em(e.bytes,e.contentType);return{kind:"structural",status:t?"passed":"failed",label:`Validated ${e.title} structure`,detail:t?`Content matches ${e.contentType}.`:`Content does not match ${e.contentType}.`}}r(_m,"structuralValidation");function Em(e,t){if(e.byteLength===0)return!1;if(t.startsWith("text/")||t==="application/json"||t==="image/svg+xml"){let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return!1}if(t==="application/json")try{JSON.parse(n)}catch{return!1}return t==="text/html"?/<(?:!doctype\s+html|html|body)\b/i.test(n):t==="image/svg+xml"?/<svg\b/i.test(n):n.trim().length>0}if(t==="application/pdf")return e.subarray(0,5).toString("ascii")==="%PDF-"&&e.subarray(Math.max(0,e.byteLength-1024)).toString("ascii").includes("%%EOF");if(t.includes("wordprocessingml")||t.includes("spreadsheetml")||t.includes("presentationml")){let n=Mm(e),o=t.includes("wordprocessingml")?"word/document.xml":t.includes("spreadsheetml")?"xl/workbook.xml":"ppt/presentation.xml";return n.has("[Content_Types].xml")&&n.has("_rels/.rels")&&n.has(o)}return t==="image/png"?e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])):t==="image/jpeg"?e[0]===255&&e[1]===216:t==="image/gif"?e.subarray(0,4).toString("ascii")==="GIF8":t==="image/webp"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WEBP":t==="image/avif"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="audio/wav"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WAVE":t==="audio/mpeg"?e.subarray(0,3).toString("ascii")==="ID3"||e[0]===255&&(e[1]&224)===224:t==="audio/mp4"||t==="video/mp4"||t==="video/quicktime"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="video/webm"?e.subarray(0,4).equals(Buffer.from([26,69,223,163])):!0}r(Em,"structuralContentMatches");function Mm(e){let t=new Set;for(let n=0;n+46<=e.byteLength;){if(e.readUInt32LE(n)!==33639248){n+=1;continue}let o=e.readUInt16LE(n+28),s=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32),a=n+46+o+s+i;if(a>e.byteLength)return new Set;let l=e.subarray(n+46,n+46+o).toString("utf8").replaceAll("\\","/").replace(/^\/+/,"");l&&t.add(l),n=a}return t}r(Mm,"zipCentralDirectoryEntries");function Om(e){let t=e.trim().replaceAll("\\","/");if(!t||t.startsWith("/"))throw new Error("Work output path must be relative to /workspace.");let n=ke.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../")||!n.startsWith("outputs/")||n==="outputs/")throw new Error("Completed Work outputs must be inside /workspace/outputs.");return n}r(Om,"normalizeOutputCandidatePath");async function Ql(e){let t=await e.runtimeEventsForSession(e.sessionId),n=null;for(let o of t){let s=hs(o.data);s?.kind!=="file"||s.title!==e.title||(!n||s.revision>n.revision)&&(n=s)}return{id:n?.id??e.firstId??Zl(),revision:(n?.revision??0)+1}}r(Ql,"nextOutputIdentity");function hs(e,t=0){if(t>6||e==null)return null;let n=Kt.safeParse(e);if(n.success)return n.data;if(Array.isArray(e)){for(let s of e){let i=hs(s,t+1);if(i)return i}return null}let o=En(e);for(let s of Object.values(o)){let i=hs(s,t+1);if(i)return i}return null}r(hs,"findOutputRef");function ws(e,t,n,o=0){if(o>8||e==null)return null;let s=Kt.safeParse(e);if(s.success&&s.data.id===t&&(n==null||s.data.revision===n))return s.data;if(Array.isArray(e)){let l=null;for(let p of e){let d=ws(p,t,n,o+1);d&&(!l||d.revision>l.revision)&&(l=d)}return l}let i=En(e),a=null;for(let l of Object.values(i)){let p=ws(l,t,n,o+1);p&&(!a||p.revision>a.revision)&&(a=p)}return a}r(ws,"findOutputRefById");function Jo(e){let n=ke.basename(e.trim()).replace(/[^a-zA-Z0-9._ -]+/g,"-").replace(/\s+/g," ").trim().slice(0,180);if(!n||n==="."||n==="..")throw new Error("A valid output file name is required.");return n}r(Jo,"safeOutputName");function Xo(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,100)||"item"}r(Xo,"safePathSegment");function En(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(En,"asRecord");function Yl(e){return typeof e=="number"&&Number.isFinite(e)?e:null}r(Yl,"numberValue");import{promises as Qo}from"node:fs";import Fm from"node:path";async function tu(e,t,n=Date.now()){let o=[];for(let i of await Qo.readdir(e,{withFileTypes:!0})){if(!i.isFile()||!/\.log(?:\.\d+)?$/.test(i.name))continue;let a=Fm.join(e,i.name),l=await Qo.lstat(a).catch(p=>{if(p.code==="ENOENT")return null;throw p});l?.isFile()&&o.push({file:a,size:l.size,modified:l.mtimeMs})}let s=o.reduce((i,a)=>i+a.size,0);for(let i of o.sort((a,l)=>a.modified-l.modified)){if(i.file===t||i.modified>=n-14*864e5&&s<=256*1024*1024)continue;let a=await Qo.lstat(i.file).catch(()=>null);a?.isFile()&&a.size===i.size&&a.mtimeMs===i.modified&&(await Qo.rm(i.file,{force:!0}),s-=i.size)}}r(tu,"pruneLogs");import{promises as Kn}from"node:fs";import jm from"node:path";var nu=1024*1024,Nm=5,bs=/authorization|api[_-]?key|token|session[_-]?token|secret|password/i,$m=/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,qm=/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi;function Bm(e){return{name:e.name,message:e.message,stack:e.stack}}r(Bm,"serializeError");function Yo(e){if(e instanceof Error)return Yo(Bm(e));if(typeof e=="string")return Wm(e);if(Array.isArray(e))return e.map(n=>Yo(n));if(!e||typeof e!="object")return e;let t={};for(let[n,o]of Object.entries(e))t[n]=bs.test(n)?"[REDACTED]":Yo(o);return t}r(Yo,"redact");async function ou(e,t){try{await Kn.rm(t,{force:!0}),await Kn.rename(e,t)}catch(n){if(n.code!=="ENOENT")throw n}}r(ou,"renameIfExists");function Wm(e){return e.replace($m,"Bearer [REDACTED]").replace(qm,t=>Dm(t))}r(Wm,"redactString");function Dm(e){let{url:t,suffix:n}=Hm(e);try{let o=new URL(t);return(o.username||o.password)&&(o.username="[REDACTED]",o.password="[REDACTED]"),ru(o.searchParams),o.hash&&(o.hash=Lm(o.hash.slice(1))),`${o.toString()}${n}`}catch{return e}}r(Dm,"redactUrl");function Hm(e){let t=e,n="";for(;/[),.;!?]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{url:t,suffix:n}}r(Hm,"splitUrlSuffix");function ru(e){for(let t of Array.from(e.keys()))bs.test(t)&&e.set(t,"[REDACTED]")}r(ru,"redactSearchParams");function Lm(e){if(!e.includes("="))return bs.test(e)?"[REDACTED]":e;let t=new URLSearchParams(e.startsWith("?")?e.slice(1):e);return ru(t),t.toString()}r(Lm,"redactHash");function jv(e){let t=e.maxBytes??nu,n=e.maxFiles??Nm,o=jm.join(e.logDir,e.filename??`${e.channel}.log`),s=Promise.resolve(),i=0;async function a(p){let d=0;try{d=(await Kn.stat(o)).size}catch(u){if(u.code!=="ENOENT")throw u}if(!(d+p<=t)){for(let u=n-1;u>=1;u-=1)await ou(`${o}.${u}`,`${o}.${u+1}`);await ou(o,`${o}.1`)}}r(a,"rotateIfNeeded");function l(p,d,u={}){let f={ts:new Date().toISOString(),level:p,channel:e.channel,message:d,pid:process.pid,platform:process.platform,...e.metadata??{},...u},h=`${JSON.stringify(Yo(f))}
2
+ import{t as Vo}from"./chunk-BLXEAZCQ.js";import{b as Kl}from"./chunk-UCPGRPWY.js";import{f as Ll,g as Ul,h as ms,j as fs}from"./chunk-RWWE5OXU.js";import{A as vl,B as kl,C as yl,D as Sl,F as Rl,G as us,H as Il,I as Tl,J as xl,K as Pl,L as ds,N as Cl,a as Ya,b as Za,c as el,d as tl,e as nl,f as ol,g as ns,k as rl,l as sl,m as il,n as al,o as ll,p as ul,q as dl,r as zo,t as is,u as as,v as gl,w as hl,x as wl,y as ls,z as bl}from"./chunk-RNQF63ZR.js";import{b as it,c as fl,d as ss}from"./chunk-AN525SPP.js";import{c as Vl}from"./chunk-GW766ZSO.js";import{a as ts,i as An}from"./chunk-UKMA4R6X.js";import{h as gs}from"./chunk-OQKJGTTO.js";import{a as Hn}from"./chunk-KVTBX2UP.js";import{a as zl,b as Go}from"./chunk-A6USMRWK.js";import{b as Ln}from"./chunk-PCSIOUHF.js";import{a as Hl}from"./chunk-N73MU2C3.js";import{b as ml,j as rs}from"./chunk-ZGTOK7ZK.js";import{B as pl,b as Y,j as cl}from"./chunk-XW6HGSIT.js";import{c as os,d as Q,e as te,g as D}from"./chunk-KG325WTN.js";import{C as Bl,D as Wl,a as Al,b as cs,c as _l,g as Ol,h as Fl,i as jl,j as _n,k as Nl,t as $l,u as ql,x as ps}from"./chunk-TTVS6JMC.js";import{a as Dl}from"./chunk-DMFUEUAZ.js";import{a as El,d as Ml,e as Ko}from"./chunk-PSGGOZFM.js";import{$ as an,Q as Fa,S as ja,T as Na,W as $a,X as qa,Y as Ba,Z as Wa,aa as Lo,b as Ji,c as Xi,e as sn,f as Yr,h as _a,j as Ea,k as Ma,l as Ho,m as Oa}from"./chunk-VRIEKBBH.js";import{f as Aa}from"./chunk-QNG27G3T.js";import{B as xa}from"./chunk-EIRYMSEG.js";import{A as es,B as Va,Ra as Ga,Ua as Ja,Va as Xa,Wa as Qa,Za as Cn,_a as $t,c as Da,d as Ha,r as za,s as fe,t as Kt,w as Ka,x as st}from"./chunk-QL4OIPEZ.js";import{a as ya,c as Sa,g as Ra,h as Ia,k as Jr,m as Ta,n as Xr}from"./chunk-OQPJ7FJF.js";import{C as Ua,K as Uo,a as La,n as Nt,v as Zr,y as ln}from"./chunk-WJ43MJ3F.js";import{c as Do,e as ka,m as Qr,n as Pa,o as Ca}from"./chunk-3QIB5FXI.js";import{C as ca,E as ga,F as ha,c as Wn,e as ea,f as Fo,fa as wa,ha as ba,ia as va,v as qo,x as Bo}from"./chunk-I7AQMAQI.js";import{A as ia,B as on,C as rn,E as jo,I as Gr,J as aa,L as la,O as No,V as ua,W as $o,X as Dn,Z as da,c as ta,f as na,h as oa,j as ra,w as sa,y as Ge,z as be}from"./chunk-Z4Z5UOZM.js";import{e as Bn}from"./chunk-FFRFSDBM.js";import{n as Oo}from"./chunk-ACYFMLWG.js";import{m as jt}from"./chunk-KGNCKIFP.js";import{b as U}from"./chunk-ES2ISFJC.js";import{b as Qi,c as Pn,e as Yi,f as Zi,h as nn,i as Vr,p as pa,q as ma,r as Wo,s as fa}from"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";function Gl(e){let t,n,o=new Set;function s(i){if(n)return Promise.reject(new Error("Runtime service is closing"));t??=Promise.resolve().then(e);let a=t.then(l=>{if(n)throw new Error("Runtime service is closing");return i(l)});return o.add(a),a.then(()=>o.delete(a),()=>o.delete(a)),a}return r(s,"use"),{use:s,methods(i){return Object.fromEntries(i.map(a=>[a,(...l)=>s(p=>p[a].apply(p,l))]))},close(){return n??=Promise.resolve().then(async()=>{try{await(await t?.catch(()=>{}))?.close()}finally{await Promise.allSettled([...o])}})}}}r(Gl,"lazyRuntimeService");function Xl(e){let t=Im();for(let n of e)t.accept(n);return t.values()}r(Xl,"activeFileOutputRefs");function Im(e=Number.POSITIVE_INFINITY){let t=new Map,n=new Set;function o(s){let i=un(s.data);if(t.size+n.size+i.length>e)throw new Error("remote_output_reference_limit");if(s.action==="work_output_delete"&&s.status==="completed"){for(let a of i){let l=Jl(a);n.add(l),t.delete(l)}return}if(s.action!=="work_output_read")for(let a of i){let l=Jl(a);n.has(l)||t.set(l,a)}}return r(o,"accept"),{accept:o,values:r(()=>[...t.values()],"values")}}r(Im,"createOutputReferenceAccumulator");function Jl(e){return`${e.sourceTaskId}:${e.id}:${e.revision}`}r(Jl,"fileOutputRevisionKey");function un(e,t=0){if(t>8||e==null)return[];let n=Kt.safeParse(e);if(n.success)return[n.data];if(Array.isArray(e))return e.flatMap(s=>un(s,t+1));let o=Tm(e);return Object.values(o).flatMap(s=>un(s,t+1))}r(un,"fileOutputRefs");function Tm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Tm,"asRecord");import{createHash as zn,randomUUID as Zl}from"node:crypto";import{promises as Ze}from"node:fs";import ke from"node:path";function Un(e){return!!(e.experience==="work"&&!e.workspaceKind&&!e.localProjectId&&!e.cloudProjectId&&e.metadata?.workspaceTarget==="local"&&e.cwd)}r(Un,"isManagedLocalWorkSession");function Tv(e){let t=ke.join(e.storeDir,"work","outputs"),n=e.sandboxRequest??Vo;async function o(w){let x=Jo(w.suggestedName);if(w.bytes.byteLength>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let j=es[ke.extname(x).toLowerCase()];if(!j)throw new Error(`${x} is not an advertised Work output format. Save it as a supported file type or keep it in scratch space.`);let k=Am({bytes:w.bytes,contentType:j,title:x,supplied:w.validation,policy:w.validationPolicy}),C=await Ql({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:w.session.id,title:x,...e.managedPersistence?{firstId:`hosted-${zn("sha256").update(`${w.session.id}\0${x}`).digest("hex")}`}:{}});if(e.managedPersistence){let c=await e.managedPersistence.sourceTurnStartedAt(w.session.id,w.sourceTurnId),A={id:C.id,title:x,contentType:j,sizeBytes:w.bytes.byteLength,sha256:zn("sha256").update(w.bytes).digest("hex"),sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:C.revision,createdAt:new Date(c).toISOString(),validation:k};return e.managedPersistence.save({sessionId:w.session.id,turnId:w.sourceTurnId,identity:A,bytes:w.bytes})}let y=ke.join(t,Xo(w.session.id));await Ze.mkdir(y,{recursive:!0,mode:448});let m=ke.join(y,`${String(C.revision).padStart(3,"0")}-${Xo(C.id)}-${x}`),g=ke.join(y,`.${ke.basename(m)}.${Zl()}.tmp`);await Ze.writeFile(g,w.bytes,{mode:384,flag:"wx"});try{await Ze.rename(g,m)}catch(c){throw await Ze.rm(g,{force:!0}),c}return{outputRef:Kt.parse({kind:"file",id:C.id,title:x,contentType:j,sizeBytes:w.bytes.byteLength,sha256:zn("sha256").update(w.bytes).digest("hex"),sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:C.revision,createdAt:new Date().toISOString(),location:{kind:"local",path:m,deviceId:e.deviceId},validation:k}),artifact:{artifactRef:m,path:m,title:x,contentType:j,sizeBytes:w.bytes.byteLength}}}r(o,"persistWorkOutputBytes");async function s(w){if(w.session.experience!=="work")throw new Error("Only Work tasks can save Work outputs.");if(w.session.workspaceKind!=="sandbox"||!w.session.workspaceId)throw new Error("A running Work sandbox is required to save an output.");let x=Om(w.sandboxPath),j=En(await n({type:"download_file",sandboxId:w.session.workspaceId,payload:{path:x,maxBytes:st}})),k=En(j.file);if(k.truncated===!0)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let C=typeof k.contentsBase64=="string"?k.contentsBase64:"";if(!C)throw new Error("Sandbox output download did not return file contents.");let y=Buffer.from(C,"base64"),m=Yl(k.totalSizeBytes)??Yl(k.sizeBytes);if(y.byteLength>st||m!==null&&m>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);if(m!==null&&y.byteLength!==m)throw new Error("Sandbox output download was incomplete.");return o({session:w.session,sourceTurnId:w.sourceTurnId,suggestedName:w.suggestedName||ke.posix.basename(x),bytes:y,validation:w.validation??[],validationPolicy:w.validationPolicy??"strict"})}r(s,"saveWorkOutput");async function i(w){if(!Un(w.session)||!w.session.cwd)throw new Error("A managed local Work task is required to save a local output.");let x=await Ze.realpath(w.session.cwd),j=ke.isAbsolute(w.localPath)?ke.resolve(w.localPath):ke.resolve(x,w.localPath),k=await Ze.realpath(j);if(!eu(x,k))throw new Error("Local Work outputs must stay inside the managed task workspace.");let C=await Ze.stat(k);if(!C.isFile())throw new Error("A local Work output must be a file.");if(C.size>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let y=await Ze.readFile(k);return o({session:w.session,sourceTurnId:w.sourceTurnId,suggestedName:w.suggestedName??ke.basename(k),bytes:y,validation:[],validationPolicy:"preserve"})}r(i,"saveLocalWorkOutput");async function a(w){if(Un(w.session))return l(w);if(w.session.experience!=="work"||w.session.workspaceKind!=="sandbox"||!w.session.workspaceId)return[];let x=En(await n({type:"list_files",sandboxId:w.session.workspaceId,payload:{path:"outputs",recursive:!0,maxEntries:500}})),j=Array.isArray(x.files)?x.files:[],k=await e.runtimeEventsForSession(w.session.id),C=new Set(un(k).filter(m=>m.sourceTurnId===w.sourceTurnId).map(m=>m.title)),y=[];for(let m of j){let g=En(m);if(g.type!=="file"||typeof g.path!="string")continue;let R=g.path.replace(/^\/workspace\//,""),c=Jo(ke.posix.basename(R));if(!C.has(c)){if(e.managedPersistence){let A=await Ql({runtimeEventsForSession:e.runtimeEventsForSession,sessionId:w.session.id,title:c,firstId:`hosted-${zn("sha256").update(`${w.session.id}\0${c}`).digest("hex")}`}),E=await e.managedPersistence.sourceTurnStartedAt(w.session.id,w.sourceTurnId);y.push(await e.managedPersistence.saveSandboxFile({sessionId:w.session.id,turnId:w.sourceTurnId,identity:{id:A.id,title:c,sourceTaskId:w.session.id,sourceTurnId:w.sourceTurnId,revision:A.revision,createdAt:new Date(E).toISOString(),validation:[]},sandboxPath:R}))}else y.push(await s({session:w.session,sourceTurnId:w.sourceTurnId,sandboxPath:R,suggestedName:c,validationPolicy:"preserve"}));C.add(c)}}return y}r(a,"saveAllWorkOutputs");async function l(w){if(!w.session.cwd)return[];let x=await e.runtimeEventsForSession(w.session.id),j=x.filter(m=>m.turnId===w.sourceTurnId&&m.name==="assistant.delta"&&typeof m.output=="string").map(m=>m.output??"").join(""),k=await xm({assistantText:j,workspaceRoot:w.session.cwd}),C=new Set(un(x).filter(m=>m.sourceTurnId===w.sourceTurnId).map(m=>m.title)),y=[];for(let m of k){let g=Jo(ke.basename(m));C.has(g)||(y.push(await i({session:w.session,sourceTurnId:w.sourceTurnId,localPath:m,suggestedName:g})),C.add(g))}return y}r(l,"saveReferencedLocalWorkOutputs");async function p(w){if(w.experience!=="work")return[];let x=await e.runtimeEventsForSession(w.id),j=new Map;for(let k of un(x)){if(k.location.kind!=="local")continue;let C=j.get(k.title);(!C||k.revision>C.revision)&&j.set(k.title,k)}return[...j.values()].map(k=>({localPath:k.location.kind==="local"?k.location.path:"",storageName:`${Xo(k.id)}-${Jo(k.title)}`,sha256:k.sha256,sizeBytes:k.sizeBytes}))}r(p,"workInputsForSession");async function d(w){let x=await Promise.all(w.filter(j=>j.experience==="work").map(async j=>Xl(await e.runtimeEventsForSession(j.id))));return Ka.parse({outputs:x.flat().sort((j,k)=>k.createdAt.localeCompare(j.createdAt))})}r(d,"listWorkOutputs");async function u(w){if(w.session.experience!=="work")throw new Error("Only Work tasks can access Work outputs.");let x=w.outputId.trim();if(!x)throw new Error("A Work output id is required.");let j=await e.runtimeEventsForSession(w.session.id),k=ws(j,x,w.revision);if(!k)throw new Error("Work output not found.");return f(w.session,k)}r(u,"resolveLocalOutput");function f(w,x){if(w.experience!=="work"||x.sourceTaskId!==w.id||x.location.kind!=="local")throw new Error("This Work output is not stored on this device.");let j=ke.resolve(t,Xo(w.id)),k=ke.resolve(x.location.path);if(k===j||!k.startsWith(`${j}${ke.sep}`))throw new Error("Work output path is outside managed local storage.");return{outputRef:x,target:k}}r(f,"localOutputTarget");async function h(w){let{outputRef:x,target:j}=await u(w),k=await Ze.rm(j).then(()=>!0).catch(C=>{if(C.code==="ENOENT")return!1;throw C});return{outputRef:x,deleted:k}}r(h,"deleteWorkOutput");async function v(w){let{outputRef:x}=await u(w);return b(w.session,x)}r(v,"readWorkOutput");async function b(w,x){let{target:j}=f(w,x),k=await Ze.stat(j);if(k.size>st||k.size!==x.sizeBytes)throw new Error("The saved Work output no longer matches its OutputRef.");let C=await Ze.readFile(j);if(C.byteLength>st)throw new Error(`Work output exceeds the ${st.toLocaleString()} byte limit.`);let y=zn("sha256").update(C).digest("hex");if(C.byteLength!==x.sizeBytes||y!==x.sha256)throw new Error("The saved Work output no longer matches its OutputRef.");return{outputRef:x,contentsBase64:C.toString("base64")}}return r(b,"readQualifiedWorkOutput"),{outputRoot:t,deleteWorkOutput:h,listWorkOutputs:d,readWorkOutput:v,readQualifiedWorkOutput:b,saveAllWorkOutputs:a,saveLocalWorkOutput:i,saveOwnedOutputBytes:o,saveWorkOutput:s,workInputsForSession:p}}r(Tv,"createWorkOutputService");async function xm(e){let t=await Ze.realpath(e.workspaceRoot),n=new Set;for(let o of Pm(e.assistantText)){let s=Cm(o);if(!s)continue;let i=ke.isAbsolute(s)?ke.resolve(s):ke.resolve(t,s),a;try{if(a=await Ze.realpath(i),!(await Ze.stat(a)).isFile())continue}catch{continue}if(eu(t,a)&&es[ke.extname(a).toLowerCase()]&&(n.add(a),n.size>=100))break}return[...n]}r(xm,"resolveReferencedLocalFiles");function Pm(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n]==="!"?n+1:n;if(e[o]!=="[")continue;let s=e.indexOf("]",o+1);if(s<0||e[s+1]!=="(")continue;let i=s+2;if(e[i]==="<"){let l=e.indexOf(">",i+1);l>=0&&e[l+1]===")"&&(t.push(e.slice(i+1,l)),n=l+1);continue}let a=0;for(let l=i;l<e.length;l+=1){let p=e[l];if(p==="\\"){l+=1;continue}if(p==="("){a+=1;continue}if(p!==")")continue;if(a>0){a-=1;continue}let d=e.slice(i,l).trim();d&&t.push(d),n=l;break}}return t}r(Pm,"markdownLinkTargets");function Cm(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!t||/^(?:https?|data|mailto):/i.test(t))return null;if(t=t.replace(/^(?:workspace|sandbox):file:/i,""),/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}else try{t=decodeURIComponent(t)}catch{}return t.replace(/:\d+(?::\d+)?$/,"")}r(Cm,"normalizeLocalFileReference");function eu(e,t){let n=ke.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${ke.sep}`)&&!ke.isAbsolute(n)}r(eu,"isPathInside");function Am(e){let t=Va(e.contentType);if(!t)return e.supplied;let n=_m(e);if(n.status!=="passed")throw new Error(`Work output failed structural validation: ${n.detail}`);let o=[n,...e.supplied],s=t.validation.flatMap(i=>i==="visual"?["visual"]:i==="playback"||i==="browser"?["test"]:[]);for(let i of s)if(!o.some(a=>a.kind===i&&a.status==="passed")){if(e.policy==="strict")throw new Error(`${e.title} requires passed ${i} validation evidence before it can be saved as a completed Work output.`);o.push({kind:i,status:"not_run",label:`${e.title} ${i} validation was not run before automatic preservation`,detail:"The file was preserved automatically at turn completion; review this revision before relying on presentation or playback quality."})}return o}r(Am,"validateWorkOutput");function _m(e){let t=Em(e.bytes,e.contentType);return{kind:"structural",status:t?"passed":"failed",label:`Validated ${e.title} structure`,detail:t?`Content matches ${e.contentType}.`:`Content does not match ${e.contentType}.`}}r(_m,"structuralValidation");function Em(e,t){if(e.byteLength===0)return!1;if(t.startsWith("text/")||t==="application/json"||t==="image/svg+xml"){let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return!1}if(t==="application/json")try{JSON.parse(n)}catch{return!1}return t==="text/html"?/<(?:!doctype\s+html|html|body)\b/i.test(n):t==="image/svg+xml"?/<svg\b/i.test(n):n.trim().length>0}if(t==="application/pdf")return e.subarray(0,5).toString("ascii")==="%PDF-"&&e.subarray(Math.max(0,e.byteLength-1024)).toString("ascii").includes("%%EOF");if(t.includes("wordprocessingml")||t.includes("spreadsheetml")||t.includes("presentationml")){let n=Mm(e),o=t.includes("wordprocessingml")?"word/document.xml":t.includes("spreadsheetml")?"xl/workbook.xml":"ppt/presentation.xml";return n.has("[Content_Types].xml")&&n.has("_rels/.rels")&&n.has(o)}return t==="image/png"?e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])):t==="image/jpeg"?e[0]===255&&e[1]===216:t==="image/gif"?e.subarray(0,4).toString("ascii")==="GIF8":t==="image/webp"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WEBP":t==="image/avif"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="audio/wav"?e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WAVE":t==="audio/mpeg"?e.subarray(0,3).toString("ascii")==="ID3"||e[0]===255&&(e[1]&224)===224:t==="audio/mp4"||t==="video/mp4"||t==="video/quicktime"?e.subarray(4,12).toString("ascii").includes("ftyp"):t==="video/webm"?e.subarray(0,4).equals(Buffer.from([26,69,223,163])):!0}r(Em,"structuralContentMatches");function Mm(e){let t=new Set;for(let n=0;n+46<=e.byteLength;){if(e.readUInt32LE(n)!==33639248){n+=1;continue}let o=e.readUInt16LE(n+28),s=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32),a=n+46+o+s+i;if(a>e.byteLength)return new Set;let l=e.subarray(n+46,n+46+o).toString("utf8").replaceAll("\\","/").replace(/^\/+/,"");l&&t.add(l),n=a}return t}r(Mm,"zipCentralDirectoryEntries");function Om(e){let t=e.trim().replaceAll("\\","/");if(!t||t.startsWith("/"))throw new Error("Work output path must be relative to /workspace.");let n=ke.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../")||!n.startsWith("outputs/")||n==="outputs/")throw new Error("Completed Work outputs must be inside /workspace/outputs.");return n}r(Om,"normalizeOutputCandidatePath");async function Ql(e){let t=await e.runtimeEventsForSession(e.sessionId),n=null;for(let o of t){let s=hs(o.data);s?.kind!=="file"||s.title!==e.title||(!n||s.revision>n.revision)&&(n=s)}return{id:n?.id??e.firstId??Zl(),revision:(n?.revision??0)+1}}r(Ql,"nextOutputIdentity");function hs(e,t=0){if(t>6||e==null)return null;let n=Kt.safeParse(e);if(n.success)return n.data;if(Array.isArray(e)){for(let s of e){let i=hs(s,t+1);if(i)return i}return null}let o=En(e);for(let s of Object.values(o)){let i=hs(s,t+1);if(i)return i}return null}r(hs,"findOutputRef");function ws(e,t,n,o=0){if(o>8||e==null)return null;let s=Kt.safeParse(e);if(s.success&&s.data.id===t&&(n==null||s.data.revision===n))return s.data;if(Array.isArray(e)){let l=null;for(let p of e){let d=ws(p,t,n,o+1);d&&(!l||d.revision>l.revision)&&(l=d)}return l}let i=En(e),a=null;for(let l of Object.values(i)){let p=ws(l,t,n,o+1);p&&(!a||p.revision>a.revision)&&(a=p)}return a}r(ws,"findOutputRefById");function Jo(e){let n=ke.basename(e.trim()).replace(/[^a-zA-Z0-9._ -]+/g,"-").replace(/\s+/g," ").trim().slice(0,180);if(!n||n==="."||n==="..")throw new Error("A valid output file name is required.");return n}r(Jo,"safeOutputName");function Xo(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,100)||"item"}r(Xo,"safePathSegment");function En(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(En,"asRecord");function Yl(e){return typeof e=="number"&&Number.isFinite(e)?e:null}r(Yl,"numberValue");import{promises as Qo}from"node:fs";import Fm from"node:path";async function tu(e,t,n=Date.now()){let o=[];for(let i of await Qo.readdir(e,{withFileTypes:!0})){if(!i.isFile()||!/\.log(?:\.\d+)?$/.test(i.name))continue;let a=Fm.join(e,i.name),l=await Qo.lstat(a).catch(p=>{if(p.code==="ENOENT")return null;throw p});l?.isFile()&&o.push({file:a,size:l.size,modified:l.mtimeMs})}let s=o.reduce((i,a)=>i+a.size,0);for(let i of o.sort((a,l)=>a.modified-l.modified)){if(i.file===t||i.modified>=n-14*864e5&&s<=256*1024*1024)continue;let a=await Qo.lstat(i.file).catch(()=>null);a?.isFile()&&a.size===i.size&&a.mtimeMs===i.modified&&(await Qo.rm(i.file,{force:!0}),s-=i.size)}}r(tu,"pruneLogs");import{promises as Kn}from"node:fs";import jm from"node:path";var nu=1024*1024,Nm=5,bs=/authorization|api[_-]?key|token|session[_-]?token|secret|password/i,$m=/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,qm=/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi;function Bm(e){return{name:e.name,message:e.message,stack:e.stack}}r(Bm,"serializeError");function Yo(e){if(e instanceof Error)return Yo(Bm(e));if(typeof e=="string")return Wm(e);if(Array.isArray(e))return e.map(n=>Yo(n));if(!e||typeof e!="object")return e;let t={};for(let[n,o]of Object.entries(e))t[n]=bs.test(n)?"[REDACTED]":Yo(o);return t}r(Yo,"redact");async function ou(e,t){try{await Kn.rm(t,{force:!0}),await Kn.rename(e,t)}catch(n){if(n.code!=="ENOENT")throw n}}r(ou,"renameIfExists");function Wm(e){return e.replace($m,"Bearer [REDACTED]").replace(qm,t=>Dm(t))}r(Wm,"redactString");function Dm(e){let{url:t,suffix:n}=Hm(e);try{let o=new URL(t);return(o.username||o.password)&&(o.username="[REDACTED]",o.password="[REDACTED]"),ru(o.searchParams),o.hash&&(o.hash=Lm(o.hash.slice(1))),`${o.toString()}${n}`}catch{return e}}r(Dm,"redactUrl");function Hm(e){let t=e,n="";for(;/[),.;!?]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{url:t,suffix:n}}r(Hm,"splitUrlSuffix");function ru(e){for(let t of Array.from(e.keys()))bs.test(t)&&e.set(t,"[REDACTED]")}r(ru,"redactSearchParams");function Lm(e){if(!e.includes("="))return bs.test(e)?"[REDACTED]":e;let t=new URLSearchParams(e.startsWith("?")?e.slice(1):e);return ru(t),t.toString()}r(Lm,"redactHash");function jv(e){let t=e.maxBytes??nu,n=e.maxFiles??Nm,o=jm.join(e.logDir,e.filename??`${e.channel}.log`),s=Promise.resolve(),i=0;async function a(p){let d=0;try{d=(await Kn.stat(o)).size}catch(u){if(u.code!=="ENOENT")throw u}if(!(d+p<=t)){for(let u=n-1;u>=1;u-=1)await ou(`${o}.${u}`,`${o}.${u+1}`);await ou(o,`${o}.1`)}}r(a,"rotateIfNeeded");function l(p,d,u={}){let f={ts:new Date().toISOString(),level:p,channel:e.channel,message:d,pid:process.pid,platform:process.platform,...e.metadata??{},...u},h=`${JSON.stringify(Yo(f))}
3
3
  `;Buffer.byteLength(h)>Math.max(nu,t)&&(h=`${JSON.stringify({ts:f.ts,level:p,channel:e.channel,message:"Oversized log record omitted",originalBytes:Buffer.byteLength(h)})}
4
4
  `),s=s.then(async()=>{await Kn.mkdir(e.logDir,{recursive:!0}),await a(Buffer.byteLength(h,"utf8")),await Kn.appendFile(o,h,{encoding:"utf8",mode:384}),Date.now()-i>=6e4&&(await tu(e.logDir,o),i=Date.now())}).catch(v=>{console.error("OpenPond logger failed",v)})}return r(l,"write"),{debug:r((p,d)=>l("debug",p,d),"debug"),info:r((p,d)=>l("info",p,d),"info"),warn:r((p,d)=>l("warn",p,d),"warn"),error:r((p,d)=>l("error",p,d),"error"),flush:r(()=>s,"flush"),filePath:o}}r(jv,"createLogger");function vs(e){let t=e.environment??process.env;if(e.provider!=="openpond"||e.model!==t.OPENPOND_HOSTED_MODEL_ID?.trim())return null;let n=t.OPENPOND_HOSTED_MODEL_CONTEXT_WINDOW,o=t.OPENPOND_HOSTED_MODEL_OUTPUT_LIMIT;if(n===void 0&&o===void 0)return null;let s=r(i=>{if(i===void 0)return null;let a=Number(i);if(!/^\d+$/.test(i)||!Number.isSafeInteger(a)||a<=0)throw new Error("Hosted admitted model limit is invalid.");return a},"parse");return{contextWindow:s(n),outputLimit:s(o)}}r(vs,"admittedHostedModelLimits");var lu=4,Um=128e3,zm=8e3,su=8192,iu=1024;function Zo(e){return e==="openpond"?e:null}r(Zo,"hostedContextProvider");function er(e,t){let o=t.trim().toLowerCase().match(/(?:^|[-_])(\d+)\s*k(?:[-_]|$)/);return o?.[1]?Number.parseInt(o[1],10)*1e3:Um}r(er,"hostedContextLimit");function Vn(e){let t=Math.min(zm,Math.ceil(e*.25)),n=Math.min(e-1,Math.max(t,Math.ceil(e*.08)));return Math.max(1,e-n)}r(Vn,"usableHostedContextLimit");function Vt(e){let t=e.model?.trim();if(!t)return null;let n=vs({provider:e.provider,model:t});if(n?.contextWindow)return n.contextWindow;let s=e.settings?.modelCaches[e.provider]?.models.find(a=>a.id===t);if(s?.contextWindow)return s.contextWindow;let i=Zo(e.provider);return i?er(i,t):null}r(Vt,"trustedProviderContextLimit");function Ss(e){let t=e.model?.trim();if(!t)return null;let n=vs({provider:e.provider,model:t});return n?.outputLimit?n.outputLimit:e.settings?.modelCaches[e.provider]?.models.find(s=>s.id===t)?.outputLimit??null}r(Ss,"trustedProviderOutputLimit");function tr(e){let t=e.reduce((n,o)=>n+o.role.length+(o.name?.length??0)+(o.content?.length??0)+8,0);return Math.max(1,Math.ceil(t/lu)+e.length*4)}r(tr,"estimateHostedMessageTokens");function nr(e){let t=Gm(e.provider,e.model);if(!t)return{tokens:tr(e.messages),source:"heuristic",modelFamily:null};let n=e.messages.reduce((o,s)=>o+4+ys(s.role,t)+ys(s.name??"",t)+ys(s.content??"",t),1);return{tokens:Math.max(1,n),source:"model_family",modelFamily:t}}r(nr,"estimateHostedMessageTokensForProvider");function Mn(e){let t=e.maxContextTokens?Math.max(256,Math.floor(e.maxContextTokens/8)):su,n=e.modelOutputLimit&&e.modelOutputLimit>0?Math.floor(e.modelOutputLimit):Number.MAX_SAFE_INTEGER;return Math.max(1,Math.min(e.requestedOutputTokens??su,t,n))}r(Mn,"hostedRequestedOutputTokens");function Gn(e){let t=e.maxContextTokens??null,n=nr({provider:e.provider,model:e.model,messages:e.messages}),o=n.tokens,s=au(e.tools??[]),i=au(e.messages.flatMap(p=>{let d={};return p.continuation!==void 0&&(d.continuation=p.continuation),p.tool_calls!==void 0&&(d.tool_calls=p.tool_calls),p.tool_call_id!==void 0&&(d.tool_call_id=p.tool_call_id),Object.keys(d).length>0?[d]:[]})),a=Math.max(1,Math.floor(e.maxOutputTokens)),l=Km(e.provider,t);return{messageTokens:o,toolDefinitionTokens:s,continuationTokens:i,outputAllowanceTokens:a,safetyReserveTokens:l,projectedTokens:o+s+i+a+l,maxContextTokens:t,tokenSource:n.source,tokenModelFamily:n.modelFamily}}r(Gn,"estimateHostedRequestBudget");function au(e){if(Array.isArray(e)&&e.length===0)return 0;let t=JSON.stringify(e);return!t||t==="[]"||t==="{}"?0:Math.max(1,Math.ceil(t.length/lu))}r(au,"estimatedSerializedTokens");function Km(e,t){return t?Math.min(Math.max(1,Math.floor(t/8)),Math.max(iu,Math.ceil(t*.02))):iu*2}r(Km,"requestSafetyReserveTokens");function ks(e,t){if(!e||typeof e!="object")return null;let n=e;for(let o of t){let s=n[o];if(typeof s=="number"&&Number.isFinite(s)&&s>=0)return Math.round(s)}return null}r(ks,"numericUsageValue");function Vm(e,t){let n=ks(e,["prompt_tokens","promptTokens","input_tokens","inputTokens"]),o=ks(e,["completion_tokens","completionTokens","output_tokens","outputTokens"]),s=ks(e,["total_tokens","totalTokens"]);return t?s!==null?s:n!==null&&o!==null?n+o:null:n??s}r(Vm,"tokenCountFromUsage");function uu(e){let t=e.usage===void 0?null:Vm(e.usage,!!e.includeCompletion),n=nr({provider:e.provider,model:e.model,messages:e.messages}),o=t??n.tokens,s=e.maxContextTokens??Vt({provider:e.provider,model:e.model});if(!s)throw new Error(`Cannot create context usage snapshot without a trusted context limit for ${e.provider}.`);let i=Math.min(100,Math.round(o/s*100));return No.parse({provider:e.provider,model:e.model,usedTokens:o,maxContextTokens:s,usableContextTokens:Vn(s),percentFull:i,source:t===null?n.source:"provider_usage",updatedAtEventId:e.updatedAtEventId})}r(uu,"createContextUsageSnapshot");function Gm(e,t){let n=`${e}/${t??""}`.toLowerCase();return/\b(?:gpt|o[1-9]|codex)\b/.test(n)?"openai_cl100k":n.includes("claude")||e==="anthropic"?"anthropic_claude":n.includes("deepseek")||n.includes("kimi")||n.includes("glm")?"multilingual_code":null}r(Gm,"modelTokenFamily");function ys(e,t){if(!e)return 0;let n=[...e].filter(i=>/[\u3000-\u9fff\uf900-\ufaff]/u.test(i)).length,o=Math.max(0,e.length-n);return Math.max(1,n+Math.ceil(o/(t==="anthropic_claude"?3.85:t==="multilingual_code"?3.65:3.75)))}r(ys,"estimateModelFamilyTextTokens");import{randomUUID as Jm}from"node:crypto";import{promises as cu}from"node:fs";import or from"node:path";var du=8e3;function Rs(e,t){if(!/^custom:[a-zA-Z0-9_-]+$/.test(t))throw new Error("Invalid custom personality identifier.");return or.join(nn(e).instructions,"personalities",`${t.slice(7)}.md`)}r(Rs,"personalityPath");function Is(e,t){if(e.trim().length>du)throw new Pn({code:"INVALID_INSTRUCTIONS",path:t??"personalization",message:`Personality text exceeds ${du} characters.`,action:"Shorten the personality text before using it."});return e.trim()}r(Is,"validateText");async function Xm(e){let t=or.join(nn(e).instructions,"personalities"),n=await cu.readdir(t,{withFileTypes:!0}).catch(s=>{if(Yi(s))return[];throw s}),o=[...Dn];for(let s of n.sort((i,a)=>i.name.localeCompare(a.name))){if(!s.isFile()||!/^[a-zA-Z0-9_-]+\.md$/.test(s.name))continue;let i=or.join(t,s.name),a=await Wn(i);a!==null&&o.push({id:`custom:${s.name.slice(0,-3)}`,name:s.name.slice(0,-3).replace(/[-_]+/g," "),source:"custom",description:"",content:Is(a,i)})}return o}r(Xm,"templatesWithFiles");async function Qm(e,t){let{document:n}=await qo(t),o=await Xm(t),s=n.personalization?.active??`builtin:${$o}`,i=s.startsWith("builtin:")?s.slice(8):s,a=o.find(p=>p.id===i);if(!a)throw new Pn({code:"MISSING_PERSONALITY",path:s.startsWith("custom:")?Rs(t,s):nn(t).config,message:`Selected personality ${s} is unavailable.`,action:"Restore its Markdown file or select an available personality in Settings."});let l=s.startsWith("custom:")?Rs(t,s):null;return da.parse({activeTemplateId:i,customized:a.source==="custom",soul:n.personalization?.mode==="disabled"?"":a.content,soulPath:l,updatedAt:l?(await cu.stat(l)).mtime.toISOString():null,templates:o})}r(Qm,"loadPersonalizationSettings");async function Jv(e,t,n){return await Fo(or.join(nn(t).runtime,"personalization"),async()=>{let o=Is(n.soul),s=Dn.find(a=>a.id===n.activeTemplateId),i;if(!n.saveAsNew&&s&&o===s.content.trim())i=`builtin:${s.id}`;else{let a=n.templateName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,56)||"custom";i=!n.saveAsNew&&n.activeTemplateId.startsWith("custom:")?n.activeTemplateId:`custom:${a}-${Jm().slice(0,8)}`,await ea(Rs(t,i),`${o}
5
5
  `)}await Bo(t,a=>({...a,personalization:{...a.personalization,active:i}}))}),Qm(e,t)}r(Jv,"savePersonalizationSettings");function pu(e,t){return[Is(e),t.trim()].filter(Boolean).join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{t as M}from"./chunk-QOTVNQDI.js";import{Qb as A,m as S,v as T}from"./chunk-Y4OWBBDD.js";import{m as f,n as k}from"./chunk-KGNCKIFP.js";import{b as R}from"./chunk-ES2ISFJC.js";import{a as g}from"./chunk-FTQLQJQV.js";function q(e,i,a){if(i==="agent_action"){let n=e.find(u=>u.name==="workspace_action_result"&&u.action==="profile_workflow_action")?.output;if(typeof n!="string")throw new Error("Profile Agent action evaluation did not produce a released action result.");return n}if(a==="completed"){let t=[...e].reverse().find(l=>l.name==="turn.completed")?.data?.providerResponse;if(typeof t?.requestId!="string"||!t.requestId||typeof t.contentHash!="string")throw new Error("Profile evaluation has no retained final provider response.");let r=e.filter(l=>l.name==="assistant.delta"&&l.data?.providerRequestId===t.requestId).map(l=>l.output??"").join("");if(f(r)!==t.contentHash)throw new Error("Profile evaluation final provider response differs from its retained trace.");return r}return e.filter(n=>n.name==="assistant.delta"&&typeof n.output=="string").map(n=>n.output??"").join("")}g(q,"profileEvaluationOutput");async function x(e){let{store:i,manifest:a,receipt:n}=e;if(!n.metadata.retainedEvidenceRef)return null;let u=A.parse(n.metadata.retainedEvidenceRef),[t,r]=await Promise.all([i.getSession(u.sessionId),i.getTurn(u.turnId)]),l=t?.metadata?.profileEvaluationRun,h=a.profileEvaluation;if(!t||!r||r.sessionId!==t.id||!h||!t.currentProfile||f(t.currentProfile)!==f(e.profileRef)||f(l)!==f({id:a.id,contentHash:a.contentHash})||t.metadata?.taskId!==n.taskId||t.metadata?.seed!==n.seed||!r.completedAt||r.completedAt!==n.completedAt||r.startedAt!==n.startedAt||!r.harnessSnapshot||r.harnessSnapshot.harnessRelease.id!==h.harnessRelease.id||r.harnessSnapshot.harnessRelease.contentHash!==h.harnessRelease.contentHash||a.policy.kind!=="model"||!r.modelRef||r.modelRef.providerId!==a.policy.model.provider||r.modelRef.modelId!==a.policy.model.model)throw new Error("Retained Profile policy turn differs from its admitted case.");let d=await i.runtimeEventsForTurn(r.id);if(d.some(v=>v.turnId!==r.id)||f(d)!==n.traceHash)throw new Error("Retained Profile policy trace differs from its immutable receipt.");let o=q(d,h.target.kind,r.status);if(n.outputHash!==null&&f({text:o})!==n.outputHash)throw new Error("Retained Profile output differs from its immutable receipt.");let p=n.artifactRefs.flatMap(v=>{let E=d.filter(s=>(s.action==="work_output_save"||s.action==="sandbox_save_output")&&s.status==="completed").flatMap(s=>{let _=s.data&&typeof s.data=="object"?s.data:{},H=M.safeParse(_.outputRef);return H.success?[H.data]:[]}).filter(s=>s.sourceTaskId===t.id&&s.sourceTurnId===r.id&&`${t.id}/${s.id}/${s.revision}/${s.title}`===v.id&&s.sha256===v.contentHash&&s.sizeBytes===v.sizeBytes&&s.contentType===v.mediaType);if(E.length!==1)throw new Error("The case output has no unique sealed saved-file identity.");let m=E[0];if(m.location.kind!=="managed")return[];let y=`/api/work/outputs/${encodeURIComponent(m.location.fileId)}`;if(m.location.downloadPath!==y)throw new Error("The saved output has no canonical managed download route.");return[{id:m.id,title:m.title,revision:m.revision,contentType:m.contentType,sizeBytes:m.sizeBytes,sha256:m.sha256,downloadPath:y}]}),c=await i.listModelUsageRecords({sessionId:t.id,turnId:r.id,limit:1e4}),P=e.eventAfterId?d.findIndex(v=>v.id===e.eventAfterId):-1;if(e.eventAfterId&&P<0)throw new Error("Profile trace cursor is unavailable in this case.");let I=P+1,b=Math.max(1,Math.min(250,e.eventLimit??100)),w=d.slice(I,I+b);return{ref:u,prompt:r.prompt,output:n.outputHash===null?null:{text:o},partialOutput:n.outputHash===null&&o?{text:o}:null,error:r.error,events:w,eventCount:d.length,nextEventCursor:I+w.length<d.length?w.at(-1).id:null,files:p,usage:c,usageCoverage:c.length===1e4?"partial":"complete"}}g(x,"readProfileEvaluationPolicyEvidence");var G=R.object({runId:R.string().trim().min(1).max(240),receiptId:R.string().trim().min(1).max(500).optional(),eventAfterId:R.string().trim().min(1).max(500).optional(),eventLimit:R.number().int().min(1).max(250).optional(),manifest:T.optional()}).strict().refine(e=>e.receiptId||!e.eventAfterId&&!e.eventLimit,"Select a case before requesting its trace page.").refine(e=>!e.manifest||e.receiptId,"Interrupted-run inspection requires one exact case.");async function V(e){let i=await e.store.getProfileEvaluationRun(e.runId);if(i&&f(i.profileRef)!==f(e.profileRef))throw new Error("Profile evaluation run is unavailable in the selected Profile.");let a=i?.manifest??e.manifest;if(!a||!i&&!e.receiptId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");if(i){if(e.manifest&&e.manifest.contentHash!==i.manifest.contentHash)throw new Error("Profile evaluation run differs from its pinned manifest.")}else if(k(a,"Interrupted Profile evaluation manifest"),a.id!==e.runId||a.profileEvaluation?.profileId!==e.profileRef.profileId||e.profileRef.source==="openpond_git"&&a.metadata.profileRepositoryId!==e.profileRef.repositoryId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");let n=a.population.map((t,r)=>({member:t,index:r})).filter(({member:t})=>!e.receiptId||t.receiptId===e.receiptId);if(e.receiptId&&n.length!==1)throw new Error("Profile evaluation case is unavailable in the selected run.");let u=await Promise.all(n.map(async({member:t,index:r})=>{let l=i?null:await e.store.getProfileEvaluationReceipt(t.receiptId),h=i?.receiptRefs[r]??(l?{id:l.id,contentHash:l.contentHash}:null),d=i?.gradeRefs[r]??l?.graderEvidenceRefs[0];if(!h||!d)throw new Error("Profile evaluation run has incomplete case evidence.");let[o,p]=await Promise.all([e.store.getProfileEvaluationReceipt(h.id),e.store.getProfileEvaluationGrade(d.contentHash)]);if(!o||!i&&!S(o)||o.contentHash!==h.contentHash||o.id!==t.receiptId||o.taskId!==t.taskId||o.seed!==t.seed||o.runManifest.id!==a.id||o.runManifest.contentHash!==a.contentHash||!p||p.contentHash!==d.contentHash||!o.graderEvidenceRefs.some(c=>c.id===d.id&&c.contentHash===d.contentHash))throw new Error("Profile evaluation case evidence differs from its retained run.");return{taskId:t.taskId,seed:t.seed,receiptId:o.id,receiptHash:o.contentHash,traceHash:o.traceHash,outputHash:o.outputHash,score:p.score,passed:p.passed,gradingStatus:p.gradingStatus,failureClass:p.failureClass,artifactCount:o.artifactRefs.length,latencyMs:o.latencyMs,costUsd:o.costUsd,terminal:o.terminal,feedback:p.components.map(c=>({graderId:c.graderId,graderVersion:c.graderVersion,score:c.score,passed:c.passed,feedback:c.feedback})),...e.receiptId?{receipt:o,evidence:await x({store:e.store,profileRef:e.profileRef,manifest:a,receipt:o,eventAfterId:e.eventAfterId,eventLimit:e.eventLimit})}:{}}}));return{runId:a.id,sourceRevision:a.profileEvaluation?.sourceRevision??null,cases:u}}g(V,"inspectProfileEvaluationRun");export{q as a,G as b,V as c};
2
+ import{t as M}from"./chunk-QL4OIPEZ.js";import{Qb as A,m as S,v as T}from"./chunk-Y4OWBBDD.js";import{m as f,n as k}from"./chunk-KGNCKIFP.js";import{b as R}from"./chunk-ES2ISFJC.js";import{a as g}from"./chunk-FTQLQJQV.js";function q(e,i,a){if(i==="agent_action"){let n=e.find(u=>u.name==="workspace_action_result"&&u.action==="profile_workflow_action")?.output;if(typeof n!="string")throw new Error("Profile Agent action evaluation did not produce a released action result.");return n}if(a==="completed"){let t=[...e].reverse().find(l=>l.name==="turn.completed")?.data?.providerResponse;if(typeof t?.requestId!="string"||!t.requestId||typeof t.contentHash!="string")throw new Error("Profile evaluation has no retained final provider response.");let r=e.filter(l=>l.name==="assistant.delta"&&l.data?.providerRequestId===t.requestId).map(l=>l.output??"").join("");if(f(r)!==t.contentHash)throw new Error("Profile evaluation final provider response differs from its retained trace.");return r}return e.filter(n=>n.name==="assistant.delta"&&typeof n.output=="string").map(n=>n.output??"").join("")}g(q,"profileEvaluationOutput");async function x(e){let{store:i,manifest:a,receipt:n}=e;if(!n.metadata.retainedEvidenceRef)return null;let u=A.parse(n.metadata.retainedEvidenceRef),[t,r]=await Promise.all([i.getSession(u.sessionId),i.getTurn(u.turnId)]),l=t?.metadata?.profileEvaluationRun,h=a.profileEvaluation;if(!t||!r||r.sessionId!==t.id||!h||!t.currentProfile||f(t.currentProfile)!==f(e.profileRef)||f(l)!==f({id:a.id,contentHash:a.contentHash})||t.metadata?.taskId!==n.taskId||t.metadata?.seed!==n.seed||!r.completedAt||r.completedAt!==n.completedAt||r.startedAt!==n.startedAt||!r.harnessSnapshot||r.harnessSnapshot.harnessRelease.id!==h.harnessRelease.id||r.harnessSnapshot.harnessRelease.contentHash!==h.harnessRelease.contentHash||a.policy.kind!=="model"||!r.modelRef||r.modelRef.providerId!==a.policy.model.provider||r.modelRef.modelId!==a.policy.model.model)throw new Error("Retained Profile policy turn differs from its admitted case.");let d=await i.runtimeEventsForTurn(r.id);if(d.some(v=>v.turnId!==r.id)||f(d)!==n.traceHash)throw new Error("Retained Profile policy trace differs from its immutable receipt.");let o=q(d,h.target.kind,r.status);if(n.outputHash!==null&&f({text:o})!==n.outputHash)throw new Error("Retained Profile output differs from its immutable receipt.");let p=n.artifactRefs.flatMap(v=>{let E=d.filter(s=>(s.action==="work_output_save"||s.action==="sandbox_save_output")&&s.status==="completed").flatMap(s=>{let _=s.data&&typeof s.data=="object"?s.data:{},H=M.safeParse(_.outputRef);return H.success?[H.data]:[]}).filter(s=>s.sourceTaskId===t.id&&s.sourceTurnId===r.id&&`${t.id}/${s.id}/${s.revision}/${s.title}`===v.id&&s.sha256===v.contentHash&&s.sizeBytes===v.sizeBytes&&s.contentType===v.mediaType);if(E.length!==1)throw new Error("The case output has no unique sealed saved-file identity.");let m=E[0];if(m.location.kind!=="managed")return[];let y=`/api/work/outputs/${encodeURIComponent(m.location.fileId)}`;if(m.location.downloadPath!==y)throw new Error("The saved output has no canonical managed download route.");return[{id:m.id,title:m.title,revision:m.revision,contentType:m.contentType,sizeBytes:m.sizeBytes,sha256:m.sha256,downloadPath:y}]}),c=await i.listModelUsageRecords({sessionId:t.id,turnId:r.id,limit:1e4}),P=e.eventAfterId?d.findIndex(v=>v.id===e.eventAfterId):-1;if(e.eventAfterId&&P<0)throw new Error("Profile trace cursor is unavailable in this case.");let I=P+1,b=Math.max(1,Math.min(250,e.eventLimit??100)),w=d.slice(I,I+b);return{ref:u,prompt:r.prompt,output:n.outputHash===null?null:{text:o},partialOutput:n.outputHash===null&&o?{text:o}:null,error:r.error,events:w,eventCount:d.length,nextEventCursor:I+w.length<d.length?w.at(-1).id:null,files:p,usage:c,usageCoverage:c.length===1e4?"partial":"complete"}}g(x,"readProfileEvaluationPolicyEvidence");var G=R.object({runId:R.string().trim().min(1).max(240),receiptId:R.string().trim().min(1).max(500).optional(),eventAfterId:R.string().trim().min(1).max(500).optional(),eventLimit:R.number().int().min(1).max(250).optional(),manifest:T.optional()}).strict().refine(e=>e.receiptId||!e.eventAfterId&&!e.eventLimit,"Select a case before requesting its trace page.").refine(e=>!e.manifest||e.receiptId,"Interrupted-run inspection requires one exact case.");async function V(e){let i=await e.store.getProfileEvaluationRun(e.runId);if(i&&f(i.profileRef)!==f(e.profileRef))throw new Error("Profile evaluation run is unavailable in the selected Profile.");let a=i?.manifest??e.manifest;if(!a||!i&&!e.receiptId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");if(i){if(e.manifest&&e.manifest.contentHash!==i.manifest.contentHash)throw new Error("Profile evaluation run differs from its pinned manifest.")}else if(k(a,"Interrupted Profile evaluation manifest"),a.id!==e.runId||a.profileEvaluation?.profileId!==e.profileRef.profileId||e.profileRef.source==="openpond_git"&&a.metadata.profileRepositoryId!==e.profileRef.repositoryId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");let n=a.population.map((t,r)=>({member:t,index:r})).filter(({member:t})=>!e.receiptId||t.receiptId===e.receiptId);if(e.receiptId&&n.length!==1)throw new Error("Profile evaluation case is unavailable in the selected run.");let u=await Promise.all(n.map(async({member:t,index:r})=>{let l=i?null:await e.store.getProfileEvaluationReceipt(t.receiptId),h=i?.receiptRefs[r]??(l?{id:l.id,contentHash:l.contentHash}:null),d=i?.gradeRefs[r]??l?.graderEvidenceRefs[0];if(!h||!d)throw new Error("Profile evaluation run has incomplete case evidence.");let[o,p]=await Promise.all([e.store.getProfileEvaluationReceipt(h.id),e.store.getProfileEvaluationGrade(d.contentHash)]);if(!o||!i&&!S(o)||o.contentHash!==h.contentHash||o.id!==t.receiptId||o.taskId!==t.taskId||o.seed!==t.seed||o.runManifest.id!==a.id||o.runManifest.contentHash!==a.contentHash||!p||p.contentHash!==d.contentHash||!o.graderEvidenceRefs.some(c=>c.id===d.id&&c.contentHash===d.contentHash))throw new Error("Profile evaluation case evidence differs from its retained run.");return{taskId:t.taskId,seed:t.seed,receiptId:o.id,receiptHash:o.contentHash,traceHash:o.traceHash,outputHash:o.outputHash,score:p.score,passed:p.passed,gradingStatus:p.gradingStatus,failureClass:p.failureClass,artifactCount:o.artifactRefs.length,latencyMs:o.latencyMs,costUsd:o.costUsd,terminal:o.terminal,feedback:p.components.map(c=>({graderId:c.graderId,graderVersion:c.graderVersion,score:c.score,passed:c.passed,feedback:c.feedback})),...e.receiptId?{receipt:o,evidence:await x({store:e.store,profileRef:e.profileRef,manifest:a,receipt:o,eventAfterId:e.eventAfterId,eventLimit:e.eventLimit})}:{}}}));return{runId:a.id,sourceRevision:a.profileEvaluation?.sourceRevision??null,cases:u}}g(V,"inspectProfileEvaluationRun");export{q as a,G as b,V as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{m as c}from"./chunk-QOTVNQDI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{access as k,readFile as m}from"node:fs/promises";import{createHash as d}from"node:crypto";import o from"node:path";import{fileURLToPath as g}from"node:url";var a="openpond-taskset-authoring",u="artifact.json",h=o.dirname(g(import.meta.url));async function P(e=process.cwd()){return(await p(e)).bundle}i(P,"loadTasksetAuthoringSkillBundle");async function p(e=process.cwd()){let s=await f(e),t=JSON.parse(await m(o.join(s,u),"utf8"));if(t.schemaVersion!==1||t.skillName!==a||!t.artifactVersion||!t.bundle||!/^[a-f0-9]{64}$/.test(t.contentHash))throw new Error("Bundled Taskset Authoring artifact is invalid.");let{contentHash:r,...n}=t;if(d("sha256").update(JSON.stringify(n)).digest("hex")!==r)throw new Error("Bundled Taskset Authoring artifact hash does not match.");for(let l of t.files)if(d("sha256").update(l.contents).digest("hex")!==l.sha256)throw new Error(`Bundled Taskset Authoring file hash does not match: ${l.path}`);return t}i(p,"loadTasksetAuthoringSkillArtifact");async function S(e=process.cwd()){let s=await f(e),t=await p(e),r=t.bundle,n=c[0];return{...n,path:o.join(s,"SKILL.md"),sourcePath:s,charCount:r.length,sourceHash:t.contentHash,validationMessages:[...n.validationMessages],resourceFiles:[...n.resourceFiles]}}i(S,"loadTasksetAuthoringProfileSkill");async function O(e=process.cwd()){let s=await S(e),t=await P(e);return{name:s.name,description:s.description,body:t,path:s.path,sourceHash:s.sourceHash,charCount:s.charCount,packagePath:s.sourcePath,resourceFiles:s.resourceFiles}}i(O,"readTasksetAuthoringProfileSkill");async function f(e=process.cwd(),s=process.execPath){let t=[process.env.OPENPOND_TASKSET_AUTHORING_SKILL_ROOT,o.resolve(e,"apps","cli","skills",a),o.resolve(e,"dist","skills",a),o.resolve(o.dirname(s),"skills",a),o.resolve(h,"skills",a),o.resolve(h,"..","skills",a)].filter(r=>!!r);for(let r of t)if(await k(o.join(r,u)).then(()=>!0,()=>!1))return r;throw new Error(`Bundled Taskset Authoring skill was not found. Checked: ${t.join(", ")}`)}i(f,"resolveTasksetAuthoringSkillRoot");export{p as a,S as b,O as c};
2
+ import{m as c}from"./chunk-QL4OIPEZ.js";import{a as i}from"./chunk-FTQLQJQV.js";import{access as k,readFile as m}from"node:fs/promises";import{createHash as d}from"node:crypto";import o from"node:path";import{fileURLToPath as g}from"node:url";var a="openpond-taskset-authoring",u="artifact.json",h=o.dirname(g(import.meta.url));async function P(e=process.cwd()){return(await p(e)).bundle}i(P,"loadTasksetAuthoringSkillBundle");async function p(e=process.cwd()){let s=await f(e),t=JSON.parse(await m(o.join(s,u),"utf8"));if(t.schemaVersion!==1||t.skillName!==a||!t.artifactVersion||!t.bundle||!/^[a-f0-9]{64}$/.test(t.contentHash))throw new Error("Bundled Taskset Authoring artifact is invalid.");let{contentHash:r,...n}=t;if(d("sha256").update(JSON.stringify(n)).digest("hex")!==r)throw new Error("Bundled Taskset Authoring artifact hash does not match.");for(let l of t.files)if(d("sha256").update(l.contents).digest("hex")!==l.sha256)throw new Error(`Bundled Taskset Authoring file hash does not match: ${l.path}`);return t}i(p,"loadTasksetAuthoringSkillArtifact");async function S(e=process.cwd()){let s=await f(e),t=await p(e),r=t.bundle,n=c[0];return{...n,path:o.join(s,"SKILL.md"),sourcePath:s,charCount:r.length,sourceHash:t.contentHash,validationMessages:[...n.validationMessages],resourceFiles:[...n.resourceFiles]}}i(S,"loadTasksetAuthoringProfileSkill");async function O(e=process.cwd()){let s=await S(e),t=await P(e);return{name:s.name,description:s.description,body:t,path:s.path,sourceHash:s.sourceHash,charCount:s.charCount,packagePath:s.sourcePath,resourceFiles:s.resourceFiles}}i(O,"readTasksetAuthoringProfileSkill");async function f(e=process.cwd(),s=process.execPath){let t=[process.env.OPENPOND_TASKSET_AUTHORING_SKILL_ROOT,o.resolve(e,"apps","cli","skills",a),o.resolve(e,"dist","skills",a),o.resolve(o.dirname(s),"skills",a),o.resolve(h,"skills",a),o.resolve(h,"..","skills",a)].filter(r=>!!r);for(let r of t)if(await k(o.join(r,u)).then(()=>!0,()=>!1))return r;throw new Error(`Bundled Taskset Authoring skill was not found. Checked: ${t.join(", ")}`)}i(f,"resolveTasksetAuthoringSkillRoot");export{p as a,S as b,O as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Me,d as Ne,e as qe}from"./chunk-SH5CBAFC.js";import{a as te}from"./chunk-DMVD2RFZ.js";import{b as He,c as _e,h as Ue}from"./chunk-JDEEWOD7.js";import{b as ee}from"./chunk-4NESNOK5.js";import{j as Ee,p as ke,r as Ce}from"./chunk-UKMA4R6X.js";import{a as Q,b as Ae,h as Oe}from"./chunk-KG325WTN.js";import{I as b,M as Te}from"./chunk-VRIEKBBH.js";import{Ua as _,Xa as W,Ya as Pe,a as $}from"./chunk-QOTVNQDI.js";import{p as F,q as N}from"./chunk-WJ43MJ3F.js";import{h as H,i as xe}from"./chunk-Q4TBTRIG.js";import{X as ve,Y as we,_ as Z,b as ue,ba as be,c as ce,ea as Se,fa as V,ja as ye,la as Ie,ma as Re,p as pe,r as de,s as me,t as ge,u as fe,w as he}from"./chunk-I7AQMAQI.js";import{z as M}from"./chunk-Z4Z5UOZM.js";import{v as ie}from"./chunk-TVQAPBLZ.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ae,d as B,f as le,h as U}from"./chunk-H7IWJN7L.js";import{a as l}from"./chunk-FTQLQJQV.js";import{promises as ne}from"node:fs";import dt from"node:os";import mt from"node:path";import{createServer as gt}from"node:http";import{randomBytes as ft}from"node:crypto";var ot=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),it=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(ot).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ye,importOnly:o.boolean().optional()})]);function De(n,e){let t=null;async function r(i,a){let c=U(n).config,p=null,u=null,m=null;try{p=await ce(c),m=await V(n,{projectRoot:i,accountId:a}),i||(t=m)}catch(R){u=B(R,c)}let w=m??(i?null:t);return{path:c,text:p,rawRevision:ue(p),issue:u,effective:w,usingLastValid:!m&&!!w,applies:"next_turn",recoverableRevisions:await de(n),clientState:u?null:await Ie(n)}}l(r,"status");async function s(i){let a=it.parse(i);if(a.action==="validate")return{valid:!0,document:pe(a.text,U(n).config)};if(a.action==="client-state")return Re(n,a.owner,a.patch,a.importOnly);let c=l(async()=>{a.action==="patch"&&await he(n,a.expectedRevision,a.operations),a.action==="replace"&&await me(n,a.expectedRevision,a.text),a.action==="restore"&&await ge(n,a.revision,a.expectedRevision),a.action==="trust"&&await Se(n,a.root,a.accountId,a.trusted)},"mutation");return e?await e(c):await c(),r()}return l(s,"mutate"),{status:r,mutate:s,schema:fe}}l(De,"createConfigurationPayloads");import{Buffer as Be}from"node:buffer";var G={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id, idempotency-key","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},at=25*1024*1024,j=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{l(this,"HttpBodyError")}};function je(n,e,t={}){for(let[s,i]of Object.entries(G))e.setHeader(s,i);let r=Ve(n.headers.origin);return r?(e.setHeader("Vary",pt(e.getHeader("Vary"))),lt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}l(je,"applyCorsHeaders");function lt(n,e={}){if(n==="null")return!0;let t=Fe(n);return t?ct(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Fe(s):null).filter(s=>!!s)).has(t):!1}l(lt,"isAllowedCorsOrigin");function P(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...G}),n.end(JSON.stringify(t))}l(P,"sendJson");function Kt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...G}),n.end(t)}l(Kt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...G}),n.end(t)}l(Yt,"sendBinary");async function re(n,e={}){let t=e.maxBytes??at,r=Ve(n.headers["content-type"]),s=[],i=0;for await(let c of n){let p=Be.from(c);if(i+=p.byteLength,i>t)throw new j(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(p)}let a=Be.concat(s).toString("utf8").trim();if(!a)return{};if(!ut(r))throw new j(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new j(400,"invalid_json","Request body is not valid JSON.")}}l(re,"readJson");function Le(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}l(Le,"hasAuth");function Ve(n){return Array.isArray(n)?n[0]??null:n??null}l(Ve,"headerValue");function ut(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}l(ut,"isJsonContentType");function Fe(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}l(Fe,"normalizeOrigin");function ct(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}l(ct,"isLoopbackOrigin");function pt(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}l(pt,"appendVaryOrigin");function $e(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
2
+ import{a as Me,d as Ne,e as qe}from"./chunk-JAJ46T5X.js";import{a as te}from"./chunk-DMVD2RFZ.js";import{b as He,c as _e,h as Ue}from"./chunk-JDEEWOD7.js";import{b as ee}from"./chunk-4NESNOK5.js";import{j as Ee,p as ke,r as Ce}from"./chunk-UKMA4R6X.js";import{a as Q,b as Ae,h as Oe}from"./chunk-KG325WTN.js";import{I as b,M as Te}from"./chunk-VRIEKBBH.js";import{Ua as _,Xa as W,Ya as Pe,a as $}from"./chunk-QL4OIPEZ.js";import{p as F,q as N}from"./chunk-WJ43MJ3F.js";import{h as H,i as xe}from"./chunk-Q4TBTRIG.js";import{X as ve,Y as we,_ as Z,b as ue,ba as be,c as ce,ea as Se,fa as V,ja as ye,la as Ie,ma as Re,p as pe,r as de,s as me,t as ge,u as fe,w as he}from"./chunk-I7AQMAQI.js";import{z as M}from"./chunk-Z4Z5UOZM.js";import{v as ie}from"./chunk-TVQAPBLZ.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ae,d as B,f as le,h as U}from"./chunk-H7IWJN7L.js";import{a as l}from"./chunk-FTQLQJQV.js";import{promises as ne}from"node:fs";import dt from"node:os";import mt from"node:path";import{createServer as gt}from"node:http";import{randomBytes as ft}from"node:crypto";var ot=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),it=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(ot).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ye,importOnly:o.boolean().optional()})]);function De(n,e){let t=null;async function r(i,a){let c=U(n).config,p=null,u=null,m=null;try{p=await ce(c),m=await V(n,{projectRoot:i,accountId:a}),i||(t=m)}catch(R){u=B(R,c)}let w=m??(i?null:t);return{path:c,text:p,rawRevision:ue(p),issue:u,effective:w,usingLastValid:!m&&!!w,applies:"next_turn",recoverableRevisions:await de(n),clientState:u?null:await Ie(n)}}l(r,"status");async function s(i){let a=it.parse(i);if(a.action==="validate")return{valid:!0,document:pe(a.text,U(n).config)};if(a.action==="client-state")return Re(n,a.owner,a.patch,a.importOnly);let c=l(async()=>{a.action==="patch"&&await he(n,a.expectedRevision,a.operations),a.action==="replace"&&await me(n,a.expectedRevision,a.text),a.action==="restore"&&await ge(n,a.revision,a.expectedRevision),a.action==="trust"&&await Se(n,a.root,a.accountId,a.trusted)},"mutation");return e?await e(c):await c(),r()}return l(s,"mutate"),{status:r,mutate:s,schema:fe}}l(De,"createConfigurationPayloads");import{Buffer as Be}from"node:buffer";var G={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id, idempotency-key","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},at=25*1024*1024,j=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{l(this,"HttpBodyError")}};function je(n,e,t={}){for(let[s,i]of Object.entries(G))e.setHeader(s,i);let r=Ve(n.headers.origin);return r?(e.setHeader("Vary",pt(e.getHeader("Vary"))),lt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}l(je,"applyCorsHeaders");function lt(n,e={}){if(n==="null")return!0;let t=Fe(n);return t?ct(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Fe(s):null).filter(s=>!!s)).has(t):!1}l(lt,"isAllowedCorsOrigin");function P(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...G}),n.end(JSON.stringify(t))}l(P,"sendJson");function Kt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...G}),n.end(t)}l(Kt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...G}),n.end(t)}l(Yt,"sendBinary");async function re(n,e={}){let t=e.maxBytes??at,r=Ve(n.headers["content-type"]),s=[],i=0;for await(let c of n){let p=Be.from(c);if(i+=p.byteLength,i>t)throw new j(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(p)}let a=Be.concat(s).toString("utf8").trim();if(!a)return{};if(!ut(r))throw new j(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new j(400,"invalid_json","Request body is not valid JSON.")}}l(re,"readJson");function Le(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}l(Le,"hasAuth");function Ve(n){return Array.isArray(n)?n[0]??null:n??null}l(Ve,"headerValue");function ut(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}l(ut,"isJsonContentType");function Fe(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}l(Fe,"normalizeOrigin");function ct(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}l(ct,"isLoopbackOrigin");function pt(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}l(pt,"appendVaryOrigin");function $e(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
3
3
  <style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
4
4
  <h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
5
5
  <p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as T,b as R,c as H}from"./chunk-GZ7M5XBP.js";import{b as L,c as q}from"./chunk-TRQQNFMO.js";import{i as M,j as O,m as k,n as C}from"./chunk-APB2STJK.js";import{l as S}from"./chunk-ACYFMLWG.js";import{m as N}from"./chunk-KGNCKIFP.js";import{b as c}from"./chunk-ES2ISFJC.js";import{a}from"./chunk-FTQLQJQV.js";var j=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(64),arguments:c.record(c.string(),c.unknown())}).strict(),W=c.object({text:c.string().max(262144),toolCalls:c.array(j).max(200)}).strict();async function D(e){if(!e.taskId||e.taskId.length>500)throw new Error("environment_task_identity_invalid");if(!Number.isInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>36e5)throw new Error("environment_attempt_timeout_invalid");S(e.instructions,262144);let m=e.taskId,f=e.instructions,d=structuredClone(e.input),J=e.policy,x=new AbortController,u=e.signal?AbortSignal.any([x.signal,e.signal]):x.signal,i=!1,_=setTimeout(()=>{i=!0,x.abort(new Error("environment_attempt_timeout"))},e.timeoutMs);_.unref?.();let t=null,h=null,o="environment_failure",p=null,v=null,b=!1,r=!1,n=[],y=0,E=a(s=>{if(y+=new TextEncoder().encode(JSON.stringify(s)).byteLength,y>4194304)throw o="budget_exhausted",new Error("environment_transcript_budget_exhausted");n.push(s)},"append"),P=new Set;try{t=await H({...e,input:d,signal:u}),E({role:"system",text:f}),E({role:"user",text:JSON.stringify({input:d,observation:t.observation})});for(let s=0;s<=t.definition.maxSteps;s++){u.throwIfAborted();let w;try{let l=await J({messages:structuredClone(n),tools:structuredClone(t.definition.tools),signal:u});S(l,1048576),w=structuredClone(W.parse(l));for(let g of w.toolCalls){if(P.has(g.id))throw new Error("environment_duplicate_tool_call_identity");P.add(g.id)}}catch(l){throw u.aborted||(o="policy_failure"),l}if(u.throwIfAborted(),E({role:"assistant",...w}),!w.toolCalls.length){p=w.text,await t.collect(),h=t.snapshot(),b=!0,o="completed";break}for(let l of w.toolCalls){let g;try{g=await t.step({name:l.name,arguments:l.arguments})}catch(I){if(!(I instanceof R))throw I;if(I.code==="step_budget_exhausted"){o="budget_exhausted";break}g={error:I.code}}E({role:"tool",callId:l.id,name:l.name,observation:g})}if(o==="budget_exhausted")break;s===t.definition.maxSteps&&(o="budget_exhausted")}h??=t.snapshot()}catch(s){u.aborted&&(o=i?"timed_out":"cancelled"),v=s instanceof Error?s.message:"environment_attempt_failed",h??=t?.snapshot()??null}finally{if(clearTimeout(_),t)try{await t.destroy(),r=!0}catch(s){o="environment_failure",v=s instanceof Error?s.message:"environment_cleanup_failed"}}let B={schemaVersion:"openpond.javascriptEnvironmentAttempt.v1",taskId:m,status:o,output:p,snapshot:h,collected:b,environmentCleanupComplete:r,messages:n,error:v};return{...B,contentHash:N(B)}}a(D,"runJavaScriptEnvironmentAttempt");import{spawn as z}from"node:child_process";async function A(e){if(e.signal?.throwIfAborted(),!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e4)throw new Error("sql_timeout_invalid");let m=O(e.request),{sqlExecutionProcessSource:f}=await import("./sql-execution-process-source-B4HQM6ZV.js");e.signal?.throwIfAborted();let{signal:d}=e,J=`globalThis.__openpondSqlInput = JSON.parse(${JSON.stringify(JSON.stringify(m))});
2
+ import{a as T,b as R,c as H}from"./chunk-YNH3NMPF.js";import{b as L,c as q}from"./chunk-TRQQNFMO.js";import{i as M,j as O,m as k,n as C}from"./chunk-APB2STJK.js";import{l as S}from"./chunk-ACYFMLWG.js";import{m as N}from"./chunk-KGNCKIFP.js";import{b as c}from"./chunk-ES2ISFJC.js";import{a}from"./chunk-FTQLQJQV.js";var j=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(64),arguments:c.record(c.string(),c.unknown())}).strict(),W=c.object({text:c.string().max(262144),toolCalls:c.array(j).max(200)}).strict();async function D(e){if(!e.taskId||e.taskId.length>500)throw new Error("environment_task_identity_invalid");if(!Number.isInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>36e5)throw new Error("environment_attempt_timeout_invalid");S(e.instructions,262144);let m=e.taskId,f=e.instructions,d=structuredClone(e.input),J=e.policy,x=new AbortController,u=e.signal?AbortSignal.any([x.signal,e.signal]):x.signal,i=!1,_=setTimeout(()=>{i=!0,x.abort(new Error("environment_attempt_timeout"))},e.timeoutMs);_.unref?.();let t=null,h=null,o="environment_failure",p=null,v=null,b=!1,r=!1,n=[],y=0,E=a(s=>{if(y+=new TextEncoder().encode(JSON.stringify(s)).byteLength,y>4194304)throw o="budget_exhausted",new Error("environment_transcript_budget_exhausted");n.push(s)},"append"),P=new Set;try{t=await H({...e,input:d,signal:u}),E({role:"system",text:f}),E({role:"user",text:JSON.stringify({input:d,observation:t.observation})});for(let s=0;s<=t.definition.maxSteps;s++){u.throwIfAborted();let w;try{let l=await J({messages:structuredClone(n),tools:structuredClone(t.definition.tools),signal:u});S(l,1048576),w=structuredClone(W.parse(l));for(let g of w.toolCalls){if(P.has(g.id))throw new Error("environment_duplicate_tool_call_identity");P.add(g.id)}}catch(l){throw u.aborted||(o="policy_failure"),l}if(u.throwIfAborted(),E({role:"assistant",...w}),!w.toolCalls.length){p=w.text,await t.collect(),h=t.snapshot(),b=!0,o="completed";break}for(let l of w.toolCalls){let g;try{g=await t.step({name:l.name,arguments:l.arguments})}catch(I){if(!(I instanceof R))throw I;if(I.code==="step_budget_exhausted"){o="budget_exhausted";break}g={error:I.code}}E({role:"tool",callId:l.id,name:l.name,observation:g})}if(o==="budget_exhausted")break;s===t.definition.maxSteps&&(o="budget_exhausted")}h??=t.snapshot()}catch(s){u.aborted&&(o=i?"timed_out":"cancelled"),v=s instanceof Error?s.message:"environment_attempt_failed",h??=t?.snapshot()??null}finally{if(clearTimeout(_),t)try{await t.destroy(),r=!0}catch(s){o="environment_failure",v=s instanceof Error?s.message:"environment_cleanup_failed"}}let B={schemaVersion:"openpond.javascriptEnvironmentAttempt.v1",taskId:m,status:o,output:p,snapshot:h,collected:b,environmentCleanupComplete:r,messages:n,error:v};return{...B,contentHash:N(B)}}a(D,"runJavaScriptEnvironmentAttempt");import{spawn as z}from"node:child_process";async function A(e){if(e.signal?.throwIfAborted(),!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e4)throw new Error("sql_timeout_invalid");let m=O(e.request),{sqlExecutionProcessSource:f}=await import("./sql-execution-process-source-B4HQM6ZV.js");e.signal?.throwIfAborted();let{signal:d}=e,J=`globalThis.__openpondSqlInput = JSON.parse(${JSON.stringify(JSON.stringify(m))});
3
3
  ${f}`;return new Promise((x,u)=>{let i=z("node",["--max-old-space-size=64","--input-type=module","-"],{stdio:["pipe","pipe","pipe"],env:{PATH:process.env.PATH},windowsHide:!0}),_,t="",h=0,o=0,p=a(r=>{_??=r,i.kill("SIGKILL")},"stop"),v=a(()=>p(d?.reason instanceof Error?d.reason:new Error("sql_cancelled")),"cancel"),b=setTimeout(()=>p(new Error("sql_timeout")),e.timeoutMs);d?.addEventListener("abort",v,{once:!0}),i.stdout.setEncoding("utf8"),i.stdout.on("data",r=>{h+=Buffer.byteLength(r),h>m.maxResultBytes+65536?p(new Error("sql_process_response_too_large")):t+=r}),i.stderr.on("data",r=>{o+=r.byteLength,o>65536&&p(new Error("sql_process_stderr_too_large"))}),i.once("error",r=>{_??=r}),i.stdin.on("error",r=>p(r)),i.once("close",r=>{if(clearTimeout(b),d?.removeEventListener("abort",v),_){u(_);return}try{if(r!==0)throw new Error("sql_process_exited_without_result");let n=JSON.parse(t);if(!n||typeof n!="object"||!("ok"in n)||n.ok!==!0||!("result"in n))throw new Error("sql_environment_failed");let y=M.parse(n.result);S(y,m.maxResultBytes),x(y)}catch(n){u(n)}}),i.stdin.end(J),d?.aborted&&v()})}a(A,"executeSqlInProcess");async function ie(e){let m=k.parse(e.operation);return T(e,{sql:A,candidate:q,controller:a(async f=>C.parse(await L({...f,exportName:m,maxResultBytes:1572864,deterministic:!0,errorPrefix:"environment"})),"controller")})}a(ie,"executeJavaScriptEnvironmentInWorker");async function le(e){let m=k.parse(e.operation);return T(e,{sql:A,candidate:q,controller:a(async f=>C.parse(await q({...f,exportName:m,maxResultBytes:1572864,deterministic:!0,errorPrefix:"environment"})),"controller")})}a(le,"executeJavaScriptEnvironmentInProcess");export{D as a,ie as b,le as c};