@ours.network/sdk 0.1.1 → 0.1.3

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 (63) hide show
  1. package/dist/api/contacts.js +1 -1
  2. package/dist/api/files.d.ts +4 -1
  3. package/dist/api/files.js +1 -1
  4. package/dist/api/identity.js +1 -1
  5. package/dist/api/messaging.js +1 -1
  6. package/dist/api/profile.d.ts +2 -1
  7. package/dist/api/profile.js +1 -1
  8. package/dist/api/types.d.ts +29 -0
  9. package/dist/book.js +1 -1
  10. package/dist/boot.js +1 -1
  11. package/dist/{chunk-7UUFYO6G.js → chunk-2W4CPM4Q.js} +1 -1
  12. package/dist/{chunk-NQQ4GSVI.js → chunk-2YUTV62M.js} +1 -1
  13. package/dist/chunk-37QQN5ND.js +2 -0
  14. package/dist/{chunk-RAGUBE4Y.js → chunk-3AK2WAWH.js} +1 -1
  15. package/dist/{chunk-NSPYN5TT.js → chunk-63OOHGB4.js} +1 -1
  16. package/dist/chunk-ACYEO2FM.js +2 -0
  17. package/dist/{chunk-T25JIPX5.js → chunk-AEWWZ67F.js} +1 -1
  18. package/dist/chunk-IDH22QWU.js +2 -0
  19. package/dist/{chunk-NMYSFQBL.js → chunk-JS5YFY7A.js} +1 -1
  20. package/dist/{chunk-X4RVJ5VL.js → chunk-KCMMTTYK.js} +1 -1
  21. package/dist/chunk-KKRG4E3A.js +2 -0
  22. package/dist/{chunk-VOYMK2OO.js → chunk-MRCIRJYN.js} +1 -1
  23. package/dist/{chunk-Q3UVLSCX.js → chunk-MYLXP6TV.js} +1 -1
  24. package/dist/{chunk-PCHN744Y.js → chunk-NLBDQY22.js} +1 -1
  25. package/dist/{chunk-TZBRSDND.js → chunk-Q3RMTP4Y.js} +1 -1
  26. package/dist/{chunk-HSVIKO4D.js → chunk-UPZVGDSI.js} +1 -1
  27. package/dist/{chunk-KZMPGVQM.js → chunk-VRL5GND4.js} +1 -1
  28. package/dist/{chunk-A3SXVUOC.js → chunk-X5RROKTP.js} +1 -1
  29. package/dist/{chunk-ZAXRB5MO.js → chunk-XST3WFRG.js} +1 -1
  30. package/dist/{chunk-VW2KWXSJ.js → chunk-Z63GGB2N.js} +1 -1
  31. package/dist/{chunk-HCIVLHKC.js → chunk-Z6KWRSU7.js} +1 -1
  32. package/dist/client/http.d.ts +2 -0
  33. package/dist/client/http.js +1 -1
  34. package/dist/client/select.d.ts +108 -0
  35. package/dist/client/select.js +2 -0
  36. package/dist/cluster/control.js +1 -1
  37. package/dist/cluster/manifest.js +1 -1
  38. package/dist/connector.js +1 -1
  39. package/dist/daemon.js +1 -1
  40. package/dist/gc.js +1 -1
  41. package/dist/http/api-routes.d.ts +2 -0
  42. package/dist/http/api-routes.js +1 -1
  43. package/dist/http/server.js +1 -1
  44. package/dist/identity/hierarchy.js +1 -1
  45. package/dist/identity/lease.js +1 -1
  46. package/dist/identity/lifecycle.js +1 -1
  47. package/dist/identity/model.js +1 -1
  48. package/dist/identity/provision.js +1 -1
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -1
  51. package/dist/messaging/send.js +1 -1
  52. package/dist/mufl/handlers.js +1 -1
  53. package/dist/mufl/tx.js +1 -1
  54. package/dist/mufl_code/8ED6356B41CC689C75DA3302AD7856058131661A6ABBAC961E71BA838D8C97A3.muflo +0 -0
  55. package/dist/notify.js +1 -1
  56. package/dist/render/adapt-to-json.js +1 -1
  57. package/dist/runtime/env.js +1 -1
  58. package/dist/state.js +1 -1
  59. package/dist/sweeps.js +1 -1
  60. package/package.json +2 -2
  61. package/dist/chunk-3DQSMLVZ.js +0 -2
  62. package/dist/chunk-AJQIWYXG.js +0 -2
  63. package/dist/chunk-UELGY557.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e,f,g,h,i,j}from"../chunk-KZMPGVQM.js";import"../chunk-7UUFYO6G.js";import"../chunk-UM73BGFH.js";import"../chunk-NMYSFQBL.js";import"../chunk-VOYMK2OO.js";import"../chunk-T25JIPX5.js";import"../chunk-HCIVLHKC.js";import"../chunk-NQQ4GSVI.js";import"../chunk-X4RVJ5VL.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-P55RJGZU.js";import"../chunk-RAGUBE4Y.js";import"../chunk-Q3UVLSCX.js";import"../chunk-HSVIKO4D.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";import"../chunk-UJGRFV4J.js";export{d as addContact,a as generateInvite,e as listContacts,b as listInvites,f as listLocalContactBook,h as removeContact,i as renameContact,j as respondToIntroduction,c as revokeInvite,g as setLocalBookPolicy};
2
+ import{a,b,c,d,e,f,g,h,i,j}from"../chunk-VRL5GND4.js";import"../chunk-2W4CPM4Q.js";import"../chunk-UM73BGFH.js";import"../chunk-JS5YFY7A.js";import"../chunk-MRCIRJYN.js";import"../chunk-AEWWZ67F.js";import"../chunk-Z6KWRSU7.js";import"../chunk-2YUTV62M.js";import"../chunk-KCMMTTYK.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-UJGRFV4J.js";import"../chunk-P55RJGZU.js";import"../chunk-3AK2WAWH.js";import"../chunk-MYLXP6TV.js";import"../chunk-UPZVGDSI.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";export{d as addContact,a as generateInvite,e as listContacts,b as listInvites,f as listLocalContactBook,h as removeContact,i as renameContact,j as respondToIntroduction,c as revokeInvite,g as setLocalBookPolicy};
@@ -1,5 +1,5 @@
1
1
  import { type IncomingFileMeta } from '../render/adapt-to-json.js';
2
- import type { GetFilesResult, SaveFileNotice, SessionContext } from './types.js';
2
+ import type { DeferResult, GetFilesResult, SaveFileNotice, SessionContext } from './types.js';
3
3
  export type * from './types.js';
4
4
  export declare function listIncomingFiles(ctx: SessionContext): Promise<IncomingFileMeta[]>;
