omo-ai 5.1.57 → 5.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/bin/darwin/omo-keychain +0 -0
  2. package/bin/lib/doctor.js +2 -1
  3. package/bin/lib/provider-map.json +1 -1
  4. package/bin/lib/same-version.js +16 -0
  5. package/bin/lib/service-auth.generated.js +2 -2
  6. package/package.json +2 -2
  7. package/plugin/CHANGELOG.md +21 -0
  8. package/plugin/extensions/gateway-store-worker.mjs +1 -1
  9. package/plugin/extensions/memory-run-supervisor.mjs +1 -1
  10. package/plugin/extensions/omo-claim-receipt.js +1 -1
  11. package/plugin/extensions/omo-computer-use.js +1 -1
  12. package/plugin/extensions/omo-desktop-toolkit.js +1 -1
  13. package/plugin/extensions/omo-device-account.js +1 -1
  14. package/plugin/extensions/omo-feedback.js +2 -2
  15. package/plugin/extensions/omo-init-deep-advisor.js +1 -1
  16. package/plugin/extensions/omo-member.js +2 -2
  17. package/plugin/extensions/omo-memory-commands.js +1 -1
  18. package/plugin/extensions/omo-memory-doctor.js +1 -1
  19. package/plugin/extensions/omo-memory-memfs.js +1 -1
  20. package/plugin/extensions/omo-memory-palace.js +1 -1
  21. package/plugin/extensions/omo-memory-sync.js +1 -1
  22. package/plugin/extensions/omo-onboarding-scan.js +2 -2
  23. package/plugin/extensions/omo-recall-store.js +1 -1
  24. package/plugin/extensions/omo-session-history.js +1 -1
  25. package/plugin/extensions/omo-side-panel.js +2 -2
  26. package/plugin/extensions/omo-task.js +2 -2
  27. package/plugin/extensions/omo-telemetry-otlp.js +1 -1
  28. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  29. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  30. package/plugin/extensions/omo-thread-client.js +1 -1
  31. package/plugin/extensions/omo.js +3 -3
  32. package/plugin/package.json +1 -1
  33. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  34. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  35. package/plugin/runtime/category-coverage/index.js +1 -1
  36. package/plugin/runtime/rollback-migrate.js +2 -2
  37. package/plugin/runtime/task-config/index.js +1 -1
  38. package/plugin/runtime/thread-sdk/sdk.js +2 -2
  39. package/plugin/skills/browser/runtime/omowright/index.js +20 -19
  40. package/plugin/skills/browser/runtime/omowright/manifest.json +3 -3
  41. package/plugin/skills/ultimate-browsing/engine/executor.py +56 -5
Binary file
package/bin/lib/doctor.js CHANGED
@@ -10,6 +10,7 @@ import { migrationReport } from "./doctor-migration.js"
10
10
  import { launchSpecDoctorLines } from "./launch-spec-mode.js"
11
11
  import { piConfigReport } from "./doctor-pi-config.js"
12
12
  import { needsSetupSuggestion } from "./setup-detect.js"
13
+ import { sameVersion } from "./same-version.js"
13
14
 
