@reason-machines/cli-linux-x64 0.2.568 → 0.2.569
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.
- package/bin/reason +1 -1
- package/bin/vm-hands/agent-network-wnhby2hh.js +2 -0
- package/bin/vm-hands/{api-credentials-ntpwt7rg.js → api-credentials-5av6jdtt.js} +1 -1
- package/bin/vm-hands/api-j7g5mxg0.js +2 -0
- package/bin/vm-hands/{ask-relay-hfa5kzxn.js → ask-relay-q93yfzy6.js} +2 -2
- package/bin/vm-hands/connect-cli-fn0ek2c4.js +2 -0
- package/bin/vm-hands/{credentials-nfx99zxr.js → credentials-gwh93z0q.js} +1 -1
- package/bin/vm-hands/{custom-endpoint-device-5047vdn3.js → custom-endpoint-device-yvjz40qq.js} +1 -1
- package/bin/vm-hands/{desktop-components-577haqrs.js → desktop-components-gsqad6xm.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-8a4kh44t.js → hands-worker-source-j4yz7x6h.js} +1 -1
- package/bin/vm-hands/{install-receipt-rckwjqmt.js → install-receipt-7hvy0181.js} +1 -1
- package/bin/vm-hands/local-automation-zjrnxdh7.js +2 -0
- package/bin/vm-hands/local-capabilities-ka01z0mb.js +2 -0
- package/bin/vm-hands/local-display-session-vbsgwq8z.js +2 -0
- package/bin/vm-hands/local-display-video-yb4bh3t9.js +2 -0
- package/bin/vm-hands/local-managed-process-52qasdaq.js +2 -0
- package/bin/vm-hands/{local-pty-session-w0yhjdvz.js → local-pty-session-hnxtqd5m.js} +1 -1
- package/bin/vm-hands/{managed-runtime-e4cj6r2s.js → managed-runtime-80xhqysb.js} +1 -1
- package/bin/vm-hands/{network-auto-update-8f2745gk.js → network-auto-update-3036s9xr.js} +2 -2
- package/bin/vm-hands/{network-contract-ht0psj5j.js → network-contract-3jfjnv65.js} +1 -1
- package/bin/vm-hands/{network-sign-in-s00679q9.js → network-sign-in-dx5eg0xz.js} +1 -1
- package/bin/vm-hands/{permissions-74rj58e1.js → permissions-8egc93sd.js} +1 -1
- package/bin/vm-hands/{reason-hands-protocol-9r62swp0.js → reason-hands-protocol-wz7z9pzz.js} +1 -1
- package/bin/vm-hands/{serve-service-19s965ze.js → serve-service-cdfwh6pg.js} +1 -1
- package/bin/vm-hands/{status-099b2ec1.js → status-0td77s7a.js} +6 -6
- package/bin/vm-hands/{version-avq09c5d.js → version-6m3prwm9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-vvhfaxpd.js → vm-hands-entry-lite-1bdtt81g.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-9meg54bs.js → vm-hands-entry-lite-2dx59pgq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mzw2vcah.js → vm-hands-entry-lite-2zf4bqx9.js} +86 -86
- package/bin/vm-hands/{vm-hands-entry-lite-bcz4qpp6.js → vm-hands-entry-lite-3929hmh0.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-r131db1f.js → vm-hands-entry-lite-39anhpg6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mktndd2r.js → vm-hands-entry-lite-5ypg0t3q.js} +14 -14
- package/bin/vm-hands/{vm-hands-entry-lite-1as6h9ed.js → vm-hands-entry-lite-73tecmk2.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-8s5n4wps.js → vm-hands-entry-lite-7vg80fmc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y2vqwds4.js → vm-hands-entry-lite-8tjr2pqm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n9277v11.js → vm-hands-entry-lite-9c0g9ykw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0xfme8gg.js → vm-hands-entry-lite-a4fn6ye1.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-7jmt3q38.js → vm-hands-entry-lite-bpc8z6p7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-dhn0fs5e.js → vm-hands-entry-lite-cr3hypam.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-jm9jpj77.js → vm-hands-entry-lite-d7gepm66.js} +11 -11
- package/bin/vm-hands/{vm-hands-entry-lite-vha0pf8k.js → vm-hands-entry-lite-ea3cts1t.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-4kb5rq3d.js → vm-hands-entry-lite-hnsdwskm.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-3594pdj0.js → vm-hands-entry-lite-htrswrf0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bbjsnjct.js → vm-hands-entry-lite-jjv6s3mx.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-kc8p21xt.js +10 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ezkb7f6j.js → vm-hands-entry-lite-kvxf67qp.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-1cdtev4n.js → vm-hands-entry-lite-mkvey48j.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bt6skt4h.js → vm-hands-entry-lite-n31pta3n.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-bc9zq8gx.js → vm-hands-entry-lite-n6q8033g.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rpf4t8r4.js → vm-hands-entry-lite-nrr68p5x.js} +14 -14
- package/bin/vm-hands/{vm-hands-entry-lite-fp3gaa2c.js → vm-hands-entry-lite-nsaa15dt.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kzygj0q8.js → vm-hands-entry-lite-p0gtjbkp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-2qh3rat2.js → vm-hands-entry-lite-qb0tvsw7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-h5x725z8.js → vm-hands-entry-lite-sqp59sgh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ksfd234v.js → vm-hands-entry-lite-x81fqstd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8twdd0ff.js → vm-hands-entry-lite-yqzy5wp8.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-xd8v5v0e.js → vm-hands-executor-n3q4gj7p.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-nr4ncs4p.js → vm-hands-op-runner-jtd2nfyk.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-qvy5s122.js → vm-hands-runtime-912jvj9s.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/agent-network-dw7yrrwt.js +0 -2
- package/bin/vm-hands/api-xvjq0bka.js +0 -2
- package/bin/vm-hands/connect-cli-2ja7aj4w.js +0 -2
- package/bin/vm-hands/local-automation-fxdb4ynz.js +0 -2
- package/bin/vm-hands/local-capabilities-8fgrfpj4.js +0 -2
- package/bin/vm-hands/local-display-session-8b2hx1k6.js +0 -2
- package/bin/vm-hands/local-display-video-511qjgmq.js +0 -2
- package/bin/vm-hands/local-managed-process-h0fypn67.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-rd7bm9we.js +0 -10
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{w,An}from"./vm-hands-entry-lite-0xfme8gg.js";import{En}from"./vm-hands-entry-lite-sb1xtqxr.js";import{Bi,De,wt}from"./vm-hands-entry-lite-peyr9y6z.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{t,n,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";import{createHmac as Le,createPublicKey as we,randomBytes as Ae,randomUUID as G,verify as Pe}from"crypto";import{chmodSync as P,existsSync as H,mkdirSync as Ee,readFileSync as Re,realpathSync as xe,renameSync as Ne,statSync as Oe,unlinkSync as Ke,writeFileSync as Ce}from"fs";import{basename as Te,dirname as R,isAbsolute as J,join as h,resolve as Ue}from"path";var We=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var te="REASON_DESKTOP_RUNTIME",ne="REASON_DESKTOP_RUNTIME_CHANNEL",ie="REASON_DESKTOP_RUNTIME_INSTANCE_ID",re="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",it={[te]:"ARA_DESKTOP_RUNTIME",[ne]:"ARA_DESKTOP_RUNTIME_CHANNEL",[ie]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[re]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function K(e){if(e===void 0)return;if(!/^[a-f0-9]{64}$/.test(e))throw Error("Invalid desktop workspace scope.");return e}import{chmodSync as S,existsSync as y,mkdirSync as I,readFileSync as C,realpathSync as oe,renameSync as se,unlinkSync as k,writeFileSync as D}from"fs";import{createPrivateKey as ce,createPublicKey as le,generateKeyPairSync as de,randomUUID as ue,sign as pe}from"crypto";import{createRequire as ge}from"module";import{homedir as fe,platform as M}from"os";import{dirname as ye,join as v}from"path";var T=1,ve=16384,_=65536,_e=128,be=128,j=65536;class a extends Error{code;nativeStatus;constructor(e,r){super(`Reason Device proof boundary failed (${e}).${r===void 0?"":` Native status: ${r}.`}`);this.code=e;this.nativeStatus=r;this.name="LocalCredentialBoundaryError"}}function V(e){if(e.code==="proof_key_read_failed"&&e.nativeStatus===-25300)return"proof_key_missing";switch(e.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return e.code}}var L=null;function B(){if(!L)try{L=ge(import.meta.url)("bun:ffi")}catch{throw new a("native_boundary_unavailable")}return L}function me(e){if(typeof e!=="string")return null;try{let r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="[::1]"&&r.hostname!=="::1")return null;return r.origin}catch{return null}}function he(e){if(!e||typeof e!=="object"||Array.isArray(e))throw new a("invalid_credential_record");let r=e,o=me(r.apiOrigin);if(r.version!==T||!o||typeof r.orgId!=="string"||r.orgId.length<1||r.orgId.length>160||typeof r.deviceId!=="string"||r.deviceId.length<1||r.deviceId.length>160||typeof r.credential!=="string"||!/^(?:reason|ara)_dev_/.test(r.credential)||r.credential.length>4096)throw new a("invalid_credential_record");return{version:T,apiOrigin:o,orgId:r.orgId,deviceId:r.deviceId,credential:r.credential}}function fn(e=process.execPath){let r=e;try{r=oe(e)}catch{}return En(ye(r))}function p(e){return B().ptr(e)}function Ie(e){if(!y(e))throw new a("native_boundary_unavailable");let{dlopen:r,FFIType:o}=B();try{return r(e,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(l){if(l instanceof a)throw l;throw new a("native_boundary_unavailable")}}function U(e){return Buffer.from(e).toString("base64url")}function Ht(e){if(typeof e!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(e))return!1;try{let r=Buffer.from(e,"base64url");return r.byteLength===65&&r[0]===4}catch{return!1}}function Si(e){if(e.byteLength<8||e.byteLength>72||e[0]!==48)return!1;let r=e[1];return r!==void 0&&r<128&&r+2===e.byteLength}class mt{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(e=fn(),r=M(),o){this.libraryPath=e;this.runtimePlatform=r;this.workspaceScope=o;K(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new a("unsupported_platform");this.library??=Ie(this.libraryPath);let e=new TextEncoder().encode(this.workspaceScope??""),r=this.library.symbols.ara_device_configure_scope(p(e.length?e:new Uint8Array(1)),BigInt(e.length));if(r!==0)throw new a("native_boundary_unavailable",r);return this.library.symbols}publicKey(e){let r=new Uint8Array(_e),o=new BigUint64Array(1),l=e==="load"?this.symbols().ara_device_key_load_public(p(r),BigInt(r.byteLength),p(o)):this.symbols().ara_device_key_create_fresh_public(p(r),BigInt(r.byteLength),p(o));if(l!==0)throw new a(e==="load"?"proof_key_read_failed":"proof_key_generation_failed",l);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new a("invalid_public_key");let u=U(r.subarray(0,d));if(!Ht(u))throw new a("invalid_public_key");return u}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(e){if(e.byteLength<1||e.byteLength>j)throw new a("proof_sign_failed");let r=new Uint8Array(be),o=new BigUint64Array(1),l=this.symbols().ara_device_key_sign(p(e),BigInt(e.byteLength),p(r),BigInt(r.byteLength),p(o));if(l!==0)throw new a("proof_sign_failed",l);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>r.byteLength)throw new a("invalid_signature");let u=r.subarray(0,d);if(!Si(u))throw new a("invalid_signature");return U(u)}privateKeyIsNonExtractable(){let e=new Uint8Array(1),r=this.symbols().ara_device_key_is_non_extractable(p(e));if(r!==0||e[0]!==1)throw new a("proof_key_read_failed",r);return!0}deleteKey(){let e=new Uint8Array(1),r=this.symbols().ara_device_key_delete(p(e));if(r!==0)throw new a("proof_key_delete_failed",r);return e[0]===1}loadBinding(){let e=new Uint8Array(_),r=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(p(e),BigInt(e.byteLength),p(r));if(o===1)return null;if(o!==0)throw new a("binding_read_failed",o);let l=Number(r[0]);if(!Number.isSafeInteger(l)||l<1||l>e.byteLength)throw new a("invalid_binding");return e.slice(0,l)}createBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");let r=this.symbols().ara_device_binding_create(p(e),BigInt(e.byteLength));if(r!==0)throw new a("binding_create_failed",r)}updateBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");let r=this.symbols().ara_device_binding_update(p(e),BigInt(e.byteLength));if(r!==0)throw new a("binding_update_failed",r)}deleteBinding(){let e=new Uint8Array(1),r=this.symbols().ara_device_binding_delete(p(e));if(r!==0)throw new a("binding_delete_failed",r);return e[0]===1}loadLegacyCredential(){let e=new Uint8Array(ve),r=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(p(e),BigInt(e.byteLength),p(r));if(o===1)return null;if(o!==0)throw new a("legacy_credential_read_failed",o);let l=Number(r[0]);if(!Number.isSafeInteger(l)||l<1||l>e.byteLength)throw new a("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(0,l));return he(JSON.parse(d))}catch(d){if(d instanceof a)throw d;throw new a("invalid_credential_record")}}deleteLegacyCredential(){let e=new Uint8Array(1),r=this.symbols().ara_device_keychain_delete(p(e));if(r!==0)throw new a("legacy_credential_delete_failed",r);return e[0]===1}}function F(e){let r=e.export({format:"jwk"});if(r.crv!=="P-256"||typeof r.x!=="string"||typeof r.y!=="string")throw new a("invalid_public_key");let o=Buffer.from(r.x,"base64url"),l=Buffer.from(r.y,"base64url");if(o.byteLength!==32||l.byteLength!==32)throw new a("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,l]).toString("base64url");if(!Ht(d))throw new a("invalid_public_key");return d}function ke(){let e=process.env.XDG_CONFIG_HOME?.trim()||v(fe(),".config");De(e);let r=v(e,"ara");return Bi(r)?r:v(e,"reason")}class mn{directory;constructor(e=ke()){this.directory=e}keyPath(){return v(this.directory,"local-device.key")}bindingPath(){return v(this.directory,"local-device.binding")}loadPrivateKeyObject(){let e=this.keyPath();if(!y(e))throw new a("proof_key_read_failed");try{let r=C(e,"utf8");return ce({key:r,format:"pem"})}catch{throw new a("proof_key_read_failed")}}loadPublicKey(){let e=this.loadPrivateKeyObject(),r=le(e);return F(r)}createFreshPublicKey(){I(this.directory,{recursive:!0,mode:448});let{privateKey:e,publicKey:r}=de("ec",{namedCurve:"P-256"}),o=e.export({type:"pkcs8",format:"pem"}),l=this.keyPath();return D(l,o,{mode:384}),S(l,384),F(r)}sign(e){if(e.byteLength<1||e.byteLength>j)throw new a("proof_sign_failed");let r=this.loadPrivateKeyObject(),o;try{o=pe("sha256",e,r)}catch{throw new a("proof_sign_failed")}if(!Si(o))throw new a("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let e=this.keyPath();if(!y(e))return!1;return k(e),!0}loadBinding(){let e=this.bindingPath();if(!y(e))return null;try{return new Uint8Array(C(e))}catch{return null}}createBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");I(this.directory,{recursive:!0,mode:448});let r=this.bindingPath();if(y(r))throw new a("binding_create_failed");D(r,e,{mode:384}),S(r,384)}updateBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");I(this.directory,{recursive:!0,mode:448});let r=this.bindingPath();if(!y(r))throw new a("binding_update_failed");let o=`${r}.${ue()}`;try{D(o,e,{mode:384,flag:"wx"}),S(o,384),se(o,r)}finally{if(y(o))k(o)}}deleteBinding(){let e=this.bindingPath();if(!y(e))return!1;return k(e),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function A(){return M()==="darwin"?new mt:new mn}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),z=n({id:b,kind:i("permission_denied"),operation:c(["bash","read","write","edit"]),provenance:c(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var x=4;var m="macos-keychain-p256-v1",Y=1,Fe=`ARA-DEVICE-BINDING-V1
|
|
3
|
-
`;function Me(e){return e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=1&&e<=4}function fr(e,r=Date.now()){let o=z.safeParse(e);if(!o.success)return!1;let l=o.data,d=typeof l.occurredAt==="string"?Date.parse(l.occurredAt):NaN,u=typeof l.expiresAt==="string"?Date.parse(l.expiresAt):NaN;return l.kind==="permission_denied"&&["bash","read","write","edit"].includes(l.operation)&&["sandbox_policy","os_permission_unknown"].includes(l.provenance)&&Number.isFinite(d)&&d<=r&&u>r&&u>d&&u-d<=600000}function gn(e,r,o=Date.now()){if(!e||!r||e.state!=="connected"||e.deviceId!==r.deviceId)return null;let l=Date.parse(e.lastHeartbeatAt??""),d=e.permissionRecovery;if(!(o-l>=0&&o-l<30000)||!fr(d,o)||d.deviceId!==r.deviceId||d.organizationId!==r.orgId)return null;try{process.kill(e.pid,0)}catch{return null}return d}function X(e={},r=s()){let o=w({env:{...process.env,...e}}),l=e.XDG_CONFIG_HOME?.trim()||h(r,".config");return wt(l,...o==="staging"?["staging"]:[])}function gt(e={},r=s()){return h(X(e,r),"local-device.json")}function mr(e={},r=s()){return h(X(e,r),"local-daemon.json")}function N(e,r){
|
|
4
|
-
`,{mode:384,flag:"wx"}),P(o,384),Ne(o,e),P(e,384)}finally{if(H(o))Ke(o)}return e}function O(e){if(!H(e))return null;try{return JSON.parse(Re(e,"utf8"))}catch{return null}}function E(e,r,o){try{e.onCredentialLifecycle?.({event:r,...o?{reasonCode:o}:{}})}catch{}}function je(e){if(!Array.isArray(e))return null;let r=[];for(let o of e){if(!o||typeof o!=="object")return null;let l=o;if(typeof l.id!=="string"||typeof l.label!=="string"||typeof l.path!=="string"||typeof l.pathFingerprint!=="string"||!l.permissions||typeof l.permissions.read!=="boolean"||typeof l.permissions.write!=="boolean"||typeof l.permissions.execute!=="boolean"||typeof l.permissions.discover_environment!=="boolean"||typeof l.permissions.expose_mcp!=="boolean")return null;r.push({id:l.id,label:l.label,path:l.path,pathFingerprint:l.pathFingerprint,permissions:l.permissions})}return r}function W(e,r,o=[]){let l=Object.keys(e);return r.every((d)=>Object.hasOwn(e,d))&&l.every((d)=>r.includes(d)||o.includes(d))}function Ve(e){if(typeof e!=="string")return null;try{let r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="127.0.0.1"&&r.hostname!=="localhost")return null;return r.origin}catch{return null}}function Z(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let r=e,o=je(r.roots),l=Ve(r.apiOrigin);if(!l||typeof r.orgId!=="string"||typeof r.deviceId!=="string"||typeof r.displayName!=="string"||typeof r.registeredAt!=="string"||!Me(r.handsSlots)||r.worker!==void 0&&(!r.worker||!/^[a-f0-9]{64}$/.test(r.worker.configDigest)||!["persistent","ephemeral"].includes(r.worker.lifetime)||!Number.isFinite(Date.parse(r.worker.expiresAt)))||!o)return null;return{apiOrigin:l,orgId:r.orgId,deviceId:r.deviceId,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:o}}function Be(e){return{...e,credentialStorage:m}}function $e(e){return{version:x,apiOrigin:e.apiOrigin,orgId:e.orgId,deviceId:e.deviceId,devicePublicKey:e.devicePublicKey,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:e.roots.map((r)=>({id:r.id,label:r.label,path:r.path,pathFingerprint:r.pathFingerprint,permissions:{read:r.permissions.read,write:r.permissions.write,execute:r.permissions.execute,discover_environment:r.permissions.discover_environment,expose_mcp:r.permissions.expose_mcp}})),credentialStorage:m}}function q(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let r=e;if(!W(r,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Z(r);if(!o||r.version!==x||r.credentialStorage!==m||!Ht(r.devicePublicKey))return null;return{version:x,...o,devicePublicKey:r.devicePublicKey,credentialStorage:m}}function Q(e){return new TextEncoder().encode(`${Fe}${JSON.stringify($e(e))}`)}function ze(e){let r=Buffer.from(e,"base64url");return
|
|
5
|
-
export{a,fn,Ht,Si,mt,mn,fr,gn,gt,mr,Ut,ae,rt,Ei,gr,
|
|
2
|
+
import{w,An}from"./vm-hands-entry-lite-a4fn6ye1.js";import{En}from"./vm-hands-entry-lite-sb1xtqxr.js";import{Bi,De,wt}from"./vm-hands-entry-lite-peyr9y6z.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{t,n,c,i}from"./vm-hands-entry-lite-n31pta3n.js";import{createHmac as ke,createPublicKey as Le,randomBytes as we,randomUUID as G,verify as Ae}from"crypto";import{chmodSync as P,existsSync as H,mkdirSync as Pe,readFileSync as Re,realpathSync as xe,renameSync as Ne,statSync as Oe,unlinkSync as Ke,writeFileSync as Ce}from"fs";import{basename as Te,dirname as R,isAbsolute as J,join as h,resolve as Ue}from"path";var We=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var te="REASON_DESKTOP_RUNTIME",ne="REASON_DESKTOP_RUNTIME_CHANNEL",ie="REASON_DESKTOP_RUNTIME_INSTANCE_ID",re="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",it={[te]:"ARA_DESKTOP_RUNTIME",[ne]:"ARA_DESKTOP_RUNTIME_CHANNEL",[ie]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[re]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function K(e){if(e===void 0)return;if(!/^[a-f0-9]{64}$/.test(e))throw Error("Invalid desktop workspace scope.");return e}import{chmodSync as S,existsSync as y,mkdirSync as I,readFileSync as C,realpathSync as oe,renameSync as se,unlinkSync as k,writeFileSync as D}from"fs";import{createPrivateKey as ce,createPublicKey as le,generateKeyPairSync as de,randomUUID as ue,sign as pe}from"crypto";import{createRequire as ge}from"module";import{homedir as fe,platform as M}from"os";import{dirname as ye,join as v}from"path";var T=1,ve=16384,_=65536,_e=128,be=128,j=65536;class a extends Error{code;nativeStatus;constructor(e,r){super(`Reason Device proof boundary failed (${e}).${r===void 0?"":` Native status: ${r}.`}`);this.code=e;this.nativeStatus=r;this.name="LocalCredentialBoundaryError"}}function V(e){if(e.code==="proof_key_read_failed"&&e.nativeStatus===-25300)return"proof_key_missing";switch(e.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return e.code}}var L=null;function B(){if(!L)try{L=ge(import.meta.url)("bun:ffi")}catch{throw new a("native_boundary_unavailable")}return L}function me(e){if(typeof e!=="string")return null;try{let r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="[::1]"&&r.hostname!=="::1")return null;return r.origin}catch{return null}}function he(e){if(!e||typeof e!=="object"||Array.isArray(e))throw new a("invalid_credential_record");let r=e,o=me(r.apiOrigin);if(r.version!==T||!o||typeof r.orgId!=="string"||r.orgId.length<1||r.orgId.length>160||typeof r.deviceId!=="string"||r.deviceId.length<1||r.deviceId.length>160||typeof r.credential!=="string"||!/^(?:reason|ara)_dev_/.test(r.credential)||r.credential.length>4096)throw new a("invalid_credential_record");return{version:T,apiOrigin:o,orgId:r.orgId,deviceId:r.deviceId,credential:r.credential}}function fn(e=process.execPath){let r=e;try{r=oe(e)}catch{}return En(ye(r))}function p(e){return B().ptr(e)}function Se(e){if(!y(e))throw new a("native_boundary_unavailable");let{dlopen:r,FFIType:o}=B();try{return r(e,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(l){if(l instanceof a)throw l;throw new a("native_boundary_unavailable")}}function U(e){return Buffer.from(e).toString("base64url")}function Ht(e){if(typeof e!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(e))return!1;try{let r=Buffer.from(e,"base64url");return r.byteLength===65&&r[0]===4}catch{return!1}}function Si(e){if(e.byteLength<8||e.byteLength>72||e[0]!==48)return!1;let r=e[1];return r!==void 0&&r<128&&r+2===e.byteLength}class mt{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(e=fn(),r=M(),o){this.libraryPath=e;this.runtimePlatform=r;this.workspaceScope=o;K(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new a("unsupported_platform");this.library??=Se(this.libraryPath);let e=new TextEncoder().encode(this.workspaceScope??""),r=this.library.symbols.ara_device_configure_scope(p(e.length?e:new Uint8Array(1)),BigInt(e.length));if(r!==0)throw new a("native_boundary_unavailable",r);return this.library.symbols}publicKey(e){let r=new Uint8Array(_e),o=new BigUint64Array(1),l=e==="load"?this.symbols().ara_device_key_load_public(p(r),BigInt(r.byteLength),p(o)):this.symbols().ara_device_key_create_fresh_public(p(r),BigInt(r.byteLength),p(o));if(l!==0)throw new a(e==="load"?"proof_key_read_failed":"proof_key_generation_failed",l);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new a("invalid_public_key");let u=U(r.subarray(0,d));if(!Ht(u))throw new a("invalid_public_key");return u}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(e){if(e.byteLength<1||e.byteLength>j)throw new a("proof_sign_failed");let r=new Uint8Array(be),o=new BigUint64Array(1),l=this.symbols().ara_device_key_sign(p(e),BigInt(e.byteLength),p(r),BigInt(r.byteLength),p(o));if(l!==0)throw new a("proof_sign_failed",l);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>r.byteLength)throw new a("invalid_signature");let u=r.subarray(0,d);if(!Si(u))throw new a("invalid_signature");return U(u)}privateKeyIsNonExtractable(){let e=new Uint8Array(1),r=this.symbols().ara_device_key_is_non_extractable(p(e));if(r!==0||e[0]!==1)throw new a("proof_key_read_failed",r);return!0}deleteKey(){let e=new Uint8Array(1),r=this.symbols().ara_device_key_delete(p(e));if(r!==0)throw new a("proof_key_delete_failed",r);return e[0]===1}loadBinding(){let e=new Uint8Array(_),r=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(p(e),BigInt(e.byteLength),p(r));if(o===1)return null;if(o!==0)throw new a("binding_read_failed",o);let l=Number(r[0]);if(!Number.isSafeInteger(l)||l<1||l>e.byteLength)throw new a("invalid_binding");return e.slice(0,l)}createBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");let r=this.symbols().ara_device_binding_create(p(e),BigInt(e.byteLength));if(r!==0)throw new a("binding_create_failed",r)}updateBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");let r=this.symbols().ara_device_binding_update(p(e),BigInt(e.byteLength));if(r!==0)throw new a("binding_update_failed",r)}deleteBinding(){let e=new Uint8Array(1),r=this.symbols().ara_device_binding_delete(p(e));if(r!==0)throw new a("binding_delete_failed",r);return e[0]===1}loadLegacyCredential(){let e=new Uint8Array(ve),r=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(p(e),BigInt(e.byteLength),p(r));if(o===1)return null;if(o!==0)throw new a("legacy_credential_read_failed",o);let l=Number(r[0]);if(!Number.isSafeInteger(l)||l<1||l>e.byteLength)throw new a("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(0,l));return he(JSON.parse(d))}catch(d){if(d instanceof a)throw d;throw new a("invalid_credential_record")}}deleteLegacyCredential(){let e=new Uint8Array(1),r=this.symbols().ara_device_keychain_delete(p(e));if(r!==0)throw new a("legacy_credential_delete_failed",r);return e[0]===1}}function F(e){let r=e.export({format:"jwk"});if(r.crv!=="P-256"||typeof r.x!=="string"||typeof r.y!=="string")throw new a("invalid_public_key");let o=Buffer.from(r.x,"base64url"),l=Buffer.from(r.y,"base64url");if(o.byteLength!==32||l.byteLength!==32)throw new a("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,l]).toString("base64url");if(!Ht(d))throw new a("invalid_public_key");return d}function Ie(){let e=process.env.XDG_CONFIG_HOME?.trim()||v(fe(),".config");De(e);let r=v(e,"ara");return Bi(r)?r:v(e,"reason")}class mn{directory;constructor(e=Ie()){this.directory=e}keyPath(){return v(this.directory,"local-device.key")}bindingPath(){return v(this.directory,"local-device.binding")}loadPrivateKeyObject(){let e=this.keyPath();if(!y(e))throw new a("proof_key_read_failed");try{let r=C(e,"utf8");return ce({key:r,format:"pem"})}catch{throw new a("proof_key_read_failed")}}loadPublicKey(){let e=this.loadPrivateKeyObject(),r=le(e);return F(r)}createFreshPublicKey(){I(this.directory,{recursive:!0,mode:448});let{privateKey:e,publicKey:r}=de("ec",{namedCurve:"P-256"}),o=e.export({type:"pkcs8",format:"pem"}),l=this.keyPath();return D(l,o,{mode:384}),S(l,384),F(r)}sign(e){if(e.byteLength<1||e.byteLength>j)throw new a("proof_sign_failed");let r=this.loadPrivateKeyObject(),o;try{o=pe("sha256",e,r)}catch{throw new a("proof_sign_failed")}if(!Si(o))throw new a("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let e=this.keyPath();if(!y(e))return!1;return k(e),!0}loadBinding(){let e=this.bindingPath();if(!y(e))return null;try{return new Uint8Array(C(e))}catch{return null}}createBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");I(this.directory,{recursive:!0,mode:448});let r=this.bindingPath();if(y(r))throw new a("binding_create_failed");D(r,e,{mode:384}),S(r,384)}updateBinding(e){if(e.byteLength<1||e.byteLength>_)throw new a("invalid_binding");I(this.directory,{recursive:!0,mode:448});let r=this.bindingPath();if(!y(r))throw new a("binding_update_failed");let o=`${r}.${ue()}`;try{D(o,e,{mode:384,flag:"wx"}),S(o,384),se(o,r)}finally{if(y(o))k(o)}}deleteBinding(){let e=this.bindingPath();if(!y(e))return!1;return k(e),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function A(){return M()==="darwin"?new mt:new mn}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),z=n({id:b,kind:i("permission_denied"),operation:c(["bash","read","write","edit"]),provenance:c(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var x=4;var m="macos-keychain-p256-v1",Y=1,Fe=`ARA-DEVICE-BINDING-V1
|
|
3
|
+
`;function Me(e){return e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=1&&e<=4}function fr(e,r=Date.now()){let o=z.safeParse(e);if(!o.success)return!1;let l=o.data,d=typeof l.occurredAt==="string"?Date.parse(l.occurredAt):NaN,u=typeof l.expiresAt==="string"?Date.parse(l.expiresAt):NaN;return l.kind==="permission_denied"&&["bash","read","write","edit"].includes(l.operation)&&["sandbox_policy","os_permission_unknown"].includes(l.provenance)&&Number.isFinite(d)&&d<=r&&u>r&&u>d&&u-d<=600000}function gn(e,r,o=Date.now()){if(!e||!r||e.state!=="connected"||e.deviceId!==r.deviceId)return null;let l=Date.parse(e.lastHeartbeatAt??""),d=e.permissionRecovery;if(!(o-l>=0&&o-l<30000)||!fr(d,o)||d.deviceId!==r.deviceId||d.organizationId!==r.orgId)return null;try{process.kill(e.pid,0)}catch{return null}return d}function X(e={},r=s()){let o=w({env:{...process.env,...e}}),l=e.XDG_CONFIG_HOME?.trim()||h(r,".config");return wt(l,...o==="staging"?["staging"]:[])}function gt(e={},r=s()){return h(X(e,r),"local-device.json")}function mr(e={},r=s()){return h(X(e,r),"local-daemon.json")}function N(e,r){Pe(R(e),{recursive:!0,mode:448}),P(R(e),448);let o=`${e}.${process.pid}.${G()}.tmp`;try{Ce(o,`${JSON.stringify(r,null,2)}
|
|
4
|
+
`,{mode:384,flag:"wx"}),P(o,384),Ne(o,e),P(e,384)}finally{if(H(o))Ke(o)}return e}function O(e){if(!H(e))return null;try{return JSON.parse(Re(e,"utf8"))}catch{return null}}function E(e,r,o){try{e.onCredentialLifecycle?.({event:r,...o?{reasonCode:o}:{}})}catch{}}function je(e){if(!Array.isArray(e))return null;let r=[];for(let o of e){if(!o||typeof o!=="object")return null;let l=o;if(typeof l.id!=="string"||typeof l.label!=="string"||typeof l.path!=="string"||typeof l.pathFingerprint!=="string"||!l.permissions||typeof l.permissions.read!=="boolean"||typeof l.permissions.write!=="boolean"||typeof l.permissions.execute!=="boolean"||typeof l.permissions.discover_environment!=="boolean"||typeof l.permissions.expose_mcp!=="boolean")return null;r.push({id:l.id,label:l.label,path:l.path,pathFingerprint:l.pathFingerprint,permissions:l.permissions})}return r}function W(e,r,o=[]){let l=Object.keys(e);return r.every((d)=>Object.hasOwn(e,d))&&l.every((d)=>r.includes(d)||o.includes(d))}function Ve(e){if(typeof e!=="string")return null;try{let r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="127.0.0.1"&&r.hostname!=="localhost")return null;return r.origin}catch{return null}}function Z(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let r=e,o=je(r.roots),l=Ve(r.apiOrigin);if(!l||typeof r.orgId!=="string"||typeof r.deviceId!=="string"||typeof r.displayName!=="string"||typeof r.registeredAt!=="string"||!Me(r.handsSlots)||r.worker!==void 0&&(!r.worker||!/^[a-f0-9]{64}$/.test(r.worker.configDigest)||!["persistent","ephemeral"].includes(r.worker.lifetime)||!Number.isFinite(Date.parse(r.worker.expiresAt)))||!o)return null;return{apiOrigin:l,orgId:r.orgId,deviceId:r.deviceId,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:o}}function Be(e){return{...e,credentialStorage:m}}function $e(e){return{version:x,apiOrigin:e.apiOrigin,orgId:e.orgId,deviceId:e.deviceId,devicePublicKey:e.devicePublicKey,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:e.roots.map((r)=>({id:r.id,label:r.label,path:r.path,pathFingerprint:r.pathFingerprint,permissions:{read:r.permissions.read,write:r.permissions.write,execute:r.permissions.execute,discover_environment:r.permissions.discover_environment,expose_mcp:r.permissions.expose_mcp}})),credentialStorage:m}}function q(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let r=e;if(!W(r,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Z(r);if(!o||r.version!==x||r.credentialStorage!==m||!Ht(r.devicePublicKey))return null;return{version:x,...o,devicePublicKey:r.devicePublicKey,credentialStorage:m}}function Q(e){return new TextEncoder().encode(`${Fe}${JSON.stringify($e(e))}`)}function ze(e){let r=Buffer.from(e,"base64url");return Le({format:"jwk",key:{kty:"EC",crv:"P-256",x:r.subarray(1,33).toString("base64url"),y:r.subarray(33,65).toString("base64url")}})}function Ge(e,r){let o={version:Y,state:e,signature:r.sign(Q(e))};return new TextEncoder().encode(JSON.stringify(o))}function ee(e){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new a("invalid_binding")}if(!r||typeof r!=="object"||Array.isArray(r))throw new a("invalid_binding");let o=r;if(!W(o,["version","state","signature"])||o.version!==Y||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new a("invalid_binding");let l=q(o.state);if(!l)throw new a("invalid_binding");let d=!1;try{d=Ae("sha256",Q(l),ze(l.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new a("invalid_binding");return l}function He(e){let{credentialStorage:r,...o}=e;return o}function Je(e){return e instanceof a?V(e):"credential_boundary_failed"}function Ut(e=gt(),r={}){let o=O(e),l=r.proofStore??r.credentialStore??A(),d=l.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&Ye(o))return null;if(o!==null)throw new a("invalid_binding");return null}let u=ee(d),g=l.loadPublicKey();if(l.privateKeyIsNonExtractable(),g!==u.devicePublicKey)throw new a("invalid_public_key");let f=q(o);if(r.repair!==!1&&(!f||JSON.stringify(f)!==JSON.stringify(u)))N(e,u);return He(u)}function Ye(e){let r=e,o=Z(e);if(!o)return null;if(r.version===2){if(typeof r.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(r.deviceCredential)||r.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(r.version!==3||r.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in r)return null;return{state:o,credentialSource:"keychain-v3"}}function ae(e,r=gt(),o={}){let l=o.proofStore??o.credentialStore??A();E(o,"credential.store_started");try{if(!Ht(e.devicePublicKey)||l.loadPublicKey()!==e.devicePublicKey)throw new a("invalid_public_key");l.privateKeyIsNonExtractable();let d=Be(e),u=l.loadBinding();if(u){let f=ee(u);if(f.devicePublicKey!==e.devicePublicKey||f.orgId!==e.orgId||f.deviceId!==e.deviceId||f.apiOrigin!==e.apiOrigin&&!An(f.apiOrigin,e.apiOrigin))throw new a("invalid_binding")}let g=Ge(d,l);if(u)l.updateBinding(g);else l.createBinding(g);return N(r,d),E(o,"credential.store_completed"),r}catch(d){throw E(o,"credential.store_failed",Je(d)),d}}function rt(e=mr()){let r=O(e);if(!r||typeof r!=="object")return null;let o=r;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!fr(o.permissionRecovery))delete o.permissionRecovery;return o}function Ei(e,r=mr()){return N(r,e)}var gr=1;function Xe(e=gt()){return h(R(e),"local-device.proxy.json")}function Ee(e=Xe()){let r=O(e);if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r;if(o.version!==gr||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!J(o.caFile)))return null;return{version:gr,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}function zt(e,r={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},o=we(32)){let l=new Set,d=[];for(let u of e){let g=xe(J(u)?u:Ue(u));if(!Oe(g).isDirectory())throw Error(`Local execution root is not a directory: ${u}`);if(l.has(g))continue;l.add(g),d.push({id:G(),label:Te(g)||g,path:g,pathFingerprint:ke("sha256",o).update(g).digest("hex"),permissions:{...r}})}if(d.length===0)throw Error("At least one explicit local execution root is required.");return d}
|
|
5
|
+
export{a,fn,Ht,Si,mt,mn,fr,gn,gt,mr,Ut,ae,rt,Ei,gr,Ee,zt};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w,Ve}from"./vm-hands-entry-lite-
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w,Ve}from"./vm-hands-entry-lite-a4fn6ye1.js";import{ve,C}from"./vm-hands-entry-lite-cr3hypam.js";import{q}from"./vm-hands-entry-lite-a6ss0ges.js";function ut(e,i){let t=R(e,"REASON_API_URL")?.trim();if(!t)return Ve(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function el(e){return R(e,"REASON_API_URL")?.trim()?ut(e,"production"):void 0}function Vn(e){return R(e,"REASON_API_KEY")?.trim()||void 0}async function ir(e,i){let t=e.env??process.env,n=Vn(t);if(!n)return(e.getCredentials??ve)({apiOrigin:el(t),signal:i});let a=ut(t,e.channel??w({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=q(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new C(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{ut,el,Vn,ir};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{mkdirSync as R,readdirSync as A,readFileSync as k,realpathSync as x}from"fs";import{userInfo as E}from"os";var qn="--vm-hands-op-runner-kind=person",Wn="--vm-hands-op-runner-kind=surface",Wr="--vm-hands-surface-uid=",Vr="--vm-hands-surface-dir=",C="/sys/fs/cgroup/reason-person/desktop",Gr=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function D(t){let a=new Set([t]),l=[];try{l=A("/proc")}catch{}for(let n of l){if(!/^\d+$/.test(n))continue;try{let o=k(`/proc/${n}/stat`,"utf8");if(Number(o.slice(o.lastIndexOf(")")+2).split(" ")[3])===t)a.add(Number(n))}catch{}}for(let n of a)try{process.kill(n,"SIGKILL")}catch{}}var H=(t)=>{let a=globalThis.Bun;if(!a)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=a.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(c,d)=>t.onData(d)}}),n=l.terminal,o=()=>{D(l.pid);try{n?.close()}catch{}};if(!n)throw o(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(c)=>n.write(c),resize:(c,d)=>n.resize(c,d),kill:o,exited:l.exited.then((c)=>typeof c==="number"?c:null,()=>null)}};function O(){let t=(()=>{try{return E().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...t?{USER:t,LOGNAME:t}:{}}}async function L(t){let[{localAutomationAvailable:a},{localDisplayReady:l},{localDisplayVideoAvailable:n},{probeWorkerPreview:o},m]=await Promise.all([import("./local-automation-
|
|
3
|
-
`).find((o)=>o.startsWith("0::"))?.slice(3)??""}catch{return null}if(!/^\/reason-person\/vm-hands\/[A-Za-z0-9._-]+$/.test(a))return null;if(!t)return null;let l=[t.xvnc,t.xvfb,t.openbox,t.x11vnc,t.pulseaudio,t.browser,"/usr/bin/dbus-daemon","/bin/dbus-daemon"].flatMap((o)=>{try{return o?[x(o)]:[]}catch{return[]}}),n={join:`/sys/fs/cgroup${a}/desktop`,keep:C,programs:[...new Set(l)]};for(let o of[n.join,n.keep])try{R(o,{mode:493})}catch(m){if(m.code!=="EEXIST")return null}return n}async function hl(){let[{executeLocalOperation:t,spawnCaptured:a},{runLocalPtySession:l},{configureDesktopAccount:n,desktopAccount:o},{configureWorkerSandbox:m},{configureDesktopPlacement:c},{readDesktopComponents:d}]=await Promise.all([import("./local-capabilities-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{mkdirSync as R,readdirSync as A,readFileSync as k,realpathSync as x}from"fs";import{userInfo as E}from"os";var qn="--vm-hands-op-runner-kind=person",Wn="--vm-hands-op-runner-kind=surface",Wr="--vm-hands-surface-uid=",Vr="--vm-hands-surface-dir=",C="/sys/fs/cgroup/reason-person/desktop",Gr=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function D(t){let a=new Set([t]),l=[];try{l=A("/proc")}catch{}for(let n of l){if(!/^\d+$/.test(n))continue;try{let o=k(`/proc/${n}/stat`,"utf8");if(Number(o.slice(o.lastIndexOf(")")+2).split(" ")[3])===t)a.add(Number(n))}catch{}}for(let n of a)try{process.kill(n,"SIGKILL")}catch{}}var H=(t)=>{let a=globalThis.Bun;if(!a)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=a.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(c,d)=>t.onData(d)}}),n=l.terminal,o=()=>{D(l.pid);try{n?.close()}catch{}};if(!n)throw o(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(c)=>n.write(c),resize:(c,d)=>n.resize(c,d),kill:o,exited:l.exited.then((c)=>typeof c==="number"?c:null,()=>null)}};function O(){let t=(()=>{try{return E().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...t?{USER:t,LOGNAME:t}:{}}}async function L(t){let[{localAutomationAvailable:a},{localDisplayReady:l},{localDisplayVideoAvailable:n},{probeWorkerPreview:o},m]=await Promise.all([import("./local-automation-zjrnxdh7.js"),import("./local-display-session-vbsgwq8z.js"),import("./local-display-video-yb4bh3t9.js"),import("./worker-preview-readiness-w4zy5g2p.js"),import("fs")]),c=AbortSignal.timeout(15000),d=null;try{m.mkdirSync(t,{recursive:!0,mode:448}),d=m.mkdtempSync(`${t}/probe-`);let[w,u,v]=await Promise.all([Promise.resolve().then(()=>a()).catch(()=>!1),l().catch(()=>!1),o(d,c).catch(()=>!1)]);return{t:"readiness",display_video:u&&await n().catch(()=>!1),lanes:{"automation.call.v1":w,"display.stream.v1":u,"preview.serve.v1":v,"tunnel.open":v,"tunnel.close":v}}}finally{if(d)m.rmSync(d,{recursive:!0,force:!0})}}function N(t){let a="";try{a=k("/proc/self/cgroup","utf8").split(`
|
|
3
|
+
`).find((o)=>o.startsWith("0::"))?.slice(3)??""}catch{return null}if(!/^\/reason-person\/vm-hands\/[A-Za-z0-9._-]+$/.test(a))return null;if(!t)return null;let l=[t.xvnc,t.xvfb,t.openbox,t.x11vnc,t.pulseaudio,t.browser,"/usr/bin/dbus-daemon","/bin/dbus-daemon"].flatMap((o)=>{try{return o?[x(o)]:[]}catch{return[]}}),n={join:`/sys/fs/cgroup${a}/desktop`,keep:C,programs:[...new Set(l)]};for(let o of[n.join,n.keep])try{R(o,{mode:493})}catch(m){if(m.code!=="EEXIST")return null}return n}async function hl(){let[{executeLocalOperation:t,spawnCaptured:a},{runLocalPtySession:l},{configureDesktopAccount:n,desktopAccount:o},{configureWorkerSandbox:m},{configureDesktopPlacement:c},{readDesktopComponents:d}]=await Promise.all([import("./local-capabilities-ka01z0mb.js"),import("./local-pty-session-hnxtqd5m.js"),import("./desktop-account-d1g1m6yb.js"),import("./worker-sandbox-2trfs79b.js"),import("./desktop-delegate-4hb0163k.js"),import("./desktop-components-gsqad6xm.js")]);m();let w=process.argv.includes(qn),u=process.argv.includes(Wn),v=(i,e,p)=>a(i,e[0]==="-lic"?["-lc",...e.slice(1)]:e,p),y=(process.geteuid?.()??0)!==0;if(u){y=!1;let i=process.argv.find((e)=>e.startsWith(Wr))?.slice(Wr.length);if((process.geteuid?.()??-1)===0&&i)try{y=n({value:i})!==null&&o()!==null}catch{y=!1}}let S=new Map,_=new Map,f=(i)=>{try{process.send?.(i)}catch{}};if(u&&y){let i=o()?.home,e=i?N(d({home:i})):null;c(e&&{...e,log:(p,g)=>f({t:"log",event:p,fields:g})})}if(process.on("message",(i)=>{let e=i;if(e?.t==="cancel"){S.get(e.id)?.abort();return}if(e?.t==="control"){let s=_.get(e.id);if(u&&s&&e.control&&typeof e.control.kind==="string")import("./local-managed-process-52qasdaq.js").then(({controlManagedDeviceProcess:h})=>h(s,{kind:e.control.kind,payload:e.control.payload??{}})).catch(()=>!1);return}if(e?.t==="retire"){if(u&&typeof e.operation_id==="string"&&typeof e.status==="string")import("./local-managed-process-52qasdaq.js").then(({retireManagedDeviceProcess:s})=>s(e.operation_id,e.status)).catch(()=>!1);return}if(e?.t!=="op")return;if(!y){f({t:"done",id:e.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let p=e.claim.capability;if(p==="pty.start"&&!w){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}if(Gr.has(p)!==u){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let g=new AbortController;S.set(e.id,g),_.set(e.id,e.claim);let b=p==="pty.start"?{runPtySession:(s)=>l(s,{spawnPty:H,environment:O(),loadProxy:()=>null})}:{worker:e.worker,...p==="exec.full"?{spawnFullControl:v}:{}};t(e.state,e.claim,{...b,signal:g.signal,emit:(s)=>{let{deliverySignal:h,...P}=s;f({t:"event",id:e.id,event:P})}}).then((s)=>f({t:"done",id:e.id,completion:s}),(s)=>f({t:"done",id:e.id,completion:{status:"failed",error_code:s&&typeof s==="object"&&"code"in s&&typeof s.code==="string"?s.code:"vm_hands_op_failed"}})).finally(()=>{S.delete(e.id),_.delete(e.id)})}),process.on("disconnect",()=>process.exit(0)),u){let i=process.argv.find((p)=>p.startsWith(Vr))?.slice(Vr.length),e={t:"readiness",display_video:!1,lanes:{}};f(y&&i?await L(i).catch(()=>e):e)}await new Promise(()=>{})}
|
|
4
4
|
export{qn,Wn,Wr,Vr,Gr,hl};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Mn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Mn}from"./vm-hands-entry-lite-nsaa15dt.js";var g=Mn.version,Ir=`reason-cli/${g}`,Hc=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Il(r,c){if(!Hc.test(r)||!Hc.test(c))throw Error("cannot compare invalid CLI versions");let f=(t)=>{let e=t.indexOf("-");return e===-1?[t,void 0]:[t.slice(0,e),t.slice(e+1)]},[h,i]=f(r),[x,s]=f(c),u=h.split(".").map(BigInt),d=x.split(".").map(BigInt);for(let t=0;t<3;t+=1){if(u[t]===d[t])continue;return u[t]<d[t]?-1:1}if(i===void 0||s===void 0){if(i===s)return 0;return i===void 0?1:-1}let l=i.split("."),a=s.split("."),C=Math.max(l.length,a.length);for(let t=0;t<C;t+=1){let e=l[t],n=a[t];if(e===void 0||n===void 0){if(e===n)return 0;return e===void 0?-1:1}if(e===n)continue;let o=/^\d+$/.test(e),p=/^\d+$/.test(n);if(o&&p){let I=BigInt(e),m=BigInt(n);if(I===m)continue;return I<m?-1:1}if(o!==p)return o?-1:1;return e<n?-1:1}return 0}function bs(r=Bun.main){return r.startsWith("/$bunfs/")||/^B:[\\/]~BUN[\\/]/i.test(r)}
|
|
3
3
|
export{g,Ir,Hc,Il,bs};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{basename as o}from"path";var xr=["production","staging"],s="https://api.reasonmachines.com",l="https://staging-api.reasonmachines.com";var r={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},p=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function w(n={}){let t=R(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(t){if(xr.includes(t))return t;throw Error(`Unknown Reason CLI channel: ${t}`)}let e=o(n.executablePath??process.execPath).toLowerCase();return p.has(e)?"staging":"production"}function Ve(n){return n==="staging"?l:s}function kc(n){return`${Ve(n)}/mcp/ara`}var i={production:["https://api.ara.so",r.production.api],staging:["https://api-staging.ara.so",r.staging.api]};function
|
|
3
|
-
export{xr,w,Ve,kc,
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{basename as o}from"path";var xr=["production","staging"],s="https://api.reasonmachines.com",l="https://staging-api.reasonmachines.com";var r={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},p=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function w(n={}){let t=R(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(t){if(xr.includes(t))return t;throw Error(`Unknown Reason CLI channel: ${t}`)}let e=o(n.executablePath??process.execPath).toLowerCase();return p.has(e)?"staging":"production"}function Ve(n){return n==="staging"?l:s}function kc(n){return`${Ve(n)}/mcp/ara`}var i={production:["https://api.ara.so",r.production.api],staging:["https://api-staging.ara.so",r.staging.api]};function we(n){let t;try{t=new URL(n).origin}catch{return n}let e=xr.find((a)=>i[a].includes(t));return e?Ve(e):t}function W(n,t){return n===t||we(n)===we(t)}function An(n,t){return xr.some((e)=>i[e].includes(n)&&t===Ve(e))}function Pn(n,t){try{let e=new URL(t);return!e.username&&!e.password&&(e.origin===Ve(n)||e.origin===r[n].api)}catch{return!1}}function Cr(n){try{let t=new URL(n).hostname.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}
|
|
3
|
+
export{xr,w,Ve,kc,we,W,An,Pn,Cr};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{U,H,T}from"./vm-hands-entry-lite-
|
|
3
|
-
`)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function ei(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=$t({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{U,H,T}from"./vm-hands-entry-lite-jjv6s3mx.js";import{_e,$t,oi,Po,Ro,ur}from"./vm-hands-entry-lite-5ypg0t3q.js";import{gt}from"./vm-hands-entry-lite-73tecmk2.js";import{v,pr,Io,ht,ft}from"./vm-hands-entry-lite-sxnvhzy5.js";import{b,m}from"./vm-hands-entry-lite-2927z566.js";import{s,Et,qc}from"./vm-hands-entry-lite-tzv8s0e7.js";import{Xi,I,t,V,o,_,cl,Rt,_a,d,n,be,P,$e,c,i,Yi}from"./vm-hands-entry-lite-n31pta3n.js";import{Ye,G}from"./vm-hands-entry-lite-04nx5y4f.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as X}from"crypto";import{spawn as ke}from"child_process";import{existsSync as Y,lstatSync as de,mkdirSync as Oe,readFileSync as Me,realpathSync as q,rmSync as Te,writeFileSync as je}from"fs";import{dirname as Le,join as A,relative as We,sep as Ne}from"path";var ge=["process.run.v1","process.full.v1"],ve=600000,we=1800000,ye=20000,re="process.cancel.v1",oe=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:c(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(we).default(ve).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),B={device_id:t().uuid(),root_id:t().uuid()},Se=P("action",[oe.extend(B),n({...B,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(ye).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...B,action:i("cancel"),process_id:t().uuid()}).strict()]),qe=Xi(Se,{io:"input"}),Je=oe.extend({process_brain_fence:t().uuid(),process_expires_at:I.datetime()}).strict(),W=n({version:i(1),process_id:t().uuid(),state:c(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:_(),observed_at:I.datetime(),output:d(n({cursor:o().int().min(1),stream:c(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let p=e.first_cursor-1;for(let l of e.output){if(l.cursor<=p||l.cursor>e.next_cursor)return!1;p=l.cursor}return!0});function Qn(e){return ge.includes(e)}var ze=n({operation_constraints:$e(t(),Rt())}),Ge=n({ready:i(!0),version:i(1),execution_mode:c(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var xe=n({version:i(1),process_id:t().uuid(),state:c(["queued","cancelled_before_start","not_started"]),exit_code:cl(),output:d(_a()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:c(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Pe=n({...W.shape,state:c(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:I.datetime().optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:_(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:_(),next_step:c(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:W.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),Be=Xi(Pe),Fe=be([W,xe.refine((e)=>e.state==="cancelled_before_start")]),F=n({version:i(1),process_id:t().uuid(),state:c(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:I.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ee=n({process_terminal_observation:F}).strict();function Ba(e,a){let p=Ee.safeParse(e);return p.success&&p.data.process_terminal_observation.process_id===a?p.data:null}var Fa="preview.serve.v1",ja=43200000;var Ha=3,ne="preview.open.v1",se=1,yo="gid_proxy_v1",Ua="egress",wo=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Re=n({version:i(yo),allowed_domains:d(t().max(260).regex(wo)).max(1024)}).strict(),Ie=Yi((e)=>te(e)!==null,"invalid workspace"),De=n({version:i(1),request_id:V(),session_id:V(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ie,egress:Re.optional()}).strict(),za=De.extend({expires_at:I.datetime()}).strict();var Ce=4,Ae=5000;function K(e,a,p){let l=null;try{l=pr(e)}catch{}Io({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:a,port:l?.binding.port??0,reason:l?p:"binding_invalid"})}function ie(e){let a=new Map;return{open(p){let l=(w)=>K(p,e.claim.operation_id,w),E;try{E=pr(p)}catch{return l("binding_invalid")}let{binding:h,deviceRelayUrl:N}=E,S=e.claim.owner;if(!S||h.organizationId!==S.organization_id||h.userId!==S.user_id||h.deviceId!==S.device_id||h.rootId!==e.claim.root_id||h.jobId!==e.claim.operation_id||h.fenceId!==e.claim.operation_id||h.generation!==se||h.expiresAtMs>Math.min(Date.now()+v.lifetimeMs+Ae,e.expiresAtMs))return l("binding_mismatch");if(h.expiresAtMs<=Date.now())return l("binding_expired");if(a.get(h.port)?.abort(),a.delete(h.port),a.size>=Ce)return l("preview_capacity");let k=new AbortController;a.set(h.port,k);let y=ft({binding:h,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(k.signal.aborted)return null;let w=await e.inspect();return w?{binding:h,executorLaunchId:e.executorLaunchId,job:w}:null}});ht({binding:h,deviceRelayUrl:N,port:y,signal:k.signal}).then((w)=>w.closed,(w)=>{let x=w instanceof Error?w.message:"preview_failed";if(x!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:h.jobId,port:h.port,reason_code:x})}
|
|
3
|
+
`)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function ei(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=$t({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!_e(q(u),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(u){throw l.disposeSocket(),u}let E=de(l.journalDirectory),h=e.claim.capability===pe,N=()=>J.set(e.claim.operation_id,{path:l.journalDirectory,ino:E.ino,dev:E.dev,anyCompletion:h}),S=l.launchDirectory,k=A(S,"config.json"),y={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:U,protocolVersion:2,workerArtifactSha256:T,workerEntrypoint:H,targetGeneration:1,fenceId:X(),...process.platform==="win32"?{bashExecutable:Ye()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:A(S,"unused.env"),replSocketPath:A(S,"unused.sock"),readyPath:A(S,"ready.json"),directTerminalReceiptPath:A(S,"terminal.json"),launchId:X(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},w;try{je(k,JSON.stringify(y),{mode:384});let u=Po({configPath:k,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:S});w=e.spawnWorker?.(k,y)??ke(u.command,u.args,{...u.options,env:e.environment,stdio:[Ro,"ignore","ignore"]})}catch(u){throw l.disposeSocket(),u}let x=!1,z=new Promise((u,g)=>{w.once("exit",(f)=>{x=!0,u(f)}),w.once("error",(f)=>{x=!0,g(f)})});z.catch(()=>{});let me={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:y.fenceId,executorLaunchId:y.launchId,expiresAtMs:y.expiresAtMs},O=async(u)=>{let g=await oi(me,{type:"job",version:2,generation:1,id:X(),jobId:e.claim.operation_id,...u==="start"?{action:u,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:u==="inspect"?{action:u,input:{after:0}}:u==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:u,input:{}}},new AbortController().signal);if(!g.ok)throw D(g.error);return g.job},j=!1,L=!1,Q,Z=()=>{j=!0,ur(w,"SIGTERM")};e.signal.addEventListener("abort",Z,{once:!0});let C,ee=0,fe=async(u)=>{let g=[...u.output],f={version:1,process_id:e.claim.operation_id,state:u.state,exit_code:u.exitCode,first_cursor:u.firstCursor,next_cursor:u.nextCursor,truncated:u.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&g.length)g.shift(),f.truncated=!0,f.first_cursor=g[0]?.cursor??f.next_cursor+1;C=W.parse(f),await e.emit(C),ee=Date.now()};try{let u=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Y(y.readyPath)){if(x)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=u)throw D("process_start_unconfirmed");await ce(25)}let g=JSON.parse(Me(y.readyPath,"utf8"));if(g.launchId!==y.launchId||g.fenceId!==y.fenceId||g.workerArtifactSha256!==T)throw D();if(e.signal.throwIfAborted(),a.cancelRequested)return ae(e.claim.operation_id);let f;try{L=!0,f=await O("start")}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown")throw R;f=await O("inspect")}if(a.phase="running",a.cancel=async()=>{await O("cancel")},h&&e.preview)a.tunnels=ie({claim:e.claim,executorLaunchId:y.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>a.phase==="running"&&!x?await O("probe"):null});if(a.cancelRequested)await a.cancel(),f=await O("inspect");for(;;){if(!["starting","running"].includes(f.state))a.phase="settling",a.cancel=void 0;if(!C||C.state!==f.state||C.next_cursor!==f.nextCursor&&Date.now()-ee>=5000)await fe(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||x)throw D();await ce(1000);try{f=await O("inspect"),Q=void 0}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown"||e.signal.aborted||x||Date.now()-(Q??=Date.now())>120000)throw R}}if(!C||C.state==="uncertain")throw D();return C}finally{if(a.phase="settling",a.cancel=void 0,a.tunnels?.dispose(),a.tunnels=void 0,await a.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",Z),!x&&!j)ur(w,"SIGTERM");let u,g=await Promise.race([z.then((f)=>({code:f})),new Promise((f)=>{u=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(u)});if(!g){try{ur(w,"SIGKILL")}catch{}try{await z}finally{if(x)l.disposeSocket()}throw D("process_cleanup_unconfirmed")}try{if((j||e.signal.aborted)&&g.code===0&&L){b(S);let f=JSON.parse(m(y.directTerminalReceiptPath)),R=F.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===y.launchId&&f.fence_id===y.fenceId&&f.scope_id===l.scopeId&&R.success&&R.data.process_id===e.claim.operation_id){if(h)N();throw new lr(R.data)}}}catch(f){if(f instanceof lr)throw f}finally{if(x)l.disposeSocket()}if(g.code!==0&&!j&&L)throw D("process_cleanup_unconfirmed");if(!j&&g.code===0&&(C&&["exited","cancelled","expired"].includes(C.state)||!L&&a.cancelRequested)||h&&g.code===0&&!L)N()}}async function bo(e,a){if(a.kind===ne&&e.capability===pe){let E=M.get(e.operation_id);if(E?.claim===e&&E.tunnels)E.tunnels.open(a.payload);else K(a.payload,e.operation_id,"server_not_running");return!0}if(a.kind!==re||!Qn(e.capability)||!e.owner||a.payload.process_id!==e.operation_id)return!1;let p=M.get(e.operation_id);if(p&&p.claim!==e)return!1;let l=ue(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function ti(e,a){M.delete(e);let p=J.get(e);if(!p||a!=="succeeded"&&!p.anyCompletion)return J.delete(e),!1;try{let l=de(p.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==p.ino||l.dev!==p.dev||!G(l)||q(p.path)!==p.path||Y(A(p.path,"owner.lock")))return!1;return Te(p.path,{recursive:!0}),J.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Qn,Ba,Fa,ja,Ha,yo,Ua,wo,za,lr,ei,bo,ti};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra}from"./vm-hands-entry-lite-r131db1f.js";import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{W}from"./vm-hands-entry-lite-0xfme8gg.js";import{Q,so,ve,ao}from"./vm-hands-entry-lite-4kb5rq3d.js";import{Ir}from"./vm-hands-entry-lite-n9277v11.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Aa(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return so(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return ao(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Pa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function io(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Ra,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
|
-
export{Aa,
|
|
2
|
+
import{Ra}from"./vm-hands-entry-lite-39anhpg6.js";import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{W}from"./vm-hands-entry-lite-a4fn6ye1.js";import{Q,so,Se,ao}from"./vm-hands-entry-lite-hnsdwskm.js";import{Ir}from"./vm-hands-entry-lite-9c0g9ykw.js";import{t,o,_,d,n,ll,be,c,i}from"./vm-hands-entry-lite-n31pta3n.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Aa(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return so(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function ve(e={}){let s=e.path??Q(),r=Se(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(Se(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(Se(s)))return ve({fetchImpl:e.fetchImpl,path:s});return ao(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Pa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),me=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=be([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function io(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class ge{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await ve({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await ve({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(me,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Ra,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
|
+
export{Aa,ve,Pa,C,io,ge};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{us,ds,Mc,On}from"./vm-hands-entry-lite-hh0kba1y.js";import{A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{us,ds,Mc,On}from"./vm-hands-entry-lite-hh0kba1y.js";import{A}from"./vm-hands-entry-lite-2dx59pgq.js";import{Ue,wr,br}from"./vm-hands-entry-lite-g0bpdyfz.js";import{qr}from"./vm-hands-entry-lite-t3k90kdn.js";import{Go,Kt,_c,Ko,Jo,Xo,Jt}from"./vm-hands-entry-lite-x81fqstd.js";import{vi}from"./vm-hands-entry-lite-htrswrf0.js";import{Ee}from"./vm-hands-entry-lite-73tecmk2.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as ce}from"child_process";import{randomBytes as Ce}from"crypto";import{chmodSync as Ge,existsSync as ne,lstatSync as Oe,mkdirSync as he,readFileSync as S,rmSync as ae,writeFileSync as R}from"fs";import{connect as Je}from"net";import{join as p}from"path";var B=32,N=76;var M="./desktop-wallpaper-fd8f2wb2.jpg";var v="./dock-browser-y53t41cx.png";var Z="./dock-files-cp52htdw.png";var V="./dock-terminal-1es514yq.png";var z="./grok-wallpaper-71zwn2pj.jpg";var W="./grok-dock-browser-pzw59wnd.png";var j="./grok-dock-files-eckq444x.png";var U="./grok-dock-terminal-hcpz3e43.png";var ee=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -56,7 +56,7 @@ x.XSetWindowBackgroundPixmap(d, root, pix)
|
|
|
56
56
|
x.XClearWindow(d, root)
|
|
57
57
|
x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
|
|
58
58
|
x.XCloseDisplay(d)
|
|
59
|
-
`;function
|
|
59
|
+
`;function Pe(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
60
|
<openbox_config xmlns="http://openbox.org/3.4/rc">
|
|
61
61
|
<theme><keepBorder>no</keepBorder></theme>
|
|
62
62
|
<applications>
|
|
@@ -67,7 +67,7 @@ x.XCloseDisplay(d)
|
|
|
67
67
|
<size><width>${e.width-B*2}</width><height>${e.height-B-N}</height></size>
|
|
68
68
|
</application>
|
|
69
69
|
</applications>
|
|
70
|
-
</openbox_config>`}var
|
|
70
|
+
</openbox_config>`}var Ye=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
|
|
71
71
|
panel_items = L
|
|
72
72
|
panel_size = 100% 46
|
|
73
73
|
panel_margin = 0 10
|
|
@@ -88,7 +88,7 @@ launcher_tooltip = 1
|
|
|
88
88
|
launcher_item_app = /tmp/ara-chromium.desktop
|
|
89
89
|
launcher_item_app = /tmp/ara-files.desktop
|
|
90
90
|
launcher_item_app = /tmp/ara-terminal.desktop
|
|
91
|
-
`,re=32,
|
|
91
|
+
`,re=32,Ne=`# Remote sandbox dock (grok look) \u2014 small launcher icons only, centred, no panel fill
|
|
92
92
|
panel_items = L
|
|
93
93
|
panel_size = 100% ${re+16}
|
|
94
94
|
panel_margin = 0 0
|
|
@@ -109,7 +109,7 @@ launcher_tooltip = 1
|
|
|
109
109
|
launcher_item_app = /tmp/ara-chromium.desktop
|
|
110
110
|
launcher_item_app = /tmp/ara-files.desktop
|
|
111
111
|
launcher_item_app = /tmp/ara-terminal.desktop
|
|
112
|
-
`,
|
|
112
|
+
`,ue=`corner-radius = 12;
|
|
113
113
|
rounded-corners-exclude = [
|
|
114
114
|
"class_g = 'tint2'",
|
|
115
115
|
"window_type = 'dock'",
|
|
@@ -121,13 +121,13 @@ fading = false;
|
|
|
121
121
|
vsync = false;
|
|
122
122
|
inactive-opacity = 1.0;
|
|
123
123
|
active-opacity = 1.0;
|
|
124
|
-
`,
|
|
124
|
+
`,Re="/tmp/ara-dock-browser.png",ge=`[Desktop Entry]
|
|
125
125
|
Name=Chrome
|
|
126
126
|
Exec=chromium --no-sandbox %U
|
|
127
|
-
Icon=${
|
|
127
|
+
Icon=${Re}
|
|
128
128
|
Type=Application
|
|
129
129
|
Categories=Network;WebBrowser;
|
|
130
|
-
`,
|
|
130
|
+
`,Ke=`[Desktop Entry]
|
|
131
131
|
Name=Terminal
|
|
132
132
|
Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
|
|
133
133
|
Icon=/tmp/ara-dock-terminal.png
|
|
@@ -139,12 +139,12 @@ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
|
|
|
139
139
|
Icon=/tmp/ara-dock-files.png
|
|
140
140
|
Type=Application
|
|
141
141
|
Categories=System;FileManager;
|
|
142
|
-
`;var te={"wallpaper.jpg":M,"dock-browser.png":v,"dock-terminal.png":V,"dock-files.png":Z,"grok-wallpaper.jpg":z,"grok-dock-browser.png":W,"grok-dock-terminal.png":U,"grok-dock-files.png":j},
|
|
142
|
+
`;var te={"wallpaper.jpg":M,"dock-browser.png":v,"dock-terminal.png":V,"dock-files.png":Z,"grok-wallpaper.jpg":z,"grok-dock-browser.png":W,"grok-dock-terminal.png":U,"grok-dock-files.png":j},Fe=ee,qe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function $e(e){let D=(I)=>I.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),n=e.look==="grok",d=new Set(e.absent??[]),t=d.has("files")&&e.filesViewerExec?e.filesViewerExec:null;if(t)d.delete("files");let c=(n?Ne:Ye).split(`
|
|
143
143
|
`).filter((I)=>!(d.has("terminal")&&I.endsWith("/ara-terminal.desktop"))&&!(d.has("files")&&I.endsWith("/ara-files.desktop"))).join(`
|
|
144
|
-
`),a=(I)=>n?I.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):I,o=t?De.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):De,f=n?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":
|
|
144
|
+
`),a=(I)=>n?I.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):I,o=t?De.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):De,f=n?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":Pe(e.screen),"tint2/tint2rc":D(c),"picom/picom.conf":ue,...d.has("terminal")?{}:{"ara-terminal.desktop":D(a(Ke))},...d.has("files")?{}:{"ara-files.desktop":D(a(o))},"ara-chromium.desktop":D(a(ge)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Fe},X=[...u.slice(0,3),qe,`[ ! -f "$ROOT/${f}" ] || set_wallpaper "$ROOT/${f}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...u.slice(3)];return{files:i,start:X}}var u=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Qe=43200000,y=":99",Se=60000,Y=15000,g={width:1280,height:800},ke=/^[A-Za-z0-9._:-]{1,160}$/;function _e(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var we=["video","viewer","viewer_same_network","viewer_network","look"];function me(e,D=Date.now()){let n=["relay_url","session_id","expires_at"];if(!_e(e)||n.some((f)=>!(f in e))||Object.keys(e).some((f)=>!n.includes(f)&&!we.includes(f)))throw new r("invalid_display_request","Reason desktop request is malformed.");let d="video"in e?Mc(e.video):void 0,t="viewer"in e?us(e.viewer):null,c="look"in e?ds(e.look):null;if(d===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let a=null;try{a=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!a||a.protocol!=="wss:"&&a.protocol!=="ws:"||a.username||a.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!ke.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let o=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(o)||o<=D)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(o,D+Qe)).toISOString(),...d?{video:d}:{},...t?{viewer:t}:{},...d&&e.viewer_same_network===!0?{viewer_same_network:!0}:{},...c?{look:c}:{}}}function dn(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&A()?.features.display===!0}async function Bo(){if(process.platform==="win32")return dn()&&await Jt();if(process.platform!=="darwin")return dn();return await Jt()}function Te(e){he(e,{recursive:!0,mode:448});let D=Oe(e);if(!D.isDirectory()||D.isSymbolicLink()||process.getuid&&D.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");Ge(e,448)}function Me(e,D){let n=(t)=>{let c=Buffer.alloc(2);return c.writeUInt16BE(t.length),Buffer.concat([c,t])},d=Buffer.from([255,255]);return Buffer.concat([d,n(Buffer.alloc(0)),n(Buffer.from(e)),n(Buffer.from("MIT-MAGIC-COOKIE-1")),n(D)])}function x(e,D,n=2000){return new Promise((d)=>{let t=Je(e),c="",a=(o)=>{t.destroy(),d(o)};t.setTimeout(n,()=>a(!1)),t.once("error",()=>a(!1)),t.once("close",()=>a(!1)),t.once("connect",()=>{if(!D)a(!0)}),t.on("data",(o)=>{if(c+=o.toString("latin1"),c.length>=4)a(c.startsWith("RFB "))})})}async function Q(e,D){let n=Date.now()+D;while(Date.now()<n){if(await e())return!0;await new Promise((d)=>setTimeout(d,100))}return!1}function K(e,D,n,d=!1){return new Promise((t)=>{let c=ce(e,D,{detached:!0,stdio:"ignore",env:n});if(d)Ue(c.pid);c.once("error",()=>t(-1)),c.once("exit",(a)=>t(a)),c.unref(),setTimeout(()=>t(null),Y).unref()})}var J=null;function jt(e=s()){return J??=ve(e).finally(()=>{J=null}),J}async function ve(e){let D=A({home:e});if(!D?.xvfb||!D.x11vnc||!D.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");qr({root:D.root,automation:D.automation,extensionDir:D.extensionDir});let n=p(D.root,"display");Te(n);let d=await ze(e,n,D.x11vnc);if(d)return d;let t={display:y,xauthority:p(n,"Xauthority"),rfbSocket:p(n,"rfb.sock")},c=p(n,"pulse"),a=(async()=>{try{Te(c)}catch{return null}return await _c(c,D.pulseaudio)})();Te(p(n,"home"));let o=k(n,t,D.pulseaudio),f=async()=>({...t,sound:await a});if(await x({path:t.rfbSocket},!0))return pe(p(n,"theme"),u,o),await f();if(!ne(t.xauthority))R(t.xauthority,Me(y.slice(1),Ce(16)),{mode:384,flag:"wx"});let i=T(p(n,"theme"),t.display,g,e),X={path:`/tmp/.X11-unix/X${y.slice(1)}`};if(!await x(X,!1)){let I=`${g.width}x${g.height}`,L;if(D.xvnc)ae(t.rfbSocket,{force:!0}),L=K(D.xvnc,[t.display,"-geometry",I,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],o,!0);else L=K(D.xvfb,[t.display,"-screen","0",`${I}x24`,"-nolisten","tcp","-auth",t.xauthority],o,!0);if(!await Q(()=>x(X,!1),Y)||D.xvnc&&!await Q(()=>x({path:t.rfbSocket},!0),Y)){if(await L!==null&&Ze())wr("display");throw new r("display_unavailable","Reason could not start the virtual display.")}K(D.openbox,["--config-file",i.openboxConfig],o,!0)}if(await _(i,o),!await oe(D.x11vnc,t,n,"x11vnc.log",o))throw new r("display_unavailable","Reason could not start the desktop server.");return await f()}function Ze(){let e=0;try{e=Number(S(`/tmp/.X${y.slice(1)}-lock`,"utf8").trim())}catch{return!1}if(!Number.isSafeInteger(e)||e<=1)return!1;try{return process.kill(e,0),!0}catch(D){return D.code==="EPERM"}}function k(e,D,n){let d={HOME:p(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:D.display,XAUTHORITY:D.xauthority};if(n)d.PULSE_SERVER=Kt(Go(p(e,"pulse")));return d}async function oe(e,D,n,d,t){if(await x({path:D.rfbSocket},!0))return!0;ae(D.rfbSocket,{force:!0});let c=await K(e,["-display",D.display,"-auth",D.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",D.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",p(n,d)],t);if(c!==null&&c!==0)return!1;if(!await Q(()=>x({path:D.rfbSocket},!0),Y))return!1;return br("x11vnc",D.rfbSocket),!0}async function Ve(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],D=(n)=>Object.fromEntries(e.flatMap((d)=>n[d]?[[d,n[d]]]:[]));if(process.env.DISPLAY)return D(process.env);try{let n=await new Promise((d,t)=>se("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(c,a)=>c?t(c):d(a)));return D(Object.fromEntries(n.split(`
|
|
145
145
|
`).flatMap((d)=>{let t=d.indexOf("=");return t>0?[[d.slice(0,t),d.slice(t+1)]]:[]})))}catch{return{}}}var de=new Set;async function ze(e,D,n){let d=await Ve(),t=/^:(\d+)(?:\.\d+)?$/.exec(d.DISPLAY??"")?.[1];if(!t||`:${t}`===y||d.WAYLAND_DISPLAY||d.XDG_SESSION_TYPE==="wayland")return null;let c={display:`:${t}`,xauthority:d.XAUTHORITY??p(e,".Xauthority"),rfbSocket:p(D,`rfb-${t}.sock`)},a=`${c.display} ${c.xauthority}`;if(de.has(a)||!await x({path:`/tmp/.X11-unix/X${t}`},!1))return null;let o={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:c.display,XAUTHORITY:c.xauthority};if(await oe(n,c,D,`x11vnc-${t}.log`,o))return{...c,sound:null};return de.add(a),process.stderr.write(`Reason worker: your screen ${c.display} could not be served; using the virtual desktop
|
|
146
146
|
`),null}var ie="look";function fe(e){try{return ds(S(p(e,ie),"utf8").trim())??"reason"}catch{return"reason"}}function T(e,D,n,d,t=fe(e)){let c=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,a=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!ne(`/usr/bin/${i}`)).map(([i])=>i),o=`${c.replace(/ %U$/,"")} --app=file://${p(d,".reason","workspace")}/`,f=$e({root:e,display:D,screen:n,browserExec:c,absent:a,look:t,filesViewerExec:o});for(let i of["","openbox","tint2","picom"])Te(p(e,i));R(p(e,ie),`${t}
|
|
147
147
|
`,{mode:384});for(let[i,X]of Object.entries(f.files))R(p(e,i),X,{mode:384});for(let[i,X]of Object.entries(te))R(p(e,`ara-${i}`),S(X),{mode:384});return{root:e,openboxConfig:p(e,"openbox","rc.xml"),start:f.start}}function _(e,D){return pe(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],D)}function pe(e,D,n){let d=[`ROOT=${JSON.stringify(e)}`,...D].join(`
|
|
148
148
|
`);return new Promise((t)=>{let c=ce("/bin/sh",["-c",d],{stdio:"ignore",env:{...n,PATH:"/usr/bin:/bin"}}),a=setTimeout(()=>{c.kill(),t()},Y);c.once("error",()=>{clearTimeout(a),t()}),c.once("exit",()=>{clearTimeout(a),t()})})}var We=2073600,je=320;function er(e,D){let n=Math.min(1,Math.sqrt(We/(e.width*e.height))),d=(t,c)=>Math.min(Math.floor(c/8)*8,Math.max(je,Math.round(t*n/8)*8));return{width:d(e.width,D.width),height:d(e.height,D.height)}}function w(e,D,n){return new Promise((d)=>se(e,D,{env:n,encoding:"utf8",timeout:5000},(t,c)=>d(t?null:c)))}function Ie(e){let D=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),n=e.split(`
|
|
149
|
-
`),d=n.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of n.slice(d+1)){let a=/^\s+(\d+x\d+)\s/.exec(c);if(!a)break;t.push(a[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:n[d].split(" ")[0],modes:t}}async function rr(e,D,n){if(e.display!==y)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>w("xrandr",f,d),c=Ie(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let a=er(D,c.maximum);if(a.width===c.current.width&&a.height===c.current.height)return{size:a,changed:!1};let o=`${a.width}x${a.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[a.width,a.width,a.width,a.width,a.height,a.height,a.height,a.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return n(),await t(["--output",c.output,"--mode",o])===null?null:{size:a,changed:!0}}async function Dr(e,D){let n=s(),d=A({home:n});if(!d)return;let t=p(d.root,"display"),c=k(t,e,d.pulseaudio);await _(T(p(t,"theme"),e.display,D,n),c);let a=D.width-B*2,o=D.height-B-N;await w("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(a),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var F=Promise.resolve();function tr(e,D,n=()=>{}){let d=F.then(()=>rr(e,D,n));return F=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function $r(e,D){if(e.display!==y)return Promise.resolve();let n=F.then(async()=>{let d=s(),t=A({home:d});if(!t)return;let c=p(t.root,"display"),a=p(c,"theme");if(fe(a)===D)return;let o=k(c,e,t.pulseaudio),f=Ie(await w("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await _(T(a,e.display,f?.current??g,d,D),o)});return F=n.catch(()=>{}),n.catch(()=>{})}async function pn(e,D={}){let n=D.now??Date.now,d=me(e.payload,n());if(e.signal.throwIfAborted(),!d.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=D.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:c,look:a}=d,o=(D.video?.desktop??(t==="darwin"?async()=>Ko:t==="win32"?async()=>Jo:async()=>{let f=await jt();if(a)await $r(f,a);return f}))();return await dr(e.signal,d,D,n,(f)=>Xo(f,{request:c,desktop:o,...d.viewer?{viewer:d.viewer}:{},viewerSameNetwork:d.viewer_same_network===!0},{resizeDesktop:tr,...D.video}),(f)=>On({type:"error",code:f}))}function dr(e,D,n,d,t,c){let a=d();return new Promise((o,f)=>{let i=null,X=!1,I=!1,L,q,P,C=!1,l=null,E=(b)=>{if(I)return;if(l)b=l.outcome;I=!0,clearTimeout(L),clearTimeout(q),e.removeEventListener("abort",O),P?.close();try{i?.close(1000,"display_session_over")}catch{}if("error"in b){f(b.error);return}o({reason:b.reason,...P?.summary(),duration_ms:Math.max(0,d()-a)})},G=()=>E({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),O=()=>{let b=e.reason;E({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},m=()=>{if(!l||!i)return;let{outcome:b}=l,H=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!l.told)try{i.send(c(H))}catch{}E(b)};if(P=t({get done(){return I||l!==null},get open(){return X&&!I&&l===null},get bufferedAmount(){return i?.bufferedAmount??0},send(b){if(I||l||!X||!i)return;try{i.send(b)}catch{E({reason:"relay_closed"})}},end:(b)=>{if(I||l)return;if(!("error"in b)&&C&&X){E(b);return}if(l={outcome:b,told:!("error"in b)&&X},C&&X)m()}}),I){P.close();return}if(e.aborted){O();return}e.addEventListener("abort",O,{once:!0}),L=setTimeout(()=>E({reason:"session_expired"}),Math.max(1,Date.parse(D.expires_at)-d())),q=setTimeout(()=>E({reason:"viewer_absent"}),n.viewerWaitMs??
|
|
149
|
+
`),d=n.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of n.slice(d+1)){let a=/^\s+(\d+x\d+)\s/.exec(c);if(!a)break;t.push(a[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:n[d].split(" ")[0],modes:t}}async function rr(e,D,n){if(e.display!==y)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>w("xrandr",f,d),c=Ie(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let a=er(D,c.maximum);if(a.width===c.current.width&&a.height===c.current.height)return{size:a,changed:!1};let o=`${a.width}x${a.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[a.width,a.width,a.width,a.width,a.height,a.height,a.height,a.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return n(),await t(["--output",c.output,"--mode",o])===null?null:{size:a,changed:!0}}async function Dr(e,D){let n=s(),d=A({home:n});if(!d)return;let t=p(d.root,"display"),c=k(t,e,d.pulseaudio);await _(T(p(t,"theme"),e.display,D,n),c);let a=D.width-B*2,o=D.height-B-N;await w("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(a),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var F=Promise.resolve();function tr(e,D,n=()=>{}){let d=F.then(()=>rr(e,D,n));return F=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function $r(e,D){if(e.display!==y)return Promise.resolve();let n=F.then(async()=>{let d=s(),t=A({home:d});if(!t)return;let c=p(t.root,"display"),a=p(c,"theme");if(fe(a)===D)return;let o=k(c,e,t.pulseaudio),f=Ie(await w("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await _(T(a,e.display,f?.current??g,d,D),o)});return F=n.catch(()=>{}),n.catch(()=>{})}async function pn(e,D={}){let n=D.now??Date.now,d=me(e.payload,n());if(e.signal.throwIfAborted(),!d.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=D.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:c,look:a}=d,o=(D.video?.desktop??(t==="darwin"?async()=>Ko:t==="win32"?async()=>Jo:async()=>{let f=await jt();if(a)await $r(f,a);return f}))();return await dr(e.signal,d,D,n,(f)=>Xo(f,{request:c,desktop:o,...d.viewer?{viewer:d.viewer}:{},viewerSameNetwork:d.viewer_same_network===!0},{resizeDesktop:tr,...D.video}),(f)=>On({type:"error",code:f}))}function dr(e,D,n,d,t,c){let a=d();return new Promise((o,f)=>{let i=null,X=!1,I=!1,L,q,P,C=!1,l=null,E=(b)=>{if(I)return;if(l)b=l.outcome;I=!0,clearTimeout(L),clearTimeout(q),e.removeEventListener("abort",O),P?.close();try{i?.close(1000,"display_session_over")}catch{}if("error"in b){f(b.error);return}o({reason:b.reason,...P?.summary(),duration_ms:Math.max(0,d()-a)})},G=()=>E({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),O=()=>{let b=e.reason;E({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},m=()=>{if(!l||!i)return;let{outcome:b}=l,H=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!l.told)try{i.send(c(H))}catch{}E(b)};if(P=t({get done(){return I||l!==null},get open(){return X&&!I&&l===null},get bufferedAmount(){return i?.bufferedAmount??0},send(b){if(I||l||!X||!i)return;try{i.send(b)}catch{E({reason:"relay_closed"})}},end:(b)=>{if(I||l)return;if(!("error"in b)&&C&&X){E(b);return}if(l={outcome:b,told:!("error"in b)&&X},C&&X)m()}}),I){P.close();return}if(e.aborted){O();return}e.addEventListener("abort",O,{once:!0}),L=setTimeout(()=>E({reason:"session_expired"}),Math.max(1,Date.parse(D.expires_at)-d())),q=setTimeout(()=>E({reason:"viewer_absent"}),n.viewerWaitMs??Se);try{i=(n.connect??vi)(D.relay_url,(n.loadProxy??Ee)()?.url)}catch{G();return}i.binaryType="arraybuffer",i.onopen=()=>{if(I||!i)return;X=!0,P?.opened()},i.onmessage=(b)=>{if(I)return;let H=b.data,h=H instanceof ArrayBuffer?new Uint8Array(H):ArrayBuffer.isView(H)?new Uint8Array(H.buffer,H.byteOffset,H.byteLength):null;if(!h||h.byteLength===0)return;if(clearTimeout(q),C=!0,l){m();return}P?.received(h)},i.onclose=()=>{if(I)return;if(!X){G();return}E({reason:"relay_closed"})},i.onerror=()=>{if(I||X)return;G()}})}
|
|
150
150
|
export{dn,Bo,Te,jt,pn};
|