@probnaya/057-cli 1.2.0 → 1.2.2
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/README.md +2 -3
- package/dist-server/057.mjs +20 -21
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,7 +90,7 @@ serves, and `057 --open` opens it; the history is the same either way.
|
|
|
90
90
|
| **OS** | **macOS only.** The package declares `"os": ["darwin"]` and npm will refuse to install elsewhere — the process sampler reads a BSD process table and the Cursor reader looks in a macOS path. A 057 that silently mis-parsed your process table would be worse than one that will not start. |
|
|
91
91
|
| **Node** | 24.x. The package declares `>=22.5.0`, where the built-in SQLite the store needs first exists, but only 24 has been exercised. |
|
|
92
92
|
| **Browser** | A WebGPU browser: Chrome 113+, Edge 113+, or Safari 26+. Without WebGPU the interface says so plainly rather than falling back to something that is not FIELD. |
|
|
93
|
-
| **Network** | The web / CLI surface stays on this Mac. The macOS app checks its signed update feed about once a day. When a trusted 057 Display is paired, current FIELD state is delivered directly to that device on the local network.
|
|
93
|
+
| **Network** | The web / CLI surface stays on this Mac. The macOS app checks its signed update feed about once a day. When a trusted 057 Display is paired, current FIELD state is delivered directly to that device on the local network. |
|
|
94
94
|
|
|
95
95
|
## What it reads, and what it keeps
|
|
96
96
|
|
|
@@ -116,8 +116,7 @@ overrides the database path; `057 status` prints the telemetry-store path, size
|
|
|
116
116
|
you pair a trusted 057 Display, Desktop sends that device the complete current `057.landscape` over
|
|
117
117
|
an authenticated local connection: machine, project and task labels; execution/session labels;
|
|
118
118
|
statuses, timings and geometry. It does not send source files, prompts, response bodies, telemetry
|
|
119
|
-
history, credentials, paths, models, tools or token counts.
|
|
120
|
-
will be publicly usable only after 057 Display for iPhone is released. There is no account, cloud,
|
|
119
|
+
history, credentials, paths, models, tools or token counts. There is no account, cloud,
|
|
121
120
|
synchronisation, product analytics or crash reporting. This is 057's own behaviour; the runtimes it
|
|
122
121
|
observes talk to their providers on their own terms.
|
|
123
122
|
|
package/dist-server/057.mjs
CHANGED
|
@@ -100,18 +100,18 @@ ${e.join(`
|
|
|
100
100
|
${r}
|
|
101
101
|
-----END ${t}-----
|
|
102
102
|
`}function XE(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}async function im(t){return{privateKey:await Ze.subtle.exportKey("jwk",t.privateKey),publicKey:await Ze.subtle.exportKey("jwk",t.publicKey)}}async function am(t){return{privateKey:await Ze.subtle.importKey("jwk",t.privateKey,ho,!0,["sign"]),publicKey:await Ze.subtle.importKey("jwk",t.publicKey,ho,!0,["verify"])}}function _v(t){const e=new js(t).publicKey.export({format:"jwk"});if(!e.x||!e.y)throw new Error("057 Display CA is not a P-256 key");const r=Buffer.concat([Buffer.from([4]),Buffer.from(e.x,"base64url"),Buffer.from(e.y,"base64url")]);return Qn("sha256").update(r).digest("base64url")}async function JE(){const t=Date.now(),e=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),r=await wl.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+10*365*kl),signingAlgorithm:Al,extensions:[new fo(!0,0,!0),new po(jn.keyCertSign|jn.cRLSign,!0),await _o.create(e.publicKey,!1,Ze)]},Ze),n=r.toString("pem"),s=_v(n),o=Qn("sha256").update(s).digest("hex").slice(0,20),i=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),a=await wl.create({subject:`CN=057 Display ${o}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+2*365*kl),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([qE],!0),new jd([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await pn.create(e.publicKey,!1,Ze)]},Ze);return{version:1,coreId:o,caPin:s,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await im(e),serverKeys:await im(i)}}async function ZE(t){if(t.caPin!==_v(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await am(t.caKeys),r=await am(t.serverKeys),n=YE("PRIVATE KEY",await Ze.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:Qn("sha256").update(new js(t.serverCertificate).raw).digest("base64url"),caCertificate:t.caCertificate,serverCertificate:t.serverCertificate,serverPrivateKey:n,async issueClient(s,o){const i=new ArrayBuffer(s.byteLength);new Uint8Array(i).set(s);const a=await Ze.subtle.importKey("raw",i,ho,!0,["verify"]),c=Date.now(),u=c+5*365*kl,d=(await wl.create({subject:`CN=${o.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new js(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(c-5*Sl),notAfter:new Date(u),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([zE],!0),await pn.create(e.publicKey,!1,Ze)]},Ze)).toString("pem"),m=new js(d);return{certificate:d,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function QE(t){const e=Rv(t),r=se(e,"identity.json");Dc(ii(e),{recursive:!0,mode:448}),Dc(e,{recursive:!0,mode:448}),ea(e,448);let n;if(fe(r)){if(n=JSON.parse(Cl(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await JE(),XE(r,`${JSON.stringify(n)}
|
|
103
|
-
`);return ZE(n)}const
|
|
104
|
-
`)}}function n1(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function s1(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return sb({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class o1{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Dn(18).toString("base64url"),secret:Dn(32),expiresAt:e+e1};this.grants.set(r.id,r);const n={p:Zi,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==Zi)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const s=this.grants.get(e.grantId);if(!s||s.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const o=Buffer.from(e.secret,"base64url");if(o.length!==s.secret.length||!rb(o,s.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!nb("sha256",n1(e),s1(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const xl="127.0.0.1",i1="0.0.0.0",a1=16*1024,c1=4e3;function cm(t,e,r){return new Promise((n,s)=>{t.once("error",s),t.listen(e,r,()=>{t.off("error",s);const o=t.address();if(!o||typeof o=="string")return s(new Error("Display listener has no TCP address"));n(o.port)})})}function jc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function Lt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
|
|
105
|
-
`)}async function u1(t){let e=0;const r=[];for await(const n of t){const s=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=s.length,e>a1)throw new Error("request body is too large");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function l1(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function d1(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function f1(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(15e3)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==hi||r.version!==qs||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:hi,version:qs,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function p1(t,e,r,n){e.statusCode=200,e.setHeader("content-type","text/event-stream; charset=utf-8"),e.setHeader("cache-control","no-store"),e.setHeader("connection","keep-alive"),e.setHeader("x-content-type-options","nosniff"),e.flushHeaders();let s=!1,o="",i=0,a;const c=()=>{s=!0,a&&clearInterval(a)};t.once("close",c);const u=async()=>{if(!s)try{const l=await f1(r);if(l.wire!==o){o=l.wire;const d=Qn("sha256").update(l.wire).digest("base64url").slice(0,16);e.write(`id: ${d}
|
|
103
|
+
`);return ZE(n)}const e1=4e3,t1=8e3;function r1(t,e,r){t.statusCode=200,t.setHeader("content-type","text/event-stream; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("connection","keep-alive"),t.setHeader("x-content-type-options","nosniff"),t.flushHeaders();let n=!1,s=!1,o;const i=()=>{n=!0,clearInterval(c),clearInterval(u)},a=async()=>{if(!(n||s)){s=!0;try{const l=await e();if(n)return;l.wire!==o&&(o=l.wire,t.write(`id: ${l.id}
|
|
106
104
|
event: landscape
|
|
107
105
|
data: ${l.wire}
|
|
108
106
|
|
|
109
|
-
`)}
|
|
107
|
+
`))}catch(l){n||(r(l),i(),t.end())}finally{s=!1}}},c=setInterval(()=>{a()},e1),u=setInterval(()=>{n||t.write(`: 057
|
|
110
108
|
|
|
111
|
-
`)}
|
|
112
|
-
|
|
109
|
+
`)},t1);t.once("close",i),a()}const Zi=1,n1=12e4;function s1(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}class o1{path;state;constructor(e){if(this.path=se(e,"trusted.json"),this.state=fe(this.path)?JSON.parse(Cl(this.path,"utf8")):{version:1,displays:[]},this.state.version!==1)throw new Error(`unsupported 057 Display trust version ${String(this.state.version)}`)}list(){return this.state.displays.map(e=>({...e}))}trusts(e){const r=e.replaceAll(":","").toLowerCase();return this.state.displays.some(n=>n.fingerprint===r&&n.revokedAt===void 0&&n.expiresAt>Date.now())}add(e,r){const n=this.state.displays.find(s=>s.deviceId===e.deviceId&&s.revokedAt===void 0);n&&(n.revokedAt=Date.now()),this.state.displays.push({deviceId:e.deviceId,name:e.deviceName.slice(0,80)||"iPhone",fingerprint:r.fingerprint,serial:r.serial,pairedAt:Date.now(),expiresAt:r.expiresAt}),this.save()}revoke(e){const r=this.state.displays.find(n=>n.deviceId===e&&n.revokedAt===void 0);return r?(r.revokedAt=Date.now(),this.save(),!0):!1}save(){s1(this.path,`${JSON.stringify(this.state,null,1)}
|
|
110
|
+
`)}}function i1(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function a1(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return sb({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class c1{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Dn(18).toString("base64url"),secret:Dn(32),expiresAt:e+n1};this.grants.set(r.id,r);const n={p:Zi,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==Zi)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const s=this.grants.get(e.grantId);if(!s||s.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const o=Buffer.from(e.secret,"base64url");if(o.length!==s.secret.length||!rb(o,s.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!nb("sha256",i1(e),a1(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const xl="127.0.0.1",u1="0.0.0.0",l1=16*1024;function cm(t,e,r){return new Promise((n,s)=>{t.once("error",s),t.listen(e,r,()=>{t.off("error",s);const o=t.address();if(!o||typeof o=="string")return s(new Error("Display listener has no TCP address"));n(o.port)})})}function jc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function Lt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
|
|
111
|
+
`)}async function d1(t){let e=0;const r=[];for await(const n of t){const s=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=s.length,e>l1)throw new Error("request body is too large");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function f1(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function p1(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function h1(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(6e4)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==hi||r.version!==qs||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:hi,version:qs,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function m1(t,e,r){r1(t,async()=>{const n=await h1(e),s=Qn("sha256").update(n.wire).digest("base64url").slice(0,16);return{wire:n.wire,id:s}},n=>r.warn(`[057] Display landscape delivery failed: ${String(n)}`))}function y1(t,e){const r=t.socket.remoteAddress;return(r===xl||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function g1(t){const e=await QE(t.storePath),r=new o1(Rv(t.storePath)),n=new c1(e),s=cb({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
|
|
112
|
+
${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",requestCert:!0,rejectUnauthorized:!1},(l,d)=>{(async()=>{const m=new URL(l.url??"/","https://057-display.local");if(l.method==="POST"&&m.pathname==="/v1/pair"){try{const p=f1(await d1(l)),y=await n.redeem(p,r);Lt(d,201,{protocol:Zi,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new js(e.caCertificate).raw).toString("base64"),clientCertificate:y.certificateDer,expiresAt:y.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),Lt(d,403,{error:p instanceof Error?p.message:String(p)})}return}if(l.method==="GET"&&m.pathname==="/v1/landscape"){const p=p1(l);if(!p||!r.trusts(p)){Lt(d,401,{error:"trusted Display certificate required"});return}m1(d,t.loopbackUrl,t.log);return}Lt(d,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),d.headersSent?d.end():Lt(d,500,{error:"Display request failed"})})});s.requestTimeout=15e3,s.headersTimeout=15e3;const o=await cm(s,t.port??0,u1),i=Dn(32).toString("base64url"),a=pm((l,d)=>{(async()=>{if(!y1(l,i)){Lt(d,403,{error:"local Display control token required"});return}const m=new URL(l.url??"/","http://localhost");if(l.method==="POST"&&m.pathname==="/v1/grants"){Lt(d,201,n.create());return}if(l.method==="GET"&&m.pathname==="/v1/displays"){Lt(d,200,{displays:r.list()});return}if(l.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));Lt(d,r.revoke(p)?200:404,{revoked:p});return}Lt(d,404,{error:"not found"})})()}),c=await cm(a,0,xl).catch(async l=>{throw await jc(s),l}),u={protocol:Zi,landscape:qs,coreId:e.coreId,caPin:e.caPin,port:o,controlUrl:`http://${xl}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${o}`),{info:u,async close(){await Promise.all([jc(a),jc(s)])}}}const Pd=5057,ar="127.0.0.1",v1=["localhost","127.0.0.1","[::1]","::1"],b1=10,w1={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function um(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const s=yo(t,`.${Xv(n)}`);if(s!==t&&!s.startsWith(t+Lc)||!fe(s)||!Qi(s).isFile())return!1;const o=w1[Jv(s).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",o),r.setHeader("x-content-type-options","nosniff"),ql(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),dm(s).pipe(r),!0}function A1(t,e,r,n){return new Promise((s,o)=>{let i=n,a=e;const c=u=>{if(u.code==="EADDRINUSE"&&i>1){i--,a++,t.listen(a,r);return}t.off("error",c),o(u)};t.on("error",c),t.once("listening",()=>{t.off("error",c);const u=t.address();s(typeof u=="object"&&u?u.port:a)}),t.listen(a,r)})}function S1(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(k1.has(r))return`refusing to be embedded as ${r}`;const n=t.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${e}`:null}const k1=new Set(["iframe","frame","embed","object","fencedframe"]);async function Mv(t){const e=t.log??Iy,r=yo(t.root),n=t.host??ar,s=n===ar||n==="::1"||n==="localhost",o=t.runtime?.path??t.storePath??sa();if(!t.runtime){const y=await kS(o);if(y)throw new Gl(y)}const i=t.runtime??Cy({path:t.storePath,log:e,retention:t.retention,observe:t.observe}),a=import.meta.url.endsWith(".mjs")?wS(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?DS(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=qS({runtime:i,log:e,version:t.version,activity:a,landscape:c,allowedHosts:s?v1:null}),l=pm((y,v)=>{(async()=>{try{if(await u(y,v))return;if(y.method!=="GET"&&y.method!=="HEAD"){v.statusCode=405,v.setHeader("allow","GET, HEAD"),v.end();return}const g=new URL(y.url??"/","http://localhost").pathname,C=S1(y,g);if(C){e.warn(`[057] ${C}`),v.statusCode=403,v.setHeader("content-type","text/plain; charset=utf-8"),ql(v),v.end(`${C}
|
|
113
113
|
`);return}if(um(r,g==="/"?"/index.html":g,v)||!g.startsWith("/assets/")&&um(r,"/index.html",v))return;v.statusCode=404,v.setHeader("content-type","text/plain; charset=utf-8"),v.end(`not found
|
|
114
|
-
`)}catch(g){e.error(`[057] request failed: ${String(g)}`),v.headersSent||(v.statusCode=500),v.end()}})()}),d=await
|
|
114
|
+
`)}catch(g){e.error(`[057] request failed: ${String(g)}`),v.headersSent||(v.statusCode=500),v.end()}})()}),d=await A1(l,t.port??Pd,n,b1).catch(y=>{throw i.stop(),y}),m=s?"localhost":n;let p;if(t.display)try{p=await g1({storePath:i.path,loopbackUrl:`http://${ar}:${d}`,log:e})}catch(y){e.error(`[057] authenticated Display delivery could not start: ${String(y)}`)}return xS(i.path,{pid:process.pid,url:`http://${s?ar:n}:${d}`,version:t.version??"dev",contract:Wl,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...p?{display:p.info}:{}}),{url:`http://${m}:${d}`,port:d,host:n,runtime:i,server:l,display:p?.info,close(){ES(i.path),a?.close(),c?.close();const y=new Promise(v=>l.close(()=>v()));return l.closeAllConnections?.(),Promise.all([y,p?.close()]).then(()=>i.stop())}}}function x1(t){return yo(Zv(new URL(".",t)),"..","dist")}function E1(t,e){switch(e.operation){case"summary":return{operation:"summary",result:t.summary(e.period)};case"availability":return{operation:"availability",result:t.availability(e.period)};case"compare":return{operation:"compare",result:t.compare(e.periodA,e.periodB)};case"breakdown":return{operation:"breakdown",result:t.breakdown(e.period,e.dimension)}}}const mo="1.2.2";function I1(t){const e={command:"serve",activityOperation:"summary",activityPrevious:!1,activityAscii:!1,open:!1,yes:!1,desktop:!1},r=[...t],n=r[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")e.command=n,r.shift();else if(n==="activity"){e.command="activity",r.shift();const s=r[0];if(s&&!s.startsWith("-")){const o=j1(s);if(o)e.activityOperation=o.operation,e.activityDimension=o.dimension,e.activityItemFilter=o.itemFilter;else if(s==="today")e.activityOperation="summary";else if(Kw.includes(s))e.activityOperation=s;else return{...e,command:"help",error:`unknown activity operation: ${s}`};r.shift()}}else return{...e,command:"help",error:`unknown command: ${n}`};for(;r.length;){const s=r.shift(),[o,i]=s.includes("=")?C1(s,"="):[s,void 0],a=()=>i??r.shift();switch(o){case"-h":case"--help":e.command="help";break;case"-v":case"--version":e.command="version";break;case"--open":e.open=!0;break;case"--yes":case"-y":e.yes=!0;break;case"--desktop":e.desktop=!0;break;case"--last":{const c=a(),u=c?.match(/^(\d+)d$/),l=u?Number(u[1]):NaN;if(!Number.isInteger(l)||l<1)return{...e,command:"help",error:`--last needs a positive duration such as 7d, got ${c}`};e.activityLastDays=l;break}case"--previous":e.activityPrevious=!0;break;case"--by":{const c=a(),u=["model","executor","lifecycle","outcome","session","duration-band"];if(!c||!u.includes(c))return{...e,command:"help",error:`--by needs one of: ${u.join(", ")}`};e.activityDimension=c;break}case"--width":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<1)return{...e,command:"help",error:`--width needs a positive number of columns, got ${c}`};e.activityWidth=u;break}case"--color":{const c=a();if(c!=="always"&&c!=="never"&&c!=="auto")return{...e,command:"help",error:`--color needs always, never or auto, got ${c}`};e.activityColor=c;break}case"--ascii":e.activityAscii=!0;break;case"--port":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...e,command:"help",error:`--port needs a port number, got ${c}`};e.port=u;break}case"--host":{const c=a();if(!c)return{...e,command:"help",error:"--host needs a value"};e.host=c;break}case"--store":{const c=a();if(!c)return{...e,command:"help",error:"--store needs a path"};e.store=c;break}default:return{...e,command:"help",error:`unknown option: ${o}`}}}return e}function C1(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const O1=`057 — a spatial interface for observing the shape of a computational workday
|
|
115
115
|
|
|
116
116
|
057 observe this machine and serve the interface
|
|
117
117
|
057 status where the store is, what it holds, what is observed
|
|
@@ -150,26 +150,25 @@ Environment
|
|
|
150
150
|
|
|
151
151
|
057 observes this machine only. It has no account, no cloud, and no analytics. Its browser API
|
|
152
152
|
stays on this Mac. If you pair a 057 Display, current FIELD labels and timing are sent directly
|
|
153
|
-
to that trusted device on your local network.
|
|
154
|
-
released. Reset deletes the SQLite store and any Display trust.
|
|
153
|
+
to that trusted device on your local network. Reset deletes the SQLite store and any Display trust.
|
|
155
154
|
|
|
156
155
|
--host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
|
|
157
156
|
anything that can reach that address. Do not do it on a network you do not control.
|
|
158
|
-
`;function kr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function Gs(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function
|
|
159
|
-
`)}async function
|
|
160
|
-
`),(r.error?console.error:console.log)(
|
|
157
|
+
`;function kr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function Gs(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function N1(t,e,r,n){const s=["",` 057 ${mo}`,` ${t}`,"",kr(" observing this machine only — its process table, and any AI runtime state it finds"),kr(` storing ${e}`),kr(` keeping ${r}`),kr(" sending local only to a paired Display; no account, no cloud, no analytics."),kr(" resetting 057 reset")];return n!==ar&&s.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),s.push(""),s.join(`
|
|
158
|
+
`)}async function T1(t){if(!process.stdin.isTTY)return!1;const e=Yv({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>e.question(`${t} [y/N] `,n))).trim().toLowerCase()==="y"}finally{e.close()}}async function B1(t,e){const r=I1(t);if(r.command==="version")return console.log(mo),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
|
|
159
|
+
`),(r.error?console.error:console.log)(O1),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=sa(),s=ly();if(r.command==="status")return P1(n,s);if(r.command==="activity")return $1(n,s,r);if(r.command==="compact")return L1(n);if(r.command==="reset")return U1(n,r.yes);if(r.desktop)return D1(e,n,s,r.port??0);const o=r.port??V1(process.env.O57_PORT)??Pd,i=r.host??process.env.O57_HOST??ar;let a;try{a=await Mv({root:e,port:o,host:i,storePath:n,retention:s,log:Ld(),version:mo,display:!0})}catch(l){if(l instanceof Gl){const d=l.record;return r.open?(console.log(`
|
|
161
160
|
${l.message}${d.owner==="desktop"?" — 057.app":""}.
|
|
162
161
|
Opening ${d.url}
|
|
163
162
|
`),await lm(d.url),0):(console.error(`
|
|
164
163
|
${l.message}.
|
|
165
164
|
Open ${d.url} (\`057 --open\`), or stop that 057 before starting another.
|
|
166
|
-
`),1)}return sc(l)}console.log(
|
|
165
|
+
`),1)}return sc(l)}console.log(N1(a.url,n,ia(s),i)),r.open&&await lm(a.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
|
|
167
166
|
057 stopping — history is on disk
|
|
168
|
-
`),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function
|
|
169
|
-
`),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:o,periodB:
|
|
170
|
-
`),2;a={operation:"breakdown",period:o,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:o}:a={operation:"summary",period:o};return process.stdout.write(qt(
|
|
167
|
+
`),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function $1(t,e,r){let n;try{n=aa(t)}catch(s){return sc(s)}try{const s=Date.now(),o=_1(s,r.activityLastDays),i=ky(n,e,_r().id,s);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
|
|
168
|
+
`),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:o,periodB:M1(o)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
|
|
169
|
+
`),2;a={operation:"breakdown",period:o,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:o}:a={operation:"summary",period:o};return process.stdout.write(qt(E1(i,a),r.activityItemFilter,R1(r,process.stdout,process.env))),0}finally{n.close()}}function R1(t,e,r){const n=e.isTTY===!0,s=t.activityWidth??(n&&e.columns?e.columns:80),o=r.FORCE_COLOR!==void 0&&r.FORCE_COLOR!=="0"&&r.FORCE_COLOR!=="false",i=t.activityColor??(o?"always":"auto"),a=i==="always"||i==="auto"&&n&&!r.NO_COLOR&&r.TERM!=="dumb",c=r.LC_ALL||r.LC_CTYPE||r.LANG,u=!c||/utf-?8/i.test(c);return{width:s,color:a,ascii:t.activityAscii||!u}}function _1(t,e){if(e!==void 0)return{from:t-e*864e5,to:t};const r=new Date(t);return r.setHours(0,0,0,0),{from:r.getTime(),to:t}}function M1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function j1(t){switch(t){case"running":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"running"};case"waiting":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"waiting"};case"failed":return{operation:"breakdown",dimension:"outcome",itemFilter:"failed"};case"sessions":return{operation:"breakdown",dimension:"session"};case"usage":case"concurrency":return{operation:"summary"};default:return}}async function D1(t,e,r,n){const s=c=>{process.stdout.write(`${JSON.stringify(c)}
|
|
171
170
|
`)};let o;try{o=await Mv({root:t,port:n,host:ar,storePath:e,retention:r,log:Ld(),version:mo,owner:"desktop",display:!0})}catch(c){if(c instanceof Gl){const u=c.record;return s({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof gt?(s({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(s({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let i=!1;const a=c=>{i||(i=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
|
|
172
|
-
`),o.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.stdin.on("end",()=>a("app closed its pipe")),process.stdin.on("close",()=>a("app closed its pipe")),process.stdin.resume(),s({event:"ready",url:`http://${ar}:${o.port}`,pid:process.pid,version:mo,store:e,contract:Wl,display:o.display}),new Promise(()=>{})}function
|
|
171
|
+
`),o.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.stdin.on("end",()=>a("app closed its pipe")),process.stdin.on("close",()=>a("app closed its pipe")),process.stdin.resume(),s({event:"ready",url:`http://${ar}:${o.port}`,pid:process.pid,version:mo,store:e,contract:Wl,display:o.display}),new Promise(()=>{})}function P1(t,e){let r=null;if(t!==":memory:"&&fe(t))try{r=aa(t)}catch(n){return sc(n)}try{const n=r?.stats()??{events:0,claims:0,bySource:[],earliest:null,latest:null},s=r?.sizeBytes()??{db:0,wal:0,shm:0,total:0},o=oa(t).map(a=>Vl(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
|
|
173
172
|
store ${t}${ay()?" (from O57_STORE)":""}
|
|
174
173
|
schema ${r?r.schemaVersion:"none"}
|
|
175
174
|
size ${Gs(s.total)} ${kr(`(db ${Gs(s.db)}, wal ${Gs(s.wal)})`)}
|
|
@@ -179,12 +178,12 @@ anything that can reach that address. Do not do it on a network you do not contr
|
|
|
179
178
|
permissions ${o||"none — no store yet"}
|
|
180
179
|
`),n.bySource.length===0)console.log(` nothing has been captured yet
|
|
181
180
|
`);else{for(const a of n.bySource){const c=`${new Date(a.first).toISOString().slice(0,10)} → ${new Date(a.last).toISOString().slice(0,10)}`;console.log(` ${a.source.padEnd(20)}${String(a.events).padStart(10)} events ${kr(c)}`)}console.log("")}const i=uy();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
|
|
182
|
-
`),0}finally{r?.close()}}function
|
|
181
|
+
`),0}finally{r?.close()}}function L1(t){let e;try{e=Cy({path:t,observe:!1,log:Ld()})}catch(r){return sc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const s=e.store.sizeBytes().total;return console.log(`
|
|
183
182
|
removed ${n.processEvents+n.otherEvents} expired events
|
|
184
183
|
${Gs(r)} → ${Gs(s)}
|
|
185
|
-
`),0}finally{e.stop()}}async function
|
|
184
|
+
`),0}finally{e.stop()}}async function U1(t,e){const r=wA(t);console.log(`
|
|
186
185
|
this deletes, permanently:
|
|
187
|
-
`);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await
|
|
186
|
+
`);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await T1(" delete the local store?"))return console.log(` nothing was deleted
|
|
188
187
|
`),1;for(const n of r)fm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
|
|
189
188
|
`),0}function Ld(){return{info:t=>{process.stderr.write(`${kr(t)}
|
|
190
189
|
`)},warn:t=>{process.stderr.write(`${t}
|
|
@@ -198,4 +197,4 @@ anything that can reach that address. Do not do it on a network you do not contr
|
|
|
198
197
|
057: cannot bind that address or port (${e}).
|
|
199
198
|
`),1):(console.error(`
|
|
200
199
|
057: ${t instanceof Error?t.message:String(t)}
|
|
201
|
-
`),1)}function
|
|
200
|
+
`),1)}function V1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function lm(t){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:r}=await import("node:child_process");try{r(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function dO(t){const e=await B1(t,x1(import.meta.url));e!==0&&process.exit(e)}export{x1 as defaultRoot,dO as main,B1 as run};
|