14
15
  export function installedDistTag(version) {
15
16
  return releaseChannel(version)
@@ -401,7 +402,7 @@ export function runDoctor(inventory, args = [], options = {}) {
401
402
  try {
402
403
  const expected = packageManifest().dependencies["@code-yeongyu/senpi"]
403
404
  const installed = readJson(join(senpi.packageRoot, "package.json")).version
404
- if (installed === expected) pass(lines, `senpi version ${installed}`)
405
+ if (sameVersion(installed, expected)) pass(lines, `senpi version ${installed}`)
405
406
  else {
406
407
  fail(lines, `senpi version: expected ${expected}, found ${installed}`)
407
408
  failed = true
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "Derived from @code-yeongyu/senpi 2026.10.31-2 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
2
+ "_comment": "Derived from @code-yeongyu/senpi 2026.11.2-1 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
3
3
  "builtinProviderIds": [
4
4
  "alibaba-token-plan",
5
5
  "amazon-bedrock",
@@ -0,0 +1,16 @@
1
+ // npm normalizes a published version (`2026.11.02-1` -> `2026.11.2-1`) but the tarball keeps the
2
+ // manifest it was packed with, so an installed engine can report a zero-padded spelling of the exact pin.
3
+ // Two versions are the same release when they match after dropping build metadata and leading zeros
4
+ // from every numeric identifier.
5
+ function normalize(version) {
6
+ const [core = "", ...pre] = String(version).trim().replace(/^v/, "").split("+")[0].split("-")
7
+ const numeric = (part) => (/^\d+$/.test(part) ? String(Number.parseInt(part, 10)) : part)
8
+ const release = core.split(".").map(numeric).join(".")
9
+ const prerelease = pre.join("-").split(".").filter((part) => part !== "").map(numeric).join(".")
10
+ return prerelease === "" ? release : `${release}-${prerelease}`
11
+ }
12
+
13
+ export function sameVersion(left, right) {
14
+ if (typeof left !== "string" || typeof right !== "string") return false
15
+ return normalize(left) === normalize(right)
16
+ }
@@ -182,8 +182,8 @@ public static class LaSddl {
182
182
  `,SID_TOKEN_SCRIPT=String.raw`
183
183
  $ErrorActionPreference = 'Stop'
184
184
  (New-Object System.Security.AccessControl.RawSecurityDescriptor("O:$env:LA_SID")).GetSddlForm('Owner')
185
- `;var TOKEN_FILE="token",TOKEN_BYTES=32,NONCE_BYTES=32,SOCKET_FILE="service.sock",base64url3=(bytes)=>Buffer.from(bytes).toString("base64url"),mintNonce=()=>base64url3(randomBytes4(NONCE_BYTES)),mintId=()=>base64url3(randomBytes4(16)),insecure=(detail)=>{throw new LocalApiError("insecure_state_dir",detail)},decoded=(value,bytes,what)=>{let out=Buffer.from(value,"base64url");if(out.length!==bytes||base64url3(out)!==value)throw new LocalApiError("protocol_violation",`${what} is not ${bytes} base64url bytes`);return out},UNIX_ENDPOINT="unix",tcpEndpoint=(port)=>`tcp:${port}`,proof=(token,label,nonce,endpoint)=>base64url3(createHmac3("sha256",token).update(label).update(decoded(nonce,NONCE_BYTES,"a nonce")).update(endpoint,"utf8").digest()),serverProof=(token,clientNonce,endpoint)=>proof(token,"server",clientNonce,endpoint),clientProof=(token,serverNonce,endpoint)=>proof(token,"client",serverNonce,endpoint),proofMatches=(expected,actual)=>{let a=Buffer.from(expected),b=Buffer.from(actual);return a.length===b.length&&timingSafeEqual2(a,b)},isMissing2=(error)=>typeof error==="object"&&error!==null&&("code"in error)&&(error.code==="ENOENT"||error.code==="ENOTDIR"),currentUid=()=>process.getuid?.()??insecure("this platform has no uid"),privateEntry=(path,kind,uid,checkMode=!0)=>{let stat;try{stat=lstatSync2(path)}catch(error){if(isMissing2(error))return insecure(`the ${kind} is missing`);throw error}if(!(kind==="dir"?stat.isDirectory():kind==="socket"?stat.isSocket():stat.isFile()))insecure(`the ${kind} is not a plain ${kind}`);if(stat.uid!==uid)insecure(`the ${kind} belongs to another user`);if(checkMode&&(stat.mode&63)!==0)insecure(`the ${kind} is open to group or others`)},checkPosixAccess=(stateDir)=>{let uid=currentUid();privateEntry(stateDir,"dir",uid),privateEntry(join7(stateDir,SOCKET_FILE),"socket",uid),privateEntry(join7(stateDir,TOKEN_FILE),"file",uid)};var readToken=(stateDir)=>{let value;try{value=readFileSync2(join7(stateDir,TOKEN_FILE),"utf8")}catch(error){if(isMissing2(error))return insecure("the token is missing");throw error}try{return decoded(value,TOKEN_BYTES,"the token")}catch(error){if(error instanceof LocalApiError)return insecure("the token is malformed");throw error}};import{createHash as createHash7}from"node:crypto";var SESSION_BLOB_MAX=16777216,SESSION_COMMAND_TEXT_MAX_CHARS=1e6,SESSION_COMMAND_TEXT_MAX_BYTES=3000000,SESSION_UI_REQUEST_ID_MAX_CHARS=256,SESSION_QUESTION_ANSWERS_MAX=64,SESSION_ANSWER_SELECTED_MAX=64,SESSION_DEVICE_MAX_CHARS=64,SESSION_PROJECT_MAX_CHARS=256,SESSION_ID_MAX_CHARS=128,SESSION_READ_TAIL_MAX=200,SESSION_SUMMARY_TITLE_MAX_CHARS=256,SESSION_SUMMARY_PROJECT_MAX_CHARS=128,SESSION_SUMMARY_PATH_MAX_CHARS=1024;class ProtoError extends Error{code;constructor(code,message){super(message);this.code=code}}var validateCommandText=(text)=>{if(typeof text!=="string"||!text.isWellFormed())throw new ProtoError("malformed","command text");if(text.length>1e6||new TextEncoder().encode(text).length>3000000)throw new ProtoError("payload_too_large","session command text over the limit");return text};var LOCAL_INLINE_MAX=524288,LOCAL_CHUNK_MAX=262144,LOCAL_JSON_EXPANSION_MAX=6,LOCAL_BLOB_MAX=LOCAL_JSON_EXPANSION_MAX*SESSION_BLOB_MAX,encoder=new TextEncoder,lineBytes=(value)=>encoder.encode(JSON.stringify(value)).length+1,sha256Hex=(data)=>createHash7("sha256").update(data).digest("hex"),chunkPayload=(data)=>{let chunks=[];for(let off=0;off<data.length;off+=LOCAL_CHUNK_MAX)chunks.push({off,b:Buffer.from(data.subarray(off,off+LOCAL_CHUNK_MAX)).toString("base64")});return chunks};import{posix,win32}from"node:path";var LOCAL_API_VERSION=1,STATUS_STATES=["not_configured","disabled","sign_in_required","plan_required","keychain_locked","connecting","activation_pending","connected","offline","authorization_stale","service_degraded","update_required","signed_out"],POLICY_STATES=["off","pending","active"],THIS_DEVICE_STATES=["unclassified","desktop_unregistered","indeterminate","desktop","cli_only","acked"];var CAPABILITIES=["sessions","devices","enforcement","upgrade"],REFUSED_REASONS=["version","data_home_required","malformed"],ROUND_STATES=["open","done"],ROUND_DEVICE_STATES=["answered","pending","undelivered","page_cap","cursor_echo","timed_out","skipped"],LISTING_SOURCES=["live","cache"],SESSION_ROW_STATES=["running","idle","ended"],FILTER_KEYS=["device","project","state"],BLOB_OF=["state","record","entry"],BLOB_ABORT_REASONS=["digest_mismatch","source_gone","too_large","detached"],UPLOAD_ABORT_REASONS=["message_too_long","parts_conflict","malformed","detached"],DETACH_REASONS=["authorization_expired","activation_pending","service_disabled","owner_transfer","peer_revoked","stream_key_pending","peer_detached","blob_failed"],ATTACH_PENDING_REASONS=["stream_key_pending"],COMMAND_ID_CHARS=22,COMMAND_OPS=["prompt","steer","abort","permission","question"],COMMAND_STATES=["queued","transport_confirmed","not confirmed","not delivered: never_sent","engine_dispatched","engine_applied","engine_refused","engine_stale","uncertain"],COMMAND_UNCERTAIN_REASONS=["request_gone","no_receipt","engine_restarted","recipient_revoked","transport_expired","unconfirmed"],COMMAND_REFUSAL_REASONS=["parts_conflict","peer_unauthorized","message_too_long","engine_capability_missing"],RETRYABLE_STATES=["not confirmed","not delivered: never_sent"],ERROR_CODES=["unauthenticated","client_proof_invalid","invalid_request","unknown_type","forbidden","owner_transfer","internal","signed_out","device_mismatch","device_changed","account_changed","device_key_invalid","service_disabled","sign_in_required","plan_required","activation_pending","authorization_stale","peer_not_found","peer_not_session_client","session_not_found","engine_too_old","not_attached","command_id_conflict","message_too_long","upload_incomplete"];var REQUEST_ID_MAX_CHARS=64,LOCAL_ID_MAX_CHARS=64,PATH_MAX_CHARS=4096,LABEL_MAX_CHARS=256,REASON_MAX_CHARS=1024,ENTRY_ID_MAX_BYTES=128,NONCE_CHARS=43;class InvalidMessage extends Error{detail;constructor(detail){super(detail);this.name="InvalidMessage",this.detail=detail}}var fail=(detail)=>{throw new InvalidMessage(detail)},assertNever=(value)=>{throw Error(`unexpected variant ${JSON.stringify(value)}`)},keysOf=(record)=>Object.keys(record).filter((key)=>Object.hasOwn(record,key)),isRecord6=(v)=>typeof v==="object"&&v!==null&&!Array.isArray(v),exactly=(v,required,optional=[],what="message")=>{if(!isRecord6(v))return fail(`${what} must be an object`);for(let name of required)if(!Object.hasOwn(v,name))fail(`${what} misses ${name}`);for(let key of Object.keys(v))if(!required.includes(key)&&!optional.includes(key))fail(`${what} has an unknown field`);return v},oneOf=(list,v,what)=>list.find((item)=>item===v)??fail(what),text3=(v,max,what,min=1)=>typeof v==="string"&&v.length>=min&&v.length<=max&&v.isWellFormed()?v:fail(what),bool=(v,what)=>typeof v==="boolean"?v:fail(what),uint=(v,min,max,what)=>typeof v==="number"&&Number.isSafeInteger(v)&&v>=min&&v<=max?v:fail(what),BASE64URL=/^[A-Za-z0-9_-]+$/,localId=(v,what)=>typeof v==="string"&&v.length>=1&&v.length<=LOCAL_ID_MAX_CHARS&&BASE64URL.test(v)?v:fail(what),commandId=(v)=>typeof v==="string"&&v.length===COMMAND_ID_CHARS&&BASE64URL.test(v)?v:fail("command_id"),nonce=(v,what)=>typeof v==="string"&&v.length===NONCE_CHARS&&BASE64URL.test(v)?v:fail(what),PRINTABLE=/^[\x21-\x7e]+$/,requestId=(v)=>typeof v==="string"&&v.length<=REQUEST_ID_MAX_CHARS&&PRINTABLE.test(v)?v:void 0,SEMVER=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,semver=(v,what)=>typeof v==="string"&&v.length<=64&&SEMVER.test(v)?v:fail(what),absolutePath=(v,what)=>typeof v==="string"&&v.length<=PATH_MAX_CHARS&&v.isWellFormed()&&!v.includes("\x00")&&(posix.isAbsolute(v)||win32.isAbsolute(v))?v:fail(what),entryId=(v,what)=>typeof v==="string"&&v.length>0&&v.isWellFormed()&&new TextEncoder().encode(v).length<=ENTRY_ID_MAX_BYTES?v:fail(what),nullable2=(v,check)=>v===null?null:check(v),SHA256_HEX=/^[0-9a-f]{64}$/,sha256Field=(v,what)=>typeof v==="string"&&SHA256_HEX.test(v)?v:fail(what),base64Bytes=(v,max,what)=>{if(typeof v!=="string"||v.length===0||v.length>4*Math.ceil(max/3))return fail(what);let bytes=Buffer.from(v,"base64");return bytes.length<=max&&bytes.toString("base64")===v?new Uint8Array(bytes):fail(what)},UNSAFE_KEYS=["__proto__","constructor","prototype"],safeKey=(key,what)=>UNSAFE_KEYS.includes(key)?fail(what):key,jsonValue=(v,what)=>{if(v===null||typeof v==="boolean"||typeof v==="string")return v;if(typeof v==="number")return Number.isFinite(v)?v:fail(what);if(Array.isArray(v))return v.map((item)=>jsonValue(item,what));if(isRecord6(v))return jsonObject(v,what);return fail(what)},jsonObject=(v,what)=>{if(!isRecord6(v))return fail(what);let out={};for(let[key,item]of Object.entries(v))out[key]=jsonValue(item,what);return out};var MESSAGE_LIMIT_CHARS=SESSION_COMMAND_TEXT_MAX_CHARS,LOCAL_UPLOAD_PARTS_MAX=Math.ceil(SESSION_COMMAND_TEXT_MAX_BYTES/LOCAL_CHUNK_MAX),checkCommandText=(value)=>{try{return validateCommandText(value),"ok"}catch(error){if(error instanceof ProtoError)return error.code==="payload_too_large"?"message_too_long":"malformed";throw error}},uploadParts=(value)=>{let chunks=chunkPayload(new TextEncoder().encode(value));return chunks.map(({b},index)=>({index,count:chunks.length,b}))};class LocalBlobAssembler{#open;#parts=[];#received=0;inFlight(){return this.#open!==void 0}accept(event){switch(event.kind){case"session.blob_open":if(this.#open!==void 0)return protocolViolation("one blob in flight per attach");if(event.bytes>LOCAL_BLOB_MAX)return protocolViolation("blob over LOCAL_BLOB_MAX");this.#open=event;return;case"session.blob_chunk":{let open=this.#current(event.id),data=Buffer.from(event.b,"base64"),end=this.#received+data.length;if(event.off!==this.#received||end>open.bytes)return protocolViolation("blob chunk out of order");if(data.length!==LOCAL_CHUNK_MAX&&end!==open.bytes)return protocolViolation("short blob chunk");this.#parts.push(new Uint8Array(data)),this.#received=end;return}case"session.blob_done":{let open=this.#current(event.id);if(this.#received!==open.bytes)return protocolViolation("blob done before its last chunk");let data=new Uint8Array(open.bytes),at=0;for(let part of this.#parts)data.set(part,at),at+=part.length;return this.#reset(),sha256Hex(data)===open.sha256?{kind:"blob",open,data}:protocolViolation("blob digest mismatch")}case"session.blob_abort":{if(event.reason==="too_large")return{kind:"too_large",query_id:event.query_id,entry_id:event.entry_id};let open=this.#current(event.id);return this.#reset(),{kind:"aborted",open,reason:event.reason}}default:return assertNever(event)}}#current(id){let open=this.#open;return open!==void 0&&open.id===id?open:protocolViolation("blob not open")}#reset(){this.#open=void 0,this.#parts=[],this.#received=0}}class ListingTracker{#watches=new Map;watch(query_id,settle,onRevision){this.#watches.set(query_id,{...settle,onRevision,open:void 0,last:void 0})}failAll(error){for(let watch of this.#watches.values())watch.reject(error);this.#watches.clear()}accept(event){let watch=this.#watches.get(event.query_id);if(watch===void 0)return;switch(event.kind){case"sessions.round":{if(event.state==="open")return;if(watch.open!==void 0)return protocolViolation("a round ended during an open revision");this.#watches.delete(event.query_id);let last=watch.last;return watch.resolve({query_id:event.query_id,revision:last?.revision??0,rows:last?.rows??[],incomplete:last?.incomplete??[],devices:event.devices})}case"sessions.listing_begin":if(watch.open!==void 0||event.revision<=(watch.last?.revision??0))return protocolViolation("a revision out of order");watch.open={revision:event.revision,rows:[]};return;case"sessions.listing_rows":if(watch.open?.revision!==event.revision)return protocolViolation("rows outside their revision");for(let row of event.rows)watch.open.rows.push(row);return;case"sessions.listing_end":{if(watch.open?.revision!==event.revision)return protocolViolation("listing_end outside its revision");let revision={query_id:event.query_id,revision:event.revision,rows:watch.open.rows,incomplete:event.incomplete};watch.open=void 0,watch.last=revision,watch.onRevision?.(revision);return}default:return assertNever(event)}}}var CODE=/^[a-z_]{1,64}$/,ATTACH_ID_MAX=4294967295,MILLIS_MAX=Number.MAX_SAFE_INTEGER,deviceId=(v,what="device")=>text3(v,SESSION_DEVICE_MAX_CHARS,what),sessionId=(v)=>text3(v,SESSION_ID_MAX_CHARS,"session_id"),attachId=(v)=>uint(v,1,ATTACH_ID_MAX,"attach_id"),millis=(v,what)=>uint(v,0,MILLIS_MAX,what),deviceRef=(v,what="device")=>{let m=exactly(v,["id","name"],[],what);return{id:deviceId(m.id,`${what}.id`),name:text3(m.name,LABEL_MAX_CHARS,`${what}.name`)}},policyOf=(v)=>{let m=exactly(v,["state","generation","this_device","homes_pending","unacked"],[],"policy"),unacked=m.unacked;if(!Array.isArray(unacked))return fail("policy.unacked");return{state:oneOf(POLICY_STATES,m.state,"policy.state"),generation:millis(m.generation,"policy.generation"),this_device:oneOf(THIS_DEVICE_STATES,m.this_device,"policy.this_device"),homes_pending:millis(m.homes_pending,"policy.homes_pending"),unacked:unacked.map((u)=>{let entry=exactly(u,["device","label"],[],"policy.unacked");return{device:deviceId(entry.device),label:text3(entry.label,LABEL_MAX_CHARS,"label",0)}})}},statusOf=(v)=>{let m=exactly(v,["state","since_ms","device","origin_configured","enabled"],["detail","policy"],"status"),{detail,policy}=m;return{state:oneOf(STATUS_STATES,m.state,"status.state"),since_ms:millis(m.since_ms,"status.since_ms"),...detail===void 0?{}:{detail:detailOf(detail)},device:nullable2(m.device,(d)=>deviceRef(d,"status.device")),origin_configured:bool(m.origin_configured,"status.origin_configured"),enabled:bool(m.enabled,"status.enabled"),...policy===void 0?{}:{policy:policyOf(policy)}}},detailOf=(v)=>{let m=exactly(v,["code","action"],[],"status.detail"),code=m.code;return{code:typeof code==="string"&&CODE.test(code)?code:fail("status.detail.code"),action:nullable2(m.action,(a)=>text3(a,LABEL_MAX_CHARS,"status.detail.action"))}},deviceRowOf=(v)=>{let m=exactly(v,["device","label","kind","platform","last_seen_ms","online"],[],"device row");return{device:deviceId(m.device),label:text3(m.label,LABEL_MAX_CHARS,"label",0),kind:text3(m.kind,64,"kind",0),platform:text3(m.platform,64,"platform",0),last_seen_ms:nullable2(m.last_seen_ms,(t)=>millis(t,"last_seen_ms")),online:bool(m.online,"online")}},ROW_FIELDS=["device","session_id","title","project","path","state","updated_ms","source","as_of"],listingRowOf=(v)=>{let m=exactly(v,ROW_FIELDS,[],"listing row");return{device:deviceId(m.device),session_id:sessionId(m.session_id),title:text3(m.title,SESSION_SUMMARY_TITLE_MAX_CHARS,"title",0),project:text3(m.project,SESSION_SUMMARY_PROJECT_MAX_CHARS,"project"),path:text3(m.path,SESSION_SUMMARY_PATH_MAX_CHARS,"path"),state:oneOf(SESSION_ROW_STATES,m.state,"row state"),updated_ms:millis(m.updated_ms,"updated_ms"),source:oneOf(LISTING_SOURCES,m.source,"row source"),as_of:millis(m.as_of,"as_of")}},BODY_FIELDS=["attach_id","cursor","state","entries","history_truncated","oldest_entry_id"],snapshotBodyOf=(m)=>{let cursor=exactly(m.cursor,["marker_id","last_entry_id"],[],"cursor"),entries=m.entries;if(!Array.isArray(entries))return fail("entries");return{attach_id:attachId(m.attach_id),cursor:{marker_id:entryId(cursor.marker_id,"cursor.marker_id"),last_entry_id:nullable2(cursor.last_entry_id,(e)=>entryId(e,"cursor.last_entry_id"))},state:jsonObject(m.state,"state"),entries:entries.map((e)=>jsonValue(e,"entries")),history_truncated:bool(m.history_truncated,"history_truncated"),oldest_entry_id:nullable2(m.oldest_entry_id,(e)=>entryId(e,"oldest_entry_id"))}},snapshotBlobOf=(v)=>snapshotBodyOf(exactly(v,BODY_FIELDS,[],"snapshot")),SNAPSHOT_FIELDS=BODY_FIELDS,readEntryOf=(v)=>{let m=exactly(v,["kind","entry_id"],["entry","bytes","sha256"],"read entry"),entry_id=entryId(m.entry_id,"entry_id");if(m.kind==="entry")return exactly(m,["kind","entry_id","entry"],[],"read entry"),{kind:"entry",entry_id,entry:jsonValue(m.entry,"entry")};if(m.kind!=="entry_ref")return fail("read entry kind");return exactly(m,["kind","entry_id","bytes","sha256"],[],"read entry"),{kind:"entry_ref",entry_id,bytes:uint(m.bytes,1,MILLIS_MAX,"bytes"),sha256:sha256Field(m.sha256,"sha256")}},errorBodyOf=(v)=>{let m=exactly(v,["code","reason","action"],["limit_chars"],"error"),code=oneOf(ERROR_CODES,m.code,"error.code"),limit=m.limit_chars;if(code==="message_too_long"!==(limit!==void 0))return fail("error.limit_chars");return{code,reason:text3(m.reason,REASON_MAX_CHARS,"error.reason",0),action:nullable2(m.action,(a)=>text3(a,LABEL_MAX_CHARS,"error.action")),...limit===void 0?{}:{limit_chars:uint(limit,1,MILLIS_MAX,"error.limit_chars")}}};var eventFields=(v,names,optional=[])=>exactly(v,["type","kind",...names],optional,"event"),attachOf=(m)=>localId(m.attach,"attach"),queryOf=(m)=>localId(m.query_id,"query_id"),blobIdOf=(m)=>localId(m.id,"blob id"),targetOf=(m)=>{let of=oneOf(BLOB_OF,m.of,"blob of");switch(of){case"state":{let p=exactly(m.position,["attach_id"],[],"position");return{of,position:{attach_id:attachId(p.attach_id)}}}case"record":{let p=exactly(m.position,["attach_id","seq"],[],"position"),seq=uint(p.seq,1,Number.MAX_SAFE_INTEGER,"seq");return{of,position:{attach_id:attachId(p.attach_id),seq}}}case"entry":{let p=exactly(m.position,["query_id","entry_id"],[],"position");return{of,position:{query_id:queryOf(p),entry_id:entryId(p.entry_id,"position.entry_id")}}}}},STREAM_EVENT_VALIDATORS={"session.snapshot":(v)=>{let m=eventFields(v,["attach",...SNAPSHOT_FIELDS]);return{type:"event",kind:"session.snapshot",attach:attachOf(m),...snapshotBodyOf(m)}},"session.snapshot_loading":(v)=>{let m=eventFields(v,["attach","blob"]);return{type:"event",kind:"session.snapshot_loading",attach:attachOf(m),blob:localId(m.blob,"blob")}},"session.records":(v)=>{let m=eventFields(v,["attach","attach_id","records"]),records=m.records;if(!Array.isArray(records)||records.length===0)return fail("records");let attach_id=attachId(m.attach_id);return{type:"event",kind:"session.records",attach:attachOf(m),attach_id,records:records.map((r)=>jsonObject(r,"record"))}},"session.blob_open":(v)=>{let m=eventFields(v,["attach","id","of","bytes","sha256","position"]);return{type:"event",kind:"session.blob_open",attach:attachOf(m),id:blobIdOf(m),bytes:uint(m.bytes,1,LOCAL_BLOB_MAX,"blob bytes"),sha256:sha256Field(m.sha256,"blob sha256"),...targetOf(m)}},"session.blob_chunk":(v)=>{let m=eventFields(v,["attach","id","off","b"]);base64Bytes(m.b,LOCAL_CHUNK_MAX,"blob chunk");let b=typeof m.b==="string"?m.b:fail("blob chunk"),off=uint(m.off,0,LOCAL_BLOB_MAX,"blob off");return{type:"event",kind:"session.blob_chunk",attach:attachOf(m),id:blobIdOf(m),off,b}},"session.blob_done":(v)=>{let m=eventFields(v,["attach","id"]);return{type:"event",kind:"session.blob_done",attach:attachOf(m),id:blobIdOf(m)}},"session.blob_abort":(v)=>{let head=eventFields(v,["attach","id","reason"],["query_id","entry_id"]),reason=oneOf(BLOB_ABORT_REASONS,head.reason,"blob abort reason"),base={type:"event",kind:"session.blob_abort",attach:attachOf(head),id:blobIdOf(head)};if(reason!=="too_large")return eventFields(v,["attach","id","reason"]),{...base,reason};let m=eventFields(v,["attach","id","reason","query_id","entry_id"]);return{...base,reason,query_id:queryOf(m),entry_id:entryId(m.entry_id,"entry_id")}},"session.attach_pending":(v)=>{let m=eventFields(v,["attach","reason"]),reason=oneOf(ATTACH_PENDING_REASONS,m.reason,"pending reason");return{type:"event",kind:"session.attach_pending",attach:attachOf(m),reason}},"session.detached":(v)=>{let m=eventFields(v,["attach","reason"]),reason=oneOf(DETACH_REASONS,m.reason,"detach reason");return{type:"event",kind:"session.detached",attach:attachOf(m),reason}}};var revisionOf=(m)=>uint(m.revision,1,Number.MAX_SAFE_INTEGER,"revision"),devicesOf=(v)=>{if(!isRecord6(v))return fail("round devices");let out={};for(let[device,state]of Object.entries(v))out[safeKey(deviceId(device),"round device")]=oneOf(ROUND_DEVICE_STATES,state,"round device state");return out},commandStateOf=(v)=>{let m=eventFields(v,["command_id","state","retryable"],["reason","receipt"]),state=oneOf(COMMAND_STATES,m.state,"command state");if(bool(m.retryable,"retryable")!==RETRYABLE_STATES.includes(state))return fail("retryable");let head={type:"event",kind:"session.command_state",command_id:commandId(m.command_id),...m.receipt===void 0?{}:{receipt:jsonObject(m.receipt,"receipt")}},reason=m.reason;switch(state){case"engine_refused":return{...head,state,reason:oneOf(COMMAND_REFUSAL_REASONS,reason,"refusal reason"),retryable:!1};case"uncertain":return{...head,state,reason:oneOf(COMMAND_UNCERTAIN_REASONS,reason,"uncertain reason"),retryable:!1};case"not confirmed":case"not delivered: never_sent":return reason===void 0?{...head,state,retryable:!0}:fail("reason");case"queued":case"transport_confirmed":case"engine_dispatched":case"engine_applied":case"engine_stale":return reason===void 0?{...head,state,retryable:!1}:fail("reason")}},VALIDATORS={...STREAM_EVENT_VALIDATORS,"status.changed":(v)=>({type:"event",kind:"status.changed",status:statusOf(eventFields(v,["status"]).status)}),"sessions.round":(v)=>{let m=eventFields(v,["query_id","state","devices"]),state=oneOf(ROUND_STATES,m.state,"round state");return{type:"event",kind:"sessions.round",query_id:queryOf(m),state,devices:devicesOf(m.devices)}},"sessions.listing_begin":(v)=>{let m=eventFields(v,["query_id","revision"]);return{type:"event",kind:"sessions.listing_begin",query_id:queryOf(m),revision:revisionOf(m)}},"sessions.listing_rows":(v)=>{let m=eventFields(v,["query_id","revision","rows"]),rows=m.rows;if(!Array.isArray(rows)||rows.length===0)return fail("rows");return{type:"event",kind:"sessions.listing_rows",query_id:queryOf(m),revision:revisionOf(m),rows:rows.map(listingRowOf)}},"sessions.listing_end":(v)=>{let m=eventFields(v,["query_id","revision","incomplete"]),incomplete=m.incomplete;if(!Array.isArray(incomplete))return fail("incomplete");let devices=incomplete.map((d)=>deviceId(d));return{type:"event",kind:"sessions.listing_end",query_id:queryOf(m),revision:revisionOf(m),incomplete:devices}},"session.command_state":commandStateOf,"session.read_result":(v)=>{let m=eventFields(v,["attach","query_id","entries","next_before"]),entries=m.entries;if(!Array.isArray(entries)||entries.length>SESSION_READ_TAIL_MAX)return fail("entries");let rows=entries.map(readEntryOf);if(new Set(rows.map((r)=>r.entry_id)).size!==rows.length)return fail("duplicate entry_id");let next_before=nullable2(m.next_before,(e)=>entryId(e,"next_before"));return{type:"event",kind:"session.read_result",attach:attachOf(m),query_id:queryOf(m),entries:rows,next_before}},"session.upload_abort":(v)=>{let m=eventFields(v,["upload_id","reason"]),reason=oneOf(UPLOAD_ABORT_REASONS,m.reason,"upload abort reason");return{type:"event",kind:"session.upload_abort",upload_id:localId(m.upload_id,"upload_id"),reason}}},EVENT_KINDS=keysOf(VALIDATORS),validateEventFields=(v)=>{if(v.type!=="event")return fail("an event has type event");return VALIDATORS[oneOf(EVENT_KINDS,v.kind,"event kind")](v)};var requestFields=(v,names,optional=[])=>exactly(v,["id","type",...names],optional,"request"),commandText=(v,what)=>typeof v==="string"&&v.isWellFormed()?v:fail(what),answersOf=(v)=>{if(!isRecord6(v)||Object.keys(v).length>SESSION_QUESTION_ANSWERS_MAX)return fail("answers");let out={};for(let[key,answer]of Object.entries(v)){let id=safeKey(text3(key,SESSION_UI_REQUEST_ID_MAX_CHARS,"answer key"),"answer key"),m=exactly(answer,["selected"],["text"],"answer"),selected=m.selected;if(!Array.isArray(selected)||selected.length>SESSION_ANSWER_SELECTED_MAX)return fail("answer selected");let extra=m.text===void 0?{}:{text:commandText(m.text,"answer text")};out[id]={selected:selected.map((s)=>commandText(s,"answer selected")),...extra}}return out},commandOf=(v)=>{let m=exactly(v,["op"],["text","ui_request_id","confirmed","answers","comment"],"command"),op=COMMAND_OPS.find((o)=>o===m.op)??fail("command op"),uiRequest=()=>text3(m.ui_request_id,SESSION_UI_REQUEST_ID_MAX_CHARS,"ui_request_id");switch(op){case"prompt":case"steer":return exactly(m,["op","text"],[],"command"),{op,text:commandText(m.text,"command text")};case"abort":return exactly(m,["op"],[],"command"),{op};case"permission":return exactly(m,["op","ui_request_id","confirmed"],[],"command"),{op,ui_request_id:uiRequest(),confirmed:bool(m.confirmed,"confirmed")};case"question":{exactly(m,["op","ui_request_id","answers"],["comment"],"command");let comment=m.comment===void 0?{}:{comment:commandText(m.comment,"comment")};return{op,ui_request_id:uiRequest(),answers:answersOf(m.answers),...comment}}}},commandIdField=(v)=>v===void 0?{}:{command_id:commandId(v)},COMMAND_REQUEST_VALIDATORS={"session.command":(v,id)=>{if(Object.hasOwn(v,"upload_id")){let m=requestFields(v,["attach","upload_id","op"],["command_id"]),op=m.op==="prompt"||m.op==="steer"?m.op:fail("upload op"),upload_id=localId(m.upload_id,"upload_id");return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),upload_id,op}}let m=requestFields(v,["attach","command"],["command_id"]),command=commandOf(m.command);return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),command}},"session.command_part":(v,id)=>{let m=requestFields(v,["attach","upload_id","index","count","b"]),count=uint(m.count,1,LOCAL_UPLOAD_PARTS_MAX,"count");return base64Bytes(m.b,LOCAL_CHUNK_MAX,"b"),{id,type:"session.command_part",attach:localId(m.attach,"attach"),upload_id:localId(m.upload_id,"upload_id"),index:uint(m.index,0,count-1,"index"),count,b:typeof m.b==="string"?m.b:fail("b")}}};var ENVIRONMENTS_MAX=1024,PKCS8_KEY_BYTES=48,PKCS8_PREFIX={ed25519:"302e020100300506032b657004220420",x25519:"302e020100300506032b656e04220420"},pkcs8=(v,algorithm,what)=>{let bytes=base64Bytes(v,PKCS8_KEY_BYTES,what),prefix=Buffer.from(bytes.subarray(0,16)).toString("hex");return bytes.length===PKCS8_KEY_BYTES&&prefix===PKCS8_PREFIX[algorithm]&&typeof v==="string"?v:fail(what)},filterOf=(v)=>{let{device,project,state}=exactly(v,[],FILTER_KEYS,"filter");return{...device===void 0?{}:{device:deviceId(device,"filter.device")},...project===void 0?{}:{project:text3(project,SESSION_PROJECT_MAX_CHARS,"filter.project")},...state===void 0?{}:{state:SESSION_ROW_STATES.find((s)=>s===state)??fail("filter.state")}}},environmentsOf=(v)=>{if(!Array.isArray(v)||v.length>ENVIRONMENTS_MAX)return fail("environments");let rows=v.map((e)=>{let m=exactly(e,["environment_id","revoked","closed"],[],"environment");return{environment_id:text3(m.environment_id,128,"environment_id"),revoked:uint(m.revoked,0,Number.MAX_SAFE_INTEGER,"revoked"),closed:uint(m.closed,0,Number.MAX_SAFE_INTEGER,"closed")}});return new Set(rows.map((r)=>r.environment_id)).size===rows.length?rows:fail("duplicate environment_id")},bare=(v)=>{requestFields(v,[])},agentDir=(v)=>absolutePath(requestFields(v,["agent_dir"]).agent_dir,"agent_dir"),VALIDATORS2={...COMMAND_REQUEST_VALIDATORS,authenticate:(v,id)=>{let m=requestFields(v,["client_proof"]);return{id,type:"authenticate",client_proof:text3(m.client_proof,64,"client_proof")}},"status.get":(v,id)=>(bare(v),{id,type:"status.get"}),"status.subscribe":(v,id)=>(bare(v),{id,type:"status.subscribe"}),"service.set_enabled":(v,id)=>{let enabled=bool(requestFields(v,["enabled"]).enabled,"enabled");return{id,type:"service.set_enabled",enabled}},"refresher.register":(v,id)=>{let m=requestFields(v,["binary_path","version"]),binary_path=absolutePath(m.binary_path,"binary_path");return{id,type:"refresher.register",binary_path,version:semver(m.version,"version")}},"device.adopt":(v,id)=>{let m=requestFields(v,["device","signing_private_key","sealing_private_key"]);return{id,type:"device.adopt",device:deviceRef(m.device),signing_private_key:pkcs8(m.signing_private_key,"ed25519","signing_private_key"),sealing_private_key:pkcs8(m.sealing_private_key,"x25519","sealing_private_key")}},"device.forget":(v,id)=>(bare(v),{id,type:"device.forget"}),"device.info":(v,id)=>(bare(v),{id,type:"device.info"}),"endpoints.register":(v,id)=>({id,type:"endpoints.register",agent_dir:agentDir(v)}),"endpoints.unregister":(v,id)=>({id,type:"endpoints.unregister",agent_dir:agentDir(v)}),"devices.list":(v,id)=>(bare(v),{id,type:"devices.list"}),"sessions.list":(v,id)=>{let filter=requestFields(v,[],["filter"]).filter;return filter===void 0?{id,type:"sessions.list"}:{id,type:"sessions.list",filter:filterOf(filter)}},"session.attach":(v,id)=>{let m=requestFields(v,["device","session_id"]);return{id,type:"session.attach",device:deviceId(m.device),session_id:sessionId(m.session_id)}},"session.detach":(v,id)=>({id,type:"session.detach",attach:localId(requestFields(v,["attach"]).attach,"attach")}),"session.read":(v,id)=>{let m=requestFields(v,["attach"],["before_entry_id","tail"]),{before_entry_id:before,tail}=m;return{id,type:"session.read",attach:localId(m.attach,"attach"),...before===void 0?{}:{before_entry_id:entryId(before,"before_entry_id")},...tail===void 0?{}:{tail:uint(tail,1,SESSION_READ_TAIL_MAX,"tail")}}},"enforcement.report":(v,id)=>{let m=requestFields(v,["generation","data_home","environments","complete"]);return{id,type:"enforcement.report",generation:uint(m.generation,0,Number.MAX_SAFE_INTEGER,"generation"),data_home:absolutePath(m.data_home,"data_home"),environments:environmentsOf(m.environments),complete:bool(m.complete,"complete")}},"owner.shutdown_for_upgrade":(v,id)=>{let target_version=semver(requestFields(v,["target_version"]).target_version,"target_version");return{id,type:"owner.shutdown_for_upgrade",target_version}}},REQUEST_TYPES=keysOf(VALIDATORS2);var asViolation=(check)=>{try{return check()}catch(error){if(error instanceof InvalidMessage)throw new LocalApiError("protocol_violation",error.detail);throw error}};var validateWelcome=(v)=>asViolation(()=>{if(isRecord6(v)&&v.type==="refused"){let m=exactly(v,["type","reason"],[],"refused");return{type:"refused",reason:oneOf(REFUSED_REASONS,m.reason,"refused reason")}}if(isRecord6(v)&&v.type==="welcome"&&v.v!==LOCAL_API_VERSION)return{type:"refused",reason:"version"};let m=exactly(v,["type","v","service_version","owner","server_proof","server_nonce","capabilities","state"],[],"welcome"),capabilities=m.capabilities;if(m.type!=="welcome"||m.owner!=="service")return fail("welcome");if(!Array.isArray(capabilities)||new Set(capabilities).size!==capabilities.length)return fail("capabilities");return{type:"welcome",v:LOCAL_API_VERSION,service_version:semver(m.service_version,"service_version"),owner:"service",server_proof:nonce(m.server_proof,"server_proof"),server_nonce:nonce(m.server_nonce,"server_nonce"),capabilities:capabilities.map((c)=>oneOf(CAPABILITIES,c,"capability")),state:statusOf(m.state)}});var empty=(v)=>(exactly(v,[],[],"data"),{}),one=(v,name)=>exactly(v,[name],[],"data")[name],DATA={authenticate:empty,"status.get":statusOf,"status.subscribe":empty,"service.set_enabled":(v)=>({enabled:bool(one(v,"enabled"),"enabled")}),"refresher.register":empty,"device.adopt":(v)=>({device:deviceRef(one(v,"device"))}),"device.forget":empty,"device.info":(v)=>({device:nullable2(one(v,"device"),(d)=>deviceRef(d))}),"endpoints.register":empty,"endpoints.unregister":empty,"devices.list":(v)=>{let devices=one(v,"devices");return Array.isArray(devices)?{devices:devices.map(deviceRowOf)}:fail("devices")},"sessions.list":(v)=>({query_id:localId(one(v,"query_id"),"query_id")}),"session.attach":(v)=>({attach:localId(one(v,"attach"),"attach")}),"session.detach":empty,"session.command":(v)=>({command_id:commandId(one(v,"command_id"))}),"session.command_part":(v)=>({received:uint(one(v,"received"),0,LOCAL_UPLOAD_PARTS_MAX-1,"received")}),"session.read":(v)=>({query_id:localId(one(v,"query_id"),"query_id")}),"enforcement.report":empty,"owner.shutdown_for_upgrade":empty},validateResponse=(v,type)=>asViolation(()=>{let m=exactly(v,["id","type","ok"],["data","error"],"response"),id=requestId(m.id)??fail("response id");if(m.type!=="response")return fail("response type");if(m.ok===!0)return exactly(m,["id","type","ok","data"],[],"response"),{id,ok:!0,data:DATA[type](m.data)};if(m.ok!==!1)return fail("response ok");return exactly(m,["id","type","ok","error"],[],"response"),{id,ok:!1,error:errorBodyOf(m.error)}}),validateEvent=(v)=>asViolation(()=>isRecord6(v)?validateEventFields(v):fail("an event is an object")),validateSnapshotBlob=(v)=>asViolation(()=>snapshotBlobOf(v));var parsed=(data)=>{try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(data))}catch(error){if(error instanceof SyntaxError||error instanceof TypeError)return protocolViolation("a blob is not UTF-8 JSON");throw error}},checked=(check)=>{try{return check()}catch(error){if(error instanceof InvalidMessage)return protocolViolation(error.detail);throw error}};class EventAssembler{#emit;#blobs=new Map;#listings=new ListingTracker;#reads=new Map;constructor(emit){this.#emit=emit}watchListing(query_id,settle,onRevision){this.#listings.watch(query_id,settle,onRevision)}watchRead(query_id,attach,settle){this.#reads.set(query_id,{...settle,attach,result:void 0,filled:new Map})}failAll(error){this.#listings.failAll(error);for(let watch of this.#reads.values())watch.reject(error);this.#reads.clear()}accept(event){switch(this.#emit(event),event.kind){case"session.blob_open":case"session.blob_chunk":case"session.blob_done":case"session.blob_abort":return this.#blob(event.attach,event);case"sessions.listing_begin":case"sessions.listing_rows":case"sessions.listing_end":case"sessions.round":return this.#listings.accept(event);case"session.read_result":return this.#readResult(event);case"session.detached":return this.#detached(event.attach);case"status.changed":case"session.snapshot":case"session.snapshot_loading":case"session.records":case"session.attach_pending":case"session.command_state":case"session.upload_abort":return;default:return assertNever(event)}}#blob(attach,event){let assembler=this.#blobs.get(attach)??new LocalBlobAssembler;this.#blobs.set(attach,assembler);let outcome=assembler.accept(event);if(outcome===void 0)return;switch(outcome.kind){case"blob":return this.#apply(attach,outcome.open,outcome.data);case"aborted":if(outcome.open.of==="entry")this.#failRead(outcome.open.position.query_id,"an entry blob was aborted");return;case"too_large":return this.#fill(outcome.query_id,outcome.entry_id,(ref)=>({entry_id:ref.entry_id,too_large:!0,bytes:ref.bytes}));default:return assertNever(outcome)}}#apply(attach,open,data){let value=parsed(data);switch(open.of){case"state":{let body=validateSnapshotBlob(value);if(body.attach_id!==open.position.attach_id)protocolViolation("a snapshot blob of another attach generation");return this.#emit({type:"event",kind:"session.snapshot",attach,...body})}case"record":{let records=[checked(()=>jsonObject(value,"record"))];return this.#emit({type:"event",kind:"session.records",attach,attach_id:open.position.attach_id,records})}case"entry":{let entry=checked(()=>jsonValue(value,"entry"));return this.#fill(open.position.query_id,open.position.entry_id,(ref)=>ref.bytes===open.bytes&&ref.sha256===open.sha256?{entry_id:ref.entry_id,entry}:protocolViolation("an entry blob unlike its entry_ref"))}default:return assertNever(open)}}#fill(query_id,entry_id,make){let watch=this.#reads.get(query_id);if(watch===void 0)return;if(watch.result===void 0)return protocolViolation("an entry blob before its read_result");let ref=watch.result.entries.find((e)=>e.kind==="entry_ref"&&e.entry_id===entry_id);if(ref===void 0||ref.kind!=="entry_ref")return protocolViolation("a blob for an entry the page did not reference");watch.filled.set(entry_id,make(ref)),this.#finishRead(query_id,watch)}#readResult(event){let watch=this.#reads.get(event.query_id);if(watch===void 0)return;watch.result=event,this.#finishRead(event.query_id,watch)}#finishRead(query_id,watch){let result=watch.result;if(result===void 0)return;let entries=[];for(let entry of result.entries){let filled=entry.kind==="entry"?{entry_id:entry.entry_id,entry:entry.entry}:watch.filled.get(entry.entry_id);if(filled===void 0)return;entries.push(filled)}this.#reads.delete(query_id),watch.resolve({entries,next_before:result.next_before})}#failRead(query_id,reason){let watch=this.#reads.get(query_id);if(watch===void 0)return;this.#reads.delete(query_id),watch.reject(new LocalApiError("read_failed",reason))}#detached(attach){this.#blobs.delete(attach);for(let[query_id,watch]of this.#reads)if(watch.attach===attach)this.#failRead(query_id,"the attach was detached")}}var LOCAL_LINE_MAX=1048576,LF=10,encoder2=new TextEncoder,utf8=new TextDecoder("utf-8",{fatal:!0}),encodeLine=(value)=>{let body=encoder2.encode(JSON.stringify(value));if(body.length>LOCAL_LINE_MAX)throw new LocalApiError("protocol_violation",`a ${body.length}-byte line exceeds LOCAL_LINE_MAX`);let line=new Uint8Array(body.length+1);return line.set(body),line[body.length]=LF,line},parseLine=(line)=>{let decoded;try{decoded=utf8.decode(line)}catch(error){if(error instanceof TypeError)throw new LocalApiError("protocol_violation","a line is not UTF-8");throw error}try{return JSON.parse(decoded)}catch(error){if(error instanceof SyntaxError)throw new LocalApiError("protocol_violation","a line is not JSON");throw error}};class LineDecoder{#onLine;#onOversized;#parts=[];#length=0;#discarding=!1;constructor(onLine,onOversized){this.#onLine=onLine,this.#onOversized=onOversized}push(chunk){let start=0;while(start<chunk.length){let lf=chunk.indexOf(LF,start);if(this.#take(chunk.subarray(start,lf===-1?chunk.length:lf)),lf===-1)return;this.#finish(),start=lf+1}}#take(piece){if(this.#discarding||piece.length===0)return;if(this.#length+piece.length>LOCAL_LINE_MAX){this.#discarding=!0,this.#onOversized(this.#length+piece.length),this.#parts=[],this.#length=0;return}this.#parts.push(piece.slice()),this.#length+=piece.length}#finish(){if(this.#discarding){this.#discarding=!1;return}let line=new Uint8Array(this.#length),at=0;for(let part of this.#parts)line.set(part,at),at+=part.length;this.#parts=[],this.#length=0,this.#onLine(line)}}var EXPIRED={settle:()=>{},fail:()=>{}},typeOf=(message)=>typeof message==="object"&&message!==null?Reflect.get(message,"type"):void 0;class ClientConnection{#transport;#onEvent;#pending=new Map;closed;#first;#resolveFirst;#rejectFirst;#nextId=1;#ended=!1;#oversized=0;#deadline;constructor(transport,onEvent,deadline){this.#transport=transport,this.#onEvent=onEvent,this.#deadline=deadline,this.#first=new Promise((resolve,reject)=>{this.#resolveFirst=resolve,this.#rejectFirst=reject});let decoder=new LineDecoder((line)=>this.#onLine(line),()=>{this.#oversized+=1});transport.onData((bytes)=>decoder.push(bytes)),this.closed=new Promise((resolve)=>{transport.onClose(()=>{this.#ended=!0,this.#failAll(new LocalApiError("closed","the connection closed")),resolve()})})}send(message){this.#transport.write(encodeLine(message))}firstMessage(){return this.#first}oversizedLines(){return this.#oversized}get endpoint(){return this.#transport.endpoint}close(){this.#transport.close()}destroy(){this.#transport.destroy()}request(type,params,onAnswer){if(this.#ended)return Promise.reject(new LocalApiError("closed","the connection is closed"));let id=String(this.#nextId);this.#nextId+=1;let message={id,type,...params};if(lineBytes(message)>LOCAL_INLINE_MAX)return Promise.reject(new LocalApiError("protocol_violation","a request line over LOCAL_INLINE_MAX"));return new Promise((resolve,reject)=>{let cancel=this.#deadline.timer(()=>{if(this.#pending.get(id)===void 0)return;this.#pending.set(id,EXPIRED),reject(new LocalApiError("request_timeout",`the owner did not answer ${type} in time`))},this.#deadline.ms);this.#pending.set(id,{settle:(raw)=>{cancel();let response;try{response=validateResponse(raw,type)}catch(error){if(error instanceof LocalApiError)reject(error);throw error}if(!response.ok){let{code,reason,action,limit_chars}=response.error;reject(new LocalApiError(code,reason,limit_chars===void 0?{action}:{action,limit_chars}));return}onAnswer?.(response.data),resolve(response.data)},fail:(error)=>{cancel(),reject(error)}}),this.send(message)})}#onLine(line){try{let message=parseLine(line);if(this.#resolveFirst!==void 0){let resolve=this.#resolveFirst;this.#resolveFirst=void 0,this.#rejectFirst=void 0,resolve(message);return}let type=typeOf(message);if(type==="response")return this.#settle(message);if(type==="event")return this.#onEvent(validateEvent(message));this.#violation("a message that is neither a response nor an event")}catch(error){if(!(error instanceof LocalApiError))throw error;this.#violation(error.reason)}}#settle(message){let id=typeof message==="object"&&message!==null?Reflect.get(message,"id"):void 0,pending=typeof id==="string"?this.#pending.get(id):void 0;if(typeof id!=="string"||pending===void 0)return this.#violation("a response to no pending request");this.#pending.delete(id),pending.settle(message)}#violation(detail){this.#failAll(new LocalApiError("protocol_violation",detail)),this.#transport.destroy()}#failAll(error){this.#rejectFirst?.(error),this.#resolveFirst=void 0,this.#rejectFirst=void 0;for(let pending of this.#pending.values())pending.fail(error);this.#pending.clear()}}import{lstatSync as lstatSync3,readFileSync as readFileSync3,unlinkSync as unlinkSync2}from"node:fs";import{createConnection,createServer as createServer2}from"node:net";import{join as join8}from"node:path";var ENDPOINT_FILE="endpoint.json",wrap2=(socket,endpoint)=>{let closeListeners=[],closed=!1;return socket.on("close",()=>{closed=!0;for(let listener of closeListeners.splice(0))listener()}),socket.on("error",()=>{}),{endpoint,write:(bytes)=>{if(!closed)socket.write(bytes)},close:()=>{socket.end()},destroy:()=>{socket.destroy()},onData:(listener)=>{socket.on("data",(chunk)=>listener(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength)))},onClose:(listener)=>{if(closed)listener();else closeListeners.push(listener)}}};var readEndpointPort=(stateDir)=>{let parsed=JSON.parse(readFileSync3(join8(stateDir,ENDPOINT_FILE),"utf8")),port=typeof parsed==="object"&&parsed!==null?Reflect.get(parsed,"port"):void 0;if(typeof port!=="number"||!Number.isInteger(port)||port<1||port>65535)throw new LocalApiError("insecure_state_dir","endpoint.json holds no port");return port};var connectLocal=(stateDir)=>new Promise((resolve,reject)=>{let port=process.platform==="win32"?readEndpointPort(stateDir):void 0,endpoint=port===void 0?UNIX_ENDPOINT:tcpEndpoint(port),socket=port===void 0?createConnection({path:join8(stateDir,SOCKET_FILE)}):createConnection({host:"127.0.0.1",port});socket.once("error",reject),socket.once("connect",()=>{socket.off("error",reject),resolve(wrap2(socket,endpoint))})});var HANDSHAKE_TIMEOUT_MS=1e4,REQUEST_TIMEOUT_MS=30000,realTimer=(expire,ms)=>{let timer=setTimeout(expire,ms);return()=>clearTimeout(timer)},proveAndAuthenticate=async(connection,options)=>{let nonce=mintNonce();connection.send({type:"hello",v:LOCAL_API_VERSION,client:options.client,client_nonce:nonce});try{let welcome=validateWelcome(await connection.firstMessage());if(welcome.type==="refused")throw new LocalApiError("refused",welcome.reason);let token=(options.readToken??(()=>readToken(options.stateDir)))();if(!proofMatches(serverProof(token,nonce,connection.endpoint),welcome.server_proof))throw new LocalApiError("server_proof_invalid","the owner did not prove the per-boot token");return await connection.request("authenticate",{client_proof:clientProof(token,welcome.server_nonce,connection.endpoint)}),welcome}catch(error){throw connection.destroy(),error}},handshake=(connection,options)=>new Promise((resolve,reject)=>{let cancel=(options.handshakeTimer??realTimer)(()=>{connection.destroy(),reject(new LocalApiError("handshake_timeout","the owner did not complete the handshake"))},HANDSHAKE_TIMEOUT_MS);proveAndAuthenticate(connection,options).then(resolve,reject).finally(cancel)}),sendCommand=async(connection,attach,command,command_id)=>{let sent=command_id??mintId(),id={command_id:sent},timedOut=(error)=>{if(error instanceof LocalApiError&&error.code==="request_timeout")throw new LocalApiError("request_timeout",`command ${sent} may have been dispatched; follow its command state`,{command_id:sent});throw error};if(command.op==="prompt"||command.op==="steer"){let verdict=checkCommandText(command.text);if(verdict==="message_too_long")throw new LocalApiError("message_too_long","the text is over the engine limit",{limit_chars:MESSAGE_LIMIT_CHARS});if(verdict==="malformed")throw new LocalApiError("invalid_request","the text is not well-formed");let draft={id:"x".repeat(REQUEST_ID_MAX_CHARS),type:"session.command",attach,...id,command};if(lineBytes(draft)>LOCAL_INLINE_MAX){let upload_id=mintId(),parts=uploadParts(command.text).map((part)=>connection.request("session.command_part",{attach,upload_id,...part}));return await Promise.all(parts),(await connection.request("session.command",{attach,...id,upload_id,op:command.op}).catch(timedOut)).command_id}}return(await connection.request("session.command",{attach,...id,command}).catch(timedOut)).command_id},connectLocalApi=async(options)=>{if(process.platform!=="win32")checkPosixAccess(options.stateDir);let transport=await(options.transport??(()=>connectLocal(options.stateDir)))(),listeners=new Set,assembler=new EventAssembler((event)=>{for(let listener of[...listeners])listener(event)}),connection=new ClientConnection(transport,(event)=>assembler.accept(event),{timer:options.requestTimer??realTimer,ms:REQUEST_TIMEOUT_MS});return connection.closed.then(()=>assembler.failAll(new LocalApiError("closed","the connection closed"))),{welcome:await handshake(connection,options),request:(type,params)=>connection.request(type,params),onEvent:(listener)=>(listeners.add(listener),()=>{listeners.delete(listener)}),command:(attach,command,command_id)=>sendCommand(connection,attach,command,command_id),list:(filter,onRevision)=>new Promise((resolve,reject)=>{let params=filter===void 0?{}:{filter},watch=(data)=>assembler.watchListing(data.query_id,{resolve,reject},onRevision);connection.request("sessions.list",params,watch).catch(reject)}),read:(attach,options={})=>new Promise((resolve,reject)=>{let watch=(data)=>assembler.watchRead(data.query_id,attach,{resolve,reject});connection.request("session.read",{attach,...options},watch).catch(reject)}),oversizedLines:()=>connection.oversizedLines(),close:()=>connection.close(),closed:connection.closed}};function deviceServiceStateDir(platform=process.platform,env=process.env,home=homedir4()){if(platform!=="win32")return join9(home,".omo","device-service");let localAppData=env.LOCALAPPDATA??join9(home,"AppData","Local");return join9(localAppData,"OmO","device-service")}function deviceServiceEndpointPath(stateDir,platform=process.platform){return join9(stateDir,platform==="win32"?ENDPOINT_FILE:SOCKET_FILE)}var attachEvent=(event)=>{switch(event.kind){case"session.snapshot":case"session.records":case"session.attach_pending":case"session.detached":return event;default:return}},toRemote=(event)=>{switch(event.kind){case"session.snapshot":{let{type:_type,kind:_kind,attach:_attach,...snapshot}=event;return{kind:"snapshot",snapshot}}case"session.records":return{kind:"records",attach_id:event.attach_id,records:event.records};case"session.attach_pending":return{kind:"pending",reason:event.reason};case"session.detached":return{kind:"detached",reason:event.reason}}};function openAttach(client,device,sessionId){let early=[],history=[],listeners=new Set,handle,resolveSnapshot,rejectSnapshot,snapshot=new Promise((resolve,reject)=>{resolveSnapshot=resolve,rejectSnapshot=reject});snapshot.catch(()=>{});let resolveDetached,detached=new Promise((resolve)=>{resolveDetached=resolve}),ended=!1,failure,finish=(reason)=>{if(ended)return;ended=!0,stop(),listeners.clear(),rejectSnapshot(Error(`the attach ended before its snapshot: ${reason}`)),resolveDetached(reason)},deliver=(event)=>{let remote=toRemote(event);if(remote.kind==="snapshot")history.length=0,resolveSnapshot(remote.snapshot);history.push(remote);for(let listener of[...listeners])try{listener(remote)}catch(error){failure=error,finish("listener_failed");return}if(remote.kind==="detached")finish(remote.reason)},stop=client.onEvent((event)=>{let mine=attachEvent(event);if(mine===void 0)return;if(handle===void 0)early.push(mine);else if(mine.attach===handle)deliver(mine)});return client.closed.then(()=>finish("closed")),client.request("session.attach",{device,session_id:sessionId}).then(({attach})=>{handle=attach;for(let event of early.splice(0))if(event.attach===attach)deliver(event);return{device,sessionId,handle:attach,snapshot,detached,onEvent:(listener)=>{for(let event of history)listener(event);if(!ended)listeners.add(listener);return()=>listeners.delete(listener)},failure:()=>failure,read:(options={})=>client.read(attach,{...options.before===void 0?{}:{before_entry_id:options.before},...options.tail===void 0?{}:{tail:options.tail}}),detach:async()=>{try{await client.request("session.detach",{attach})}catch(error){if(!(error instanceof LocalApiError&&error.code==="not_attached"))throw error}finish("detached")}}},(error)=>{throw stop(),error})}async function connectDeviceService(options){let stateDir=options.stateDir??deviceServiceStateDir(),client=await(options.connect??connectLocalApi)({stateDir,client:{name:"omo",version:options.version}});return{serviceVersion:client.welcome.service_version,initialStatus:client.welcome.state,status:()=>client.request("status.get",{}),watchStatus:async(listener)=>{let stop=client.onEvent((event)=>{if(event.kind==="status.changed")listener(event.status)});try{await client.request("status.subscribe",{})}catch(error){throw stop(),error}return stop},setEnabled:async(enabled)=>(await client.request("service.set_enabled",{enabled})).enabled,thisDevice:async()=>(await client.request("device.info",{})).device,devices:async()=>(await client.request("devices.list",{})).devices,sessions:(filter,onRevision)=>client.list(filter,onRevision),attach:(device,sessionId)=>openAttach(client,device,sessionId),close:()=>client.close(),closed:client.closed}}var STORE_UNAVAILABLE_EXITS=[8,9],isRecord7=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),text4=(value)=>typeof value==="string"&&value.length>0;function lastJsonLine(stdout){let line=stdout.trim().split(`
186
- `).at(-1);if(line===void 0||line==="")return;try{return JSON.parse(line)}catch{return}}function classifyAccountShow(result){let value=lastJsonLine(result.stdout);if(result.exitCode===7&&isRecord7(value)&&value.keychain==="locked")return{kind:"keychain_locked"};if(STORE_UNAVAILABLE_EXITS.includes(result.exitCode))return{kind:"store_unavailable"};if(!isRecord7(value))return{kind:"account_unavailable",reason:"omo account show printed no JSON"};if(value.signedIn===!1)return{kind:"signed_out"};if(value.signedIn===!0&&result.exitCode===0){let device=value.device;if(isRecord7(device)&&text4(device.id)&&text4(device.name))return{kind:"signed_in",device:{id:device.id,name:device.name},refreshState:text4(value.refreshState)?value.refreshState:"ok"}}return{kind:"account_unavailable",reason:`omo account show answered an unexpected shape (exit ${result.exitCode})`}}function accountStateNotice(state){switch(state.kind){case"signed_in":return;case"signed_out":return"Sign in to OmO first: run omo login (or sign in from the OmO desktop app).";case"keychain_locked":return"Your OmO sign-in is behind a locked keychain. Unlock it, then try again.";case"store_unavailable":return"The credential store holding your OmO sign-in is not available right now. Try again in a moment.";case"account_unavailable":return`Could not read your OmO sign-in (${state.reason}). Sign in again with omo login.`}}var package_default={name:"omo-ai",version:"5.1.57",type:"module",description:"OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",bin:{omo:"bin/omo.js"},files:["bin","plugin"],engines:{node:">=24.0.0"},scripts:{postinstall:"node bin/senpi-patch.mjs"},dependencies:{"@code-yeongyu/senpi":"2026.10.31-2"},repository:{type:"git",url:"git+https://github.com/code-yeongyu/oh-my-openagent.git"}};import{createHash as createHash8,randomBytes as randomBytes5,randomUUID as randomUUID7,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{chmodSync as chmodSync3,mkdtempSync,rmSync as rmSync2,writeFileSync as writeFileSync3}from"node:fs";import{createServer as createServer3}from"node:net";import{tmpdir}from"node:os";import{join as join10,win32 as win322}from"node:path";var REMOTE_INPUT_OFF="remote input not enabled yet: this view is observe-only",SECRET_BYTES=32,HANDSHAKE_TIMEOUT_MS2=2000,MAX_LINE_CHARS=67108864,PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",LOCAL_SESSION_ID="remote",INPUT_COMMANDS=new Set(["prompt","steer","follow_up","abort","bash","compact","new_session","switch_session"]);function pipeAddress(socketPath,secret){let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret)]);return`${PIPE_PREFIX}${createHash8("sha256").update(identity).digest("hex").slice(0,32)}`}var isRecord8=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);function stateOf(snapshot){let state=isRecord8(snapshot.state)?snapshot.state:{};return{...state,sessionId:LOCAL_SESSION_ID,isStreaming:state.isStreaming===!0}}class Presentation{snapshot;streaming=!1;stopStream;attach;label;socket;constructor(attach,label,socket){this.attach=attach,this.label=label,this.socket=socket}startStream(){if(this.streaming)return;this.streaming=!0,this.notify(`Observing ${this.label}: ${REMOTE_INPUT_OFF}`,"info"),this.stopStream=this.attach.onEvent((event)=>this.event(event))}stop(){this.stopStream?.()}send(value){if(this.socket.writable&&!this.socket.destroyed)this.socket.write(`${JSON.stringify(value)}
185
+ `;var TOKEN_FILE="token",TOKEN_BYTES=32,NONCE_BYTES=32,SOCKET_FILE="service.sock",base64url3=(bytes)=>Buffer.from(bytes).toString("base64url"),mintNonce=()=>base64url3(randomBytes4(NONCE_BYTES)),mintId=()=>base64url3(randomBytes4(16)),insecure=(detail)=>{throw new LocalApiError("insecure_state_dir",detail)},decoded=(value,bytes,what)=>{let out=Buffer.from(value,"base64url");if(out.length!==bytes||base64url3(out)!==value)throw new LocalApiError("protocol_violation",`${what} is not ${bytes} base64url bytes`);return out},UNIX_ENDPOINT="unix",tcpEndpoint=(port)=>`tcp:${port}`,proof=(token,label,nonce,endpoint)=>base64url3(createHmac3("sha256",token).update(label).update(decoded(nonce,NONCE_BYTES,"a nonce")).update(endpoint,"utf8").digest()),serverProof=(token,clientNonce,endpoint)=>proof(token,"server",clientNonce,endpoint),clientProof=(token,serverNonce,endpoint)=>proof(token,"client",serverNonce,endpoint),proofMatches=(expected,actual)=>{let a=Buffer.from(expected),b=Buffer.from(actual);return a.length===b.length&&timingSafeEqual2(a,b)},isMissing2=(error)=>typeof error==="object"&&error!==null&&("code"in error)&&(error.code==="ENOENT"||error.code==="ENOTDIR"),currentUid=()=>process.getuid?.()??insecure("this platform has no uid"),privateEntry=(path,kind,uid,checkMode=!0)=>{let stat;try{stat=lstatSync2(path)}catch(error){if(isMissing2(error))return insecure(`the ${kind} is missing`);throw error}if(!(kind==="dir"?stat.isDirectory():kind==="socket"?stat.isSocket():stat.isFile()))insecure(`the ${kind} is not a plain ${kind}`);if(stat.uid!==uid)insecure(`the ${kind} belongs to another user`);if(checkMode&&(stat.mode&63)!==0)insecure(`the ${kind} is open to group or others`)},checkPosixAccess=(stateDir)=>{let uid=currentUid();privateEntry(stateDir,"dir",uid),privateEntry(join7(stateDir,SOCKET_FILE),"socket",uid),privateEntry(join7(stateDir,TOKEN_FILE),"file",uid)};var readToken=(stateDir)=>{let value;try{value=readFileSync2(join7(stateDir,TOKEN_FILE),"utf8")}catch(error){if(isMissing2(error))return insecure("the token is missing");throw error}try{return decoded(value,TOKEN_BYTES,"the token")}catch(error){if(error instanceof LocalApiError)return insecure("the token is malformed");throw error}};import{createHash as createHash7}from"node:crypto";var SESSION_BLOB_MAX=16777216,SESSION_COMMAND_TEXT_MAX_CHARS=1e6,SESSION_COMMAND_TEXT_MAX_BYTES=3000000,SESSION_UI_REQUEST_ID_MAX_CHARS=256,SESSION_QUESTION_ANSWERS_MAX=64,SESSION_ANSWER_SELECTED_MAX=64,SESSION_DEVICE_MAX_CHARS=64,SESSION_PROJECT_MAX_CHARS=256,SESSION_ID_MAX_CHARS=128,SESSION_READ_TAIL_MAX=200,SESSION_SUMMARY_TITLE_MAX_CHARS=256,SESSION_SUMMARY_PROJECT_MAX_CHARS=128,SESSION_SUMMARY_PATH_MAX_CHARS=1024;class ProtoError extends Error{code;constructor(code,message){super(message);this.code=code}}var validateCommandText=(text)=>{if(typeof text!=="string"||!text.isWellFormed())throw new ProtoError("malformed","command text");if(text.length>1e6||new TextEncoder().encode(text).length>3000000)throw new ProtoError("payload_too_large","session command text over the limit");return text};var LOCAL_INLINE_MAX=524288,LOCAL_CHUNK_MAX=262144,LOCAL_JSON_EXPANSION_MAX=6,LOCAL_BLOB_MAX=LOCAL_JSON_EXPANSION_MAX*SESSION_BLOB_MAX,encoder=new TextEncoder,lineBytes=(value)=>encoder.encode(JSON.stringify(value)).length+1,sha256Hex=(data)=>createHash7("sha256").update(data).digest("hex"),chunkPayload=(data)=>{let chunks=[];for(let off=0;off<data.length;off+=LOCAL_CHUNK_MAX)chunks.push({off,b:Buffer.from(data.subarray(off,off+LOCAL_CHUNK_MAX)).toString("base64")});return chunks};import{posix,win32}from"node:path";var LOCAL_API_VERSION=1,STATUS_STATES=["not_configured","disabled","sign_in_required","plan_required","keychain_locked","connecting","activation_pending","connected","offline","authorization_stale","service_degraded","update_required","signed_out"],POLICY_STATES=["off","pending","active"],THIS_DEVICE_STATES=["unclassified","desktop_unregistered","indeterminate","desktop","cli_only","acked"];var CAPABILITIES=["sessions","devices","enforcement","upgrade"],REFUSED_REASONS=["version","data_home_required","malformed"],ROUND_STATES=["open","done"],ROUND_DEVICE_STATES=["answered","pending","undelivered","page_cap","cursor_echo","timed_out","skipped"],LISTING_SOURCES=["live","cache"],SESSION_ROW_STATES=["running","idle","ended"],FILTER_KEYS=["device","project","state"],BLOB_OF=["state","record","entry"],BLOB_ABORT_REASONS=["digest_mismatch","source_gone","too_large","detached"],UPLOAD_ABORT_REASONS=["message_too_long","parts_conflict","malformed","detached"],DETACH_REASONS=["authorization_expired","activation_pending","service_disabled","owner_transfer","peer_revoked","stream_key_pending","peer_detached","blob_failed"],ATTACH_PENDING_REASONS=["stream_key_pending"],COMMAND_ID_CHARS=22,COMMAND_OPS=["prompt","steer","abort","permission","question"],COMMAND_STATES=["queued","transport_confirmed","not confirmed","not delivered: never_sent","engine_dispatched","engine_applied","engine_refused","engine_stale","uncertain"],COMMAND_UNCERTAIN_REASONS=["request_gone","no_receipt","engine_restarted","recipient_revoked","transport_expired","unconfirmed"],COMMAND_REFUSAL_REASONS=["parts_conflict","peer_unauthorized","message_too_long","engine_capability_missing"],RETRYABLE_STATES=["not confirmed","not delivered: never_sent"],ERROR_CODES=["unauthenticated","client_proof_invalid","invalid_request","unknown_type","forbidden","owner_transfer","internal","signed_out","device_mismatch","device_changed","account_changed","device_key_invalid","service_disabled","sign_in_required","plan_required","activation_pending","authorization_stale","peer_not_found","peer_not_session_client","session_not_found","engine_too_old","not_attached","command_id_conflict","message_too_long","upload_incomplete"];var REQUEST_ID_MAX_CHARS=64,LOCAL_ID_MAX_CHARS=64,PATH_MAX_CHARS=4096,LABEL_MAX_CHARS=256,REASON_MAX_CHARS=1024,ENTRY_ID_MAX_BYTES=128,NONCE_CHARS=43;class InvalidMessage extends Error{detail;constructor(detail){super(detail);this.name="InvalidMessage",this.detail=detail}}var fail=(detail)=>{throw new InvalidMessage(detail)},assertNever=(value)=>{throw Error(`unexpected variant ${JSON.stringify(value)}`)},keysOf=(record)=>Object.keys(record).filter((key)=>Object.hasOwn(record,key)),isRecord6=(v)=>typeof v==="object"&&v!==null&&!Array.isArray(v),exactly=(v,required,optional=[],what="message")=>{if(!isRecord6(v))return fail(`${what} must be an object`);for(let name of required)if(!Object.hasOwn(v,name))fail(`${what} misses ${name}`);for(let key of Object.keys(v))if(!required.includes(key)&&!optional.includes(key))fail(`${what} has an unknown field`);return v},oneOf=(list,v,what)=>list.find((item)=>item===v)??fail(what),text3=(v,max,what,min=1)=>typeof v==="string"&&v.length>=min&&v.length<=max&&v.isWellFormed()?v:fail(what),bool=(v,what)=>typeof v==="boolean"?v:fail(what),uint=(v,min,max,what)=>typeof v==="number"&&Number.isSafeInteger(v)&&v>=min&&v<=max?v:fail(what),BASE64URL=/^[A-Za-z0-9_-]+$/,localId=(v,what)=>typeof v==="string"&&v.length>=1&&v.length<=LOCAL_ID_MAX_CHARS&&BASE64URL.test(v)?v:fail(what),commandId=(v)=>typeof v==="string"&&v.length===COMMAND_ID_CHARS&&BASE64URL.test(v)?v:fail("command_id"),nonce=(v,what)=>typeof v==="string"&&v.length===NONCE_CHARS&&BASE64URL.test(v)?v:fail(what),PRINTABLE=/^[\x21-\x7e]+$/,requestId=(v)=>typeof v==="string"&&v.length<=REQUEST_ID_MAX_CHARS&&PRINTABLE.test(v)?v:void 0,SEMVER=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,semver=(v,what)=>typeof v==="string"&&v.length<=64&&SEMVER.test(v)?v:fail(what),absolutePath=(v,what)=>typeof v==="string"&&v.length<=PATH_MAX_CHARS&&v.isWellFormed()&&!v.includes("\x00")&&(posix.isAbsolute(v)||win32.isAbsolute(v))?v:fail(what),entryId=(v,what)=>typeof v==="string"&&v.length>0&&v.isWellFormed()&&new TextEncoder().encode(v).length<=ENTRY_ID_MAX_BYTES?v:fail(what),nullable2=(v,check)=>v===null?null:check(v),SHA256_HEX=/^[0-9a-f]{64}$/,sha256Field=(v,what)=>typeof v==="string"&&SHA256_HEX.test(v)?v:fail(what),base64Bytes=(v,max,what)=>{if(typeof v!=="string"||v.length===0||v.length>4*Math.ceil(max/3))return fail(what);let bytes=Buffer.from(v,"base64");return bytes.length<=max&&bytes.toString("base64")===v?new Uint8Array(bytes):fail(what)},UNSAFE_KEYS=["__proto__","constructor","prototype"],safeKey=(key,what)=>UNSAFE_KEYS.includes(key)?fail(what):key,jsonValue=(v,what)=>{if(v===null||typeof v==="boolean"||typeof v==="string")return v;if(typeof v==="number")return Number.isFinite(v)?v:fail(what);if(Array.isArray(v))return v.map((item)=>jsonValue(item,what));if(isRecord6(v))return jsonObject(v,what);return fail(what)},jsonObject=(v,what)=>{if(!isRecord6(v))return fail(what);let out={};for(let[key,item]of Object.entries(v))out[key]=jsonValue(item,what);return out};var MESSAGE_LIMIT_CHARS=SESSION_COMMAND_TEXT_MAX_CHARS,LOCAL_UPLOAD_PARTS_MAX=Math.ceil(SESSION_COMMAND_TEXT_MAX_BYTES/LOCAL_CHUNK_MAX),checkCommandText=(value)=>{try{return validateCommandText(value),"ok"}catch(error){if(error instanceof ProtoError)return error.code==="payload_too_large"?"message_too_long":"malformed";throw error}},uploadParts=(value)=>{let chunks=chunkPayload(new TextEncoder().encode(value));return chunks.map(({b},index)=>({index,count:chunks.length,b}))};class LocalBlobAssembler{#open;#parts=[];#received=0;inFlight(){return this.#open!==void 0}accept(event){switch(event.kind){case"session.blob_open":if(this.#open!==void 0)return protocolViolation("one blob in flight per attach");if(event.bytes>LOCAL_BLOB_MAX)return protocolViolation("blob over LOCAL_BLOB_MAX");this.#open=event;return;case"session.blob_chunk":{let open=this.#current(event.id),data=Buffer.from(event.b,"base64"),end=this.#received+data.length;if(event.off!==this.#received||end>open.bytes)return protocolViolation("blob chunk out of order");if(data.length!==LOCAL_CHUNK_MAX&&end!==open.bytes)return protocolViolation("short blob chunk");this.#parts.push(new Uint8Array(data)),this.#received=end;return}case"session.blob_done":{let open=this.#current(event.id);if(this.#received!==open.bytes)return protocolViolation("blob done before its last chunk");let data=new Uint8Array(open.bytes),at=0;for(let part of this.#parts)data.set(part,at),at+=part.length;return this.#reset(),sha256Hex(data)===open.sha256?{kind:"blob",open,data}:protocolViolation("blob digest mismatch")}case"session.blob_abort":{if(event.reason==="too_large")return{kind:"too_large",query_id:event.query_id,entry_id:event.entry_id};let open=this.#current(event.id);return this.#reset(),{kind:"aborted",open,reason:event.reason}}default:return assertNever(event)}}#current(id){let open=this.#open;return open!==void 0&&open.id===id?open:protocolViolation("blob not open")}#reset(){this.#open=void 0,this.#parts=[],this.#received=0}}class ListingTracker{#watches=new Map;watch(query_id,settle,onRevision){this.#watches.set(query_id,{...settle,onRevision,open:void 0,last:void 0})}failAll(error){for(let watch of this.#watches.values())watch.reject(error);this.#watches.clear()}accept(event){let watch=this.#watches.get(event.query_id);if(watch===void 0)return;switch(event.kind){case"sessions.round":{if(event.state==="open")return;if(watch.open!==void 0)return protocolViolation("a round ended during an open revision");this.#watches.delete(event.query_id);let last=watch.last;return watch.resolve({query_id:event.query_id,revision:last?.revision??0,rows:last?.rows??[],incomplete:last?.incomplete??[],devices:event.devices})}case"sessions.listing_begin":if(watch.open!==void 0||event.revision<=(watch.last?.revision??0))return protocolViolation("a revision out of order");watch.open={revision:event.revision,rows:[]};return;case"sessions.listing_rows":if(watch.open?.revision!==event.revision)return protocolViolation("rows outside their revision");for(let row of event.rows)watch.open.rows.push(row);return;case"sessions.listing_end":{if(watch.open?.revision!==event.revision)return protocolViolation("listing_end outside its revision");let revision={query_id:event.query_id,revision:event.revision,rows:watch.open.rows,incomplete:event.incomplete};watch.open=void 0,watch.last=revision,watch.onRevision?.(revision);return}default:return assertNever(event)}}}var CODE=/^[a-z_]{1,64}$/,ATTACH_ID_MAX=4294967295,MILLIS_MAX=Number.MAX_SAFE_INTEGER,deviceId=(v,what="device")=>text3(v,SESSION_DEVICE_MAX_CHARS,what),sessionId=(v)=>text3(v,SESSION_ID_MAX_CHARS,"session_id"),attachId=(v)=>uint(v,1,ATTACH_ID_MAX,"attach_id"),millis=(v,what)=>uint(v,0,MILLIS_MAX,what),deviceRef=(v,what="device")=>{let m=exactly(v,["id","name"],[],what);return{id:deviceId(m.id,`${what}.id`),name:text3(m.name,LABEL_MAX_CHARS,`${what}.name`)}},policyOf=(v)=>{let m=exactly(v,["state","generation","this_device","homes_pending","unacked"],[],"policy"),unacked=m.unacked;if(!Array.isArray(unacked))return fail("policy.unacked");return{state:oneOf(POLICY_STATES,m.state,"policy.state"),generation:millis(m.generation,"policy.generation"),this_device:oneOf(THIS_DEVICE_STATES,m.this_device,"policy.this_device"),homes_pending:millis(m.homes_pending,"policy.homes_pending"),unacked:unacked.map((u)=>{let entry=exactly(u,["device","label"],[],"policy.unacked");return{device:deviceId(entry.device),label:text3(entry.label,LABEL_MAX_CHARS,"label",0)}})}},statusOf=(v)=>{let m=exactly(v,["state","since_ms","device","origin_configured","enabled"],["detail","policy"],"status"),{detail,policy}=m;return{state:oneOf(STATUS_STATES,m.state,"status.state"),since_ms:millis(m.since_ms,"status.since_ms"),...detail===void 0?{}:{detail:detailOf(detail)},device:nullable2(m.device,(d)=>deviceRef(d,"status.device")),origin_configured:bool(m.origin_configured,"status.origin_configured"),enabled:bool(m.enabled,"status.enabled"),...policy===void 0?{}:{policy:policyOf(policy)}}},detailOf=(v)=>{let m=exactly(v,["code","action"],[],"status.detail"),code=m.code;return{code:typeof code==="string"&&CODE.test(code)?code:fail("status.detail.code"),action:nullable2(m.action,(a)=>text3(a,LABEL_MAX_CHARS,"status.detail.action"))}},deviceRowOf=(v)=>{let m=exactly(v,["device","label","kind","platform","last_seen_ms","online"],[],"device row");return{device:deviceId(m.device),label:text3(m.label,LABEL_MAX_CHARS,"label",0),kind:text3(m.kind,64,"kind",0),platform:text3(m.platform,64,"platform",0),last_seen_ms:nullable2(m.last_seen_ms,(t)=>millis(t,"last_seen_ms")),online:bool(m.online,"online")}},ROW_FIELDS=["device","session_id","title","project","path","state","updated_ms","source","as_of"],listingRowOf=(v)=>{let m=exactly(v,ROW_FIELDS,[],"listing row");return{device:deviceId(m.device),session_id:sessionId(m.session_id),title:text3(m.title,SESSION_SUMMARY_TITLE_MAX_CHARS,"title",0),project:text3(m.project,SESSION_SUMMARY_PROJECT_MAX_CHARS,"project"),path:text3(m.path,SESSION_SUMMARY_PATH_MAX_CHARS,"path"),state:oneOf(SESSION_ROW_STATES,m.state,"row state"),updated_ms:millis(m.updated_ms,"updated_ms"),source:oneOf(LISTING_SOURCES,m.source,"row source"),as_of:millis(m.as_of,"as_of")}},BODY_FIELDS=["attach_id","cursor","state","entries","history_truncated","oldest_entry_id"],snapshotBodyOf=(m)=>{let cursor=exactly(m.cursor,["marker_id","last_entry_id"],[],"cursor"),entries=m.entries;if(!Array.isArray(entries))return fail("entries");return{attach_id:attachId(m.attach_id),cursor:{marker_id:entryId(cursor.marker_id,"cursor.marker_id"),last_entry_id:nullable2(cursor.last_entry_id,(e)=>entryId(e,"cursor.last_entry_id"))},state:jsonObject(m.state,"state"),entries:entries.map((e)=>jsonValue(e,"entries")),history_truncated:bool(m.history_truncated,"history_truncated"),oldest_entry_id:nullable2(m.oldest_entry_id,(e)=>entryId(e,"oldest_entry_id"))}},snapshotBlobOf=(v)=>snapshotBodyOf(exactly(v,BODY_FIELDS,[],"snapshot")),SNAPSHOT_FIELDS=BODY_FIELDS,readEntryOf=(v)=>{let m=exactly(v,["kind","entry_id"],["entry","bytes","sha256"],"read entry"),entry_id=entryId(m.entry_id,"entry_id");if(m.kind==="entry")return exactly(m,["kind","entry_id","entry"],[],"read entry"),{kind:"entry",entry_id,entry:jsonValue(m.entry,"entry")};if(m.kind!=="entry_ref")return fail("read entry kind");return exactly(m,["kind","entry_id","bytes","sha256"],[],"read entry"),{kind:"entry_ref",entry_id,bytes:uint(m.bytes,1,MILLIS_MAX,"bytes"),sha256:sha256Field(m.sha256,"sha256")}},errorBodyOf=(v)=>{let m=exactly(v,["code","reason","action"],["limit_chars"],"error"),code=oneOf(ERROR_CODES,m.code,"error.code"),limit=m.limit_chars;if(code==="message_too_long"!==(limit!==void 0))return fail("error.limit_chars");return{code,reason:text3(m.reason,REASON_MAX_CHARS,"error.reason",0),action:nullable2(m.action,(a)=>text3(a,LABEL_MAX_CHARS,"error.action")),...limit===void 0?{}:{limit_chars:uint(limit,1,MILLIS_MAX,"error.limit_chars")}}};var eventFields=(v,names,optional=[])=>exactly(v,["type","kind",...names],optional,"event"),attachOf=(m)=>localId(m.attach,"attach"),queryOf=(m)=>localId(m.query_id,"query_id"),blobIdOf=(m)=>localId(m.id,"blob id"),targetOf=(m)=>{let of=oneOf(BLOB_OF,m.of,"blob of");switch(of){case"state":{let p=exactly(m.position,["attach_id"],[],"position");return{of,position:{attach_id:attachId(p.attach_id)}}}case"record":{let p=exactly(m.position,["attach_id","seq"],[],"position"),seq=uint(p.seq,1,Number.MAX_SAFE_INTEGER,"seq");return{of,position:{attach_id:attachId(p.attach_id),seq}}}case"entry":{let p=exactly(m.position,["query_id","entry_id"],[],"position");return{of,position:{query_id:queryOf(p),entry_id:entryId(p.entry_id,"position.entry_id")}}}}},STREAM_EVENT_VALIDATORS={"session.snapshot":(v)=>{let m=eventFields(v,["attach",...SNAPSHOT_FIELDS]);return{type:"event",kind:"session.snapshot",attach:attachOf(m),...snapshotBodyOf(m)}},"session.snapshot_loading":(v)=>{let m=eventFields(v,["attach","blob"]);return{type:"event",kind:"session.snapshot_loading",attach:attachOf(m),blob:localId(m.blob,"blob")}},"session.records":(v)=>{let m=eventFields(v,["attach","attach_id","records"]),records=m.records;if(!Array.isArray(records)||records.length===0)return fail("records");let attach_id=attachId(m.attach_id);return{type:"event",kind:"session.records",attach:attachOf(m),attach_id,records:records.map((r)=>jsonObject(r,"record"))}},"session.blob_open":(v)=>{let m=eventFields(v,["attach","id","of","bytes","sha256","position"]);return{type:"event",kind:"session.blob_open",attach:attachOf(m),id:blobIdOf(m),bytes:uint(m.bytes,1,LOCAL_BLOB_MAX,"blob bytes"),sha256:sha256Field(m.sha256,"blob sha256"),...targetOf(m)}},"session.blob_chunk":(v)=>{let m=eventFields(v,["attach","id","off","b"]);base64Bytes(m.b,LOCAL_CHUNK_MAX,"blob chunk");let b=typeof m.b==="string"?m.b:fail("blob chunk"),off=uint(m.off,0,LOCAL_BLOB_MAX,"blob off");return{type:"event",kind:"session.blob_chunk",attach:attachOf(m),id:blobIdOf(m),off,b}},"session.blob_done":(v)=>{let m=eventFields(v,["attach","id"]);return{type:"event",kind:"session.blob_done",attach:attachOf(m),id:blobIdOf(m)}},"session.blob_abort":(v)=>{let head=eventFields(v,["attach","id","reason"],["query_id","entry_id"]),reason=oneOf(BLOB_ABORT_REASONS,head.reason,"blob abort reason"),base={type:"event",kind:"session.blob_abort",attach:attachOf(head),id:blobIdOf(head)};if(reason!=="too_large")return eventFields(v,["attach","id","reason"]),{...base,reason};let m=eventFields(v,["attach","id","reason","query_id","entry_id"]);return{...base,reason,query_id:queryOf(m),entry_id:entryId(m.entry_id,"entry_id")}},"session.attach_pending":(v)=>{let m=eventFields(v,["attach","reason"]),reason=oneOf(ATTACH_PENDING_REASONS,m.reason,"pending reason");return{type:"event",kind:"session.attach_pending",attach:attachOf(m),reason}},"session.detached":(v)=>{let m=eventFields(v,["attach","reason"]),reason=oneOf(DETACH_REASONS,m.reason,"detach reason");return{type:"event",kind:"session.detached",attach:attachOf(m),reason}}};var revisionOf=(m)=>uint(m.revision,1,Number.MAX_SAFE_INTEGER,"revision"),devicesOf=(v)=>{if(!isRecord6(v))return fail("round devices");let out={};for(let[device,state]of Object.entries(v))out[safeKey(deviceId(device),"round device")]=oneOf(ROUND_DEVICE_STATES,state,"round device state");return out},commandStateOf=(v)=>{let m=eventFields(v,["command_id","state","retryable"],["reason","receipt"]),state=oneOf(COMMAND_STATES,m.state,"command state");if(bool(m.retryable,"retryable")!==RETRYABLE_STATES.includes(state))return fail("retryable");let head={type:"event",kind:"session.command_state",command_id:commandId(m.command_id),...m.receipt===void 0?{}:{receipt:jsonObject(m.receipt,"receipt")}},reason=m.reason;switch(state){case"engine_refused":return{...head,state,reason:oneOf(COMMAND_REFUSAL_REASONS,reason,"refusal reason"),retryable:!1};case"uncertain":return{...head,state,reason:oneOf(COMMAND_UNCERTAIN_REASONS,reason,"uncertain reason"),retryable:!1};case"not confirmed":case"not delivered: never_sent":return reason===void 0?{...head,state,retryable:!0}:fail("reason");case"queued":case"transport_confirmed":case"engine_dispatched":case"engine_applied":case"engine_stale":return reason===void 0?{...head,state,retryable:!1}:fail("reason")}},VALIDATORS={...STREAM_EVENT_VALIDATORS,"status.changed":(v)=>({type:"event",kind:"status.changed",status:statusOf(eventFields(v,["status"]).status)}),"sessions.round":(v)=>{let m=eventFields(v,["query_id","state","devices"]),state=oneOf(ROUND_STATES,m.state,"round state");return{type:"event",kind:"sessions.round",query_id:queryOf(m),state,devices:devicesOf(m.devices)}},"sessions.listing_begin":(v)=>{let m=eventFields(v,["query_id","revision"]);return{type:"event",kind:"sessions.listing_begin",query_id:queryOf(m),revision:revisionOf(m)}},"sessions.listing_rows":(v)=>{let m=eventFields(v,["query_id","revision","rows"]),rows=m.rows;if(!Array.isArray(rows)||rows.length===0)return fail("rows");return{type:"event",kind:"sessions.listing_rows",query_id:queryOf(m),revision:revisionOf(m),rows:rows.map(listingRowOf)}},"sessions.listing_end":(v)=>{let m=eventFields(v,["query_id","revision","incomplete"]),incomplete=m.incomplete;if(!Array.isArray(incomplete))return fail("incomplete");let devices=incomplete.map((d)=>deviceId(d));return{type:"event",kind:"sessions.listing_end",query_id:queryOf(m),revision:revisionOf(m),incomplete:devices}},"session.command_state":commandStateOf,"session.read_result":(v)=>{let m=eventFields(v,["attach","query_id","entries","next_before"]),entries=m.entries;if(!Array.isArray(entries)||entries.length>SESSION_READ_TAIL_MAX)return fail("entries");let rows=entries.map(readEntryOf);if(new Set(rows.map((r)=>r.entry_id)).size!==rows.length)return fail("duplicate entry_id");let next_before=nullable2(m.next_before,(e)=>entryId(e,"next_before"));return{type:"event",kind:"session.read_result",attach:attachOf(m),query_id:queryOf(m),entries:rows,next_before}},"session.upload_abort":(v)=>{let m=eventFields(v,["upload_id","reason"]),reason=oneOf(UPLOAD_ABORT_REASONS,m.reason,"upload abort reason");return{type:"event",kind:"session.upload_abort",upload_id:localId(m.upload_id,"upload_id"),reason}}},EVENT_KINDS=keysOf(VALIDATORS),validateEventFields=(v)=>{if(v.type!=="event")return fail("an event has type event");return VALIDATORS[oneOf(EVENT_KINDS,v.kind,"event kind")](v)};var requestFields=(v,names,optional=[])=>exactly(v,["id","type",...names],optional,"request"),commandText=(v,what)=>typeof v==="string"&&v.isWellFormed()?v:fail(what),answersOf=(v)=>{if(!isRecord6(v)||Object.keys(v).length>SESSION_QUESTION_ANSWERS_MAX)return fail("answers");let out={};for(let[key,answer]of Object.entries(v)){let id=safeKey(text3(key,SESSION_UI_REQUEST_ID_MAX_CHARS,"answer key"),"answer key"),m=exactly(answer,["selected"],["text"],"answer"),selected=m.selected;if(!Array.isArray(selected)||selected.length>SESSION_ANSWER_SELECTED_MAX)return fail("answer selected");let extra=m.text===void 0?{}:{text:commandText(m.text,"answer text")};out[id]={selected:selected.map((s)=>commandText(s,"answer selected")),...extra}}return out},commandOf=(v)=>{let m=exactly(v,["op"],["text","ui_request_id","confirmed","answers","comment"],"command"),op=COMMAND_OPS.find((o)=>o===m.op)??fail("command op"),uiRequest=()=>text3(m.ui_request_id,SESSION_UI_REQUEST_ID_MAX_CHARS,"ui_request_id");switch(op){case"prompt":case"steer":return exactly(m,["op","text"],[],"command"),{op,text:commandText(m.text,"command text")};case"abort":return exactly(m,["op"],[],"command"),{op};case"permission":return exactly(m,["op","ui_request_id","confirmed"],[],"command"),{op,ui_request_id:uiRequest(),confirmed:bool(m.confirmed,"confirmed")};case"question":{exactly(m,["op","ui_request_id","answers"],["comment"],"command");let comment=m.comment===void 0?{}:{comment:commandText(m.comment,"comment")};return{op,ui_request_id:uiRequest(),answers:answersOf(m.answers),...comment}}}},commandIdField=(v)=>v===void 0?{}:{command_id:commandId(v)},COMMAND_REQUEST_VALIDATORS={"session.command":(v,id)=>{if(Object.hasOwn(v,"upload_id")){let m=requestFields(v,["attach","upload_id","op"],["command_id"]),op=m.op==="prompt"||m.op==="steer"?m.op:fail("upload op"),upload_id=localId(m.upload_id,"upload_id");return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),upload_id,op}}let m=requestFields(v,["attach","command"],["command_id"]),command=commandOf(m.command);return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),command}},"session.command_part":(v,id)=>{let m=requestFields(v,["attach","upload_id","index","count","b"]),count=uint(m.count,1,LOCAL_UPLOAD_PARTS_MAX,"count");return base64Bytes(m.b,LOCAL_CHUNK_MAX,"b"),{id,type:"session.command_part",attach:localId(m.attach,"attach"),upload_id:localId(m.upload_id,"upload_id"),index:uint(m.index,0,count-1,"index"),count,b:typeof m.b==="string"?m.b:fail("b")}}};var ENVIRONMENTS_MAX=1024,PKCS8_KEY_BYTES=48,PKCS8_PREFIX={ed25519:"302e020100300506032b657004220420",x25519:"302e020100300506032b656e04220420"},pkcs8=(v,algorithm,what)=>{let bytes=base64Bytes(v,PKCS8_KEY_BYTES,what),prefix=Buffer.from(bytes.subarray(0,16)).toString("hex");return bytes.length===PKCS8_KEY_BYTES&&prefix===PKCS8_PREFIX[algorithm]&&typeof v==="string"?v:fail(what)},filterOf=(v)=>{let{device,project,state}=exactly(v,[],FILTER_KEYS,"filter");return{...device===void 0?{}:{device:deviceId(device,"filter.device")},...project===void 0?{}:{project:text3(project,SESSION_PROJECT_MAX_CHARS,"filter.project")},...state===void 0?{}:{state:SESSION_ROW_STATES.find((s)=>s===state)??fail("filter.state")}}},environmentsOf=(v)=>{if(!Array.isArray(v)||v.length>ENVIRONMENTS_MAX)return fail("environments");let rows=v.map((e)=>{let m=exactly(e,["environment_id","revoked","closed"],[],"environment");return{environment_id:text3(m.environment_id,128,"environment_id"),revoked:uint(m.revoked,0,Number.MAX_SAFE_INTEGER,"revoked"),closed:uint(m.closed,0,Number.MAX_SAFE_INTEGER,"closed")}});return new Set(rows.map((r)=>r.environment_id)).size===rows.length?rows:fail("duplicate environment_id")},bare=(v)=>{requestFields(v,[])},agentDir=(v)=>absolutePath(requestFields(v,["agent_dir"]).agent_dir,"agent_dir"),VALIDATORS2={...COMMAND_REQUEST_VALIDATORS,authenticate:(v,id)=>{let m=requestFields(v,["client_proof"]);return{id,type:"authenticate",client_proof:text3(m.client_proof,64,"client_proof")}},"status.get":(v,id)=>(bare(v),{id,type:"status.get"}),"status.subscribe":(v,id)=>(bare(v),{id,type:"status.subscribe"}),"service.set_enabled":(v,id)=>{let enabled=bool(requestFields(v,["enabled"]).enabled,"enabled");return{id,type:"service.set_enabled",enabled}},"refresher.register":(v,id)=>{let m=requestFields(v,["binary_path","version"]),binary_path=absolutePath(m.binary_path,"binary_path");return{id,type:"refresher.register",binary_path,version:semver(m.version,"version")}},"device.adopt":(v,id)=>{let m=requestFields(v,["device","signing_private_key","sealing_private_key"]);return{id,type:"device.adopt",device:deviceRef(m.device),signing_private_key:pkcs8(m.signing_private_key,"ed25519","signing_private_key"),sealing_private_key:pkcs8(m.sealing_private_key,"x25519","sealing_private_key")}},"device.forget":(v,id)=>(bare(v),{id,type:"device.forget"}),"device.info":(v,id)=>(bare(v),{id,type:"device.info"}),"endpoints.register":(v,id)=>({id,type:"endpoints.register",agent_dir:agentDir(v)}),"endpoints.unregister":(v,id)=>({id,type:"endpoints.unregister",agent_dir:agentDir(v)}),"devices.list":(v,id)=>(bare(v),{id,type:"devices.list"}),"sessions.list":(v,id)=>{let filter=requestFields(v,[],["filter"]).filter;return filter===void 0?{id,type:"sessions.list"}:{id,type:"sessions.list",filter:filterOf(filter)}},"session.attach":(v,id)=>{let m=requestFields(v,["device","session_id"]);return{id,type:"session.attach",device:deviceId(m.device),session_id:sessionId(m.session_id)}},"session.detach":(v,id)=>({id,type:"session.detach",attach:localId(requestFields(v,["attach"]).attach,"attach")}),"session.read":(v,id)=>{let m=requestFields(v,["attach"],["before_entry_id","tail"]),{before_entry_id:before,tail}=m;return{id,type:"session.read",attach:localId(m.attach,"attach"),...before===void 0?{}:{before_entry_id:entryId(before,"before_entry_id")},...tail===void 0?{}:{tail:uint(tail,1,SESSION_READ_TAIL_MAX,"tail")}}},"enforcement.report":(v,id)=>{let m=requestFields(v,["generation","data_home","environments","complete"]);return{id,type:"enforcement.report",generation:uint(m.generation,0,Number.MAX_SAFE_INTEGER,"generation"),data_home:absolutePath(m.data_home,"data_home"),environments:environmentsOf(m.environments),complete:bool(m.complete,"complete")}},"owner.shutdown_for_upgrade":(v,id)=>{let target_version=semver(requestFields(v,["target_version"]).target_version,"target_version");return{id,type:"owner.shutdown_for_upgrade",target_version}}},REQUEST_TYPES=keysOf(VALIDATORS2);var asViolation=(check)=>{try{return check()}catch(error){if(error instanceof InvalidMessage)throw new LocalApiError("protocol_violation",error.detail);throw error}};var validateWelcome=(v)=>asViolation(()=>{if(isRecord6(v)&&v.type==="refused"){let m=exactly(v,["type","reason"],[],"refused");return{type:"refused",reason:oneOf(REFUSED_REASONS,m.reason,"refused reason")}}if(isRecord6(v)&&v.type==="welcome"&&v.v!==LOCAL_API_VERSION)return{type:"refused",reason:"version"};let m=exactly(v,["type","v","service_version","owner","server_proof","server_nonce","capabilities","state"],[],"welcome"),capabilities=m.capabilities;if(m.type!=="welcome"||m.owner!=="service")return fail("welcome");if(!Array.isArray(capabilities)||new Set(capabilities).size!==capabilities.length)return fail("capabilities");return{type:"welcome",v:LOCAL_API_VERSION,service_version:semver(m.service_version,"service_version"),owner:"service",server_proof:nonce(m.server_proof,"server_proof"),server_nonce:nonce(m.server_nonce,"server_nonce"),capabilities:capabilities.map((c)=>oneOf(CAPABILITIES,c,"capability")),state:statusOf(m.state)}});var empty=(v)=>(exactly(v,[],[],"data"),{}),one=(v,name)=>exactly(v,[name],[],"data")[name],DATA={authenticate:empty,"status.get":statusOf,"status.subscribe":empty,"service.set_enabled":(v)=>({enabled:bool(one(v,"enabled"),"enabled")}),"refresher.register":empty,"device.adopt":(v)=>({device:deviceRef(one(v,"device"))}),"device.forget":empty,"device.info":(v)=>({device:nullable2(one(v,"device"),(d)=>deviceRef(d))}),"endpoints.register":empty,"endpoints.unregister":empty,"devices.list":(v)=>{let devices=one(v,"devices");return Array.isArray(devices)?{devices:devices.map(deviceRowOf)}:fail("devices")},"sessions.list":(v)=>({query_id:localId(one(v,"query_id"),"query_id")}),"session.attach":(v)=>({attach:localId(one(v,"attach"),"attach")}),"session.detach":empty,"session.command":(v)=>({command_id:commandId(one(v,"command_id"))}),"session.command_part":(v)=>({received:uint(one(v,"received"),0,LOCAL_UPLOAD_PARTS_MAX-1,"received")}),"session.read":(v)=>({query_id:localId(one(v,"query_id"),"query_id")}),"enforcement.report":empty,"owner.shutdown_for_upgrade":empty},validateResponse=(v,type)=>asViolation(()=>{let m=exactly(v,["id","type","ok"],["data","error"],"response"),id=requestId(m.id)??fail("response id");if(m.type!=="response")return fail("response type");if(m.ok===!0)return exactly(m,["id","type","ok","data"],[],"response"),{id,ok:!0,data:DATA[type](m.data)};if(m.ok!==!1)return fail("response ok");return exactly(m,["id","type","ok","error"],[],"response"),{id,ok:!1,error:errorBodyOf(m.error)}}),validateEvent=(v)=>asViolation(()=>isRecord6(v)?validateEventFields(v):fail("an event is an object")),validateSnapshotBlob=(v)=>asViolation(()=>snapshotBlobOf(v));var parsed=(data)=>{try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(data))}catch(error){if(error instanceof SyntaxError||error instanceof TypeError)return protocolViolation("a blob is not UTF-8 JSON");throw error}},checked=(check)=>{try{return check()}catch(error){if(error instanceof InvalidMessage)return protocolViolation(error.detail);throw error}};class EventAssembler{#emit;#blobs=new Map;#listings=new ListingTracker;#reads=new Map;constructor(emit){this.#emit=emit}watchListing(query_id,settle,onRevision){this.#listings.watch(query_id,settle,onRevision)}watchRead(query_id,attach,settle){this.#reads.set(query_id,{...settle,attach,result:void 0,filled:new Map})}failAll(error){this.#listings.failAll(error);for(let watch of this.#reads.values())watch.reject(error);this.#reads.clear()}accept(event){switch(this.#emit(event),event.kind){case"session.blob_open":case"session.blob_chunk":case"session.blob_done":case"session.blob_abort":return this.#blob(event.attach,event);case"sessions.listing_begin":case"sessions.listing_rows":case"sessions.listing_end":case"sessions.round":return this.#listings.accept(event);case"session.read_result":return this.#readResult(event);case"session.detached":return this.#detached(event.attach);case"status.changed":case"session.snapshot":case"session.snapshot_loading":case"session.records":case"session.attach_pending":case"session.command_state":case"session.upload_abort":return;default:return assertNever(event)}}#blob(attach,event){let assembler=this.#blobs.get(attach)??new LocalBlobAssembler;this.#blobs.set(attach,assembler);let outcome=assembler.accept(event);if(outcome===void 0)return;switch(outcome.kind){case"blob":return this.#apply(attach,outcome.open,outcome.data);case"aborted":if(outcome.open.of==="entry")this.#failRead(outcome.open.position.query_id,"an entry blob was aborted");return;case"too_large":return this.#fill(outcome.query_id,outcome.entry_id,(ref)=>({entry_id:ref.entry_id,too_large:!0,bytes:ref.bytes}));default:return assertNever(outcome)}}#apply(attach,open,data){let value=parsed(data);switch(open.of){case"state":{let body=validateSnapshotBlob(value);if(body.attach_id!==open.position.attach_id)protocolViolation("a snapshot blob of another attach generation");return this.#emit({type:"event",kind:"session.snapshot",attach,...body})}case"record":{let records=[checked(()=>jsonObject(value,"record"))];return this.#emit({type:"event",kind:"session.records",attach,attach_id:open.position.attach_id,records})}case"entry":{let entry=checked(()=>jsonValue(value,"entry"));return this.#fill(open.position.query_id,open.position.entry_id,(ref)=>ref.bytes===open.bytes&&ref.sha256===open.sha256?{entry_id:ref.entry_id,entry}:protocolViolation("an entry blob unlike its entry_ref"))}default:return assertNever(open)}}#fill(query_id,entry_id,make){let watch=this.#reads.get(query_id);if(watch===void 0)return;if(watch.result===void 0)return protocolViolation("an entry blob before its read_result");let ref=watch.result.entries.find((e)=>e.kind==="entry_ref"&&e.entry_id===entry_id);if(ref===void 0||ref.kind!=="entry_ref")return protocolViolation("a blob for an entry the page did not reference");watch.filled.set(entry_id,make(ref)),this.#finishRead(query_id,watch)}#readResult(event){let watch=this.#reads.get(event.query_id);if(watch===void 0)return;watch.result=event,this.#finishRead(event.query_id,watch)}#finishRead(query_id,watch){let result=watch.result;if(result===void 0)return;let entries=[];for(let entry of result.entries){let filled=entry.kind==="entry"?{entry_id:entry.entry_id,entry:entry.entry}:watch.filled.get(entry.entry_id);if(filled===void 0)return;entries.push(filled)}this.#reads.delete(query_id),watch.resolve({entries,next_before:result.next_before})}#failRead(query_id,reason){let watch=this.#reads.get(query_id);if(watch===void 0)return;this.#reads.delete(query_id),watch.reject(new LocalApiError("read_failed",reason))}#detached(attach){this.#blobs.delete(attach);for(let[query_id,watch]of this.#reads)if(watch.attach===attach)this.#failRead(query_id,"the attach was detached")}}var LOCAL_LINE_MAX=1048576,LF=10,encoder2=new TextEncoder,utf8=new TextDecoder("utf-8",{fatal:!0}),encodeLine=(value)=>{let body=encoder2.encode(JSON.stringify(value));if(body.length>LOCAL_LINE_MAX)throw new LocalApiError("protocol_violation",`a ${body.length}-byte line exceeds LOCAL_LINE_MAX`);let line=new Uint8Array(body.length+1);return line.set(body),line[body.length]=LF,line},parseLine=(line)=>{let decoded;try{decoded=utf8.decode(line)}catch(error){if(error instanceof TypeError)throw new LocalApiError("protocol_violation","a line is not UTF-8");throw error}try{return JSON.parse(decoded)}catch(error){if(error instanceof SyntaxError)throw new LocalApiError("protocol_violation","a line is not JSON");throw error}};class LineDecoder{#onLine;#onOversized;#parts=[];#length=0;#discarding=!1;constructor(onLine,onOversized){this.#onLine=onLine,this.#onOversized=onOversized}push(chunk){let start=0;while(start<chunk.length){let lf=chunk.indexOf(LF,start);if(this.#take(chunk.subarray(start,lf===-1?chunk.length:lf)),lf===-1)return;this.#finish(),start=lf+1}}#take(piece){if(this.#discarding||piece.length===0)return;if(this.#length+piece.length>LOCAL_LINE_MAX){this.#discarding=!0,this.#onOversized(this.#length+piece.length),this.#parts=[],this.#length=0;return}this.#parts.push(piece.slice()),this.#length+=piece.length}#finish(){if(this.#discarding){this.#discarding=!1;return}let line=new Uint8Array(this.#length),at=0;for(let part of this.#parts)line.set(part,at),at+=part.length;this.#parts=[],this.#length=0,this.#onLine(line)}}var EXPIRED={settle:()=>{},fail:()=>{}},typeOf=(message)=>typeof message==="object"&&message!==null?Reflect.get(message,"type"):void 0;class ClientConnection{#transport;#onEvent;#pending=new Map;closed;#first;#resolveFirst;#rejectFirst;#nextId=1;#ended=!1;#oversized=0;#deadline;constructor(transport,onEvent,deadline){this.#transport=transport,this.#onEvent=onEvent,this.#deadline=deadline,this.#first=new Promise((resolve,reject)=>{this.#resolveFirst=resolve,this.#rejectFirst=reject});let decoder=new LineDecoder((line)=>this.#onLine(line),()=>{this.#oversized+=1});transport.onData((bytes)=>decoder.push(bytes)),this.closed=new Promise((resolve)=>{transport.onClose(()=>{this.#ended=!0,this.#failAll(new LocalApiError("closed","the connection closed")),resolve()})})}send(message){this.#transport.write(encodeLine(message))}firstMessage(){return this.#first}oversizedLines(){return this.#oversized}get endpoint(){return this.#transport.endpoint}close(){this.#transport.close()}destroy(){this.#transport.destroy()}request(type,params,onAnswer){if(this.#ended)return Promise.reject(new LocalApiError("closed","the connection is closed"));let id=String(this.#nextId);this.#nextId+=1;let message={id,type,...params};if(lineBytes(message)>LOCAL_INLINE_MAX)return Promise.reject(new LocalApiError("protocol_violation","a request line over LOCAL_INLINE_MAX"));return new Promise((resolve,reject)=>{let cancel=this.#deadline.timer(()=>{if(this.#pending.get(id)===void 0)return;this.#pending.set(id,EXPIRED),reject(new LocalApiError("request_timeout",`the owner did not answer ${type} in time`))},this.#deadline.ms);this.#pending.set(id,{settle:(raw)=>{cancel();let response;try{response=validateResponse(raw,type)}catch(error){if(error instanceof LocalApiError)reject(error);throw error}if(!response.ok){let{code,reason,action,limit_chars}=response.error;reject(new LocalApiError(code,reason,limit_chars===void 0?{action}:{action,limit_chars}));return}onAnswer?.(response.data),resolve(response.data)},fail:(error)=>{cancel(),reject(error)}}),this.send(message)})}#onLine(line){try{let message=parseLine(line);if(this.#resolveFirst!==void 0){let resolve=this.#resolveFirst;this.#resolveFirst=void 0,this.#rejectFirst=void 0,resolve(message);return}let type=typeOf(message);if(type==="response")return this.#settle(message);if(type==="event")return this.#onEvent(validateEvent(message));this.#violation("a message that is neither a response nor an event")}catch(error){if(!(error instanceof LocalApiError))throw error;this.#violation(error.reason)}}#settle(message){let id=typeof message==="object"&&message!==null?Reflect.get(message,"id"):void 0,pending=typeof id==="string"?this.#pending.get(id):void 0;if(typeof id!=="string"||pending===void 0)return this.#violation("a response to no pending request");this.#pending.delete(id),pending.settle(message)}#violation(detail){this.#failAll(new LocalApiError("protocol_violation",detail)),this.#transport.destroy()}#failAll(error){this.#rejectFirst?.(error),this.#resolveFirst=void 0,this.#rejectFirst=void 0;for(let pending of this.#pending.values())pending.fail(error);this.#pending.clear()}}import{lstatSync as lstatSync3,readFileSync as readFileSync3,unlinkSync as unlinkSync2}from"node:fs";import{createConnection,createServer as createServer2}from"node:net";import{join as join8}from"node:path";var ENDPOINT_FILE="endpoint.json",wrap2=(socket,endpoint)=>{let closeListeners=[],closed=!1;return socket.on("close",()=>{closed=!0;for(let listener of closeListeners.splice(0))listener()}),socket.on("error",()=>{}),{endpoint,write:(bytes)=>{if(!closed)socket.write(bytes)},close:()=>{socket.end()},destroy:()=>{socket.destroy()},onData:(listener)=>{socket.on("data",(chunk)=>listener(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength)))},onClose:(listener)=>{if(closed)listener();else closeListeners.push(listener)}}};var readEndpointPort=(stateDir)=>{let parsed=JSON.parse(readFileSync3(join8(stateDir,ENDPOINT_FILE),"utf8")),port=typeof parsed==="object"&&parsed!==null?Reflect.get(parsed,"port"):void 0;if(typeof port!=="number"||!Number.isInteger(port)||port<1||port>65535)throw new LocalApiError("insecure_state_dir","endpoint.json holds no port");return port};var connectLocal=(stateDir)=>new Promise((resolve,reject)=>{let port=process.platform==="win32"?readEndpointPort(stateDir):void 0,endpoint=port===void 0?UNIX_ENDPOINT:tcpEndpoint(port),socket=port===void 0?createConnection({path:join8(stateDir,SOCKET_FILE)}):createConnection({host:"127.0.0.1",port});socket.once("error",reject),socket.once("connect",()=>{socket.off("error",reject),resolve(wrap2(socket,endpoint))})});var HANDSHAKE_TIMEOUT_MS=1e4,REQUEST_TIMEOUT_MS=30000,realTimer=(expire,ms)=>{let timer=setTimeout(expire,ms);return()=>clearTimeout(timer)},proveAndAuthenticate=async(connection,options)=>{let nonce=mintNonce();connection.send({type:"hello",v:LOCAL_API_VERSION,client:options.client,client_nonce:nonce});try{let welcome=validateWelcome(await connection.firstMessage());if(welcome.type==="refused")throw new LocalApiError("refused",welcome.reason);let token=(options.readToken??(()=>readToken(options.stateDir)))();if(!proofMatches(serverProof(token,nonce,connection.endpoint),welcome.server_proof))throw new LocalApiError("server_proof_invalid","the owner did not prove the per-boot token");return await connection.request("authenticate",{client_proof:clientProof(token,welcome.server_nonce,connection.endpoint)}),welcome}catch(error){throw connection.destroy(),error}},handshake=(connection,options)=>new Promise((resolve,reject)=>{let cancel=(options.handshakeTimer??realTimer)(()=>{connection.destroy(),reject(new LocalApiError("handshake_timeout","the owner did not complete the handshake"))},HANDSHAKE_TIMEOUT_MS);proveAndAuthenticate(connection,options).then(resolve,reject).finally(cancel)}),sendCommand=async(connection,attach,command,command_id)=>{let sent=command_id??mintId(),id={command_id:sent},timedOut=(error)=>{if(error instanceof LocalApiError&&error.code==="request_timeout")throw new LocalApiError("request_timeout",`command ${sent} may have been dispatched; follow its command state`,{command_id:sent});throw error};if(command.op==="prompt"||command.op==="steer"){let verdict=checkCommandText(command.text);if(verdict==="message_too_long")throw new LocalApiError("message_too_long","the text is over the engine limit",{limit_chars:MESSAGE_LIMIT_CHARS});if(verdict==="malformed")throw new LocalApiError("invalid_request","the text is not well-formed");let draft={id:"x".repeat(REQUEST_ID_MAX_CHARS),type:"session.command",attach,...id,command};if(lineBytes(draft)>LOCAL_INLINE_MAX){let upload_id=mintId(),parts=uploadParts(command.text).map((part)=>connection.request("session.command_part",{attach,upload_id,...part}));return await Promise.all(parts),(await connection.request("session.command",{attach,...id,upload_id,op:command.op}).catch(timedOut)).command_id}}return(await connection.request("session.command",{attach,...id,command}).catch(timedOut)).command_id},connectLocalApi=async(options)=>{if(process.platform!=="win32")checkPosixAccess(options.stateDir);let transport=await(options.transport??(()=>connectLocal(options.stateDir)))(),listeners=new Set,assembler=new EventAssembler((event)=>{for(let listener of[...listeners])listener(event)}),connection=new ClientConnection(transport,(event)=>assembler.accept(event),{timer:options.requestTimer??realTimer,ms:REQUEST_TIMEOUT_MS});return connection.closed.then(()=>assembler.failAll(new LocalApiError("closed","the connection closed"))),{welcome:await handshake(connection,options),request:(type,params)=>connection.request(type,params),onEvent:(listener)=>(listeners.add(listener),()=>{listeners.delete(listener)}),command:(attach,command,command_id)=>sendCommand(connection,attach,command,command_id),list:(filter,onRevision)=>new Promise((resolve,reject)=>{let params=filter===void 0?{}:{filter},watch=(data)=>assembler.watchListing(data.query_id,{resolve,reject},onRevision);connection.request("sessions.list",params,watch).catch(reject)}),read:(attach,options={})=>new Promise((resolve,reject)=>{let watch=(data)=>assembler.watchRead(data.query_id,attach,{resolve,reject});connection.request("session.read",{attach,...options},watch).catch(reject)}),oversizedLines:()=>connection.oversizedLines(),close:()=>connection.close(),closed:connection.closed}};var attachEvent=(event)=>{switch(event.kind){case"session.snapshot":case"session.records":case"session.attach_pending":case"session.detached":return event;default:return}},toRemote=(event)=>{switch(event.kind){case"session.snapshot":{let{type:_type,kind:_kind,attach:_attach,...snapshot}=event;return{kind:"snapshot",snapshot}}case"session.records":return{kind:"records",attach_id:event.attach_id,records:event.records};case"session.attach_pending":return{kind:"pending",reason:event.reason};case"session.detached":return{kind:"detached",reason:event.reason}}};function openAttach(client,device,sessionId){let early=[],history=[],listeners=new Set,handle,resolveSnapshot,rejectSnapshot,snapshot=new Promise((resolve,reject)=>{resolveSnapshot=resolve,rejectSnapshot=reject});snapshot.catch(()=>{});let resolveDetached,detached=new Promise((resolve)=>{resolveDetached=resolve}),ended=!1,failure,finish=(reason)=>{if(ended)return;ended=!0,stop(),listeners.clear(),rejectSnapshot(Error(`the attach ended before its snapshot: ${reason}`)),resolveDetached(reason)},deliver=(event)=>{let remote=toRemote(event);if(remote.kind==="snapshot")history.length=0,resolveSnapshot(remote.snapshot);history.push(remote);for(let listener of[...listeners])try{listener(remote)}catch(error){failure=error,finish("listener_failed");return}if(remote.kind==="detached")finish(remote.reason)},stop=client.onEvent((event)=>{let mine=attachEvent(event);if(mine===void 0)return;if(handle===void 0)early.push(mine);else if(mine.attach===handle)deliver(mine)});return client.closed.then(()=>finish("closed")),client.request("session.attach",{device,session_id:sessionId}).then(({attach})=>{handle=attach;for(let event of early.splice(0))if(event.attach===attach)deliver(event);return{device,sessionId,handle:attach,snapshot,detached,onEvent:(listener)=>{for(let event of history)listener(event);if(!ended)listeners.add(listener);return()=>listeners.delete(listener)},failure:()=>failure,read:(options={})=>client.read(attach,{...options.before===void 0?{}:{before_entry_id:options.before},...options.tail===void 0?{}:{tail:options.tail}}),detach:async()=>{try{await client.request("session.detach",{attach})}catch(error){if(!(error instanceof LocalApiError&&error.code==="not_attached"))throw error}finish("detached")}}},(error)=>{throw stop(),error})}function deviceServiceStateDir(platform=process.platform,env=process.env,home=homedir4()){if(platform!=="win32")return join9(home,".omo","device-service");let localAppData=env.LOCALAPPDATA??join9(home,"AppData","Local");return join9(localAppData,"OmO","device-service")}function deviceServiceEndpointPath(stateDir,platform=process.platform){return join9(stateDir,platform==="win32"?ENDPOINT_FILE:SOCKET_FILE)}async function connectDeviceService(options){let stateDir=options.stateDir??deviceServiceStateDir(),client=await(options.connect??connectLocalApi)({stateDir,client:{name:"omo",version:options.version}});return{serviceVersion:client.welcome.service_version,initialStatus:client.welcome.state,status:()=>client.request("status.get",{}),watchStatus:async(listener)=>{let stop=client.onEvent((event)=>{if(event.kind==="status.changed")listener(event.status)});try{await client.request("status.subscribe",{})}catch(error){throw stop(),error}return stop},setEnabled:async(enabled)=>(await client.request("service.set_enabled",{enabled})).enabled,registerRefresher:async(binaryPath,version)=>{await client.request("refresher.register",{binary_path:binaryPath,version})},adopt:async({device,signingPrivateKey,sealingPrivateKey})=>(await client.request("device.adopt",{device,signing_private_key:signingPrivateKey,sealing_private_key:sealingPrivateKey})).device,registerEndpoints:async(agentDir)=>{await client.request("endpoints.register",{agent_dir:agentDir})},forget:async()=>{await client.request("device.forget",{})},thisDevice:async()=>(await client.request("device.info",{})).device,devices:async()=>(await client.request("devices.list",{})).devices,sessions:(filter,onRevision)=>client.list(filter,onRevision),attach:(device,sessionId)=>openAttach(client,device,sessionId),close:()=>client.close(),closed:client.closed}}var STORE_UNAVAILABLE_EXITS=[8,9],isRecord7=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),text4=(value)=>typeof value==="string"&&value.length>0;function lastJsonLine(stdout){let line=stdout.trim().split(`
186
+ `).at(-1);if(line===void 0||line==="")return;try{return JSON.parse(line)}catch{return}}function classifyAccountShow(result){let value=lastJsonLine(result.stdout);if(result.exitCode===7&&isRecord7(value)&&value.keychain==="locked")return{kind:"keychain_locked"};if(STORE_UNAVAILABLE_EXITS.includes(result.exitCode))return{kind:"store_unavailable"};if(!isRecord7(value))return{kind:"account_unavailable",reason:"omo account show printed no JSON"};if(value.signedIn===!1)return{kind:"signed_out"};if(value.signedIn===!0&&result.exitCode===0){let device=value.device;if(isRecord7(device)&&text4(device.id)&&text4(device.name))return{kind:"signed_in",device:{id:device.id,name:device.name},refreshState:text4(value.refreshState)?value.refreshState:"ok"}}return{kind:"account_unavailable",reason:`omo account show answered an unexpected shape (exit ${result.exitCode})`}}function accountStateNotice(state){switch(state.kind){case"signed_in":return;case"signed_out":return"Sign in to OmO first: run omo login (or sign in from the OmO desktop app).";case"keychain_locked":return"Your OmO sign-in is behind a locked keychain. Unlock it, then try again.";case"store_unavailable":return"The credential store holding your OmO sign-in is not available right now. Try again in a moment.";case"account_unavailable":return`Could not read your OmO sign-in (${state.reason}). Sign in again with omo login.`}}var package_default={name:"omo-ai",version:"5.1.58",type:"module",description:"OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",bin:{omo:"bin/omo.js"},files:["bin","plugin"],engines:{node:">=24.0.0"},scripts:{postinstall:"node bin/senpi-patch.mjs"},dependencies:{"@code-yeongyu/senpi":"2026.11.2-1"},repository:{type:"git",url:"git+https://github.com/code-yeongyu/oh-my-openagent.git"}};import{createHash as createHash8,randomBytes as randomBytes5,randomUUID as randomUUID7,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{chmodSync as chmodSync3,mkdtempSync,rmSync as rmSync2,writeFileSync as writeFileSync3}from"node:fs";import{createServer as createServer3}from"node:net";import{tmpdir}from"node:os";import{join as join10,win32 as win322}from"node:path";var REMOTE_INPUT_OFF="remote input not enabled yet: this view is observe-only",SECRET_BYTES=32,HANDSHAKE_TIMEOUT_MS2=2000,MAX_LINE_CHARS=67108864,PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",LOCAL_SESSION_ID="remote",INPUT_COMMANDS=new Set(["prompt","steer","follow_up","abort","bash","compact","new_session","switch_session"]);function pipeAddress(socketPath,secret){let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret)]);return`${PIPE_PREFIX}${createHash8("sha256").update(identity).digest("hex").slice(0,32)}`}var isRecord8=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);function stateOf(snapshot){let state=isRecord8(snapshot.state)?snapshot.state:{};return{...state,sessionId:LOCAL_SESSION_ID,isStreaming:state.isStreaming===!0}}class Presentation{snapshot;streaming=!1;stopStream;attach;label;socket;constructor(attach,label,socket){this.attach=attach,this.label=label,this.socket=socket}startStream(){if(this.streaming)return;this.streaming=!0,this.notify(`Observing ${this.label}: ${REMOTE_INPUT_OFF}`,"info"),this.stopStream=this.attach.onEvent((event)=>this.event(event))}stop(){this.stopStream?.()}send(value){if(this.socket.writable&&!this.socket.destroyed)this.socket.write(`${JSON.stringify(value)}
187
187
  `)}event(event){switch(event.kind){case"snapshot":this.snapshot=event.snapshot;return;case"records":for(let record of event.records)this.send({...record,sessionId:LOCAL_SESSION_ID});return;case"pending":this.notify("Waiting for the remote device to share this session","info");return;case"detached":this.notify(`The remote session ended (${event.reason})`,"warning"),this.socket.end();return}}notify(message,notifyType){this.send({type:"extension_ui_request",id:randomUUID7(),method:"notify",message,notifyType,sessionId:LOCAL_SESSION_ID})}async answer(request){let type=String(request.type),reply=(data={})=>this.send({type:"response",id:request.id,command:type,success:!0,data}),refuse=(error)=>this.send({type:"response",id:request.id,command:type,success:!1,error});try{switch(type){case"set_client_info":case"attach_session":case"release_attachment":return reply();case"list_sessions":return reply({sessions:[{sessionId:LOCAL_SESSION_ID,durableSessionId:this.attach.sessionId,retain_on_disconnect:!0,sessionName:this.label}]});case"subscribe_sessions":return reply({subscriptionId:randomUUID7(),snapshot:[]}),this.startStream();case"get_state":{let snapshot=this.snapshot??await this.attach.snapshot;return this.snapshot=snapshot,reply(stateOf(snapshot))}case"get_entries":return reply(await this.entries(request));case"extension_ui_response":return refuse(REMOTE_INPUT_OFF);default:return refuse(INPUT_COMMANDS.has(type)?REMOTE_INPUT_OFF:`${type} is not available on a remote session`)}}catch(error){refuse(error instanceof Error?error.message:String(error))}}async entries(request){let before=typeof request.before==="string"?request.before:void 0,tail=typeof request.tail==="number"?Math.min(Math.max(Math.trunc(request.tail),1),200):void 0;if(before===void 0){let snapshot=this.snapshot??await this.attach.snapshot;this.snapshot=snapshot;let next=snapshot.history_truncated&&snapshot.oldest_entry_id!==null?{next_before:snapshot.oldest_entry_id}:{};return{entries:snapshot.entries,leafId:null,...next}}let page=await this.attach.read({before,...tail===void 0?{}:{tail}}),shown=page.entries.flatMap((entry)=>("entry"in entry)?[entry.entry]:[]),skipped=page.entries.length-shown.length;if(skipped>0)this.notify(`${skipped} older ${skipped===1?"entry is":"entries are"} too large to show`,"info");return{entries:shown,leafId:null,...page.next_before===null?{}:{next_before:page.next_before}}}}function authenticate(socket,secret,onAuthenticated){let received=Buffer.alloc(0),timer=setTimeout(()=>socket.destroy(),HANDSHAKE_TIMEOUT_MS2),onData=(chunk)=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(clearTimeout(timer),socket.off("data",onData),!timingSafeEqual3(received.subarray(0,secret.length),secret)){socket.destroy();return}let rest=received.subarray(secret.length);if(rest.length>0)socket.unshift(rest);onAuthenticated()};socket.on("data",onData),socket.once("close",()=>clearTimeout(timer))}function serveLines(socket,onLine){let buffer="";socket.setEncoding("utf8"),socket.on("data",(chunk)=>{if(buffer+=chunk,buffer.length>MAX_LINE_CHARS){socket.destroy();return}let newline=buffer.indexOf(`
188
188
  `);while(newline!==-1){let line=buffer.slice(0,newline).replace(/\r$/,"");if(buffer=buffer.slice(newline+1),line)onLine(line);newline=buffer.indexOf(`
189
189
  `)}})}async function serveRemoteAttach(attach,options={label:""}){let platform=options.platform??process.platform,dir=mkdtempSync(join10(options.parent??tmpdir(),"omo-ra-"));chmodSync3(dir,448);let socketPath=join10(dir,`t-${randomBytes5(8).toString("hex")}.sock`),secret=randomBytes5(SECRET_BYTES);writeFileSync3(`${socketPath}.secret`,secret,{mode:384});let sockets=new Set,server=createServer3((socket)=>{sockets.add(socket),socket.once("close",()=>sockets.delete(socket)),socket.once("error",()=>socket.destroy()),authenticate(socket,secret,()=>{let presentation=new Presentation(attach,options.label,socket);socket.once("close",()=>presentation.stop()),serveLines(socket,(line)=>{let request;try{request=JSON.parse(line)}catch{socket.destroy();return}if(isRecord8(request))presentation.answer(request)})})}),address=platform==="win32"?pipeAddress(socketPath,secret):socketPath;await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(address,()=>{server.off("error",reject),resolve()})});let removeDir=()=>rmSync2(dir,{recursive:!0,force:!0});process.once("exit",removeDir);let closing,close=()=>closing??=new Promise((resolve)=>{for(let socket of sockets)socket.destroy();server.close(()=>{process.off("exit",removeDir),removeDir(),resolve()})});return attach.detached.then(()=>{for(let socket of sockets)socket.end()}),{socketPath,sessionRef:attach.sessionId,close}}var REMOTE_EXIT={ok:0,failed:1,usage:2,unavailable:3},REMOTE_USAGE=`usage: omo remote <command> [--json]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omo-ai",
3
- "version": "5.1.57",
3
+ "version": "5.1.58",
4
4
  "type": "module",
5
5
  "description": "OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",
6
6
  "bin": {
@@ -17,7 +17,7 @@
17
17
  "postinstall": "node bin/senpi-patch.mjs"
18
18
  },
19
19
  "dependencies": {
20
- "@code-yeongyu/senpi": "2026.10.31-2"
20
+ "@code-yeongyu/senpi": "2026.11.2-1"
21
21
  },
22
22
  "repository": {
23
23
  "type": "git",
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [5.1.58] - 2026-11-02
11
+
12
+ Runs on senpi 2026.11.2-1: Claude subscription sign-in works again. ([#12126](https://github.com/code-yeongyu/oh-my-openagent/pull/12126))
13
+
14
+ **A timed-out or cancelled ultimate-browsing template gives its browser a graceful quit.** On macOS/Linux the executor runs each Playwright template in its own session and, on timeout or cancellation (Ctrl-C), sends SIGTERM to the template's process group and waits up to 5 s before SIGKILL, so Chrome can quit cleanly and remove its macOS code-sign clone and temp profile instead of being orphaned. The bundled omowright browser engine is pinned at the release whose pipe-launched browsers also get a graceful quit (SIGTERM, then SIGKILL after a grace period) when the engine closes them. ([#12068](https://github.com/code-yeongyu/oh-my-openagent/pull/12068))
15
+
16
+ ### Fixed
17
+
18
+ - The builtin `dev-browser` skill's macOS/Linux standalone command now runs a release step before `server.sh`. When nothing answers on 9222, it sends SIGTERM to whatever holds 9223, waits up to 5 s, and sends SIGKILL only to survivors. dev-browser's `start-server.ts` then finds the port free and never reaches its `kill -9`, so a browser gets its clean exit and does not leak per-launch state such as the macOS Chrome code-sign clone. A running server on 9222 is left alone, and the step does nothing when `curl` or `lsof` is missing. It works the same under bash and zsh. The upstream fix is SawyerHood/dev-browser#146. ([#12071](https://github.com/code-yeongyu/oh-my-openagent/pull/12071), part of [#12067](https://github.com/code-yeongyu/oh-my-openagent/issues/12067))
19
+ - A delegated task now runs only on the models designated for it (its category's or agent's model chain). It never falls back to the parent session's model, whatever the failure: a usage limit, a missing or rejected sign-in, a content-policy refusal or an overload on every designated model ends the task with `failure_kind: "model_chain_exhausted"` and an error listing each model it tried and why, including any reset time the provider reported. This applies to every category and to workflow nodes. A `categories.<name>.provider_lock` key left in `omo.json` is ignored. ([#12006](https://github.com/code-yeongyu/oh-my-openagent/issues/12006), [#11781](https://github.com/code-yeongyu/oh-my-openagent/issues/11781)) ([#12010](https://github.com/code-yeongyu/oh-my-openagent/pull/12010))
20
+ - Keep an unacknowledged task-host session close reachable by teardown so detaching
21
+ releases its transport instead of leaving the connection open until the RPC deadline. ([#11931](https://github.com/code-yeongyu/oh-my-openagent/pull/11931))
22
+
23
+ ### Changed
24
+
25
+ - The macOS (darwin-arm64) EQ.omo goldens for E21-E24 are re-recorded against senpi 2026.10.31-2, and recording now refuses a golden that carries a host-only notice or terminal event, so a machine-specific row can no longer be committed as the expected output. ([#12056](https://github.com/code-yeongyu/oh-my-openagent/pull/12056), fixes [#12054](https://github.com/code-yeongyu/oh-my-openagent/issues/12054))
26
+
27
+ ### Added
28
+
29
+ - The device service SDK (`@oh-my-opencode/device-service-core`) can download, verify and install the OmO device service and run its start-up bootstrap: the release signature is checked with the repository's strict Ed25519 helper against a compiled-in release key, every file against the signed checksums, and the release lands in the service's state dir only after every check passed. Nothing calls it yet, and the release key is a placeholder until it is published. ([#12052](https://github.com/code-yeongyu/oh-my-openagent/pull/12052))
30
+
10
31
  ## [5.1.57] - 2026-11-01
11
32
 
12
33
  Runs on senpi 2026.10.31-2: Claude subscription sign-in now goes through the Claude Code CLI (accounts from the old sign-in are asked once to sign in again, keeping their name, pin and order), `/gpt-account unblock <id>` clears a usage-limit block after you reset it on the provider side, a finished turn no longer sits at "Working" while an extension's settle handler is slow, and startup warns when a skills root's ignore file hides a skill folder. A Claude OAuth token given to the plain `anthropic` provider is now refused with a pointer at `/login anthropic-subscription` instead of being sent as Claude Code, so omo no longer rewrites the engine's Claude Code version at install; every skill a prompt invokes now loads instead of stopping at five. ([#11983](https://github.com/code-yeongyu/oh-my-openagent/pull/11983))