5
5
  export declare function getFiles(ctx: SessionContext, a?: {
@@ -8,3 +8,6 @@ export declare function getFiles(ctx: SessionContext, a?: {
8
8
  export declare function saveFileFallbackNotice(ctx: SessionContext, a: {
9
9
  wire_id: string;
10
10
  }): SaveFileNotice;
11
+ export declare function deferFiles(ctx: SessionContext, a: {
12
+ file_ids: number[];
13
+ }): Promise<DeferResult>;
package/dist/api/files.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a,b,c}from"../chunk-AJQIWYXG.js";import"../chunk-7UUFYO6G.js";import"../chunk-UM73BGFH.js";import"../chunk-NMYSFQBL.js";import"../chunk-VOYMK2OO.js";import"../chunk-T25JIPX5.js";import"../chunk-HCIVLHKC.js";import"../chunk-NQQ4GSVI.js";import"../chunk-X4RVJ5VL.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-P55RJGZU.js";import"../chunk-RAGUBE4Y.js";import"../chunk-Q3UVLSCX.js";import"../chunk-HSVIKO4D.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";import"../chunk-UJGRFV4J.js";export{b as getFiles,a as listIncomingFiles,c as saveFileFallbackNotice};
2
+ import{a,b,c,d}from"../chunk-37QQN5ND.js";import"../chunk-2W4CPM4Q.js";import"../chunk-UM73BGFH.js";import"../chunk-JS5YFY7A.js";import"../chunk-MRCIRJYN.js";import"../chunk-AEWWZ67F.js";import"../chunk-Z6KWRSU7.js";import"../chunk-2YUTV62M.js";import"../chunk-KCMMTTYK.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-UJGRFV4J.js";import"../chunk-P55RJGZU.js";import"../chunk-3AK2WAWH.js";import"../chunk-MYLXP6TV.js";import"../chunk-UPZVGDSI.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";export{d as deferFiles,b as getFiles,a as listIncomingFiles,c as saveFileFallbackNotice};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-7UUFYO6G.js";import"../chunk-UM73BGFH.js";import"../chunk-NMYSFQBL.js";import"../chunk-VOYMK2OO.js";import"../chunk-T25JIPX5.js";import"../chunk-HCIVLHKC.js";import"../chunk-NQQ4GSVI.js";import"../chunk-X4RVJ5VL.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-P55RJGZU.js";import"../chunk-RAGUBE4Y.js";import"../chunk-Q3UVLSCX.js";import"../chunk-HSVIKO4D.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";import"../chunk-UJGRFV4J.js";export{g as chooseIdentity,d as closeTemporaryIdentityOp,b as createIdentity,e as createRootIdentity,c as createTemporaryIdentity,i as currentIdentity,f as defineLocalIdentityFile,h as listIdentities,k as releaseLease,j as removeIdentity,a as requireBound};
2
+ import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-2W4CPM4Q.js";import"../chunk-UM73BGFH.js";import"../chunk-JS5YFY7A.js";import"../chunk-MRCIRJYN.js";import"../chunk-AEWWZ67F.js";import"../chunk-Z6KWRSU7.js";import"../chunk-2YUTV62M.js";import"../chunk-KCMMTTYK.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-UJGRFV4J.js";import"../chunk-P55RJGZU.js";import"../chunk-3AK2WAWH.js";import"../chunk-MYLXP6TV.js";import"../chunk-UPZVGDSI.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";export{g as chooseIdentity,d as closeTemporaryIdentityOp,b as createIdentity,e as createRootIdentity,c as createTemporaryIdentity,i as currentIdentity,f as defineLocalIdentityFile,h as listIdentities,k as releaseLease,j as removeIdentity,a as requireBound};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e}from"../chunk-NSPYN5TT.js";import"../chunk-VW2KWXSJ.js";import"../chunk-7UUFYO6G.js";import"../chunk-UM73BGFH.js";import"../chunk-NMYSFQBL.js";import"../chunk-VOYMK2OO.js";import"../chunk-T25JIPX5.js";import"../chunk-HCIVLHKC.js";import"../chunk-NQQ4GSVI.js";import"../chunk-X4RVJ5VL.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-P55RJGZU.js";import"../chunk-RAGUBE4Y.js";import"../chunk-Q3UVLSCX.js";import"../chunk-HSVIKO4D.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";import"../chunk-UJGRFV4J.js";export{e as deferMessages,d as getMessages,c as listIncomingMessages,b as sendFile,a as sendMessage};
2
+ import{a,b,c,d,e}from"../chunk-63OOHGB4.js";import"../chunk-Z63GGB2N.js";import"../chunk-2W4CPM4Q.js";import"../chunk-UM73BGFH.js";import"../chunk-JS5YFY7A.js";import"../chunk-MRCIRJYN.js";import"../chunk-AEWWZ67F.js";import"../chunk-Z6KWRSU7.js";import"../chunk-2YUTV62M.js";import"../chunk-KCMMTTYK.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-UJGRFV4J.js";import"../chunk-P55RJGZU.js";import"../chunk-3AK2WAWH.js";import"../chunk-MYLXP6TV.js";import"../chunk-UPZVGDSI.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";export{e as deferMessages,d as getMessages,c as listIncomingMessages,b as sendFile,a as sendMessage};
@@ -1,4 +1,4 @@
1
- import type { AdvertiseMigrateResult, SessionContext, SetBioResult, SetPersonaResult } from './types.js';
1
+ import type { AdvertiseMigrateResult, ReadvertiseResult, SessionContext, SetBioResult, SetPersonaResult } from './types.js';
2
2
  export type * from './types.js';
3
3
  export declare function setBio(ctx: SessionContext, a: {
4
4
  bio: string;
@@ -7,3 +7,4 @@ export declare function advertiseMigrate(ctx: SessionContext): Promise<Advertise
7
7
  export declare function setPersona(ctx: SessionContext, a: {
8
8
  persona: string;
9
9
  }): Promise<SetPersonaResult>;
10
+ export declare function readvertiseOnUpgrade(ctx: SessionContext): Promise<ReadvertiseResult>;
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a,b,c}from"../chunk-3DQSMLVZ.js";import"../chunk-7UUFYO6G.js";import"../chunk-UM73BGFH.js";import"../chunk-NMYSFQBL.js";import"../chunk-VOYMK2OO.js";import"../chunk-T25JIPX5.js";import"../chunk-HCIVLHKC.js";import"../chunk-NQQ4GSVI.js";import"../chunk-X4RVJ5VL.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-P55RJGZU.js";import"../chunk-RAGUBE4Y.js";import"../chunk-Q3UVLSCX.js";import"../chunk-HSVIKO4D.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";import"../chunk-UJGRFV4J.js";export{b as advertiseMigrate,a as setBio,c as setPersona};
2
+ import{a,b,c,d}from"../chunk-KKRG4E3A.js";import"../chunk-2W4CPM4Q.js";import"../chunk-UM73BGFH.js";import"../chunk-JS5YFY7A.js";import"../chunk-MRCIRJYN.js";import"../chunk-AEWWZ67F.js";import"../chunk-Z6KWRSU7.js";import"../chunk-2YUTV62M.js";import"../chunk-KCMMTTYK.js";import"../chunk-DIRW7I4S.js";import"../chunk-YRPUM6JG.js";import"../chunk-LKFYUCN7.js";import"../chunk-UJGRFV4J.js";import"../chunk-P55RJGZU.js";import"../chunk-3AK2WAWH.js";import"../chunk-MYLXP6TV.js";import"../chunk-UPZVGDSI.js";import"../chunk-ZHH3PWEW.js";import"../chunk-IB2U7K6Y.js";export{b as advertiseMigrate,d as readvertiseOnUpgrade,a as setBio,c as setPersona};
@@ -161,8 +161,37 @@ export interface MessagesPayload {
161
161
  messages: MessageJson[];
162
162
  }
163
163
  export interface DeferResult {
164
+ /**
165
+ * HOW MANY WERE ACTUALLY RESTORED, which can be lower than the number of ids
166
+ * you passed, with nothing wrong.
167
+ *
168
+ * `defer_files` only restores files in `processed` or `ready_to_delete`
169
+ * (actor.mu:752); an already-unread file and an unknown id are both silently
170
+ * skipped and counted zero. `deferred < ids.length` is therefore a normal
171
+ * outcome of a retry, NOT an error — do not report it as one.
172
+ *
173
+ * NOTE THE IDENTIFIER SPLIT, because it reads as a typo and gets "fixed":
174
+ * `deferFiles` takes **file_id**s while `getFiles` selects by **wire_id**.
175
+ * They are different identifiers on the same file and the two surfaces
176
+ * disagree on purpose — the cell keys on `$file_ids -> ids: int[]`.
177
+ */
164
178
  deferred: string;
165
179
  }
180
+ export interface ReadvertiseResult {
181
+ /**
182
+ * HOW MANY CONTACTS THE FRESH AD WAS SENT TO — **not** how many upgraded.
183
+ *
184
+ * A still-v1 peer does not understand the transaction and ignores it; it is
185
+ * counted here identically to a v2 peer that ingests the AD and offers back.
186
+ * There is no signal in this number distinguishing the two, and there cannot
187
+ * be: the cell only sends. Rendering it as "N contacts upgraded" is wrong, and
188
+ * that is the phrasing someone will reach for.
189
+ *
190
+ * The packet's own Visualize() string, unparsed — the same rule as
191
+ * `DeferResult.deferred`.
192
+ */
193
+ readvertised: string;
194
+ }
166
195
  export interface GetFilesResult {
167
196
  files: ReceivedFileMeta[];
168
197
  text: string;
package/dist/book.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{K as a,L as b,M as c,N as d,O as e,P as f,Q as g,R as h,S as i,T as j}from"./chunk-NQQ4GSVI.js";import"./chunk-X4RVJ5VL.js";import"./chunk-DIRW7I4S.js";import"./chunk-YRPUM6JG.js";import"./chunk-LKFYUCN7.js";import"./chunk-P55RJGZU.js";import"./chunk-RAGUBE4Y.js";import"./chunk-Q3UVLSCX.js";import"./chunk-HSVIKO4D.js";import"./chunk-ZHH3PWEW.js";import"./chunk-IB2U7K6Y.js";import"./chunk-UJGRFV4J.js";export{a as bookDir,c as bookPath,f as exportAdBlob,g as exportSigningSecret,j as pinRegistrar,h as publishToBook,d as readBook,b as registrarKeyPath,i as unpublishFromBook,e as writeBook};
2
+ import{K as a,L as b,M as c,N as d,O as e,P as f,Q as g,R as h,S as i,T as j}from"./chunk-2YUTV62M.js";import"./chunk-KCMMTTYK.js";import"./chunk-DIRW7I4S.js";import"./chunk-YRPUM6JG.js";import"./chunk-LKFYUCN7.js";import"./chunk-UJGRFV4J.js";import"./chunk-P55RJGZU.js";import"./chunk-3AK2WAWH.js";import"./chunk-MYLXP6TV.js";import"./chunk-UPZVGDSI.js";import"./chunk-ZHH3PWEW.js";import"./chunk-IB2U7K6Y.js";export{a as bookDir,c as bookPath,f as exportAdBlob,g as exportSigningSecret,j as pinRegistrar,h as publishToBook,d as readBook,b as registrarKeyPath,i as unpublishFromBook,e as writeBook};
package/dist/boot.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-A3SXVUOC.js";import"./chunk-NMYSFQBL.js";import"./chunk-VOYMK2OO.js";import"./chunk-T25JIPX5.js";import"./chunk-HCIVLHKC.js";import"./chunk-NQQ4GSVI.js";import"./chunk-X4RVJ5VL.js";import"./chunk-DIRW7I4S.js";import"./chunk-YRPUM6JG.js";import"./chunk-LKFYUCN7.js";import"./chunk-P55RJGZU.js";import"./chunk-RAGUBE4Y.js";import"./chunk-Q3UVLSCX.js";import"./chunk-HSVIKO4D.js";import"./chunk-ZHH3PWEW.js";import"./chunk-IB2U7K6Y.js";import"./chunk-UJGRFV4J.js";export{a as bootWrapper};
2
+ import{a}from"./chunk-X5RROKTP.js";import"./chunk-JS5YFY7A.js";import"./chunk-MRCIRJYN.js";import"./chunk-AEWWZ67F.js";import"./chunk-Z6KWRSU7.js";import"./chunk-2YUTV62M.js";import"./chunk-KCMMTTYK.js";import"./chunk-DIRW7I4S.js";import"./chunk-YRPUM6JG.js";import"./chunk-LKFYUCN7.js";import"./chunk-UJGRFV4J.js";import"./chunk-P55RJGZU.js";import"./chunk-3AK2WAWH.js";import"./chunk-MYLXP6TV.js";import"./chunk-UPZVGDSI.js";import"./chunk-ZHH3PWEW.js";import"./chunk-IB2U7K6Y.js";export{a as bootWrapper};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{J as p,a as T,f as k,g as q,h as W,i as z,j as U,k as Y,l as G,m as J,n as K,o as Q,p as S,q as X,r as Z,s as ee,t as te,u as oe,v as ne,w as re,x as ie}from"./chunk-UM73BGFH.js";import{a as se,b as A}from"./chunk-NMYSFQBL.js";import{a as ae,c as de}from"./chunk-VOYMK2OO.js";import{b as f,e as b,f as N,g as E}from"./chunk-HCIVLHKC.js";import{F as M,J as j,x as L,y as _}from"./chunk-NQQ4GSVI.js";import{a as h,b as v,e as I,f as B,g as H,h as V,i as g}from"./chunk-RAGUBE4Y.js";import{c,o as w,p as $}from"./chunk-Q3UVLSCX.js";import{i as R,p as x}from"./chunk-HSVIKO4D.js";import{k as D,m as F}from"./chunk-IB2U7K6Y.js";import{randomBytes as ce}from"node:crypto";import{isAbsolute as me}from"node:path";function le(r){try{return b(r)}catch{return null}}function C(r){let o=le(r);return{name:r.name,cid:r.cid,bio:o?.bio??"",persona:o?.persona??"",roleId:o?.roleId??"",rootCid:o?.rootCid??"",rootName:o?.rootName??""}}async function P(r,o){o&&await M(async e=>{await j(r,"::a2a_messaging::set_my_bio",{bio:o},e)})}function pe(r){let o=V(r.sessionId());if(!("error"in o))return o.id;throw new T(o.code,o.error)}async function ke(r,o){let{name:e,bio:i,exposeLocal:d,localAutoAccept:s}=o,n=x(e);if(n)throw p("create_identity",n,"NAME_INVALID");if(c.has(e))throw k("create_identity",e);try{let t=await _(e,{exposeLocal:d,localAutoAccept:s});await P(t,i);let a,l=null,m=[],u=[],y=f?c.get(f):void 0;if(y)await N(y,t),a="role",l=y.name,ae()&&de(y);else{a="root";let O=await E(t);m=O.adopted,u=O.failed}return g(r.sessionId(),e),{info:C(t),hierarchy:a,underRoot:l,adopted:m,failed:u,exposedLocal:d,localAutoAccept:s}}catch(t){throw p("create_identity",String(t),"PROVISION_FAILED")}}async function Ae(r,o){let{bio:e,exposeLocal:i,localAutoAccept:d}=o,s=r.leaseToken(),n=r.clientPid();if(!s||!n)throw q();let t=o.name;if(t!==void 0){let l=x(t);if(l)throw p("create_temporary_identity",l,"NAME_INVALID");if(c.has(t)||L.has(t))throw k("create_temporary_identity",t)}else{for(let l=0;l<5&&t===void 0;l++){let m=`tmp-${ce(5).toString("hex")}`;!c.has(m)&&!L.has(m)&&(t=m)}if(t===void 0)throw W()}let a=t;try{let l=await _(a,{exposeLocal:i,localAutoAccept:d,temp:{tokenHash:w(s),pid:n}});return await P(l,e),g(r.sessionId(),a),{info:C(l),ownerPid:n,exposedLocal:i,localAutoAccept:d}}catch(l){throw p("create_temporary_identity",String(l),"PROVISION_FAILED")}}async function Ce(r,o){let e=r.leaseToken(),i;if(o.name!==void 0){if(i=c.get(o.name),!i)return{name:o.name,result:null}}else{let n=e?B(e):void 0;if(i=n?c.get(n.identity):void 0,!i)throw U()}if(!i.temp)throw Y(i.name);let d=i.temp.owner,s=e!==void 0&&d.tokenHash===w(e);if(!s&&!i.temp.closing&&I(d.pid))throw G(i.name,d.pid);try{let n=await A(i,s?"explicit close by owner":"stale reclaim via close_temporary_identity");if(n.deleteError){let t=n.attempted===0?"It had no contacts, so no remove-me notices were needed.":`Remove-me notices: ${n.notified}/${n.attempted} queued, ${n.failed} not sent (best effort \u2014 delivery and remote contact deletion are not guaranteed).`;throw J(i.name,n.deleteError,t)}return{name:i.name,result:n}}catch(n){throw n instanceof T?n:p("close_temporary_identity",String(n),"CLOSE_FAILED")}}async function ve(r,o){let{name:e,bio:i,exposeLocal:d,localAutoAccept:s,skipIfRootExists:n}=o,t=x(e);if(t)throw p("create_root_identity",t,"NAME_INVALID");let a=f;if(n&&a&&c.has(a))throw z(a);if(c.has(e))throw k("create_root_identity",e);try{let l=await _(e,{exposeLocal:d,localAutoAccept:s});await P(l,i);let m=f?c.get(f):void 0;if(m&&m.name!==e)return await N(m,l),g(r.sessionId(),e),{info:C(l),hierarchy:"role",underRoot:m.name,adopted:[],failed:[],exposedLocal:d,localAutoAccept:s};let{adopted:u,failed:y}=await E(l);return g(r.sessionId(),e),{info:C(l),hierarchy:"root",underRoot:null,adopted:u,failed:y,exposedLocal:d,localAutoAccept:s}}catch(l){throw p("create_root_identity",String(l),"PROVISION_FAILED")}}async function Le(r){if(!me(r.path))throw K(r.path);let o={name:r.name,force:r.force,exposeLocal:r.exposeLocal,localAutoAccept:r.localAutoAccept};try{return{written:F(r.path,o,r.overwrite),json:D(o)}}catch(e){throw p("define_local_identity_file",String(e),"WRITE_FAILED")}}async function Se(r,o){let{name:e,force:i}=o;if(!c.has(e))throw Q(e);let d=r.sessionId(),s=r.leaseToken();if(!s)throw S();let n=c.get(e);if(n.temp){if(n.temp.closing)throw X(e);let m=n.temp.owner;if(m.tokenHash!==w(s))throw I(m.pid)?Z(e,m.pid):ee(e,m.pid);let u=r.clientPid();if(u&&u!==m.pid){m.pid=u;try{$(n.dir,n.temp)}catch(y){R(`[${e}] temp marker refresh failed:`,String(y))}}}let t=h.get(e);if(t&&t.token!==s)if(!I(t.pid))R(`auto-reclaiming "${e}" from dead client pid ${t.pid}`),h.delete(e);else if(i)v.add(t.token),h.delete(e);else throw te(e);let a=[...h.values()].find(m=>m.token===s&&m.identity!==e)?.identity,l=a&&c.has(a)?a:null;return g(d,e),{name:e,cid:c.get(e).cid,switchedFrom:l}}async function Ne(r){if(c.size===0)return[];let o=r.leaseToken(),e=t=>{let a=h.get(t);return a?a.token===o?"mine":I(a.pid)?"other-live":null:null},i=t=>{if(!t.temp)return null;let a=t.temp.owner.pid;return t.temp.closing?{state:"closing",ownerPid:a}:o!==void 0&&t.temp.owner.tokenHash===w(o)?{state:"mine",ownerPid:a}:I(a)?{state:"other-live",ownerPid:a}:{state:"stale",ownerPid:a}},d=(t,a)=>({name:t.name,cid:t.cid,kind:a,temp:i(t),session:e(t.name)}),s=f?c.get(f):void 0,n=[];if(s){n.push({...d(s,"root"),temp:null});for(let t of c.values())t.name!==s.name&&b(t).roleId!==""&&n.push(d(t,"role"));for(let t of c.values())t.name===s.name||b(t).roleId!==""||n.push(d(t,"flat"))}else for(let t of c.values())n.push(d(t,"flat"));return n}async function Ee(r){let o=pe(r),e=le(o);return{name:o.name,cid:o.cid,bio:e?.bio??"",persona:e?.persona??"",roleId:e?.roleId??"",rootCid:e?.rootCid??"",rootName:e?.rootName??"",temporary:o.temp!==void 0,isRoot:o.name===f,described:e!==null}}async function Pe(r,o){let{name:e}=o,i=c.get(e);if(!i)throw p("remove_identity",`no identity named "${e}".`,"NO_SUCH_IDENTITY");if(i.temp){let s=r.leaseToken(),n=i.temp.owner;if((s===void 0||n.tokenHash!==w(s))&&!i.temp.closing&&I(n.pid))throw oe(e,n.pid);try{let t=await A(i,"remove_identity");if(t.deleteError){let a=t.attempted===0?"":` Remove-me notices: ${t.notified}/${t.attempted} queued, ${t.failed} not sent (best effort).`;throw ne(e,t.deleteError,a)}return{name:e,kind:"temporary",close:t}}catch(t){throw t instanceof T?t:p("remove_identity",String(t),"CLOSE_FAILED")}}if(e===f){let s=[...c.values()].filter(n=>n.name!==e&&b(n).rootCid===i.cid);if(s.length>0)throw re(e,s.map(n=>n.name))}let d=se(i);if(d)throw ie(e,d);return{name:e,kind:"permanent"}}async function Oe(r){let o=r.leaseToken();if(!o)throw S();let e=[];for(let[i,d]of[...h]){if(d.token!==o)continue;h.delete(i),e.push(i);let s=c.get(i);s?.temp&&s.temp.owner.tokenHash===w(o)&&!s.temp.closing&&A(s,"owning session released its lease").catch(n=>R(`[${i}] close on lease release failed:`,String(n)))}return v.delete(o),H(),R(`lease released by token \u2026${o.slice(-6)}`),{released:e}}export{pe as a,ke as b,Ae as c,Ce as d,ve as e,Le as f,Se as g,Ne as h,Ee as i,Pe as j,Oe as k};
2
+ import{J as p,a as T,f as k,g as q,h as W,i as z,j as U,k as Y,l as G,m as J,n as K,o as Q,p as S,q as X,r as Z,s as ee,t as te,u as oe,v as ne,w as re,x as ie}from"./chunk-UM73BGFH.js";import{a as se,b as A}from"./chunk-JS5YFY7A.js";import{a as ae,c as de}from"./chunk-MRCIRJYN.js";import{b as f,e as b,f as N,g as E}from"./chunk-Z6KWRSU7.js";import{F as M,J as j,x as L,y as _}from"./chunk-2YUTV62M.js";import{a as h,b as v,e as I,f as B,g as H,h as V,i as g}from"./chunk-3AK2WAWH.js";import{c,o as w,p as $}from"./chunk-MYLXP6TV.js";import{i as R,p as x}from"./chunk-UPZVGDSI.js";import{k as D,m as F}from"./chunk-IB2U7K6Y.js";import{randomBytes as ce}from"node:crypto";import{isAbsolute as me}from"node:path";function le(r){try{return b(r)}catch{return null}}function C(r){let o=le(r);return{name:r.name,cid:r.cid,bio:o?.bio??"",persona:o?.persona??"",roleId:o?.roleId??"",rootCid:o?.rootCid??"",rootName:o?.rootName??""}}async function P(r,o){o&&await M(async e=>{await j(r,"::a2a_messaging::set_my_bio",{bio:o},e)})}function pe(r){let o=V(r.sessionId());if(!("error"in o))return o.id;throw new T(o.code,o.error)}async function ke(r,o){let{name:e,bio:i,exposeLocal:d,localAutoAccept:s}=o,n=x(e);if(n)throw p("create_identity",n,"NAME_INVALID");if(c.has(e))throw k("create_identity",e);try{let t=await _(e,{exposeLocal:d,localAutoAccept:s});await P(t,i);let a,l=null,m=[],u=[],y=f?c.get(f):void 0;if(y)await N(y,t),a="role",l=y.name,ae()&&de(y);else{a="root";let O=await E(t);m=O.adopted,u=O.failed}return g(r.sessionId(),e),{info:C(t),hierarchy:a,underRoot:l,adopted:m,failed:u,exposedLocal:d,localAutoAccept:s}}catch(t){throw p("create_identity",String(t),"PROVISION_FAILED")}}async function Ae(r,o){let{bio:e,exposeLocal:i,localAutoAccept:d}=o,s=r.leaseToken(),n=r.clientPid();if(!s||!n)throw q();let t=o.name;if(t!==void 0){let l=x(t);if(l)throw p("create_temporary_identity",l,"NAME_INVALID");if(c.has(t)||L.has(t))throw k("create_temporary_identity",t)}else{for(let l=0;l<5&&t===void 0;l++){let m=`tmp-${ce(5).toString("hex")}`;!c.has(m)&&!L.has(m)&&(t=m)}if(t===void 0)throw W()}let a=t;try{let l=await _(a,{exposeLocal:i,localAutoAccept:d,temp:{tokenHash:w(s),pid:n}});return await P(l,e),g(r.sessionId(),a),{info:C(l),ownerPid:n,exposedLocal:i,localAutoAccept:d}}catch(l){throw p("create_temporary_identity",String(l),"PROVISION_FAILED")}}async function Ce(r,o){let e=r.leaseToken(),i;if(o.name!==void 0){if(i=c.get(o.name),!i)return{name:o.name,result:null}}else{let n=e?B(e):void 0;if(i=n?c.get(n.identity):void 0,!i)throw U()}if(!i.temp)throw Y(i.name);let d=i.temp.owner,s=e!==void 0&&d.tokenHash===w(e);if(!s&&!i.temp.closing&&I(d.pid))throw G(i.name,d.pid);try{let n=await A(i,s?"explicit close by owner":"stale reclaim via close_temporary_identity");if(n.deleteError){let t=n.attempted===0?"It had no contacts, so no remove-me notices were needed.":`Remove-me notices: ${n.notified}/${n.attempted} queued, ${n.failed} not sent (best effort \u2014 delivery and remote contact deletion are not guaranteed).`;throw J(i.name,n.deleteError,t)}return{name:i.name,result:n}}catch(n){throw n instanceof T?n:p("close_temporary_identity",String(n),"CLOSE_FAILED")}}async function ve(r,o){let{name:e,bio:i,exposeLocal:d,localAutoAccept:s,skipIfRootExists:n}=o,t=x(e);if(t)throw p("create_root_identity",t,"NAME_INVALID");let a=f;if(n&&a&&c.has(a))throw z(a);if(c.has(e))throw k("create_root_identity",e);try{let l=await _(e,{exposeLocal:d,localAutoAccept:s});await P(l,i);let m=f?c.get(f):void 0;if(m&&m.name!==e)return await N(m,l),g(r.sessionId(),e),{info:C(l),hierarchy:"role",underRoot:m.name,adopted:[],failed:[],exposedLocal:d,localAutoAccept:s};let{adopted:u,failed:y}=await E(l);return g(r.sessionId(),e),{info:C(l),hierarchy:"root",underRoot:null,adopted:u,failed:y,exposedLocal:d,localAutoAccept:s}}catch(l){throw p("create_root_identity",String(l),"PROVISION_FAILED")}}async function Le(r){if(!me(r.path))throw K(r.path);let o={name:r.name,force:r.force,exposeLocal:r.exposeLocal,localAutoAccept:r.localAutoAccept};try{return{written:F(r.path,o,r.overwrite),json:D(o)}}catch(e){throw p("define_local_identity_file",String(e),"WRITE_FAILED")}}async function Se(r,o){let{name:e,force:i}=o;if(!c.has(e))throw Q(e);let d=r.sessionId(),s=r.leaseToken();if(!s)throw S();let n=c.get(e);if(n.temp){if(n.temp.closing)throw X(e);let m=n.temp.owner;if(m.tokenHash!==w(s))throw I(m.pid)?Z(e,m.pid):ee(e,m.pid);let u=r.clientPid();if(u&&u!==m.pid){m.pid=u;try{$(n.dir,n.temp)}catch(y){R(`[${e}] temp marker refresh failed:`,String(y))}}}let t=h.get(e);if(t&&t.token!==s)if(!I(t.pid))R(`auto-reclaiming "${e}" from dead client pid ${t.pid}`),h.delete(e);else if(i)v.add(t.token),h.delete(e);else throw te(e);let a=[...h.values()].find(m=>m.token===s&&m.identity!==e)?.identity,l=a&&c.has(a)?a:null;return g(d,e),{name:e,cid:c.get(e).cid,switchedFrom:l}}async function Ne(r){if(c.size===0)return[];let o=r.leaseToken(),e=t=>{let a=h.get(t);return a?a.token===o?"mine":I(a.pid)?"other-live":null:null},i=t=>{if(!t.temp)return null;let a=t.temp.owner.pid;return t.temp.closing?{state:"closing",ownerPid:a}:o!==void 0&&t.temp.owner.tokenHash===w(o)?{state:"mine",ownerPid:a}:I(a)?{state:"other-live",ownerPid:a}:{state:"stale",ownerPid:a}},d=(t,a)=>({name:t.name,cid:t.cid,kind:a,temp:i(t),session:e(t.name)}),s=f?c.get(f):void 0,n=[];if(s){n.push({...d(s,"root"),temp:null});for(let t of c.values())t.name!==s.name&&b(t).roleId!==""&&n.push(d(t,"role"));for(let t of c.values())t.name===s.name||b(t).roleId!==""||n.push(d(t,"flat"))}else for(let t of c.values())n.push(d(t,"flat"));return n}async function Ee(r){let o=pe(r),e=le(o);return{name:o.name,cid:o.cid,bio:e?.bio??"",persona:e?.persona??"",roleId:e?.roleId??"",rootCid:e?.rootCid??"",rootName:e?.rootName??"",temporary:o.temp!==void 0,isRoot:o.name===f,described:e!==null}}async function Pe(r,o){let{name:e}=o,i=c.get(e);if(!i)throw p("remove_identity",`no identity named "${e}".`,"NO_SUCH_IDENTITY");if(i.temp){let s=r.leaseToken(),n=i.temp.owner;if((s===void 0||n.tokenHash!==w(s))&&!i.temp.closing&&I(n.pid))throw oe(e,n.pid);try{let t=await A(i,"remove_identity");if(t.deleteError){let a=t.attempted===0?"":` Remove-me notices: ${t.notified}/${t.attempted} queued, ${t.failed} not sent (best effort).`;throw ne(e,t.deleteError,a)}return{name:e,kind:"temporary",close:t}}catch(t){throw t instanceof T?t:p("remove_identity",String(t),"CLOSE_FAILED")}}if(e===f){let s=[...c.values()].filter(n=>n.name!==e&&b(n).rootCid===i.cid);if(s.length>0)throw re(e,s.map(n=>n.name))}let d=se(i);if(d)throw ie(e,d);return{name:e,kind:"permanent"}}async function Oe(r){let o=r.leaseToken();if(!o)throw S();let e=[];for(let[i,d]of[...h]){if(d.token!==o)continue;h.delete(i),e.push(i);let s=c.get(i);s?.temp&&s.temp.owner.tokenHash===w(o)&&!s.temp.closing&&A(s,"owning session released its lease").catch(n=>R(`[${i}] close on lease release failed:`,String(n)))}return v.delete(o),H(),R(`lease released by token \u2026${o.slice(-6)}`),{released:e}}export{pe as a,ke as b,Ae as c,Ce as d,ve as e,Le as f,Se as g,Ne as h,Ee as i,Pe as j,Oe as k};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{c as pe}from"./chunk-X4RVJ5VL.js";import{b as M}from"./chunk-YRPUM6JG.js";import{a as de}from"./chunk-LKFYUCN7.js";import{d as ce}from"./chunk-RAGUBE4Y.js";import{a as j,c as N,d as b,e as W,f as ne,g as oe,h as J,i as O,j as k,k as L,l as B,p as se,w as ae}from"./chunk-Q3UVLSCX.js";import{c as T,i as l,o as F,p as re}from"./chunk-HSVIKO4D.js";import{b as ue,e as le,f as fe}from"./chunk-UJGRFV4J.js";import{join as be}from"node:path";import*as _ from"node:fs";import{AdaptObjectLifetime as Re}from"@adapt-toolkit/sdk/common";import{object_to_adapt_value as $e}from"@adapt-toolkit/sdk/wrapper";import*as m from"node:fs";import{randomBytes as Ve}from"node:crypto";import*as $ from"node:fs";import{randomBytes as Ie}from"node:crypto";import{PacketWrapperConfigurator as Te}from"@adapt-toolkit/sdk/wrappers";import{AdaptObjectLifetime as Ne}from"@adapt-toolkit/sdk/common";function He(e){let t=[],s=e.Reduce("degraded");if(s.IsNil())return t;for(let r=0;;r++){let a=s.Reduce(r);if(a.IsNil())break;t.push({cid:a.Reduce("container_id").Visualize(),name:a.Reduce("name").Visualize(),attempts:Number(a.Reduce("attempts").Visualize()),queued:Number(a.Reduce("queued").Visualize())})}return t}function ke(e){let t=[],s=e.Reduce("queues");if(s.IsNil())return t;for(let r=0;;r++){let a=s.Reduce(r);if(a.IsNil())break;t.push({cid:a.Reduce("container_id").Visualize(),queued:Number(a.Reduce("queued").Visualize()),degraded:a.Reduce("degraded").GetBoolean()})}return t}async function K(e,t){try{let s=await w(async r=>{let a=await h(e,"::a2a_messaging::flush_deferred",{contact:t},r);return Number(a.Reduce("flushed").Visualize())});s>0&&l(`[${e.name}] flushed ${s} deferred message(s) to ${t.slice(0,12)}\u2026`)}catch(s){l(`[${e.name}] deferred flush to ${t.slice(0,12)}\u2026 failed:`,String(s))}}async function me(e){try{let t=await w(async r=>{let a=await h(e,"::a2a_messaging::restore_degraded_contacts",{},r);return Number(a.Reduce("requested").Visualize())});t>0&&l(`[${e.name}] contact restore requested for ${t} degraded contact(s)`);let s=S(r=>ke(R(e,"::a2a_messaging::list_deferred_queues",r)));for(let r of s)r.degraded||await K(e,r.cid)}catch(t){l(`[${e.name}] contact-restore sweep failed:`,String(t))}}async function xe(e){try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::reconcile_advertise",{},s),a=d=>r.Reduce(d).IsNil()?0:Number(r.Reduce(d).Visualize());return{changed:/true/i.test(r.Reduce("changed").Visualize()),capabilityAdvertised:a("capability_advertised"),legacyReadvertised:a("legacy_readvertised")}});(t.capabilityAdvertised>0||t.legacyReadvertised>0)&&l(`[${e.name}] capability reconcile: changed=${t.changed} advertised=${t.capabilityAdvertised} legacy_migration_bootstrap=${t.legacyReadvertised}`)}catch(t){l(`[${e.name}] capability reconcile sweep failed:`,String(t))}}var G=new Set;function H(e){if(!G.has(e.name)){G.add(e.name);for(let t of[2e3,15e3])setTimeout(()=>{t===15e3&&G.delete(e.name);let s=N.get(e.name);s&&xe(s)},t)}}async function qe(e){try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::readvertise_e2e_recovery",{},s);return Number(r.Reduce("readvertised").Visualize())});t>0&&l(`[${e.name}] re-advertised fresh AD to ${t} e2e contact(s) (session recovery)`)}catch(t){l(`[${e.name}] e2e recovery re-advertise failed:`,String(t))}try{await w(async t=>{await h(e,"::a2a_messaging::sweep_e2e_migrations",{},t)})}catch(t){l(`[${e.name}] e2e migration sweep failed:`,String(t))}try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::redrive_unacked_sweep",{},s),a=d=>r.Reduce(d).IsNil()?0:Number(r.Reduce(d).Visualize());return{redriven:a("redriven_contacts"),purged:a("purged_contacts"),deferred:a("deferred_contacts")}});(t.redriven>0||t.purged>0||t.deferred>0)&&l(`[${e.name}] unacked sweep: redriven=${t.redriven} ttl_purged=${t.purged} deferred=${t.deferred} contact(s)`)}catch(t){l(`[${e.name}] unacked redrive sweep failed:`,String(t))}}function ge(e,t){e.pw.on_return_data=s=>{let r=new Ne;s.Attach(r);try{let a=s.Reduce("kind").Visualize();if(a==="save_state"){z(e);return}if(a==="notify_agent"){let i=s.Reduce("payload"),f=i.Reduce("event").Visualize();if(f==="message_received"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("msg_id").Visualize(),c=i.Reduce("date").Visualize();g(e,{event:"message_received",from:o,msg_id:n,date:c}),P(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] new message from ${o} (#${n})`))}else if(f==="file_received"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("sender_id").Visualize(),c=i.Reduce("file_id").Visualize(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("filename").Visualize(),y=i.Reduce("mime").Visualize(),v=i.Reduce("bytes").Visualize(),I=i.Reduce("date").Visualize();g(e,{event:"file_received",from:o,sender_id:n,file_id:c,wire_id:u,filename:p,mime:y,bytes:v,date:I}),P(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] new file ${p} (${v} B) from ${o} (sender_id ${n}, file_id ${c}, wire_id ${u})`))}else if(f==="contact_accepted"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] contact "${o}" (${n}) accepted your invite.`))}else if(f==="local_contact_added"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] local contact "${o}" (${n}) connected via the contact book.`))}else if(f==="contact_name_collision"){let o=i.Reduce("message").Visualize(),n=i.Reduce("desired").Visualize(),c=i.Reduce("assigned").Visualize(),u=i.Reduce("existing_container_id").Visualize(),p=i.Reduce("container_id").Visualize();g(e,{event:"contact_name_collision",desired:n,assigned:c,existing_container_id:u,container_id:p}),l(`[${e.name}] CONTACT NAME COLLISION \u2014 ${o}`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] \u26A0 ${o}`))}else if(f==="sibling_contact_added"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"sibling_contact_added",from:o}),H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] sibling "${o}" (${n}) connected (intra-root auto-accept).`))}else if(f==="local_contact_request"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"local_contact_request",from:o}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] pending local introduction from "${o}" (${n}) \u2014 approve or reject with respond_to_introduction.`))}else if(f==="pending_message"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("queued").Visualize();g(e,{event:"pending_message",from:o,queued:n}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] "${o}" queued a message awaiting introduction approval (${n} queued).`))}else if(f==="e2e_restore_rejected")g(e,{event:"e2e_restore_rejected"}),l(`[${e.name}] E2E RESTORE REJECTED \u2014 corrupt session blob failed pickle_key validation; reset to empty e2e state, self-heal fallback will re-establish`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] persisted e2e sessions were corrupt \u2014 rejected cleanly, sessions re-establishing`));else if(f==="contact_restored"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"contact_restored",from:o}),l(`[${e.name}] contact "${o}" restored (re-keyed)`),process.nextTick(()=>void K(e,String(n)))}else if(f==="migration_active"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("role").Visualize(),c=V(i,"epoch"),u=V(i,"session_id");g(e,{event:"migration_active",cid:String(o),role:String(n),...c?{epoch:c}:{},...u?{session_id:u}:{}}),l(`[migration] active cid=${o} role=${n}${c?` epoch=${c}`:""}${u?` session_id=${u}`:""}`)}else if(f==="e2e_app_send"){let o=i.Reduce("cid").Visualize(),n=V(i,"session_id"),c=i.Reduce("olm_type").Visualize(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("retained").IsNil()?void 0:i.Reduce("retained").GetBoolean(),y=[],v=i.Reduce("evicted");if(!v.IsNil())for(let I=0;;I++){let ie=v.Reduce(I);if(ie.IsNil())break;y.push(String(ie.Visualize()))}g(e,{event:"e2e_app_send",cid:String(o),session_id:n,olm_type:String(c),wire_id:String(u),...p===!1?{retained:!1}:{},...y.length?{evicted:y}:{}}),l(`[${e.name}] [e2e-app] send cid=${o} session_id=${n} olm_type=${c} wire_id=${u}${p===!1?" retained=false":""}${y.length?` evicted=${y.join(",")}`:""}`),y.length&&process.nextTick(()=>t.onNotify(e.name,`[${e.name}] redrive window overflow: ${y.length} older unacked send(s) lost their auto-resend guarantee (${y.join(", ")})`))}else if(f==="dedup_degraded"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("dropped_wire_id").Visualize();g(e,{event:"dedup_degraded",cid:String(o),dropped_wire_id:String(n)}),l(`[${e.name}] [e2e-app] DEDUP DEGRADED cid=${o} dropped_wire_id=${n} (storage ceiling \u2014 a late redrive of that id could re-deposit)`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] dedup window overflowed for ${String(o).slice(0,12)}\u2026 \u2014 one oldest entry dropped (guarantee loss surfaced)`))}else if(f==="e2e_delivery_expired"){let o=i.Reduce("cid").Visualize(),n=[],c=i.Reduce("wire_ids");if(!c.IsNil())for(let u=0;;u++){let p=c.Reduce(u);if(p.IsNil())break;n.push(String(p.Visualize()))}g(e,{event:"e2e_delivery_expired",cid:String(o),wire_ids:n}),l(`[${e.name}] [e2e-app] delivery EXPIRED (2-day TTL, receipt never arrived) cid=${o} wire_ids=${n.join(",")}`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] ${n.length} message(s)/file(s) to ${String(o).slice(0,12)}\u2026 expired undelivered (no receipt within 2 days)`))}else if(f==="e2e_app_recv"){let o=i.Reduce("cid").Visualize(),n=V(i,"session_id"),c=i.Reduce("ok").GetBoolean(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("code").IsNil()?void 0:String(i.Reduce("code").Visualize()),y=!i.Reduce("duplicate").IsNil(),v=!i.Reduce("file").IsNil();g(e,{event:"e2e_app_recv",cid:String(o),session_id:n,ok:c,wire_id:String(u),...p?{code:p}:{},...y?{duplicate:!0}:{},...v?{file:!0}:{}}),l(`[${e.name}] [e2e-app] recv cid=${o} session_id=${n} ok=${c} wire_id=${u}${p?` code=${p}`:""}${y?" duplicate=true":""}${v?" file=true":""}`)}else if(f==="e2e_rekey"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("role").Visualize(),c=V(i,"session_id"),u=i.Reduce("attempts").IsNil()?void 0:String(i.Reduce("attempts").Visualize()),p=i.Reduce("peer_supports").IsNil()?void 0:String(i.Reduce("peer_supports").Visualize()),y=i.Reduce("rejected").IsNil()?void 0:String(i.Reduce("rejected").Visualize());g(e,{event:"e2e_rekey",cid:String(o),role:String(n),...c?{session_id:c}:{},...u?{attempts:u}:{},...p?{peer_supports:p}:{},...y?{rejected:y}:{}}),l(`[${e.name}] [e2e-rekey] cid=${o} role=${n}${c?` session_id=${c}`:""}${u?` attempts=${u}`:""}${p?` peer_supports=${p}`:""}${y?` rejected=${y}`:""}`)}else if(f==="migration_deferred_flush"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("wire_id").Visualize();g(e,{event:"migration_deferred_flush",cid:String(o),wire_id:String(n)}),l(`[migration] flush-notify cid=${o} wire_id=${n} (deferred\u2192e2e; core delivers)`)}else if(f==="migration_stalled"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("phase").Visualize(),c=i.Reduce("attempts").Visualize();g(e,{event:"migration_stalled",cid:String(o),phase:String(n),attempts:String(c)}),l(`[migration] stalled-notify cid=${o} phase=${n} attempts=${c} (core re-drives via sweep)`)}else if(f==="downgrade_refused"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("wire_id"),c=n.IsNil()?"":String(n.Visualize());g(e,{event:"downgrade_refused",cid:String(o),...c?{wire_id:c}:{}}),l(`[e2e-route] downgrade-dropped cid=${o}${c?` wire_id=${c}`:""} (legacy plaintext from a migrated peer \u2014 dropped by core)`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] a message from a migrated contact was rejected as an unsafe downgrade (dropped).`))}else if(f==="contact_removed"){let o=String(i.Reduce("cid").Visualize()),n=ce.has(e.name);g(e,{event:"contact_removed",cid:o,by:n?"local":"peer"}),n||(l(`[${e.name}] contact ${o} removed you (authenticated peer removal notice) \u2014 dropped from contacts`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] contact ${o.slice(0,12)}\u2026 removed you as a contact (the removal was applied locally too).`)))}else if(f==="monitoring_disabled"){let o=String(i.Reduce("cid").Visualize()),n=i.Reduce("cause"),c=n.IsNil()?"":String(n.Visualize());g(e,{event:"monitoring_disabled",cid:o,...c?{cause:c}:{}}),l(`[${e.name}] monitoring disabled (cid=${o}${c?` cause=${c}`:""})`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] the monitoring/control-plane binding was disabled${c==="control_plane_removed_contact"?" \u2014 the control plane removed you as a contact":""}.`))}else(f==="control_request"||f==="host_provision_child"||f==="host_destroy_child"||f==="host_mint_child_invite"||f==="host_set_child_monitoring")&&l(`[${e.name}] ${f}: the daemon-side control plane is removed \u2014 ignoring`);return}let d=e.pending.shift();if(!d)return;clearTimeout(d.timer),d.resolve(s.Reduce("payload").Detach())}finally{r.Finalize()}},e.pw.on_transaction_failure=s=>{let r=e.pending.shift();r?(clearTimeout(r.timer),r.reject(new Error(s))):(l(`[${e.name}] inbound transaction rejected:`,s),g(e,{event:"inbound_error",message:s}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] inbound transaction rejected: ${s}`)))}}import{join as X}from"node:path";import*as x from"node:fs";var E=()=>X(T,F),Q=()=>X(E(),"registrar.key"),Y=()=>X(E(),"book.json");function ye(){try{let e=JSON.parse(x.readFileSync(Y(),"utf8"));return e&&typeof e.entries=="object"?e.entries:{}}catch{return{}}}function _e(e){x.mkdirSync(E(),{recursive:!0});let t=`${Y()}.tmp`;x.writeFileSync(t,JSON.stringify({v:1,entries:e},null,2),{mode:384}),x.renameSync(t,Y())}function Z(e){return S(t=>Buffer.from(R(e,"::actor::export_address_document",t).GetBinary()))}function q(e){return S(t=>Buffer.from(R(e,"::actor::export_signing_secret",t).Serialize()).toString("hex"))}async function we(e){if(!b)throw new Error("registrar is not available");let t=Z(e),s=await w(async a=>{let d=await h(b,"::actor::sign_book_entry",{name:e.name,ad:b.pw.packet.NewBinaryFromBuffer(t).Attach(a)},a);return Buffer.from(d.Reduce("sig").GetBinary()).toString("base64url")}),r=ye();r[e.name]={v:1,name:e.name,container_id:e.cid,address_document:t.toString("base64url"),published_at:new Date().toISOString(),registrar_sig:s},_e(r),l(`[${e.name}] published to the local contact book`)}function it(e){let t=ye(),s=Object.entries(t).find(([,r])=>r.container_id===e.cid);s&&(delete t[s[0]],_e(t),l(`[${e.name}] removed from the local contact book (entry "${s[0]}")`))}async function he(e){if(!W)throw new Error("registrar is not available");await w(async t=>{await h(e,"::actor::pin_registrar",{registrar_ad:e.pw.packet.NewBinaryFromBuffer(W).Attach(t)},t)})}function C(e,t,s,r=!0,a,d=!1){let i=new Te;i.deferred_exposure=d;let f=["--unit_hash",M.hash,"--seed_phrase",t,"--unit_dir_path",M.dir];return a&&f.push("--init_trn_argument",JSON.stringify(a)),i.process_arguments(f),new Promise((o,n)=>{let c=setTimeout(()=>n(new Error(`packet creation for "${e}" timed out`)),3e4);j.packet_manager.create_packet(i,u=>{clearTimeout(c);let p={name:e,cid:S(y=>u.packet.GetContainerID().Attach(y).Visualize()),pw:u,dir:s,pending:[],lock:Promise.resolve()};ge(p,ve),r&&N.set(e,p),l(`[${e}] packet created \u2014 container id ${p.cid}`),o(p)},M.contents)})}var A=new Set(ae());A.size>0&&l(`reserved ${A.size} persisted identity name(s) at module load: ${[...A].join(", ")}`);async function gt(e,t={exposeLocal:!0,localAutoAccept:!0}){if(A.has(e)||N.has(e))throw new Error(`identity name "${e}" is reserved \u2014 a persisted identity with this name is restoring, present, or being provisioned; refusing to provision over it`);A.add(e);try{let s=J(e);$.mkdirSync(s,{recursive:!0,mode:448});let r;t.temp&&(r={owner:{tokenHash:t.temp.tokenHash,pid:t.temp.pid},createdAt:Date.now()},se(s,r));let a=Ie(24).toString("hex"),d=await C(e,a,s);return r&&(d.temp=r),$.writeFileSync(O(s),q(d),{mode:384}),await w(async i=>{await h(d,"::a2a_messaging::set_my_name",{name:e},i)}),await he(d),t.localAutoAccept||await w(async i=>{await h(d,"::actor::set_local_policy",{auto_accept:!1},i)}),t.exposeLocal&&await we(d),z(d),d}catch(s){throw A.delete(e),s}}async function yt(e){let t=J(e),s=$.readFileSync(O(t),"utf8").trim(),r=await C(e,"",t,!1,s,!0);l(`[${e}] created QUARANTINED (no routing/broker registration, not client-bindable) \u2014 importing state before exposure`);let a=Number(process.env.OURS_TEST_RESTORE_HOLD_MS||"")||0;a>0&&(l(`[${e}] TEST HOLD: keeping restore open ${a}ms (OURS_TEST_RESTORE_HOLD_MS)`),await new Promise(o=>setTimeout(o,a)));let d=o=>/timed out waiting for the transaction result/.test(String(o)),i=(o,n,c)=>{l(`[${e}] ${o} ${n} \u2014 identity left UNEXPOSED and UNTRACKED (fail-closed)`);try{g(r,{event:"restore_fail_closed",step:o,error:String(c).slice(0,300)})}catch{}N.delete(e);try{j.remove_packet(r.cid)}catch(u){l(`[${e}] quarantined-packet teardown failed:`,String(u))}throw new Error(`identity "${e}": ${o} failed during restore (${n}) \u2014 left unexposed (fail-closed)`)},f=(o,n)=>i(o,"outcome UNKNOWN (timeout): the transaction may still execute and exposure would race it",n);if(Se(t)){let o=!1;try{if(process.env.OURS_TEST_FORCE_IMPORT_TIMEOUT==="1")throw new Error("timed out waiting for the transaction result (forced by OURS_TEST_FORCE_IMPORT_TIMEOUT)");let n=$.readFileSync(k(t));await w(async c=>{let u=r.pw.packet.ParseValue(new Uint8Array(n)).Attach(c),p=Number(process.env.OURS_IMPORT_TIMEOUT_MS||"")||void 0;await h(r,"::actor::import_state",u,c,p)}),o=!0,l(`[${e}] state import completed (positively observed)`)}catch(n){d(n)&&f("import_state",n),l(`[${e}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`,String(n)),g(r,{event:"state_import_failed",error:String(n).slice(0,300)});try{let c=`${k(t)}.failed-${Date.now()}`;$.renameSync(k(t),c),$.chmodSync(c,384),l(`[${e}] unreadable state blob preserved as state_data.bin.failed-*`)}catch{}}if(o){try{let u=await w(async p=>{let y=await h(r,"::a2a_messaging::commit_e2e_restore",{},p),v=y.Reduce("status").Visualize(),I=y.Reduce("sessions").IsNil()?"0":y.Reduce("sessions").Visualize();return{status:String(v),sessions:String(I)}});l(`[${e}] e2e restore commit: status=${u.status} sessions=${u.sessions}`)}catch(u){d(u)&&f("commit_e2e_restore",u),l(`[${e}] E2E RESTORE REJECTED \u2014 staged session blob failed pickle_key validation; discarding it, fresh account + self-heal fallback take over: ${String(u).slice(0,260)}`),g(r,{event:"e2e_restore_rejected",origin:"restore",error:String(u).slice(0,300)});try{await w(async p=>{await h(r,"::a2a_messaging::reject_e2e_restore",{},p)})}catch(p){d(p)&&f("reject_e2e_restore",p),l(`[${e}] reject_e2e_restore failed (staging is transient; continuing):`,String(p))}}try{r.pw.refresh_identity_proof_document(),l(`[${e}] transport IPD refreshed from post-import state`)}catch(u){i("ipd_refresh","FAILED (IPD would advertise a stale bundle)",u)}let n=!1,c="";try{if(process.env.OURS_TEST_FORCE_IPD_INCOHERENT==="1")throw new Error("forced incoherent (OURS_TEST_FORCE_IPD_INCOHERENT)");let u=S(v=>String(R(r,"::a2a_messaging::e2e_self_fp",v).Reduce("ik").Visualize())),p=r.pw.identity_proof_document.Visualize(),y=u.replace(/^0x/i,"");n=y.length>=32&&p.toLowerCase().includes(y.toLowerCase()),c=u.slice(0,18),g(r,{event:"ipd_coherence",ik:u,coherent:n})}catch(u){i("ipd_coherence","probe FAILED (coherence unprovable)",u)}l(`[${e}] IPD/e2e coherence: account_ik=${c}\u2026 ipd_advertises_it=${n}`),n||i("ipd_coherence","IPD does NOT advertise the live account ik",new Error("incoherent transport IPD"))}}return j.expose_packet(r.cid),N.set(e,r),l(`[${e}] EXPOSED (routing + broker registration) \u2014 import phase complete`),await me(r),P(r),r}async function kt(){m.mkdirSync(E(),{recursive:!0});let e;try{e=m.readFileSync(Q(),"utf8").trim()}catch{}let t=Ve(24).toString("hex");ne(await C(F,t,E(),!1,e)),e||m.writeFileSync(Q(),q(b),{mode:384}),oe(Z(b)),l(`contact-book registrar ready (${b.cid})`)}function Se(e){try{return m.existsSync(k(e))&&m.statSync(k(e)).size>0}catch{return!1}}function ze(e){let t=S(d=>Buffer.from(R(e,"::actor::export_state",d).Serialize()));m.mkdirSync(e.dir,{recursive:!0,mode:448});let s=k(e.dir),r=`${s}.tmp`,a;try{a=m.openSync(r,"w",384),m.fchmodSync(a,384),m.writeFileSync(a,t),m.fsyncSync(a),m.closeSync(a),a=void 0,m.renameSync(r,s),m.chmodSync(s,384);try{m.chmodSync(O(e.dir),384)}catch{}let d=m.openSync(e.dir,"r");try{m.fsyncSync(d)}finally{m.closeSync(d)}}catch(d){if(a!==void 0)try{m.closeSync(a)}catch{}try{m.rmSync(r,{force:!0})}catch{}throw d}}function z(e){try{ze(e),e.persistFailed&&(e.persistFailed=!1,l(`[${e.name}] persist recovered \u2014 quarantine lifted`),g(e,{event:"persist_recovered"}))}catch(t){e.persistFailed=!0,l(`[${e.name}] PERSIST FAILED \u2014 identity quarantined (fail-closed), outbound of this txn withheld:`,String(t));try{g(e,{event:"persist_failed",error:String(t).slice(0,300)})}catch{}throw process.nextTick(()=>ee(e.name,`[${e.name}] PERSIST FAILED \u2014 messaging quarantined until the state file is writable again`)),t}}function S(e){let t=new Re;try{return e(t)}finally{t.Finalize()}}async function w(e){let t=new Re;try{return await e(t)}finally{t.Finalize()}}function R(e,t,s){let r=$e({name:t,targ:void 0}),a=e.pw.packet.ExecuteTransaction(r);return r.Destroy(),s?a.Attach(s):a}async function Ee(e,t){let s=e.lock,r;e.lock=new Promise(a=>r=a),await s;try{return await t()}finally{r()}}function Ae(e,t,s=25e3){return new Promise((r,a)=>{let d=setTimeout(()=>{let i=e.pending.findIndex(f=>f.timer===d);i>=0&&e.pending.splice(i,1),a(new Error("timed out waiting for the transaction result"))},s);e.pending.push({resolve:r,reject:a,timer:d}),e.pw.add_client_message(t)})}function h(e,t,s,r,a){if(e.persistFailed)try{z(e)}catch(i){return Promise.reject(new Error(`identity "${e.name}" is quarantined: state persist is failing (${String(i)}) \u2014 mutations are rejected until state_data.bin is writable again`))}let d=$e({name:t,targ:s});return Ee(e,()=>Ae(e,d,a)).then(i=>{if(d.Destroy(),e.persistFailed){try{i.Destroy()}catch{}throw new Error(`identity "${e.name}": state persist FAILED \u2014 this transaction's outbound was withheld (fail-closed); fix the state directory and retry`)}return r?i.Attach(r):i},i=>{try{d.Destroy()}catch{}throw i})}var D=null;function jt(e){D?.uninstall(),D=e===null?null:{hook:e,uninstall:ue("notification",e)}}function Lt(e){D?.hook===e&&(D.uninstall(),D=null)}function ee(e,t){fe(e,t)}var ve={onNotify:(e,t)=>ee(e,t)},U=new Map;function Oe(e){let t=U.get(e);if(!(!t||t.size===0))for(let s of[...t])try{s()}catch{}}function Pe(e,t){return new Promise(s=>{let r=U.get(e);r||(r=new Set,U.set(e,r));let a=!1,d=()=>{a||(a=!0,r.delete(i),r.size===0&&U.delete(e),clearTimeout(f),s())},i=d,f=setTimeout(d,t);r.add(i)})}function g(e,t){try{_.mkdirSync(e.dir,{recursive:!0,mode:448}),_.appendFileSync(L(e.dir),JSON.stringify(t)+`
2
+ import{c as pe}from"./chunk-KCMMTTYK.js";import{b as M}from"./chunk-YRPUM6JG.js";import{a as de}from"./chunk-LKFYUCN7.js";import{b as ue,e as le,f as fe}from"./chunk-UJGRFV4J.js";import{d as ce}from"./chunk-3AK2WAWH.js";import{a as j,c as N,d as b,e as W,f as ne,g as oe,h as J,i as O,j as k,k as L,l as B,p as se,w as ae}from"./chunk-MYLXP6TV.js";import{c as T,i as l,o as F,p as re}from"./chunk-UPZVGDSI.js";import{join as be}from"node:path";import*as _ from"node:fs";import{AdaptObjectLifetime as Re}from"@adapt-toolkit/sdk/common";import{object_to_adapt_value as $e}from"@adapt-toolkit/sdk/wrapper";import*as m from"node:fs";import{randomBytes as Ve}from"node:crypto";import*as $ from"node:fs";import{randomBytes as Ie}from"node:crypto";import{PacketWrapperConfigurator as Te}from"@adapt-toolkit/sdk/wrappers";import{AdaptObjectLifetime as Ne}from"@adapt-toolkit/sdk/common";function He(e){let t=[],s=e.Reduce("degraded");if(s.IsNil())return t;for(let r=0;;r++){let a=s.Reduce(r);if(a.IsNil())break;t.push({cid:a.Reduce("container_id").Visualize(),name:a.Reduce("name").Visualize(),attempts:Number(a.Reduce("attempts").Visualize()),queued:Number(a.Reduce("queued").Visualize())})}return t}function ke(e){let t=[],s=e.Reduce("queues");if(s.IsNil())return t;for(let r=0;;r++){let a=s.Reduce(r);if(a.IsNil())break;t.push({cid:a.Reduce("container_id").Visualize(),queued:Number(a.Reduce("queued").Visualize()),degraded:a.Reduce("degraded").GetBoolean()})}return t}async function K(e,t){try{let s=await w(async r=>{let a=await h(e,"::a2a_messaging::flush_deferred",{contact:t},r);return Number(a.Reduce("flushed").Visualize())});s>0&&l(`[${e.name}] flushed ${s} deferred message(s) to ${t.slice(0,12)}\u2026`)}catch(s){l(`[${e.name}] deferred flush to ${t.slice(0,12)}\u2026 failed:`,String(s))}}async function me(e){try{let t=await w(async r=>{let a=await h(e,"::a2a_messaging::restore_degraded_contacts",{},r);return Number(a.Reduce("requested").Visualize())});t>0&&l(`[${e.name}] contact restore requested for ${t} degraded contact(s)`);let s=S(r=>ke(R(e,"::a2a_messaging::list_deferred_queues",r)));for(let r of s)r.degraded||await K(e,r.cid)}catch(t){l(`[${e.name}] contact-restore sweep failed:`,String(t))}}async function xe(e){try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::reconcile_advertise",{},s),a=d=>r.Reduce(d).IsNil()?0:Number(r.Reduce(d).Visualize());return{changed:/true/i.test(r.Reduce("changed").Visualize()),capabilityAdvertised:a("capability_advertised"),legacyReadvertised:a("legacy_readvertised")}});(t.capabilityAdvertised>0||t.legacyReadvertised>0)&&l(`[${e.name}] capability reconcile: changed=${t.changed} advertised=${t.capabilityAdvertised} legacy_migration_bootstrap=${t.legacyReadvertised}`)}catch(t){l(`[${e.name}] capability reconcile sweep failed:`,String(t))}}var G=new Set;function H(e){if(!G.has(e.name)){G.add(e.name);for(let t of[2e3,15e3])setTimeout(()=>{t===15e3&&G.delete(e.name);let s=N.get(e.name);s&&xe(s)},t)}}async function qe(e){try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::readvertise_e2e_recovery",{},s);return Number(r.Reduce("readvertised").Visualize())});t>0&&l(`[${e.name}] re-advertised fresh AD to ${t} e2e contact(s) (session recovery)`)}catch(t){l(`[${e.name}] e2e recovery re-advertise failed:`,String(t))}try{await w(async t=>{await h(e,"::a2a_messaging::sweep_e2e_migrations",{},t)})}catch(t){l(`[${e.name}] e2e migration sweep failed:`,String(t))}try{let t=await w(async s=>{let r=await h(e,"::a2a_messaging::redrive_unacked_sweep",{},s),a=d=>r.Reduce(d).IsNil()?0:Number(r.Reduce(d).Visualize());return{redriven:a("redriven_contacts"),purged:a("purged_contacts"),deferred:a("deferred_contacts")}});(t.redriven>0||t.purged>0||t.deferred>0)&&l(`[${e.name}] unacked sweep: redriven=${t.redriven} ttl_purged=${t.purged} deferred=${t.deferred} contact(s)`)}catch(t){l(`[${e.name}] unacked redrive sweep failed:`,String(t))}}function ge(e,t){e.pw.on_return_data=s=>{let r=new Ne;s.Attach(r);try{let a=s.Reduce("kind").Visualize();if(a==="save_state"){z(e);return}if(a==="notify_agent"){let i=s.Reduce("payload"),f=i.Reduce("event").Visualize();if(f==="message_received"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("msg_id").Visualize(),c=i.Reduce("date").Visualize();g(e,{event:"message_received",from:o,msg_id:n,date:c}),P(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] new message from ${o} (#${n})`))}else if(f==="file_received"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("sender_id").Visualize(),c=i.Reduce("file_id").Visualize(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("filename").Visualize(),y=i.Reduce("mime").Visualize(),v=i.Reduce("bytes").Visualize(),I=i.Reduce("date").Visualize();g(e,{event:"file_received",from:o,sender_id:n,file_id:c,wire_id:u,filename:p,mime:y,bytes:v,date:I}),P(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] new file ${p} (${v} B) from ${o} (sender_id ${n}, file_id ${c}, wire_id ${u})`))}else if(f==="contact_accepted"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] contact "${o}" (${n}) accepted your invite.`))}else if(f==="local_contact_added"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] local contact "${o}" (${n}) connected via the contact book.`))}else if(f==="contact_name_collision"){let o=i.Reduce("message").Visualize(),n=i.Reduce("desired").Visualize(),c=i.Reduce("assigned").Visualize(),u=i.Reduce("existing_container_id").Visualize(),p=i.Reduce("container_id").Visualize();g(e,{event:"contact_name_collision",desired:n,assigned:c,existing_container_id:u,container_id:p}),l(`[${e.name}] CONTACT NAME COLLISION \u2014 ${o}`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] \u26A0 ${o}`))}else if(f==="sibling_contact_added"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"sibling_contact_added",from:o}),H(e),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] sibling "${o}" (${n}) connected (intra-root auto-accept).`))}else if(f==="local_contact_request"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"local_contact_request",from:o}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] pending local introduction from "${o}" (${n}) \u2014 approve or reject with respond_to_introduction.`))}else if(f==="pending_message"){let o=i.Reduce("sender_name").Visualize(),n=i.Reduce("queued").Visualize();g(e,{event:"pending_message",from:o,queued:n}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] "${o}" queued a message awaiting introduction approval (${n} queued).`))}else if(f==="e2e_restore_rejected")g(e,{event:"e2e_restore_rejected"}),l(`[${e.name}] E2E RESTORE REJECTED \u2014 corrupt session blob failed pickle_key validation; reset to empty e2e state, self-heal fallback will re-establish`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] persisted e2e sessions were corrupt \u2014 rejected cleanly, sessions re-establishing`));else if(f==="contact_restored"){let o=i.Reduce("name").Visualize(),n=i.Reduce("container_id").Visualize();g(e,{event:"contact_restored",from:o}),l(`[${e.name}] contact "${o}" restored (re-keyed)`),process.nextTick(()=>void K(e,String(n)))}else if(f==="migration_active"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("role").Visualize(),c=V(i,"epoch"),u=V(i,"session_id");g(e,{event:"migration_active",cid:String(o),role:String(n),...c?{epoch:c}:{},...u?{session_id:u}:{}}),l(`[migration] active cid=${o} role=${n}${c?` epoch=${c}`:""}${u?` session_id=${u}`:""}`)}else if(f==="e2e_app_send"){let o=i.Reduce("cid").Visualize(),n=V(i,"session_id"),c=i.Reduce("olm_type").Visualize(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("retained").IsNil()?void 0:i.Reduce("retained").GetBoolean(),y=[],v=i.Reduce("evicted");if(!v.IsNil())for(let I=0;;I++){let ie=v.Reduce(I);if(ie.IsNil())break;y.push(String(ie.Visualize()))}g(e,{event:"e2e_app_send",cid:String(o),session_id:n,olm_type:String(c),wire_id:String(u),...p===!1?{retained:!1}:{},...y.length?{evicted:y}:{}}),l(`[${e.name}] [e2e-app] send cid=${o} session_id=${n} olm_type=${c} wire_id=${u}${p===!1?" retained=false":""}${y.length?` evicted=${y.join(",")}`:""}`),y.length&&process.nextTick(()=>t.onNotify(e.name,`[${e.name}] redrive window overflow: ${y.length} older unacked send(s) lost their auto-resend guarantee (${y.join(", ")})`))}else if(f==="dedup_degraded"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("dropped_wire_id").Visualize();g(e,{event:"dedup_degraded",cid:String(o),dropped_wire_id:String(n)}),l(`[${e.name}] [e2e-app] DEDUP DEGRADED cid=${o} dropped_wire_id=${n} (storage ceiling \u2014 a late redrive of that id could re-deposit)`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] dedup window overflowed for ${String(o).slice(0,12)}\u2026 \u2014 one oldest entry dropped (guarantee loss surfaced)`))}else if(f==="e2e_delivery_expired"){let o=i.Reduce("cid").Visualize(),n=[],c=i.Reduce("wire_ids");if(!c.IsNil())for(let u=0;;u++){let p=c.Reduce(u);if(p.IsNil())break;n.push(String(p.Visualize()))}g(e,{event:"e2e_delivery_expired",cid:String(o),wire_ids:n}),l(`[${e.name}] [e2e-app] delivery EXPIRED (2-day TTL, receipt never arrived) cid=${o} wire_ids=${n.join(",")}`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] ${n.length} message(s)/file(s) to ${String(o).slice(0,12)}\u2026 expired undelivered (no receipt within 2 days)`))}else if(f==="e2e_app_recv"){let o=i.Reduce("cid").Visualize(),n=V(i,"session_id"),c=i.Reduce("ok").GetBoolean(),u=i.Reduce("wire_id").Visualize(),p=i.Reduce("code").IsNil()?void 0:String(i.Reduce("code").Visualize()),y=!i.Reduce("duplicate").IsNil(),v=!i.Reduce("file").IsNil();g(e,{event:"e2e_app_recv",cid:String(o),session_id:n,ok:c,wire_id:String(u),...p?{code:p}:{},...y?{duplicate:!0}:{},...v?{file:!0}:{}}),l(`[${e.name}] [e2e-app] recv cid=${o} session_id=${n} ok=${c} wire_id=${u}${p?` code=${p}`:""}${y?" duplicate=true":""}${v?" file=true":""}`)}else if(f==="e2e_rekey"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("role").Visualize(),c=V(i,"session_id"),u=i.Reduce("attempts").IsNil()?void 0:String(i.Reduce("attempts").Visualize()),p=i.Reduce("peer_supports").IsNil()?void 0:String(i.Reduce("peer_supports").Visualize()),y=i.Reduce("rejected").IsNil()?void 0:String(i.Reduce("rejected").Visualize());g(e,{event:"e2e_rekey",cid:String(o),role:String(n),...c?{session_id:c}:{},...u?{attempts:u}:{},...p?{peer_supports:p}:{},...y?{rejected:y}:{}}),l(`[${e.name}] [e2e-rekey] cid=${o} role=${n}${c?` session_id=${c}`:""}${u?` attempts=${u}`:""}${p?` peer_supports=${p}`:""}${y?` rejected=${y}`:""}`)}else if(f==="migration_deferred_flush"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("wire_id").Visualize();g(e,{event:"migration_deferred_flush",cid:String(o),wire_id:String(n)}),l(`[migration] flush-notify cid=${o} wire_id=${n} (deferred\u2192e2e; core delivers)`)}else if(f==="migration_stalled"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("phase").Visualize(),c=i.Reduce("attempts").Visualize();g(e,{event:"migration_stalled",cid:String(o),phase:String(n),attempts:String(c)}),l(`[migration] stalled-notify cid=${o} phase=${n} attempts=${c} (core re-drives via sweep)`)}else if(f==="downgrade_refused"){let o=i.Reduce("cid").Visualize(),n=i.Reduce("wire_id"),c=n.IsNil()?"":String(n.Visualize());g(e,{event:"downgrade_refused",cid:String(o),...c?{wire_id:c}:{}}),l(`[e2e-route] downgrade-dropped cid=${o}${c?` wire_id=${c}`:""} (legacy plaintext from a migrated peer \u2014 dropped by core)`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] a message from a migrated contact was rejected as an unsafe downgrade (dropped).`))}else if(f==="contact_removed"){let o=String(i.Reduce("cid").Visualize()),n=ce.has(e.name);g(e,{event:"contact_removed",cid:o,by:n?"local":"peer"}),n||(l(`[${e.name}] contact ${o} removed you (authenticated peer removal notice) \u2014 dropped from contacts`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] contact ${o.slice(0,12)}\u2026 removed you as a contact (the removal was applied locally too).`)))}else if(f==="monitoring_disabled"){let o=String(i.Reduce("cid").Visualize()),n=i.Reduce("cause"),c=n.IsNil()?"":String(n.Visualize());g(e,{event:"monitoring_disabled",cid:o,...c?{cause:c}:{}}),l(`[${e.name}] monitoring disabled (cid=${o}${c?` cause=${c}`:""})`),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] the monitoring/control-plane binding was disabled${c==="control_plane_removed_contact"?" \u2014 the control plane removed you as a contact":""}.`))}else(f==="control_request"||f==="host_provision_child"||f==="host_destroy_child"||f==="host_mint_child_invite"||f==="host_set_child_monitoring")&&l(`[${e.name}] ${f}: the daemon-side control plane is removed \u2014 ignoring`);return}let d=e.pending.shift();if(!d)return;clearTimeout(d.timer),d.resolve(s.Reduce("payload").Detach())}finally{r.Finalize()}},e.pw.on_transaction_failure=s=>{let r=e.pending.shift();r?(clearTimeout(r.timer),r.reject(new Error(s))):(l(`[${e.name}] inbound transaction rejected:`,s),g(e,{event:"inbound_error",message:s}),process.nextTick(()=>t.onNotify(e.name,`[${e.name}] inbound transaction rejected: ${s}`)))}}import{join as X}from"node:path";import*as x from"node:fs";var E=()=>X(T,F),Q=()=>X(E(),"registrar.key"),Y=()=>X(E(),"book.json");function ye(){try{let e=JSON.parse(x.readFileSync(Y(),"utf8"));return e&&typeof e.entries=="object"?e.entries:{}}catch{return{}}}function _e(e){x.mkdirSync(E(),{recursive:!0});let t=`${Y()}.tmp`;x.writeFileSync(t,JSON.stringify({v:1,entries:e},null,2),{mode:384}),x.renameSync(t,Y())}function Z(e){return S(t=>Buffer.from(R(e,"::actor::export_address_document",t).GetBinary()))}function q(e){return S(t=>Buffer.from(R(e,"::actor::export_signing_secret",t).Serialize()).toString("hex"))}async function we(e){if(!b)throw new Error("registrar is not available");let t=Z(e),s=await w(async a=>{let d=await h(b,"::actor::sign_book_entry",{name:e.name,ad:b.pw.packet.NewBinaryFromBuffer(t).Attach(a)},a);return Buffer.from(d.Reduce("sig").GetBinary()).toString("base64url")}),r=ye();r[e.name]={v:1,name:e.name,container_id:e.cid,address_document:t.toString("base64url"),published_at:new Date().toISOString(),registrar_sig:s},_e(r),l(`[${e.name}] published to the local contact book`)}function it(e){let t=ye(),s=Object.entries(t).find(([,r])=>r.container_id===e.cid);s&&(delete t[s[0]],_e(t),l(`[${e.name}] removed from the local contact book (entry "${s[0]}")`))}async function he(e){if(!W)throw new Error("registrar is not available");await w(async t=>{await h(e,"::actor::pin_registrar",{registrar_ad:e.pw.packet.NewBinaryFromBuffer(W).Attach(t)},t)})}function C(e,t,s,r=!0,a,d=!1){let i=new Te;i.deferred_exposure=d;let f=["--unit_hash",M.hash,"--seed_phrase",t,"--unit_dir_path",M.dir];return a&&f.push("--init_trn_argument",JSON.stringify(a)),i.process_arguments(f),new Promise((o,n)=>{let c=setTimeout(()=>n(new Error(`packet creation for "${e}" timed out`)),3e4);j.packet_manager.create_packet(i,u=>{clearTimeout(c);let p={name:e,cid:S(y=>u.packet.GetContainerID().Attach(y).Visualize()),pw:u,dir:s,pending:[],lock:Promise.resolve()};ge(p,ve),r&&N.set(e,p),l(`[${e}] packet created \u2014 container id ${p.cid}`),o(p)},M.contents)})}var A=new Set(ae());A.size>0&&l(`reserved ${A.size} persisted identity name(s) at module load: ${[...A].join(", ")}`);async function gt(e,t={exposeLocal:!0,localAutoAccept:!0}){if(A.has(e)||N.has(e))throw new Error(`identity name "${e}" is reserved \u2014 a persisted identity with this name is restoring, present, or being provisioned; refusing to provision over it`);A.add(e);try{let s=J(e);$.mkdirSync(s,{recursive:!0,mode:448});let r;t.temp&&(r={owner:{tokenHash:t.temp.tokenHash,pid:t.temp.pid},createdAt:Date.now()},se(s,r));let a=Ie(24).toString("hex"),d=await C(e,a,s);return r&&(d.temp=r),$.writeFileSync(O(s),q(d),{mode:384}),await w(async i=>{await h(d,"::a2a_messaging::set_my_name",{name:e},i)}),await he(d),t.localAutoAccept||await w(async i=>{await h(d,"::actor::set_local_policy",{auto_accept:!1},i)}),t.exposeLocal&&await we(d),z(d),d}catch(s){throw A.delete(e),s}}async function yt(e){let t=J(e),s=$.readFileSync(O(t),"utf8").trim(),r=await C(e,"",t,!1,s,!0);l(`[${e}] created QUARANTINED (no routing/broker registration, not client-bindable) \u2014 importing state before exposure`);let a=Number(process.env.OURS_TEST_RESTORE_HOLD_MS||"")||0;a>0&&(l(`[${e}] TEST HOLD: keeping restore open ${a}ms (OURS_TEST_RESTORE_HOLD_MS)`),await new Promise(o=>setTimeout(o,a)));let d=o=>/timed out waiting for the transaction result/.test(String(o)),i=(o,n,c)=>{l(`[${e}] ${o} ${n} \u2014 identity left UNEXPOSED and UNTRACKED (fail-closed)`);try{g(r,{event:"restore_fail_closed",step:o,error:String(c).slice(0,300)})}catch{}N.delete(e);try{j.remove_packet(r.cid)}catch(u){l(`[${e}] quarantined-packet teardown failed:`,String(u))}throw new Error(`identity "${e}": ${o} failed during restore (${n}) \u2014 left unexposed (fail-closed)`)},f=(o,n)=>i(o,"outcome UNKNOWN (timeout): the transaction may still execute and exposure would race it",n);if(Se(t)){let o=!1;try{if(process.env.OURS_TEST_FORCE_IMPORT_TIMEOUT==="1")throw new Error("timed out waiting for the transaction result (forced by OURS_TEST_FORCE_IMPORT_TIMEOUT)");let n=$.readFileSync(k(t));await w(async c=>{let u=r.pw.packet.ParseValue(new Uint8Array(n)).Attach(c),p=Number(process.env.OURS_IMPORT_TIMEOUT_MS||"")||void 0;await h(r,"::actor::import_state",u,c,p)}),o=!0,l(`[${e}] state import completed (positively observed)`)}catch(n){d(n)&&f("import_state",n),l(`[${e}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`,String(n)),g(r,{event:"state_import_failed",error:String(n).slice(0,300)});try{let c=`${k(t)}.failed-${Date.now()}`;$.renameSync(k(t),c),$.chmodSync(c,384),l(`[${e}] unreadable state blob preserved as state_data.bin.failed-*`)}catch{}}if(o){try{let u=await w(async p=>{let y=await h(r,"::a2a_messaging::commit_e2e_restore",{},p),v=y.Reduce("status").Visualize(),I=y.Reduce("sessions").IsNil()?"0":y.Reduce("sessions").Visualize();return{status:String(v),sessions:String(I)}});l(`[${e}] e2e restore commit: status=${u.status} sessions=${u.sessions}`)}catch(u){d(u)&&f("commit_e2e_restore",u),l(`[${e}] E2E RESTORE REJECTED \u2014 staged session blob failed pickle_key validation; discarding it, fresh account + self-heal fallback take over: ${String(u).slice(0,260)}`),g(r,{event:"e2e_restore_rejected",origin:"restore",error:String(u).slice(0,300)});try{await w(async p=>{await h(r,"::a2a_messaging::reject_e2e_restore",{},p)})}catch(p){d(p)&&f("reject_e2e_restore",p),l(`[${e}] reject_e2e_restore failed (staging is transient; continuing):`,String(p))}}try{r.pw.refresh_identity_proof_document(),l(`[${e}] transport IPD refreshed from post-import state`)}catch(u){i("ipd_refresh","FAILED (IPD would advertise a stale bundle)",u)}let n=!1,c="";try{if(process.env.OURS_TEST_FORCE_IPD_INCOHERENT==="1")throw new Error("forced incoherent (OURS_TEST_FORCE_IPD_INCOHERENT)");let u=S(v=>String(R(r,"::a2a_messaging::e2e_self_fp",v).Reduce("ik").Visualize())),p=r.pw.identity_proof_document.Visualize(),y=u.replace(/^0x/i,"");n=y.length>=32&&p.toLowerCase().includes(y.toLowerCase()),c=u.slice(0,18),g(r,{event:"ipd_coherence",ik:u,coherent:n})}catch(u){i("ipd_coherence","probe FAILED (coherence unprovable)",u)}l(`[${e}] IPD/e2e coherence: account_ik=${c}\u2026 ipd_advertises_it=${n}`),n||i("ipd_coherence","IPD does NOT advertise the live account ik",new Error("incoherent transport IPD"))}}return j.expose_packet(r.cid),N.set(e,r),l(`[${e}] EXPOSED (routing + broker registration) \u2014 import phase complete`),await me(r),P(r),r}async function kt(){m.mkdirSync(E(),{recursive:!0});let e;try{e=m.readFileSync(Q(),"utf8").trim()}catch{}let t=Ve(24).toString("hex");ne(await C(F,t,E(),!1,e)),e||m.writeFileSync(Q(),q(b),{mode:384}),oe(Z(b)),l(`contact-book registrar ready (${b.cid})`)}function Se(e){try{return m.existsSync(k(e))&&m.statSync(k(e)).size>0}catch{return!1}}function ze(e){let t=S(d=>Buffer.from(R(e,"::actor::export_state",d).Serialize()));m.mkdirSync(e.dir,{recursive:!0,mode:448});let s=k(e.dir),r=`${s}.tmp`,a;try{a=m.openSync(r,"w",384),m.fchmodSync(a,384),m.writeFileSync(a,t),m.fsyncSync(a),m.closeSync(a),a=void 0,m.renameSync(r,s),m.chmodSync(s,384);try{m.chmodSync(O(e.dir),384)}catch{}let d=m.openSync(e.dir,"r");try{m.fsyncSync(d)}finally{m.closeSync(d)}}catch(d){if(a!==void 0)try{m.closeSync(a)}catch{}try{m.rmSync(r,{force:!0})}catch{}throw d}}function z(e){try{ze(e),e.persistFailed&&(e.persistFailed=!1,l(`[${e.name}] persist recovered \u2014 quarantine lifted`),g(e,{event:"persist_recovered"}))}catch(t){e.persistFailed=!0,l(`[${e.name}] PERSIST FAILED \u2014 identity quarantined (fail-closed), outbound of this txn withheld:`,String(t));try{g(e,{event:"persist_failed",error:String(t).slice(0,300)})}catch{}throw process.nextTick(()=>ee(e.name,`[${e.name}] PERSIST FAILED \u2014 messaging quarantined until the state file is writable again`)),t}}function S(e){let t=new Re;try{return e(t)}finally{t.Finalize()}}async function w(e){let t=new Re;try{return await e(t)}finally{t.Finalize()}}function R(e,t,s){let r=$e({name:t,targ:void 0}),a=e.pw.packet.ExecuteTransaction(r);return r.Destroy(),s?a.Attach(s):a}async function Ee(e,t){let s=e.lock,r;e.lock=new Promise(a=>r=a),await s;try{return await t()}finally{r()}}function Ae(e,t,s=25e3){return new Promise((r,a)=>{let d=setTimeout(()=>{let i=e.pending.findIndex(f=>f.timer===d);i>=0&&e.pending.splice(i,1),a(new Error("timed out waiting for the transaction result"))},s);e.pending.push({resolve:r,reject:a,timer:d}),e.pw.add_client_message(t)})}function h(e,t,s,r,a){if(e.persistFailed)try{z(e)}catch(i){return Promise.reject(new Error(`identity "${e.name}" is quarantined: state persist is failing (${String(i)}) \u2014 mutations are rejected until state_data.bin is writable again`))}let d=$e({name:t,targ:s});return Ee(e,()=>Ae(e,d,a)).then(i=>{if(d.Destroy(),e.persistFailed){try{i.Destroy()}catch{}throw new Error(`identity "${e.name}": state persist FAILED \u2014 this transaction's outbound was withheld (fail-closed); fix the state directory and retry`)}return r?i.Attach(r):i},i=>{try{d.Destroy()}catch{}throw i})}var D=null;function jt(e){D?.uninstall(),D=e===null?null:{hook:e,uninstall:ue("notification",e)}}function Lt(e){D?.hook===e&&(D.uninstall(),D=null)}function ee(e,t){fe(e,t)}var ve={onNotify:(e,t)=>ee(e,t)},U=new Map;function Oe(e){let t=U.get(e);if(!(!t||t.size===0))for(let s of[...t])try{s()}catch{}}function Pe(e,t){return new Promise(s=>{let r=U.get(e);r||(r=new Set,U.set(e,r));let a=!1,d=()=>{a||(a=!0,r.delete(i),r.size===0&&U.delete(e),clearTimeout(f),s())},i=d,f=setTimeout(d,t);r.add(i)})}function g(e,t){try{_.mkdirSync(e.dir,{recursive:!0,mode:448}),_.appendFileSync(L(e.dir),JSON.stringify(t)+`
3
3
  `)}catch(s){l(`[${e.name}] failed to append notifications.log:`,String(s))}Oe(e.name),le(e,t)}function Bt(e){let t=L(e.dir),s="";try{s=_.readFileSync(t,"utf8")}catch{return new Set}let r=[];for(let a of s.split(`
4
4
  `))if(a.trim())try{r.push(JSON.parse(a))}catch{}return de(r)}function V(e,t){let s=e.Reduce(t);return s.IsNil()?"":Buffer.from(s.GetBinary()).toString("hex")}var De=Number(process.env.OURS_NOTIFY_LONGPOLL_MS)>0?Number(process.env.OURS_NOTIFY_LONGPOLL_MS):25e3,Fe=250;function te(e){try{return _.statSync(e).size}catch{return 0}}function je(e,t,s){if(s<=t)return{events:[],cursor:t};let r=Buffer.alloc(s-t),a=0;try{let o=_.openSync(e,"r");try{a=_.readSync(o,r,0,r.length,t)}finally{_.closeSync(o)}}catch{return{events:[],cursor:t}}let d=r.subarray(0,a),i=d.lastIndexOf(10);if(i===-1)return{events:[],cursor:t};let f=[];for(let o of d.subarray(0,i+1).toString("utf8").split(`
5
5
  `))if(o.trim())try{f.push(JSON.parse(o))}catch{}return{events:f,cursor:t+i+1}}async function Mt(e,t,s,r){let a=L(be(T,s)),d=(n,c)=>{t.writableEnded||(t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({cursor:n,events:c})))};if(r===null||r==="tip"){d(te(a),[]);return}let i=parseInt(r,10);if(!Number.isFinite(i)||i<0){t.writableEnded||(t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid since cursor"})));return}let f=!1;e.on("close",()=>{f=!0});let o=Date.now()+De;for(;!f;){let n=te(a);if(i>n&&(i=0),n>i){let{events:c,cursor:u}=je(a,i,n);if(c.length>0){d(u,c);return}i=u}if(Date.now()>=o)break;await Pe(s,Math.min(Fe,o-Date.now()))}f||d(te(a),[])}function P(e){try{let{unread:t,unreadFiles:s}=S(d=>{let f=pe(R(e,"::actor::list_incoming_messages",d)).filter(c=>c.status==="unread"),o=R(e,"::actor::list_incoming_files",d),n=[];if(!o.IsNil())for(let c=0;;c++){let u=o.Reduce(c);if(u.IsNil())break;u.Reduce("status").Visualize()==="unread"&&n.push({file_id:u.Reduce("file_id").Visualize(),sender_id:u.Reduce("sender_id").Visualize(),from:u.Reduce("sender_name").Visualize(),filename:u.Reduce("filename").Visualize(),mime:u.Reduce("mime").Visualize(),bytes:u.Reduce("size").Visualize(),date:u.Reduce("date").Visualize(),wire_id:u.Reduce("wire_id").Visualize()})}return{unread:f,unreadFiles:n}}),r={count:t.length,recent:t.slice(-10).map(d=>({from:d.sender_name,msg_id:d.msg_id,date:d.date})),files:s.length,unread_files:s.slice(-10)};_.mkdirSync(e.dir,{recursive:!0,mode:448});let a=`${B(e.dir)}.tmp`;_.writeFileSync(a,JSON.stringify(r)),_.renameSync(a,B(e.dir))}catch(t){l(`[${e.name}] failed to refresh unread snapshot:`,String(t))}}function Ht(){let e=[],t=[];try{t=_.readdirSync(T,{withFileTypes:!0})}catch{return{identities:e}}for(let s of t){if(!s.isDirectory()||re(s.name)!==null)continue;let r;try{r=JSON.parse(_.readFileSync(B(be(T,s.name)),"utf8"))}catch{continue}let a=Number.isSafeInteger(r.count)&&Number(r.count)>=0?Number(r.count):0,d=Number.isSafeInteger(r.files)&&Number(r.files)>=0?Number(r.files):0;if(a===0&&d===0)continue;let i=Array.isArray(r.recent)?r.recent.slice(-10).flatMap(o=>{if(!o||typeof o!="object")return[];let n=o;return typeof n.from!="string"||!["string","number"].includes(typeof n.msg_id)||typeof n.date!="string"?[]:[{from:n.from,msg_id:n.msg_id,date:n.date}]}):[],f=Array.isArray(r.unread_files)?r.unread_files.slice(-10).flatMap(o=>{if(!o||typeof o!="object")return[];let n=o;return typeof n.from!="string"||typeof n.filename!="string"||typeof n.mime!="string"||typeof n.wire_id!="string"?[]:[{from:n.from,filename:n.filename,mime:n.mime,wire_id:n.wire_id,...typeof n.sender_id=="string"?{sender_id:n.sender_id}:{},...["string","number"].includes(typeof n.file_id)?{file_id:n.file_id}:{},...["string","number"].includes(typeof n.bytes)?{bytes:n.bytes}:{},...typeof n.date=="string"?{date:n.date}:{}}]}):[];e.push({name:s.name,count:a,recent:i,files:d,unread_files:f})}return e.sort((s,r)=>String(s.name).localeCompare(String(r.name))),{identities:e}}export{jt as a,Lt as b,ee as c,ve as d,Oe as e,Pe as f,g,Bt as h,V as i,te as j,je as k,Mt as l,P as m,Ht as n,He as o,ke as p,K as q,me as r,xe as s,H as t,qe as u,ge as v,C as w,A as x,gt as y,yt as z,kt as A,Se as B,ze as C,z as D,S as E,w as F,R as G,Ee as H,Ae as I,h as J,E as K,Q as L,Y as M,ye as N,_e as O,Z as P,q as Q,we as R,it as S,he as T};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{a as s}from"./chunk-2W4CPM4Q.js";import{F as h,G as y,H as x,I as F,J as l}from"./chunk-UM73BGFH.js";import{E as S,F as d,G as _,J as f,m as c}from"./chunk-2YUTV62M.js";import{d as g,f as p}from"./chunk-KCMMTTYK.js";import{t as m,u as a,v as w}from"./chunk-MYLXP6TV.js";async function M(n){let r=s(n);try{return S(t=>g(_(r,"::actor::list_incoming_files",t)))}catch(t){throw l("list_incoming_files",String(t))}}async function N(n,r={}){let t=s(n),{wire_ids:e}=r;if(e!==void 0){if(e.length<1||e.length>a)throw h(a);if(e.some(i=>!m(i)))throw y();if(new Set(e).size!==e.length)throw x()}try{let i=await d(async o=>{let u=await f(t,"::actor::get_files",e===void 0?{}:{wire_ids:e},o);return await p(t,u.Reduce("files"))});return c(t),{files:i.files,text:i.text,mode:e===void 0?"all_unread":"selected",requested:e??null}}catch(i){let o=String(i);throw e!==void 0&&/unknown, stale, or no longer unread/i.test(o)?F():l("get_files",o)}}function P(n,r){let t=s(n);return{existsOnDisk:w(t,r.wire_id)!==null}}async function T(n,r){let t=s(n),{file_ids:e}=r;try{let i=await d(async o=>(await f(t,"::actor::defer_files",{file_ids:e},o)).Reduce("deferred").Visualize());return c(t),{deferred:i}}catch(i){throw l("defer_files",String(i))}}export{M as a,N as b,P as c,T as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{c as a}from"./chunk-Q3UVLSCX.js";import{c as d,i as u}from"./chunk-HSVIKO4D.js";import{join as h}from"node:path";import*as r from"node:fs";var i=new Map,g=new Set,c=new Map,k=new Set;function E(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function m(e){for(let t of i.values())if(t.token===e)return t}var f=()=>h(d,"bindings.json");function l(){try{r.mkdirSync(d,{recursive:!0});let e=`${f()}.tmp`;r.writeFileSync(e,JSON.stringify({pid:process.pid,bound:[...i.keys()],holders:[...i.values()].map(t=>({identity:t.identity,pid:t.pid}))})),r.renameSync(e,f())}catch(e){u("failed to persist bindings snapshot:",String(e))}}function _(e){let t=c.get(e)?.token;if(!t)return{code:"NOT_BOUND",error:"No identity bound to this session. Call choose_identity (or create_identity) first."};if(g.has(t))return{code:"BINDING_REASSIGNED",error:"Your identity binding was reassigned to another session. Call choose_identity again to continue."};let n=m(t);if(!n)return{code:"NOT_BOUND",error:"No identity bound to this session. Call choose_identity (or create_identity) first."};let o=a.get(n.identity);if(!o)return i.delete(n.identity),l(),{code:"BOUND_IDENTITY_GONE",error:`The bound identity "${n.identity}" no longer exists. Choose another with choose_identity.`};if(o.temp?.closing)return{code:"TEMP_CLOSING",error:`The temporary identity "${o.name}" is closing and no longer accepts work. Its contacts are being notified and its local state deleted.`};n.sid=e;let s=c.get(e)?.pid;return s&&(n.pid=s),{id:o}}function x(e,t){let n=c.get(e),o=n?.token;if(!o)return;for(let[p,y]of[...i])y.token===o&&p!==t&&i.delete(p);let s=i.get(t)?.epoch??0;i.set(t,{identity:t,token:o,pid:n?.pid??0,sid:e,epoch:s+1,boundAt:Date.now()}),g.delete(o),l()}export{i as a,g as b,c,k as d,E as e,m as f,l as g,_ as h,x as i};
2
+ import{c as a}from"./chunk-MYLXP6TV.js";import{c as d,i as u}from"./chunk-UPZVGDSI.js";import{join as h}from"node:path";import*as r from"node:fs";var i=new Map,g=new Set,c=new Map,k=new Set;function E(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function m(e){for(let t of i.values())if(t.token===e)return t}var f=()=>h(d,"bindings.json");function l(){try{r.mkdirSync(d,{recursive:!0});let e=`${f()}.tmp`;r.writeFileSync(e,JSON.stringify({pid:process.pid,bound:[...i.keys()],holders:[...i.values()].map(t=>({identity:t.identity,pid:t.pid}))})),r.renameSync(e,f())}catch(e){u("failed to persist bindings snapshot:",String(e))}}function _(e){let t=c.get(e)?.token;if(!t)return{code:"NOT_BOUND",error:"No identity bound to this session. Call choose_identity (or create_identity) first."};if(g.has(t))return{code:"BINDING_REASSIGNED",error:"Your identity binding was reassigned to another session. Call choose_identity again to continue."};let n=m(t);if(!n)return{code:"NOT_BOUND",error:"No identity bound to this session. Call choose_identity (or create_identity) first."};let o=a.get(n.identity);if(!o)return i.delete(n.identity),l(),{code:"BOUND_IDENTITY_GONE",error:`The bound identity "${n.identity}" no longer exists. Choose another with choose_identity.`};if(o.temp?.closing)return{code:"TEMP_CLOSING",error:`The temporary identity "${o.name}" is closing and no longer accepts work. Its contacts are being notified and its local state deleted.`};n.sid=e;let s=c.get(e)?.pid;return s&&(n.pid=s),{id:o}}function x(e,t){let n=c.get(e),o=n?.token;if(!o)return;for(let[p,y]of[...i])y.token===o&&p!==t&&i.delete(p);let s=i.get(t)?.epoch??0;i.set(t,{identity:t,token:o,pid:n?.pid??0,sid:e,epoch:s+1,boundAt:Date.now()}),g.delete(o),l()}export{i as a,g as b,c,k as d,E as e,m as f,l as g,_ as h,x as i};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as P,b as B,c as C,d as b}from"./chunk-VW2KWXSJ.js";import{a as g}from"./chunk-7UUFYO6G.js";import{A as M,B as A,C as E,J as m,a as R}from"./chunk-UM73BGFH.js";import{E as v,F as u,G as F,J as _,g as p,h as $,m as y}from"./chunk-NQQ4GSVI.js";import{c as w}from"./chunk-X4RVJ5VL.js";import{d as k}from"./chunk-LKFYUCN7.js";import{a as I}from"./chunk-P55RJGZU.js";import{i as c}from"./chunk-HSVIKO4D.js";import{readFile as q}from"node:fs/promises";import{basename as N}from"node:path";function O(s,r){if(s)return r!==void 0?{wire_id:s,sentence:r}:{wire_id:s}}async function Q(s,r){let e=g(s),{contact:o,text:n}=r,a=O(r.reply_to_wire_id,r.reply_to_sentence);try{let t=await u(async d=>b(await _(e,"::a2a_messaging::send_message",{contact:o,text:n,...a?{reply_to:a}:{}},d)));switch(t.kind){case"refused":c(`[e2e-route] refused cid=${t.cid} wire_id=${t.wireId} (downgrade_refused)`);break;case"migrating":c(`[migration] queued cid=${t.cid} wire_id=${t.wireId} (migrating, ${t.queued} queued)`);break;case"e2e":c(`[e2e-route] cid=${t.cid} wire_id=${t.wireId} verdict=e2e (core delivered over migrated session)${t.notRetained?" NOT RETAINED (oversized)":""}`),t.notRetained&&p(e,{event:"send_not_retained",wire_id:t.wireId,kind:"message"});break;default:break}return t}catch(t){if(!/Unknown contact/.test(String(t)))throw m("send_message",String(t));try{let d=P(e,o);return{kind:"introduced",text:d?await B(e,d,n):await C(e,o,n)}}catch(d){throw m("send_message",String(d),"FALLBACK_FAILED")}}}async function X(s,r){let e=g(s),{contact:o,path:n,data_base64:a,filename:t,mime:d}=r;if((n?1:0)+(a?1:0)!=1)throw M();let f,l;try{if(n)f=await q(n),l=t??N(n);else{if(!t)throw A();f=Buffer.from(a,"base64"),l=t}}catch(i){throw i instanceof R?i:E(String(i))}let h=d??(n?I(n):""),S=O(r.reply_to_wire_id,r.reply_to_sentence);try{let i=await u(async x=>{let T=e.pw.packet.NewBinaryFromBuffer(f).Attach(x);return b(await _(e,"::a2a_messaging::send_file",{contact:o,filename:l,mime:h,data:T,...S?{reply_to:S}:{}},x))});switch(i.kind){case"refused":c(`[e2e-route] refused cid=${i.cid} wire_id=${i.wireId} (downgrade_refused, file)`);break;case"migrating":c(`[migration] file-defer cid=${i.cid} wire_id=${i.wireId} (migrating, not queued)`);break;case"e2e":c(`[e2e-route] cid=${i.cid} wire_id=${i.wireId} verdict=e2e file (core delivered over migrated session)${i.notRetained?" NOT RETAINED (oversized)":""}`),i.notRetained&&p(e,{event:"send_not_retained",wire_id:i.wireId,kind:"file"});break;default:break}return{...i,filename:l,bytes:f.length,mime:h}}catch(i){throw m("send_file",String(i))}}async function Y(s){let r=g(s);try{return v(e=>w(F(r,"::actor::list_incoming_messages",e)))}catch(e){throw m("list_incoming_messages",String(e))}}async function Z(s){let r=g(s);try{let e=await u(async n=>{let a=await _(r,"::actor::get_messages",{},n);return w(a.Reduce("messages"))});y(r);let o=$(r);return k(e,o)}catch(e){throw m("get_messages",String(e))}}async function ee(s,r){let e=g(s),{msg_ids:o}=r;try{let n=await u(async a=>(await _(e,"::actor::defer_messages",{msg_ids:o},a)).Reduce("deferred").Visualize());return y(e),{deferred:n}}catch(n){throw m("defer_messages",String(n))}}export{Q as a,X as b,Y as c,Z as d,ee as e};
2
+ import{a as P,b as B,c as C,d as b}from"./chunk-Z63GGB2N.js";import{a as g}from"./chunk-2W4CPM4Q.js";import{A as M,B as A,C as E,J as m,a as R}from"./chunk-UM73BGFH.js";import{E as v,F as u,G as F,J as _,g as p,h as $,m as y}from"./chunk-2YUTV62M.js";import{c as w}from"./chunk-KCMMTTYK.js";import{d as k}from"./chunk-LKFYUCN7.js";import{a as I}from"./chunk-P55RJGZU.js";import{i as c}from"./chunk-UPZVGDSI.js";import{readFile as q}from"node:fs/promises";import{basename as N}from"node:path";function O(s,r){if(s)return r!==void 0?{wire_id:s,sentence:r}:{wire_id:s}}async function Q(s,r){let e=g(s),{contact:o,text:n}=r,a=O(r.reply_to_wire_id,r.reply_to_sentence);try{let t=await u(async d=>b(await _(e,"::a2a_messaging::send_message",{contact:o,text:n,...a?{reply_to:a}:{}},d)));switch(t.kind){case"refused":c(`[e2e-route] refused cid=${t.cid} wire_id=${t.wireId} (downgrade_refused)`);break;case"migrating":c(`[migration] queued cid=${t.cid} wire_id=${t.wireId} (migrating, ${t.queued} queued)`);break;case"e2e":c(`[e2e-route] cid=${t.cid} wire_id=${t.wireId} verdict=e2e (core delivered over migrated session)${t.notRetained?" NOT RETAINED (oversized)":""}`),t.notRetained&&p(e,{event:"send_not_retained",wire_id:t.wireId,kind:"message"});break;default:break}return t}catch(t){if(!/Unknown contact/.test(String(t)))throw m("send_message",String(t));try{let d=P(e,o);return{kind:"introduced",text:d?await B(e,d,n):await C(e,o,n)}}catch(d){throw m("send_message",String(d),"FALLBACK_FAILED")}}}async function X(s,r){let e=g(s),{contact:o,path:n,data_base64:a,filename:t,mime:d}=r;if((n?1:0)+(a?1:0)!=1)throw M();let f,l;try{if(n)f=await q(n),l=t??N(n);else{if(!t)throw A();f=Buffer.from(a,"base64"),l=t}}catch(i){throw i instanceof R?i:E(String(i))}let h=d??(n?I(n):""),S=O(r.reply_to_wire_id,r.reply_to_sentence);try{let i=await u(async x=>{let T=e.pw.packet.NewBinaryFromBuffer(f).Attach(x);return b(await _(e,"::a2a_messaging::send_file",{contact:o,filename:l,mime:h,data:T,...S?{reply_to:S}:{}},x))});switch(i.kind){case"refused":c(`[e2e-route] refused cid=${i.cid} wire_id=${i.wireId} (downgrade_refused, file)`);break;case"migrating":c(`[migration] file-defer cid=${i.cid} wire_id=${i.wireId} (migrating, not queued)`);break;case"e2e":c(`[e2e-route] cid=${i.cid} wire_id=${i.wireId} verdict=e2e file (core delivered over migrated session)${i.notRetained?" NOT RETAINED (oversized)":""}`),i.notRetained&&p(e,{event:"send_not_retained",wire_id:i.wireId,kind:"file"});break;default:break}return{...i,filename:l,bytes:f.length,mime:h}}catch(i){throw m("send_file",String(i))}}async function Y(s){let r=g(s);try{return v(e=>w(F(r,"::actor::list_incoming_messages",e)))}catch(e){throw m("list_incoming_messages",String(e))}}async function Z(s){let r=g(s);try{let e=await u(async n=>{let a=await _(r,"::actor::get_messages",{},n);return w(a.Reduce("messages"))});y(r);let o=$(r);return k(e,o)}catch(e){throw m("get_messages",String(e))}}async function ee(s,r){let e=g(s),{msg_ids:o}=r;try{let n=await u(async a=>(await _(e,"::actor::defer_messages",{msg_ids:o},a)).Reduce("deferred").Visualize());return y(e),{deferred:n}}catch(n){throw m("defer_messages",String(n))}}export{Q as a,X as b,Y as c,Z as d,ee as e};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{a as M,b,c as F,d as w,e as T,f as N,g as L,h as H,i as B,j}from"./chunk-VRL5GND4.js";import{a as E,b as J,c as _,d as $}from"./chunk-37QQN5ND.js";import{a as U,b as V,c as X,d as q,e as z}from"./chunk-63OOHGB4.js";import{a as D,b as G,c as K,d as Q}from"./chunk-KKRG4E3A.js";import{b as u,c as v,d as S,e as k,f as x,g as h,h as O,i as R,j as C,k as P}from"./chunk-2W4CPM4Q.js";import{a as I}from"./chunk-UM73BGFH.js";import{c as d}from"./chunk-3AK2WAWH.js";import{o as f}from"./chunk-MYLXP6TV.js";import{i as m,m as y}from"./chunk-UPZVGDSI.js";var Z="/api/v1/",t=i=>(e,n)=>i(e,n),s=i=>e=>i(e),ee=i=>(e,n)=>i(n),W={createIdentity:t(u),createTemporaryIdentity:t(v),closeTemporaryIdentityOp:t(S),createRootIdentity:t(k),defineLocalIdentityFile:ee(x),chooseIdentity:t(h),listIdentities:s(O),currentIdentity:s(R),removeIdentity:t(C),releaseLease:s(P),generateInvite:t(M),listInvites:s(b),revokeInvite:t(F),addContact:t(w),listContacts:s(T),listLocalContactBook:s(N),setLocalBookPolicy:t(L),removeContact:t(H),renameContact:t(B),respondToIntroduction:t(j),setBio:t(D),advertiseMigrate:s(G),readvertiseOnUpgrade:s(Q),setPersona:t(K),sendMessage:t(U),sendFile:t(V),listIncomingMessages:s(X),getMessages:s(q),deferMessages:t(z),deferFiles:t($),listIncomingFiles:s(E),getFiles:t(J),saveFileFallbackNotice:t(_)},l=new Map,Y=(i,e)=>{let n=i.headers[e];return typeof n=="string"&&n!==""?n:void 0};function te(i){let e=Y(i,"x-ours-lease-token"),n=Y(i,"x-ours-client-pid"),A=n?parseInt(n,10):NaN,a=Number.isInteger(A)?A:void 0,o=e?`api:${f(e)}`:"api:anonymous";return d.set(o,{token:e,pid:a}),l.set(o,(l.get(o)??0)+1),{ctx:{sessionId:()=>o,leaseToken:()=>d.get(o)?.token,clientPid:()=>d.get(o)?.pid},release:()=>{let r=(l.get(o)??1)-1;if(r>0){l.set(o,r);return}l.delete(o),d.delete(o)}}}var p=(i,e,n)=>{i.writableEnded||(i.writeHead(e,{"Content-Type":"application/json"}),i.end(JSON.stringify(n??null)))};async function le(i,e,n,A){let a=n.slice(Z.length);if(!y(i,e))return;if(i.method!=="POST"){p(e,405,{error:"method not allowed: the typed API is POST-only"});return}let o=Object.prototype.hasOwnProperty.call(W,a)?W[a]:void 0;if(!o){p(e,404,{error:`unknown operation "${a}"`});return}let r;try{r=await A(i)}catch{p(e,400,{error:"the request body must be JSON"});return}if(r===null||typeof r!="object"||Array.isArray(r)){p(e,400,{error:"the request body must be a JSON object"});return}let g=te(i);try{p(e,200,await o(g.ctx,r))}catch(c){if(c instanceof I){p(e,400,{error:{code:c.code,message:c.message}});return}m("api handler error:",a,String(c)),p(e,500,{error:`internal error in ${a}: ${String(c)}`})}finally{g.release()}}export{Z as a,W as b,te as c,le as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{e as d}from"./chunk-HCIVLHKC.js";import{E as a,G as c}from"./chunk-NQQ4GSVI.js";import{c as s}from"./chunk-Q3UVLSCX.js";function y(e){try{return a(n=>{let i=c(e,"::a2a_capabilities::get_manifest",n).Reduce("capabilities");return i.IsNil()?[]:[...i.GetKeys()].map(t=>typeof t=="string"?t:t.Visualize())})}catch{return[]}}function R(e){let n="",i="",t="",u="",l=[];try{a(g=>{let p=c(e,"::a2a_capabilities::get_manifest",g),r=o=>{let f=p.Reduce(o);return f.IsNil()?"":f.Visualize()};n=r("app_id"),i=r("name"),t=r("description"),u=r("version");let m=p.Reduce("capabilities");m.IsNil()||(l=[...m.GetKeys()].map(o=>typeof o=="string"?o:o.Visualize()))})}catch{}return{app_id:n,name:i,description:t,version:u,capabilities:l,monitoring_status:"unbound"}}function h(e){let n=[];for(let i of s.values()){if(i.name===e.name)continue;let t=d(i);t.rootCid===e.cid&&n.push({name:i.name,cid:i.cid,role_id:t.roleId,bio:t.bio,monitoring:t.monitoringEnabled,capabilities:y(i)})}return n}function v(e,n){let i=s.get(n)??[...s.values()].find(t=>t.cid===n);return!i||i.name===e.name?null:d(i).rootCid===e.cid?i:null}export{y as a,R as b,h as c,v as d};
2
+ import{e as d}from"./chunk-Z6KWRSU7.js";import{E as a,G as c}from"./chunk-2YUTV62M.js";import{c as s}from"./chunk-MYLXP6TV.js";function y(e){try{return a(n=>{let i=c(e,"::a2a_capabilities::get_manifest",n).Reduce("capabilities");return i.IsNil()?[]:[...i.GetKeys()].map(t=>typeof t=="string"?t:t.Visualize())})}catch{return[]}}function R(e){let n="",i="",t="",u="",l=[];try{a(g=>{let p=c(e,"::a2a_capabilities::get_manifest",g),r=o=>{let f=p.Reduce(o);return f.IsNil()?"":f.Visualize()};n=r("app_id"),i=r("name"),t=r("description"),u=r("version");let m=p.Reduce("capabilities");m.IsNil()||(l=[...m.GetKeys()].map(o=>typeof o=="string"?o:o.Visualize()))})}catch{}return{app_id:n,name:i,description:t,version:u,capabilities:l,monitoring_status:"unbound"}}function h(e){let n=[];for(let i of s.values()){if(i.name===e.name)continue;let t=d(i);t.rootCid===e.cid&&n.push({name:i.name,cid:i.cid,role_id:t.roleId,bio:t.bio,monitoring:t.monitoringEnabled,capabilities:y(i)})}return n}function v(e,n){let i=s.get(n)??[...s.values()].find(t=>t.cid===n);return!i||i.name===e.name?null:d(i).rootCid===e.cid?i:null}export{y as a,R as b,h as c,v as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{b as m,e as N}from"./chunk-IB2U7K6Y.js";import{readFileSync as v}from"node:fs";import{homedir as I}from"node:os";import{join as E,resolve as p}from"node:path";var r=class extends Error{constructor(s,n){super(n);this.code=s;this.name="DaemonSelectionError"}},O=m.port,b=N,R=".ours",w=["explicit","environment","config-file"];function $(e={}){let t=e.env??process.env,s=e.readTextFile??(h=>v(h,"utf8")),n=e.homeDir??I(),l=f(t,"OURS_INSTANCE");if(l!==void 0)throw new r("INCOHERENT_SELECTION",`OURS_INSTANCE=${JSON.stringify(l)} is set, but named daemon instances are not implemented. Select the daemon with an explicit endpoint/port option or with OURS_PORT, and unset OURS_INSTANCE.`);if(e.stateDir!==void 0&&e.expectStateDir!==void 0){let h=p(e.stateDir),y=p(e.expectStateDir);if(h!==y)throw new r("INCOHERENT_SELECTION",`stateDir ${JSON.stringify(h)} and expectStateDir ${JSON.stringify(y)} name different directories. The state directory decides which token is read; the expected one decides which daemon that token may be sent to. Reconcile them, or pass only one.`)}let o=U(e.configPath,f(t,"OURS_CONFIG")),a=o?_(o.value,s):{},i=T(e.port,k(f(t,"OURS_PORT")),a.port,O),c=T(e.stateDir??e.expectStateDir,f(t,"OURS_STATE_DIR"),a.stateDir,E(n,R)),d={value:p(c.value),source:c.source},g=e.endpoint!==void 0?{value:A(e.endpoint),source:"explicit"}:{value:`http://127.0.0.1:${i.value}`,source:i.source},S=f(t,"OURS_API_TOKEN");x({endpointSelected:e.endpoint!==void 0||i.source!=="default",endpointSource:g.source,stateDirIntentional:w.includes(d.source),stateDirSource:d.source,hasExplicitToken:e.token!==void 0&&e.token!=="",hasEnvToken:S!==void 0,requireExplicitSelection:e.requireExplicitSelection===!0,portSource:i.source});let D=C(e.token,S,a,d,s);return{baseUrl:g,port:i,stateDir:d,expectStateDir:e.expectStateDir!==void 0?p(e.expectStateDir):d.value,...D?{token:D}:{},...o?{configPath:o}:{}}}function J(e){return{baseUrl:e.baseUrl.value,baseUrlSource:e.baseUrl.source,port:e.port.value,portSource:e.port.source,stateDir:e.stateDir.value,stateDirSource:e.stateDir.source,expectStateDir:e.expectStateDir,tokenSource:e.token?.source??"none",configPath:e.configPath?.value??null}}function x(e){if(e.requireExplicitSelection){if(e.endpointSource==="default"&&e.portSource==="default")throw u(`requireExplicitSelection is set, but no daemon was selected. Pass endpoint/port, set OURS_PORT, or point OURS_CONFIG at a config file. Refusing the built-in default 127.0.0.1:${O}.`);if(!e.stateDirIntentional)throw u("requireExplicitSelection is set, but the state directory is the built-in default. Every auth-affecting field must be chosen deliberately: pass stateDir or expectStateDir, set OURS_STATE_DIR, or name a config file. Refusing before reading any token or opening any socket.")}if(e.endpointSelected&&!e.stateDirIntentional)throw u(`the endpoint was selected (source: ${e.endpointSource}) but the state directory is the built-in default. A daemon's API token belongs to one state directory, so reading the default token and sending it to a separately chosen endpoint would disclose a credential to it. Select the state directory too: stateDir, expectStateDir, OURS_STATE_DIR, or one config file. An explicit token alone is not enough \u2014 without an expected state directory there is nothing to assert the endpoint against before the token is sent.`);if(e.hasEnvToken&&!e.stateDirIntentional)throw u("OURS_API_TOKEN is set, but the state directory is the built-in default. An environment token is process-wide and authenticates to every daemon it is offered to, so it requires an explicitly expected state directory: pass stateDir or expectStateDir, or set OURS_STATE_DIR.");if(e.hasExplicitToken&&!e.stateDirIntentional)throw u("an explicit token was given, but the state directory is the built-in default, so there would be nothing to assert the daemon against before the token is sent. Pass expectStateDir (or stateDir) naming the state directory that token belongs to.")}function u(e){return new r("INCOHERENT_SELECTION",e)}function C(e,t,s,n,l){if(e!==void 0&&e!=="")return{value:e,source:"explicit"};if(t!==void 0)return{value:t,source:"environment"};let o=s.apiToken?.trim();if(o)return{value:o,source:"config-file"};try{let a=l(E(n.value,b)).trim();if(a)return{value:a,source:"token-file"}}catch{}}function _(e,t){let s;try{s=t(e)}catch{throw new r("CONFIG_UNREADABLE",`the daemon config file ${JSON.stringify(e)} could not be read.`)}let n;try{n=JSON.parse(s)}catch{throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} is not valid JSON.`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} is not a JSON object.`);let l=n,o={},a=l.port;if(a!==void 0){if(typeof a!="number"||!Number.isInteger(a)||a<1||a>65535)throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} declares an invalid port; expected an integer 1-65535.`);o.port=a}let i=l.stateDir;if(i!==void 0){if(typeof i!="string"||i.trim()==="")throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} declares an invalid stateDir; expected a non-empty string.`);o.stateDir=i}let c=l.apiToken;if(c!==void 0){if(typeof c!="string"||c.trim()==="")throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} declares an invalid apiToken; expected a non-empty string.`);o.apiToken=c}let d=l.apiVisibility;if(d!==void 0){if(d!=="owner"&&d!=="shared"&&d!=="open")throw new r("CONFIG_INVALID",`the daemon config file ${JSON.stringify(e)} declares an unknown apiVisibility ${JSON.stringify(d)}; expected "owner", "shared" or "open".`);o.apiVisibility=d}return o}function f(e,t){let s=e[t];if(s===void 0)return;let n=s.trim();return n===""?void 0:n}function k(e){if(e===void 0)return;let t=Number.parseInt(e,10);if(!Number.isInteger(t)||t<1||t>65535)throw new r("INCOHERENT_SELECTION",`OURS_PORT=${JSON.stringify(e)} is not a TCP port between 1 and 65535.`);return t}function A(e){return e.endsWith("/")?e.slice(0,-1):e}function T(e,t,s,n){return e!==void 0?{value:e,source:"explicit"}:t!==void 0?{value:t,source:"environment"}:s!==void 0?{value:s,source:"config-file"}:{value:n,source:"default"}}function U(e,t){if(e!==void 0)return{value:e,source:"explicit"};if(t!==void 0)return{value:t,source:"environment"}}async function G(e,t={}){let s=t.fetch??globalThis.fetch,n=new AbortController,l=setTimeout(()=>n.abort(),t.timeoutMs??5e3),o;try{let i=await s(`${e.baseUrl.value}/state-dir`,{signal:n.signal});if(!i.ok)throw new r("INCOHERENT_SELECTION",`${e.baseUrl.value}/state-dir answered HTTP ${i.status}, so the daemon at that address could not be identified. Refusing to send a credential to it.`);o=await i.json()}catch(i){throw i instanceof r?i:new r("INCOHERENT_SELECTION",`${e.baseUrl.value}/state-dir could not be reached (${String(i)}), so the daemon at that address could not be identified. Refusing to send a credential to it.`)}finally{clearTimeout(l)}let a=typeof o.stateDir=="string"?p(o.stateDir):null;if(a===null)throw new r("INCOHERENT_SELECTION",`${e.baseUrl.value}/state-dir did not report a state directory, so this is not an ours daemon or not one this client understands. Refusing to send a credential to it.`);if(a!==e.expectStateDir)throw new r("INCOHERENT_SELECTION",`the daemon at ${e.baseUrl.value} owns state directory ${JSON.stringify(a)}, but this selection expects ${JSON.stringify(e.expectStateDir)}. The token belongs to the expected directory, so it is NOT being sent. Point the endpoint and the state directory at the same daemon.`)}export{r as a,O as b,b as c,$ as d,J as e,G as f};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as E,b as k,d as A}from"./chunk-HCIVLHKC.js";import{E as T,F as I,G as _,J as R,S as x,x as y}from"./chunk-NQQ4GSVI.js";import{a as S}from"./chunk-X4RVJ5VL.js";import{a as l,d as u,e as d,g as w}from"./chunk-RAGUBE4Y.js";import{a as $,c as m,q as v}from"./chunk-Q3UVLSCX.js";import{c as s,i as r}from"./chunk-HSVIKO4D.js";import{join as b}from"node:path";import*as i from"node:fs";function D(e){try{$.remove_packet(e.cid)}catch(t){r(`remove_packet(${e.cid}) failed:`,String(t))}m.delete(e.name);try{x(e)}catch(t){r(`failed to unpublish "${e.name}" from the contact book:`,String(t))}l.has(e.name)&&(l.delete(e.name),w()),e.name===k&&(E(null),A());try{i.rmSync(e.dir,{recursive:!0,force:!0}),y.delete(e.name)}catch(t){return`deleting ${e.dir} failed: ${String(t)}`}return null}function F(e,t){let n=e.temp;return n?(n.closing||(n.closing=(async()=>{r(`[${e.name}] closing temporary identity (${t})`);let o=[];try{o=T(a=>S(_(e,"::a2a_messaging::list_contacts",a)))}catch(a){r(`[${e.name}] contact snapshot failed during close (continuing with local cleanup):`,String(a))}let p=0,c=0;u.add(e.name);try{for(let a of o)try{await I(async C=>{let h=(await R(e,"::a2a_messaging::remove_contact",{contact:a.container_id},C)).Reduce("notified");return h.IsNil()?!1:h.GetBoolean()})?p++:c++}catch(g){c++,r(`[${e.name}] remove-me to ${a.container_id} failed (continuing):`,String(g))}}finally{u.delete(e.name)}let f=D(e);return f?r(`[${e.name}] temporary identity close: LOCAL DELETE FAILED \u2014 ${f}`):r(`[${e.name}] temporary identity closed: ${o.length} contact(s), ${p} remove-me notice(s) queued, ${c} not sent (delivery unverified by design)`),{attempted:o.length,notified:p,failed:c,deleteError:f}})()),n.closing):Promise.reject(new Error(`identity "${e.name}" is not temporary`))}function H(){for(let e of[...m.values()]){let t=e.temp;if(!t||t.closing||d(t.owner.pid))continue;let n=l.get(e.name);n&&d(n.pid)||F(e,`stale lease \u2014 owner pid ${t.owner.pid} is dead`).catch(o=>r(`[${e.name}] stale-temp reclaim failed:`,String(o)))}}function J(){if(i.existsSync(s))for(let e of i.readdirSync(s,{withFileTypes:!0})){if(!e.isDirectory()||m.has(e.name))continue;let t=b(s,e.name),n=v(t);if(!(!n||d(n.owner.pid)))try{i.rmSync(t,{recursive:!0,force:!0}),y.delete(e.name),r(`[${e.name}] removed orphaned temporary-identity dir (owner pid ${n.owner.pid} dead, no live packet)`)}catch(o){r(`[${e.name}] failed to remove orphaned temporary-identity dir:`,String(o))}}}export{D as a,F as b,H as c,J as d};
2
+ import{a as E,b as k,d as A}from"./chunk-Z6KWRSU7.js";import{E as T,F as I,G as _,J as R,S as x,x as y}from"./chunk-2YUTV62M.js";import{a as S}from"./chunk-KCMMTTYK.js";import{a as l,d as u,e as d,g as w}from"./chunk-3AK2WAWH.js";import{a as $,c as m,q as v}from"./chunk-MYLXP6TV.js";import{c as s,i as r}from"./chunk-UPZVGDSI.js";import{join as b}from"node:path";import*as i from"node:fs";function D(e){try{$.remove_packet(e.cid)}catch(t){r(`remove_packet(${e.cid}) failed:`,String(t))}m.delete(e.name);try{x(e)}catch(t){r(`failed to unpublish "${e.name}" from the contact book:`,String(t))}l.has(e.name)&&(l.delete(e.name),w()),e.name===k&&(E(null),A());try{i.rmSync(e.dir,{recursive:!0,force:!0}),y.delete(e.name)}catch(t){return`deleting ${e.dir} failed: ${String(t)}`}return null}function F(e,t){let n=e.temp;return n?(n.closing||(n.closing=(async()=>{r(`[${e.name}] closing temporary identity (${t})`);let o=[];try{o=T(a=>S(_(e,"::a2a_messaging::list_contacts",a)))}catch(a){r(`[${e.name}] contact snapshot failed during close (continuing with local cleanup):`,String(a))}let p=0,c=0;u.add(e.name);try{for(let a of o)try{await I(async C=>{let h=(await R(e,"::a2a_messaging::remove_contact",{contact:a.container_id},C)).Reduce("notified");return h.IsNil()?!1:h.GetBoolean()})?p++:c++}catch(g){c++,r(`[${e.name}] remove-me to ${a.container_id} failed (continuing):`,String(g))}}finally{u.delete(e.name)}let f=D(e);return f?r(`[${e.name}] temporary identity close: LOCAL DELETE FAILED \u2014 ${f}`):r(`[${e.name}] temporary identity closed: ${o.length} contact(s), ${p} remove-me notice(s) queued, ${c} not sent (delivery unverified by design)`),{attempted:o.length,notified:p,failed:c,deleteError:f}})()),n.closing):Promise.reject(new Error(`identity "${e.name}" is not temporary`))}function H(){for(let e of[...m.values()]){let t=e.temp;if(!t||t.closing||d(t.owner.pid))continue;let n=l.get(e.name);n&&d(n.pid)||F(e,`stale lease \u2014 owner pid ${t.owner.pid} is dead`).catch(o=>r(`[${e.name}] stale-temp reclaim failed:`,String(o)))}}function J(){if(i.existsSync(s))for(let e of i.readdirSync(s,{withFileTypes:!0})){if(!e.isDirectory()||m.has(e.name))continue;let t=b(s,e.name),n=v(t);if(!(!n||d(n.owner.pid)))try{i.rmSync(t,{recursive:!0,force:!0}),y.delete(e.name),r(`[${e.name}] removed orphaned temporary-identity dir (owner pid ${n.owner.pid} dead, no live packet)`)}catch(o){r(`[${e.name}] failed to remove orphaned temporary-identity dir:`,String(o))}}}export{D as a,F as b,H as c,J as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{c as p,h as w,j as I,k as b,l as x}from"./chunk-DIRW7I4S.js";import{b as z}from"./chunk-P55RJGZU.js";import{m as h}from"./chunk-Q3UVLSCX.js";import{b as _}from"./chunk-HSVIKO4D.js";import{basename as M,join as $}from"node:path";import{createHash as S,randomUUID as G}from"node:crypto";import{mkdir as C,open as O,rename as v,unlink as N,lstat as D}from"node:fs/promises";import{brotliCompressSync as K,brotliDecompressSync as P}from"node:zlib";function Z(e){let n=[];if(e.IsNil())return n;for(let i of e.GetKeys()){let t=e.Reduce(i);t.IsNil()||n.push({name:t.Reduce("name").Visualize(),container_id:t.Reduce("container_id").Visualize()})}return n}function ee(e){let n={};if(e.IsNil())return n;for(let i of e.GetKeys()){let t=e.Reduce(i);t.IsNil()||(n[typeof i=="string"?i:i.Visualize()]=t.Visualize())}return n}function te(e){let n=[];if(e.IsNil())return n;for(let i=0;;i++){let t=e.Reduce(i);if(t.IsNil())break;let s=t.Reduce("reply_to"),o=null;if(!s.IsNil()){o={wire_id:s.Reduce("wire_id").Visualize()};let r=s.Reduce("sentence");r.IsNil()||(o.sentence=parseInt(r.Visualize(),10))}n.push({msg_id:parseInt(t.Reduce("msg_id").Visualize(),10),sender_id:t.Reduce("sender_id").Visualize(),sender_name:t.Reduce("sender_name").Visualize(),text:t.Reduce("text").Visualize(),date:t.Reduce("date").Visualize(),status:t.Reduce("status").Visualize(),wire_id:t.Reduce("wire_id").Visualize(),reply_to:o})}return n}function ie(e){let n=[];if(e.IsNil())return n;for(let i=0;;i++){let t=e.Reduce(i);if(t.IsNil())break;let s=t.Reduce("filename").Visualize(),o=t.Reduce("mime").Visualize()||"application/octet-stream",r=t.Reduce("reply_to"),a=null;if(!r.IsNil()){a={wire_id:r.Reduce("wire_id").Visualize()};let u=parseInt(r.Reduce("sentence").Visualize(),10);Number.isSafeInteger(u)&&u>0&&(a.sentence=u)}n.push({file_id:parseInt(t.Reduce("file_id").Visualize(),10),wire_id:t.Reduce("wire_id").Visualize(),from:{id:t.Reduce("sender_id").Visualize(),name:t.Reduce("sender_name").Visualize()},filename:s,mime:o,size:parseInt(t.Reduce("size").Visualize(),10),size_source:"received_payload",status:t.Reduce("status").Visualize(),date:t.Reduce("date").Visualize(),sha256:null,reply_to:a,kind:p(o,s)?"voice_message":"file"})}return n}function ne(e){if(e.length===0)return"No files received.";let n=[];for(let i of e){let t=i.kind==="voice_message"?"\u{1F3A4} voice message \xB7 ":"";n.push(` \u2022 ${t}${i.filename} (${i.mime}, ${i.size} B) from ${i.from.name} [${i.status}] {${i.wire_id}} sender_id=${i.from.id}`)}return`${n.length} file(s):
2
+ import{c as p,h as w,j as I,k as b,l as x}from"./chunk-DIRW7I4S.js";import{b as z}from"./chunk-P55RJGZU.js";import{m as h}from"./chunk-MYLXP6TV.js";import{b as _}from"./chunk-UPZVGDSI.js";import{basename as M,join as $}from"node:path";import{createHash as S,randomUUID as G}from"node:crypto";import{mkdir as C,open as O,rename as v,unlink as N,lstat as D}from"node:fs/promises";import{brotliCompressSync as K,brotliDecompressSync as P}from"node:zlib";function Z(e){let n=[];if(e.IsNil())return n;for(let i of e.GetKeys()){let t=e.Reduce(i);t.IsNil()||n.push({name:t.Reduce("name").Visualize(),container_id:t.Reduce("container_id").Visualize()})}return n}function ee(e){let n={};if(e.IsNil())return n;for(let i of e.GetKeys()){let t=e.Reduce(i);t.IsNil()||(n[typeof i=="string"?i:i.Visualize()]=t.Visualize())}return n}function te(e){let n=[];if(e.IsNil())return n;for(let i=0;;i++){let t=e.Reduce(i);if(t.IsNil())break;let s=t.Reduce("reply_to"),o=null;if(!s.IsNil()){o={wire_id:s.Reduce("wire_id").Visualize()};let r=s.Reduce("sentence");r.IsNil()||(o.sentence=parseInt(r.Visualize(),10))}n.push({msg_id:parseInt(t.Reduce("msg_id").Visualize(),10),sender_id:t.Reduce("sender_id").Visualize(),sender_name:t.Reduce("sender_name").Visualize(),text:t.Reduce("text").Visualize(),date:t.Reduce("date").Visualize(),status:t.Reduce("status").Visualize(),wire_id:t.Reduce("wire_id").Visualize(),reply_to:o})}return n}function ie(e){let n=[];if(e.IsNil())return n;for(let i=0;;i++){let t=e.Reduce(i);if(t.IsNil())break;let s=t.Reduce("filename").Visualize(),o=t.Reduce("mime").Visualize()||"application/octet-stream",r=t.Reduce("reply_to"),a=null;if(!r.IsNil()){a={wire_id:r.Reduce("wire_id").Visualize()};let u=parseInt(r.Reduce("sentence").Visualize(),10);Number.isSafeInteger(u)&&u>0&&(a.sentence=u)}n.push({file_id:parseInt(t.Reduce("file_id").Visualize(),10),wire_id:t.Reduce("wire_id").Visualize(),from:{id:t.Reduce("sender_id").Visualize(),name:t.Reduce("sender_name").Visualize()},filename:s,mime:o,size:parseInt(t.Reduce("size").Visualize(),10),size_source:"received_payload",status:t.Reduce("status").Visualize(),date:t.Reduce("date").Visualize(),sha256:null,reply_to:a,kind:p(o,s)?"voice_message":"file"})}return n}function ne(e){if(e.length===0)return"No files received.";let n=[];for(let i of e){let t=i.kind==="voice_message"?"\u{1F3A4} voice message \xB7 ":"";n.push(` \u2022 ${t}${i.filename} (${i.mime}, ${i.size} B) from ${i.from.name} [${i.status}] {${i.wire_id}} sender_id=${i.from.id}`)}return`${n.length} file(s):
3
3
  ${n.join(`
4
4
  `)}`}async function j(e,n,i){await C(e,{recursive:!0,mode:448});let t=await D(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("received-files directory is not a safe directory");let s=$(e,`.${M(n)}.${G()}.tmp`),o=await O(s,"wx",384);try{await o.writeFile(i),await o.sync()}catch(r){throw await o.close().catch(()=>{}),await N(s).catch(()=>{}),r}await o.close();try{await v(s,n)}catch(r){throw await N(s).catch(()=>{}),r}}async function re(e,n){let i=[];if(n.IsNil())return{text:"No new files.",files:i};let t=h(e),s=[];for(let o=0;;o++){let r=n.Reduce(o);if(r.IsNil())break;let a=r.Reduce("filename").Visualize(),u=r.Reduce("mime").Visualize()||"application/octet-stream",f=r.Reduce("sender_name").Visualize(),A=r.Reduce("sender_id").Visualize(),F=parseInt(r.Reduce("file_id").Visualize(),10),B=r.Reduce("date").Visualize(),d=r.Reduce("wire_id").Visualize(),c=Buffer.from(r.Reduce("data").GetBinary()),V=S("sha256").update(c).digest("hex"),l=$(t,`${d}-${z(a)}`);await j(t,l,c);let g={file_id:F,wire_id:d,from:{id:A,name:f},filename:a,path:l,mime:u,size:c.length,sha256:V,status:"processed",date:B,kind:p(u,a)?"voice_message":"file",sender:f};if(p(u,a)){let y=w(_.stt),m;if(!y.ready)m={kind:"unconfigured",reason:y.reason};else{let R=await I(c,a,u,_.stt);m=R.ok?{kind:"transcript",text:R.text}:{kind:"failed",error:R.error}}g.transcription=b(y,m,{audioPath:l,wireId:d}),s.push(x({sender:f,wire:d,savedPath:l,sizeBytes:c.length},m)),i.push(g);continue}i.push(g),s.push(` \u2022 ${a} (${u}, ${c.length} B, sha256 ${V}) from ${f} \u2192 ${l} {${d}}`)}return s.length===0?{text:"No new files.",files:i}:{text:`${s.length} new file(s) written to your identity's files dir \u2014 paths + metadata below (bytes stay on disk, never in this result). If your OS user can read the path, use it directly; otherwise use save_file({ wire_id, dest_path }) to stream a copy to a path you can write:
5
5
  ${s.join(`
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{a as c}from"./chunk-2W4CPM4Q.js";import{J as d}from"./chunk-UM73BGFH.js";import{b as g,e as f,f as p}from"./chunk-Z6KWRSU7.js";import{F as o,J as n}from"./chunk-2YUTV62M.js";import{c as m}from"./chunk-MYLXP6TV.js";import{i as u}from"./chunk-UPZVGDSI.js";async function h(i,s){let e=c(i),{bio:t}=s;try{await o(async a=>{await n(e,"::a2a_messaging::set_my_bio",{bio:t},a)});let r=0;if(e.name===g){for(let a of m.values())if(a.name!==e.name&&f(a).rootCid===e.cid)try{await p(e,a),r+=1}catch(y){u(`failed to refresh root profile in role "${a.name}":`,String(y))}}return{identity:e.name,rolesRefreshed:r}}catch(r){throw d("set_bio",String(r))}}async function x(i){let s=c(i);try{return await o(async e=>{let t=await n(s,"::a2a_messaging::advertise_migrate",{},e);return{wasAdvertising:t.Reduce("was_advertising").Visualize()==="true",advertising:t.Reduce("advertising").Visualize()==="true",offers:parseInt(t.Reduce("offers_initiated").Visualize(),10)||0}})}catch(e){throw d("advertise_migrate",String(e))}}async function P(i,s){let e=c(i),{persona:t}=s;try{return await o(async r=>{await n(e,"::a2a_messaging::set_my_persona",{persona:t},r)}),{identity:e.name}}catch(r){throw d("set_persona",String(r))}}async function C(i){let s=c(i);try{return{readvertised:await o(async t=>(await n(s,"::a2a_messaging::readvertise_on_upgrade",{},t)).Reduce("readvertised").Visualize())}}catch(e){throw d("readvertise_on_upgrade",String(e))}}export{h as a,x as b,P as c,C as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as l}from"./chunk-T25JIPX5.js";import{e as o}from"./chunk-HCIVLHKC.js";import{F as p,G as f,J as m}from"./chunk-NQQ4GSVI.js";import{c as r}from"./chunk-Q3UVLSCX.js";import{i as u}from"./chunk-HSVIKO4D.js";var A=()=>d,d=!0,C=d?2:1;function g(e,n){let a=[];for(let t of r.values()){if(t.name===e.name)continue;let i=o(t);if(i.rootCid!==e.cid)continue;let c=f(t,"::actor::export_address_document_native",n);a.push({cid:c.Reduce("identity").Reduce("container_id"),role_id:i.roleId,name:t.name,bio:i.bio,persona:i.persona,caps:l(t),child_ad:c})}return a}var s=new Set;async function y(e){if(!s.has(e.name)){s.add(e.name);try{await p(async n=>{await m(e,"::a2a_cluster::reconcile",{pending_handle:"",children:g(e,n)},n)})}catch(n){u(`[${e.name}] cluster sweep failed:`,String(n))}finally{s.delete(e.name)}}}var w=6e4;function T(){setInterval(()=>{if(d)for(let e of r.values())o(e).roleId===""&&y(e)},w).unref()}export{A as a,C as b,y as c,T as d};
2
+ import{a as l}from"./chunk-AEWWZ67F.js";import{e as o}from"./chunk-Z6KWRSU7.js";import{F as p,G as f,J as m}from"./chunk-2YUTV62M.js";import{c as r}from"./chunk-MYLXP6TV.js";import{i as u}from"./chunk-UPZVGDSI.js";var A=()=>d,d=!0,C=d?2:1;function g(e,n){let a=[];for(let t of r.values()){if(t.name===e.name)continue;let i=o(t);if(i.rootCid!==e.cid)continue;let c=f(t,"::actor::export_address_document_native",n);a.push({cid:c.Reduce("identity").Reduce("container_id"),role_id:i.roleId,name:t.name,bio:i.bio,persona:i.persona,caps:l(t),child_ad:c})}return a}var s=new Set;async function y(e){if(!s.has(e.name)){s.add(e.name);try{await p(async n=>{await m(e,"::a2a_cluster::reconcile",{pending_handle:"",children:g(e,n)},n)})}catch(n){u(`[${e.name}] cluster sweep failed:`,String(n))}finally{s.delete(e.name)}}}var w=6e4;function T(){setInterval(()=>{if(d)for(let e of r.values())o(e).roleId===""&&y(e)},w).unref()}export{A as a,C as b,y as c,T as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{c as i,i as a}from"./chunk-HSVIKO4D.js";import{join as n}from"node:path";import{createHash as u}from"node:crypto";import*as r from"node:fs";var m;function P(t){m=t}var v=new Map,g=null,y=null;function T(t){g=t}function I(t){y=t}var _=t=>n(i,t),d=t=>n(t,"identity.key"),h=t=>n(t,"state_data.bin"),F=t=>n(t,"notifications.log"),W=t=>n(t,"unread.json"),x=t=>n(t.dir,"files"),c=t=>n(t,"temp.json"),E=t=>u("sha256").update(t).digest("hex");function H(t,e){r.writeFileSync(c(t),JSON.stringify({v:1,owner:{token_sha256:e.owner.tokenHash,pid:e.owner.pid},created_at:e.createdAt}),{mode:384})}function M(t){try{let e=JSON.parse(r.readFileSync(c(t),"utf8"));return e.v!==1||typeof e.owner?.token_sha256!="string"||typeof e.owner?.pid!="number"?null:{owner:{tokenHash:e.owner.token_sha256,pid:e.owner.pid},createdAt:typeof e.created_at=="number"?e.created_at:0}}catch{return null}}function R(){for(let t of w()){let e=n(i,t);try{r.chmodSync(e,448)}catch(o){a(`[${t}] chmod 0700 failed:`,String(o))}for(let o of[h(e),d(e)])if(r.existsSync(o))try{r.chmodSync(o,384)}catch(s){a(`[${t}] chmod 0600 ${o} failed:`,String(s))}}}var k=t=>/^[A-Za-z0-9]+$/.test(t)&&t.length>0&&t.length<=128,$=t=>/^[A-Fa-f0-9]{64}$/.test(t),j=32;function B(t,e){if(!k(e))return null;let o=x(t),s;try{s=r.readdirSync(o)}catch{return null}let l=`${e}-`,p=s.find(f=>f.startsWith(l));return p?n(o,p):null}function w(){return r.existsSync(i)?r.readdirSync(i,{withFileTypes:!0}).filter(t=>t.isDirectory()&&r.existsSync(d(n(i,t.name)))).map(t=>t.name):[]}export{m as a,P as b,v as c,g as d,y as e,T as f,I as g,_ as h,d as i,h as j,F as k,W as l,x as m,c as n,E as o,H as p,M as q,R as r,k as s,$ as t,j as u,B as v,w};
2
+ import{c as i,i as a}from"./chunk-UPZVGDSI.js";import{join as n}from"node:path";import{createHash as u}from"node:crypto";import*as r from"node:fs";var m;function P(t){m=t}var v=new Map,g=null,y=null;function T(t){g=t}function I(t){y=t}var _=t=>n(i,t),d=t=>n(t,"identity.key"),h=t=>n(t,"state_data.bin"),F=t=>n(t,"notifications.log"),W=t=>n(t,"unread.json"),x=t=>n(t.dir,"files"),c=t=>n(t,"temp.json"),E=t=>u("sha256").update(t).digest("hex");function H(t,e){r.writeFileSync(c(t),JSON.stringify({v:1,owner:{token_sha256:e.owner.tokenHash,pid:e.owner.pid},created_at:e.createdAt}),{mode:384})}function M(t){try{let e=JSON.parse(r.readFileSync(c(t),"utf8"));return e.v!==1||typeof e.owner?.token_sha256!="string"||typeof e.owner?.pid!="number"?null:{owner:{tokenHash:e.owner.token_sha256,pid:e.owner.pid},createdAt:typeof e.created_at=="number"?e.created_at:0}}catch{return null}}function R(){for(let t of w()){let e=n(i,t);try{r.chmodSync(e,448)}catch(o){a(`[${t}] chmod 0700 failed:`,String(o))}for(let o of[h(e),d(e)])if(r.existsSync(o))try{r.chmodSync(o,384)}catch(s){a(`[${t}] chmod 0600 ${o} failed:`,String(s))}}}var k=t=>/^[A-Za-z0-9]+$/.test(t)&&t.length>0&&t.length<=128,$=t=>/^[A-Fa-f0-9]{64}$/.test(t),j=32;function B(t,e){if(!k(e))return null;let o=x(t),s;try{s=r.readdirSync(o)}catch{return null}let l=`${e}-`,p=s.find(f=>f.startsWith(l));return p?n(o,p):null}function w(){return r.existsSync(i)?r.readdirSync(i,{withFileTypes:!0}).filter(t=>t.isDirectory()&&r.existsSync(d(n(i,t.name)))).map(t=>t.name):[]}export{m as a,P as b,v as c,g as d,y as e,T as f,I as g,_ as h,d as i,h as j,F as k,W as l,x as m,c as n,E as o,H as p,M as q,R as r,k as s,$ as t,j as u,B as v,w};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as L}from"./chunk-37D5PCFY.js";import{d as D}from"./chunk-V64IUVSS.js";import{a as de,b as ce}from"./chunk-ZAXRB5MO.js";import{a as pe,d as le}from"./chunk-UELGY557.js";import{a as ae}from"./chunk-A3SXVUOC.js";import{b as ie,c as se}from"./chunk-NMYSFQBL.js";import{b as re}from"./chunk-VOYMK2OO.js";import{C as oe,a as q,b as ee,l as te,n as ne}from"./chunk-NQQ4GSVI.js";import{a as $,b as X,c as u,e as x,f as Y,g as Z}from"./chunk-RAGUBE4Y.js";import{c as I,o as Q,v as W}from"./chunk-Q3UVLSCX.js";import{a as N,b as B,c as M,d as F,e as k,g as V,h as P,i as p,m as T,p as K}from"./chunk-HSVIKO4D.js";import{createServer as he}from"node:http";import{randomUUID as we}from"node:crypto";import*as H from"node:fs";function Ie(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;let r=s;return r.jsonrpc==="2.0"&&r.method==="initialize"}var Se=["brokerUrl","port","stateDir","gcIntervalMs","apiVisibility"];function fe(s){return new Promise((r,R)=>{let h="";s.on("data",a=>h+=a),s.on("end",()=>{try{r(JSON.parse(h))}catch(a){R(a)}}),s.on("error",R)})}async function Le(s={}){try{return await ve(s)}catch(r){throw P?.failed(),p(`fatal startup error: ${r?.stack??r}`),r}}async function ve(s){if(process.env.OURS_TEST_STARTUP_FAIL==="1")throw new Error("forced startup failure (OURS_TEST_STARTUP_FAIL)");if(s.config){let t=Se.filter(e=>s.config[e]!==B[e]);if(t.length>0)throw new Error(`startDaemon(config) disagrees with the config resolved at module load (${t.join(", ")}). The engine reads its config when src/runtime/env.ts is imported, so a later override cannot move the state dir, port or broker \u2014 set OURS_* env or config.json before importing the SDK.`)}let r=s.mcp,R=r?.isInitializeRequest??Ie,h=null;if(typeof s.onIdentityNotify=="function"){let t=s.onIdentityNotify;h=(e,i)=>{t(e,i,$.get(e)?.sid??null)},q(h)}p("booting wrapper\u2026"),await ae(),de(),p(`wrapper ready (identities=${I.size}), starting HTTP server\u2026`),P?.update("server");let a={},S=new Map,v=new Map,me=3e4,j=t=>{let e=v.get(t);e?e.n++:v.set(t,{n:1,since:Date.now()})},A=t=>{let e=v.get(t);e&&--e.n<=0&&v.delete(t)},G=()=>{let t=0;for(let e of[...S.keys()]){if(e==="stdio")continue;let i=u.get(e)?.pid;if(i===void 0||i<=1||x(i))continue;let n=v.get(e);if(n&&n.n>0&&Date.now()-n.since<me)continue;let o=S.get(e);S.delete(e),delete a[e],u.delete(e),v.delete(e),o?.close().catch(()=>{}),r?.onSessionClosed?.(e),t++,p(`session ${e.slice(0,8)}\u2026 reaped (client pid ${i} dead)`)}return t},U=setInterval(()=>{G(),se()},6e4);U.unref?.();let _=1e3,ue=10*6e4,f=new Map,ge=(t,e)=>{let i=Array.isArray(e)?e:[e];for(let n of i){let o=n;!o||typeof o!="object"||o.id===void 0||o.id===null||typeof o.method!="string"||f.set(`${t}:${String(o.id)}`,{method:o.method,at:Date.now()})}if(f.size>_){let n=Date.now()-ue;for(let[o,d]of f)if(d.at<n&&f.delete(o),f.size<=_)break;for(;f.size>_;){let o=f.keys().next();if(o.done)break;f.delete(o.value)}}},ye=(t,e)=>{try{let i=e instanceof Error?e.message:String(e),n=/No connection established for request ID:\s*(\S+)/.exec(i);if(!n)return;let o=n[1],d=f.get(`${t}:${o}`);f.delete(`${t}:${o}`),p(`UNDELIVERABLE RESPONSE session=${t.slice(0,8)}\u2026 request_id=${o} method=${d?.method??"unknown"} age_ms=${d?Date.now()-d.at:"unknown"} at=${new Date().toISOString()} \u2014 the answer was produced but its stream was already gone`)}catch{}},g=he(async(t,e)=>{let i=new URL(t.url,`http://localhost:${k}`);if(t.method==="GET"&&i.pathname==="/state-dir"){e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({stateDir:M,version:N,compat:1}));return}if(t.method==="GET"&&(i.pathname==="/version"||i.pathname==="/info")){e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({name:"ours",version:N,compat:1,protocol:re,pid:process.pid,stateDir:M}));return}if(t.method==="GET"&&i.pathname==="/identities"){if(!T(t,e))return;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({identities:[...I.values()].map(n=>({name:n.name,...n.temp?{temporary:!0,stale:!x(n.temp.owner.pid)}:{}}))}));return}if(t.method==="GET"&&i.pathname==="/unread"){if(!T(t,e))return;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(ne()));return}{let n=/^\/identities\/([^/]+)\/notifications$/.exec(i.pathname);if(t.method==="GET"&&n){if(!T(t,e))return;let o=decodeURIComponent(n[1]);if(K(o)!==null){e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"invalid identity name"}));return}await te(t,e,o,i.searchParams.get("since"));return}}{let n=/^\/files\/([^/]+)$/.exec(i.pathname);if(t.method==="GET"&&n){if(!T(t,e))return;let o=decodeURIComponent(n[1]),d=t.headers["x-ours-lease-token"],w=typeof d=="string"&&d?Y(d):void 0,m=w?I.get(w.identity):void 0;if(!m){e.writeHead(401,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"no identity bound to this session"}));return}let y=W(m,o);if(!y){e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"no such file for the bound identity (run get_files first, or it belongs to another identity)"}));return}try{let l=H.statSync(y);e.writeHead(200,{"Content-Type":"application/octet-stream","Content-Length":String(l.size)});let E=H.createReadStream(y);E.on("error",()=>{try{e.destroy()}catch{}}),E.pipe(e)}catch(l){e.writeHead(500,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:`failed to read file: ${String(l)}`}))}return}}if(i.pathname.startsWith(pe)){await le(t,e,i.pathname,fe);return}if(i.pathname!=="/mcp"||!r){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not found");return}if(T(t,e))try{if(t.method==="POST"){let n=await fe(t),o=t.headers["mcp-session-id"],d=t.headers["x-ours-lease-token"],w=t.headers["x-ours-client-pid"],m=w?parseInt(w,10):void 0,y={token:d,pid:Number.isInteger(m)?m:void 0};if(o&&a[o]){u.set(o,y),ge(o,n),j(o),D(e);try{await a[o].handleRequest(t,e,n)}finally{A(o)}}else if(!o&&R(n)){G();let l=r.createTransport({sessionIdGenerator:()=>we(),onsessioninitialized:c=>{a[c]=l,u.set(c,y),S.set(c,C),r.onSessionInitialized?.(c,C),p(`session ${c.slice(0,8)}\u2026 initialized`)}}),E={sessionId:()=>l.sessionId??"pending",leaseToken:()=>u.get(l.sessionId??"pending")?.token,clientPid:()=>u.get(l.sessionId??"pending")?.pid},C=r.createServer(E);C.server.onerror=c=>ye(l.sessionId??"pending",c),l.onclose=()=>{let c=l.sessionId;c&&(delete a[c],S.delete(c),u.delete(c),r.onSessionClosed?.(c),p(`session ${c.slice(0,8)}\u2026 closed (lease kept)`))},await C.connect(l),D(e),await l.handleRequest(t,e,n)}else e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID"},id:null}))}else if(t.method==="GET"){let n=t.headers["mcp-session-id"];if(!n||!a[n]){e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Invalid or missing session ID");return}j(n),D(e);try{await a[n].handleRequest(t,e)}finally{A(n)}}else if(t.method==="DELETE"){let n=t.headers["mcp-session-id"];if(!n||!a[n]){e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Invalid or missing session ID");return}let o=u.get(n)?.token??t.headers["x-ours-lease-token"];if(o){for(let[d,w]of[...$]){if(w.token!==o)continue;$.delete(d);let m=I.get(d);m?.temp&&m.temp.owner.tokenHash===Q(o)&&!m.temp.closing&&ie(m,"owning session released its lease").catch(y=>p(`[${d}] close on lease release failed:`,String(y)))}X.delete(o),Z(),p(`lease released by token \u2026${o.slice(-6)}`)}await a[n].handleRequest(t,e)}else e.writeHead(405,{"Content-Type":"text/plain"}),e.end("Method not allowed")}catch(n){p("HTTP handler error:",String(n)),e.headersSent||(e.writeHead(500,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})))}});g.requestTimeout=0,await new Promise((t,e)=>{let i=n=>e(n);g.once("error",i),g.listen(k,"127.0.0.1",()=>{g.off("error",i),P?.ready(),p(`MCP server v${s.version??N} ready (transport=http, port=${k}, visibility=${V}, identities=${I.size}, state=${M}, broker=${F})`),t()})});let z=!1,J=async()=>{if(!z){z=!0,clearInterval(U),ce();for(let t of Object.keys(a)){try{await a[t].close()}catch{}delete a[t]}S.clear();for(let t of I.values())try{oe(t)}catch(e){p(`[${t.name}] shutdown save failed:`,String(e))}g.closeAllConnections?.()}},O=async()=>{p("shutting down\u2026"),await J(),g.close(),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O);let b=g.address();return{port:typeof b=="object"&&b!==null?b.port:k,close:async()=>{process.off("SIGINT",O),process.off("SIGTERM",O),h&&ee(h),await J(),await new Promise(t=>g.close(()=>t()))}}}export{Le as a};
2
+ import{a as L}from"./chunk-37D5PCFY.js";import{d as D}from"./chunk-V64IUVSS.js";import{a as de,b as ce}from"./chunk-XST3WFRG.js";import{a as pe,d as le}from"./chunk-ACYEO2FM.js";import{a as ae}from"./chunk-X5RROKTP.js";import{b as ie,c as se}from"./chunk-JS5YFY7A.js";import{b as re}from"./chunk-MRCIRJYN.js";import{C as oe,a as q,b as ee,l as te,n as ne}from"./chunk-2YUTV62M.js";import{a as $,b as X,c as u,e as x,f as Y,g as Z}from"./chunk-3AK2WAWH.js";import{c as I,o as Q,v as W}from"./chunk-MYLXP6TV.js";import{a as N,b as B,c as M,d as F,e as k,g as V,h as P,i as p,m as T,p as K}from"./chunk-UPZVGDSI.js";import{createServer as he}from"node:http";import{randomUUID as we}from"node:crypto";import*as H from"node:fs";function Ie(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;let r=s;return r.jsonrpc==="2.0"&&r.method==="initialize"}var Se=["brokerUrl","port","stateDir","gcIntervalMs","apiVisibility"];function fe(s){return new Promise((r,R)=>{let h="";s.on("data",a=>h+=a),s.on("end",()=>{try{r(JSON.parse(h))}catch(a){R(a)}}),s.on("error",R)})}async function Le(s={}){try{return await ve(s)}catch(r){throw P?.failed(),p(`fatal startup error: ${r?.stack??r}`),r}}async function ve(s){if(process.env.OURS_TEST_STARTUP_FAIL==="1")throw new Error("forced startup failure (OURS_TEST_STARTUP_FAIL)");if(s.config){let t=Se.filter(e=>s.config[e]!==B[e]);if(t.length>0)throw new Error(`startDaemon(config) disagrees with the config resolved at module load (${t.join(", ")}). The engine reads its config when src/runtime/env.ts is imported, so a later override cannot move the state dir, port or broker \u2014 set OURS_* env or config.json before importing the SDK.`)}let r=s.mcp,R=r?.isInitializeRequest??Ie,h=null;if(typeof s.onIdentityNotify=="function"){let t=s.onIdentityNotify;h=(e,i)=>{t(e,i,$.get(e)?.sid??null)},q(h)}p("booting wrapper\u2026"),await ae(),de(),p(`wrapper ready (identities=${I.size}), starting HTTP server\u2026`),P?.update("server");let a={},S=new Map,v=new Map,me=3e4,j=t=>{let e=v.get(t);e?e.n++:v.set(t,{n:1,since:Date.now()})},A=t=>{let e=v.get(t);e&&--e.n<=0&&v.delete(t)},G=()=>{let t=0;for(let e of[...S.keys()]){if(e==="stdio")continue;let i=u.get(e)?.pid;if(i===void 0||i<=1||x(i))continue;let n=v.get(e);if(n&&n.n>0&&Date.now()-n.since<me)continue;let o=S.get(e);S.delete(e),delete a[e],u.delete(e),v.delete(e),o?.close().catch(()=>{}),r?.onSessionClosed?.(e),t++,p(`session ${e.slice(0,8)}\u2026 reaped (client pid ${i} dead)`)}return t},U=setInterval(()=>{G(),se()},6e4);U.unref?.();let _=1e3,ue=10*6e4,f=new Map,ge=(t,e)=>{let i=Array.isArray(e)?e:[e];for(let n of i){let o=n;!o||typeof o!="object"||o.id===void 0||o.id===null||typeof o.method!="string"||f.set(`${t}:${String(o.id)}`,{method:o.method,at:Date.now()})}if(f.size>_){let n=Date.now()-ue;for(let[o,d]of f)if(d.at<n&&f.delete(o),f.size<=_)break;for(;f.size>_;){let o=f.keys().next();if(o.done)break;f.delete(o.value)}}},ye=(t,e)=>{try{let i=e instanceof Error?e.message:String(e),n=/No connection established for request ID:\s*(\S+)/.exec(i);if(!n)return;let o=n[1],d=f.get(`${t}:${o}`);f.delete(`${t}:${o}`),p(`UNDELIVERABLE RESPONSE session=${t.slice(0,8)}\u2026 request_id=${o} method=${d?.method??"unknown"} age_ms=${d?Date.now()-d.at:"unknown"} at=${new Date().toISOString()} \u2014 the answer was produced but its stream was already gone`)}catch{}},g=he(async(t,e)=>{let i=new URL(t.url,`http://localhost:${k}`);if(t.method==="GET"&&i.pathname==="/state-dir"){e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({stateDir:M,version:N,compat:1}));return}if(t.method==="GET"&&(i.pathname==="/version"||i.pathname==="/info")){e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({name:"ours",version:N,compat:1,protocol:re,pid:process.pid,stateDir:M}));return}if(t.method==="GET"&&i.pathname==="/identities"){if(!T(t,e))return;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({identities:[...I.values()].map(n=>({name:n.name,...n.temp?{temporary:!0,stale:!x(n.temp.owner.pid)}:{}}))}));return}if(t.method==="GET"&&i.pathname==="/unread"){if(!T(t,e))return;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(ne()));return}{let n=/^\/identities\/([^/]+)\/notifications$/.exec(i.pathname);if(t.method==="GET"&&n){if(!T(t,e))return;let o=decodeURIComponent(n[1]);if(K(o)!==null){e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"invalid identity name"}));return}await te(t,e,o,i.searchParams.get("since"));return}}{let n=/^\/files\/([^/]+)$/.exec(i.pathname);if(t.method==="GET"&&n){if(!T(t,e))return;let o=decodeURIComponent(n[1]),d=t.headers["x-ours-lease-token"],w=typeof d=="string"&&d?Y(d):void 0,m=w?I.get(w.identity):void 0;if(!m){e.writeHead(401,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"no identity bound to this session"}));return}let y=W(m,o);if(!y){e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"no such file for the bound identity (run get_files first, or it belongs to another identity)"}));return}try{let l=H.statSync(y);e.writeHead(200,{"Content-Type":"application/octet-stream","Content-Length":String(l.size)});let E=H.createReadStream(y);E.on("error",()=>{try{e.destroy()}catch{}}),E.pipe(e)}catch(l){e.writeHead(500,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:`failed to read file: ${String(l)}`}))}return}}if(i.pathname.startsWith(pe)){await le(t,e,i.pathname,fe);return}if(i.pathname!=="/mcp"||!r){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not found");return}if(T(t,e))try{if(t.method==="POST"){let n=await fe(t),o=t.headers["mcp-session-id"],d=t.headers["x-ours-lease-token"],w=t.headers["x-ours-client-pid"],m=w?parseInt(w,10):void 0,y={token:d,pid:Number.isInteger(m)?m:void 0};if(o&&a[o]){u.set(o,y),ge(o,n),j(o),D(e);try{await a[o].handleRequest(t,e,n)}finally{A(o)}}else if(!o&&R(n)){G();let l=r.createTransport({sessionIdGenerator:()=>we(),onsessioninitialized:c=>{a[c]=l,u.set(c,y),S.set(c,C),r.onSessionInitialized?.(c,C),p(`session ${c.slice(0,8)}\u2026 initialized`)}}),E={sessionId:()=>l.sessionId??"pending",leaseToken:()=>u.get(l.sessionId??"pending")?.token,clientPid:()=>u.get(l.sessionId??"pending")?.pid},C=r.createServer(E);C.server.onerror=c=>ye(l.sessionId??"pending",c),l.onclose=()=>{let c=l.sessionId;c&&(delete a[c],S.delete(c),u.delete(c),r.onSessionClosed?.(c),p(`session ${c.slice(0,8)}\u2026 closed (lease kept)`))},await C.connect(l),D(e),await l.handleRequest(t,e,n)}else e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID"},id:null}))}else if(t.method==="GET"){let n=t.headers["mcp-session-id"];if(!n||!a[n]){e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Invalid or missing session ID");return}j(n),D(e);try{await a[n].handleRequest(t,e)}finally{A(n)}}else if(t.method==="DELETE"){let n=t.headers["mcp-session-id"];if(!n||!a[n]){e.writeHead(400,{"Content-Type":"text/plain"}),e.end("Invalid or missing session ID");return}let o=u.get(n)?.token??t.headers["x-ours-lease-token"];if(o){for(let[d,w]of[...$]){if(w.token!==o)continue;$.delete(d);let m=I.get(d);m?.temp&&m.temp.owner.tokenHash===Q(o)&&!m.temp.closing&&ie(m,"owning session released its lease").catch(y=>p(`[${d}] close on lease release failed:`,String(y)))}X.delete(o),Z(),p(`lease released by token \u2026${o.slice(-6)}`)}await a[n].handleRequest(t,e)}else e.writeHead(405,{"Content-Type":"text/plain"}),e.end("Method not allowed")}catch(n){p("HTTP handler error:",String(n)),e.headersSent||(e.writeHead(500,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})))}});g.requestTimeout=0,await new Promise((t,e)=>{let i=n=>e(n);g.once("error",i),g.listen(k,"127.0.0.1",()=>{g.off("error",i),P?.ready(),p(`MCP server v${s.version??N} ready (transport=http, port=${k}, visibility=${V}, identities=${I.size}, state=${M}, broker=${F})`),t()})});let z=!1,J=async()=>{if(!z){z=!0,clearInterval(U),ce();for(let t of Object.keys(a)){try{await a[t].close()}catch{}delete a[t]}S.clear();for(let t of I.values())try{oe(t)}catch(e){p(`[${t.name}] shutdown save failed:`,String(e))}g.closeAllConnections?.()}},O=async()=>{p("shutting down\u2026"),await J(),g.close(),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O);let b=g.address();return{port:typeof b=="object"&&b!==null?b.port:k,close:async()=>{process.off("SIGINT",O),process.off("SIGTERM",O),h&&ee(h),await J(),await new Promise(t=>g.close(()=>t()))}}}export{Le as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-UM73BGFH.js";var a=class{base;leaseToken;clientPid;apiToken;fetchImpl;constructor(e){this.base=e.url.replace(/\/+$/,""),this.leaseToken=e.leaseToken,this.clientPid=e.clientPid??process.pid,this.apiToken=e.apiToken,this.fetchImpl=e.fetch??globalThis.fetch}headers(e={}){return{"x-ours-lease-token":this.leaseToken,"x-ours-client-pid":String(this.clientPid),...this.apiToken?{"x-ours-api-token":this.apiToken}:{},...e}}async post(e,s){let i=await this.fetchImpl(`${this.base}/api/v1/${e}`,{method:"POST",headers:this.headers({"content-type":"application/json"}),body:JSON.stringify(s??{})}),t;try{t=await i.json()}catch{throw new Error(`${e}: the daemon returned a non-JSON response (HTTP ${i.status})`)}if(t&&typeof t=="object"&&!Array.isArray(t)&&"error"in t){let r=t.error,o=r!==null&&typeof r=="object"&&"code"in r&&"message"in r;if(i.status===400&&o){let{code:c,message:d}=r;throw new n(c,d)}let p=o?r.message:String(r);throw new Error(`${e}: ${p} (HTTP ${i.status})`)}if(!i.ok)throw new Error(`${e}: the daemon returned HTTP ${i.status} with no error field`);return t}async get(e,s){let i=await this.fetchImpl(`${this.base}${e}`,{headers:s?this.headers():{}}),t;try{t=await i.json()}catch{throw new Error(`GET ${e}: the daemon returned a non-JSON response (HTTP ${i.status})`)}if(t&&typeof t=="object"&&"error"in t)throw new Error(`GET ${e}: ${String(t.error)} (HTTP ${i.status})`);if(!i.ok)throw new Error(`GET ${e}: the daemon returned HTTP ${i.status} with no error field`);return t}createIdentity(e){return this.post("createIdentity",e)}createTemporaryIdentity(e){return this.post("createTemporaryIdentity",e)}closeTemporaryIdentityOp(e={}){return this.post("closeTemporaryIdentityOp",e)}createRootIdentity(e){return this.post("createRootIdentity",e)}defineLocalIdentityFile(e){return this.post("defineLocalIdentityFile",e)}chooseIdentity(e){return this.post("chooseIdentity",e)}listIdentities(){return this.post("listIdentities",{})}currentIdentity(){return this.post("currentIdentity",{})}removeIdentity(e){return this.post("removeIdentity",e)}releaseLease(){return this.post("releaseLease",{})}generateInvite(e={}){return this.post("generateInvite",e)}listInvites(){return this.post("listInvites",{})}revokeInvite(e){return this.post("revokeInvite",e)}addContact(e){return this.post("addContact",e)}listContacts(){return this.post("listContacts",{})}listLocalContactBook(){return this.post("listLocalContactBook",{})}setLocalBookPolicy(e){return this.post("setLocalBookPolicy",e)}removeContact(e){return this.post("removeContact",e)}renameContact(e){return this.post("renameContact",e)}respondToIntroduction(e){return this.post("respondToIntroduction",e)}setBio(e){return this.post("setBio",e)}advertiseMigrate(){return this.post("advertiseMigrate",{})}setPersona(e){return this.post("setPersona",e)}sendMessage(e){return this.post("sendMessage",e)}sendFile(e){return this.post("sendFile",e)}listIncomingMessages(){return this.post("listIncomingMessages",{})}getMessages(){return this.post("getMessages",{})}deferMessages(e){return this.post("deferMessages",e)}listIncomingFiles(){return this.post("listIncomingFiles",{})}getFiles(e={}){return this.post("getFiles",e)}saveFileFallbackNotice(e){return this.post("saveFileFallbackNotice",e)}version(){return this.get("/version",!1)}stateDir(){return this.get("/state-dir",!1)}async identities(){return(await this.get("/identities",!0)).identities}unread(){return this.get("/unread",!0)}async*watchNotifications(e,s={}){let i=s.since??"tip",t=`/identities/${encodeURIComponent(e)}/notifications`;for(;!s.signal?.aborted;){let r;try{let o=await this.fetchImpl(`${this.base}${t}?since=${i}`,{headers:this.headers(),signal:s.signal});try{r=await o.json()}catch{throw new Error(`watchNotifications(${e}): the daemon returned a non-JSON response (HTTP ${o.status})`)}}catch(o){if(s.signal?.aborted)return;throw o}if("error"in r)throw new Error(`watchNotifications(${e}): ${r.error}`);i=r.cursor;for(let o of r.events)yield o}}async fetchFile(e){let s=await this.fetchImpl(`${this.base}/files/${encodeURIComponent(e)}`,{headers:this.headers()});if(!s.ok){let i=`HTTP ${s.status}`;try{let t=await s.json();t&&t.error!==void 0&&(i=String(t.error))}catch{}throw new Error(`fetchFile(${e}): ${i}`)}return new Uint8Array(await s.arrayBuffer())}};export{a};
2
+ import{a as n}from"./chunk-UM73BGFH.js";var a=class{base;leaseToken;clientPid;apiToken;fetchImpl;constructor(e){this.base=e.url.replace(/\/+$/,""),this.leaseToken=e.leaseToken,this.clientPid=e.clientPid??process.pid,this.apiToken=e.apiToken,this.fetchImpl=e.fetch??globalThis.fetch}headers(e={}){return{"x-ours-lease-token":this.leaseToken,"x-ours-client-pid":String(this.clientPid),...this.apiToken?{"x-ours-api-token":this.apiToken}:{},...e}}async post(e,s){let i=await this.fetchImpl(`${this.base}/api/v1/${e}`,{method:"POST",headers:this.headers({"content-type":"application/json"}),body:JSON.stringify(s??{})}),t;try{t=await i.json()}catch{throw new Error(`${e}: the daemon returned a non-JSON response (HTTP ${i.status})`)}if(t&&typeof t=="object"&&!Array.isArray(t)&&"error"in t){let r=t.error,o=r!==null&&typeof r=="object"&&"code"in r&&"message"in r;if(i.status===400&&o){let{code:c,message:d}=r;throw new n(c,d)}let p=o?r.message:String(r);throw new Error(`${e}: ${p} (HTTP ${i.status})`)}if(!i.ok)throw new Error(`${e}: the daemon returned HTTP ${i.status} with no error field`);return t}async get(e,s){let i=await this.fetchImpl(`${this.base}${e}`,{headers:s?this.headers():{}}),t;try{t=await i.json()}catch{throw new Error(`GET ${e}: the daemon returned a non-JSON response (HTTP ${i.status})`)}if(t&&typeof t=="object"&&"error"in t)throw new Error(`GET ${e}: ${String(t.error)} (HTTP ${i.status})`);if(!i.ok)throw new Error(`GET ${e}: the daemon returned HTTP ${i.status} with no error field`);return t}createIdentity(e){return this.post("createIdentity",e)}createTemporaryIdentity(e){return this.post("createTemporaryIdentity",e)}closeTemporaryIdentityOp(e={}){return this.post("closeTemporaryIdentityOp",e)}createRootIdentity(e){return this.post("createRootIdentity",e)}defineLocalIdentityFile(e){return this.post("defineLocalIdentityFile",e)}chooseIdentity(e){return this.post("chooseIdentity",e)}listIdentities(){return this.post("listIdentities",{})}currentIdentity(){return this.post("currentIdentity",{})}removeIdentity(e){return this.post("removeIdentity",e)}releaseLease(){return this.post("releaseLease",{})}generateInvite(e={}){return this.post("generateInvite",e)}listInvites(){return this.post("listInvites",{})}revokeInvite(e){return this.post("revokeInvite",e)}addContact(e){return this.post("addContact",e)}listContacts(){return this.post("listContacts",{})}listLocalContactBook(){return this.post("listLocalContactBook",{})}setLocalBookPolicy(e){return this.post("setLocalBookPolicy",e)}removeContact(e){return this.post("removeContact",e)}renameContact(e){return this.post("renameContact",e)}respondToIntroduction(e){return this.post("respondToIntroduction",e)}setBio(e){return this.post("setBio",e)}advertiseMigrate(){return this.post("advertiseMigrate",{})}readvertiseOnUpgrade(){return this.post("readvertiseOnUpgrade",{})}setPersona(e){return this.post("setPersona",e)}sendMessage(e){return this.post("sendMessage",e)}sendFile(e){return this.post("sendFile",e)}listIncomingMessages(){return this.post("listIncomingMessages",{})}getMessages(){return this.post("getMessages",{})}deferMessages(e){return this.post("deferMessages",e)}deferFiles(e){return this.post("deferFiles",e)}listIncomingFiles(){return this.post("listIncomingFiles",{})}getFiles(e={}){return this.post("getFiles",e)}saveFileFallbackNotice(e){return this.post("saveFileFallbackNotice",e)}version(){return this.get("/version",!1)}stateDir(){return this.get("/state-dir",!1)}async identities(){return(await this.get("/identities",!0)).identities}unread(){return this.get("/unread",!0)}async*watchNotifications(e,s={}){let i=s.since??"tip",t=`/identities/${encodeURIComponent(e)}/notifications`;for(;!s.signal?.aborted;){let r;try{let o=await this.fetchImpl(`${this.base}${t}?since=${i}`,{headers:this.headers(),signal:s.signal});try{r=await o.json()}catch{throw new Error(`watchNotifications(${e}): the daemon returned a non-JSON response (HTTP ${o.status})`)}}catch(o){if(s.signal?.aborted)return;throw o}if("error"in r)throw new Error(`watchNotifications(${e}): ${r.error}`);i=r.cursor;for(let o of r.events)yield o}}async fetchFile(e){let s=await this.fetchImpl(`${this.base}/files/${encodeURIComponent(e)}`,{headers:this.headers()});if(!s.ok){let i=`HTTP ${s.status}`;try{let t=await s.json();t&&t.error!==void 0&&(i=String(t.error))}catch{}throw new Error(`fetchFile(${e}): ${i}`)}return new Uint8Array(await s.arrayBuffer())}};export{a};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{e as a}from"./chunk-ZHH3PWEW.js";import{d as s,f as i,g as u,h as p}from"./chunk-IB2U7K6Y.js";import{timingSafeEqual as d}from"node:crypto";var b="0.1.1",r=s(),_=r.stateDir,k=r.brokerUrl,g=process.env.OURS_TRANSPORT??"http",E=r.port,A=r.gcIntervalMs,c=r.apiVisibility,R=Number(process.env.OURS_TEST_STARTUP_HEARTBEAT_MS||"")||void 0,N=g==="http"?a(_,{heartbeatMs:R}):null,v=(...e)=>process.stderr.write(`ours: ${e.join(" ")}
2
+ import{e as a}from"./chunk-ZHH3PWEW.js";import{d as s,f as i,g as u,h as p}from"./chunk-IB2U7K6Y.js";import{timingSafeEqual as d}from"node:crypto";var b="0.1.3",r=s(),_=r.stateDir,k=r.brokerUrl,g=process.env.OURS_TRANSPORT??"http",E=r.port,A=r.gcIntervalMs,c=r.apiVisibility,R=Number(process.env.OURS_TEST_STARTUP_HEARTBEAT_MS||"")||void 0,N=g==="http"?a(_,{heartbeatMs:R}):null,v=(...e)=>process.stderr.write(`ours: ${e.join(" ")}
3
3
  `);function S(){if(c==="open")return null;if(c==="shared"){let e=u(r);if(!e)throw new Error(`apiVisibility=shared requires an operator-supplied token so it can be distributed to cross-user agents \u2014 set OURS_API_TOKEN or "apiToken" in config (${i(r)} is not used for shared mode). Use apiVisibility=owner for a same-user-only auto-token, or =open to disable auth.`);return e}return p(r,{generate:!0}).token}var f=S();function T(e){let t=e.headers["x-ours-api-token"];if(typeof t=="string"&&t)return t;let o=e.headers.authorization;if(typeof o=="string"){let n=/^Bearer\s+(.+)$/i.exec(o.trim());if(n)return n[1]}}function h(e){if(f===null)return!0;let t=T(e);if(!t)return!1;let o=Buffer.from(t),n=Buffer.from(f);return o.length===n.length&&d(o,n)}function P(e,t){return h(e)?!0:(t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"})),!1)}var O=/^[A-Za-z0-9 _.@-]{1,64}$/,l="contact-book";function y(e){return O.test(e)?e==="."||e===".."||e.includes("/")||e.includes("\\")?"invalid name":e===l?`"${l}" is reserved for the local contact book`:e==="root.json"||e==="bindings.json"?`"${e}" is reserved for daemon bookkeeping`:null:"name must be 1-64 chars of letters, digits, space, _ . @ or -"}export{b as a,r as b,_ as c,k as d,E as e,A as f,c as g,N as h,v as i,f as j,T as k,h as l,P as m,O as n,l as o,y as p};