omo-ai 5.1.63 → 5.1.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/darwin/omo-keychain +0 -0
- package/bin/lib/engine-boot.js +27 -0
- package/bin/lib/launcher.js +23 -0
- package/bin/lib/memory-sync-boot.js +19 -0
- package/bin/lib/service-auth.generated.js +1 -1
- package/package.json +1 -1
- package/plugin/CHANGELOG.md +32 -0
- package/plugin/extensions/gateway-store-worker.mjs +2 -2
- package/plugin/extensions/memory-run-supervisor.mjs +1 -1
- package/plugin/extensions/omo-claim-receipt.js +1 -1
- package/plugin/extensions/omo-computer-use.js +1 -1
- package/plugin/extensions/omo-desktop-toolkit.js +1 -1
- package/plugin/extensions/omo-device-account.js +2 -2
- package/plugin/extensions/omo-device-service.js +2 -2
- package/plugin/extensions/omo-feedback.js +2 -2
- package/plugin/extensions/omo-init-deep-advisor.js +1 -1
- package/plugin/extensions/omo-member.js +1 -1
- package/plugin/extensions/omo-memory-commands.js +3 -3
- package/plugin/extensions/omo-memory-doctor.js +3 -3
- package/plugin/extensions/omo-memory-memfs.js +3 -3
- package/plugin/extensions/omo-memory-palace.js +3 -3
- package/plugin/extensions/omo-memory-sync.js +2 -2
- package/plugin/extensions/omo-onboarding-scan.js +3 -3
- package/plugin/extensions/omo-recall-store.js +1 -1
- package/plugin/extensions/omo-session-history.js +1 -1
- package/plugin/extensions/omo-side-panel.js +1 -1
- package/plugin/extensions/omo-task.js +1 -1
- package/plugin/extensions/omo-telemetry-otlp.js +1 -1
- package/plugin/extensions/omo-telemetry-posthog.js +1 -1
- package/plugin/extensions/omo-telemetry-recovery.js +1 -1
- package/plugin/extensions/omo-thread-client.js +1 -1
- package/plugin/extensions/omo.js +3 -3
- package/plugin/package.json +1 -1
- package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
- package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
- package/plugin/runtime/bunshin-ts/sdk.js +2 -2
- package/plugin/runtime/rollback-migrate.js +1 -1
- package/plugin/runtime/thread-sdk/sdk.js +2 -2
- package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
package/bin/darwin/omo-keychain
CHANGED
|
Binary file
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The npm launcher's engine entry for a launch that claims memory sync at boot (#11997, memory-sync-boot.js):
|
|
2
|
+
// argv is `<runtime> engine-boot.js <senpi cli> ...engine args`. It drops its own path so the engine sees the argv
|
|
3
|
+
// it always has, starts the claim, then runs senpi's CLI in this process. It follows the entry contract in omo-senpi
|
|
4
|
+
// desktop-sync/bootClaim.ts with the engine's own modules: cwd guard, filler release, gate, then the capture and claim.
|
|
5
|
+
import { basename, dirname, join } from "node:path"
|
|
6
|
+
import { pathToFileURL } from "node:url"
|
|
7
|
+
import { launchClaimsMemorySyncAtBoot } from "./memory-sync-boot.js"
|
|
8
|
+
import { packageRoot } from "./package-paths.js"
|
|
9
|
+
|
|
10
|
+
const cliPath = process.argv[2]
|
|
11
|
+
process.argv.splice(1, 1)
|
|
12
|
+
// The engine ships its CLI pre-bundled under dist/bundle and every module unbundled under dist.
|
|
13
|
+
const distDir = basename(dirname(cliPath)) === "bundle" ? dirname(dirname(cliPath)) : dirname(cliPath)
|
|
14
|
+
const moduleUrl = (path) => pathToFileURL(path).href
|
|
15
|
+
try {
|
|
16
|
+
await import(moduleUrl(join(distDir, "valid-cwd.js")))
|
|
17
|
+
await import(moduleUrl(join(distDir, "private-fd-startup-release.js")))
|
|
18
|
+
const sidecar = await import(moduleUrl(join(packageRoot, "plugin", "extensions", "omo-device-account.js")))
|
|
19
|
+
if (launchClaimsMemorySyncAtBoot(process.argv.slice(2), process.env, sidecar.claimsMemorySyncAtBoot)) {
|
|
20
|
+
const { takeInheritedPrivateChannel } = await import(moduleUrl(join(distDir, "private-fds.js")))
|
|
21
|
+
sidecar.claimMemorySyncAtBoot(takeInheritedPrivateChannel)
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
// The memory component's registration still selects once when the first session opens.
|
|
25
|
+
process.stderr.write(`omo: memory sync could not start at boot: ${error instanceof Error ? error.message : String(error)}\n`)
|
|
26
|
+
}
|
|
27
|
+
await import(moduleUrl(cliPath))
|
package/bin/lib/launcher.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process"
|
|
2
2
|
import { existsSync } from "node:fs"
|
|
3
3
|
import { join } from "node:path"
|
|
4
|
+
import { pathToFileURL } from "node:url"
|
|
4
5
|
import { isEngineCommand } from "./engine-commands.js"
|
|
5
6
|
import { spawnNode } from "./child-process.js"
|
|
6
7
|
import { privateFdHandoff } from "./private-fds.js"
|
|
8
|
+
import { launchClaimsMemorySyncAtBoot } from "./memory-sync-boot.js"
|
|
7
9
|
import { doctorCoverageLines } from "./category-coverage.js"
|
|
8
10
|
import { runDoctorModels } from "./model-chains.js"
|
|
9
11
|
import { doctorComputerUseLines } from "./computer-use-doctor.js"
|
|
@@ -46,6 +48,23 @@ function preparedSenpi() {
|
|
|
46
48
|
return senpi
|
|
47
49
|
}
|
|
48
50
|
|
|
51
|
+
// A memory-sync launch reaches the engine through this entry, which claims before senpi's CLI loads (#11997).
|
|
52
|
+
const ENGINE_BOOT_ENTRY = join(packageRoot, "bin", "lib", "engine-boot.js")
|
|
53
|
+
const DEVICE_ACCOUNT_SIDECAR = join(packageRoot, "plugin", "extensions", "omo-device-account.js")
|
|
54
|
+
|
|
55
|
+
/** Whether a launch that hands down a private-descriptor table claims memory sync at boot (the sidecar's gate). */
|
|
56
|
+
async function bootsWithMemorySyncClaim(args, env) {
|
|
57
|
+
try {
|
|
58
|
+
const { claimsMemorySyncAtBoot } = await import(pathToFileURL(DEVICE_ACCOUNT_SIDECAR).href)
|
|
59
|
+
// spawnNode starts the engine entry on this runtime without exec arguments; engine-boot.js checks again in-process.
|
|
60
|
+
return launchClaimsMemorySyncAtBoot(args, env, claimsMemorySyncAtBoot, { execArgv: [], versions: process.versions })
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// Without the sidecar the memory component's registration still selects once when the first session opens.
|
|
63
|
+
process.stderr.write(`omo: memory sync could not start at boot: ${error instanceof Error ? error.message : String(error)}\n`)
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
49
68
|
async function spawnSenpi(args, withExtension) {
|
|
50
69
|
const senpi = preparedSenpi()
|
|
51
70
|
const finalArgs = withExtension
|
|
@@ -62,6 +81,10 @@ async function spawnSenpi(args, withExtension) {
|
|
|
62
81
|
// A failed replacement still uses the signal-aware child path below.
|
|
63
82
|
}
|
|
64
83
|
}
|
|
84
|
+
if (handoff !== undefined && await bootsWithMemorySyncClaim(finalArgs, handoff.env)) {
|
|
85
|
+
await spawnNode(ENGINE_BOOT_ENTRY, [senpi.cliPath, ...finalArgs], handoff)
|
|
86
|
+
return
|
|
87
|
+
}
|
|
65
88
|
await spawnNode(senpi.cliPath, finalArgs, handoff ?? { env })
|
|
66
89
|
}
|
|
67
90
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { isEngineCommand } from "./engine-commands.js"
|
|
2
|
+
|
|
3
|
+
// #11997: a `--mode rpc` engine whose launch carried a private-descriptor table naming memory-sync starts that claim
|
|
4
|
+
// before senpi's CLI loads, because a multi-session host (what `host ensure` starts) loads extensions only when a
|
|
5
|
+
// session opens, and the desktop opens none before it has answered the claim's bootstrap frame. The launch rules are
|
|
6
|
+
// the device-account sidecar's `claimsMemorySyncAtBoot` (omo-senpi desktop-sync/bootGate.ts), which every entry, the
|
|
7
|
+
// desktop's included, calls; each omo entry passes it in from where it loads omo-senpi. omo adds only its own one-shot
|
|
8
|
+
// engine commands on top.
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Whether this omo launch should claim memory sync at boot: not an omo one-shot engine command, and the shared gate.
|
|
12
|
+
* @param {readonly string[]} args
|
|
13
|
+
* @param {Readonly<Record<string, string | undefined>>} env
|
|
14
|
+
* @param {(args: readonly string[], env?: Readonly<Record<string, string | undefined>>, runtime?: { readonly execArgv: readonly string[], readonly versions: { readonly bun?: string | undefined } }) => boolean} claimsMemorySyncAtBoot
|
|
15
|
+
* @param {{ readonly execArgv: readonly string[], readonly versions: { readonly bun?: string | undefined } }} [runtime]
|
|
16
|
+
*/
|
|
17
|
+
export function launchClaimsMemorySyncAtBoot(args, env, claimsMemorySyncAtBoot, runtime = process) {
|
|
18
|
+
return !isEngineCommand(args) && claimsMemorySyncAtBoot(args, env, runtime)
|
|
19
|
+
}
|
|
@@ -196,7 +196,7 @@ $ErrorActionPreference = 'Stop'
|
|
|
196
196
|
`,CURRENT_USER_SID_SCRIPT="[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",ACE_TYPES=new Set(["A","D","OA","OD","AU","AL","OU","OL","ML","XA","XD","ZA","XU","SP","RA","SD","CA"]),DACL_FLAG=/^(?:P|AI|AR|NO_ACCESS_CONTROL)/,SID_TOKEN=/^(?:S-1-\d+(?:-\d+)+|[A-Z]{2})$/,aceEnd=(text,start)=>{let depth=0;for(let i=start;i<text.length;i+=1)if(text[i]==='"'){if(depth<2)return;let close=text.indexOf('"',i+1);if(close===-1)return;i=close}else if(text[i]==="(")depth+=1;else if(text[i]===")"){if(depth-=1,depth===0)return i}return},GUID_FIELD=/^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})?$/,parseAce=(body)=>{let parts=body.split(";");if(parts.length<6)return;let[type="",flags="",rights="",objectGuid="",inheritObjectGuid="",sid=""]=parts,extra=parts.length>6?parts.slice(6).join(";"):void 0;if(!ACE_TYPES.has(type)||!SID_TOKEN.test(sid))return;if(!/^[A-Z]*$/.test(flags)||!/^(?:[A-Z]+|0x[0-9a-fA-F]+)?$/.test(rights))return;if(extra===void 0&&parts.length!==6)return;if(!GUID_FIELD.test(objectGuid)||!GUID_FIELD.test(inheritObjectGuid))return;return{type,flags,rights,objectGuid,inheritObjectGuid,sid,extra}},parseSddl=(sddl)=>{let head=/^O:(S-1-\d+(?:-\d+)+|[A-Z]{2})D:/.exec(sddl);if(head===null)return;let owner=head[1]??"",rest=sddl.slice(head[0].length),tokens=[];for(let flag=DACL_FLAG.exec(rest);flag!==null;flag=DACL_FLAG.exec(rest))tokens.push(flag[0]),rest=rest.slice(flag[0].length);let aces=[];while(rest.length>0){if(!rest.startsWith("("))return;let close=aceEnd(rest,0);if(close===void 0)return;let ace=parseAce(rest.slice(1,close));if(ace===void 0)return;aces.push(ace),rest=rest.slice(close+1)}return{sddl,owner,protected:tokens.includes("P"),flags:tokens.join(""),aces}},exactDaclVerdict=(dacl,userSid,kind,userAlias)=>{let isUser=(token)=>token===userSid||userAlias!==void 0&&token===userAlias,[ace,...others]=dacl.aces;return isUser(dacl.owner)&&dacl.flags==="PAI"&&ace!==void 0&&others.length===0&&ace.type==="A"&&ace.flags===(kind==="dir"?"OICI":"")&&ace.rights==="FA"&&ace.objectGuid===""&&ace.inheritObjectGuid===""&&isUser(ace.sid)&&ace.extra===void 0},currentUserSid=async(run=runPowerShell)=>{let{code,out}=await run(CURRENT_USER_SID_SCRIPT,{}),sid=out.trim();if(code!==0||!/^S-1-[0-9-]+$/.test(sid))throw new LocalApiError("insecure_state_dir","the user SID is unreadable");return sid},userSidToken=async(userSid,run=runPowerShell)=>{let{code,out}=await run(SID_TOKEN_SCRIPT,{LA_SID:userSid});return(code===0?/^O:(S-1-\d+(?:-\d+)+|[A-Z]{2})$/.exec(out.trim()):null)?.[1]},applyExactDacl=async(path,userSid,kind,run=runPowerShell)=>{let{code,err}=await run(APPLY,{LA_PATH:path,LA_SID:userSid,LA_KIND:kind});if(code!==0)throw new LocalApiError("insecure_state_dir",`the exact DACL could not be applied${firstErrorLine(err)}`)},describeDacl=async(path,run=runPowerShell)=>{let{code,out}=await run(DESCRIBE_DACL_SCRIPT,{LA_PATH:path}),dacl=code===0?parseSddl(out.trim()):void 0;if(dacl===void 0)throw new LocalApiError("insecure_state_dir","the DACL could not be read back");return dacl},verifyExactDacl=async(path,userSid,kind,run=runPowerShell)=>{let dacl;try{dacl=await describeDacl(path,run)}catch(error){if(error instanceof LocalApiError)return!1;throw error}return exactDaclVerdict(dacl,userSid,kind,await userSidToken(userSid,run))},windowsSecureFile=(userSid,run=runPowerShell)=>async(path,kind)=>{let target=kind==="dir"?"dir":"file";if(await applyExactDacl(path,userSid,target,run),!await verifyExactDacl(path,userSid,target,run))throw new LocalApiError("insecure_state_dir","the DACL is not exactly one ACE for the user")};var TOKEN_FILE="token",TOKEN_BYTES=32,NONCE_BYTES=32,SOCKET_FILE="service.sock",base64url3=(bytes)=>Buffer.from(bytes).toString("base64url"),mintNonce=()=>base64url3(randomBytes5(NONCE_BYTES)),mintId=()=>base64url3(randomBytes5(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(join14(stateDir,SOCKET_FILE),"socket",uid),privateEntry(join14(stateDir,TOKEN_FILE),"file",uid)},posixSecureFile=async(path,kind)=>{let uid=currentUid();privateEntry(path,kind,uid,!1),chmodSync2(path,kind==="dir"?448:384),privateEntry(path,kind,uid)},readToken=(stateDir)=>{let value;try{value=readFileSync2(join14(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_DEVICE_MAX_CHARS=64,SESSION_PROJECT_MAX_CHARS=256,SESSION_ID_MAX_CHARS=128,SESSION_KIND_MAX_CHARS=32,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 as posix3,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","control"],OPTIONAL_CAPABILITIES=["machine"],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","session_closed","session_replaced"],ATTACH_PENDING_REASONS=["stream_key_pending"],COMMAND_ID_CHARS=22,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","lease_expired","cancelled","hand_restarted","result_expired","record_too_large"],COMMAND_REFUSAL_REASONS=["parts_conflict","peer_unauthorized","message_too_long","engine_capability_missing","malformed","method_unclassified","method_local_only","capability_missing","schema_stale","tool_unknown","cancelled","hand_restarted","scope_unknown","scope_closed","epoch_fenced","epoch_step_exceeded"],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","malformed","method_unclassified","method_local_only","host_not_answering","unsupported"];var PATH_REFUSAL_PROBLEMS=["not_absolute","not_found","not_regular_file","not_executable","foreign_owner","group_writable","world_writable","windows_acl"],CHANNEL_CLOSED_REASONS=["event_overflow","event_too_large","idle","engine_closed","event_lost","event_gap"];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")&&(posix3.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"],ROW_KIND=new RegExp(`^[a-z][a-z0-9_-]{0,${SESSION_KIND_MAX_CHARS-1}}$`),rowLinks=(m)=>{let kind=m.kind;if(Object.hasOwn(m,"parent")!==Object.hasOwn(m,"parent_listed"))fail("parent_listed");return{...kind===void 0?{}:{kind:typeof kind==="string"&&ROW_KIND.test(kind)?kind:fail("row kind")},...m.parent===void 0?{}:{parent:sessionId(m.parent),parent_listed:bool(m.parent_listed,"parent_listed")}}},listingRowOf=(v)=>{let m=exactly(v,ROW_FIELDS,["kind","parent","parent_listed"],"listing row");return{...rowLinks(m),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")}},pathRefusalOf=(v)=>{let m=exactly(v,["component","problem"],[],"error.path_refusal");return{component:text3(m.component,PATH_MAX_CHARS,"error.path_refusal.component"),problem:oneOf(PATH_REFUSAL_PROBLEMS,m.problem,"error.path_refusal.problem")}},errorBodyOf=(v)=>{let m=exactly(v,["code","reason","action"],["limit_chars","path_refusal"],"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");let refusal=m.path_refusal;if(refusal!==void 0&&code!=="forbidden")return fail("error.path_refusal");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")},...refusal===void 0?{}:{path_refusal:pathRefusalOf(refusal)}}};var commandRpcOf=(v)=>jsonObject(v,"rpc"),requestFields=(v,names,optional=[])=>exactly(v,["id","type",...names],optional,"request"),commandIdField=(v)=>v===void 0?{}:{command_id:commandId(v)},ROUTE_FIELDS=["command_id","delegated","endpoint"],routeFields=(m)=>{let delegated=m.delegated;if(delegated!==void 0&&delegated!==!0)return fail("delegated");return{...delegated===!0?{delegated:!0}:{},...m.endpoint===void 0?{}:{endpoint:endpointKey(m.endpoint)}}},COMMAND_REQUEST_VALIDATORS={"session.command":(v,id)=>{if(Object.hasOwn(v,"device")){let m=requestFields(v,["device","endpoint","rpc"],["command_id"]);return{id,type:"session.command",device:deviceId(m.device),endpoint:endpointKey(m.endpoint),...commandIdField(m.command_id),rpc:commandRpcOf(m.rpc)}}if(Object.hasOwn(v,"upload_id")){let m=requestFields(v,["attach","upload_id"],ROUTE_FIELDS);return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),upload_id:localId(m.upload_id,"upload_id"),...routeFields(m)}}let m=requestFields(v,["attach","rpc"],ROUTE_FIELDS);return{id,type:"session.command",attach:localId(m.attach,"attach"),...commandIdField(m.command_id),rpc:commandRpcOf(m.rpc),...routeFields(m)}},"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 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 ENDPOINT_KEY=/^[A-Za-z0-9_-]{22}$/,ENDPOINTS_MAX=16,endpointKey=(v,what="endpoint")=>typeof v==="string"&&ENDPOINT_KEY.test(v)?v:fail(what),ENGINE_ID_MAX_CHARS=128,engineId=(v)=>typeof v==="string"&&v.length>=1&&v.length<=ENGINE_ID_MAX_CHARS&&v.isWellFormed()?v:fail("engine_id"),DELEGATED_REQUEST_VALIDATORS={"session.endpoints":(v,id)=>({id,type:"session.endpoints",device:deviceId(requestFields(v,["device"]).device)}),"session.locate":(v,id)=>{let m=requestFields(v,["device","engine_id"]);return{id,type:"session.locate",device:deviceId(m.device),engine_id:engineId(m.engine_id)}}},locateData=(v)=>{let m=exactly(v,["device","key","session"],[],"data"),device=deviceId(m.device),key=endpointKey(m.key,"key");return m.session===`${device}.${key}`?{device,key,session:`${device}.${key}`}:fail("session")},endpointsData=(v)=>{let endpoints=exactly(v,["endpoints"],[],"data").endpoints;if(!Array.isArray(endpoints)||endpoints.length>ENDPOINTS_MAX)return fail("endpoints");let keys=endpoints.map((e)=>endpointKey(e,"endpoints"));return new Set(keys).size===keys.length?{endpoints:keys}:fail("endpoints")},blobId=(m)=>localId(m.id,"blob id"),blobRefOf=(v)=>{let m=exactly(v,["id","bytes","sha256"],[],"blob");return{id:blobId(m),bytes:uint(m.bytes,1,LOCAL_BLOB_MAX,"blob bytes"),sha256:sha256Field(m.sha256,"blob sha256")}},commandEventOf=(v)=>{let head={type:"event",kind:"session.command_event"};if(Object.hasOwn(v,"blob")){let m=eventFields(v,["device","blob"]);return{...head,device:deviceId(m.device),blob:blobRefOf(m.blob)}}if(lineBytes(v)>LOCAL_INLINE_MAX)return fail("an inline command event over LOCAL_INLINE_MAX is a blob");if(Object.hasOwn(v,"frame")){let m=eventFields(v,["device","frame"]);return{...head,device:deviceId(m.device),frame:jsonObject(m.frame,"frame")}}let m=eventFields(v,["device","command_id","response"]);return{...head,device:deviceId(m.device),command_id:commandId(m.command_id),response:jsonObject(m.response,"response")}},DELEGATED_EVENT_VALIDATORS={"session.command_event":commandEventOf,"session.command_blob_chunk":(v)=>{let m=eventFields(v,["id","off","b"]);return base64Bytes(m.b,LOCAL_CHUNK_MAX,"blob chunk"),{type:"event",kind:"session.command_blob_chunk",id:blobId(m),off:uint(m.off,0,LOCAL_BLOB_MAX,"blob off"),b:typeof m.b==="string"?m.b:fail("blob chunk")}},"session.command_blob_done":(v)=>({type:"event",kind:"session.command_blob_done",id:blobId(eventFields(v,["id"]))}),"session.channel_closed":(v)=>{let m=eventFields(v,["device","reason"]);return{type:"event",kind:"session.channel_closed",device:deviceId(m.device),reason:oneOf(CHANNEL_CLOSED_REASONS,m.reason,"channel closed 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,...DELEGATED_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 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,...DELEGATED_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"}),"control.attach.get":(v,id)=>(bare(v),{id,type:"control.attach.get"}),"control.attach.set":(v,id)=>{let attached=bool(requestFields(v,["attached"]).attached,"attached");return{id,type:"control.attach.set",attached}},"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,rows}=requestFields(v,[],["filter","rows"]);if(rows!==void 0&&rows!==2)return fail("rows");return{id,type:"sessions.list",...filter===void 0?{}:{filter:filterOf(filter)},...rows===void 0?{}:{rows}}},"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,...OPTIONAL_CAPABILITIES],c,"capability")),state:statusOf(m.state)}});var empty=(v)=>(exactly(v,[],[],"data"),{}),one=(v,name)=>exactly(v,[name],[],"data")[name],attachState=(v)=>{let m=exactly(v,["attached","changedAt"],[],"data"),changedAt=m.changedAt;return{attached:bool(m.attached,"attached"),changedAt:typeof changedAt==="string"?changedAt:fail("changedAt")}},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,"session.endpoints":endpointsData,"session.locate":locateData,"control.attach.get":attachState,"control.attach.set":attachState},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":case"session.command_event":case"session.command_blob_chunk":case"session.command_blob_done":case"session.channel_closed":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,path_refusal}=response.error;reject(new LocalApiError(code,reason,{action,...limit_chars===void 0?{}:{limit_chars},...path_refusal===void 0?{}:{path_refusal}}));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 join15}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(join15(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,options={})=>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:join15(stateDir,SOCKET_FILE)}):createConnection({host:"127.0.0.1",port});if(options.background===!0)socket.unref();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,rpc,command_id,route)=>{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},draft={id:"x".repeat(REQUEST_ID_MAX_CHARS),type:"session.command",attach,...id,...route,rpc};if(lineBytes(draft)>LOCAL_INLINE_MAX){let json=JSON.stringify(rpc);if(checkCommandText(json)==="message_too_long")throw new LocalApiError("message_too_long","the command is over the engine limit",{limit_chars:MESSAGE_LIMIT_CHARS});let upload_id=mintId(),parts=uploadParts(json).map((part)=>connection.request("session.command_part",{attach,upload_id,...part}));return await Promise.all(parts),(await connection.request("session.command",{attach,...id,...route,upload_id}).catch(timedOut)).command_id}return(await connection.request("session.command",{attach,...id,...route,rpc}).catch(timedOut)).command_id},sendEndpointCommand=async(connection,device,endpoint,rpc,command_id)=>{let sent=command_id??mintId(),params={device,endpoint,command_id:sent,rpc};if(lineBytes({id:"x".repeat(REQUEST_ID_MAX_CHARS),type:"session.command",...params})>LOCAL_INLINE_MAX)throw new LocalApiError("message_too_long","an endpoint command travels inline only",{limit_chars:MESSAGE_LIMIT_CHARS});try{return(await connection.request("session.command",params)).command_id}catch(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}},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,rpc,command_id,route={})=>sendCommand(connection,attach,rpc,command_id,route),endpointCommand:(device,endpoint,rpc,command_id)=>sendEndpointCommand(connection,device,endpoint,rpc,command_id),list:(filter,onRevision,rows)=>new Promise((resolve,reject)=>{let params={...filter===void 0?{}:{filter},...rows===void 0?{}:{rows}},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}};import{randomBytes as randomBytes6}from"node:crypto";import{createHash as createHash8}from"node:crypto";var isObject3=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);function followDelegatedChannel(device){let replies=new Map,frames=new Set,losses=new Set,blobs=new Map,lost=(reason)=>{for(let listener of[...losses])listener(reason)},body=(value)=>{if(!isObject3(value))return lost("a command event that is not an object");let frame=value.frame;if(isObject3(frame)){for(let listener of[...frames])listener(frame);return}let{command_id:commandId,response}=value;if(typeof commandId==="string"&&isObject3(response))replies.set(commandId,response);else lost("a command event with neither a frame nor a reply")};return{takeReply:(commandId)=>{let reply=replies.get(commandId);return replies.delete(commandId),reply},onFrame:(listener)=>(frames.add(listener),()=>frames.delete(listener)),onLoss:(listener)=>(losses.add(listener),()=>losses.delete(listener)),accept:(event)=>{switch(event.kind){case"session.command_event":if(event.device!==device)return;if("blob"in event)blobs.set(event.blob.id,{ref:event.blob,parts:[],received:0});else body(event);return;case"session.command_blob_chunk":{let blob=blobs.get(event.id);if(blob===void 0)return;let bytes=Buffer.from(event.b,"base64");if(event.off!==blob.received||blob.received+bytes.length>blob.ref.bytes)return blobs.delete(event.id),lost("a command event blob arrived out of order or over its length");blob.parts.push(bytes),blob.received+=bytes.length;return}case"session.command_blob_done":{let blob=blobs.get(event.id);if(blob===void 0)return;blobs.delete(event.id);let bytes=Buffer.concat(blob.parts);if(bytes.length!==blob.ref.bytes||createHash8("sha256").update(bytes).digest("hex")!==blob.ref.sha256)return lost("a command event blob failed its length or sha256 check");let parsed;try{parsed=JSON.parse(bytes.toString("utf8"))}catch{return lost("a command event blob is not JSON")}return body(parsed)}case"session.channel_closed":if(event.device!==device)return;return blobs.clear(),lost(`the delegated channel closed (${event.reason})`);default:return}},stop:()=>{frames.clear(),losses.clear(),blobs.clear(),replies.clear()}}}var attachEvent=(event)=>{switch(event.kind){case"session.snapshot":case"session.records":case"session.attach_pending":case"session.detached":return event;default:return}},ENDED_COMMAND_WAIT_MS=30000,PROGRESS_STATES=new Set(["queued","transport_confirmed","engine_dispatched"]),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,commands=new Set,channel,drain,released=!1,release=()=>{if(released)return;released=!0,clearTimeout(drain),stop(),channel?.stop()},endCommands=(reason)=>{for(let end of[...commands])end(reason);release()},finish=(reason)=>{if(ended)return;if(ended=!0,listeners.clear(),rejectSnapshot(Error(`the attach ended before its snapshot: ${reason}`)),resolveDetached(reason),reason==="closed"||commands.size===0)return endCommands(reason);drain=setTimeout(()=>endCommands(reason),ENDED_COMMAND_WAIT_MS),drain.unref?.()},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)=>{channel?.accept(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"),endCommands("closed")}),client.request("session.attach",{device,session_id:sessionId}).then(({attach})=>{handle=attach;let delegated=followDelegatedChannel(device);if(channel=delegated,ended)delegated.stop();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,onFrame:(listener)=>delegated.onFrame(listener),onChannelLoss:(listener)=>delegated.onLoss(listener),command:(rpc)=>new Promise((resolve,reject)=>{if(ended)return reject(Error("the attach has ended"));let commandId=randomBytes6(16).toString("base64url"),settle=()=>{if(stopState(),commands.delete(end),ended&&commands.size===0)release()},end=(reason)=>{settle(),reject(Error(`the attach ended before the command settled: ${reason}`))},stopState=client.onEvent((event)=>{if(event.kind!=="session.command_state"||event.command_id!==commandId)return;if(PROGRESS_STATES.has(event.state))return;let response=delegated.takeReply(commandId);settle(),resolve(response===void 0?{outcome:event}:{outcome:event,response})});commands.add(end),client.command(attach,rpc,commandId,{delegated:!0}).catch((error)=>{settle(),reject(error)})}),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})}import{randomBytes as randomBytes7}from"node:crypto";var ENDPOINT_COMMAND_WAIT_MS=120000;function sendToEndpoint(client,device,endpoint,rpc){return new Promise((resolve,reject)=>{let commandId=randomBytes7(16).toString("base64url"),channel=followDelegatedChannel(device),done=!1,settle=()=>{done=!0,stop(),channel.stop(),clearTimeout(timer)},fail=(error)=>{if(done)return;settle(),reject(error)},stop=client.onEvent((event)=>{if(channel.accept(event),done||event.kind!=="session.command_state"||event.command_id!==commandId)return;if(PROGRESS_STATES.has(event.state))return;let response=channel.takeReply(commandId);settle(),resolve(response===void 0?{outcome:event}:{outcome:event,response})}),timer=setTimeout(()=>fail(Error(`no final state for endpoint command ${commandId} within ${ENDPOINT_COMMAND_WAIT_MS} ms`)),ENDPOINT_COMMAND_WAIT_MS);timer.unref?.(),client.closed.then(()=>fail(Error("the connection closed before the endpoint command settled"))),client.endpointCommand(device,endpoint,rpc,commandId).catch(fail)})}var markNotSent=(error)=>error instanceof LocalApiError?new LocalApiError(error.code,error.reason,{action:error.action,...error.limit_chars===void 0?{}:{limit_chars:error.limit_chars},...error.path_refusal===void 0?{}:{path_refusal:error.path_refusal},not_sent:!0}):error;function deviceServiceStateDir(platform=process.platform,env=process.env,home=homedir6()){if(platform!=="win32")return join16(home,".omo","device-service");let localAppData=env.LOCALAPPDATA??join16(home,"AppData","Local");return join16(localAppData,"OmO","device-service")}function deviceServiceEndpointPath(stateDir,platform=process.platform){return join16(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},...options.background===!0?{transport:()=>connectLocal(stateDir,{background:!0})}:{}});return{serviceVersion:client.welcome.service_version,capabilities:client.welcome.capabilities,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,attachControl:()=>client.request("control.attach.get",{}),setAttachControl:(attached)=>client.request("control.attach.set",{attached}),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),endpointCommand:async(device,rpc)=>{let endpoint;try{endpoint=(await client.request("session.endpoints",{device})).endpoints[0]}catch(error){throw markNotSent(error)}if(endpoint===void 0)throw new LocalApiError("unsupported","the device lists no engine endpoint",{not_sent:!0});return await sendToEndpoint(client,device,endpoint,rpc)},close:()=>client.close(),closed:client.closed,locate:(device,engineId)=>client.request("session.locate",{device,engine_id:engineId})}}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(`
|
|
197
197
|
`).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.`}}import{existsSync}from"node:fs";var SEMVER2=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,isSemver=(value)=>SEMVER2.test(value),compareIdentifier=(a,b)=>{let numericA=/^\d+$/.test(a),numericB=/^\d+$/.test(b);if(numericA&&numericB)return Math.sign(Number(a)-Number(b));if(numericA!==numericB)return numericA?-1:1;return a<b?-1:a>b?1:0},compareVersions=(a,b)=>{let left=SEMVER2.exec(a),right=SEMVER2.exec(b);if(left===null||right===null)throw Error(`not a semantic version: ${left===null?a:b}`);for(let index of[1,2,3]){let difference=Number(left[index])-Number(right[index]);if(difference!==0)return Math.sign(difference)}let preLeft=left[4]?.split(".")??[],preRight=right[4]?.split(".")??[];if(preLeft.length===0||preRight.length===0)return Math.sign(preRight.length-preLeft.length);for(let index=0;index<Math.max(preLeft.length,preRight.length);index++){let x=preLeft[index],y=preRight[index];if(x===void 0||y===void 0)return x===void 0?-1:1;let order=compareIdentifier(x,y);if(order!==0)return order}return 0};var BOOTSTRAP_STOPPED_EXIT=3,ACCOUNT_STOP={signed_out:"signed_out",keychain_locked:"keychain_locked",store_unavailable:"store_unavailable",account_unavailable:"account_unavailable"},stopped=(state,notice)=>({kind:"stopped",state,notice,exitCode:BOOTSTRAP_STOPPED_EXIT}),isHandshakeTimeout=(error)=>error instanceof LocalApiError&&error.code==="handshake_timeout",isServiceStopped=(error,platform=process.platform)=>error instanceof Error&&("code"in error)&&["ENOENT","ECONNREFUSED","ECONNRESET"].includes(String(error.code))||platform==="win32"&&isHandshakeTimeout(error),failureNotice=(error)=>error instanceof LocalApiError?error.action??`The OmO device service did not answer as expected (${error.reason}). Try again; if it keeps failing, report it with /bug.`:"The OmO device service could not be reached. Try again; if it keeps failing, report it with /bug.",connectCurrent=async(deps)=>{if(!existsSync(deviceServiceEndpointPath(deps.stateDir)))return"absent";let service;try{service=await deps.connect()}catch(first){if(!isHandshakeTimeout(first)||isServiceStopped(first))return isServiceStopped(first)?"absent":stopped("service_degraded",failureNotice(first));try{service=await deps.connect()}catch(error){return isServiceStopped(error)?"absent":stopped("service_degraded",failureNotice(error))}}if(compareVersions(service.serviceVersion,deps.pinVersion)>=0)return service;return service.close(),"absent"},connectInstalled=async(deps)=>{let current=await connectCurrent(deps);if(current!=="absent")return current;let installed=await deps.install();if(!installed.ok)return stopped(installed.state,installed.action);try{return await deps.connect()}catch(error){return stopped("service_degraded",failureNotice(error))}},bootstrapDeviceService=async(deps)=>{let account=classifyAccountShow(await deps.accountShow());if(account.kind!=="signed_in")return stopped(ACCOUNT_STOP[account.kind],accountStateNotice(account)??"");let credential=await deps.credential();if(credential===null)return stopped("account_unavailable",accountStateNotice({kind:"account_unavailable",reason:"no device keys are stored"})??"");let service=await connectInstalled(deps);if("kind"in service)return service;try{return await service.registerRefresher(deps.refresher.binaryPath,deps.refresher.version),await service.adopt(credential),await service.registerEndpoints(deps.agentDir),{kind:"connected",status:await service.status(),service}}catch(error){return service.close(),stopped("service_degraded",failureNotice(error))}};import{spawn as spawn4}from"node:child_process";import{createHash as createHash9}from"node:crypto";import{chmodSync as chmodSync3,existsSync as existsSync2,mkdirSync as mkdirSync2,mkdtempSync,renameSync as renameSync3,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{join as join17}from"node:path";var CHECKSUMS="checksums.txt",SIGNATURE="checksums.txt.sig",MANIFEST="latest.json",SIGNATURE_BYTES=64,CHECKSUMS_MAX_BYTES=65536,MANIFEST_MAX_BYTES=4096,BINARY_MAX_BYTES=536870912,DEVICE_SERVICE_HOSTS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","windows-x64","windows-arm64"],isDeviceServiceHost=(value)=>DEVICE_SERVICE_HOSTS.some((host)=>host===value),deviceServiceHost=(platform,arch)=>{let host=`${platform==="win32"?"windows":platform}-${arch}`;return isDeviceServiceHost(host)?host:void 0},deviceServiceAssetName=(host)=>host.startsWith("windows-")?`omo-device-service-${host}.exe`:`omo-device-service-${host}`,RELEASE_FILES=new Set([MANIFEST,...DEVICE_SERVICE_HOSTS.map(deviceServiceAssetName)]),CHECKSUM_LINE=/^([0-9a-f]{64}) {2}([A-Za-z0-9.-]+)$/,strictUtf8=(bytes)=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}catch{return}},parseChecksums=(bytes)=>{let text=strictUtf8(bytes);if(text===void 0||!text.endsWith(`
|
|
198
198
|
`))return;let digests=new Map;for(let line of text.slice(0,-1).split(`
|
|
199
|
-
`)){let match=CHECKSUM_LINE.exec(line),digest=match?.[1],name=match?.[2];if(digest===void 0||name===void 0||!RELEASE_FILES.has(name)||digests.has(name))return;digests.set(name,digest)}return digests},parseManifest=(bytes)=>{let text=strictUtf8(bytes);if(text===void 0)return;let value;try{value=JSON.parse(text)}catch{return}if(typeof value!=="object"||value===null||Array.isArray(value))return;if(Object.keys(value).toSorted().join(",")!=="min_engine_version,version")return;let version=Reflect.get(value,"version"),engine=Reflect.get(value,"min_engine_version");if(typeof version!=="string"||typeof engine!=="string"||!isSemver(version)||!isSemver(engine))return;return{version,min_engine_version:engine}};import{spawnSync as spawnSync2}from"node:child_process";var P2=(1n<<255n)-19n,L2=(1n<<252n)+27742317777372353535851937790883648493n,mod2=(n)=>{let r=n%P2;return r<0n?r+P2:r},power2=(base,exponent)=>{let result=1n,b=mod2(base);for(let n=exponent;n>0n;n>>=1n){if(n&1n)result=mod2(result*b);b=mod2(b*b)}return result},D2=mod2(-121665n*power2(121666n,P2-2n)),SQRT_MINUS_ONE2=power2(2n,(P2-1n)/4n),squareN2=(x,n)=>{for(let i=0;i<n;i++)x=mod2(x*x);return x},sqrtPower2=(z)=>{let z2=mod2(z*z),z9=mod2(squareN2(z2,2)*z),a=mod2(squareN2(mod2(z2*z9),1)*z9);a=mod2(squareN2(a,5)*a);let b=mod2(squareN2(a,10)*a);return b=mod2(squareN2(b,20)*b),a=mod2(squareN2(b,10)*a),b=mod2(squareN2(a,50)*a),b=mod2(squareN2(b,100)*b),a=mod2(squareN2(b,50)*a),mod2(squareN2(a,2)*z)},IDENTITY2={x:0n,y:1n,z:1n,t:0n},add2=(p,q)=>{let a=mod2((p.y-p.x)*(q.y-q.x)),b=mod2((p.y+p.x)*(q.y+q.x)),c=mod2(2n*D2*p.t*q.t),d=mod2(2n*p.z*q.z),e=b-a,f=d-c,g=d+c,h=b+a;return{x:mod2(e*f),y:mod2(g*h),z:mod2(f*g),t:mod2(e*h)}},multiply2=(point,scalar)=>{let result=IDENTITY2,p=point;for(let n=scalar;n>0n;n>>=1n){if(n&1n)result=add2(result,p);p=add2(p,p)}return result},equal2=(p,q)=>mod2(p.x*q.z-q.x*p.z)===0n&&mod2(p.y*q.z-q.y*p.z)===0n,littleEndian2=(bytes)=>{let n=0n;for(let b of Array.from(bytes).reverse())n=n<<8n|BigInt(b);return n},decodePoint2=(bytes)=>{if(bytes.length!==32)return;let encoded=littleEndian2(bytes),sign=encoded>>255n,y=encoded&(1n<<255n)-1n;if(y>=P2)return;let y2=mod2(y*y),u=mod2(y2-1n),v=mod2(D2*y2+1n),v3=mod2(v*v*v),v7=mod2(v3*v3*v),x=mod2(u*v3*sqrtPower2(mod2(u*v7)));if(mod2(v*x*x)===mod2(-u))x=mod2(x*SQRT_MINUS_ONE2);if(mod2(v*x*x)!==u)return;if(x===0n&&sign===1n)return;if((x&1n)!==sign)x=mod2(-x);let point={x,y,z:1n,t:mod2(x*y)};if(equal2(multiply2(point,8n),IDENTITY2))return;return point};var keyCache2=new Map,cachedPublicKey2=(key)=>{let encoded=Array.from(key,(b)=>b.toString(16).padStart(2,"0")).join(""),cached=keyCache2.get(encoded);if(cached!==void 0)return keyCache2.delete(encoded),keyCache2.set(encoded,cached),cached;let point=decodePublicKeyUncached2(key);if(keyCache2.size===1024){let oldest=keyCache2.keys().next().value;if(oldest!==void 0)keyCache2.delete(oldest)}let entry={point:point??!1};return keyCache2.set(encoded,entry),entry},decodePublicKey2=(key)=>{if(key.length!==32)return;let point=cachedPublicKey2(key).point;return point===!1?void 0:point},decodePublicKeyUncached2=(key)=>{let point=decodePoint2(key);if(point===void 0||!equal2(multiply2(point,L2),IDENTITY2))return;return point},strictEd25519Key2=(key)=>decodePublicKey2(key)!==void 0,strictEd25519Precheck2=(key,sig)=>{if(key.length!==32||sig.length!==64)return{ok:!1,refusal:"malformed"};if(decodePublicKey2(key)===void 0||decodePoint2(sig.subarray(0,32))===void 0||littleEndian2(sig.subarray(32))>=L2)return{ok:!1,refusal:"malformed"};return{ok:!0}},strictEd25519Verify=async(key,sig,msg)=>{let checked=strictEd25519Precheck2(key,sig);if(!checked.ok)return checked;let aBytes=Uint8Array.from(key),signature=Uint8Array.from(sig),message=Uint8Array.from(msg),cached=cachedPublicKey2(aBytes);if(cached.point===!1)throw Error("prechecked Ed25519 key lost its validated point");cached.native??=crypto.subtle.importKey("raw",aBytes,"Ed25519",!1,["verify"]).catch((error)=>{throw delete cached.native,error});let nativeKey=await cached.native;return await crypto.subtle.verify("Ed25519",nativeKey,signature,message)?{ok:!0}:{ok:!1,refusal:"signature"}};var release_key_default={alg:"Ed25519",public_keys_hex:["6c6781a91888e3e5be10d1b27466319a7d5adf2a7d2b254f4118eda9cbcb4465","ca9407b484a30ac7f09cb152455176f1e03fc6ca3446ff930bc7587215759016"]};var HEX_KEY=/^[0-9a-f]{64}$/,parseReleaseKeySet=(value)=>{if(typeof value!=="object"||value===null||Array.isArray(value))throw Error("release key: not an object");if(Object.keys(value).toSorted().join(",")!=="alg,public_keys_hex")throw Error("release key: fields must be exactly alg and public_keys_hex");let alg=Reflect.get(value,"alg"),hexes=Reflect.get(value,"public_keys_hex");if(alg!=="Ed25519")throw Error("release key: alg must be Ed25519");if(!Array.isArray(hexes))throw Error("release key: public_keys_hex must be an array");if(new Set(hexes).size!==hexes.length)throw Error("release key: public_keys_hex must not repeat a key");return hexes.map((hex)=>{if(typeof hex!=="string"||!HEX_KEY.test(hex))throw Error("release key: each public_keys_hex entry must be 64 lowercase hex characters");return hex})},DEVICE_SERVICE_RELEASE_KEYS=parseReleaseKeySet(release_key_default),verifyReleaseSignature=async(releaseKeys,signature,checksums)=>{if(releaseKeys.length===0||!releaseKeys.every((key)=>strictEd25519Key2(key)))return{ok:!1,refusal:"malformed"};let verdict={ok:!1,refusal:"signature"};for(let key of releaseKeys)if(verdict=await strictEd25519Verify(key,signature,checksums),verdict.ok||verdict.refusal==="malformed")return verdict;return verdict},releaseKeySetBytes=(hexes)=>{if(hexes.length===0||new Set(hexes).size!==hexes.length||!hexes.every((hex)=>HEX_KEY.test(hex)))return;let keys=hexes.map((hex)=>new Uint8Array(Buffer.from(hex,"hex")));return keys.every((key)=>strictEd25519Key2(key))?keys:void 0},SIGNING_IDENTIFIER="",SIGNING_TEAM="523JNR86LZ",codeSignaturePasses=(path)=>{if(SIGNING_IDENTIFIER==="")return!1;let requirement=`identifier "${SIGNING_IDENTIFIER}" and anchor apple generic and certificate leaf[subject.OU] = "${SIGNING_TEAM}" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists`,result=spawnSync2("/usr/bin/codesign",["--verify","--strict",`-R=${requirement}`,path],{stdio:"ignore",timeout:1e4});return result.error===void 0&&result.status===0};var DEVICE_SERVICE_ORIGIN="https://get.omo.dev",VERIFY_FAILED="The downloaded OmO device service failed verification and was not installed. Try again later; if it keeps failing, report it with /bug.",refuse=(refusal,action=VERIFY_FAILED)=>({ok:!1,refusal,action}),sha2562=(bytes)=>createHash9("sha256").update(bytes).digest("hex"),platformSecure=process.platform==="win32"?async(path,kind)=>windowsSecureFile(await currentUserSid())(path,kind):posixSecureFile,downloader=(fetchRelease,base)=>async(name,maxBytes)=>{let response;try{response=await fetchRelease(`${base}${name}`,{signal:AbortSignal.timeout(120000)})}catch{return"missing"}if(!response.ok)return"missing";if(Number(response.headers.get("content-length")??"0")>maxBytes)return"too_large";let bytes=new Uint8Array(await response.arrayBuffer());return bytes.length>maxBytes?"too_large":bytes},downloadRefusal=(download)=>download==="missing"?refuse("download_failed","Could not download the OmO device service. Check the connection and try again."):refuse("malformed"),install=async(options,files,binaryName)=>{let secure=options.secure??platformSecure,bin=join17(options.stateDir,"bin");for(let dir of[options.stateDir,bin])mkdirSync2(dir,{recursive:!0,mode:448}),await secure(dir,"dir");let staging=mkdtempSync(join17(bin,".staging-")),releaseDir=join17(bin,options.version);try{for(let[name,bytes]of files)writeFileSync3(join17(staging,name),bytes,{mode:384});if(chmodSync3(join17(staging,binaryName),493),options.host.startsWith("darwin-")&&!(options.verifyCodeSignature??codeSignaturePasses)(join17(staging,binaryName)))return refuse("code_signature");let previous=existsSync2(releaseDir)?`${staging}.previous`:void 0;if(previous!==void 0)renameSync3(releaseDir,previous);if(renameSync3(staging,releaseDir),previous!==void 0)rmSync3(previous,{recursive:!0,force:!0})}finally{rmSync3(staging,{recursive:!0,force:!0})}return{ok:!0,version:options.version,releaseDir,binary:join17(releaseDir,binaryName)}},acquireDeviceService=async(options)=>{let keys=releaseKeySetBytes(options.releaseKeys??DEVICE_SERVICE_RELEASE_KEYS);if(keys===void 0)return refuse("release_key_invalid","This omo build carries no usable device service release key, so it cannot verify device service releases. That is a defect in this build: report it with /bug.");let get=downloader(options.fetch??globalThis.fetch,`${options.origin??DEVICE_SERVICE_ORIGIN}/${options.channel??"stable"}/device-service/${options.version}/`),[checksums,signature]=await Promise.all([get(CHECKSUMS,CHECKSUMS_MAX_BYTES),get(SIGNATURE,SIGNATURE_BYTES)]);if(typeof checksums==="string")return downloadRefusal(checksums);if(typeof signature==="string")return downloadRefusal(signature);let verdict=await verifyReleaseSignature(keys,signature,checksums);if(!verdict.ok)return refuse(verdict.refusal);let digests=parseChecksums(checksums),binaryName=deviceServiceAssetName(options.host),manifestDigest=digests?.get(MANIFEST),binaryDigest=digests?.get(binaryName);if(manifestDigest===void 0||binaryDigest===void 0)return refuse("malformed");let[manifestBytes,binary]=await Promise.all([get(MANIFEST,MANIFEST_MAX_BYTES),get(binaryName,BINARY_MAX_BYTES)]);if(typeof manifestBytes==="string")return downloadRefusal(manifestBytes);if(typeof binary==="string")return downloadRefusal(binary);if(sha2562(manifestBytes)!==manifestDigest||sha2562(binary)!==binaryDigest)return refuse("checksum");let manifest=parseManifest(manifestBytes);if(manifest===void 0)return refuse("malformed");if(manifest.version!==options.version)return refuse("version_mismatch");if(compareVersions(manifest.min_engine_version,options.engineVersion)>0)return refuse("update_required",`This OmO device service needs engine ${manifest.min_engine_version} or later. Update OmO, then try again.`);return install(options,new Map([[CHECKSUMS,checksums],[SIGNATURE,signature],[MANIFEST,manifestBytes],[binaryName,binary]]),binaryName)};var INSTALL_TIMEOUT_MS=120000,runCommand=([command,...args])=>new Promise((resolve)=>{if(command===void 0)return resolve({exitCode:1,output:"no command"});let child=spawn4(command,args,{stdio:["ignore","pipe","pipe"],timeout:INSTALL_TIMEOUT_MS,windowsHide:!0}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.stderr.on("data",(chunk)=>chunks.push(chunk)),child.on("error",(error)=>resolve({exitCode:1,output:error.message})),child.on("close",(code)=>resolve({exitCode:code??1,output:Buffer.concat(chunks).toString("utf8")}))}),firstLine2=(text)=>text.trim().split(/\r?\n/)[0]??"",installDeviceService=async(options)=>{let acquired=await acquireDeviceService(options);if(!acquired.ok)return{ok:!1,state:acquired.refusal==="update_required"||acquired.refusal==="release_key_invalid"?"update_required":"service_degraded",action:acquired.action};let result=await(options.run??runCommand)([acquired.binary,"install-service","--from",acquired.releaseDir]);if(result.exitCode===0)return{ok:!0};return{ok:!1,state:"service_degraded",action:`The OmO device service could not be installed (${firstLine2(result.output)||`exit ${result.exitCode}`}). Try again; if it keeps failing, report it with /bug.`}};var DEVICE_SERVICE_VERSION="0.1.0";var NONE2=Symbol("none registered");import{homedir as homedir7}from"node:os";import{join as join18,resolve as resolve2}from"node:path";var AGENT_DIR_ENV_NAMES=["OMO_CODING_AGENT_DIR","SENPI_CODING_AGENT_DIR","PI_CODING_AGENT_DIR"];function runtimeHome(env=process.env){return env.HOME||env.USERPROFILE||homedir7()}function canonicalAgentDir(env=process.env,home=runtimeHome(env)){for(let name of AGENT_DIR_ENV_NAMES){let configured=env[name]?.trim();if(configured)return resolve2(configured)}return defaultAgentDir(home)}function defaultAgentDir(home){return join18(home,".omo","agent")}var package_default={name:"omo-ai",version:"5.1.63",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.5-1"},repository:{type:"git",url:"git+https://github.com/code-yeongyu/oh-my-openagent.git"}};import{isAbsolute,resolve as resolve3}from"node:path";var STATE_LABELS={not_configured:"Not set up",disabled:"Off",sign_in_required:"Sign-in required",plan_required:"Plan required",keychain_locked:"Keychain locked",connecting:"Connecting",activation_pending:"Waiting for activation",connected:"Connected",offline:"Offline",authorization_stale:"Reconnecting",service_degraded:"Needs attention",update_required:"Update required",signed_out:"Signed out"};function renderTable(header,rows){let widths=header.map((title,column)=>Math.max(title.length,...rows.map((row)=>(row[column]??"").length))),line=(cells)=>cells.map((cell,column)=>cell.padEnd(widths[column]??0)).join(" ").trimEnd();return[line(header),...rows.map(line)]}function ago(ms,now){if(ms===null)return"never";let seconds=Math.max(0,Math.round((now-ms)/1000));if(seconds<60)return"just now";let minutes=Math.round(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.round(minutes/60);if(hours<48)return`${hours}h ago`;return`${Math.round(hours/24)}d ago`}function statusLines(status,serviceVersion){let rows=[["State",STATE_LABELS[status.state]],["Remote sessions",status.enabled?"on":"off"],["This device",status.device===null?"not set up":status.device.name],["Service",serviceVersion]];if(status.detail?.action)rows.push(["Action",status.detail.action]);let width=Math.max(...rows.map(([label])=>label.length));return rows.map(([label,value])=>`${label.padEnd(width)} ${value}`)}function deviceLines(devices,now){if(devices.length===0)return["No devices on this account yet."];return renderTable(["DEVICE","NAME","KIND","PLATFORM","SEEN"],devices.map((device)=>[device.device,device.label,device.kind,device.platform,device.online?"online":ago(device.last_seen_ms,now)]))}function sessionLines(result,labels,now){let lines=result.rows.length===0?["No sessions found."]:renderTable(["SESSION","TITLE","STATE","PROJECT","DEVICE","UPDATED"],result.rows.map((row)=>[`${row.device}/${row.session_id}`,row.title,row.source==="cache"?`${row.state} (cached)`:row.state,row.project,labels.get(row.device)??row.device,ago(row.updated_ms,now)])),missing=[...new Set([...result.incomplete,...Object.entries(result.devices).filter(([,state])=>state!=="answered").map(([device])=>device)])];if(missing.length>0)lines.push("",`Not answered, rows may be missing or cached: ${missing.map((device)=>labels.get(device)??device).join(", ")}`);return lines}function controlLines(state,now){let line=state.attached?"Remote control is on: your other signed-in devices can view and command sessions on this device.":"Remote control is off: your other devices cannot view or command sessions on this device.";return state.changedAt===""?[line]:[line,`Changed ${ago(Date.parse(state.changedAt),now)}.`]}var UNSUPPORTED_HOST="The OmO device service does not run on this platform yet.";function deviceServiceBootstrapSetup(options){let host=deviceServiceHost(options.platform??process.platform,options.arch??process.arch);return{pinVersion:DEVICE_SERVICE_VERSION,install:async()=>host===void 0?{ok:!1,state:"service_degraded",action:UNSUPPORTED_HOST}:installDeviceService({...options.release,version:DEVICE_SERVICE_VERSION,host,stateDir:options.stateDir,engineVersion:package_default.dependencies["@code-yeongyu/senpi"]}),credential:options.credential,refresher:{binaryPath:options.binaryPath,version:package_default.version},agentDir:options.agentDir}}function storedDeviceCredential(api){return async()=>{let stored=await createCredentialStore(api,{wait:SESSION_READ_WAIT}).read();if(stored===null)return null;return{device:{id:stored.device.id,name:stored.device.name},signingPrivateKey:stored.signingPrivateKey,sealingPrivateKey:stored.sealingPrivateKey}}}function omoBinaryPath(env=process.env){let declared=env.OMO_BIN;if(declared!==void 0&&isAbsolute(declared))return declared;let bun=Reflect.get(globalThis,"Bun"),embedded=typeof bun==="object"&&bun!==null?Reflect.get(bun,"embeddedFiles"):void 0;if(Array.isArray(embedded)&&embedded.length>0)return process.execPath;return resolve3(process.argv[1]??process.execPath)}async function runBootstrapVerb(io,setup,json){let outcome=await bootstrapDeviceService({accountShow:io.accountShow,stateDir:io.stateDir,connect:io.connect,...setup});if(outcome.kind==="stopped"){if(json)io.output(JSON.stringify({state:outcome.state,notice:outcome.notice}));else io.error(outcome.notice);return"stopped"}try{if(json)io.output(JSON.stringify({state:"connected",status:outcome.status}));else for(let line of statusLines(outcome.status,outcome.service.serviceVersion))io.output(line)}finally{outcome.service.close()}return"connected"}import{existsSync as existsSync3}from"node:fs";import{createHash as createHash10,randomBytes as randomBytes8,randomUUID as randomUUID8,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{chmodSync as chmodSync4,mkdtempSync as mkdtempSync2,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{createServer as createServer3}from"node:net";import{tmpdir as tmpdir2}from"node:os";import{join as join19,win32 as win322}from"node:path";var SECRET_BYTES=32,HANDSHAKE_TIMEOUT_MS2=2000,MAX_LINE_CHARS=67108864,PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",LOCAL_SESSION_ID="remote";function pipeAddress(socketPath,secret){let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret)]);return`${PIPE_PREFIX}${createHash10("sha256").update(identity).digest("hex").slice(0,32)}`}var isRecord8=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),isParsedRecord=(value)=>isRecord8(value),outcomeText=(outcome)=>("reason"in outcome)?`${outcome.state}: ${outcome.reason}`:outcome.state;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(`Attached to ${this.label}`,"info");let stopEvents=this.attach.onEvent((event)=>this.event(event)),stopFrames=this.attach.onFrame((frame)=>this.send("sessionId"in frame?{...frame,sessionId:LOCAL_SESSION_ID}:frame)),stopLosses=this.attach.onChannelLoss((reason)=>this.notify(`Lost a reply or event from the remote device: ${reason}`,"warning"));this.stopStream=()=>{stopEvents(),stopFrames(),stopLosses()}}stop(){this.stopStream?.()}send(value){if(this.socket.writable&&!this.socket.destroyed)this.socket.write(`${JSON.stringify(value)}
|
|
199
|
+
`)){let match=CHECKSUM_LINE.exec(line),digest=match?.[1],name=match?.[2];if(digest===void 0||name===void 0||!RELEASE_FILES.has(name)||digests.has(name))return;digests.set(name,digest)}return digests},parseManifest=(bytes)=>{let text=strictUtf8(bytes);if(text===void 0)return;let value;try{value=JSON.parse(text)}catch{return}if(typeof value!=="object"||value===null||Array.isArray(value))return;if(Object.keys(value).toSorted().join(",")!=="min_engine_version,version")return;let version=Reflect.get(value,"version"),engine=Reflect.get(value,"min_engine_version");if(typeof version!=="string"||typeof engine!=="string"||!isSemver(version)||!isSemver(engine))return;return{version,min_engine_version:engine}};import{spawnSync as spawnSync2}from"node:child_process";var P2=(1n<<255n)-19n,L2=(1n<<252n)+27742317777372353535851937790883648493n,mod2=(n)=>{let r=n%P2;return r<0n?r+P2:r},power2=(base,exponent)=>{let result=1n,b=mod2(base);for(let n=exponent;n>0n;n>>=1n){if(n&1n)result=mod2(result*b);b=mod2(b*b)}return result},D2=mod2(-121665n*power2(121666n,P2-2n)),SQRT_MINUS_ONE2=power2(2n,(P2-1n)/4n),squareN2=(x,n)=>{for(let i=0;i<n;i++)x=mod2(x*x);return x},sqrtPower2=(z)=>{let z2=mod2(z*z),z9=mod2(squareN2(z2,2)*z),a=mod2(squareN2(mod2(z2*z9),1)*z9);a=mod2(squareN2(a,5)*a);let b=mod2(squareN2(a,10)*a);return b=mod2(squareN2(b,20)*b),a=mod2(squareN2(b,10)*a),b=mod2(squareN2(a,50)*a),b=mod2(squareN2(b,100)*b),a=mod2(squareN2(b,50)*a),mod2(squareN2(a,2)*z)},IDENTITY2={x:0n,y:1n,z:1n,t:0n},add2=(p,q)=>{let a=mod2((p.y-p.x)*(q.y-q.x)),b=mod2((p.y+p.x)*(q.y+q.x)),c=mod2(2n*D2*p.t*q.t),d=mod2(2n*p.z*q.z),e=b-a,f=d-c,g=d+c,h=b+a;return{x:mod2(e*f),y:mod2(g*h),z:mod2(f*g),t:mod2(e*h)}},multiply2=(point,scalar)=>{let result=IDENTITY2,p=point;for(let n=scalar;n>0n;n>>=1n){if(n&1n)result=add2(result,p);p=add2(p,p)}return result},equal2=(p,q)=>mod2(p.x*q.z-q.x*p.z)===0n&&mod2(p.y*q.z-q.y*p.z)===0n,littleEndian2=(bytes)=>{let n=0n;for(let b of Array.from(bytes).reverse())n=n<<8n|BigInt(b);return n},decodePoint2=(bytes)=>{if(bytes.length!==32)return;let encoded=littleEndian2(bytes),sign=encoded>>255n,y=encoded&(1n<<255n)-1n;if(y>=P2)return;let y2=mod2(y*y),u=mod2(y2-1n),v=mod2(D2*y2+1n),v3=mod2(v*v*v),v7=mod2(v3*v3*v),x=mod2(u*v3*sqrtPower2(mod2(u*v7)));if(mod2(v*x*x)===mod2(-u))x=mod2(x*SQRT_MINUS_ONE2);if(mod2(v*x*x)!==u)return;if(x===0n&&sign===1n)return;if((x&1n)!==sign)x=mod2(-x);let point={x,y,z:1n,t:mod2(x*y)};if(equal2(multiply2(point,8n),IDENTITY2))return;return point};var keyCache2=new Map,cachedPublicKey2=(key)=>{let encoded=Array.from(key,(b)=>b.toString(16).padStart(2,"0")).join(""),cached=keyCache2.get(encoded);if(cached!==void 0)return keyCache2.delete(encoded),keyCache2.set(encoded,cached),cached;let point=decodePublicKeyUncached2(key);if(keyCache2.size===1024){let oldest=keyCache2.keys().next().value;if(oldest!==void 0)keyCache2.delete(oldest)}let entry={point:point??!1};return keyCache2.set(encoded,entry),entry},decodePublicKey2=(key)=>{if(key.length!==32)return;let point=cachedPublicKey2(key).point;return point===!1?void 0:point},decodePublicKeyUncached2=(key)=>{let point=decodePoint2(key);if(point===void 0||!equal2(multiply2(point,L2),IDENTITY2))return;return point},strictEd25519Key2=(key)=>decodePublicKey2(key)!==void 0,strictEd25519Precheck2=(key,sig)=>{if(key.length!==32||sig.length!==64)return{ok:!1,refusal:"malformed"};if(decodePublicKey2(key)===void 0||decodePoint2(sig.subarray(0,32))===void 0||littleEndian2(sig.subarray(32))>=L2)return{ok:!1,refusal:"malformed"};return{ok:!0}},strictEd25519Verify=async(key,sig,msg)=>{let checked=strictEd25519Precheck2(key,sig);if(!checked.ok)return checked;let aBytes=Uint8Array.from(key),signature=Uint8Array.from(sig),message=Uint8Array.from(msg),cached=cachedPublicKey2(aBytes);if(cached.point===!1)throw Error("prechecked Ed25519 key lost its validated point");cached.native??=crypto.subtle.importKey("raw",aBytes,"Ed25519",!1,["verify"]).catch((error)=>{throw delete cached.native,error});let nativeKey=await cached.native;return await crypto.subtle.verify("Ed25519",nativeKey,signature,message)?{ok:!0}:{ok:!1,refusal:"signature"}};var release_key_default={alg:"Ed25519",public_keys_hex:["6c6781a91888e3e5be10d1b27466319a7d5adf2a7d2b254f4118eda9cbcb4465","ca9407b484a30ac7f09cb152455176f1e03fc6ca3446ff930bc7587215759016"]};var HEX_KEY=/^[0-9a-f]{64}$/,parseReleaseKeySet=(value)=>{if(typeof value!=="object"||value===null||Array.isArray(value))throw Error("release key: not an object");if(Object.keys(value).toSorted().join(",")!=="alg,public_keys_hex")throw Error("release key: fields must be exactly alg and public_keys_hex");let alg=Reflect.get(value,"alg"),hexes=Reflect.get(value,"public_keys_hex");if(alg!=="Ed25519")throw Error("release key: alg must be Ed25519");if(!Array.isArray(hexes))throw Error("release key: public_keys_hex must be an array");if(new Set(hexes).size!==hexes.length)throw Error("release key: public_keys_hex must not repeat a key");return hexes.map((hex)=>{if(typeof hex!=="string"||!HEX_KEY.test(hex))throw Error("release key: each public_keys_hex entry must be 64 lowercase hex characters");return hex})},DEVICE_SERVICE_RELEASE_KEYS=parseReleaseKeySet(release_key_default),verifyReleaseSignature=async(releaseKeys,signature,checksums)=>{if(releaseKeys.length===0||!releaseKeys.every((key)=>strictEd25519Key2(key)))return{ok:!1,refusal:"malformed"};let verdict={ok:!1,refusal:"signature"};for(let key of releaseKeys)if(verdict=await strictEd25519Verify(key,signature,checksums),verdict.ok||verdict.refusal==="malformed")return verdict;return verdict},releaseKeySetBytes=(hexes)=>{if(hexes.length===0||new Set(hexes).size!==hexes.length||!hexes.every((hex)=>HEX_KEY.test(hex)))return;let keys=hexes.map((hex)=>new Uint8Array(Buffer.from(hex,"hex")));return keys.every((key)=>strictEd25519Key2(key))?keys:void 0},SIGNING_IDENTIFIER="",SIGNING_TEAM="523JNR86LZ",codeSignaturePasses=(path)=>{if(SIGNING_IDENTIFIER==="")return!1;let requirement=`identifier "${SIGNING_IDENTIFIER}" and anchor apple generic and certificate leaf[subject.OU] = "${SIGNING_TEAM}" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists`,result=spawnSync2("/usr/bin/codesign",["--verify","--strict",`-R=${requirement}`,path],{stdio:"ignore",timeout:1e4});return result.error===void 0&&result.status===0};var DEVICE_SERVICE_ORIGIN="https://get.omo.dev",VERIFY_FAILED="The downloaded OmO device service failed verification and was not installed. Try again later; if it keeps failing, report it with /bug.",refuse=(refusal,action=VERIFY_FAILED)=>({ok:!1,refusal,action}),sha2562=(bytes)=>createHash9("sha256").update(bytes).digest("hex"),platformSecure=process.platform==="win32"?async(path,kind)=>windowsSecureFile(await currentUserSid())(path,kind):posixSecureFile,downloader=(fetchRelease,base)=>async(name,maxBytes)=>{let response;try{response=await fetchRelease(`${base}${name}`,{signal:AbortSignal.timeout(120000)})}catch{return"missing"}if(!response.ok)return"missing";if(Number(response.headers.get("content-length")??"0")>maxBytes)return"too_large";let bytes=new Uint8Array(await response.arrayBuffer());return bytes.length>maxBytes?"too_large":bytes},downloadRefusal=(download)=>download==="missing"?refuse("download_failed","Could not download the OmO device service. Check the connection and try again."):refuse("malformed"),install=async(options,files,binaryName)=>{let secure=options.secure??platformSecure,bin=join17(options.stateDir,"bin");for(let dir of[options.stateDir,bin])mkdirSync2(dir,{recursive:!0,mode:448}),await secure(dir,"dir");let staging=mkdtempSync(join17(bin,".staging-")),releaseDir=join17(bin,options.version);try{for(let[name,bytes]of files)writeFileSync3(join17(staging,name),bytes,{mode:384});if(chmodSync3(join17(staging,binaryName),493),options.host.startsWith("darwin-")&&!(options.verifyCodeSignature??codeSignaturePasses)(join17(staging,binaryName)))return refuse("code_signature");let previous=existsSync2(releaseDir)?`${staging}.previous`:void 0;if(previous!==void 0)renameSync3(releaseDir,previous);if(renameSync3(staging,releaseDir),previous!==void 0)rmSync3(previous,{recursive:!0,force:!0})}finally{rmSync3(staging,{recursive:!0,force:!0})}return{ok:!0,version:options.version,releaseDir,binary:join17(releaseDir,binaryName)}},acquireDeviceService=async(options)=>{let keys=releaseKeySetBytes(options.releaseKeys??DEVICE_SERVICE_RELEASE_KEYS);if(keys===void 0)return refuse("release_key_invalid","This omo build carries no usable device service release key, so it cannot verify device service releases. That is a defect in this build: report it with /bug.");let get=downloader(options.fetch??globalThis.fetch,`${options.origin??DEVICE_SERVICE_ORIGIN}/${options.channel??"stable"}/device-service/${options.version}/`),[checksums,signature]=await Promise.all([get(CHECKSUMS,CHECKSUMS_MAX_BYTES),get(SIGNATURE,SIGNATURE_BYTES)]);if(typeof checksums==="string")return downloadRefusal(checksums);if(typeof signature==="string")return downloadRefusal(signature);let verdict=await verifyReleaseSignature(keys,signature,checksums);if(!verdict.ok)return refuse(verdict.refusal);let digests=parseChecksums(checksums),binaryName=deviceServiceAssetName(options.host),manifestDigest=digests?.get(MANIFEST),binaryDigest=digests?.get(binaryName);if(manifestDigest===void 0||binaryDigest===void 0)return refuse("malformed");let[manifestBytes,binary]=await Promise.all([get(MANIFEST,MANIFEST_MAX_BYTES),get(binaryName,BINARY_MAX_BYTES)]);if(typeof manifestBytes==="string")return downloadRefusal(manifestBytes);if(typeof binary==="string")return downloadRefusal(binary);if(sha2562(manifestBytes)!==manifestDigest||sha2562(binary)!==binaryDigest)return refuse("checksum");let manifest=parseManifest(manifestBytes);if(manifest===void 0)return refuse("malformed");if(manifest.version!==options.version)return refuse("version_mismatch");if(compareVersions(manifest.min_engine_version,options.engineVersion)>0)return refuse("update_required",`This OmO device service needs engine ${manifest.min_engine_version} or later. Update OmO, then try again.`);return install(options,new Map([[CHECKSUMS,checksums],[SIGNATURE,signature],[MANIFEST,manifestBytes],[binaryName,binary]]),binaryName)};var INSTALL_TIMEOUT_MS=120000,runCommand=([command,...args])=>new Promise((resolve)=>{if(command===void 0)return resolve({exitCode:1,output:"no command"});let child=spawn4(command,args,{stdio:["ignore","pipe","pipe"],timeout:INSTALL_TIMEOUT_MS,windowsHide:!0}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.stderr.on("data",(chunk)=>chunks.push(chunk)),child.on("error",(error)=>resolve({exitCode:1,output:error.message})),child.on("close",(code)=>resolve({exitCode:code??1,output:Buffer.concat(chunks).toString("utf8")}))}),firstLine2=(text)=>text.trim().split(/\r?\n/)[0]??"",installDeviceService=async(options)=>{let acquired=await acquireDeviceService(options);if(!acquired.ok)return{ok:!1,state:acquired.refusal==="update_required"||acquired.refusal==="release_key_invalid"?"update_required":"service_degraded",action:acquired.action};let result=await(options.run??runCommand)([acquired.binary,"install-service","--from",acquired.releaseDir]);if(result.exitCode===0)return{ok:!0};return{ok:!1,state:"service_degraded",action:`The OmO device service could not be installed (${firstLine2(result.output)||`exit ${result.exitCode}`}). Try again; if it keeps failing, report it with /bug.`}};var DEVICE_SERVICE_VERSION="0.1.0";var NONE2=Symbol("none registered");import{homedir as homedir7}from"node:os";import{join as join18,resolve as resolve2}from"node:path";var AGENT_DIR_ENV_NAMES=["OMO_CODING_AGENT_DIR","SENPI_CODING_AGENT_DIR","PI_CODING_AGENT_DIR"];function runtimeHome(env=process.env){return env.HOME||env.USERPROFILE||homedir7()}function canonicalAgentDir(env=process.env,home=runtimeHome(env)){for(let name of AGENT_DIR_ENV_NAMES){let configured=env[name]?.trim();if(configured)return resolve2(configured)}return defaultAgentDir(home)}function defaultAgentDir(home){return join18(home,".omo","agent")}var package_default={name:"omo-ai",version:"5.1.64",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.5-1"},repository:{type:"git",url:"git+https://github.com/code-yeongyu/oh-my-openagent.git"}};import{isAbsolute,resolve as resolve3}from"node:path";var STATE_LABELS={not_configured:"Not set up",disabled:"Off",sign_in_required:"Sign-in required",plan_required:"Plan required",keychain_locked:"Keychain locked",connecting:"Connecting",activation_pending:"Waiting for activation",connected:"Connected",offline:"Offline",authorization_stale:"Reconnecting",service_degraded:"Needs attention",update_required:"Update required",signed_out:"Signed out"};function renderTable(header,rows){let widths=header.map((title,column)=>Math.max(title.length,...rows.map((row)=>(row[column]??"").length))),line=(cells)=>cells.map((cell,column)=>cell.padEnd(widths[column]??0)).join(" ").trimEnd();return[line(header),...rows.map(line)]}function ago(ms,now){if(ms===null)return"never";let seconds=Math.max(0,Math.round((now-ms)/1000));if(seconds<60)return"just now";let minutes=Math.round(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.round(minutes/60);if(hours<48)return`${hours}h ago`;return`${Math.round(hours/24)}d ago`}function statusLines(status,serviceVersion){let rows=[["State",STATE_LABELS[status.state]],["Remote sessions",status.enabled?"on":"off"],["This device",status.device===null?"not set up":status.device.name],["Service",serviceVersion]];if(status.detail?.action)rows.push(["Action",status.detail.action]);let width=Math.max(...rows.map(([label])=>label.length));return rows.map(([label,value])=>`${label.padEnd(width)} ${value}`)}function deviceLines(devices,now){if(devices.length===0)return["No devices on this account yet."];return renderTable(["DEVICE","NAME","KIND","PLATFORM","SEEN"],devices.map((device)=>[device.device,device.label,device.kind,device.platform,device.online?"online":ago(device.last_seen_ms,now)]))}function sessionLines(result,labels,now){let lines=result.rows.length===0?["No sessions found."]:renderTable(["SESSION","TITLE","STATE","PROJECT","DEVICE","UPDATED"],result.rows.map((row)=>[`${row.device}/${row.session_id}`,row.title,row.source==="cache"?`${row.state} (cached)`:row.state,row.project,labels.get(row.device)??row.device,ago(row.updated_ms,now)])),missing=[...new Set([...result.incomplete,...Object.entries(result.devices).filter(([,state])=>state!=="answered").map(([device])=>device)])];if(missing.length>0)lines.push("",`Not answered, rows may be missing or cached: ${missing.map((device)=>labels.get(device)??device).join(", ")}`);return lines}function controlLines(state,now){let line=state.attached?"Remote control is on: your other signed-in devices can view and command sessions on this device.":"Remote control is off: your other devices cannot view or command sessions on this device.";return state.changedAt===""?[line]:[line,`Changed ${ago(Date.parse(state.changedAt),now)}.`]}var UNSUPPORTED_HOST="The OmO device service does not run on this platform yet.";function deviceServiceBootstrapSetup(options){let host=deviceServiceHost(options.platform??process.platform,options.arch??process.arch);return{pinVersion:DEVICE_SERVICE_VERSION,install:async()=>host===void 0?{ok:!1,state:"service_degraded",action:UNSUPPORTED_HOST}:installDeviceService({...options.release,version:DEVICE_SERVICE_VERSION,host,stateDir:options.stateDir,engineVersion:package_default.dependencies["@code-yeongyu/senpi"]}),credential:options.credential,refresher:{binaryPath:options.binaryPath,version:package_default.version},agentDir:options.agentDir}}function storedDeviceCredential(api){return async()=>{let stored=await createCredentialStore(api,{wait:SESSION_READ_WAIT}).read();if(stored===null)return null;return{device:{id:stored.device.id,name:stored.device.name},signingPrivateKey:stored.signingPrivateKey,sealingPrivateKey:stored.sealingPrivateKey}}}function omoBinaryPath(env=process.env){let declared=env.OMO_BIN;if(declared!==void 0&&isAbsolute(declared))return declared;let bun=Reflect.get(globalThis,"Bun"),embedded=typeof bun==="object"&&bun!==null?Reflect.get(bun,"embeddedFiles"):void 0;if(Array.isArray(embedded)&&embedded.length>0)return process.execPath;return resolve3(process.argv[1]??process.execPath)}async function runBootstrapVerb(io,setup,json){let outcome=await bootstrapDeviceService({accountShow:io.accountShow,stateDir:io.stateDir,connect:io.connect,...setup});if(outcome.kind==="stopped"){if(json)io.output(JSON.stringify({state:outcome.state,notice:outcome.notice}));else io.error(outcome.notice);return"stopped"}try{if(json)io.output(JSON.stringify({state:"connected",status:outcome.status}));else for(let line of statusLines(outcome.status,outcome.service.serviceVersion))io.output(line)}finally{outcome.service.close()}return"connected"}import{existsSync as existsSync3}from"node:fs";import{createHash as createHash10,randomBytes as randomBytes8,randomUUID as randomUUID8,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{chmodSync as chmodSync4,mkdtempSync as mkdtempSync2,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{createServer as createServer3}from"node:net";import{tmpdir as tmpdir2}from"node:os";import{join as join19,win32 as win322}from"node:path";var SECRET_BYTES=32,HANDSHAKE_TIMEOUT_MS2=2000,MAX_LINE_CHARS=67108864,PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",LOCAL_SESSION_ID="remote";function pipeAddress(socketPath,secret){let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret)]);return`${PIPE_PREFIX}${createHash10("sha256").update(identity).digest("hex").slice(0,32)}`}var isRecord8=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),isParsedRecord=(value)=>isRecord8(value),outcomeText=(outcome)=>("reason"in outcome)?`${outcome.state}: ${outcome.reason}`:outcome.state;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(`Attached to ${this.label}`,"info");let stopEvents=this.attach.onEvent((event)=>this.event(event)),stopFrames=this.attach.onFrame((frame)=>this.send("sessionId"in frame?{...frame,sessionId:LOCAL_SESSION_ID}:frame)),stopLosses=this.attach.onChannelLoss((reason)=>this.notify(`Lost a reply or event from the remote device: ${reason}`,"warning"));this.stopStream=()=>{stopEvents(),stopFrames(),stopLosses()}}stop(){this.stopStream?.()}send(value){if(this.socket.writable&&!this.socket.destroyed)this.socket.write(`${JSON.stringify(value)}
|
|
200
200
|
`)}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:randomUUID8(),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:randomUUID8(),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));default:return await this.forward(request,type)}}catch(error){refuse(error instanceof Error?error.message:String(error))}}async forward(request,type){let rpc=request.sessionId===LOCAL_SESSION_ID?{...request,sessionId:this.attach.sessionId}:request,{outcome,response}=await this.attach.command(rpc);if(response!==void 0){this.send({...response,id:request.id});return}if(outcome.state==="engine_applied"){this.send({type:"response",id:request.id,command:type,success:!0});return}this.send({type:"response",id:request.id,command:type,success:!1,error:outcomeText(outcome)})}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(`
|
|
201
201
|
`);while(newline!==-1){let line=buffer.slice(0,newline).replace(/\r$/,"");if(buffer=buffer.slice(newline+1),line)onLine(line);newline=buffer.indexOf(`
|
|
202
202
|
`)}})}async function serveRemoteAttach(attach,options={label:""}){let platform=options.platform??process.platform,dir=mkdtempSync2(join19(options.parent??tmpdir2(),"omo-ra-"));chmodSync4(dir,448);let socketPath=join19(dir,`t-${randomBytes8(8).toString("hex")}.sock`),secret=randomBytes8(SECRET_BYTES);writeFileSync4(`${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(isParsedRecord(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=()=>rmSync4(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
package/plugin/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [5.1.64] - 2026-11-07
|
|
11
|
+
|
|
12
|
+
**Desktop memory sync now starts as soon as the engine boots, without waiting for a session.** An engine started by `omo host ensure` loads extensions only when a session opens, while the desktop opens none until the engine has sent the memory-sync bootstrap handshake, so the two waited on each other. The compiled `omo` and the npm launcher now start that one claim before the engine loads whenever an RPC engine's launch declares a `memory-sync` channel; the first session reuses it. A claim that fails still reports memory sync as unavailable and never falls back to CLI credentials. ([#12702](https://github.com/code-yeongyu/oh-my-openagent/issues/12702)) ([#12704](https://github.com/code-yeongyu/oh-my-openagent/pull/12704))
|
|
13
|
+
|
|
14
|
+
Internal (tests only): macOS trust acquisition reads `/etc/ssl/cert.pem` through the already-injectable bundle reader, and a test now proves that a malformed default file yields the structured `openssl-default-file-malformed` drop entry (file, cause, block index, narrowing). ([#12633](https://github.com/code-yeongyu/oh-my-openagent/pull/12633))
|
|
15
|
+
|
|
16
|
+
Internal (tests only): the OpenSSL default-file importer tests now pin that any high byte on a BEGIN line, not only a BOM, drops the whole file. ([#12632](https://github.com/code-yeongyu/oh-my-openagent/pull/12632))
|
|
17
|
+
|
|
18
|
+
Internal (release tooling): the omo-native trust mutation harness counts a mutant as killed only when a named test fails by an assertion; a mutant that only throws a runtime error or crashes on load is now reported as `crashed` and fails the run. ([#12631](https://github.com/code-yeongyu/oh-my-openagent/pull/12631))
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- Memory sync no longer loses an edit when two devices change the same line of a memory file at the same time. Devices on this version keep both edits as whole lines, and every device converges. Before, the edits were merged character by character into text that matched neither (#12279).
|
|
23
|
+
- Between devices on this version, an edit does not disturb a line nobody edited. The exception is a very large rewrite: when one device adds and removes more than about 2,000 lines of a note in one save, that save is merged character by character, as before this fix, so a concurrent edit to the same line can still splice.
|
|
24
|
+
- When the note's body or the new text does not end with a newline, the edit is still merged character by character, as before, so two concurrent edits to that last line can still splice.
|
|
25
|
+
- With a device that still runs an older version, its old character merge can still go wrong in these ways:
|
|
26
|
+
- **Adjacent lines can fuse.** The older device rewrites the line right after a line this version edited. Depending on the two devices' internal ids, the two edits can fuse into one line followed by an empty line. Measured: from `head`, `one`, `two`, `tail`, this version writes `ONE` and the older device writes `TWO`, and the result can be `head`, `TWOONE`, an empty line, `tail`. Two older devices give `head`, `ONE`, `TWO`, `tail`.
|
|
27
|
+
- **Leftover text moves.** The older device edits a line this version deletes. Its leftover text joins a neighbouring line.
|
|
28
|
+
- **Its own diff touches other lines.** The older device's character merge crosses into a line its user did not edit. This also happens between two older devices.
|
|
29
|
+
- Two older devices keep their old character merge until they update. ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
30
|
+
- Memory sync: the push phase of a large memory set no longer needs memory in proportion to the whole set. Every push step used to re-read and re-write one journal file holding every pending item's data, several times per batch. A device pushing a few thousand memory files therefore peaked at 2 GiB or more (#12286). The journal now keeps a small index of pending items with their data in separate files, and a push reads only the batch it is sending. Capturing the set before the push still holds each captured file's text until the capture ends. A journal written by an older build is converted the first time it is read, including one where an older build added items next to the new index. ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
31
|
+
- Memory sync: a device receiving a large memory set no longer slows down with every file it lands. The render step used to re-read every render record of the cycle for each file, so the first pull of a few thousand memory files took tens of minutes (#12285). Each file now costs the same, and the crash-resume behavior is unchanged. ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
32
|
+
- Memory git no longer takes `core.hooksPath`, `core.fsmonitor`, `include.path` or `includeIf.*.path` from an inherited `GIT_CONFIG_COUNT` pair or `GIT_CONFIG_PARAMETERS` entry, so an exported pair such as `core.hooksPath=/dev/null` can no longer silently skip the memory repository's hooks and mirror push. Every other injected pair (`url.*.insteadOf`, `http.extraHeader`, credentials, `safe.directory`, ...) still applies, renumbered; an injected list git itself cannot parse is dropped whole. Memory git also no longer inherits repository redirection (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR`, `GIT_OBJECT_DIRECTORY`, `GIT_NAMESPACE`, `GIT_CONFIG`, ...), so it can no longer be pointed at another repository; `GIT_INDEX_FILE`, `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_NOSYSTEM` are kept. ([#12360](https://github.com/code-yeongyu/oh-my-openagent/pull/12360), fixes [#12354](https://github.com/code-yeongyu/oh-my-openagent/issues/12354)) ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
33
|
+
- Memory sync no longer stops every push from a device when one memory file's change is larger than the 8 MiB batch limit: that file is held back and named in the sync status with what to do, every other memory keeps syncing, and the file syncs on its own once it fits. A change another device makes to a held file is kept and lands in this device's copy once the file fits, and a change an older build had already queued for such a file is recovered the same way instead of staying stuck. The TUI footer shows ` sync held` and the notice says the file is being held back, and a refused entry that pauses sync is never hidden behind a held file. ([#12284](https://github.com/code-yeongyu/oh-my-openagent/issues/12284)) ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
34
|
+
- Opening a memory repository starts up to six fewer git processes: the local config defaults are read with one `git config --list` instead of one `git config --get` per key, and the line-ending repair is skipped while the repository tracks nothing. Every session that opens memory pays this, and on a loaded machine each git process costs hundreds of milliseconds. memory-core's own tests now run under the canonical 20 s test budget instead of per-file 5-15 s limits, which made them fail only on busy hosts. ([#12104](https://github.com/code-yeongyu/oh-my-openagent/pull/12104), fixes [#12103](https://github.com/code-yeongyu/oh-my-openagent/issues/12103)) ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
35
|
+
- `thread_send` no longer reports a message as `queued` when nothing will ever pick it up. When the target thread's session has no running drain, the send now answers `queued_offline`: the message is kept and the session takes it the next time it runs, so a caller knows no turn started and can act instead of waiting. The drain also reports a message it is holding behind the user's unsent draft, so a live drain is never mistaken for a missing one. ([#12488](https://github.com/code-yeongyu/oh-my-openagent/pull/12488), fixes [#12486](https://github.com/code-yeongyu/oh-my-openagent/issues/12486))
|
|
36
|
+
- Verify recursive removal (sync and async) actually removed its path, retry bounded silent leftovers, and join sweep-test removers before deleting their fixture parents. ([#11834](https://github.com/code-yeongyu/oh-my-openagent/pull/11834))
|
|
37
|
+
|
|
38
|
+
### Added
|
|
39
|
+
|
|
40
|
+
- Windows releases now carry `omo-git-job-helper.exe`, a small native helper that runs each memory git command inside its own kill-on-close job object, so a later writer can prove that a killed writer's git is gone before it reclaims a stranded lock. Nothing uses the helper yet: memory-core keeps today's Windows behavior until a follow-up wires it in, and no release claims the new protocol until its in-flight-creation stress row has passed on Windows CI. ([#12105](https://github.com/code-yeongyu/oh-my-openagent/pull/12105), part of [#10391](https://github.com/code-yeongyu/oh-my-openagent/issues/10391)) ([#12597](https://github.com/code-yeongyu/oh-my-openagent/pull/12597))
|
|
41
|
+
|
|
10
42
|
## [5.1.63] - 2026-11-07
|
|
11
43
|
|
|
12
44
|
**The macOS keychain helper's lookup paths and tests are correct on Windows CI.** The macOS install locations (the OmO.app runtime and helper copies) are built with POSIX separators on every host, and the #11262 keychain-helper tests use platform-correct paths, so dev's Windows test legs pass again. ([#12690](https://github.com/code-yeongyu/oh-my-openagent/pull/12690), part of [#11262](https://github.com/code-yeongyu/oh-my-openagent/issues/11262))
|