docks-kit 0.26.0 → 0.27.0
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/AGENTS.md +7 -5
- package/README.md +17 -27
- package/cli/dist/docks-kit.js +54 -41
- package/cli/docs/command-guards.md +7 -4
- package/cli/docs/install.md +18 -29
- package/cli/docs/overview.md +3 -3
- package/cli/docs/platforms.md +8 -8
- package/cli/src/commands/update.ts +4 -39
- package/cli/src/engine-native/DESIGN.md +10 -9
- package/cli/src/engine-native/os/targets.ts +6 -19
- package/cli/src/engine.ts +0 -6
- package/cli/src/generated/sotPayload.ts +3 -3
- package/cli/src/kitHome.ts +7 -10
- package/cli/src/main.ts +0 -1
- package/cli/src/plan/checkout.ts +69 -31
- package/docks-kit +9 -40
- package/docks-kit.ps1 +10 -61
- package/package.json +4 -5
package/cli/dist/docks-kit.js
CHANGED
|
@@ -406,7 +406,7 @@ ${annotate2(colors,"Wizard cancelled.",red)}`,renderCommandBlock=(label,commandL
|
|
|
406
406
|
`)?"line feed (LF)":void 0;if(unsupported===void 0)return;let executablePercentHint=kind==="executable path"&&unsupported==="percent sign (%)"?" The tool must be reached through its .exe or moved out of a directory whose name contains a percent sign.":"";throw Error(`${kind} ${JSON.stringify(value)} contains a ${unsupported}, which cannot be escaped on a cmd command line; the caller must pass the value another way.${executablePercentHint}`)}function commandInterpreter(environment=process.env){let comSpec=environment.ComSpec??"";if(win322.isAbsolute(comSpec))return comSpec;let systemRoot=environment.SystemRoot??"",root=win322.isAbsolute(systemRoot)?systemRoot:"C:\\Windows";return win322.join(root,"System32","cmd.exe")}function commandShimInvocation(executablePath,args){assertCommandLineValue(executablePath,"executable path");for(let arg of args)assertCommandLineValue(arg,"argument");let normalizedPath=win322.normalize(executablePath),commandLine=[escapeCommand(normalizedPath),...args.map(escapeArgument)].join(" ");return{command:commandInterpreter(),args:["/d","/v:off","/s","/c",`"${commandLine}"`],windowsVerbatimArguments:!0}}var windows={id:"windows",toolchainOs:"windows",executableSuffixes:[".exe",".cmd",".bat",""],invoke:(executablePath,args)=>/\.(?:cmd|bat)$/i.test(executablePath)?commandShimInvocation(executablePath,args):{command:executablePath,args},bunExecutableName:"bun.exe",bunInstaller:(pin,directory)=>{let scriptPath=p(directory,"install.ps1");return{scriptPath,download:{command:"curl",args:["-fsSL","https://bun.sh/install.ps1","-o",scriptPath]},run:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",scriptPath,"-Version",pin]}}},installHint:(tool)=>{switch(tool){case"git":return"winget install --id Git.Git -e";case"jq":return"winget install --id jqlang.jq -e";case"curl":return"winget install --id cURL.cURL -e"}}};function rawPlatform(){return process.platform}function platformName(pf=rawPlatform()){switch(pf){case"linux":return"linux";case"darwin":return"darwin";case"win32":return"windows";default:return"unknown"}}var unknown2={...linux,id:"unknown",toolchainOs:""},HOSTS={linux,darwin,windows,unknown:unknown2};function hostOs(id=platformName()){return HOSTS[id]}var notFound2=(command)=>({pid:0,output:[],stdout:"",stderr:"",status:null,signal:null,error:Error(`command not found on PATH: ${command}`)}),spawnHost=(command,args,overrides={},host=hostOs())=>{let executablePath=host.executableSuffixes.some((suffix)=>suffix!=="")?which(command,host.executableSuffixes):command;if(executablePath==="")return notFound2(command);let invocation;try{invocation=host.invoke(executablePath,args)}catch(cause){return process.stderr.write(`${cause instanceof Error?cause.message:String(cause)}
|
|
407
407
|
`),process.exit(2)}let options={stdio:["ignore","pipe","pipe"],...overrides,encoding:"utf8",windowsVerbatimArguments:invocation.windowsVerbatimArguments};return spawnSync(invocation.command,[...invocation.args],options)};function p(...parts){return parts.join("/")}function processFailureSummary(result){let lines=[...result.stdout.split(`
|
|
408
408
|
`),...result.stderr.split(`
|
|
409
|
-
`)].map((line)=>line.trim()).filter((line)=>line!==""),[first,...rest]=lines;if(first===void 0)return result.error?.message??"unknown error";let cause=rest.find((line)=>/^(fatal|error):/i.test(line))??rest.at(-1);return cause===void 0?first:`${first} | ${cause}`}function spawnProcess(cmd,args,options={}){let{promise,resolve}=Promise.withResolvers(),host=options.host??hostOs(),executablePath=host.executableSuffixes.some((suffix)=>suffix!=="")?which(cmd,host.executableSuffixes):cmd;if(executablePath==="")return resolve({exitCode:null,stdout:"",stderr:"",error:Error(`command not found on PATH: ${cmd}`)}),promise;let child;try{let invocation=host.invoke(executablePath,args);child=spawn2(invocation.command,[...invocation.args],{stdio:options.stdio??["ignore","pipe","ignore"],...options.cwd!==void 0?{cwd:options.cwd}:{},...options.env!==void 0?{env:options.env}:{},...options.timeoutMs!==void 0&&!WINDOWS_PROCESS?{detached:!0}:{},windowsVerbatimArguments:invocation.windowsVerbatimArguments})}catch(cause){let error=cause instanceof Error?cause:Error(String(cause));return resolve({exitCode:null,stdout:"",stderr:"",error}),promise}let stdout="",stderr="",error;if(child.stdout!==null)child.stdout.setEncoding("utf8"),child.stdout.on("data",(chunk)=>{stdout+=chunk}),child.stdout.on("error",(cause)=>{error??=cause});if(child.stderr!==null)child.stderr.setEncoding("utf8"),child.stderr.on("data",(chunk)=>{stderr+=chunk}),child.stderr.on("error",(cause)=>{error??=cause});if(child.once("error",(cause)=>{error??=cause}),options.timeoutMs!==void 0)trackBoundedChild(child);let timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{killProcessTree(child),boundedChildren.delete(child),child.stdout?.destroy(),child.stderr?.destroy(),child.unref(),resolve({exitCode:null,stdout,stderr,timedOut:!0})},options.timeoutMs);return child.once("close",(exitCode)=>{clearTimeout(timer),boundedChildren.delete(child),resolve({exitCode,stdout,stderr,...error!==void 0?{error}:{}})}),promise}var WINDOWS_PROCESS=process.platform==="win32",boundedChildren=new Set,exitHandlerInstalled=!1;function trackBoundedChild(child){if(boundedChildren.add(child),exitHandlerInstalled)return;exitHandlerInstalled=!0,process.once("exit",()=>{for(let running of boundedChildren)killProcessTree(running)})}function killProcessTree(child){let pid=child.pid;if(pid===void 0)return;if(WINDOWS_PROCESS){if(child.exitCode!==null||child.signalCode!==null)return;let taskkill=`${process.env.SystemRoot??"C:\\Windows"}\\System32\\taskkill.exe`;spawnSync(taskkill,["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});return}try{process.kill(-pid,"SIGKILL")}catch{child.kill("SIGKILL")}}async function capture(cmd,args){let res=await spawnProcess(cmd,args,{stdio:["ignore","pipe","ignore"]});if(res.error!==void 0||res.exitCode!==0)return"";return res.stdout.replace(/[\r\n]+$/,"")}async function captureWithin(cmd,args,timeoutMs){let res=await spawnProcess(cmd,args,{stdio:["ignore","pipe","ignore"],timeoutMs});if(res.timedOut===!0)return{kind:"timed-out"};if(res.error!==void 0||res.exitCode!==0)return{kind:"failed"};return{kind:"output",stdout:res.stdout.replace(/[\r\n]+$/,"")}}function windowsPathEntries(path){let entries=[],entry="",quoted=!1;for(let char of path){if(char==='"')quoted=!quoted;if(char===";"&&!quoted)entries.push(entry),entry="";else entry+=char}return entries.push(entry),entries.map((value)=>/^".*"$/.test(value)?value.slice(1,-1):value)}function which(name,suffixes=hostOs().executableSuffixes){let runnableCandidate=(base)=>{for(let suffix of suffixes){let candidate=`${base}${suffix}`;if(isExecutable(candidate,suffixes))return candidate}return""};if(isAbsolute2(name)||name.includes("/"))return runnableCandidate(name);let path=process.env.PATH??"",windowsRules=suffixes.some((suffix)=>suffix!=="");for(let dir of windowsRules?windowsPathEntries(path):path.split(delimiter)){if(dir==="")continue;let candidate=runnableCandidate(join4(dir,name));if(candidate!=="")return candidate}return""}function commandExists(name){return which(name)!==""}function isExecutable(path,suffixes=hostOs().executableSuffixes){try{if(!statSync(path).isFile())return!1;if(suffixes.some((suffix)=>suffix!=="")){let lowerPath=path.toLowerCase();return suffixes.some((suffix)=>suffix===""?extname(path)==="":lowerPath.endsWith(suffix.toLowerCase()))}return accessSync(path,constants2.X_OK),!0}catch{return!1}}import{homedir}from"os";import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync}from"fs";import{DatabaseSync}from"node:sqlite";var GENERATED_PACKAGE_VERSION="0.
|
|
409
|
+
`)].map((line)=>line.trim()).filter((line)=>line!==""),[first,...rest]=lines;if(first===void 0)return result.error?.message??"unknown error";let cause=rest.find((line)=>/^(fatal|error):/i.test(line))??rest.at(-1);return cause===void 0?first:`${first} | ${cause}`}function spawnProcess(cmd,args,options={}){let{promise,resolve}=Promise.withResolvers(),host=options.host??hostOs(),executablePath=host.executableSuffixes.some((suffix)=>suffix!=="")?which(cmd,host.executableSuffixes):cmd;if(executablePath==="")return resolve({exitCode:null,stdout:"",stderr:"",error:Error(`command not found on PATH: ${cmd}`)}),promise;let child;try{let invocation=host.invoke(executablePath,args);child=spawn2(invocation.command,[...invocation.args],{stdio:options.stdio??["ignore","pipe","ignore"],...options.cwd!==void 0?{cwd:options.cwd}:{},...options.env!==void 0?{env:options.env}:{},...options.timeoutMs!==void 0&&!WINDOWS_PROCESS?{detached:!0}:{},windowsVerbatimArguments:invocation.windowsVerbatimArguments})}catch(cause){let error=cause instanceof Error?cause:Error(String(cause));return resolve({exitCode:null,stdout:"",stderr:"",error}),promise}let stdout="",stderr="",error;if(child.stdout!==null)child.stdout.setEncoding("utf8"),child.stdout.on("data",(chunk)=>{stdout+=chunk}),child.stdout.on("error",(cause)=>{error??=cause});if(child.stderr!==null)child.stderr.setEncoding("utf8"),child.stderr.on("data",(chunk)=>{stderr+=chunk}),child.stderr.on("error",(cause)=>{error??=cause});if(child.once("error",(cause)=>{error??=cause}),options.timeoutMs!==void 0)trackBoundedChild(child);let timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{killProcessTree(child),boundedChildren.delete(child),child.stdout?.destroy(),child.stderr?.destroy(),child.unref(),resolve({exitCode:null,stdout,stderr,timedOut:!0})},options.timeoutMs);return child.once("close",(exitCode)=>{clearTimeout(timer),boundedChildren.delete(child),resolve({exitCode,stdout,stderr,...error!==void 0?{error}:{}})}),promise}var WINDOWS_PROCESS=process.platform==="win32",boundedChildren=new Set,exitHandlerInstalled=!1;function trackBoundedChild(child){if(boundedChildren.add(child),exitHandlerInstalled)return;exitHandlerInstalled=!0,process.once("exit",()=>{for(let running of boundedChildren)killProcessTree(running)})}function killProcessTree(child){let pid=child.pid;if(pid===void 0)return;if(WINDOWS_PROCESS){if(child.exitCode!==null||child.signalCode!==null)return;let taskkill=`${process.env.SystemRoot??"C:\\Windows"}\\System32\\taskkill.exe`;spawnSync(taskkill,["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});return}try{process.kill(-pid,"SIGKILL")}catch{child.kill("SIGKILL")}}async function capture(cmd,args){let res=await spawnProcess(cmd,args,{stdio:["ignore","pipe","ignore"]});if(res.error!==void 0||res.exitCode!==0)return"";return res.stdout.replace(/[\r\n]+$/,"")}async function captureWithin(cmd,args,timeoutMs){let res=await spawnProcess(cmd,args,{stdio:["ignore","pipe","ignore"],timeoutMs});if(res.timedOut===!0)return{kind:"timed-out"};if(res.error!==void 0||res.exitCode!==0)return{kind:"failed"};return{kind:"output",stdout:res.stdout.replace(/[\r\n]+$/,"")}}function windowsPathEntries(path){let entries=[],entry="",quoted=!1;for(let char of path){if(char==='"')quoted=!quoted;if(char===";"&&!quoted)entries.push(entry),entry="";else entry+=char}return entries.push(entry),entries.map((value)=>/^".*"$/.test(value)?value.slice(1,-1):value)}function which(name,suffixes=hostOs().executableSuffixes){let runnableCandidate=(base)=>{for(let suffix of suffixes){let candidate=`${base}${suffix}`;if(isExecutable(candidate,suffixes))return candidate}return""};if(isAbsolute2(name)||name.includes("/"))return runnableCandidate(name);let path=process.env.PATH??"",windowsRules=suffixes.some((suffix)=>suffix!=="");for(let dir of windowsRules?windowsPathEntries(path):path.split(delimiter)){if(dir==="")continue;let candidate=runnableCandidate(join4(dir,name));if(candidate!=="")return candidate}return""}function commandExists(name){return which(name)!==""}function isExecutable(path,suffixes=hostOs().executableSuffixes){try{if(!statSync(path).isFile())return!1;if(suffixes.some((suffix)=>suffix!=="")){let lowerPath=path.toLowerCase();return suffixes.some((suffix)=>suffix===""?extname(path)==="":lowerPath.endsWith(suffix.toLowerCase()))}return accessSync(path,constants2.X_OK),!0}catch{return!1}}import{homedir}from"os";import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync}from"fs";import{DatabaseSync}from"node:sqlite";var GENERATED_PACKAGE_VERSION="0.27.0",GENERATED_PAYLOAD_TEXT={"SoT/toolchain.json":'{\n "$comment": "Kit toolchain manifest - DATA only (versions, floors, policy); version probing and the doctor report live in cli/src/engine-native/toolchain.ts, and the one managed install lives in cli/src/engine-native/bun.ts bunBootstrap. kind: check (doctor visibility only) | managed (kit installs it when missing) | pin (no binary probe - a version pin for a package the kit installs through another tool, such as `omp install`; the required `via` names that tool in the doctor table). policy (managed only): present (install when missing, never upgrade). `verified` = last kit-tested version; `pinnable` marks a tool whose `verified` release the bootstrap can install by exact tag. Supply-chain stance: every kit-driven package install from npm, GitHub releases, or `omp install` is pinned to `verified` - never floating @latest (npm-worm/Shai-Hulud surface). The existing omp marketplace plugins follow their marketplace and have no pin. Any new install surface, a new marketplace or plugin source included, needs a pin first. Update `verified` after testing a new release. upstream (optional) names where `docks-kit toolchain outdated` reads the newest release: npm package or GitHub repo releases with a tag prefix; results cache 24 h in ~/.docks-kit/kit.db; the report never installs or edits pins.",\n "tools": {\n "jq": { "kind": "check", "note": "optional operator CLI; EngineNative JSON handling does not invoke it" },\n "curl": { "kind": "check", "note": "installer transport for the Bun bootstrap on every host (install.sh on POSIX, install.ps1 on Windows); probed only when Bun is missing" },\n "git": { "kind": "check", "note": "omp plugin marketplaces (omp clones them) + kit checkout updates" },\n "npm": { "kind": "check", "note": "npm-global installer; `docks-kit update` uses it for an npm-installed kit" },\n "omp": { "kind": "check", "floor": "19.0.0", "verified": "19.0.0",\n "upstream": { "github": "can1357/oh-my-pi", "tagPrefix": "v" },\n "note": "Oh My Pi harness (https://github.com/can1357/oh-my-pi); upstream-owned. It updates through `omp update` or through the external manager that owns the install (for example Tern), and sync never installs or upgrades it. The floor is the oldest release the kit tested: 19.0.0 lists every model selector of the kit roles exactly, accepts every key of SoT/.omp/config.yml, and runs the bash approval order that cli/test/lib/ompBashPatterns.ts ports. Sync needs the CLI only for the marketplace and plugin passes; the file deploys proceed without it" },\n "bun": { "kind": "managed", "policy": "present", "floor": "1.4.5", "verified": "1.4.5", "pinnable": true,\n "upstream": { "github": "oven-sh/bun", "tagPrefix": "bun-v" },\n "note": "runtime for the docks-kit CLI; bootstrap installs the verified release (installer takes bun-vX.Y.Z); self-updates via `bun upgrade` when wanted. By owner decision (2026-09-25), the floor equals the verified pin and the CI Bun, and the checkout launchers refuse an older Bun. All three moved to 1.4.5 on 2026-11-21 for its TLS, DNS, and HTTP security fixes" },\n "pi-intercom": { "kind": "pin", "via": "omp install", "verified": "0.14.0",\n "upstream": { "npm": "pi-intercom" },\n "note": "the cross-session messaging plugin ompSync installs with `omp install pi-intercom@<verified>` - pinned, never floating. Its broker runs under Bun because omp\'s flat plugin store cannot resolve the default `npx --no-install tsx` launcher" }\n }\n}\n',"SoT/.omp/AGENTS.md":`# Global OMP guidance
|
|
410
410
|
|
|
411
411
|
- Verify an unfamiliar or version-sensitive API or configuration against current official documentation before you use it.
|
|
412
412
|
- When I ask for an assessment, report the findings and do not edit.
|
|
@@ -24169,16 +24169,16 @@ CREATE TABLE cache_entry (
|
|
|
24169
24169
|
) STRICT, WITHOUT ROWID;`],KIT_DB_SCHEMA_VERSION=MIGRATIONS.length;class KitDbTooNewError extends Error{}function kitDbFile(home){return p(home,".docks-kit","kit.db")}function userVersion(db){let version=db.prepare("PRAGMA user_version").get()?.user_version;return typeof version==="number"?version:0}function inTransaction(db,fn){db.exec("BEGIN IMMEDIATE");try{let result=fn();return db.exec("COMMIT"),result}catch(error){try{db.exec("ROLLBACK")}catch{}throw error}}function tooNew(version){return new KitDbTooNewError(`~/.docks-kit/kit.db uses schema ${version}; this docks-kit knows schema ${KIT_DB_SCHEMA_VERSION}. Upgrade docks-kit (docks-kit update).`)}function migrate(db){let current=userVersion(db);if(current>KIT_DB_SCHEMA_VERSION)throw tooNew(current);if(current===KIT_DB_SCHEMA_VERSION)return!1;return inTransaction(db,()=>{let locked=userVersion(db);if(locked>KIT_DB_SCHEMA_VERSION)throw tooNew(locked);if(locked===KIT_DB_SCHEMA_VERSION)return!1;for(let sql of MIGRATIONS.slice(locked))db.exec(sql);return db.exec(`PRAGMA user_version = ${KIT_DB_SCHEMA_VERSION}`),!0})}function isNonBlankString(value){return typeof value==="string"&&value.trim()!==""}function nonBlankOrNull(value){return isNonBlankString(value)?value:null}function parseLegacySession(file){let parsed;try{parsed=JSON.parse(readFileSync(file,"utf8"))}catch{return}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return;if(!("version"in parsed)||parsed.version!==1)return;let entry="ompSession"in parsed?parsed.ompSession:void 0;if(typeof entry!=="object"||entry===null||Array.isArray(entry))return;let selector=nonBlankOrNull("selector"in entry?entry.selector:void 0);if(selector===null)return;return{selector,thinking:nonBlankOrNull("thinking"in entry?entry.thinking:void 0)}}function importLegacyState(db,legacy){inTransaction(db,()=>{if(db.prepare("SELECT count(*) AS n FROM omp_session").get()?.n!==0)return;let session=parseLegacySession(legacy);if(session===void 0)return;db.prepare("INSERT INTO omp_session (id, selector, thinking) VALUES (1, ?, ?)").run(session.selector,session.thinking)});try{renameSync(legacy,`${legacy}.migrated`)}catch(error){if((typeof error==="object"&&error!==null&&"code"in error?error.code:"")!=="ENOENT")throw error}}function withKitDb(home,access,fn){let file=kitDbFile(home),legacy=p(home,".docks-kit","state.json");if(access==="read"&&!existsSync(file)&&!existsSync(legacy))return;let directory=p(home,".docks-kit"),secure=access==="write"||!existsSync(file);if(secure)mkdirSync(directory,{recursive:!0,mode:448}),chmodSync(directory,448);let db=new DatabaseSync(file);try{if(secure&&process.platform!=="win32")chmodSync(file,384);db.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;");let migrated=migrate(db),importing=existsSync(legacy);if(importing)importLegacyState(db,legacy);let result=fn(db);if(access==="write"||migrated||importing)db.exec("PRAGMA wal_checkpoint(TRUNCATE)");return result}finally{db.close()}}var CACHE_FINGERPRINT=GENERATED_PACKAGE_VERSION;function readCache(home,key,maxAgeMs,now){try{return withKitDb(home,"read",(db)=>{let row=db.prepare("SELECT fingerprint, fetched_at, payload FROM cache_entry WHERE key = ?").get(key),fetchedAt=row?.fetched_at,payload=row?.payload;if(row?.fingerprint!==CACHE_FINGERPRINT)return;if(typeof fetchedAt!=="number"||typeof payload!=="string")return;let age=now-fetchedAt;return age>=0&&age<=maxAgeMs?payload:void 0})}catch{return}}function writeCache(home,key,payload,now){try{withKitDb(home,"write",(db)=>inTransaction(db,()=>{db.prepare("DELETE FROM cache_entry WHERE fingerprint <> ?").run(CACHE_FINGERPRINT),db.prepare(`INSERT INTO cache_entry (key, fingerprint, fetched_at, payload) VALUES (?, ?, ?, ?)
|
|
24170
24170
|
ON CONFLICT(key) DO UPDATE SET fingerprint = excluded.fingerprint, fetched_at = excluded.fetched_at, payload = excluded.payload`).run(key,CACHE_FINGERPRINT,now,payload)}))}catch{}}var DEFAULT_OMP_SESSION_MODEL={selector:"opencode-zen/muse-spark-1.3-contributor-free",thinking:"xhigh"};function engineHome(env=process.env,platform=process.platform){let home=platform==="win32"?env.USERPROFILE:env.HOME;return home!==void 0&&home!==""?home:homedir()}function readOmpSessionModel(home){try{return withKitDb(home,"read",(db)=>{let row=db.prepare("SELECT selector, thinking FROM omp_session WHERE id = 1").get(),selector=row?.selector;if(!isNonBlankString(selector))return;let thinking=row?.thinking;return{selector,...isNonBlankString(thinking)?{thinking}:{}}})}catch{return}}function writeOmpSessionModel(home,model){if(!isNonBlankString(model.selector))throw Error("Omp session model selector must be a non-empty string");let thinking=nonBlankOrNull(model.thinking);withKitDb(home,"write",(db)=>db.prepare(`INSERT INTO omp_session (id, selector, thinking) VALUES (1, ?, ?)
|
|
24171
24171
|
ON CONFLICT(id) DO UPDATE SET selector = excluded.selector, thinking = excluded.thinking`).run(model.selector,thinking))}function isObject2(v){return typeof v==="object"&&v!==null&&!Array.isArray(v)}function compareCodepoints(a,b){let ia=a[Symbol.iterator](),ib=b[Symbol.iterator]();for(;;){let ra=ia.next(),rb=ib.next();if(ra.done&&rb.done)return 0;if(ra.done)return-1;if(rb.done)return 1;let ca=ra.value.codePointAt(0),cb=rb.value.codePointAt(0);if(ca!==cb)return ca-cb}}function parseJson2(text){try{return JSON.parse(text)}catch{return}}function payloadText(path){return GENERATED_PAYLOAD_TEXT[path]}function payloadBytes(path){return Buffer.from(payloadText(path))}function payloadPaths(prefix){return GENERATED_PAYLOAD_PATHS.filter((path)=>path.startsWith(prefix))}function payloadDisplayPath(path){return`embedded:${path}`}function manifest(){let doc=parseJson2(payloadText("SoT/toolchain.json")),tools=doc!==void 0&&isObject2(doc)?doc.tools:void 0;return tools!==void 0&&isObject2(tools)?tools:{}}function field(tool,name){let entry=manifest()[tool];if(entry===void 0||!isObject2(entry))return"";let v=entry[name];return v===void 0||v===null?"":String(v)}function isNewer(a,b){if(a===""||b===""||a===b)return!1;let fa=a.split("."),fb=b.split(".");for(let i=0;i<3;i++){let na=parseInt(fa[i]??"",10)||0,nb=parseInt(fb[i]??"",10)||0;if(na!==nb)return na>nb}return compareCodepoints(a,b)>0}function belowFloor(installed,floor){return installed!==""&&floor!==""&&isNewer(floor,installed)}function present(ctx,tool){return ctx.services.deps.probe(tool).state==="present"}function firstLineField(out,index){let fields=(out.split(`
|
|
24172
|
-
`)[0]??"").trim().split(/[ \t]+/);return fields[index===-1?fields.length-1:index]??""}async function installedVersion(ctx,tool){let version=()=>ctx.services.deps.version(tool);switch(tool){case"git":return firstLineField(await version(),2);case"jq":return(await version()).replace(/^jq-/,"");case"curl":return firstLineField(await version(),1);case"bun":case"omp":case"npm":return await version();default:return""}}function row(cells){let widths=[28,9,14,9,9];return cells.map((c,i)=>i<widths.length?c.padEnd(widths[i]):c).join(" ")}async function report(ctx){let{echo}=ctx.services.logger;echo(row(["TOOL","KIND","INSTALLED","FLOOR","VERIFIED","STATUS"]));let pn=ctx.services.platform.name(),platformOs=hostOs(pn).toolchainOs;for(let tool of Object.keys(manifest()).sort(compareCodepoints)){let os=field(tool,"os");if(os!==""&&platformOs!==""&&os!==platformOs)continue;let kind=field(tool,"kind"),floor=field(tool,"floor"),verified=field(tool,"verified"),dash=(v)=>v!==""?v:"-";if(kind==="pin"){let via=field(tool,"via");echo(row([tool,kind,`(${via})`,dash(floor),dash(verified),"pinned"]));continue}let installed,status,toolId=tool;if(present(ctx,toolId)){if(installed=await installedVersion(ctx,toolId),status=installed===""?"unknown":"ok",belowFloor(installed,floor))status="below-floor";else if(verified!==""&&installed!==""&&isNewer(installed,verified))status="above-verified";installed=installed!==""?installed:"?"}else installed="-",status="missing";echo(row([tool,dash(kind),installed,dash(floor),dash(verified),status]))}}var UPSTREAM_CACHE_MS=86400000;function upstreamSpec(tool){let entry=manifest()[tool],upstream=entry!==void 0&&isObject2(entry)?entry.upstream:void 0;return upstream!==void 0&&isObject2(upstream)?upstream:void 0}function upstreamLabel(spec){let{npm,github}=spec;if(typeof npm==="string")return`npm ${npm}`;return typeof github==="string"?`github ${github}`:"-"}async function fetchJson(fetchImpl,url,headers){let response=await fetchImpl(url,{headers,signal:AbortSignal.timeout(8000)});if(response.status!==200)return{ok:!1,reason:`HTTP ${response.status}`};let body=parseJson2(await response.text());return body!==void 0&&isObject2(body)?{ok:!0,body}:{ok:!1,reason:"invalid response"}}async function lookupUpstream(spec,fetchImpl,env){let{npm,github,tagPrefix}=spec;if(typeof npm==="string"){let result=await fetchJson(fetchImpl,`https://registry.npmjs.org/${npm}/latest`,{Accept:"application/json"});if(!result.ok)return result;let version=result.body.version;return typeof version==="string"&&version!==""?{ok:!0,version}:{ok:!1,reason:"invalid response"}}if(typeof github==="string"){let headers={Accept:"application/vnd.github+json","User-Agent":"docks-kit"},token=env.GITHUB_TOKEN||env.GH_TOKEN;if(token!==void 0&&token!=="")headers.Authorization=`Bearer ${token}`;let result=await fetchJson(fetchImpl,`https://api.github.com/repos/${github}/releases/latest`,headers);if(!result.ok)return result;let tag=result.body.tag_name;if(typeof tag!=="string")return{ok:!1,reason:"invalid response"};let prefix=typeof tagPrefix==="string"?tagPrefix:"";return tag.startsWith(prefix)?{ok:!0,version:tag.slice(prefix.length)}:{ok:!1,reason:`unexpected tag ${tag}`}}return{ok:!1,reason:"no upstream in SoT/toolchain.json"}}async function latestUpstream(tool,inputs){let{home,refresh,now,fetchImpl=globalThis.fetch,env=process.env}=inputs,key=`upstream:${tool}`;if(!refresh){let cached=readCache(home,key,UPSTREAM_CACHE_MS,now);if(cached!==void 0)return{ok:!0,version:cached}}let spec=upstreamSpec(tool);if(spec===void 0)return{ok:!1,reason:"no upstream in SoT/toolchain.json"};let result;try{result=await lookupUpstream(spec,fetchImpl,env)}catch(error){result={ok:!1,reason:error instanceof Error?error.message:String(error)}}if(result.ok)writeCache(home,key,result.version,now);return result}async function outdatedReport(ctx,options){let{echo}=ctx.services.logger,tools=Object.keys(manifest()).filter((tool)=>field(tool,"verified")!==""&&upstreamSpec(tool)!==void 0),now=Date.now(),results=await Promise.all(tools.map((tool)=>latestUpstream(tool,{home:ctx.home,refresh:options.refresh,now,...options.fetchImpl!==void 0?{fetchImpl:options.fetchImpl}:{}})));return echo(row(["TOOL","KIND","VERIFIED","LATEST","STATUS","UPSTREAM"])),tools.forEach((tool,index)=>{let verified=field(tool,"verified"),result=results[index],latest="-",status;if(result.ok)latest=result.version,status=isNewer(latest,verified)?"newer":"current";else status=`lookup failed: ${result.reason}`;let label=upstreamLabel(upstreamSpec(tool)??{});echo(row([tool,field(tool,"kind"),verified,latest,status,label]))}),echo("Report only: update a verified pin after testing that release (SoT/toolchain.json)."),0}var VERSION_PROBE_LIMIT_MS=60000,spec=(id,installHint,options={})=>({id,versionArgs:["--version"],installHint,resolve:options.resolve,version:options.version});function shellWord(word){return/^[\w./:=@+-]+$/.test(word)?word:`"${word}"`}function commandLine({command,args}){return[command,...args].map(shellWord).join(" ")}function bunInstallHint(pf=rawPlatform()){let host=hostOs(platformName(pf)),pin=field("bun","verified");if(host.id==="windows"){let{download,run}=host.bunInstaller(pin,"$env:TEMP");return`${commandLine({...download,command:`${download.command}.exe`})}; if ($LASTEXITCODE -eq 0) { ${commandLine(run)} }`}let{download,run}=host.bunInstaller(pin,"$tmp");return`tmp=$(mktemp -d) && ${commandLine(download)} && ${commandLine(run)}`}var pathProbe=(id)=>(exec)=>{if(!exec.commandExists(id))return{state:"missing"};let path=exec.which(id);return path===""?{state:"present"}:{state:"present",path}},findBun=(exec)=>{let onPath=exec.which("bun");if(onPath!==""&&isAbsolute3(onPath))return{command:"bun",path:onPath};let root=process.env.BUN_INSTALL!==void 0&&process.env.BUN_INSTALL!==""?process.env.BUN_INSTALL:p(engineHome(),".bun");for(let candidate of[p(root,"bin","bun"),p(engineHome(),".bun","bin","bun")]){let found=exec.which(candidate);if(found!==""&&isAbsolute3(found))return{command:found,path:found}}return},resolveBun=(exec)=>{let bun=findBun(exec);return bun===void 0?{state:"missing"}:{state:"present",path:bun.path}},defaultProbeExecutor={commandExists,capture,captureWithin,which},DEPENDENCIES={git:spec("git",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("git")),jq:spec("jq",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("jq")),curl:spec("curl",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("curl")),npm:spec("npm",()=>"ships with Node.js \u2014 install via https://nodejs.org (or your package manager)"),omp:spec("omp",()=>"install omp from https://github.com/can1357/oh-my-pi (an existing install updates with `omp update`, or through the tool that manages it, such as Tern)",{version:async(exec)=>(await exec.capture("omp",["--version"])).trim().replace(/^omp[/v]/,"")}),bun:spec("bun",bunInstallHint,{resolve:resolveBun,version:async(exec)=>{let bun=findBun(exec);if(bun===void 0)return"";return await exec.capture(bun.command,["--version"])}})};function resolveDependency(specification,exec,platform=rawPlatform()){return(specification.resolve??pathProbe(specification.id))(exec,platform)}async function resolveVersionReading(specification,exec){if(resolveDependency(specification,exec).state!=="present")return{kind:"version",value:""};if(specification.version!==void 0)return{kind:"version",value:await specification.version(exec)};if(exec.captureWithin===void 0)return{kind:"version",value:await exec.capture(specification.id,specification.versionArgs)};let outcome=await exec.captureWithin(specification.id,specification.versionArgs,VERSION_PROBE_LIMIT_MS);if(outcome.kind==="timed-out")return outcome;return{kind:"version",value:outcome.kind==="output"?outcome.stdout:""}}async function resolveVersion(specification,exec){let reading=await resolveVersionReading(specification,exec);return reading.kind==="version"?reading.value:""}async function resolvePath(specification,exec,platform=rawPlatform()){let result=resolveDependency(specification,exec,platform);return result.state==="present"?result.path??exec.which(specification.id):""}var makePlatform=(pf=rawPlatform())=>({raw:()=>pf,name:()=>platformName(pf)}),makeDependencyManager=(platform,exec=defaultProbeExecutor)=>{let warned=new Set;return{spec:(id)=>{let s=DEPENDENCIES[id];return{...s,installHint:(pf=platform.raw())=>s.installHint(pf)}},probe:(id)=>resolveDependency(DEPENDENCIES[id],exec,platform.raw()),version:(id)=>resolveVersion(DEPENDENCIES[id],exec),versionReading:(id)=>resolveVersionReading(DEPENDENCIES[id],exec),path:(id)=>resolvePath(DEPENDENCIES[id],exec,platform.raw()),warnMissing:(id,logger,context)=>{if(warned.has(id))return;warned.add(id);let suffix=context!==void 0&&context!==""?` (${context})`:"";logger.warn(`${id} not installed \u2014 ${DEPENDENCIES[id].installHint(platform.raw())}${suffix}`)}}},makeEngineServices=(opts)=>{let platform=makePlatform();return{logger:makeLogger(opts?.sinks??{}),deps:makeDependencyManager(platform),platform}};class LoggerService extends Service()("docks-kit/Logger"){}class DependencyManagerService extends Service()("docks-kit/DependencyManager"){}class PlatformService extends Service()("docks-kit/Platform"){}var live=makeEngineServices(),LoggerLive=succeed5(LoggerService,live.logger),DependencyManagerLive=succeed5(DependencyManagerService,live.deps),PlatformLive=succeed5(PlatformService,live.platform),EngineServicesLive=mergeAll2(LoggerLive,DependencyManagerLive,PlatformLive);import{readFileSync as readFileSync2}from"fs";import{dirname as dirname2,join as join5,resolve as resolve4}from"path";var isKitHome=(dir)=>{try{return JSON.parse(readFileSync2(join5(dir,"package.json"),"utf8")).name==="docks-kit"}catch{return!1}},explicitKitHome=(dir,source)=>{let packageJson=join5(dir,"package.json"),text;try{text=readFileSync2(packageJson,"utf8")}catch(error){let code=typeof error==="object"&&error!==null&&"code"in error?String(error.code):void 0;if(code==="ENOENT")throw Error(`DOCKS_KIT_HOME=${source} does not contain package.json`,{cause:error});let detail=error instanceof Error?error.message:String(error),category=code===void 0?"":` (${code})`;throw Error(`DOCKS_KIT_HOME=${source} package.json cannot be read${category}: ${detail}`,{cause:error})}let manifest;try{manifest=JSON.parse(text)}catch(error){let detail=error instanceof Error?error.message:String(error);throw Error(`DOCKS_KIT_HOME=${source} package.json contains invalid JSON: ${detail}`,{cause:error})}if(typeof manifest!=="object"||manifest===null||!("name"in manifest)||manifest.name!=="docks-kit")throw Error(`DOCKS_KIT_HOME=${source} is not a docks-kit package root (package.json name must be "docks-kit")`);return dir},findKitHome=(start)=>{if(start===void 0||start==="")return;let dir=resolve4(start);for(;;){if(isKitHome(dir))return dir;let parent=dirname2(dir);if(parent===dir)return;dir=parent}},resolveKitHome=(sources)=>{if(sources.env!==void 0&&sources.env!=="")return explicitKitHome(resolve4(sources.env),sources.env);return findKitHome(sources.moduleDir)??findKitHome(dirname2(sources.execPath))??findKitHome(sources.cwd)??dirname2(sources.execPath)},kitHome=()=>resolveKitHome({env:process.env.DOCKS_KIT_HOME,moduleDir:import.meta.dir,execPath:process.execPath,cwd:process.cwd()});function makeCtx(services,options){let env=process.env,home=engineHome(env),globals=options.envGlobals?env:{};return{repoDir:kitHome(),home,dryRun:globals.DRY_RUN==="1",verbose:globals.DOCKS_KIT_VERBOSE==="1",skipPluginRefresh:!1,services,nextStepTriggers:{ompRestart:!1},failures:[]}}import{mkdtempSync,rmSync}from"fs";import{tmpdir as tmpdir2}from"os";function predictedExecutable(ctx,host=hostOs()){let root=process.env.BUN_INSTALL!==void 0&&process.env.BUN_INSTALL!==""?process.env.BUN_INSTALL:p(ctx.home,".bun");return p(root,"bin",host.bunExecutableName)}function processFailure(result){return[result.error?.message,result.stderr.trim()].filter((value)=>value!==void 0&&value!=="").join(": ")||(result.exitCode===null?"the process ended without an exit code":`exit code ${result.exitCode}`)}async function installBun(pin,directory,host=hostOs()){let options={stdio:["ignore","ignore","pipe"]},installer=host.bunInstaller(pin,directory),download=await spawnProcess(installer.download.command,installer.download.args,options);if(download.error!==void 0||download.exitCode!==0)return{ok:!1,reason:"download-failed",detail:processFailure(download)};let install=await spawnProcess(installer.run.command,installer.run.args,options);if(install.error!==void 0||install.exitCode!==0)return{ok:!1,reason:"installer-failed",detail:processFailure(install)};return{ok:!0}}function bunBootstrap(ctx,services){if(ctx.bunRuntime!==void 0)return ctx.bunRuntime;let pending=runBunBootstrap(ctx,services);return ctx.bunRuntime=pending,pending}async function runBunBootstrap(ctx,services){let host=hostOs(services.platform.name()),existing=await services.deps.path("bun");if(existing!=="")return{kind:"ready",executable:existing};let pin=field("bun","verified");if(pin==="")return services.logger.warn("Bun bootstrap aborted \u2014 SoT/toolchain.json has no verified Bun pin"),{kind:"deferred",reason:"install-failed"};if(services.deps.probe("curl").state==="missing")return services.deps.warnMissing("curl",services.logger,"cannot bootstrap Bun; install Bun manually, then re-run sync"),{kind:"deferred",reason:"missing-curl"};if(ctx.dryRun){let executable=predictedExecutable(ctx,host);return services.logger.echo(`[dry-run] install Bun ${pin} (kit-verified) -> ${executable}`),{kind:"ready",executable}}services.logger.warn(`Bun not found \u2014 installing Bun ${pin} (kit-verified)...`);let temporaryDir=mkdtempSync(p(tmpdir2(),"docks-kit-bun-")),result;try{result=await installBun(pin,temporaryDir,host)}finally{rmSync(temporaryDir,{recursive:!0,force:!0})}if(!result.ok){let stage=result.reason==="download-failed"?"installer download":"installer";return services.logger.warn(`Bun ${stage} failed (${result.detail}). Install Bun manually from https://bun.sh/docs/installation, then re-run sync.`),{kind:"deferred",reason:result.reason}}let installed=await services.deps.path("bun");if(installed==="")return services.logger.warn("Bun install failed. Install manually from https://bun.sh/docs/installation, then re-run sync."),{kind:"deferred",reason:"install-failed"};let version=await services.deps.version("bun");return services.logger.change(`Bun installed (${version!==""?version:"version unknown"})`),{kind:"ready",executable:installed}}var TOOLCHAIN_USAGE="Usage: toolchain [check|ensure <tool> [--dry-run]|outdated [--refresh]]";async function modeToolchain(ctx,args){let{echo,err,verbose,warn}=ctx.services.logger,words=args.filter((arg)=>!arg.startsWith("--")),op=words[0]??"check",tool=words[1]??"";for(let arg of args)if(arg==="--verbose")ctx.verbose=!0;else if(arg==="--dry-run")ctx.dryRun=!0;if(words.length>(op==="ensure"?2:1))return err(TOOLCHAIN_USAGE),2;if(op==="check")return await report(ctx),0;if(op==="outdated")return await outdatedReport(ctx,{refresh:args.includes("--refresh")}),0;if(op!=="ensure")return err(TOOLCHAIN_USAGE),2;if(tool==="")return err("Usage: toolchain ensure <tool>"),2;switch(tool){case"bun":{let alreadyInstalled=present(ctx,"bun");if((await bunBootstrap(ctx,ctx.services)).kind!=="ready")return 1;if(alreadyInstalled){let probed=await installedVersion(ctx,"bun"),floor=field("bun","floor"),label=probed===""?"version unknown":probed;if(belowFloor(probed,floor))warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`);else if(ctx.dryRun)echo(`[dry-run] bun present (${label})`);else verbose(`bun present (${label})`)}return 0}default:return err("toolchain ensure supports managed tools only (bun)"),2}}class ExitError extends Error{code;constructor(code){super(`exit ${code}`);this.code=code}}function printUsage(ctx){let{echo}=ctx.services.logger,argv0="docks-kit sync";echo("Usage: docks-kit sync [flags]"),echo(""),echo("Global flags"),echo(" --dry-run preview without applying"),echo(" --skip-plugin-refresh install missing plugins but skip refresh-only updates"),echo(" --verbose also print no-op confirmations (already in sync, up to date, left as-is)")}function parseArgs2(ctx,args){let{err}=ctx.services.logger;for(let arg of args)switch(arg){case"--dry-run":ctx.dryRun=!0;continue;case"--skip-plugin-refresh":ctx.skipPluginRefresh=!0;continue;case"--verbose":ctx.verbose=!0;continue;case"-h":case"--help":throw printUsage(ctx),new ExitError(0);default:throw err(`Unknown arg: ${arg}`),new ExitError(2)}}import{existsSync as existsSync8,mkdirSync as mkdirSync5,realpathSync as realpathSync4}from"fs";import{basename as basename3,dirname as dirname6,join as join8}from"path";import{chmodSync as chmodSync2,mkdirSync as mkdirSync2}from"fs";import{dirname as dirname3}from"path";import{DatabaseSync as DatabaseSync2}from"node:sqlite";import{setTimeout as sleepMs}from"timers/promises";var POLL_MS=50,SQLITE_BUSY=5,heldConnections=new Set;function isBusy(cause){if(typeof cause!=="object"||cause===null||!("errcode"in cause))return!1;return typeof cause.errcode==="number"&&(cause.errcode&255)===SQLITE_BUSY}function tryBegin(connection){try{return connection.exec("BEGIN IMMEDIATE"),!0}catch(cause){if(isBusy(cause))return!1;throw cause}}async function acquireKitLock(path,options){let now=options.now??Date.now,sleep=options.sleep??((ms)=>sleepMs(ms)),pollMs=options.pollMs??POLL_MS,deadline=now()+options.waitMs;if(options.privateDirectory!==!1){let directory=dirname3(path);mkdirSync2(directory,{recursive:!0,mode:448}),chmodSync2(directory,448)}let connection=new DatabaseSync2(path);try{connection.exec("PRAGMA busy_timeout = 0");for(;;){if(tryBegin(connection))return heldConnections.add(connection),{kind:"acquired",lock:{path,connection}};let remaining=deadline-now();if(remaining<=0)break;await sleep(Math.min(pollMs,remaining))}}catch(cause){throw connection.close(),cause}return connection.close(),{kind:"held"}}function releaseKitLock(lock){heldConnections.delete(lock.connection);try{lock.connection.exec("ROLLBACK")}finally{lock.connection.close()}}import{isAbsolute as isAbsolute5,resolve as resolve7}from"path";function recordFailure(ctx,message){ctx.failures.push(message),ctx.services.logger.warn(message)}import{existsSync as existsSync2}from"fs";import{resolve as resolve5}from"path";var DEFAULT_CONFIG_DIR_NAME=".omp",APP_NAME="omp",PROFILE_NAME_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,WINDOWS_RESERVED_BASENAME_RE=/^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/i;function normalizeProfile(value){let name=value?.trim();if(name===void 0||name===""||name==="default")return;if(name==="."||name===".."||name.endsWith("."))return;if(!PROFILE_NAME_RE.test(name)||WINDOWS_RESERVED_BASENAME_RE.test(name))return;return name}function ompPaths({home,env,platform}){let profile=normalizeProfile(env.OMP_PROFILE!==void 0?env.OMP_PROFILE:env.PI_PROFILE),configDirName=env.PI_CONFIG_DIR,baseRoot=p(home,configDirName!==void 0&&configDirName!==""?configDirName:DEFAULT_CONFIG_DIR_NAME),configRoot=profile===void 0?baseRoot:p(baseRoot,"profiles",profile),agentOverride=env.PI_CODING_AGENT_DIR,defaultAgentDir=p(configRoot,"agent"),legacyProfile=normalizeProfile(env.PI_PROFILE),overrideIgnored=profile===void 0&&legacyProfile!==void 0&&agentOverride===p(baseRoot,"profiles",legacyProfile,"agent"),resolvedOverride=profile===void 0&&!overrideIgnored&&agentOverride!==void 0&&agentOverride!==""?resolve5(agentOverride):void 0,agentDir=resolvedOverride===void 0||resolvedOverride===resolve5(defaultAgentDir)?defaultAgentDir:resolvedOverride;return{profile,configRoot,agentDir,dataRoot:xdgDataRoot(env,platform,profile,agentDir===defaultAgentDir)??configRoot}}function xdgDataRoot(env,platform,profile,agentDirIsDefault){if(!agentDirIsDefault)return;if(platform!=="linux"&&platform!=="darwin")return;let dataHome=env.XDG_DATA_HOME;if(dataHome===void 0||dataHome==="")return;let appRoot=p(dataHome,APP_NAME),candidate=profile===void 0?appRoot:p(appRoot,"profiles",profile);return existsSync2(candidate)?candidate:void 0}var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,{YAMLError:$YAMLError,YAMLParseError:$YAMLParseError,YAMLWarning:$YAMLWarning}=errors,$Alias=Alias.Alias,{isAlias:$isAlias,isCollection:$isCollection,isDocument:$isDocument,isMap:$isMap,isNode:$isNode,isPair:$isPair,isScalar:$isScalar,isSeq:$isSeq}=identity2,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,{parse:$parse,parseAllDocuments:$parseAllDocuments,parseDocument:$parseDocument,stringify:$stringify}=publicApi,{visit:$visit,visitAsync:$visitAsync}=visit;var fallbackChainsPath=["retry","fallbackChains"];function stringKey(key){if(typeof key==="string")return key;if($isScalar(key)&&typeof key.value==="string")return key.value;return}function keyName(key){return $isScalar(key)?String(key.value):String(key)}var dropFallbackWildcard=(path,key)=>path.length===fallbackChainsPath.length&&path[0]===fallbackChainsPath[0]&&path[1]===fallbackChainsPath[1]&&key.includes("/"),keepEveryKey=()=>!1,keepSotSequence=()=>{};function bashRuleKey(match,approval){return`${approval.trim().toLowerCase()}\x00${match.trim().replace(/\s+/gu," ")}`}function bashPatternKey(node){if(!$isMap(node))return;let match=node.get("match"),approval=node.get("approval");if(typeof match!=="string"||typeof approval!=="string")return;return bashRuleKey(match,approval)}var mergeBashPatterns=(path,sotSeq,deployedSeq)=>{if(path.length!==2||path[0]!=="bash"||path[1]!=="patterns")return;let kitKeys=new Set(sotSeq.items.map(bashPatternKey)),kit={deny:[],prompt:[],allow:[]},user={deny:[],prompt:[],other:[]};for(let item of sotSeq.items){let approval=bashPatternKey(item)?.split("\x00")[0];kit[approval==="deny"||approval==="prompt"?approval:"allow"].push(item)}for(let item of deployedSeq.items){let key=bashPatternKey(item);if(key!==void 0&&kitKeys.has(key))continue;let approval=key?.split("\x00")[0];user[approval==="deny"||approval==="prompt"?approval:"other"].push(item)}sotSeq.items=[...kit.deny,...user.deny,...user.prompt,...kit.prompt,...user.other,...kit.allow]};function pruneMapping(mapping,path,drop){for(let index=mapping.items.length-1;index>=0;index--){let pair=mapping.items[index];if(pair===void 0)continue;if(drop(path,keyName(pair.key))){mapping.items.splice(index,1);continue}let key=stringKey(pair.key);if(key!==void 0&&$isMap(pair.value))pruneMapping(pair.value,[...path,key],drop)}}function mergeMappings(sotMapping,deployedMapping,path,drop,mergeSequence){for(let sotPair of sotMapping.items){let key=stringKey(sotPair.key);if(key===void 0)continue;let deployedPair=deployedMapping.items.find((candidate)=>stringKey(candidate.key)===key);if(deployedPair!==void 0&&$isMap(sotPair.value)&&$isMap(deployedPair.value))mergeMappings(sotPair.value,deployedPair.value,[...path,key],drop,mergeSequence);if(deployedPair!==void 0&&$isSeq(sotPair.value)&&$isSeq(deployedPair.value))mergeSequence([...path,key],sotPair.value,deployedPair.value)}for(let deployedPair of deployedMapping.items){let key=stringKey(deployedPair.key);if(key!==void 0&&sotMapping.items.some((candidate)=>stringKey(candidate.key)===key))continue;if(drop(path,keyName(deployedPair.key)))continue;if(key!==void 0&&$isMap(deployedPair.value))pruneMapping(deployedPair.value,[...path,key],drop);sotMapping.items.push(deployedPair)}}function mergeYamlDocuments(sotText,deployedText,name,drop,mergeSequence){let deployedDoc=$parseDocument(deployedText),deployedError=deployedDoc.errors[0];if(deployedError!==void 0)throw Error(`Invalid deployed omp ${name} YAML: ${deployedError.message}`);let deployedContents=deployedDoc.contents;if(deployedContents===null||deployedContents===void 0||$isScalar(deployedContents)&&deployedContents.value===null)return sotText;if(!$isMap(deployedContents))throw Error(`Deployed omp ${name} YAML root must be a mapping`);let sotDoc=$parseDocument(sotText),sotError=sotDoc.errors[0];if(sotError!==void 0)throw Error(`Invalid SoT omp ${name} YAML: ${sotError.message}`);if(!$isMap(sotDoc.contents))throw Error(`SoT omp ${name} YAML root must be a mapping`);return mergeMappings(sotDoc.contents,deployedContents,[],drop,mergeSequence),sotDoc.toString()}function mergeOmpConfig(sotText,deployedText){return mergeYamlDocuments(sotText,deployedText,"config.yml",dropFallbackWildcard,mergeBashPatterns)}function mergeOmpModels(sotText,deployedText){return mergeYamlDocuments(sotText,deployedText,"models.yml",keepEveryKey,keepSotSequence)}import{chmodSync as chmodSync4,copyFileSync,existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"fs";import{basename as basename2}from"path";import{createHash,randomBytes as randomBytes2}from"crypto";import{chmodSync as chmodSync3,existsSync as existsSync3,lstatSync,readdirSync,readFileSync as readFileSync3,readlinkSync,realpathSync,renameSync as renameSync2,statSync as statSync2,unlinkSync,writeFileSync}from"fs";import{basename,dirname as dirname4,join as join6,resolve as resolve6}from"path";function processExited(pid){try{return process.kill(pid,0),!1}catch(cause){return typeof cause==="object"&&cause!==null&&"code"in cause&&cause.code==="ESRCH"}}var MAX_NAME_BYTES=255,TEMPORARY_NAME=/^(.+)\.([1-9][0-9]*)\.[0-9a-f]{16}\.tmp$/,SHORT_TARGET=/^\.([0-9a-f]{16})$/;function writeTarget(target){let isLink;try{isLink=lstatSync(target).isSymbolicLink()}catch{return target}if(!isLink)return target;try{return realpathSync(target)}catch{return resolve6(dirname4(target),readlinkSync(target))}}function permissionBits(file){try{return statSync2(file).mode&511}catch{return}}function nameTag(name){return createHash("sha256").update(name).digest("hex").slice(0,16)}function temporaryPath(file){let unique=randomBytes2(8).toString("hex"),long=`${file}.${process.pid}.${unique}.tmp`;if(Buffer.byteLength(basename(long))<=MAX_NAME_BYTES)return long;return join6(dirname4(file),`.${nameTag(basename(file))}.${process.pid}.${unique}.tmp`)}function parseTemporaryName(entry){let match=TEMPORARY_NAME.exec(entry);if(match===null)return;let[,target="",digits=""]=match,pid=Number(digits);if(!Number.isSafeInteger(pid))return;let short=SHORT_TARGET.exec(target);return{target:short===null?{kind:"name",name:target}:{kind:"tag",tag:short[1]??""},pid}}function isRegularFile(path){try{return lstatSync(path).isFile()}catch{return!1}}function removeStaleTemporaries(dir,owns){let entries;try{entries=readdirSync(dir)}catch{return}for(let entry of entries){let parsed=parseTemporaryName(entry);if(parsed===void 0||parsed.pid===process.pid||!owns(parsed.target))continue;let path=join6(dir,entry);if(!isRegularFile(path)||!processExited(parsed.pid))continue;try{unlinkSync(path)}catch{}}}function removeStaleTemporariesOf(file){let name=basename(file),tag=nameTag(name);removeStaleTemporaries(dirname4(file),(target)=>target.kind==="name"?target.name===name:target.tag===tag)}function errorSyscall(error){return typeof error==="object"&&error!==null&&"syscall"in error?error.syscall:void 0}function removeTemporary(path){try{unlinkSync(path)}catch{}}function replaceFile(target,content,options={}){let file=writeTarget(target),mode=options.mode??permissionBits(file),temporary=temporaryPath(file);try{if(writeFileSync(temporary,content,mode===void 0?{flag:"wx"}:{flag:"wx",mode}),mode!==void 0)chmodSync3(temporary,mode);renameSync2(temporary,file)}catch(error){if(errorSyscall(error)!=="open")removeTemporary(temporary);throw error}removeStaleTemporariesOf(file)}function ensureDirectory(directory){mkdirSync3(directory,{recursive:!0,mode:448}),chmodSync4(directory,448)}function writePrivateFile(target,content){writeFileSync2(target,content,{mode:384}),chmodSync4(target,384)}function backupPrivateFile(target){copyFileSync(target,`${target}.bak`),chmodSync4(`${target}.bak`,384)}function syncWholeFile(ctx,sourcePath,target,alreadyMessage,syncedMessage){let{change,echo,verbose}=ctx.services.logger,source=payloadDisplayPath(sourcePath),content=payloadText(sourcePath);if(ctx.dryRun){echo(`[dry-run] cp ${source} -> ${target}`);return}if(existsSync4(target)&&readFileSync4(target,"utf8")===content){verbose(alreadyMessage);return}if(existsSync4(target))backupPrivateFile(target);writePrivateFile(target,content),change(syncedMessage),ctx.nextStepTriggers.ompRestart=!0}function syncMergedYaml(ctx,sourcePath,target,merge){let{change,echo,verbose}=ctx.services.logger,source=payloadDisplayPath(sourcePath),sotText=payloadText(sourcePath),name=basename2(sourcePath);if(!existsSync4(target)){if(ctx.dryRun)return echo(`[dry-run] cp ${source} -> ${target}`),!1;return writePrivateFile(target,sotText),change(`omp ${name} installed`),ctx.nextStepTriggers.ompRestart=!0,!1}let deployedText=readFileSync4(target,"utf8"),merged=merge(sotText,deployedText);if(merged===deployedText)return verbose(`omp ${name} already in sync`),!1;if(ctx.dryRun)return echo(`[dry-run] merge ${source} -> ${target} (backup at ${target}.bak)`),!1;return backupPrivateFile(target),replaceFile(target,merged,{mode:384}),change(`omp ${name} merged (backup at ${name}.bak)`),ctx.nextStepTriggers.ompRestart=!0,!0}import{existsSync as existsSync5,lstatSync as lstatSync2,readFileSync as readFileSync5,readdirSync as readdirSync2,rmdirSync,unlinkSync as unlinkSync2}from"fs";var KIT_PLUGIN_NAME="docks-kit-omp",SOURCE_PREFIX="SoT/.omp/plugin/";function kitPluginDir(home){return p(home,".docks-kit","omp-plugin")}function pruneStale(directory,targets){let changed=!1;for(let name of readdirSync2(directory)){let entry=p(directory,name);if(lstatSync2(entry).isDirectory()){if(changed=pruneStale(entry,targets)||changed,readdirSync2(entry).length===0)rmdirSync(entry),changed=!0}else if(!targets.has(entry))unlinkSync2(entry),changed=!0}return changed}function deployedVersion(manifestPath){if(!existsSync5(manifestPath))return;let manifest=parseJson2(readFileSync5(manifestPath,"utf8"));if(manifest===void 0||!isObject2(manifest))return;return typeof manifest.version==="string"?manifest.version:void 0}function syncKitPlugin(ctx){let{change,echo,verbose}=ctx.services.logger,pluginDir=kitPluginDir(ctx.home),files=payloadPaths(SOURCE_PREFIX).map((source)=>({source,target:p(pluginDir,source.slice(SOURCE_PREFIX.length))}));if(ctx.dryRun){echo(`[dry-run] sync embedded:${SOURCE_PREFIX} -> ${pluginDir}`);return}let before=deployedVersion(p(pluginDir,"package.json")),changed=!1;for(let{source,target}of files){let content=payloadBytes(source);if(source===`${SOURCE_PREFIX}package.json`){let manifest=JSON.parse(content.toString("utf8"));manifest.version=GENERATED_PACKAGE_VERSION,content=Buffer.from(`${JSON.stringify(manifest,null,2)}
|
|
24172
|
+
`)[0]??"").trim().split(/[ \t]+/);return fields[index===-1?fields.length-1:index]??""}async function installedVersion(ctx,tool){let version=()=>ctx.services.deps.version(tool);switch(tool){case"git":return firstLineField(await version(),2);case"jq":return(await version()).replace(/^jq-/,"");case"curl":return firstLineField(await version(),1);case"bun":case"omp":case"npm":return await version();default:return""}}function row(cells){let widths=[28,9,14,9,9];return cells.map((c,i)=>i<widths.length?c.padEnd(widths[i]):c).join(" ")}async function report(ctx){let{echo}=ctx.services.logger;echo(row(["TOOL","KIND","INSTALLED","FLOOR","VERIFIED","STATUS"]));let pn=ctx.services.platform.name(),platformOs=hostOs(pn).toolchainOs;for(let tool of Object.keys(manifest()).sort(compareCodepoints)){let os=field(tool,"os");if(os!==""&&platformOs!==""&&os!==platformOs)continue;let kind=field(tool,"kind"),floor=field(tool,"floor"),verified=field(tool,"verified"),dash=(v)=>v!==""?v:"-";if(kind==="pin"){let via=field(tool,"via");echo(row([tool,kind,`(${via})`,dash(floor),dash(verified),"pinned"]));continue}let installed,status,toolId=tool;if(present(ctx,toolId)){if(installed=await installedVersion(ctx,toolId),status=installed===""?"unknown":"ok",belowFloor(installed,floor))status="below-floor";else if(verified!==""&&installed!==""&&isNewer(installed,verified))status="above-verified";installed=installed!==""?installed:"?"}else installed="-",status="missing";echo(row([tool,dash(kind),installed,dash(floor),dash(verified),status]))}}var UPSTREAM_CACHE_MS=86400000;function upstreamSpec(tool){let entry=manifest()[tool],upstream=entry!==void 0&&isObject2(entry)?entry.upstream:void 0;return upstream!==void 0&&isObject2(upstream)?upstream:void 0}function upstreamLabel(spec){let{npm,github}=spec;if(typeof npm==="string")return`npm ${npm}`;return typeof github==="string"?`github ${github}`:"-"}async function fetchJson(fetchImpl,url,headers){let response=await fetchImpl(url,{headers,signal:AbortSignal.timeout(8000)});if(response.status!==200)return{ok:!1,reason:`HTTP ${response.status}`};let body=parseJson2(await response.text());return body!==void 0&&isObject2(body)?{ok:!0,body}:{ok:!1,reason:"invalid response"}}async function lookupUpstream(spec,fetchImpl,env){let{npm,github,tagPrefix}=spec;if(typeof npm==="string"){let result=await fetchJson(fetchImpl,`https://registry.npmjs.org/${npm}/latest`,{Accept:"application/json"});if(!result.ok)return result;let version=result.body.version;return typeof version==="string"&&version!==""?{ok:!0,version}:{ok:!1,reason:"invalid response"}}if(typeof github==="string"){let headers={Accept:"application/vnd.github+json","User-Agent":"docks-kit"},token=env.GITHUB_TOKEN||env.GH_TOKEN;if(token!==void 0&&token!=="")headers.Authorization=`Bearer ${token}`;let result=await fetchJson(fetchImpl,`https://api.github.com/repos/${github}/releases/latest`,headers);if(!result.ok)return result;let tag=result.body.tag_name;if(typeof tag!=="string")return{ok:!1,reason:"invalid response"};let prefix=typeof tagPrefix==="string"?tagPrefix:"";return tag.startsWith(prefix)?{ok:!0,version:tag.slice(prefix.length)}:{ok:!1,reason:`unexpected tag ${tag}`}}return{ok:!1,reason:"no upstream in SoT/toolchain.json"}}async function latestUpstream(tool,inputs){let{home,refresh,now,fetchImpl=globalThis.fetch,env=process.env}=inputs,key=`upstream:${tool}`;if(!refresh){let cached=readCache(home,key,UPSTREAM_CACHE_MS,now);if(cached!==void 0)return{ok:!0,version:cached}}let spec=upstreamSpec(tool);if(spec===void 0)return{ok:!1,reason:"no upstream in SoT/toolchain.json"};let result;try{result=await lookupUpstream(spec,fetchImpl,env)}catch(error){result={ok:!1,reason:error instanceof Error?error.message:String(error)}}if(result.ok)writeCache(home,key,result.version,now);return result}async function outdatedReport(ctx,options){let{echo}=ctx.services.logger,tools=Object.keys(manifest()).filter((tool)=>field(tool,"verified")!==""&&upstreamSpec(tool)!==void 0),now=Date.now(),results=await Promise.all(tools.map((tool)=>latestUpstream(tool,{home:ctx.home,refresh:options.refresh,now,...options.fetchImpl!==void 0?{fetchImpl:options.fetchImpl}:{}})));return echo(row(["TOOL","KIND","VERIFIED","LATEST","STATUS","UPSTREAM"])),tools.forEach((tool,index)=>{let verified=field(tool,"verified"),result=results[index],latest="-",status;if(result.ok)latest=result.version,status=isNewer(latest,verified)?"newer":"current";else status=`lookup failed: ${result.reason}`;let label=upstreamLabel(upstreamSpec(tool)??{});echo(row([tool,field(tool,"kind"),verified,latest,status,label]))}),echo("Report only: update a verified pin after testing that release (SoT/toolchain.json)."),0}var VERSION_PROBE_LIMIT_MS=60000,spec=(id,installHint,options={})=>({id,versionArgs:["--version"],installHint,resolve:options.resolve,version:options.version});function shellWord(word){return/^[\w./:=@+-]+$/.test(word)?word:`"${word}"`}function commandLine({command,args}){return[command,...args].map(shellWord).join(" ")}function bunInstallHint(pf=rawPlatform()){let host=hostOs(platformName(pf)),pin=field("bun","verified");if(host.id==="windows"){let{download,run}=host.bunInstaller(pin,"$env:TEMP");return`${commandLine({...download,command:`${download.command}.exe`})}; if ($LASTEXITCODE -eq 0) { ${commandLine(run)} }`}let{download,run}=host.bunInstaller(pin,"$tmp");return`tmp=$(mktemp -d) && ${commandLine(download)} && ${commandLine(run)}`}var pathProbe=(id)=>(exec)=>{if(!exec.commandExists(id))return{state:"missing"};let path=exec.which(id);return path===""?{state:"present"}:{state:"present",path}},findBun=(exec)=>{let onPath=exec.which("bun");if(onPath!==""&&isAbsolute3(onPath))return{command:"bun",path:onPath};let root=process.env.BUN_INSTALL!==void 0&&process.env.BUN_INSTALL!==""?process.env.BUN_INSTALL:p(engineHome(),".bun");for(let candidate of[p(root,"bin","bun"),p(engineHome(),".bun","bin","bun")]){let found=exec.which(candidate);if(found!==""&&isAbsolute3(found))return{command:found,path:found}}return},resolveBun=(exec)=>{let bun=findBun(exec);return bun===void 0?{state:"missing"}:{state:"present",path:bun.path}},defaultProbeExecutor={commandExists,capture,captureWithin,which},DEPENDENCIES={git:spec("git",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("git")),jq:spec("jq",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("jq")),curl:spec("curl",(pf=rawPlatform())=>hostOs(platformName(pf)).installHint("curl")),npm:spec("npm",()=>"ships with Node.js \u2014 install via https://nodejs.org (or your package manager)"),omp:spec("omp",()=>"install omp from https://github.com/can1357/oh-my-pi (an existing install updates with `omp update`, or through the tool that manages it, such as Tern)",{version:async(exec)=>(await exec.capture("omp",["--version"])).trim().replace(/^omp[/v]/,"")}),bun:spec("bun",bunInstallHint,{resolve:resolveBun,version:async(exec)=>{let bun=findBun(exec);if(bun===void 0)return"";return await exec.capture(bun.command,["--version"])}})};function resolveDependency(specification,exec,platform=rawPlatform()){return(specification.resolve??pathProbe(specification.id))(exec,platform)}async function resolveVersionReading(specification,exec){if(resolveDependency(specification,exec).state!=="present")return{kind:"version",value:""};if(specification.version!==void 0)return{kind:"version",value:await specification.version(exec)};if(exec.captureWithin===void 0)return{kind:"version",value:await exec.capture(specification.id,specification.versionArgs)};let outcome=await exec.captureWithin(specification.id,specification.versionArgs,VERSION_PROBE_LIMIT_MS);if(outcome.kind==="timed-out")return outcome;return{kind:"version",value:outcome.kind==="output"?outcome.stdout:""}}async function resolveVersion(specification,exec){let reading=await resolveVersionReading(specification,exec);return reading.kind==="version"?reading.value:""}async function resolvePath(specification,exec,platform=rawPlatform()){let result=resolveDependency(specification,exec,platform);return result.state==="present"?result.path??exec.which(specification.id):""}var makePlatform=(pf=rawPlatform())=>({raw:()=>pf,name:()=>platformName(pf)}),makeDependencyManager=(platform,exec=defaultProbeExecutor)=>{let warned=new Set;return{spec:(id)=>{let s=DEPENDENCIES[id];return{...s,installHint:(pf=platform.raw())=>s.installHint(pf)}},probe:(id)=>resolveDependency(DEPENDENCIES[id],exec,platform.raw()),version:(id)=>resolveVersion(DEPENDENCIES[id],exec),versionReading:(id)=>resolveVersionReading(DEPENDENCIES[id],exec),path:(id)=>resolvePath(DEPENDENCIES[id],exec,platform.raw()),warnMissing:(id,logger,context)=>{if(warned.has(id))return;warned.add(id);let suffix=context!==void 0&&context!==""?` (${context})`:"";logger.warn(`${id} not installed \u2014 ${DEPENDENCIES[id].installHint(platform.raw())}${suffix}`)}}},makeEngineServices=(opts)=>{let platform=makePlatform();return{logger:makeLogger(opts?.sinks??{}),deps:makeDependencyManager(platform),platform}};class LoggerService extends Service()("docks-kit/Logger"){}class DependencyManagerService extends Service()("docks-kit/DependencyManager"){}class PlatformService extends Service()("docks-kit/Platform"){}var live=makeEngineServices(),LoggerLive=succeed5(LoggerService,live.logger),DependencyManagerLive=succeed5(DependencyManagerService,live.deps),PlatformLive=succeed5(PlatformService,live.platform),EngineServicesLive=mergeAll2(LoggerLive,DependencyManagerLive,PlatformLive);import{readFileSync as readFileSync2}from"fs";import{dirname as dirname2,join as join5,resolve as resolve4}from"path";var isKitHome=(dir)=>{try{return JSON.parse(readFileSync2(join5(dir,"package.json"),"utf8")).name==="docks-kit"}catch{return!1}},explicitKitHome=(dir,source)=>{let packageJson=join5(dir,"package.json"),text;try{text=readFileSync2(packageJson,"utf8")}catch(error){let code=typeof error==="object"&&error!==null&&"code"in error?String(error.code):void 0;if(code==="ENOENT")throw Error(`DOCKS_KIT_HOME=${source} does not contain package.json`,{cause:error});let detail=error instanceof Error?error.message:String(error),category=code===void 0?"":` (${code})`;throw Error(`DOCKS_KIT_HOME=${source} package.json cannot be read${category}: ${detail}`,{cause:error})}let manifest;try{manifest=JSON.parse(text)}catch(error){let detail=error instanceof Error?error.message:String(error);throw Error(`DOCKS_KIT_HOME=${source} package.json contains invalid JSON: ${detail}`,{cause:error})}if(typeof manifest!=="object"||manifest===null||!("name"in manifest)||manifest.name!=="docks-kit")throw Error(`DOCKS_KIT_HOME=${source} is not a docks-kit package root (package.json name must be "docks-kit")`);return dir},findKitHome=(start)=>{if(start===void 0||start==="")return;let dir=resolve4(start);for(;;){if(isKitHome(dir))return dir;let parent=dirname2(dir);if(parent===dir)return;dir=parent}},resolveKitHome=(sources)=>{if(sources.env!==void 0&&sources.env!=="")return explicitKitHome(resolve4(sources.env),sources.env);return findKitHome(sources.moduleDir)??findKitHome(sources.cwd)??dirname2(sources.execPath)},kitHome=()=>resolveKitHome({env:process.env.DOCKS_KIT_HOME,moduleDir:import.meta.dir,execPath:process.execPath,cwd:process.cwd()});function makeCtx(services,options){let env=process.env,home=engineHome(env),globals=options.envGlobals?env:{};return{repoDir:kitHome(),home,dryRun:globals.DRY_RUN==="1",verbose:globals.DOCKS_KIT_VERBOSE==="1",skipPluginRefresh:!1,services,nextStepTriggers:{ompRestart:!1},failures:[]}}import{mkdtempSync,rmSync}from"fs";import{tmpdir as tmpdir2}from"os";function predictedExecutable(ctx,host=hostOs()){let root=process.env.BUN_INSTALL!==void 0&&process.env.BUN_INSTALL!==""?process.env.BUN_INSTALL:p(ctx.home,".bun");return p(root,"bin",host.bunExecutableName)}function processFailure(result){return[result.error?.message,result.stderr.trim()].filter((value)=>value!==void 0&&value!=="").join(": ")||(result.exitCode===null?"the process ended without an exit code":`exit code ${result.exitCode}`)}async function installBun(pin,directory,host=hostOs()){let options={stdio:["ignore","ignore","pipe"]},installer=host.bunInstaller(pin,directory),download=await spawnProcess(installer.download.command,installer.download.args,options);if(download.error!==void 0||download.exitCode!==0)return{ok:!1,reason:"download-failed",detail:processFailure(download)};let install=await spawnProcess(installer.run.command,installer.run.args,options);if(install.error!==void 0||install.exitCode!==0)return{ok:!1,reason:"installer-failed",detail:processFailure(install)};return{ok:!0}}function bunBootstrap(ctx,services){if(ctx.bunRuntime!==void 0)return ctx.bunRuntime;let pending=runBunBootstrap(ctx,services);return ctx.bunRuntime=pending,pending}async function runBunBootstrap(ctx,services){let host=hostOs(services.platform.name()),existing=await services.deps.path("bun");if(existing!=="")return{kind:"ready",executable:existing};let pin=field("bun","verified");if(pin==="")return services.logger.warn("Bun bootstrap aborted \u2014 SoT/toolchain.json has no verified Bun pin"),{kind:"deferred",reason:"install-failed"};if(services.deps.probe("curl").state==="missing")return services.deps.warnMissing("curl",services.logger,"cannot bootstrap Bun; install Bun manually, then re-run sync"),{kind:"deferred",reason:"missing-curl"};if(ctx.dryRun){let executable=predictedExecutable(ctx,host);return services.logger.echo(`[dry-run] install Bun ${pin} (kit-verified) -> ${executable}`),{kind:"ready",executable}}services.logger.warn(`Bun not found \u2014 installing Bun ${pin} (kit-verified)...`);let temporaryDir=mkdtempSync(p(tmpdir2(),"docks-kit-bun-")),result;try{result=await installBun(pin,temporaryDir,host)}finally{rmSync(temporaryDir,{recursive:!0,force:!0})}if(!result.ok){let stage=result.reason==="download-failed"?"installer download":"installer";return services.logger.warn(`Bun ${stage} failed (${result.detail}). Install Bun manually from https://bun.sh/docs/installation, then re-run sync.`),{kind:"deferred",reason:result.reason}}let installed=await services.deps.path("bun");if(installed==="")return services.logger.warn("Bun install failed. Install manually from https://bun.sh/docs/installation, then re-run sync."),{kind:"deferred",reason:"install-failed"};let version=await services.deps.version("bun");return services.logger.change(`Bun installed (${version!==""?version:"version unknown"})`),{kind:"ready",executable:installed}}var TOOLCHAIN_USAGE="Usage: toolchain [check|ensure <tool> [--dry-run]|outdated [--refresh]]";async function modeToolchain(ctx,args){let{echo,err,verbose,warn}=ctx.services.logger,words=args.filter((arg)=>!arg.startsWith("--")),op=words[0]??"check",tool=words[1]??"";for(let arg of args)if(arg==="--verbose")ctx.verbose=!0;else if(arg==="--dry-run")ctx.dryRun=!0;if(words.length>(op==="ensure"?2:1))return err(TOOLCHAIN_USAGE),2;if(op==="check")return await report(ctx),0;if(op==="outdated")return await outdatedReport(ctx,{refresh:args.includes("--refresh")}),0;if(op!=="ensure")return err(TOOLCHAIN_USAGE),2;if(tool==="")return err("Usage: toolchain ensure <tool>"),2;switch(tool){case"bun":{let alreadyInstalled=present(ctx,"bun");if((await bunBootstrap(ctx,ctx.services)).kind!=="ready")return 1;if(alreadyInstalled){let probed=await installedVersion(ctx,"bun"),floor=field("bun","floor"),label=probed===""?"version unknown":probed;if(belowFloor(probed,floor))warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`);else if(ctx.dryRun)echo(`[dry-run] bun present (${label})`);else verbose(`bun present (${label})`)}return 0}default:return err("toolchain ensure supports managed tools only (bun)"),2}}class ExitError extends Error{code;constructor(code){super(`exit ${code}`);this.code=code}}function printUsage(ctx){let{echo}=ctx.services.logger,argv0="docks-kit sync";echo("Usage: docks-kit sync [flags]"),echo(""),echo("Global flags"),echo(" --dry-run preview without applying"),echo(" --skip-plugin-refresh install missing plugins but skip refresh-only updates"),echo(" --verbose also print no-op confirmations (already in sync, up to date, left as-is)")}function parseArgs2(ctx,args){let{err}=ctx.services.logger;for(let arg of args)switch(arg){case"--dry-run":ctx.dryRun=!0;continue;case"--skip-plugin-refresh":ctx.skipPluginRefresh=!0;continue;case"--verbose":ctx.verbose=!0;continue;case"-h":case"--help":throw printUsage(ctx),new ExitError(0);default:throw err(`Unknown arg: ${arg}`),new ExitError(2)}}import{existsSync as existsSync8,mkdirSync as mkdirSync5,realpathSync as realpathSync4}from"fs";import{basename as basename3,dirname as dirname6,join as join8}from"path";import{chmodSync as chmodSync2,mkdirSync as mkdirSync2}from"fs";import{dirname as dirname3}from"path";import{DatabaseSync as DatabaseSync2}from"node:sqlite";import{setTimeout as sleepMs}from"timers/promises";var POLL_MS=50,SQLITE_BUSY=5,heldConnections=new Set;function isBusy(cause){if(typeof cause!=="object"||cause===null||!("errcode"in cause))return!1;return typeof cause.errcode==="number"&&(cause.errcode&255)===SQLITE_BUSY}function tryBegin(connection){try{return connection.exec("BEGIN IMMEDIATE"),!0}catch(cause){if(isBusy(cause))return!1;throw cause}}async function acquireKitLock(path,options){let now=options.now??Date.now,sleep=options.sleep??((ms)=>sleepMs(ms)),pollMs=options.pollMs??POLL_MS,deadline=now()+options.waitMs;if(options.privateDirectory!==!1){let directory=dirname3(path);mkdirSync2(directory,{recursive:!0,mode:448}),chmodSync2(directory,448)}let connection=new DatabaseSync2(path);try{connection.exec("PRAGMA busy_timeout = 0");for(;;){if(tryBegin(connection))return heldConnections.add(connection),{kind:"acquired",lock:{path,connection}};let remaining=deadline-now();if(remaining<=0)break;await sleep(Math.min(pollMs,remaining))}}catch(cause){throw connection.close(),cause}return connection.close(),{kind:"held"}}function releaseKitLock(lock){heldConnections.delete(lock.connection);try{lock.connection.exec("ROLLBACK")}finally{lock.connection.close()}}import{isAbsolute as isAbsolute5,resolve as resolve7}from"path";function recordFailure(ctx,message){ctx.failures.push(message),ctx.services.logger.warn(message)}import{existsSync as existsSync2}from"fs";import{resolve as resolve5}from"path";var DEFAULT_CONFIG_DIR_NAME=".omp",APP_NAME="omp",PROFILE_NAME_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,WINDOWS_RESERVED_BASENAME_RE=/^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/i;function normalizeProfile(value){let name=value?.trim();if(name===void 0||name===""||name==="default")return;if(name==="."||name===".."||name.endsWith("."))return;if(!PROFILE_NAME_RE.test(name)||WINDOWS_RESERVED_BASENAME_RE.test(name))return;return name}function ompPaths({home,env,platform}){let profile=normalizeProfile(env.OMP_PROFILE!==void 0?env.OMP_PROFILE:env.PI_PROFILE),configDirName=env.PI_CONFIG_DIR,baseRoot=p(home,configDirName!==void 0&&configDirName!==""?configDirName:DEFAULT_CONFIG_DIR_NAME),configRoot=profile===void 0?baseRoot:p(baseRoot,"profiles",profile),agentOverride=env.PI_CODING_AGENT_DIR,defaultAgentDir=p(configRoot,"agent"),legacyProfile=normalizeProfile(env.PI_PROFILE),overrideIgnored=profile===void 0&&legacyProfile!==void 0&&agentOverride===p(baseRoot,"profiles",legacyProfile,"agent"),resolvedOverride=profile===void 0&&!overrideIgnored&&agentOverride!==void 0&&agentOverride!==""?resolve5(agentOverride):void 0,agentDir=resolvedOverride===void 0||resolvedOverride===resolve5(defaultAgentDir)?defaultAgentDir:resolvedOverride;return{profile,configRoot,agentDir,dataRoot:xdgDataRoot(env,platform,profile,agentDir===defaultAgentDir)??configRoot}}function xdgDataRoot(env,platform,profile,agentDirIsDefault){if(!agentDirIsDefault)return;if(platform!=="linux"&&platform!=="darwin")return;let dataHome=env.XDG_DATA_HOME;if(dataHome===void 0||dataHome==="")return;let appRoot=p(dataHome,APP_NAME),candidate=profile===void 0?appRoot:p(appRoot,"profiles",profile);return existsSync2(candidate)?candidate:void 0}var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,{YAMLError:$YAMLError,YAMLParseError:$YAMLParseError,YAMLWarning:$YAMLWarning}=errors,$Alias=Alias.Alias,{isAlias:$isAlias,isCollection:$isCollection,isDocument:$isDocument,isMap:$isMap,isNode:$isNode,isPair:$isPair,isScalar:$isScalar,isSeq:$isSeq}=identity2,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,{parse:$parse,parseAllDocuments:$parseAllDocuments,parseDocument:$parseDocument,stringify:$stringify}=publicApi,{visit:$visit,visitAsync:$visitAsync}=visit;var fallbackChainsPath=["retry","fallbackChains"];function stringKey(key){if(typeof key==="string")return key;if($isScalar(key)&&typeof key.value==="string")return key.value;return}function keyName(key){return $isScalar(key)?String(key.value):String(key)}var dropFallbackWildcard=(path,key)=>path.length===fallbackChainsPath.length&&path[0]===fallbackChainsPath[0]&&path[1]===fallbackChainsPath[1]&&key.includes("/"),keepEveryKey=()=>!1,keepSotSequence=()=>{};function bashRuleKey(match,approval){return`${approval.trim().toLowerCase()}\x00${match.trim().replace(/\s+/gu," ")}`}function bashPatternKey(node){if(!$isMap(node))return;let match=node.get("match"),approval=node.get("approval");if(typeof match!=="string"||typeof approval!=="string")return;return bashRuleKey(match,approval)}var mergeBashPatterns=(path,sotSeq,deployedSeq)=>{if(path.length!==2||path[0]!=="bash"||path[1]!=="patterns")return;let kitKeys=new Set(sotSeq.items.map(bashPatternKey)),kit={deny:[],prompt:[],allow:[]},user={deny:[],prompt:[],other:[]};for(let item of sotSeq.items){let approval=bashPatternKey(item)?.split("\x00")[0];kit[approval==="deny"||approval==="prompt"?approval:"allow"].push(item)}for(let item of deployedSeq.items){let key=bashPatternKey(item);if(key!==void 0&&kitKeys.has(key))continue;let approval=key?.split("\x00")[0];user[approval==="deny"||approval==="prompt"?approval:"other"].push(item)}sotSeq.items=[...kit.deny,...user.deny,...user.prompt,...kit.prompt,...user.other,...kit.allow]};function pruneMapping(mapping,path,drop){for(let index=mapping.items.length-1;index>=0;index--){let pair=mapping.items[index];if(pair===void 0)continue;if(drop(path,keyName(pair.key))){mapping.items.splice(index,1);continue}let key=stringKey(pair.key);if(key!==void 0&&$isMap(pair.value))pruneMapping(pair.value,[...path,key],drop)}}function mergeMappings(sotMapping,deployedMapping,path,drop,mergeSequence){for(let sotPair of sotMapping.items){let key=stringKey(sotPair.key);if(key===void 0)continue;let deployedPair=deployedMapping.items.find((candidate)=>stringKey(candidate.key)===key);if(deployedPair!==void 0&&$isMap(sotPair.value)&&$isMap(deployedPair.value))mergeMappings(sotPair.value,deployedPair.value,[...path,key],drop,mergeSequence);if(deployedPair!==void 0&&$isSeq(sotPair.value)&&$isSeq(deployedPair.value))mergeSequence([...path,key],sotPair.value,deployedPair.value)}for(let deployedPair of deployedMapping.items){let key=stringKey(deployedPair.key);if(key!==void 0&&sotMapping.items.some((candidate)=>stringKey(candidate.key)===key))continue;if(drop(path,keyName(deployedPair.key)))continue;if(key!==void 0&&$isMap(deployedPair.value))pruneMapping(deployedPair.value,[...path,key],drop);sotMapping.items.push(deployedPair)}}function mergeYamlDocuments(sotText,deployedText,name,drop,mergeSequence){let deployedDoc=$parseDocument(deployedText),deployedError=deployedDoc.errors[0];if(deployedError!==void 0)throw Error(`Invalid deployed omp ${name} YAML: ${deployedError.message}`);let deployedContents=deployedDoc.contents;if(deployedContents===null||deployedContents===void 0||$isScalar(deployedContents)&&deployedContents.value===null)return sotText;if(!$isMap(deployedContents))throw Error(`Deployed omp ${name} YAML root must be a mapping`);let sotDoc=$parseDocument(sotText),sotError=sotDoc.errors[0];if(sotError!==void 0)throw Error(`Invalid SoT omp ${name} YAML: ${sotError.message}`);if(!$isMap(sotDoc.contents))throw Error(`SoT omp ${name} YAML root must be a mapping`);return mergeMappings(sotDoc.contents,deployedContents,[],drop,mergeSequence),sotDoc.toString()}function mergeOmpConfig(sotText,deployedText){return mergeYamlDocuments(sotText,deployedText,"config.yml",dropFallbackWildcard,mergeBashPatterns)}function mergeOmpModels(sotText,deployedText){return mergeYamlDocuments(sotText,deployedText,"models.yml",keepEveryKey,keepSotSequence)}import{chmodSync as chmodSync4,copyFileSync,existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"fs";import{basename as basename2}from"path";import{createHash,randomBytes as randomBytes2}from"crypto";import{chmodSync as chmodSync3,existsSync as existsSync3,lstatSync,readdirSync,readFileSync as readFileSync3,readlinkSync,realpathSync,renameSync as renameSync2,statSync as statSync2,unlinkSync,writeFileSync}from"fs";import{basename,dirname as dirname4,join as join6,resolve as resolve6}from"path";function processExited(pid){try{return process.kill(pid,0),!1}catch(cause){return typeof cause==="object"&&cause!==null&&"code"in cause&&cause.code==="ESRCH"}}var MAX_NAME_BYTES=255,TEMPORARY_NAME=/^(.+)\.([1-9][0-9]*)\.[0-9a-f]{16}\.tmp$/,SHORT_TARGET=/^\.([0-9a-f]{16})$/;function writeTarget(target){let isLink;try{isLink=lstatSync(target).isSymbolicLink()}catch{return target}if(!isLink)return target;try{return realpathSync(target)}catch{return resolve6(dirname4(target),readlinkSync(target))}}function permissionBits(file){try{return statSync2(file).mode&511}catch{return}}function nameTag(name){return createHash("sha256").update(name).digest("hex").slice(0,16)}function temporaryPath(file){let unique=randomBytes2(8).toString("hex"),long=`${file}.${process.pid}.${unique}.tmp`;if(Buffer.byteLength(basename(long))<=MAX_NAME_BYTES)return long;return join6(dirname4(file),`.${nameTag(basename(file))}.${process.pid}.${unique}.tmp`)}function parseTemporaryName(entry){let match=TEMPORARY_NAME.exec(entry);if(match===null)return;let[,target="",digits=""]=match,pid=Number(digits);if(!Number.isSafeInteger(pid))return;let short=SHORT_TARGET.exec(target);return{target:short===null?{kind:"name",name:target}:{kind:"tag",tag:short[1]??""},pid}}function isRegularFile(path){try{return lstatSync(path).isFile()}catch{return!1}}function removeStaleTemporaries(dir,owns){let entries;try{entries=readdirSync(dir)}catch{return}for(let entry of entries){let parsed=parseTemporaryName(entry);if(parsed===void 0||parsed.pid===process.pid||!owns(parsed.target))continue;let path=join6(dir,entry);if(!isRegularFile(path)||!processExited(parsed.pid))continue;try{unlinkSync(path)}catch{}}}function removeStaleTemporariesOf(file){let name=basename(file),tag=nameTag(name);removeStaleTemporaries(dirname4(file),(target)=>target.kind==="name"?target.name===name:target.tag===tag)}function errorSyscall(error){return typeof error==="object"&&error!==null&&"syscall"in error?error.syscall:void 0}function removeTemporary(path){try{unlinkSync(path)}catch{}}function replaceFile(target,content,options={}){let file=writeTarget(target),mode=options.mode??permissionBits(file),temporary=temporaryPath(file);try{if(writeFileSync(temporary,content,mode===void 0?{flag:"wx"}:{flag:"wx",mode}),mode!==void 0)chmodSync3(temporary,mode);renameSync2(temporary,file)}catch(error){if(errorSyscall(error)!=="open")removeTemporary(temporary);throw error}removeStaleTemporariesOf(file)}function ensureDirectory(directory){mkdirSync3(directory,{recursive:!0,mode:448}),chmodSync4(directory,448)}function writePrivateFile(target,content){writeFileSync2(target,content,{mode:384}),chmodSync4(target,384)}function backupPrivateFile(target){copyFileSync(target,`${target}.bak`),chmodSync4(`${target}.bak`,384)}function syncWholeFile(ctx,sourcePath,target,alreadyMessage,syncedMessage){let{change,echo,verbose}=ctx.services.logger,source=payloadDisplayPath(sourcePath),content=payloadText(sourcePath);if(ctx.dryRun){echo(`[dry-run] cp ${source} -> ${target}`);return}if(existsSync4(target)&&readFileSync4(target,"utf8")===content){verbose(alreadyMessage);return}if(existsSync4(target))backupPrivateFile(target);writePrivateFile(target,content),change(syncedMessage),ctx.nextStepTriggers.ompRestart=!0}function syncMergedYaml(ctx,sourcePath,target,merge){let{change,echo,verbose}=ctx.services.logger,source=payloadDisplayPath(sourcePath),sotText=payloadText(sourcePath),name=basename2(sourcePath);if(!existsSync4(target)){if(ctx.dryRun)return echo(`[dry-run] cp ${source} -> ${target}`),!1;return writePrivateFile(target,sotText),change(`omp ${name} installed`),ctx.nextStepTriggers.ompRestart=!0,!1}let deployedText=readFileSync4(target,"utf8"),merged=merge(sotText,deployedText);if(merged===deployedText)return verbose(`omp ${name} already in sync`),!1;if(ctx.dryRun)return echo(`[dry-run] merge ${source} -> ${target} (backup at ${target}.bak)`),!1;return backupPrivateFile(target),replaceFile(target,merged,{mode:384}),change(`omp ${name} merged (backup at ${name}.bak)`),ctx.nextStepTriggers.ompRestart=!0,!0}import{existsSync as existsSync5,lstatSync as lstatSync2,readFileSync as readFileSync5,readdirSync as readdirSync2,rmdirSync,unlinkSync as unlinkSync2}from"fs";var KIT_PLUGIN_NAME="docks-kit-omp",SOURCE_PREFIX="SoT/.omp/plugin/";function kitPluginDir(home){return p(home,".docks-kit","omp-plugin")}function pruneStale(directory,targets){let changed=!1;for(let name of readdirSync2(directory)){let entry=p(directory,name);if(lstatSync2(entry).isDirectory()){if(changed=pruneStale(entry,targets)||changed,readdirSync2(entry).length===0)rmdirSync(entry),changed=!0}else if(!targets.has(entry))unlinkSync2(entry),changed=!0}return changed}function deployedVersion(manifestPath){if(!existsSync5(manifestPath))return;let manifest=parseJson2(readFileSync5(manifestPath,"utf8"));if(manifest===void 0||!isObject2(manifest))return;return typeof manifest.version==="string"?manifest.version:void 0}function syncKitPlugin(ctx){let{change,echo,verbose}=ctx.services.logger,pluginDir=kitPluginDir(ctx.home),files=payloadPaths(SOURCE_PREFIX).map((source)=>({source,target:p(pluginDir,source.slice(SOURCE_PREFIX.length))}));if(ctx.dryRun){echo(`[dry-run] sync embedded:${SOURCE_PREFIX} -> ${pluginDir}`);return}let before=deployedVersion(p(pluginDir,"package.json")),changed=!1;for(let{source,target}of files){let content=payloadBytes(source);if(source===`${SOURCE_PREFIX}package.json`){let manifest=JSON.parse(content.toString("utf8"));manifest.version=GENERATED_PACKAGE_VERSION,content=Buffer.from(`${JSON.stringify(manifest,null,2)}
|
|
24173
24173
|
`)}if(ensureDirectory(target.slice(0,target.lastIndexOf("/"))),existsSync5(target)&&readFileSync5(target).equals(content))continue;replaceFile(target,content,{mode:384}),changed=!0}if(existsSync5(pluginDir))changed=pruneStale(pluginDir,new Set(files.map(({target})=>target)))||changed;if(changed)change(before===void 0||before===GENERATED_PACKAGE_VERSION?"omp kit plugin files synced":`omp kit plugin files synced (${KIT_PLUGIN_NAME} ${before} -> ${GENERATED_PACKAGE_VERSION})`),ctx.nextStepTriggers.ompRestart=!0;else verbose("omp kit plugin files already in sync")}import{existsSync as existsSync6,readFileSync as readFileSync6,realpathSync as realpathSync3,rmSync as rmSync3}from"fs";function spawnOmp(paths,args,stdio){if(paths.dataRoot!==paths.configRoot)return spawnProcess("omp",args,{stdio});let env={...process.env};return delete env.XDG_DATA_HOME,spawnProcess("omp",args,{stdio,env})}import{chmodSync as chmodSync5,lstatSync as lstatSync3,mkdirSync as mkdirSync4,mkdtempSync as mkdtempSync2,realpathSync as realpathSync2,rmSync as rmSync2,statSync as statSync3}from"fs";import{dirname as dirname5,isAbsolute as isAbsolute4,join as join7,relative}from"path";var LABEL_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function kitCacheDir(home){return p(home,".cache","docks-kit")}function tidyApplyLockPath(home){return join7(kitCacheDir(home),"tidy-lock.db")}function syncLockPath(home){return join7(kitCacheDir(home),"sync-lock.db")}function folderSyncLockPath(folder){return join7(folder,".docks-kit-sync-lock.db")}function scratchRoot(home){return p(kitCacheDir(home),"scratch")}function createScratchDir(root,label){if(!LABEL_PATTERN.test(label))throw Error("label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$");mkdirSync4(root,{recursive:!0,mode:448}),chmodSync5(root,448);let directory=mkdtempSync2(join7(root,`${label}-`));return chmodSync5(directory,448),realpathSync2(directory)}function isSameOrInside(parent,child){let path=relative(parent,child);return path===""||!path.startsWith("..")&&!isAbsolute4(path)}function isStrictlyInside(parent,child){let path=relative(parent,child);return path!==""&&!path.startsWith("..")&&!isAbsolute4(path)}function realpathOrUndefined(path){try{return realpathSync2(path)}catch{return}}var STICKY=512,GROUP_OR_OTHER_WRITE=18;function isTrustedOwner(uid,user){return uid===user||uid===0}function untrustedParent(path,user){let chain=[path];for(let parent=dirname5(path);parent!==chain[0];parent=dirname5(parent))chain.unshift(parent);for(let index=0;index<chain.length-1;index++){let directory=lstatSync3(chain[index]);if(!directory.isDirectory()||!isTrustedOwner(directory.uid,user))return chain[index];if((directory.mode&GROUP_OR_OTHER_WRITE)===0)continue;if((directory.mode&STICKY)===0||!isTrustedOwner(lstatSync3(chain[index+1]).uid,user))return chain[index]}return}function isTrustedRoot(root){if(process.getuid===void 0)return!0;let user=process.getuid(),stats=lstatSync3(root);if(!isTrustedOwner(stats.uid,user))return!1;if((stats.mode&GROUP_OR_OTHER_WRITE)!==0&&(stats.mode&STICKY)===0)return!1;return untrustedParent(root,user)===void 0}function allowedRemovalRoots(input){let candidates=[input.scratch,input.tmp];if(input.platform!=="win32")candidates.push("/tmp","/var/tmp");let home=realpathOrUndefined(input.home)??input.home,roots=[];for(let candidate of candidates){let root=realpathOrUndefined(candidate);if(root===void 0||roots.includes(root))continue;if(dirname5(root)===root||isSameOrInside(root,home))continue;if(!isTrustedRoot(root))continue;roots.push(root)}return roots}function errorCode(cause){return cause instanceof Error&&"code"in cause&&typeof cause.code==="string"?cause.code:void 0}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function removeTemporaryPath(operand,roots,home){let refuse=(reason)=>({kind:"refused",path:operand,reason}),trailing=process.platform==="win32"?/[\\/]+$/:/\/+$/,entry=operand.replace(trailing,"")||operand;try{if(lstatSync3(entry).isSymbolicLink())return refuse("is a symbolic link")}catch(cause){return errorCode(cause)==="ENOENT"?refuse("does not exist"):refuse(errorMessage(cause))}try{let target=realpathSync2(entry),root=roots.includes(target)?void 0:roots.find((candidate)=>isStrictlyInside(candidate,target));if(root===void 0)return refuse("is outside the scratch root, the system temporary directory, and /var/tmp");if(isSameOrInside(target,realpathOrUndefined(home)??home))return refuse("contains the home directory");let stats=statSync3(target);if(process.getuid!==void 0){let user=process.getuid();if(stats.uid!==user)return refuse("is owned by another user");let parent=untrustedParent(target,user);if(parent!==void 0)return refuse(`has a parent directory that another user can change: ${parent}`)}if(stats.dev!==statSync3(root).dev)return refuse("is on another filesystem");return rmSync2(target,{recursive:!0,force:!1}),{kind:"removed",path:target}}catch(cause){return refuse(errorMessage(cause))}}var RETIRED_PLUGIN_IDS=["docks@docks","plan-lifecycle@docks"],RETIRED_MARKETPLACE="docks",RETIRED_MARKETPLACE_LABEL=`${RETIRED_MARKETPLACE} marketplace`;async function installedPluginsFromCli(paths){let result=await spawnOmp(paths,["plugin","list","--json"],["ignore","pipe","ignore"]);if(result.error!==void 0||result.exitCode!==0)return;let value=parseJson2(result.stdout);if(value===void 0||!isObject2(value)||!Array.isArray(value.marketplace)||!Array.isArray(value.npm))return;let marketplace=[];for(let row of value.marketplace){if(!isObject2(row)||typeof row.id!=="string")continue;let scope=row.scope;if(scope!=="user"&&scope!=="project")continue;marketplace.push({id:row.id,scope})}let npm=new Map;for(let row of value.npm){if(!isObject2(row)||typeof row.name!=="string"||typeof row.version!=="string")continue;let path=typeof row.path==="string"?row.path:void 0;npm.set(row.name,{version:row.version,path})}return{marketplace,npm}}function describeOperation(operation,after){switch(operation.kind){case"link":return`${operation.id} linked`;case"uninstall":return`${operation.id} uninstalled`;case"marketplaceRemove":return`${RETIRED_MARKETPLACE_LABEL} removed`;case"npm":{let version=after?.npm.get(operation.id)?.version;if(version===void 0)return operation.id;if(operation.present===!1)return`${operation.id} ${version} (new)`;if(operation.before===void 0)return`${operation.id} ${version}`;if(operation.before===version)return`${operation.id} ${version} (current)`;return`${operation.id} ${operation.before} -> ${version}`}}}async function runPluginCommand(ctx,paths,plugin,args){let{clearProgress,progress}=ctx.services.logger;progress(`Updating omp plugin ${plugin}...`);let result=await spawnOmp(paths,args,["ignore","pipe","pipe"]);if(clearProgress(),result.error===void 0&&result.exitCode===0)return!0;return recordFailure(ctx,`omp plugin operation failed for ${plugin}: ${processFailureSummary(result)}; run manually: omp ${args.join(" ")}`),!1}function realPath2(path){try{return realpathSync3(path)}catch{return}}function registryState(registryFile){let registryText;try{registryText=readFileSync6(registryFile,"utf8")}catch(error){let code=typeof error==="object"&&error!==null&&"code"in error?error.code:"";if(code==="ENOENT"||code==="ENOTDIR")return{kind:"missing"};return{kind:"unreadable",file:registryFile}}let registry=parseJson2(registryText);if(registry===void 0)return{kind:"unreadable",file:registryFile};if(isObject2(registry)&&Object.hasOwn(registry,RETIRED_MARKETPLACE))return{kind:"listed"};return(Array.isArray(registry)?registry:isObject2(registry)&&Array.isArray(registry.marketplaces)?registry.marketplaces:[]).some((entry)=>isObject2(entry)&&entry.name===RETIRED_MARKETPLACE)?{kind:"listed"}:{kind:"absent"}}function docksRegistryState(paths){let active=registryState(p(paths.dataRoot,"marketplaces.json"));if(active.kind!=="missing")return active;if(paths.dataRoot===paths.configRoot)return{kind:"absent"};let legacy=registryState(p(paths.configRoot,"marketplaces.json"));return legacy.kind==="missing"?{kind:"absent"}:legacy}function unreadableRegistryWarning(file){return`omp marketplace registry ${file} cannot be read or parsed \u2014 the docks marketplace is not removed; repair the file, then run docks-kit sync again`}function removeUpgradeLog(ctx){let dir=p(kitCacheDir(ctx.home),"omp-plugin-upgrades");if(!existsSync6(dir))return;try{rmSync3(dir,{recursive:!0,force:!0}),ctx.services.logger.verbose(`removed the retired omp plugin upgrade log ${dir}`)}catch(error){let detail=error instanceof Error?error.message:String(error);ctx.services.logger.warn(`retired omp plugin upgrade log not removed: ${detail}`)}}async function retireMarketplacePlugins(ctx,paths,installed){let{warn}=ctx.services.logger,operations=[],uninstallFailed=!1;for(let pluginId of RETIRED_PLUGIN_IDS){let rows=installed.marketplace.filter((row)=>row.id===pluginId);if(rows.some((row)=>row.scope==="project"))warn(`omp plugin ${pluginId} is installed at project scope and docks-kit no longer ships it; run from that project: omp plugin uninstall --scope project ${pluginId}`);if(!rows.some((row)=>row.scope==="user"))continue;if(await runPluginCommand(ctx,paths,pluginId,["plugin","uninstall","--scope","user",pluginId]))operations.push({kind:"uninstall",id:pluginId});else uninstallFailed=!0}if(uninstallFailed)return operations;let registry=docksRegistryState(paths);if(registry.kind==="unreadable")warn(unreadableRegistryWarning(registry.file));else if(registry.kind==="listed"){if(await runPluginCommand(ctx,paths,RETIRED_MARKETPLACE_LABEL,["plugin","marketplace","remove",RETIRED_MARKETPLACE]))operations.push({kind:"marketplaceRemove"})}return operations}async function syncPlugins(ctx,paths){let{change,clearProgress,echo,progress,verbose,warn}=ctx.services.logger;if(!ctx.dryRun)removeUpgradeLog(ctx);if(ctx.services.deps.probe("omp").state==="missing")return ctx.services.deps.warnMissing("omp",ctx.services.logger,"deployed omp config only \u2014 plugin pass skipped; re-run sync after installing"),0;if(ctx.services.deps.probe("git").state==="missing")return ctx.services.deps.warnMissing("git",ctx.services.logger,"omp plugin pass skipped; re-run sync after installing"),0;let piIntercomPin=field("pi-intercom","verified");if(ctx.dryRun){for(let pluginId of RETIRED_PLUGIN_IDS)echo(`[dry-run] omp plugin uninstall --scope user ${pluginId}`);let registry=docksRegistryState(paths);if(registry.kind==="unreadable")warn(unreadableRegistryWarning(registry.file));else if(registry.kind==="listed")echo(`[dry-run] omp plugin marketplace remove ${RETIRED_MARKETPLACE}`);if(piIntercomPin==="")warn("pi-intercom install skipped because SoT/toolchain.json has no verified pi-intercom pin");else echo(`[dry-run] omp install pi-intercom@${piIntercomPin}`);return echo(`[dry-run] omp plugin link ${kitPluginDir(ctx.home)}`),0}progress("Checking installed omp plugins...");let installed=await installedPluginsFromCli(paths);clearProgress();let operations=[];if(installed===void 0)warn("omp plugin inventory unavailable \u2014 retirement of the docks marketplace plugins skipped until the next sync; pi-intercom and the kit plugin take the full refresh path");else operations.push(...await retireMarketplacePlugins(ctx,paths,installed));let pluginsInstalled=installed===void 0?0:(piIntercomPin!==""&&installed.npm.has("pi-intercom")?1:0)+(installed.npm.has(KIT_PLUGIN_NAME)?1:0);if(piIntercomPin==="")warn("pi-intercom install skipped because SoT/toolchain.json has no verified pi-intercom pin");else{let installedVersion=installed?.npm.get("pi-intercom")?.version,present=installedVersion!==void 0;if(installedVersion===piIntercomPin)verbose(`omp npm plugin pi-intercom already installed at ${piIntercomPin}`);else if(present&&ctx.skipPluginRefresh===!0)verbose("omp npm plugin pi-intercom already installed; refresh-only update skipped");else{let args=present?["install","--force",`pi-intercom@${piIntercomPin}`]:["install",`pi-intercom@${piIntercomPin}`];if(await runPluginCommand(ctx,paths,"pi-intercom",args)){if(operations.push({kind:"npm",id:"pi-intercom",present:installed===void 0?void 0:present,before:installedVersion}),!present)pluginsInstalled++}}}let kitDir=kitPluginDir(ctx.home),kitPluginPath=installed?.npm.get(KIT_PLUGIN_NAME)?.path,linkedTarget=kitPluginPath===void 0?void 0:realPath2(kitPluginPath);if(linkedTarget!==void 0&&linkedTarget===realPath2(kitDir))verbose(`omp kit plugin ${KIT_PLUGIN_NAME} already linked`);else if(await runPluginCommand(ctx,paths,KIT_PLUGIN_NAME,["plugin","link",kitDir])){if(operations.push({kind:"link",id:KIT_PLUGIN_NAME}),installed?.npm.has(KIT_PLUGIN_NAME)!==!0)pluginsInstalled++}if(operations.length===0)return verbose("omp plugins already in sync"),pluginsInstalled;let after;if(operations.some((operation)=>operation.kind==="npm"))progress("Reading omp plugin versions..."),after=await installedPluginsFromCli(paths),clearProgress();let items=operations.map((operation)=>describeOperation(operation,after));if(change(`omp plugins synced: ${items.join(", ")}`),operations.some((operation)=>operation.kind!=="marketplaceRemove"))ctx.nextStepTriggers.ompRestart=!0;return pluginsInstalled}import{existsSync as existsSync7,readFileSync as readFileSync7}from"fs";import{isDeepStrictEqual}from"util";var OMP_RETIRED_VALUES=[["symbolPreset","unicode"],["theme.dark","titanium"],["statusLine.preset","default"],["statusLine.showHookStatus",!0],["statusLine.sessionAccent",!0],["statusLine.transparent",!1],["terminal.showProgress",!1],["tui.textSizing",!1],["tui.tight",!1],["display.shimmer","classic"],["omitThinking",!1],["hideThinkingBlock",!1],["autocompleteMaxVisible",10],["emojiAutocomplete",!0],["readLineNumbers",!1],["interruptMode","immediate"],["autoResume",!1],["startup.changelogMode","summary"],["retry.usageAwareFallback",!0],["defaultThinkingLevel","high"],["tier.anthropic","none"],["advisor.enabled",!0],["advisor.enabled",!1],["advisor.syncBacklog","1"],["task.softRequestBudget",200],["task.softRequestBudgetNotice",!0],["task.batch",!0],["task.enableEffort",!1],["task.maxRecursionDepth",2],["modelRoles.advisor","anthropic/claude-opus-5-5:medium"],["providers.anthropic.serverSideFallback",!1],["providers.fetch","auto"],["retry.fallbackChains.advisor",[]],["includeWorkspaceTree",!1],["commands.enableOpencodeUser",!1],["skills.enableClaudeUser",!1],["skills.enableCodexUser",!1],["skills.enableAgentsUser",!0],["compaction.thresholdTokens",-1],["compaction.thresholdTokens",231200],["textVerbosity","low"],["codexResets.autoRedeem","no"],["tools.approvalMode","yolo"],["task.maxConcurrency",16],["task.maxEffort","xhigh"],["task.maxRuntimeMs",3600000],["task.agentIdleTtlMs",120000],["task.enableLsp",!0],["task.eager","always"],["task.showResolvedModelBadge",!0],["find.enabled",!0],["providers.webSearchTimeoutSeconds",30],["browser.idleCloseSec",600],["steeringMode","all"],["doubleEscapeAction","tree"],["features.unexpectedStopDetection","smart"],["compaction.idleEnabled",!0],["compaction.handoffSaveToDisk",!0],["commands.enableOpencodeProject",!1],["statusLine.compactThinkingLevel",!1],["github.enabled",!0]],OMP_RETIRED_KEYS=["providers.webSearchOrder"],OMP_RETIRED_MODEL_BLOCKS=[["providers.anthropic.modelOverrides.claude-opus-5-5",{name:"Claude Opus 5.5",reasoning:!0,input:["text","image"],contextWindow:1e6,maxTokens:128000,cost:{input:4,output:20,cacheRead:0.2,cacheWrite:5},thinking:{mode:"effort",efforts:["low","medium","high","xhigh","max"],defaultLevel:"high"}}],["providers.openai-codex.modelOverrides.gpt-6-astra",{thinking:{mode:"effort",efforts:["low","medium","high","xhigh","max"],defaultLevel:"xhigh"}}]];function shortClusters(first,second){return[...first].flatMap((a)=>[...second].map((b)=>`-${a}${b}`))}function optionRules(command,options){return options.flatMap((option)=>[`${command} ${option}*`,`${command} * ${option}*`])}var RETIRED_PROMPT_MATCHES=["git clean","git clean *","git reset *--hard*",...optionRules("git push",["-f",...shortClusters("vqdnu46","vqdnu46f"),"--f","--mi","+"]),"*git * --no-v*",...optionRules("*git commit",["-n",...shortClusters("qvseaipoz","qvseaipnoz")]),...optionRules("*git am",["-n",...shortClusters("i3qsukmcr","in3qsukmcr")]),"*git *core.hooksPath*","*git *core.hookspath*","*GIT_CONFIG_PARAMETERS*","*GIT_CONFIG_COUNT*"],OMP_RETIRED_BASH_RULES=[{match:"git rm -- *",approval:"allow"},{match:"git worktree remove -- *",approval:"allow"},{match:"gio trash -- *",approval:"allow"},{match:"rm",approval:"prompt"},{match:"rm *",approval:"prompt"},{match:"*/rm",approval:"prompt"},{match:"*/rm *",approval:"prompt"},{match:"xargs rm",approval:"prompt"},{match:"xargs rm *",approval:"prompt"},{match:"xargs * rm",approval:"prompt"},{match:"xargs * rm *",approval:"prompt"},{match:"env * rm",approval:"prompt"},{match:"env * rm *",approval:"prompt"},{match:"command rm",approval:"prompt"},{match:"command rm *",approval:"prompt"},{match:"exec rm",approval:"prompt"},{match:"exec rm *",approval:"prompt"},{match:"nohup rm",approval:"prompt"},{match:"nohup rm *",approval:"prompt"},{match:"nice rm",approval:"prompt"},{match:"nice rm *",approval:"prompt"},{match:"nice * rm",approval:"prompt"},{match:"nice * rm *",approval:"prompt"},{match:"time rm",approval:"prompt"},{match:"time rm *",approval:"prompt"},{match:"timeout * rm",approval:"prompt"},{match:"timeout * rm *",approval:"prompt"},{match:"stdbuf * rm",approval:"prompt"},{match:"stdbuf * rm *",approval:"prompt"},{match:"find -delete*",approval:"prompt"},{match:"find * -delete*",approval:"prompt"},{match:"find -exec*rm *",approval:"prompt"},{match:"find * -exec*rm *",approval:"prompt"},{match:"git rm",approval:"prompt"},{match:"git rm *",approval:"prompt"},{match:"git worktree remove",approval:"prompt"},{match:"git worktree remove *",approval:"prompt"},{match:"gio trash",approval:"prompt"},{match:"gio trash *",approval:"prompt"},{match:"git push $*",approval:"prompt"},{match:"git push * $*",approval:"prompt"},{match:"git push `*",approval:"prompt"},{match:"git push * `*",approval:"prompt"},...RETIRED_PROMPT_MATCHES.map((match)=>({match,approval:"prompt"}))],OMP_RETIRED_BASH_KEYS=new Map(OMP_RETIRED_BASH_RULES.map(({match,approval})=>[bashRuleKey(match,approval),`bash.patterns "${match}" (${approval})`]));function indexOfKey(mapping,key){return mapping.items.findIndex((pair)=>{let name=pair.key;if(typeof name==="string")return name===key;return $isScalar(name)&&name.value===key})}function deletePath(root,segments,matches){let owners=[root],cursor=root;for(let segment of segments.slice(0,-1)){let index=indexOfKey(cursor,segment),pair=index<0?void 0:cursor.items[index];if(pair===void 0||!$isMap(pair.value))return!1;cursor=pair.value,owners.push(cursor)}let leaf=segments[segments.length-1];if(leaf===void 0)return!1;let leafIndex=indexOfKey(cursor,leaf);if(leafIndex<0)return!1;let leafPair=cursor.items[leafIndex];if(leafPair===void 0||!matches(leafPair.value))return!1;let leafKey=leafPair.key,priorComment=$isScalar(leafKey)&&typeof leafKey.commentBefore==="string"?leafKey.commentBefore.slice(0,Math.max(0,leafKey.commentBefore.lastIndexOf(`
|
|
24174
24174
|
|
|
24175
24175
|
`))):"";if(cursor.items.splice(leafIndex,1),priorComment!==""){let heir=cursor.items[leafIndex]?.key;if($isScalar(heir))heir.commentBefore=typeof heir.commentBefore==="string"?`${priorComment}
|
|
24176
24176
|
|
|
24177
24177
|
${heir.commentBefore}`:priorComment;else cursor.comment=typeof cursor.comment==="string"?`${cursor.comment}
|
|
24178
|
-
${priorComment}`:priorComment}for(let depth=owners.length-1;depth>=1;depth--){let mapping=owners[depth];if(mapping===void 0||mapping.items.length>0)break;let owner=owners[depth-1],segment=segments[depth-1];if(owner===void 0||segment===void 0)break;let index=indexOfKey(owner,segment);if(index>=0)owner.items.splice(index,1)}return!0}function retiredKeys(entries){return(root)=>{let pruned=[];for(let[path,matches]of entries)if(deletePath(root,path.split("."),matches))pruned.push(path);return pruned}}var retiredBashRules=(root)=>{let bash=root.get("bash"),patterns=$isMap(bash)?bash.get("patterns"):void 0;if(!$isSeq(patterns))return[];let pruned=[];return patterns.items=patterns.items.filter((item)=>{let key=bashPatternKey(item),name=key===void 0?void 0:OMP_RETIRED_BASH_KEYS.get(key);if(name===void 0)return!0;return pruned.push(name),!1}),pruned};function pruneRetired(ctx,file,label,pruners,alreadyBackedUp){let{change,echo,verbose,warn}=ctx.services.logger;if(!existsSync7(file))return 0;let doc=$parseDocument(readFileSync7(file,"utf8")),parseError=doc.errors[0];if(parseError!==void 0)return warn(`omp ${label} unreadable, retired entries not pruned: ${parseError.message}`),0;let contents=doc.contents;if(!$isMap(contents))return 0;let pruned=pruners.flatMap((prune)=>prune(contents));if(pruned.length===0)return verbose(`omp ${label} carries no retired entries`),0;if(ctx.dryRun)return echo(`[dry-run] prune ${file}: ${pruned.join(", ")}`),pruned.length;if(!alreadyBackedUp)backupPrivateFile(file);replaceFile(file,String(doc),{mode:384});let backupNote=alreadyBackedUp?"":` (backup at ${label}.bak)`;return change(`omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}${backupNote}`),pruned.length}function syncOmpRemovals(ctx,configFile,alreadyBackedUp){return pruneRetired(ctx,configFile,"config.yml",[retiredKeys([...OMP_RETIRED_VALUES.map(([path,value])=>[path,Array.isArray(value)?(node)=>$isSeq(node)&&isDeepStrictEqual(node.toJSON(),value):(node)=>$isScalar(node)&&node.value===value]),...OMP_RETIRED_KEYS.map((path)=>[path,()=>!0])]),retiredBashRules],alreadyBackedUp)}function syncOmpModelRemovals(ctx,modelsFile,alreadyBackedUp){return pruneRetired(ctx,modelsFile,"models.yml",[retiredKeys(OMP_RETIRED_MODEL_BLOCKS.map(([path,block])=>[path,(node)=>$isMap(node)&&isDeepStrictEqual(node.toJSON(),block)]))],alreadyBackedUp)}function ompWriteFolders(ctx){let paths=ompPaths({home:ctx.home,env:process.env,platform:ctx.services.platform.raw()}),intercomRootSetting=process.env.PI_CODING_AGENT_DIR?.trim(),intercomRoot=paths.profile!==void 0?paths.agentDir:intercomRootSetting!==void 0&&intercomRootSetting!==""?isAbsolute5(intercomRootSetting)?intercomRootSetting:resolve7(process.cwd(),intercomRootSetting):p(ctx.home,".pi","agent");return{paths,intercomDir:p(intercomRoot,"intercom")}}async function ompSync(ctx,folders){await bunBootstrap(ctx,ctx.services);let{paths,intercomDir}=folders,agentDir=paths.agentDir;if(!ctx.dryRun)ensureDirectory(agentDir);syncWholeFile(ctx,"SoT/.omp/AGENTS.md",p(agentDir,"AGENTS.md"),"omp AGENTS.md already in sync","omp AGENTS.md synced"),syncWholeFile(ctx,"SoT/.omp/mcp.json",p(agentDir,"mcp.json"),"omp mcp.json already in sync","omp mcp.json synced");let configFile=p(agentDir,"config.yml"),configBackedUp=syncMergedYaml(ctx,"SoT/.omp/config.yml",configFile,mergeOmpConfig);syncOmpRemovals(ctx,configFile,configBackedUp);let modelsFile=p(agentDir,"models.yml"),modelsBackedUp=syncMergedYaml(ctx,"SoT/.omp/models.yml",modelsFile,mergeOmpModels);if(syncOmpModelRemovals(ctx,modelsFile,modelsBackedUp),!ctx.dryRun)ensureDirectory(intercomDir);syncWholeFile(ctx,"SoT/.omp/intercom.json",p(intercomDir,"config.json"),"omp intercom configuration already in sync","omp intercom configuration synced"),syncKitPlugin(ctx);let pluginsInstalled=await syncPlugins(ctx,paths);if(!ctx.dryRun){let currentRoot=ompPaths({home:ctx.home,env:process.env,platform:ctx.services.platform.raw()}).dataRoot;if(currentRoot!==paths.dataRoot)recordFailure(ctx,`omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`)}return{pluginsInstalled,agentDir}}function ompSummary(ctx,state){let{echo}=ctx.services.logger;if(echo(`omp: ${state.agentDir}`),!ctx.dryRun)echo(`omp plugins: ${state.pluginsInstalled} installed`)}function ompNextSteps(ctx){let steps=[];if(ctx.verbose||ctx.nextStepTriggers.ompRestart)steps.push("Restart omp to load any refreshed plugins, skills, or tools.");return steps}var SYNC_LOCK_WAIT_MS=120000,SYNC_LOCK_WAIT_ERROR="DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer";function syncLockWaitMs(err){let configured=process.env.DOCKS_KIT_SYNC_LOCK_WAIT_MS;if(configured===void 0||configured==="")return SYNC_LOCK_WAIT_MS;if(/^\d+$/.test(configured)&&Number.isSafeInteger(Number(configured)))return Number(configured);throw err(SYNC_LOCK_WAIT_ERROR),new ExitError(2)}var UNLOCKED_TOKENS={"--dry-run":!0,"-h":!0,"--help":!0};async function withKitLocks(err,paths,privateDirectory,body){let waitMs=syncLockWaitMs(err),held=[];try{for(let path of paths){if(!privateDirectory)mkdirSync5(dirname6(path),{recursive:!0,mode:448});let result=await acquireKitLock(path,{waitMs,privateDirectory});if(result.kind==="held")return err(`another docks-kit sync holds ${path}; run sync again after it ends`),1;held.push(result.lock)}return await body()}finally{for(let lock of held.reverse())releaseKitLock(lock)}}async function withSyncLock(ctx,args,body){if(ctx.dryRun||args.some((arg)=>Object.hasOwn(UNLOCKED_TOKENS,arg)))return await body();return await withKitLocks(ctx.services.logger.err,[syncLockPath(ctx.home)],!0,body)}function canonicalFolder(folder){let missing=[],current=folder;while(!existsSync8(current)&&dirname6(current)!==current)missing.unshift(basename3(current)),current=dirname6(current);return join8(realpathSync4.native(current),...missing)}function folderLockPaths(folders){return[...new Set(folders.map(canonicalFolder))].sort(compareCodepoints).map(folderSyncLockPath)}async function withFolderLocks(ctx,folders,body){if(ctx.dryRun)return await body();return await withKitLocks(ctx.services.logger.err,folderLockPaths(folders),!1,body)}async function withHomeAndFolderLocks(home,folders,err,body){return await withKitLocks(err,[syncLockPath(home)],!0,()=>withKitLocks(err,folderLockPaths(folders),!1,body))}async function engineSync(ctx,args){return await withSyncLock(ctx,args,()=>runSync3(ctx,args))}async function runSync3(ctx,args){parseArgs2(ctx,args);let omp=ompWriteFolders(ctx),folders=[omp.paths.agentDir,omp.intercomDir,omp.paths.dataRoot];return await withFolderLocks(ctx,folders,()=>runPipeline(ctx,omp))}async function runPipeline(ctx,omp){let{acquireTerminal,echo}=ctx.services.logger,lease=acquireTerminal("Syncing omp...");ctx.terminalLease=lease;let ompState;try{try{ompState=await ompSync(ctx,omp)}finally{lease.release(),ctx.terminalLease=void 0}}catch(error){throw printFailures(ctx),error}echo(""),echo("--- Sync complete ---"),echo(`Repo: ${ctx.repoDir}`),ompSummary(ctx,ompState);let advice=ompNextSteps(ctx);if(advice.length>0){echo("");for(let line of advice)echo(line)}if(printFailures(ctx))return 1;return 0}function printFailures(ctx){let{echo}=ctx.services.logger;if(ctx.failures.length===0)return!1;echo(""),echo("--- Failures ---");for(let failure of ctx.failures)echo(`- ${failure}`);return!0}async function runBounded(tasks,concurrency){let results=Array(tasks.length),failures=new Map,nextIndex=0,stopped=!1,workers=Array.from({length:Math.min(concurrency,tasks.length)},async()=>{for(;;){if(stopped||nextIndex>=tasks.length)return;let index=nextIndex;nextIndex+=1;try{results[index]=await tasks[index]()}catch(error){failures.set(index,error),stopped=!0}}});await Promise.all(workers);for(let index=0;index<tasks.length;index+=1)if(failures.has(index))throw failures.get(index);return results}async function runEngineNative(argv,services,options={}){let ctx,baseServices=services??makeEngineServices(),baseLogger=baseServices.logger,runServices={logger:{change:(msg)=>baseLogger.change(msg),progress:(msg)=>baseLogger.progress(msg),clearProgress:()=>baseLogger.clearProgress(),verbose:(msg)=>{if(ctx.verbose)baseLogger.verbose(msg)},warn:(msg)=>baseLogger.warn(msg),err:(msg)=>baseLogger.err(msg),echo:(line)=>baseLogger.echo(line),acquireTerminal:(message)=>baseLogger.acquireTerminal(message)},deps:baseServices.deps,platform:baseServices.platform};try{switch(ctx=makeCtx(runServices,{envGlobals:options.envGlobals===!0}),argv[0]){case"toolchain":return await modeToolchain(ctx,argv.slice(1));case"sync":return await engineSync(ctx,argv.slice(1));default:return await engineSync(ctx,argv)}}catch(e){if(e instanceof ExitError)return e.code;throw e}}var target=(id,platform,arch,unameKeys,processorArchitectures)=>({id,platform,arch,bunTarget:`bun-${id}`,artifact:platform==="windows"?`docks-kit-${id}.exe`:`docks-kit-${id}`,unameKeys,processorArchitectures}),HOST_TARGETS=[target("linux-x64","linux","x64",["Linux-x86_64"],[]),target("linux-arm64","linux","arm64",["Linux-aarch64"],[]),target("darwin-arm64","darwin","arm64",["Darwin-arm64"],[]),target("windows-x64","windows","x64",[],["AMD64"])];function targetFor(platform,arch){return HOST_TARGETS.find((t)=>t.platform===platform&&t.arch===arch)}function targetForHost(platform,arch){return targetFor(platformName(platform),arch)}var bashRemovedMessage="bash engine removed \u2014 recover at tag bash-engine-final",bashEngineRequested=()=>process.env.DOCKS_KIT_ENGINE==="bash",requireSupportedHost=()=>{let platform=process.platform,arch=process.arch;return targetForHost(platform,arch)!==void 0?void_3:bail(`unsupported host ${platform}/${arch}; docks-kit supports Linux on x64 and arm64, macOS on arm64, and Windows on x64`,2)},compiled=typeof Bun<"u"&&Bun.isStandaloneExecutable===!0,failureMessage=(error2)=>{if(error2 instanceof Error&&error2.message!=="")return error2.message;return typeof error2==="string"&&error2!==""?error2:"unknown error"},engine=(args)=>gen2(function*(){if(yield*requireSupportedHost(),bashEngineRequested())return yield*bail(bashRemovedMessage,2);let logger=yield*LoggerService,deps=yield*DependencyManagerService,platform=yield*PlatformService,code=yield*tryPromise2({try:()=>runEngineNative(args,{logger,deps,platform},{envGlobals:!1}),catch:(error2)=>new UserError({cause:error2,userMessage:`engine operation '${args.join(" ")||"default"}' failed: ${failureMessage(error2)}`})});if(code!==0)return yield*sync2(()=>process.exit(code))}),bail=(message,code=2)=>error(message).pipe(andThen2(sync2(()=>process.exit(code))));var overview_default="# docks-kit overview\n\ndocks-kit is a portable configuration kit for AI coding agents. Its Single\nSource of Truth (SoT) directory `SoT/.omp/` deploys to the user-config location\nof Oh My Pi (`omp`). Clone once, sync everywhere, and get a consistent\nAI-assisted dev environment on every machine.\n\n## Pieces\n\n| Piece | Role |\n|-------|------|\n| `SoT/.omp/` | omp config deployed to `~/.omp/agent/` (AGENTS.md, config.yml, models.yml, mcp.json) plus `intercom.json` for pi intercom, plus the `plugin/` tree, deployed to `~/.docks-kit/omp-plugin` and linked as the `docks-kit-omp` omp plugin |\n| `SoT/toolchain.json` | Verified-version floors for external tools (see `docks-kit docs toolchain`) |\n| `cli/src/generated/sotPayload.ts` | Deterministic generated payload embedded in standalone/npm execution |\n| `cli/src/engine-native/` | EngineNative mutation logic for sync/toolchain and the `docks-kit omp` session overlay |\n| `cli/` | This CLI (Effect 4 on Bun) plus bundled docs |\n| `docks-kit` / `docks-kit.ps1` | POSIX and Windows launchers: version-matching compiled binary \u2192 Bun-from-source, with Bun auto-install |\n\n## Design rules\n\n- **Idempotent**: every sync step is safe to re-run; no-change syncs are no-ops.\n- **Quiet on no-ops**: by default a re-run prints only real changes, warnings\n (with a platform-correct install command when a tool is missing), and the\n summary; `--verbose` / `-v` also prints the no-op confirmations.\n- **Additive by default**: user-only keys and plugins survive a plain sync.\n- **Engine/CLI split**: the CLI adds UX (typed flags, pickers, docs, JSON);\n EngineNative owns mutation. No-Bun recovery is a platform release binary.\n- **Authoring/runtime split**: changes begin in `SoT/`; build/prepack freshness\n checks keep the generated in-memory payload byte-identical for every runtime.\n\n## Where to go next\n\n- `docks-kit docs sync-layers` \u2014 what a sync actually touches\n- `docks-kit docs flags` \u2014 full flag reference\n- `docks-kit toolchain` \u2014 doctor view of this machine's external tools\n";var flags_default="# Flag reference\n\nConvention: global flags are unprefixed; a flag that touches one tool's\ndeployed config is `--<tool>-<setting>`.\n\n## Sync\n\n```\ndocks-kit sync # deploy the omp SoT\ndocks-kit sync --dry-run # preview it\n```\n\n`sync` deploys the omp SoT and takes no positional argument. A word after\n`sync`, such as `omp`, stops it with `Unexpected positional argument` and\nexit 1.\n\n## Global flags\n\n| Flag | Effect |\n|------|--------|\n| `--dry-run` | Preview without applying; takes no sync lock and no folder lock |\n| `--skip-plugin-refresh` | Install missing omp plugins but skip refresh-only updates |\n| `--verbose` / `-v` | Also print no-op confirmations (already in sync, up to date, left as-is); accepted on `sync` and `toolchain` |\n\n## Environment overrides\n\n| Variable | Effect |\n|----------|--------|\n| `DOCKS_KIT_SYNC_LOCK_WAIT_MS=<ms>` | Time that `sync` and `omp --fast` wait for another sync to release a sync lock. A non-negative safe integer in milliseconds (at most `9007199254740991`); unset or empty means `120000` (120 s). Any other value prints `DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer` and exits 2. |\n\n## Sync lock\n\n`sync` holds the lock `~/.cache/docks-kit/sync-lock.db` while it runs, so two\nruns never write the same files at once.\n\n- A run waits up to 120 s for another run to release the lock\n (`DOCKS_KIT_SYNC_LOCK_WAIT_MS` changes the wait). It then prints\n `another docks-kit sync holds <path>; run sync again after it ends` and\n exits 1 with no change.\n- Two homes can share an omp folder (`PI_CODING_AGENT_DIR`, `PI_CONFIG_DIR`,\n `XDG_DATA_HOME`, or a symlink). So a writing sync also holds\n `.docks-kit-sync-lock.db` inside each such folder that it writes: the omp\n agent folder, the intercom folder, and the omp data root. The held line then\n names that lock file.\n- A writing sync creates a missing folder of this set just before it takes the\n lock of that folder, after the locks of its ancestors in the set. Each folder\n that it creates gets mode 0700. The lock step does not change the mode of an\n existing folder. The omp pipeline then sets mode 0700 on the omp agent folder\n and the intercom folder.\n- A sync finds the omp folders once, before it takes the locks. The omp\n pipeline and each `omp` command that it starts use these folders. When the\n locked data root is the omp config root, each `omp` command starts without\n `XDG_DATA_HOME`. So a `$XDG_DATA_HOME/omp` folder that appears during the\n sync does not move the plugin data to a folder without a lock. A later\n `omp` uses that new folder, so the sync then prints\n `omp data root moved to <root> during the sync; run docks-kit sync again`\n and exits 1. The next sync locks the new folder and installs the plugins\n there.\n- The locks cover the folder that the kit writes into, not the target of a\n symlinked file. Two homes whose `config.yml` (or another deployed file) links\n to one shared file can still overwrite the merge of each other.\n- `docks-kit omp --fast` checks `config.yml` before it takes a lock. When the\n file is missing, it exits 2 and creates no omp folder. Otherwise it holds the\n sync lock and the omp agent folder lock while it rewrites `config.yml`. The\n wait and the held line are those of a sync.\n- A run with `--dry-run`, `-h`, or `--help` takes no lock. A dry run through\n the `DRY_RUN=1` env global of the private `native-raw` engine channel takes\n no lock either.\n- The lock goes when the run ends, also when the process is killed.\n- A held lock also delays the error of an invalid argument until the wait\n ends.\n\n## `omp` session flags\n\n| Flag | Effect |\n|------|--------|\n| `--model <selector>` | Session model for this run and later runs; rejected unless the live catalog reports zero input and output cost with `pricingStatus` `free` or `unknown`; recorded in `~/.docks-kit/kit.db` (table `omp_session`) |\n| `--pick` | Interactive picker over free catalog models; records the choice the same way |\n| `--fast` | Toggle `tier.openai` between `priority` and `none` in the deployed `~/.omp/agent/config.yml`, print the change, and exit; the same tier omp's `/fast on` selects for OpenAI and Codex models |\n\nThe launcher starts omp as\n`omp launch --config <overlay> --model <selector>[:<level>]`, followed by the\nremaining arguments in the same order. `docks-kit omp -p \"...\"` runs one\nprompt. `docks-kit omp --continue` resumes the previous session on the free\nmodel. A bare `docks-kit omp` opens an interactive session. `launch` makes omp\nread every forwarded word as message text, so no omp subcommand runs through\nthe launcher; run `omp` directly for a subcommand.\n\nThe launcher rejects a forwarded `--config`, `--model`, `--smol`, `--slow`,\n`--plan`, `--models`, `--provider`, `--prewalk-into`, or `--plan-yolo-into`,\nin the `--flag value` and the `--flag=value` form and also after a `--`. It\nexits with code 2 before omp starts. The error names the flag and the\nrecoveries: `--model <selector>` before the other arguments or `--pick` for a\nfree model, and `omp` directly for a paid model. For a forwarded `--config`, it\nalso names `PI_CONFIG_FILES` for another config file. The launcher sets\n`PI_SMOL_MODEL`, `PI_SLOW_MODEL`, and `PI_PLAN_MODEL` to the free role values,\nwarns once for each exported value that it replaces, and appends the overlay\nto `PI_CONFIG_FILES`. See\n[omp-models.md](omp-models.md#free-session-launcher-docks-kit-omp) for the\nfull policy and the paths that stay outside the launcher.\n\nThe launcher changes no deployed file and never invokes `sync`, except for\n`--fast`, which changes only `tier.openai` and launches nothing. `--fast` over\n`ultrafast` selects `priority`.\nThe boundary opens at the first token that is neither a declared launcher\nflag nor a declared global flag. Declared flags stay with docks-kit and\nnever reach omp:\n\n- `--model`, `--pick`, `--fast`\n- `--help`, `--version`, `--log-level`, `--wizard`, `--completions`\n\nThe same names, except `--model`, stay reachable on omp behind an explicit\ndelimiter. `docks-kit omp -- --help` prints the help of `omp launch`. A\nforwarded `--model` stops the launcher with exit 2, also behind `--`.\n\n## `scratch` and `tidy`\n\n| Command | Effect |\n|------|--------|\n| `scratch new <label>` | Create a private directory (mode 0700) `~/.cache/docks-kit/scratch/<label>-XXXXXX` and print its path; the label matches `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$` |\n| `scratch remove <path>...` | Remove each path whose real path is strictly inside the scratch root, the system temporary directory, or `/var/tmp`; print `removed <path>` or `refused <path>: <reason>`; exit 1 when any path is refused |\n| `tidy` | List the safe leftover actions (`remove`, `stop`) and the kept candidates (`keep`) with reasons; change nothing |\n| `tidy --apply` | Take the lock `~/.cache/docks-kit/tidy-lock.db`, then plan, perform those actions, and append the outcomes to `~/.cache/docks-kit/tidy.log`; exit 1 when an action fails. When another run holds the lock, print only `another docks-kit tidy run holds <path>`, with no plan and no report, and exit 0. A dry run (`tidy` without `--apply`) and the `--report` sections take no lock |\n| `tidy --repo <path>` | Take the worktree candidates only from that repository, at any location |\n| `tidy --report` | After the plan, print read-only sections on memory, temporary directories, processes, Docker, caches, Trash, git, agent histories, scheduled jobs, and global installs |\n";var toolchain_default="# Toolchain: verified-version floors\n\n`SoT/toolchain.json` declares every external tool the kit touches, with:\n\n| Field | Meaning |\n|-------|---------|\n| `kind` | `check` (doctor visibility) / `managed` (kit-managed install) / `pin` (no binary \u2014 a version pin for a package that the kit installs through another tool, such as `omp install` for `pi-intercom`; the required `via` field names that tool in the doctor table) |\n| `policy` | Installation policy; `present` installs when missing and never upgrades |\n| `floor` | Minimum acceptable version shown in the doctor table |\n| `verified` | Last kit-tested version and the exact pin for kit-driven installs |\n| `pinnable` | Whether an exact version can be installed |\n\n`docks-kit toolchain check` reports each installed version against the\nmanifest's `floor` and `verified` columns.\nBefore running `bun install --frozen-lockfile`, the checkout launchers reject Bun versions below the manifest's `floor` and direct the user to `bun upgrade`.\nTheir generated Bun floor is intentionally separate from the generated `verified` pin: the floor gates lockfile compatibility, while the verified pin selects the exact release for kit-driven installs.\n\n## Managed tools\n\n- **bun** \u2014 policy `present`: installed from the pinned `verified` release and\n never auto-upgraded. `bun.ts` `bunBootstrap` owns one per-engine-run memo\n shared by the omp pipeline and direct `toolchain ensure bun` on every\n supported host. The POSIX modules download `install.sh` with curl and run it\n with Bash. The Windows module downloads `install.ps1` with curl and runs it\n through `powershell.exe`. When Bun is already present, `toolchain ensure bun`\n installs nothing and warns if that Bun is below the `floor`.\n\njq and curl are `check` rows, not global prerequisites. jq is not consumed by\nnormal sync. curl is checked only when a requested Bun bootstrap must download\nan installer. An already-present Bun skips that download on every host.\n\n## Supply-chain stance\n\nEvery kit-driven package install from npm, GitHub releases, or\n`omp install` is pinned to a `SoT/toolchain.json` `verified` version \u2014 never\nfloating `@latest` (the npm-worm / Shai-Hulud attack surface). That includes\nthe release workflow (actions pinned to commit SHAs, exact bun/npm versions).\nThe kit installs no omp marketplace plugin: the kit plugin ships from this\nrepository, and sync tries to retire the user-scope installs of the former `docks` marketplace plugins (see\n`sync-layers`). Any new install surface, a new marketplace or plugin source\nincluded, needs a manifest pin first.\n\nThe kit's own package is the single exemption from the `@latest` ban. `install.sh` and `install.ps1`\nend with `bun add -g docks-kit@latest` because a global installer that pinned\nitself would install a fixed old kit forever. The exemption covers `docks-kit`\nalone; both installers still pin the Bun installer they download to the\nmanifest's `verified` version.\n\n## Commands\n\n```text\ndocks-kit toolchain check # doctor table\ndocks-kit toolchain ensure bun # ensure the only managed tool\ndocks-kit toolchain ensure bun --dry-run # preview the Bun install\ndocks-kit toolchain outdated [--refresh] # verified pins vs newest upstream release\n```\n\n`docks-kit toolchain outdated` reads each tool's optional `upstream` entry in\n`SoT/toolchain.json`. An `npm` entry reads the registry `latest` tag. A\n`github` entry reads the latest release tag and strips `tagPrefix`.\nSet `GITHUB_TOKEN` or `GH_TOKEN` to raise the GitHub rate limit. Successful\nlookups cache for 24 hours in `~/.docks-kit/kit.db`; `--refresh` bypasses the\ncache. The report never installs anything and never edits a pin. A failed\nlookup prints `lookup failed: <reason>` and the command still exits 0.\n";var sync_layers_default="# Sync layers\n\n`docks-kit sync` deploys the omp SoT. It takes no positional target. Sync\nwrites no `.agents` or `.claude` folder of its own; omp's folders follow\n`PI_CONFIG_DIR`, `PI_CODING_AGENT_DIR`, and `XDG_DATA_HOME`, so an override\nthat points into one of those folders makes omp's files go there. omp uses\n`XDG_DATA_HOME` only on Linux and macOS, only while `PI_CODING_AGENT_DIR`\ndoes not move the agent folder, and only after the omp folder under it\nexists. Sync also writes the kit plugin to `~/.docks-kit/omp-plugin`.\n\n## omp (\u2192 resolved agent dir, intercom root)\n\nAGENTS.md, mcp.json, and intercom config.json are whole-file deploys.\nconfig.yml and models.yml are deep-merged (SoT keys win, mapping nodes merge,\ndeployed-only keys survive; config.yml also drops stale slash-bearing\n`retry.fallbackChains` wildcards). A SoT list replaces the deployed list, except\nconfig.yml `bash.patterns`: the merge keeps user rules and groups all rules as\nkit deny, user deny, user prompt, kit prompt (the kit ships none since 0.22.8),\nother user rules, and kit allow, so no allow loosens a deny or a prompt (see\n`docks-kit docs command-guards`). After each merge, every sync (no flag\nneeded) force-prunes the `ompRemovals.ts` retired-key inventory:\nthe retired kit `bash.patterns` rules in `OMP_RETIRED_BASH_RULES` (exact\n`match` and `approval` pairs, including the 492 former kit prompt rules\nretired in 0.22.8), config.yml keys whose deployed value still equals the value the kit used to\nship, `providers.webSearchOrder` at any value, and the retired\n`providers.anthropic.modelOverrides.claude-opus-5-5` block in models.yml while\nit still matches the shipped block.\nDirectories are mode 0700 and files mode 0600. Then the plugin pass reads the\ninventory from `omp plugin list --json`, tries to retire the former marketplace\nplugins (user-scope installs only; see below), installs `pi-intercom` at its\n`SoT/toolchain.json` pin, and links the kit plugin `docks-kit-omp`.\n\nThe kit plugin now ships the docks and plan-lifecycle skills, the\n`code-reviewer` and `plan-reviewer` agents, and the `verify-gate` and\n`context-tree-nudge` extensions. So sync installs no plugin from the `docks`\nmarketplace. Each real sync tries to retire the former marketplace plugins.\nWhen the inventory cannot be read, it warns and skips this step; a later sync\ntries again. Otherwise:\n\n- For each of `docks@docks` and `plan-lifecycle@docks` with a `scope: \"user\"`\n inventory row, it runs `omp plugin uninstall --scope user <id>`.\n- For each `scope: \"project\"` row of these ids, it changes nothing in that\n project and warns\n `omp plugin <id> is installed at project scope and docks-kit no longer ships it; run from that project: omp plugin uninstall --scope project <id>`.\n- When no user uninstall failed, it runs `omp plugin marketplace remove docks`\n if the active registry (`<data root>/marketplaces.json`) lists `docks`, or\n if no active registry exists and the legacy config-root registry lists it.\n omp copies the legacy registry forward only when no active registry exists,\n so a legacy entry beside an active registry is stale and starts no command.\n- A failed uninstall or removal goes to the failure ledger with the manual\n command, for example\n `omp plugin operation failed for docks@docks: <detail>; run manually: omp plugin uninstall --scope user docks@docks`.\n- When the inventory cannot be read, the sync warns\n `omp plugin inventory unavailable \u2014 retirement of the docks marketplace plugins skipped until the next sync; pi-intercom and the kit plugin take the full refresh path`.\n- The sync removes the folder `~/.cache/docks-kit/omp-plugin-upgrades/` of the\n retired plugin upgrade log when it exists.\n\n`--skip-plugin-refresh` does not skip the retirement or the kit plugin link. It\nonly keeps a present `pi-intercom` at its installed version. A repeat run after\na successful retirement runs no uninstall and no removal.\n\nAfter a plugin operation, the sync prints one line that names each operation,\nfor example\n`omp plugins synced: docks@docks uninstalled, plan-lifecycle@docks uninstalled, docks marketplace removed, pi-intercom 0.14.0 (new), docks-kit-omp linked`.\nEach uninstall sets the restart next step\n`Restart omp to load any refreshed plugins, skills, or tools.`, because the\nretired plugins ship extensions, and omp loads extensions only at startup. An\nnpm install, a link, and a changed kit plugin file or omp config file also set\nit.\n\nA dry run invokes no omp subcommand. It prints\n`[dry-run] omp plugin uninstall --scope user docks@docks` and the same line\nfor `plan-lifecycle@docks`, and\n`[dry-run] omp plugin marketplace remove docks` when a registry lists `docks`.\n\nPaths mirror upstream `dirs.ts` `DirResolver`, resolved from the environment\nplus directory probes, so a dry run still runs no omp subcommand. The agent\ndirectory is `<config root>/agent`, where the config root is\n`~/<PI_CONFIG_DIR or .omp>` plus `profiles/<name>` under an active profile\n(`OMP_PROFILE`, else legacy `PI_PROFILE`). For the default profile only,\n`PI_CODING_AGENT_DIR` replaces the agent directory outright. The agent\ndirectory never moves under XDG. Only the data root that holds\n`marketplaces.json` does: on Linux and macOS, with no agent-dir override\nactive, an existing `$XDG_DATA_HOME/omp` (or `$XDG_DATA_HOME/omp/profiles/<name>`\nfor a named profile) is adopted. Under a named profile, the intercom file goes\ninto `<agent directory>/intercom`. Otherwise it goes into\n`$PI_CODING_AGENT_DIR/intercom` when that variable is set, else\n`~/.pi/agent/intercom`.\n\n## Additive by default\n\nSync has no removal flag. A key, plugin, or file that only the user added\nstays. Three passes remove kit content on every sync: the `ompRemovals.ts`\nretired-key inventory above, the kit plugin pass, which removes stale files\nfrom the kit-owned `~/.docks-kit/omp-plugin`, and the retirement of the former\nmarketplace plugins above, which earlier kit versions installed.\n";var install_default=`# Installing docks-kit
|
|
24178
|
+
${priorComment}`:priorComment}for(let depth=owners.length-1;depth>=1;depth--){let mapping=owners[depth];if(mapping===void 0||mapping.items.length>0)break;let owner=owners[depth-1],segment=segments[depth-1];if(owner===void 0||segment===void 0)break;let index=indexOfKey(owner,segment);if(index>=0)owner.items.splice(index,1)}return!0}function retiredKeys(entries){return(root)=>{let pruned=[];for(let[path,matches]of entries)if(deletePath(root,path.split("."),matches))pruned.push(path);return pruned}}var retiredBashRules=(root)=>{let bash=root.get("bash"),patterns=$isMap(bash)?bash.get("patterns"):void 0;if(!$isSeq(patterns))return[];let pruned=[];return patterns.items=patterns.items.filter((item)=>{let key=bashPatternKey(item),name=key===void 0?void 0:OMP_RETIRED_BASH_KEYS.get(key);if(name===void 0)return!0;return pruned.push(name),!1}),pruned};function pruneRetired(ctx,file,label,pruners,alreadyBackedUp){let{change,echo,verbose,warn}=ctx.services.logger;if(!existsSync7(file))return 0;let doc=$parseDocument(readFileSync7(file,"utf8")),parseError=doc.errors[0];if(parseError!==void 0)return warn(`omp ${label} unreadable, retired entries not pruned: ${parseError.message}`),0;let contents=doc.contents;if(!$isMap(contents))return 0;let pruned=pruners.flatMap((prune)=>prune(contents));if(pruned.length===0)return verbose(`omp ${label} carries no retired entries`),0;if(ctx.dryRun)return echo(`[dry-run] prune ${file}: ${pruned.join(", ")}`),pruned.length;if(!alreadyBackedUp)backupPrivateFile(file);replaceFile(file,String(doc),{mode:384});let backupNote=alreadyBackedUp?"":` (backup at ${label}.bak)`;return change(`omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}${backupNote}`),pruned.length}function syncOmpRemovals(ctx,configFile,alreadyBackedUp){return pruneRetired(ctx,configFile,"config.yml",[retiredKeys([...OMP_RETIRED_VALUES.map(([path,value])=>[path,Array.isArray(value)?(node)=>$isSeq(node)&&isDeepStrictEqual(node.toJSON(),value):(node)=>$isScalar(node)&&node.value===value]),...OMP_RETIRED_KEYS.map((path)=>[path,()=>!0])]),retiredBashRules],alreadyBackedUp)}function syncOmpModelRemovals(ctx,modelsFile,alreadyBackedUp){return pruneRetired(ctx,modelsFile,"models.yml",[retiredKeys(OMP_RETIRED_MODEL_BLOCKS.map(([path,block])=>[path,(node)=>$isMap(node)&&isDeepStrictEqual(node.toJSON(),block)]))],alreadyBackedUp)}function ompWriteFolders(ctx){let paths=ompPaths({home:ctx.home,env:process.env,platform:ctx.services.platform.raw()}),intercomRootSetting=process.env.PI_CODING_AGENT_DIR?.trim(),intercomRoot=paths.profile!==void 0?paths.agentDir:intercomRootSetting!==void 0&&intercomRootSetting!==""?isAbsolute5(intercomRootSetting)?intercomRootSetting:resolve7(process.cwd(),intercomRootSetting):p(ctx.home,".pi","agent");return{paths,intercomDir:p(intercomRoot,"intercom")}}async function ompSync(ctx,folders){await bunBootstrap(ctx,ctx.services);let{paths,intercomDir}=folders,agentDir=paths.agentDir;if(!ctx.dryRun)ensureDirectory(agentDir);syncWholeFile(ctx,"SoT/.omp/AGENTS.md",p(agentDir,"AGENTS.md"),"omp AGENTS.md already in sync","omp AGENTS.md synced"),syncWholeFile(ctx,"SoT/.omp/mcp.json",p(agentDir,"mcp.json"),"omp mcp.json already in sync","omp mcp.json synced");let configFile=p(agentDir,"config.yml"),configBackedUp=syncMergedYaml(ctx,"SoT/.omp/config.yml",configFile,mergeOmpConfig);syncOmpRemovals(ctx,configFile,configBackedUp);let modelsFile=p(agentDir,"models.yml"),modelsBackedUp=syncMergedYaml(ctx,"SoT/.omp/models.yml",modelsFile,mergeOmpModels);if(syncOmpModelRemovals(ctx,modelsFile,modelsBackedUp),!ctx.dryRun)ensureDirectory(intercomDir);syncWholeFile(ctx,"SoT/.omp/intercom.json",p(intercomDir,"config.json"),"omp intercom configuration already in sync","omp intercom configuration synced"),syncKitPlugin(ctx);let pluginsInstalled=await syncPlugins(ctx,paths);if(!ctx.dryRun){let currentRoot=ompPaths({home:ctx.home,env:process.env,platform:ctx.services.platform.raw()}).dataRoot;if(currentRoot!==paths.dataRoot)recordFailure(ctx,`omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`)}return{pluginsInstalled,agentDir}}function ompSummary(ctx,state){let{echo}=ctx.services.logger;if(echo(`omp: ${state.agentDir}`),!ctx.dryRun)echo(`omp plugins: ${state.pluginsInstalled} installed`)}function ompNextSteps(ctx){let steps=[];if(ctx.verbose||ctx.nextStepTriggers.ompRestart)steps.push("Restart omp to load any refreshed plugins, skills, or tools.");return steps}var SYNC_LOCK_WAIT_MS=120000,SYNC_LOCK_WAIT_ERROR="DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer";function syncLockWaitMs(err){let configured=process.env.DOCKS_KIT_SYNC_LOCK_WAIT_MS;if(configured===void 0||configured==="")return SYNC_LOCK_WAIT_MS;if(/^\d+$/.test(configured)&&Number.isSafeInteger(Number(configured)))return Number(configured);throw err(SYNC_LOCK_WAIT_ERROR),new ExitError(2)}var UNLOCKED_TOKENS={"--dry-run":!0,"-h":!0,"--help":!0};async function withKitLocks(err,paths,privateDirectory,body){let waitMs=syncLockWaitMs(err),held=[];try{for(let path of paths){if(!privateDirectory)mkdirSync5(dirname6(path),{recursive:!0,mode:448});let result=await acquireKitLock(path,{waitMs,privateDirectory});if(result.kind==="held")return err(`another docks-kit sync holds ${path}; run sync again after it ends`),1;held.push(result.lock)}return await body()}finally{for(let lock of held.reverse())releaseKitLock(lock)}}async function withSyncLock(ctx,args,body){if(ctx.dryRun||args.some((arg)=>Object.hasOwn(UNLOCKED_TOKENS,arg)))return await body();return await withKitLocks(ctx.services.logger.err,[syncLockPath(ctx.home)],!0,body)}function canonicalFolder(folder){let missing=[],current=folder;while(!existsSync8(current)&&dirname6(current)!==current)missing.unshift(basename3(current)),current=dirname6(current);return join8(realpathSync4.native(current),...missing)}function folderLockPaths(folders){return[...new Set(folders.map(canonicalFolder))].sort(compareCodepoints).map(folderSyncLockPath)}async function withFolderLocks(ctx,folders,body){if(ctx.dryRun)return await body();return await withKitLocks(ctx.services.logger.err,folderLockPaths(folders),!1,body)}async function withHomeAndFolderLocks(home,folders,err,body){return await withKitLocks(err,[syncLockPath(home)],!0,()=>withKitLocks(err,folderLockPaths(folders),!1,body))}async function engineSync(ctx,args){return await withSyncLock(ctx,args,()=>runSync3(ctx,args))}async function runSync3(ctx,args){parseArgs2(ctx,args);let omp=ompWriteFolders(ctx),folders=[omp.paths.agentDir,omp.intercomDir,omp.paths.dataRoot];return await withFolderLocks(ctx,folders,()=>runPipeline(ctx,omp))}async function runPipeline(ctx,omp){let{acquireTerminal,echo}=ctx.services.logger,lease=acquireTerminal("Syncing omp...");ctx.terminalLease=lease;let ompState;try{try{ompState=await ompSync(ctx,omp)}finally{lease.release(),ctx.terminalLease=void 0}}catch(error){throw printFailures(ctx),error}echo(""),echo("--- Sync complete ---"),echo(`Repo: ${ctx.repoDir}`),ompSummary(ctx,ompState);let advice=ompNextSteps(ctx);if(advice.length>0){echo("");for(let line of advice)echo(line)}if(printFailures(ctx))return 1;return 0}function printFailures(ctx){let{echo}=ctx.services.logger;if(ctx.failures.length===0)return!1;echo(""),echo("--- Failures ---");for(let failure of ctx.failures)echo(`- ${failure}`);return!0}async function runBounded(tasks,concurrency){let results=Array(tasks.length),failures=new Map,nextIndex=0,stopped=!1,workers=Array.from({length:Math.min(concurrency,tasks.length)},async()=>{for(;;){if(stopped||nextIndex>=tasks.length)return;let index=nextIndex;nextIndex+=1;try{results[index]=await tasks[index]()}catch(error){failures.set(index,error),stopped=!0}}});await Promise.all(workers);for(let index=0;index<tasks.length;index+=1)if(failures.has(index))throw failures.get(index);return results}async function runEngineNative(argv,services,options={}){let ctx,baseServices=services??makeEngineServices(),baseLogger=baseServices.logger,runServices={logger:{change:(msg)=>baseLogger.change(msg),progress:(msg)=>baseLogger.progress(msg),clearProgress:()=>baseLogger.clearProgress(),verbose:(msg)=>{if(ctx.verbose)baseLogger.verbose(msg)},warn:(msg)=>baseLogger.warn(msg),err:(msg)=>baseLogger.err(msg),echo:(line)=>baseLogger.echo(line),acquireTerminal:(message)=>baseLogger.acquireTerminal(message)},deps:baseServices.deps,platform:baseServices.platform};try{switch(ctx=makeCtx(runServices,{envGlobals:options.envGlobals===!0}),argv[0]){case"toolchain":return await modeToolchain(ctx,argv.slice(1));case"sync":return await engineSync(ctx,argv.slice(1));default:return await engineSync(ctx,argv)}}catch(e){if(e instanceof ExitError)return e.code;throw e}}var target=(id,platform,arch,unameKeys,processorArchitectures)=>({id,platform,arch,unameKeys,processorArchitectures}),HOST_TARGETS=[target("linux-x64","linux","x64",["Linux-x86_64"],[]),target("linux-arm64","linux","arm64",["Linux-aarch64"],[]),target("darwin-arm64","darwin","arm64",["Darwin-arm64"],[]),target("windows-x64","windows","x64",[],["AMD64"])];function targetFor(platform,arch){return HOST_TARGETS.find((t)=>t.platform===platform&&t.arch===arch)}function targetForHost(platform,arch){return targetFor(platformName(platform),arch)}var bashRemovedMessage="bash engine removed \u2014 recover at tag bash-engine-final",bashEngineRequested=()=>process.env.DOCKS_KIT_ENGINE==="bash",requireSupportedHost=()=>{let platform=process.platform,arch=process.arch;return targetForHost(platform,arch)!==void 0?void_3:bail(`unsupported host ${platform}/${arch}; docks-kit supports Linux on x64 and arm64, macOS on arm64, and Windows on x64`,2)},failureMessage=(error2)=>{if(error2 instanceof Error&&error2.message!=="")return error2.message;return typeof error2==="string"&&error2!==""?error2:"unknown error"},engine=(args)=>gen2(function*(){if(yield*requireSupportedHost(),bashEngineRequested())return yield*bail(bashRemovedMessage,2);let logger=yield*LoggerService,deps=yield*DependencyManagerService,platform=yield*PlatformService,code=yield*tryPromise2({try:()=>runEngineNative(args,{logger,deps,platform},{envGlobals:!1}),catch:(error2)=>new UserError({cause:error2,userMessage:`engine operation '${args.join(" ")||"default"}' failed: ${failureMessage(error2)}`})});if(code!==0)return yield*sync2(()=>process.exit(code))}),bail=(message,code=2)=>error(message).pipe(andThen2(sync2(()=>process.exit(code))));var overview_default="# docks-kit overview\n\ndocks-kit is a portable configuration kit for AI coding agents. Its Single\nSource of Truth (SoT) directory `SoT/.omp/` deploys to the user-config location\nof Oh My Pi (`omp`). Clone once, sync everywhere, and get a consistent\nAI-assisted dev environment on every machine.\n\n## Pieces\n\n| Piece | Role |\n|-------|------|\n| `SoT/.omp/` | omp config deployed to `~/.omp/agent/` (AGENTS.md, config.yml, models.yml, mcp.json) plus `intercom.json` for pi intercom, plus the `plugin/` tree, deployed to `~/.docks-kit/omp-plugin` and linked as the `docks-kit-omp` omp plugin |\n| `SoT/toolchain.json` | Verified-version floors for external tools (see `docks-kit docs toolchain`) |\n| `cli/src/generated/sotPayload.ts` | Deterministic generated payload embedded in the npm bundle |\n| `cli/src/engine-native/` | EngineNative mutation logic for sync/toolchain and the `docks-kit omp` session overlay |\n| `cli/` | This CLI (Effect 4 on Bun) plus bundled docs |\n| `docks-kit` / `docks-kit.ps1` | POSIX and Windows launchers: host check \u2192 Bun-from-source, with Bun auto-install |\n\n## Design rules\n\n- **Idempotent**: every sync step is safe to re-run; no-change syncs are no-ops.\n- **Quiet on no-ops**: by default a re-run prints only real changes, warnings\n (with a platform-correct install command when a tool is missing), and the\n summary; `--verbose` / `-v` also prints the no-op confirmations.\n- **Additive by default**: user-only keys and plugins survive a plain sync.\n- **Engine/CLI split**: the CLI adds UX (typed flags, pickers, docs, JSON);\n EngineNative owns mutation. Every install runs on Bun.\n- **Authoring/runtime split**: changes begin in `SoT/`; build/prepack freshness\n checks keep the generated in-memory payload byte-identical for every runtime.\n\n## Where to go next\n\n- `docks-kit docs sync-layers` \u2014 what a sync actually touches\n- `docks-kit docs flags` \u2014 full flag reference\n- `docks-kit toolchain` \u2014 doctor view of this machine's external tools\n";var flags_default="# Flag reference\n\nConvention: global flags are unprefixed; a flag that touches one tool's\ndeployed config is `--<tool>-<setting>`.\n\n## Sync\n\n```\ndocks-kit sync # deploy the omp SoT\ndocks-kit sync --dry-run # preview it\n```\n\n`sync` deploys the omp SoT and takes no positional argument. A word after\n`sync`, such as `omp`, stops it with `Unexpected positional argument` and\nexit 1.\n\n## Global flags\n\n| Flag | Effect |\n|------|--------|\n| `--dry-run` | Preview without applying; takes no sync lock and no folder lock |\n| `--skip-plugin-refresh` | Install missing omp plugins but skip refresh-only updates |\n| `--verbose` / `-v` | Also print no-op confirmations (already in sync, up to date, left as-is); accepted on `sync` and `toolchain` |\n\n## Environment overrides\n\n| Variable | Effect |\n|----------|--------|\n| `DOCKS_KIT_SYNC_LOCK_WAIT_MS=<ms>` | Time that `sync` and `omp --fast` wait for another sync to release a sync lock. A non-negative safe integer in milliseconds (at most `9007199254740991`); unset or empty means `120000` (120 s). Any other value prints `DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer` and exits 2. |\n\n## Sync lock\n\n`sync` holds the lock `~/.cache/docks-kit/sync-lock.db` while it runs, so two\nruns never write the same files at once.\n\n- A run waits up to 120 s for another run to release the lock\n (`DOCKS_KIT_SYNC_LOCK_WAIT_MS` changes the wait). It then prints\n `another docks-kit sync holds <path>; run sync again after it ends` and\n exits 1 with no change.\n- Two homes can share an omp folder (`PI_CODING_AGENT_DIR`, `PI_CONFIG_DIR`,\n `XDG_DATA_HOME`, or a symlink). So a writing sync also holds\n `.docks-kit-sync-lock.db` inside each such folder that it writes: the omp\n agent folder, the intercom folder, and the omp data root. The held line then\n names that lock file.\n- A writing sync creates a missing folder of this set just before it takes the\n lock of that folder, after the locks of its ancestors in the set. Each folder\n that it creates gets mode 0700. The lock step does not change the mode of an\n existing folder. The omp pipeline then sets mode 0700 on the omp agent folder\n and the intercom folder.\n- A sync finds the omp folders once, before it takes the locks. The omp\n pipeline and each `omp` command that it starts use these folders. When the\n locked data root is the omp config root, each `omp` command starts without\n `XDG_DATA_HOME`. So a `$XDG_DATA_HOME/omp` folder that appears during the\n sync does not move the plugin data to a folder without a lock. A later\n `omp` uses that new folder, so the sync then prints\n `omp data root moved to <root> during the sync; run docks-kit sync again`\n and exits 1. The next sync locks the new folder and installs the plugins\n there.\n- The locks cover the folder that the kit writes into, not the target of a\n symlinked file. Two homes whose `config.yml` (or another deployed file) links\n to one shared file can still overwrite the merge of each other.\n- `docks-kit omp --fast` checks `config.yml` before it takes a lock. When the\n file is missing, it exits 2 and creates no omp folder. Otherwise it holds the\n sync lock and the omp agent folder lock while it rewrites `config.yml`. The\n wait and the held line are those of a sync.\n- A run with `--dry-run`, `-h`, or `--help` takes no lock. A dry run through\n the `DRY_RUN=1` env global of the private `native-raw` engine channel takes\n no lock either.\n- The lock goes when the run ends, also when the process is killed.\n- A held lock also delays the error of an invalid argument until the wait\n ends.\n\n## `omp` session flags\n\n| Flag | Effect |\n|------|--------|\n| `--model <selector>` | Session model for this run and later runs; rejected unless the live catalog reports zero input and output cost with `pricingStatus` `free` or `unknown`; recorded in `~/.docks-kit/kit.db` (table `omp_session`) |\n| `--pick` | Interactive picker over free catalog models; records the choice the same way |\n| `--fast` | Toggle `tier.openai` between `priority` and `none` in the deployed `~/.omp/agent/config.yml`, print the change, and exit; the same tier omp's `/fast on` selects for OpenAI and Codex models |\n\nThe launcher starts omp as\n`omp launch --config <overlay> --model <selector>[:<level>]`, followed by the\nremaining arguments in the same order. `docks-kit omp -p \"...\"` runs one\nprompt. `docks-kit omp --continue` resumes the previous session on the free\nmodel. A bare `docks-kit omp` opens an interactive session. `launch` makes omp\nread every forwarded word as message text, so no omp subcommand runs through\nthe launcher; run `omp` directly for a subcommand.\n\nThe launcher rejects a forwarded `--config`, `--model`, `--smol`, `--slow`,\n`--plan`, `--models`, `--provider`, `--prewalk-into`, or `--plan-yolo-into`,\nin the `--flag value` and the `--flag=value` form and also after a `--`. It\nexits with code 2 before omp starts. The error names the flag and the\nrecoveries: `--model <selector>` before the other arguments or `--pick` for a\nfree model, and `omp` directly for a paid model. For a forwarded `--config`, it\nalso names `PI_CONFIG_FILES` for another config file. The launcher sets\n`PI_SMOL_MODEL`, `PI_SLOW_MODEL`, and `PI_PLAN_MODEL` to the free role values,\nwarns once for each exported value that it replaces, and appends the overlay\nto `PI_CONFIG_FILES`. See\n[omp-models.md](omp-models.md#free-session-launcher-docks-kit-omp) for the\nfull policy and the paths that stay outside the launcher.\n\nThe launcher changes no deployed file and never invokes `sync`, except for\n`--fast`, which changes only `tier.openai` and launches nothing. `--fast` over\n`ultrafast` selects `priority`.\nThe boundary opens at the first token that is neither a declared launcher\nflag nor a declared global flag. Declared flags stay with docks-kit and\nnever reach omp:\n\n- `--model`, `--pick`, `--fast`\n- `--help`, `--version`, `--log-level`, `--wizard`, `--completions`\n\nThe same names, except `--model`, stay reachable on omp behind an explicit\ndelimiter. `docks-kit omp -- --help` prints the help of `omp launch`. A\nforwarded `--model` stops the launcher with exit 2, also behind `--`.\n\n## `scratch` and `tidy`\n\n| Command | Effect |\n|------|--------|\n| `scratch new <label>` | Create a private directory (mode 0700) `~/.cache/docks-kit/scratch/<label>-XXXXXX` and print its path; the label matches `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$` |\n| `scratch remove <path>...` | Remove each path whose real path is strictly inside the scratch root, the system temporary directory, or `/var/tmp`; print `removed <path>` or `refused <path>: <reason>`; exit 1 when any path is refused |\n| `tidy` | List the safe leftover actions (`remove`, `stop`) and the kept candidates (`keep`) with reasons; change nothing |\n| `tidy --apply` | Take the lock `~/.cache/docks-kit/tidy-lock.db`, then plan, perform those actions, and append the outcomes to `~/.cache/docks-kit/tidy.log`; exit 1 when an action fails. When another run holds the lock, print only `another docks-kit tidy run holds <path>`, with no plan and no report, and exit 0. A dry run (`tidy` without `--apply`) and the `--report` sections take no lock |\n| `tidy --repo <path>` | Take the worktree candidates only from that repository, at any location |\n| `tidy --report` | After the plan, print read-only sections on memory, temporary directories, processes, Docker, caches, Trash, git, agent histories, scheduled jobs, and global installs |\n";var toolchain_default="# Toolchain: verified-version floors\n\n`SoT/toolchain.json` declares every external tool the kit touches, with:\n\n| Field | Meaning |\n|-------|---------|\n| `kind` | `check` (doctor visibility) / `managed` (kit-managed install) / `pin` (no binary \u2014 a version pin for a package that the kit installs through another tool, such as `omp install` for `pi-intercom`; the required `via` field names that tool in the doctor table) |\n| `policy` | Installation policy; `present` installs when missing and never upgrades |\n| `floor` | Minimum acceptable version shown in the doctor table |\n| `verified` | Last kit-tested version and the exact pin for kit-driven installs |\n| `pinnable` | Whether an exact version can be installed |\n\n`docks-kit toolchain check` reports each installed version against the\nmanifest's `floor` and `verified` columns.\nBefore running `bun install --frozen-lockfile`, the checkout launchers reject Bun versions below the manifest's `floor` and direct the user to `bun upgrade`.\nTheir generated Bun floor is intentionally separate from the generated `verified` pin: the floor gates lockfile compatibility, while the verified pin selects the exact release for kit-driven installs.\n\n## Managed tools\n\n- **bun** \u2014 policy `present`: installed from the pinned `verified` release and\n never auto-upgraded. `bun.ts` `bunBootstrap` owns one per-engine-run memo\n shared by the omp pipeline and direct `toolchain ensure bun` on every\n supported host. The POSIX modules download `install.sh` with curl and run it\n with Bash. The Windows module downloads `install.ps1` with curl and runs it\n through `powershell.exe`. When Bun is already present, `toolchain ensure bun`\n installs nothing and warns if that Bun is below the `floor`.\n\njq and curl are `check` rows, not global prerequisites. jq is not consumed by\nnormal sync. curl is checked only when a requested Bun bootstrap must download\nan installer. An already-present Bun skips that download on every host.\n\n## Supply-chain stance\n\nEvery kit-driven package install from npm, GitHub releases, or\n`omp install` is pinned to a `SoT/toolchain.json` `verified` version \u2014 never\nfloating `@latest` (the npm-worm / Shai-Hulud attack surface). That includes\nthe release workflow (actions pinned to commit SHAs, exact bun/npm versions).\nThe kit installs no omp marketplace plugin: the kit plugin ships from this\nrepository, and sync tries to retire the user-scope installs of the former `docks` marketplace plugins (see\n`sync-layers`). Any new install surface, a new marketplace or plugin source\nincluded, needs a manifest pin first.\n\nThe kit's own package is the single exemption from the `@latest` ban. `install.sh` and `install.ps1`\nend with `bun add -g docks-kit@latest` because a global installer that pinned\nitself would install a fixed old kit forever. The exemption covers `docks-kit`\nalone; both installers still pin the Bun installer they download to the\nmanifest's `verified` version.\n\n## Commands\n\n```text\ndocks-kit toolchain check # doctor table\ndocks-kit toolchain ensure bun # ensure the only managed tool\ndocks-kit toolchain ensure bun --dry-run # preview the Bun install\ndocks-kit toolchain outdated [--refresh] # verified pins vs newest upstream release\n```\n\n`docks-kit toolchain outdated` reads each tool's optional `upstream` entry in\n`SoT/toolchain.json`. An `npm` entry reads the registry `latest` tag. A\n`github` entry reads the latest release tag and strips `tagPrefix`.\nSet `GITHUB_TOKEN` or `GH_TOKEN` to raise the GitHub rate limit. Successful\nlookups cache for 24 hours in `~/.docks-kit/kit.db`; `--refresh` bypasses the\ncache. The report never installs anything and never edits a pin. A failed\nlookup prints `lookup failed: <reason>` and the command still exits 0.\n";var sync_layers_default="# Sync layers\n\n`docks-kit sync` deploys the omp SoT. It takes no positional target. Sync\nwrites no `.agents` or `.claude` folder of its own; omp's folders follow\n`PI_CONFIG_DIR`, `PI_CODING_AGENT_DIR`, and `XDG_DATA_HOME`, so an override\nthat points into one of those folders makes omp's files go there. omp uses\n`XDG_DATA_HOME` only on Linux and macOS, only while `PI_CODING_AGENT_DIR`\ndoes not move the agent folder, and only after the omp folder under it\nexists. Sync also writes the kit plugin to `~/.docks-kit/omp-plugin`.\n\n## omp (\u2192 resolved agent dir, intercom root)\n\nAGENTS.md, mcp.json, and intercom config.json are whole-file deploys.\nconfig.yml and models.yml are deep-merged (SoT keys win, mapping nodes merge,\ndeployed-only keys survive; config.yml also drops stale slash-bearing\n`retry.fallbackChains` wildcards). A SoT list replaces the deployed list, except\nconfig.yml `bash.patterns`: the merge keeps user rules and groups all rules as\nkit deny, user deny, user prompt, kit prompt (the kit ships none since 0.22.8),\nother user rules, and kit allow, so no allow loosens a deny or a prompt (see\n`docks-kit docs command-guards`). After each merge, every sync (no flag\nneeded) force-prunes the `ompRemovals.ts` retired-key inventory:\nthe retired kit `bash.patterns` rules in `OMP_RETIRED_BASH_RULES` (exact\n`match` and `approval` pairs, including the 492 former kit prompt rules\nretired in 0.22.8), config.yml keys whose deployed value still equals the value the kit used to\nship, `providers.webSearchOrder` at any value, and the retired\n`providers.anthropic.modelOverrides.claude-opus-5-5` block in models.yml while\nit still matches the shipped block.\nDirectories are mode 0700 and files mode 0600. Then the plugin pass reads the\ninventory from `omp plugin list --json`, tries to retire the former marketplace\nplugins (user-scope installs only; see below), installs `pi-intercom` at its\n`SoT/toolchain.json` pin, and links the kit plugin `docks-kit-omp`.\n\nThe kit plugin now ships the docks and plan-lifecycle skills, the\n`code-reviewer` and `plan-reviewer` agents, and the `verify-gate` and\n`context-tree-nudge` extensions. So sync installs no plugin from the `docks`\nmarketplace. Each real sync tries to retire the former marketplace plugins.\nWhen the inventory cannot be read, it warns and skips this step; a later sync\ntries again. Otherwise:\n\n- For each of `docks@docks` and `plan-lifecycle@docks` with a `scope: \"user\"`\n inventory row, it runs `omp plugin uninstall --scope user <id>`.\n- For each `scope: \"project\"` row of these ids, it changes nothing in that\n project and warns\n `omp plugin <id> is installed at project scope and docks-kit no longer ships it; run from that project: omp plugin uninstall --scope project <id>`.\n- When no user uninstall failed, it runs `omp plugin marketplace remove docks`\n if the active registry (`<data root>/marketplaces.json`) lists `docks`, or\n if no active registry exists and the legacy config-root registry lists it.\n omp copies the legacy registry forward only when no active registry exists,\n so a legacy entry beside an active registry is stale and starts no command.\n- A failed uninstall or removal goes to the failure ledger with the manual\n command, for example\n `omp plugin operation failed for docks@docks: <detail>; run manually: omp plugin uninstall --scope user docks@docks`.\n- When the inventory cannot be read, the sync warns\n `omp plugin inventory unavailable \u2014 retirement of the docks marketplace plugins skipped until the next sync; pi-intercom and the kit plugin take the full refresh path`.\n- The sync removes the folder `~/.cache/docks-kit/omp-plugin-upgrades/` of the\n retired plugin upgrade log when it exists.\n\n`--skip-plugin-refresh` does not skip the retirement or the kit plugin link. It\nonly keeps a present `pi-intercom` at its installed version. A repeat run after\na successful retirement runs no uninstall and no removal.\n\nAfter a plugin operation, the sync prints one line that names each operation,\nfor example\n`omp plugins synced: docks@docks uninstalled, plan-lifecycle@docks uninstalled, docks marketplace removed, pi-intercom 0.14.0 (new), docks-kit-omp linked`.\nEach uninstall sets the restart next step\n`Restart omp to load any refreshed plugins, skills, or tools.`, because the\nretired plugins ship extensions, and omp loads extensions only at startup. An\nnpm install, a link, and a changed kit plugin file or omp config file also set\nit.\n\nA dry run invokes no omp subcommand. It prints\n`[dry-run] omp plugin uninstall --scope user docks@docks` and the same line\nfor `plan-lifecycle@docks`, and\n`[dry-run] omp plugin marketplace remove docks` when a registry lists `docks`.\n\nPaths mirror upstream `dirs.ts` `DirResolver`, resolved from the environment\nplus directory probes, so a dry run still runs no omp subcommand. The agent\ndirectory is `<config root>/agent`, where the config root is\n`~/<PI_CONFIG_DIR or .omp>` plus `profiles/<name>` under an active profile\n(`OMP_PROFILE`, else legacy `PI_PROFILE`). For the default profile only,\n`PI_CODING_AGENT_DIR` replaces the agent directory outright. The agent\ndirectory never moves under XDG. Only the data root that holds\n`marketplaces.json` does: on Linux and macOS, with no agent-dir override\nactive, an existing `$XDG_DATA_HOME/omp` (or `$XDG_DATA_HOME/omp/profiles/<name>`\nfor a named profile) is adopted. Under a named profile, the intercom file goes\ninto `<agent directory>/intercom`. Otherwise it goes into\n`$PI_CODING_AGENT_DIR/intercom` when that variable is set, else\n`~/.pi/agent/intercom`.\n\n## Additive by default\n\nSync has no removal flag. A key, plugin, or file that only the user added\nstays. Three passes remove kit content on every sync: the `ompRemovals.ts`\nretired-key inventory above, the kit plugin pass, which removes stale files\nfrom the kit-owned `~/.docks-kit/omp-plugin`, and the retirement of the former\nmarketplace plugins above, which earlier kit versions installed.\n";var install_default=`# Installing docks-kit
|
|
24179
24179
|
|
|
24180
24180
|
Supported hosts are Linux x64/arm64, macOS arm64, and Windows x64.
|
|
24181
|
-
Hosts outside this matrix fail before a launcher
|
|
24181
|
+
Hosts outside this matrix fail before a launcher runs the Bun source.
|
|
24182
24182
|
|
|
24183
24183
|
## 1. Repo checkout (development / current users)
|
|
24184
24184
|
|
|
@@ -24189,10 +24189,8 @@ cd ~/projects/docks-kit
|
|
|
24189
24189
|
\`\`\`
|
|
24190
24190
|
|
|
24191
24191
|
POSIX hosts use \`./docks-kit\`. Windows uses \`.\\docks-kit.ps1\`. Each
|
|
24192
|
-
launcher
|
|
24193
|
-
|
|
24194
|
-
auto-installs Bun plus \`node_modules\` when needed. Each launcher reports and
|
|
24195
|
-
bypasses an ignored stale build.
|
|
24192
|
+
launcher runs the checkout source with Bun and auto-installs Bun plus
|
|
24193
|
+
\`node_modules\` when needed. A launcher never runs a file in \`cli/dist/\`.
|
|
24196
24194
|
|
|
24197
24195
|
### Move a checkout of DocksDocks/public
|
|
24198
24196
|
|
|
@@ -24207,9 +24205,10 @@ git remote set-url origin https://github.com/DocksDocks/docks-kit.git
|
|
|
24207
24205
|
.\\docks-kit.ps1 sync # Windows
|
|
24208
24206
|
\`\`\`
|
|
24209
24207
|
|
|
24210
|
-
The update pulls from DocksDocks/docks-kit
|
|
24211
|
-
with their new report target
|
|
24212
|
-
|
|
24208
|
+
The update pulls from DocksDocks/docks-kit and chains a sync that deploys the
|
|
24209
|
+
skills with their new report target. The explicit sync covers an older
|
|
24210
|
+
checkout whose launcher still runs a binary from \`cli/dist/\`, because that
|
|
24211
|
+
binary does not chain the sync. A global npm install needs nothing.
|
|
24213
24212
|
|
|
24214
24213
|
## 2. Global via Bun
|
|
24215
24214
|
|
|
@@ -24228,11 +24227,12 @@ release asset (\`docks-kit.js.map\`), matched by the bundle's \`//# debugId=\` l
|
|
|
24228
24227
|
Kit-home resolution remains available for checkout/package update behavior and
|
|
24229
24228
|
display paths, but sync reads do not depend on it.
|
|
24230
24229
|
|
|
24231
|
-
### Bun 1.4.
|
|
24230
|
+
### Bun 1.4.5 install output
|
|
24232
24231
|
|
|
24233
|
-
|
|
24234
|
-
holds nine packages, and no package in it has an install script
|
|
24235
|
-
untrusted\`
|
|
24232
|
+
An install of the package completes with no blocked postinstall. The graph
|
|
24233
|
+
holds nine packages, and no package in it has an install script: \`bun pm
|
|
24234
|
+
untrusted\` in the consumer folder (\`bun pm -g untrusted\` after a global
|
|
24235
|
+
install) reports zero untrusted dependencies with scripts. Neither
|
|
24236
24236
|
\`@parcel/watcher\` nor \`esbuild\` is in the consumer graph.
|
|
24237
24237
|
|
|
24238
24238
|
The install prints no peer dependency warning. The root pins \`effect\`,
|
|
@@ -24251,7 +24251,7 @@ tmp="$(mktemp)" && curl -fsSL https://raw.githubusercontent.com/DocksDocks/docks
|
|
|
24251
24251
|
|
|
24252
24252
|
Download-then-run, never \`curl | bash\` \u2014 stream truncation has bitten this
|
|
24253
24253
|
kit before. The installer bootstraps Bun when absent, runs
|
|
24254
|
-
\`bun add -g docks-kit@latest\`, and links the
|
|
24254
|
+
\`bun add -g docks-kit@latest\`, and links the CLI and Bun into \`~/.local/bin\`.
|
|
24255
24255
|
This installer serves the two POSIX platforms. Windows uses the PowerShell
|
|
24256
24256
|
installer below.
|
|
24257
24257
|
|
|
@@ -24288,14 +24288,11 @@ docks-kit update --no-sync # update only
|
|
|
24288
24288
|
directory whose \`package.json\` has the name \`docks-kit\`. An invalid value
|
|
24289
24289
|
causes an error instead of a fallback.
|
|
24290
24290
|
2. The CLI uses the nearest kit root at or above its own module directory.
|
|
24291
|
-
3. Next, the CLI uses the nearest kit root at or above the
|
|
24292
|
-
the executable. A standalone binary inside \`<checkout>/cli/dist\` therefore
|
|
24293
|
-
resolves to the checkout.
|
|
24294
|
-
4. Next, the CLI uses the nearest kit root at or above the current working
|
|
24291
|
+
3. Next, the CLI uses the nearest kit root at or above the current working
|
|
24295
24292
|
directory, but only as a fallback.
|
|
24296
|
-
|
|
24293
|
+
4. Otherwise, the CLI uses the directory that holds the executable.
|
|
24297
24294
|
|
|
24298
|
-
|
|
24295
|
+
Source 2 identifies the installation that is running. A globally installed
|
|
24299
24296
|
\`docks-kit\` updates the global package even when you run it from inside a
|
|
24300
24297
|
docks-kit checkout. \`DOCKS_KIT_HOME\` lets you target a specific checkout on
|
|
24301
24298
|
purpose.
|
|
@@ -24309,8 +24306,6 @@ plain flag-less \`docks-kit sync\`. It also refreshes plugins, even when the kit
|
|
|
24309
24306
|
is already current: it moves \`pi-intercom\` to its pinned version. Pass
|
|
24310
24307
|
\`--no-sync\`, then run \`docks-kit sync --skip-plugin-refresh\` to keep a present
|
|
24311
24308
|
\`pi-intercom\` at its installed version.
|
|
24312
|
-
A compiled binary inside a checkout updates the checkout; on the next invocation
|
|
24313
|
-
the launcher bypasses that now-stale binary and uses updated source until rebuilt.
|
|
24314
24309
|
Every \`docks-kit sync\` except \`--dry-run\` also does a best-effort behind-upstream
|
|
24315
24310
|
check and nudges when the checkout is stale (silent offline / detached / no git).
|
|
24316
24311
|
|
|
@@ -24348,25 +24343,43 @@ npm install -g docks-kit@latest
|
|
|
24348
24343
|
|
|
24349
24344
|
Verified on Bun 1.4.2 and npm 11, each in a clean HOME.
|
|
24350
24345
|
|
|
24351
|
-
## No-Bun recovery
|
|
24352
|
-
|
|
24353
|
-
No Bun or constrained sandbox: download the platform release binary from GitHub
|
|
24354
|
-
Releases and run it directly. No checkout or \`DOCKS_KIT_HOME\` is required for
|
|
24355
|
-
sync/config reads.
|
|
24356
|
-
|
|
24357
24346
|
## Prerequisites
|
|
24358
24347
|
|
|
24359
|
-
- Bun for
|
|
24348
|
+
- Bun for every install: the checkout launchers and the npm package both run on Bun
|
|
24360
24349
|
- npm for an npm-installed kit
|
|
24361
24350
|
- jq is optional doctor/test tooling; sync has no jq runtime dependency
|
|
24362
24351
|
- curl is needed only to download Bun's upstream installer when Bun is absent:
|
|
24363
24352
|
by the POSIX \`docks-kit\` launcher, by the POSIX \`install.sh\`, and by sync's
|
|
24364
|
-
Bun bootstrap on every host
|
|
24353
|
+
Bun bootstrap on every host
|
|
24365
24354
|
(\`docks-kit toolchain ensure bun\` too). \`docks-kit.ps1\` and \`install.ps1\`
|
|
24366
24355
|
download Bun's installer with Invoke-WebRequest. An already-present Bun needs
|
|
24367
24356
|
no curl.
|
|
24368
24357
|
- See \`docks-kit toolchain check\` for the full picture on this machine
|
|
24369
|
-
`;var platforms_default="# Platform support\n\nThe supported host matrix is exact: Linux on x64 and arm64, macOS on arm64,\nand Windows on x64.\n\n| Platform | Architecture | docks-kit binary | Sync engine |\n|----------|--------------|------------------|-------------|\n| Linux | x64 | `docks-kit-linux-x64` | EngineNative (TS) |\n| Linux | arm64 | `docks-kit-linux-arm64` | EngineNative (TS) |\n| macOS | arm64 | `docks-kit-darwin-arm64` | EngineNative (TS) |\n| Windows | x64 | `docks-kit-windows-x64.exe` | EngineNative (TS) |\n\nPOSIX hosts use the `docks-kit` launcher. Windows uses `docks-kit.ps1`.\nHosts outside this table fail before either launcher can fall back to Bun\nsource. The POSIX launcher and `install.sh` read the architecture of the\nshell with `uname -m`. On an Apple silicon Mac, a shell that runs under\nRosetta reports `x86_64` and gets the unsupported-host message, so run\ndocks-kit from a native arm64 shell.\n\nEngineNative is the only supported engine on supported hosts.\nWhen `DOCKS_KIT_ENGINE=bash` is set, the commands that run the engine (`sync`\nand `toolchain`) exit 2 with the removed-engine message. The\nmessage points at the `bash-engine-final` tag for historical recovery. Other\ncommands ignore the variable.\n";var omp_models_default="# omp models\n\nWhy `SoT/.omp/config.yml` points each omp role at a specific model and thinking\nlevel, and the Artificial Analysis (AA) measurements the choices were weighed\nagainst.\n\n## Role map\n\n| Role | Model | Level | Index | Cost/task | TTFT |\n|---|---|---|---:|---:|---:|\n| `default` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `slow` | `anthropic/claude-opus-5-5` | xhigh | 56 | $3.46 | 136.30 s |\n| `plan` | `anthropic/claude-opus-5-5` | xhigh | 56 | $3.46 | 136.30 s |\n| `task` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `designer` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `vision` | `anthropic/claude-opus-5-5` | medium | 51 | $1.34 | 21.87 s |\n| `smol` / `commit` | `openai-codex/gpt-6-luna` | medium | 29 | $0.02 | n/a |\n| `tiny` | `openai-codex/gpt-6-luna` | low | 21 | $0.0045 | 2.18 s |\n| `fable` | `anthropic/claude-fable-5-2` | medium | 56 (v5.0.1) | $3.80 (v5.0.1) | 11.23 s (v5.0.1) |\n| `switch_fable` | `anthropic/claude-fable-5-2` | medium | 56 (v5.0.1) | $3.80 (v5.0.1) | 11.23 s (v5.0.1) |\n| `astra` | `openai-codex/gpt-6.2-astra` | xhigh | 62 (v5.0.1) | $2.52 (v5.0.1) | 52.89 s (v5.0.1) |\n| `reviewer` | `openai-codex/gpt-6.1-terra` | high | 42 (v5.0.1) | $0.26 (v5.0.1) | 10.91 s (v5.0.1) |\n| `web` | `web/firecrawl` | n/a | n/a | n/a | n/a |\n\nThe table reports the measured Artificial Analysis figures for each assigned\nmodel and level. It states no motive that the config or omp's own\ndocumentation does not establish. AA has not measured output speed or latency\nfor GPT-6 Luna medium, so that row carries `n/a` for TTFT. AA measures no web\nsearch provider, so the `web` row carries no figures. The `astra`, `reviewer`,\n`fable`, and `switch_fable` rows come from later captures at Intelligence\nIndex v5.0.1: GPT-6.1 Terra from 2026-11-05, Fable 5.2 from 2026-11-12, and\nGPT-6.2 Astra from 2026-11-18. The 2026-09-29 capture predates these models.\nCompare those rows only with other v5.0.1 figures (see GPT-6.2 Astra, GPT-6.1\nTerra, and Claude Fable 5.2 below). A review benchmark chose the model of the\n`reviewer` role (DocksDocks/public#130), not these figures. The tier of that\nrole follows the main session (DocksDocks/public#134).\n\nThe role map carries no Coding Agent Index column. That index measures specific\nagent harnesses and model levels, not omp roles. The snapshot section below\nlists the relevant entries, including Codex with GPT-6.2 Sol and GPT-6.2 Astra\nat high and xhigh.\n\n### AA rows for each role model\n\nFor each model that an omp role or retry chain uses, this topic records AA\nrows at `high` and `xhigh` at least. Each set of rows names its Intelligence\nIndex version and its capture date. A role or chain change adds the missing\nrows in the same commit. On 2026-11-18, the role map and the retry chains use\nsix models, and each has both rows:\n\n| Model | Index version | Capture date |\n|---|---|---|\n| Claude Opus 5.5 | v4.3.2 | 2026-09-29 |\n| GPT-6 Luna | v4.3.2 | 2026-09-29 |\n| Claude Fable 5.2 | v5.0.1 | 2026-11-12 |\n| GPT-6.1 Terra | v5.0.1 | 2026-11-05, speed re-measured 2026-11-18 |\n| GPT-6.2 Sol | v5.0.1 | 2026-11-18 |\n| GPT-6.2 Astra | v5.0.1 | 2026-11-18 |\n\n### OpenAI model availability in omp\n\nThe `openai-codex` selectors for GPT-6 Sol and GPT-6 Luna were deployed on\n2026-09-22, while the rollout of both models was still in progress. The owner\nchose to deploy them before the rollout completed. Checks on that date, with\nomp 18.2.9 and codex-cli 0.153.3:\n\n- At 19:02 UTC, `codex exec -m gpt-6-sol` returned HTTP 400, `The 'gpt-6-sol'\n model is not supported when using Codex with a ChatGPT account.`\n `gpt-6-luna` returned the same error. The Codex model cache fetched at that\n time listed neither model.\n- At 19:14 UTC, the Codex model cache for the same account listed\n `gpt-6-sol` and `gpt-6-luna`. A request on the new default could not be\n tested, because the account had reached its Codex usage limit.\n- The omp `openai-codex` catalog listed `gpt-6-astra` and the three `gpt-5.6`\n models, but not `gpt-6-sol` or `gpt-6-luna`, both before and after\n `omp models refresh` at 19:14 UTC. omp resolves a selector that is not in\n the catalog by provider-scoped fuzzy match. An `omp -p --mode json` run on\n `openai-codex/gpt-6-sol:low` recorded `gpt-5.6-sol` as the serving model,\n and the Luna selector recorded `gpt-5.6-luna`. omp printed no warning.\n\nOn 2026-09-25, omp 18.3.1 listed `gpt-6-sol` and `gpt-6-luna` in\n`omp models openai-codex`. An `omp -p --mode json` run on each selector\nrecorded `gpt-6-sol` and `gpt-6-luna` as the serving model, so the selected\nomp roles ran GPT-6 on that date.\n\nOn 2026-09-29, omp 18.4.4 listed `gpt-6.1-sol` at low, medium, high, xhigh,\nand max, with a 272K context window and 128K maximum output. An\n`omp -p --mode json --model openai-codex/gpt-6.1-sol:low` run recorded\n`gpt-6.1-sol` as the serving model. To recheck, run\n`omp models openai-codex`; the `gpt-6.1-sol` row must appear. Codex-cli\n0.159.0 could not complete `codex exec -m gpt-6.1-sol`: the login had ended,\nand the request returned HTTP 401 `refresh_token_invalidated`. The Codex\nmodel cache was last fetched on 2026-09-22 and does not list `gpt-6.1-sol`,\nso that Codex run did not establish model availability.\n\nOn 2026-11-18, omp 18.22.2 listed `gpt-6.2-sol` with a 500K context window\nand `gpt-6.2-astra` with a 272K context window. Both had low, medium, high,\nxhigh, and max. An `omp -p --mode json` run on each selector at `:low`\nrecorded that same id as the serving model. omp 18.22.2 listed no GPT-6.2\nTerra and no GPT-6.2 Luna. To recheck, run `omp models openai-codex`; the\n`gpt-6.2-sol` and `gpt-6.2-astra` rows must appear. Sync deploys the selectors\nwithout a catalog check. On an omp release without these ids, omp can resolve\nthem by fuzzy match to another model without a warning, as on 2026-09-22.\n\nOn 2026-11-19, omp 19.0.0 became the toolchain floor and verified pin. Its\n`omp models --json` catalog listed each of the 12 model selectors of\n`modelRoles` and `retry.fallbackChains` (the `web/` entries left out) as an\nexact `provider/id` row, so no role depends on a fuzzy match. This check read\nthe catalog only; it ran no model request. The rows also carry the fields that\nthe free launcher reads (`ompOverlay.ts parseFreeModels`): a string\n`selector`, a `cost` object with numeric `input` and `output`, a numeric\n`contextWindow`, and a `thinking` ladder array or `null`.\n\nWhat omp's settings catalog establishes about these roles:\n\n- `cycleOrder` lists the roles the model switcher cycles. `fable` is the\n fourth `Ctrl+P` stop, and `astra` is the fifth and last stop.\n- `tiny` overrides the model for lightweight background tasks: titles, memory,\n auto-thinking, and unexpected-stop detection.\n- `modelTags` carries role metadata and can introduce roles; `hidden: true`\n keeps `switch_fable` and `reviewer` out of the switcher list.\n\n`modelRoles.reviewer` is a kit-defined role, not an omp built-in. It runs\n`openai-codex/gpt-6.1-terra:high`. omp resolves `@<name>` for any key in\n`modelRoles` (`getModelRoleAlias` in omp's `model-resolver.ts`, omp 18.8.5).\n`task.agentModelOverrides` maps `reviewer`, `security-reviewer`,\n`code-reviewer`, and `plan-reviewer` to `@reviewer`, so one key sets the\nmodel for every reviewer. `task.agentServiceTierOverrides` sets the same four\nagents to `inherit`, so they take the live tier of the main session for each\nprovider. \"OpenAI fast mode\" below describes how that tier changes. The bundled\n`reviewer` and `security-reviewer` agents ship with omp, and the kit plugin\n`docks-kit-omp` ships `code-reviewer` and `plan-reviewer`.\n`retry.fallbackChains.reviewer` holds `anthropic/claude-opus-5-5:high`, and\n`retry.fallbackChains.task` holds `openai-codex/gpt-6.2-sol:high`; both are\ncross-vendor fallbacks.\n\nThe review benchmark of DocksDocks/public#130 ran on 2026-11-05. It used 24\nheld-out cases of the `review-benchmark` skill, 2 runs each. The cases came\nfrom DocksDocks/docks, the source repository of that skill at the time.\nIt compared `gpt-6.1-sol` and `gpt-6.1-terra` at `high`, each on the `default`\nand `priority` tiers. The user set the effort `high`; the benchmark chose the\nmodel. `gpt-6.1-terra` on `default` let the fewest known defects escape (34.90\nper 50 known). No other setting stayed within the pre-registered bounds. A\nTerra review took a median of 69.3 s, against 172.8 s for `gpt-6.1-sol` on\n`default`. It used about a third of the tokens. It returned more wrong\nfindings: 0.49 per run against 0.20. The issue holds the full tables and the\ndecision rule.\n\nThe benchmark rule first pinned the `default` tier. The user then chose to\nlet the reviewers follow the fast toggle (DocksDocks/public#134). On the\n`priority` tier, Terra `high` let 35.15 known defects per 50 escape, against\n34.90 on `default`, and a review took a median of 35.7 s. Its 90% intervals\nmissed two pre-registered bounds: escaped difference up to 3.26 (bound 2) and\nrecall difference down to -0.07 (bound -0.05). Both intervals include 0, and\nthe user judged the difference as noise.\n\n`retry.fallbackChains.astra` holds `anthropic/claude-fable-5-2:medium`.\n`retry.fallbackChains.fable` holds `openai-codex/gpt-6.2-astra:xhigh`.\nEach deliberate cycle stop falls to the other vendor. Without these explicit\nchains, `retry.fallbackChains.default` would send either stop to\n`openai-codex/gpt-6.2-sol:high`.\nChain entries are concrete selectors, not role aliases, so this pair cannot\nrecurse. The hidden `switch_fable` chain stays empty.\n\n### Advisor removed\n\nBy owner decision (2026-11-12, 0.22.22), the kit sets no omp advisor.\n`SoT/.omp/config.yml` has no `advisor` block, no `modelRoles.advisor`, and no\n`retry.fallbackChains.advisor`. omp keeps the advisor off by default. The\nplan-lifecycle verification loop takes its place: acceptance checks, a fresh\ncode review of the diff, and a round limit. Since 2026-11-01, 33 main\nsessions had an advisor log, and no subagent session had one. A session that\nruns `/advisor on` takes its advisor model from the `slow` role, because no\n`advisor` role is set.\n\nHistory: on 2026-09-24, with omp 18.3.0, an advisor on\n`openai-codex/gpt-6-sol:medium` looped and made 1,313 requests for 140\nmain-agent requests. The kit then ran the advisor on Opus 5.5 `medium` and\nexcluded every GPT model from that role until this removal.\n\n`modelRoles.web` is `web/firecrawl`, and `retry.fallbackChains.web` lists the\nexplicit 20-entry provider order that follows it. The two keys replace the\nretired `providers.webSearchOrder` key, which omp no longer carries in its\nsettings schema. omp still accepts that key in a deployed file, expands it in\nmemory into the same two keys, and then drops it, but it never writes the\nexpansion back to disk. The kit therefore declares both keys itself.\n\nThe chain starts from the expansion omp produces, read back with\n`omp config get retry.fallbackChains`. An explicit chain replaces omp's\nbuilt-in web order wholesale, so a shortened list drops providers instead of\nreordering them. The kit makes two deliberate edits to omp's order:\n\n- The Codex Luna entry follows the kit's Luna generation and names\n `openai-codex/gpt-6-luna`.\n- The owner removed every entry that named an older model:\n `google/gemini-2.5-flash`, `google-antigravity/gemini-2.5-flash`,\n `anthropic/claude-haiku-4-5`, `openai-codex/gpt-5.6`,\n `openai-codex/gpt-5.5`, `xai/grok-4.5`, and `xai-oauth/grok-4.5`. omp never\n tries those search backends now.\n\nThe order keeps Firecrawl, Exa, Perplexity, and Codex first. The remaining\n`web/*` entries are omp's own ordering of the providers behind them.\n\n## Artificial Analysis snapshot\n\nSource: `https://artificialanalysis.ai`, read on 2026-09-29 at Intelligence\nIndex v4.3.2 and Coding Agent Index v1.5. Each per-level row comes from the\nmetric table of `/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`.\nEach page title names the requested model and level and prints the same\nIntelligence Index version. AA serves `max` under the bare model slug.\nThe GPT-5.6 Sol high self-comparison URL does not load, so that baseline row\ncomes from the GPT-5.6 Sol high column of the GPT-6.1 Sol high comparison.\nIndex composition changes between versions; figures from an earlier capture\ncannot be mixed with these.\n\nAt v1.5 on 2026-09-29, the Coding Agent Index page (`/agents/coding-agents`)\nlisted 30 harness, model, and level entries. It covered GPT-6.1 Sol with Codex\nat low, medium, high, xhigh, and max; Opus 5.5 and Fable 5.1 with Claude Code\nat max; and Astra and Luna with Codex at max. It also covered Grok Build with\nGrok 4.7 at xhigh, Antigravity SDK with Gemini 3.8 Flash at high, and Opencode\nwith GLM-5.3 and Kimi Code CLI with Kimi K3 without levels. The relevant\npublished v1.5 scores are:\n\n| Harness and model | Coding Agent Index |\n|---|---:|\n| Claude Code - Opus 5.5 (max) | 66 |\n| Claude Code - Fable 5.1 (max, with fallback) | 62 |\n| Codex - GPT-6 Astra (max) | 62 |\n| Codex - GPT-6.1 Sol (xhigh) | 63 |\n| Codex - GPT-6.1 Sol (medium) | 61 |\n| Codex - GPT-6.1 Sol (high) | 60 |\n| Codex - GPT-6.1 Sol (max) | 60 |\n| Codex - GPT-6.1 Sol (low) | 57 |\n| Claude Code - Opus 5 (max) | 60 |\n| Codex - GPT-6 Luna (max) | 41 |\n\nThese are coding-agent scores for specific harnesses and levels, not scores\nfor the omp role map. The v1.5 table stays as history. Coding Agent Index v2.1\nbelow has the 2026-11-18 entries for GPT-6.2 Sol and GPT-6.2 Astra.\n\nColumn meanings:\n\n- **Index** - AA Intelligence Index, a weighted aggregate across its\n evaluation set. Comparable only inside one index version.\n- **Cost/task** - weighted average USD to run one index task, including\n input, cache, reasoning, and answer tokens.\n- **Tokens/task** - answer plus reasoning tokens for one index task.\n- **Index tokens** - total output tokens the model spends to complete the\n whole index run. This is the token-efficiency signal.\n- **Speed** - output tokens per second.\n- **TTFT** - seconds to the first answer token, so reasoning time counts.\n- **TB 4.0** - Terminal-Bench 4.0, one of the index evaluations (ten at v4.3.2,\n nine at v5.0.1).\n\n### Coding Agent Index v2.1\n\nSource: `https://artificialanalysis.ai/agents/coding-agents`, read on\n2026-11-18 at Coding Agent Index v2.1. This version gives equal weight to\nFrontierCode-AA 2.0, Terminal-Bench 4.1, and SWE-Atlas-QnA-AA, and lists 39\nentries. The page draws the scores only in charts. The values below are the\n`indexScore` fields of the page data, on a 0 to 1 scale. The cost and agent\nwall time columns are the mean per task from the same data. This capture did\nnot observe the rendered integer values. Do not compare these values with the\nv1.5 integers above.\n\n| Harness and model | indexScore | Cost/task | Agent wall time s |\n|---|---:|---:|---:|\n| Codex - GPT-6.2 Astra (max) | 0.5347 | $5.117 | 1506.7 |\n| Codex - GPT-6.2 Astra (xhigh) | 0.5312 | $3.198 | 992.4 |\n| Codex - GPT-6.2 Astra (high) | 0.5228 | $2.372 | 947.4 |\n| Codex - GPT-6.2 Sol (max) | 0.4862 | $1.216 | 1051.4 |\n| Codex - GPT-6.2 Sol (xhigh) | 0.4979 | $0.898 | 755.8 |\n| Codex - GPT-6.2 Sol (high) | 0.4746 | $0.764 | 635.4 |\n\nGPT-6.2 Sol scores higher at `xhigh` than at `max`. v2.1 lists GPT-6.1 Sol\nand GPT-6.1 Terra with Codex only at max.\n\n### Claude Opus 5.5 (Anthropic) - `anthropic/claude-opus-5-5`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 58 | $5.98 | 119k | 260M | 93 | 692.63 | 60% |\n| xhigh | 56 | $3.46 | 66k | 100M | 80 | 136.30 | 60% |\n| high | 54 | $1.82 | 36k | 53M | 74 | 52.85 | 57% |\n| medium | 51 | $1.34 | 26k | 38M | 74 | 21.87 | 53% |\n| low | 42 | $0.55 | 10k | 20M | 74 | 12.49 | 31% |\n\nPrice: $4.00 in, $20.00 out, $0.20 cache hit per 1M. The Anthropic platform\ndocumentation lists the same input, output, and cache-read prices. It adds a\n$5.00 five-minute cache write and an $8.00 one-hour cache write, which the AA\ncomparison table does not show. Context is 1M, with 128K maximum output.\nAdaptive thinking is always on, and the Claude API default effort is\n`medium`. All AA levels run with fallback. Max has the highest Intelligence\nIndex in this topic at this capture. AA now measures speed and latency for\nevery Opus 5.5 level; medium has a shorter TTFT than high.\n\nUntil 0.20.1, `SoT/.omp/models.yml` carried the Anthropic limits and prices as\nan `anthropic` `modelOverrides` block, because the shared catalog served this\nid as a stub with null limits and zero cost. On 2026-09-25 the catalog at\n`catalog.stencil.so` published the same context window, output cap, ladder,\nand prices, so the block was removed. Sync prunes the deployed copy only while\nit still equals the shipped block.\n\nThe removal fixes how the Opus role levels reach the API. The block set\n`thinking.mode: effort`. For that mode, omp 18.3.1 (`packages/ai/src/stream.ts`,\ntag `v18.3.1`) sends `thinking: {type: \"enabled\", budget_tokens}` and no\n`output_config.effort`. The level only picked the budget from\n`ANTHROPIC_THINKING`: `medium` 8,192, `high` 16,384, and `xhigh` and `max`\nboth 32,768 tokens. So before 0.20.1 the levels in the role table above were\nnot the effort levels that Artificial Analysis measured, and `xhigh` equaled\n`max`. The catalog row sets `thinking.mode: anthropic-adaptive`, so omp now\nsends `thinking: {type: \"adaptive\"}` with `output_config.effort` set to the\nrole level. The block also set `defaultLevel: high` for a bare\n`claude-opus-5-5` selector. `SoT/.omp/config.yml` names a level on every Opus\nselector, so no kit role depends on that default. Runs on\n`anthropic/claude-opus-5-5:high` and `:max` after the prune answered with\nexit 0.\n\n### Claude Fable 5.2 (Anthropic) - `anthropic/claude-fable-5-2`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-12 at Intelligence\nIndex v5.0.1, from the metric table of\n`/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`. AA serves `max` under\nthe bare model slug. These figures use another index version than the rest of\nthis snapshot, so they do not compare with the v4.3.2 rows above. Compare them\nwith GPT-6.1 Terra below.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 65 | $26.54 | 274k | 275M | 98 | 262.29 | 60% |\n| xhigh | 62 | $14.83 | 162k | 144M | 102 | 85.87 | 62% |\n| high | 62 | $9.08 | 98k | 85M | 97 | 27.98 | 60% |\n| medium | 56 | $3.80 | 43k | 41M | 93 | 11.23 | 55% |\n| low | 54 | $3.10 | 36k | 35M | 97 | 8.42 | 55% |\n\nPrice: $8.00 in, $40.00 out, $0.20 cache hit per 1M. The omp catalog lists\nthe same prices, a $10.00 cache write, a 1M context, and 128K maximum output.\nAll AA levels run with default fallback. On 2026-11-12, omp 18.19.0 listed\n`claude-fable-5-2` at low, medium, high, xhigh, and max, and an\n`omp -p --mode json --model anthropic/claude-fable-5-2:medium` run recorded\n`claude-fable-5-2` as the serving model.\n\n`fable` and `switch_fable` moved from Fable 5.1 to Fable 5.2 at the same\nlevel, `medium`. The Fable 5.1 table below stays as the previous-generation\nbaseline at v4.3.2.\n\n### Claude Fable 5.1 (Anthropic) - `anthropic/claude-fable-5-1`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 53 | $7.63 | 78k | 188M | 69 | 285.98 | 52% |\n| xhigh | 53 | $5.98 | 61k | 121M | 57 | 104.51 | 55% |\n| high | 51 | $3.91 | 38k | 62M | 52 | 26.01 | 52% |\n| medium | 49 | $2.98 | 28k | 44M | 50 | 8.00 | 45% |\n| low | 47 | $2.37 | 22k | 33M | 48 | 4.83 | 40% |\n\nPrice: $10.00 in, $50.00 out, $0.25 cache hit per 1M. Context 1M. All levels\nrun with fallback.\n\n### GPT-6.2 Sol (OpenAI) - `openai-codex/gpt-6.2-sol`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-18 at Intelligence\nIndex v5.0.1. The rows come from the rendered metric table of\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra`, which shows every level of\nboth models. Tokens per task and index tokens come from the data of the model\npage `/models/gpt-6-2-sol`, because the comparison table does not show them.\nThe other values in that data match the rendered table. These rows compare\nonly with other v5.0.1 figures, not with the v4.3.2 rows.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 57 | $1.01 | 40k | 61M | 85 | 66.70 | 60% |\n| xhigh | 56 | $0.65 | 24k | 33M | 81 | 26.63 | 56% |\n| high | 55 | $0.56 | 20k | 23M | 78 | 9.63 | 59% |\n\nAA and OpenAI list $2.00 input, $0.10 cached input, $2.50 cache write, and\n$10.00 output per 1M tokens. OpenAI also lists a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.2-sol>). Prompts above\n272K input tokens cost 2x input and cache rates and 1.5x output rates for the\nfull request. The knowledge cutoff is 2026-06-01. OpenAI released the model on\n2026-11-17 (<https://developers.openai.com/api/docs/changelog>). Codex uses a\n500,000-token default context (<https://developers.openai.com/codex/models>).\nOn 2026-11-18, omp 18.22.2 listed `gpt-6.2-sol` with the same 500K context\nwindow, 128K maximum output, and the levels low, medium, high, xhigh, and max.\n\n`retry.fallbackChains.default` and `.task` moved from GPT-6.1 Sol `high` to\nGPT-6.2 Sol `high`, and `.vision` moved at `medium` (DocksDocks/public#175).\nOn 2026-11-18, the v5.0.1 data of the model page `/models/gpt-6-1-sol` listed\nGPT-6.1 Sol high at index 50 and $0.59 per task. GPT-6.2 Sol high has 55 and\n$0.56.\n\n### GPT-6.2 Astra (OpenAI) - `openai-codex/gpt-6.2-astra`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-18 at Intelligence\nIndex v5.0.1. The rows come from the rendered metric table of\n`/models/comparisons/gpt-6-2-astra-vs-gpt-6-2-sol`. Tokens per task and index\ntokens come from the data of the model page `/models/gpt-6-2-astra`. These\nrows compare only with other v5.0.1 figures, not with the v4.3.2 rows.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 62 | $4.00 | 41k | 66M | 53 | 170.99 | 64% |\n| xhigh | 62 | $2.52 | 22k | 27M | 54 | 52.89 | 64% |\n| high | 60 | $2.07 | 18k | 20M | 56 | 22.07 | 60% |\n\nThe `max` and `xhigh` rows both round to 62. The page data gives 62.14 and\n61.56.\n\nAA and OpenAI list $8.00 input, $0.40 cached input, $10.00 cache write, and\n$40.00 output per 1M tokens. OpenAI also lists a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.2-astra>). The\nlong-prompt rule of GPT-6.2 Sol also applies. The knowledge cutoff is\n2026-05-18. OpenAI released the model on 2026-11-17, in the same changelog\nentry as GPT-6.2 Sol. Codex uses a 272,000-token default context. On\n2026-11-18, omp 18.22.2 listed `gpt-6.2-astra` with the same 272K context\nwindow, 128K maximum output, and the levels low, medium, high, xhigh, and max.\n\n`modelRoles.astra` and `retry.fallbackChains.fable` moved from GPT-6 Astra\n`xhigh` to GPT-6.2 Astra `xhigh` (DocksDocks/public#175). GPT-6 Astra below\nhas the v5.0.1 figures for a like-for-like comparison.\n\n### GPT-6 Astra (OpenAI) - previous generation\n\nThe role map and the retry chains no longer use GPT-6 Astra. This table stays\nas the v4.3.2 baseline for the previous `astra` role.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 53 | $3.26 | 27k | 60M | 57 | 305.56 | 59% |\n| xhigh | 52 | $2.31 | 17k | 38M | 49 | 126.90 | 60% |\n| high | 51 | $1.73 | 12k | 26M | 50 | 41.09 | 54% |\n| medium | 50 | $1.54 | 10k | 19M | 47 | 4.88 | 49% |\n| low | 46 | $0.82 | 4k | 10M | 49 | 2.81 | 42% |\n\nPrice: $10.00 in, $50.00 out, $1.00 cache hit per 1M. Context 1M. Knowledge\ncutoff 2026-04-30. AA publishes no non-reasoning Astra row.\n\nOn 2026-11-18, the v5.0.1 data of the AA model page `/models/gpt-6-astra`\nlisted GPT-6 Astra `xhigh` at index 55 and $3.66 per task, with 44 t/s and an\n83.77 s TTFT. It listed `high` at index 55, $3.24, 44 t/s, and 40.21 s. At\n`xhigh`, GPT-6.2 Astra scores 62 against 55 and costs $2.52 against $3.66 per\ntask. It produces 54 against 44 t/s, with a TTFT of 52.89 s against 83.77 s.\nAA marks GPT-6 Astra deprecated, so its comparison pages return HTTP 404.\n\n### GPT-6.1 Sol (OpenAI) - previous generation\n\nThe role map and the retry chains no longer use GPT-6.1 Sol. This table stays\nas the v4.3.2 baseline for the former `task` role and retry fallbacks.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 52 | $0.72 | 38k | 67M | 67 | 267.64 | 56% |\n| xhigh | 51 | $0.39 | 18k | 36M | 64 | 68.65 | 54% |\n| high | 50 | $0.32 | 13k | 25M | 66 | 57.26 | 52% |\n| medium | 48 | $0.21 | 8k | 15M | 62 | 5.29 | 48% |\n| low | 42 | $0.13 | 4k | 9M | 74 | 1.84 | 31% |\n\nAA lists $2.00 input, $10.00 output, and $0.10 cached input per 1M tokens.\nOpenAI also lists $2.50 per 1M cache-write tokens, a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens. Prompts above\n272K input tokens cost 2x input and cache rates and 1.5x output rates for the\nfull request. The knowledge cutoff is 2026-04-30. The API effort ladder is\n`low, medium, high, xhigh, max`, with `medium` as the default. There is no\n`none`, `minimal`, or non-reasoning level. On 2026-11-18, omp 18.22.2 still\nserved `gpt-6.1-sol`, and the OpenAI deprecations page did not list it. AA\nmarks it deprecated.\n\n### GPT-6.1 Terra (OpenAI) - `openai-codex/gpt-6.1-terra`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-05 at Intelligence\nIndex v5.0.1, from the metric table of\n`/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`. AA serves `max` under\nthe bare model slug. These figures use another index version than the rest of\nthis snapshot, so they do not compare with the v4.3.2 rows above.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 51 | $0.96 | 60k | 99M | 76 | 159.59 | 56% |\n| xhigh | 45 | $0.40 | 26k | 35M | 74 | 33.02 | 46% |\n| high | 42 | $0.26 | 17k | 21M | 73 | 10.91 | 42% |\n| medium | 38 | $0.17 | 11k | 14M | 72 | 4.43 | 32% |\n| low | 29 | $0.07 | 4k | 7M | 72 | 2.34 | 15% |\n\nFor comparison at the same index version, AA lists GPT-6.1 Sol high at index\n50, $0.59 per task, 23k tokens per task, 25M index tokens, 57 t/s, a 38.27 s\nTTFT, and 52% on Terminal-Bench 4.0. The same Sol high row read 50, $0.32, and\n57.26 s at v4.3.2, which shows why the two captures do not mix.\n\nOn 2026-11-18, the release comparison page\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra` showed new speed and TTFT\nfigures for GPT-6.1 Terra at v5.0.1. `high` ran at 65 t/s with a 10.50 s\nTTFT, `xhigh` at 65 t/s with 30.33 s, and `max` at 69 t/s with 146.49 s. The\nindex, cost, and token figures were unchanged. AA measures speed and latency\ncontinuously, so the table keeps the 2026-11-05 rows. The speed comparison\nbelow uses the 2026-11-18 figures.\n\nAA and OpenAI list $1.00 input, $5.00 output, and $0.05 cached input per 1M\ntokens. OpenAI also lists a 1,050,000-token context, 922,000 maximum input\ntokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.1-terra>).\nFast mode costs 2x Standard. The knowledge cutoff is 2026-06-01. The API effort\nladder is `none, low, medium, high, xhigh, max`, with `medium` as the default.\n\n### Output speed: GPT-6.2 Sol and GPT-6.1 Terra\n\nGPT-6.2 Sol has the higher output speed at `high` and at `xhigh`.\nThe figures come from one page,\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra`, read on 2026-11-18 at\nIntelligence Index v5.0.1.\n\n| Metric | GPT-6.2 Sol | GPT-6.1 Terra |\n|---|---:|---:|\n| `high` output speed | 78 t/s | 65 t/s |\n| `xhigh` output speed | 81 t/s | 65 t/s |\n| `high` TTFT | 9.63 s | 10.50 s |\n| `xhigh` TTFT | 26.63 s | 30.33 s |\n| `high` end-to-end time | 42.65 s | 43.91 s |\n| `xhigh` end-to-end time | 85.03 s | 86.53 s |\n\nAt `high`, Sol produces about 19% more tokens per second than Terra. At\n`xhigh`, the gain is about 24%. Sol also has the lower TTFT and end-to-end\ntime at both levels.\n\nThe `reviewer` role stays on GPT-6.1 Terra `high`. The DocksDocks/public#130 benchmark chose\nTerra by escaped defects, not by speed. omp 18.22.2 lists no GPT-6.2 Terra. A\nmove of the reviewer to GPT-6.2 Sol needs a new benchmark.\n\n### GPT-6 Luna (OpenAI) - `openai-codex/gpt-6-luna`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 37 | $0.07 | 50k | 145M | 148 | 96.96 | 13% |\n| xhigh | 34 | $0.04 | 27k | 69M | 133 | 16.87 | 8% |\n| high | 32 | $0.03 | 20k | 47M | 132 | 10.97 | 5% |\n| medium | 29 | $0.02 | 11k | 29M | n/a | n/a | 3% |\n| low | 21 | $0.0045 | 2k | 8M | 124 | 2.18 | 0% |\n| non-reasoning | 18 | $0.01 | 4k | 7M | 142 | 0.80 | 2% |\n\nPrice: $0.10 in, $0.50 out, $0.01 cache hit per 1M. OpenAI's model page lists\na $0.125 cache write, the same context, output, and long-prompt billing as\nGPT-6.1 Sol, and a 2026-05-18 knowledge cutoff. Luna also offers a\nnon-reasoning level. AA has not measured speed or latency for `medium`; it\nhas measured both at the other levels.\n\n### GPT-5.6 Sol (OpenAI) - previous generation\n\nThe role map no longer uses GPT-5.6 Sol. This table stays as the measured\nbaseline for the former GPT-6.1 Sol `task` retry fallback.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 47 | $1.99 | 29k | 90M | 85 | 98.68 | 40% |\n| xhigh | 44 | $1.18 | 20k | 51M | 77 | 24.79 | 25% |\n| high | 42 | $0.81 | 13k | 34M | 75 | 9.40 | 21% |\n| medium | 39 | $0.50 | 8k | 21M | 73 | 4.92 | 15% |\n| low | 33 | $0.26 | 4k | 13M | 74 | 2.26 | 1% |\n| non-reasoning | 28 (estimated) | n/a | n/a | n/a | 67 | 1.03 | n/a |\n\nPrice: $4.00 in, $20.00 out, $0.40 cache hit per 1M. Context 1M. AA marks the\nnon-reasoning index score as estimated.\n\n### GPT-5.6 Luna (OpenAI) - previous generation\n\nThe role map no longer uses GPT-5.6 Luna. This table stays as the measured\nbaseline for the GPT-6 Luna switch.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 37 | $0.18 | 41k | 154M | 119 | 106.29 | 12% |\n| xhigh | 35 | $0.09 | 24k | 85M | 115 | 43.42 | 4% |\n| high | 32 | $0.04 | 14k | 50M | 110 | 14.13 | 3% |\n| medium | 25 | $0.02 | 4k | 18M | 114 | 2.28 | 1% |\n| low | 21 | $0.01 | 3k | 10M | 116 | 1.56 | 0% |\n| non-reasoning | 16 | $0.01 | 2k | 5M | 113 | 0.68 | 1% |\n\nPrice: $0.20 in, $1.20 out, $0.02 cache hit per 1M. Context 1M.\n\n## Why `task` runs Opus 5.5 high\n\n`task` runs `anthropic/claude-opus-5-5:high`, the same model and level as\n`default`. The owner moved it from `openai-codex/gpt-6.1-sol:high` on\n2026-10-09. GPT-6.1 Sol high then became the `task` retry fallback. Since\nDocksDocks/public#175, the fallback is GPT-6.2 Sol high\n(`openai-codex/gpt-6.2-sol:high`). The owner uses Astra only for main\norchestration, so Astra has a dedicated `astra` cycle stop at `xhigh`. This\ncomparison keeps the retired Astra-low, GPT-5.6 Sol, and GPT-6.1 Sol choices\nbeside the current Opus level. It is the v4.3.2 capture of 2026-09-29, so it\ndoes not compare with the v5.0.1 GPT-6.2 rows. GPT-6.2 Sol above has the\nfigures for the current fallback.\n\n| Metric | Astra low, retired | GPT-5.6 Sol high, retired | GPT-6.1 Sol high, former fallback | GPT-6.1 Sol max | Opus 5.5 high, current |\n|---|---:|---:|---:|---:|---:|\n| Intelligence Index | 46 | 42 | 50 | 52 | 54 |\n| Cost per Index task | $0.82 | $0.81 | $0.32 | $0.72 | $1.82 |\n| Output tokens per task | 4k | 13k | 13k | 38k | 36k |\n| Index output tokens | 10M | 34M | 25M | 67M | 53M |\n| Answer TTFT | 2.81 s | 9.40 s | 57.26 s | 267.64 s | 52.85 s |\n| End-to-end response time | 13.08 s | 16.04 s | 64.81 s | 275.12 s | 59.60 s |\n| Time per index task | 91.73 s | 176.91 s | 202.65 s | 568.66 s | 294.20 s |\n| Terminal-Bench 4.0 | 42% | 21% | 52% | 56% | 57% |\n| AA-Briefcase v1.1 | 1261 | 1370 | 1471 | 1564 | 1705 |\n| AA-Omniscience | 41 | 20 | 41 | 42 | 41 |\n\nGPT-6.1 Sol high scores 50 against GPT-5.6 Sol high at 42. It costs $0.32\nagainst $0.81 per index task, and both use 13k output tokens per task. It\nscores 52% against 21% on Terminal-Bench 4.0 and 1471 against 1370 on\nAA-Briefcase. The new high level has a longer answer TTFT, 57.26 s against\n9.40 s, and longer end-to-end response time, 64.81 s against 16.04 s.\n\nAstra low scores 46 against GPT-6.1 Sol high at 50 and costs $0.82 against\n$0.32 per index task. Astra low has the shorter TTFT, 2.81 s against\n57.26 s. The owner reserves Astra for interactive orchestration.\n\nGPT-6.1 Sol max scores two index points above high, at 52 against 50. It\ncosts $0.72 against $0.32 per index task, with TTFT of 267.64 s against\n57.26 s.\n\nOpus 5.5 high scores 54 against GPT-6.1 Sol high at 50, 57% against 52% on\nTerminal-Bench 4.0, and 1705 against 1471 on AA-Briefcase. It costs $1.82\nagainst $0.32 per index task. Its answer TTFT is 52.85 s against 57.26 s.\n\nThe `astra` cycle stop runs GPT-6.2 Astra `xhigh`. At v5.0.1 it has index 62,\n$2.52 per index task, and a 52.89 s TTFT (see GPT-6.2 Astra). Coding Agent\nIndex v2.1 lists Codex with GPT-6.2 Astra at high, xhigh, and max.\n\n## How Astra is selected in practice\n\nNo subagent role or `task.agentModelOverrides` entry resolves Astra.\n`modelRoles.astra` is reachable only through the model switcher as a main\norchestrator role. The explicit Fable retry chain can also select Astra.\nNo subagent selects Astra automatically.\n\n`SoT/.omp/models.yml` declares the full `low, medium, high, xhigh, max` ladder\nwith `defaultLevel: xhigh` under\n`providers.openai-codex.modelOverrides.gpt-6.2-astra.thinking`.\nThe override stays as the kit's worked example of a provider ladder\nredefinition. The in-session thinking control can still select `low` for a\nquick answer. The block is keyed by model id, so it moved from `gpt-6-astra`\nto `gpt-6.2-astra` with the role. `ompRemovals.ts syncOmpModelRemovals`\nprunes the deployed `gpt-6-astra` block while it equals the shipped block, and\nkeeps a block that the user edited.\n\n- The bundled `scout` and `sonic` agents carry `model: \"@smol\"` and\n `thinking-level: medium` in their embedded frontmatter, so they run Luna,\n not Opus 5.5 or Astra. To move them, change `modelRoles.smol` or add a\n `task.agentModelOverrides` entry for the agent name.\n- The bundled `task` agent carries `model: \"@task\"` and\n `thinking-level: auto`. It resolves Opus 5.5 high. The `:high` suffix on\n `modelRoles.task` is an explicit level, so it outranks the agent's `auto`,\n and the auto classifier does not run for a `task` spawn.\n- `task.enableEffort` stays at omp's default `false`, so the task tool has no\n `effort` field and every spawn runs the level of its agent's role. When the\n field is on, a caller can pass `effort: lo`, `med`, or `hi`, and caller\n effort outranks the role suffix. omp maps it onto the model's own ladder,\n not onto level names: `lo` selects the lowest level, `med` the lower middle,\n and `hi` the highest (`resolveTaskEffortLevel` in omp's\n `packages/tui/src/thinking.ts`, omp 18.8.5). Then omp caps the result at\n `task.maxEffort`. Up to 0.23.0 the kit set that cap to `xhigh`. On the\n `low, medium, high, xhigh, max` ladder, `hi` then gave `xhigh`, so many\n `task` spawns ran Opus 5.5 xhigh despite the `:high` role suffix. On\n 2026-11-05, a fresh `omp -p` run on omp 18.16.0 with the field off had no\n `effort` field, and its `task` child recorded\n `resolvedModel: anthropic/claude-opus-5-5:high`.\n- Since 0.24.0 the kit sets no `task.maxEffort`, so the cap is omp's default\n `max`. With `task.enableEffort` off, the cap applies only to a per-call\n `model` with a `:level` suffix.\n- In the deployed config, `scout` and `sonic` run GPT-6 Luna `medium`. The\n four reviewer agents resolve `@reviewer` and run GPT-6.1 Terra `high` on the\n live tier of the main session. A `docks-kit omp` free session replaces\n both roles with its free model (see Free session launcher). A retry can\n fall back to the role's fallback chain, for the reviewers Opus 5.5 `high`.\n\nThe runtime per-agent measurement from fresh `omp -p` runs on 2026-09-09\npredates this change. It applies to the retired Astra-low `task` configuration,\nnot the current role map.\n\nOn 2026-11-18, omp 18.22.2 listed GPT-6.2 Astra with a 272,000-token context\nwindow. This is the `/extended-context off` window, and it equals the Codex\ndefault context. OpenAI lists a 1,050,000-token context and 922,000 maximum\ninput tokens. For GPT-6 Astra, `/extended-context on` used the 922k input\nwindow. The kit has not checked the window that `/extended-context on` gives\nfor GPT-6.2 Astra.\n\n## Free session launcher (`docks-kit omp`)\n\n`docks-kit omp [--model <selector>|--pick] [args...]` starts one interactive\nomp session with a configuration overlay that selects a free model. The\noverlay sets the 16 chat-model roles in `ompOverlay.ts ROLE_ORDER` to that\nmodel and empties the 12 retry fallback chains in `ompOverlay.ts\nFALLBACK_ORDER`. These roles include `memory`, `judge`, and `advisor`. The SoT\ndoes not set them, but omp otherwise uses its built-in priority chain for\n`memory` and `judge`, and that chain can name a paid model. omp resolves the\n`/advisor on` model from `modelRoles.advisor` before the `slow` role. A\ndeployed, user, or project `advisor` role could otherwise send it to a paid\nmodel. The overlay also empties the retry\nchains keyed by the free model: the bare selector, `<selector>:off`, and\n`<selector>:<level>` for every level in `ompOverlay.ts THINKING_LADDER`. omp\nuses a chain keyed by the model before a role chain, so a project or\n`PI_CONFIG_FILES` chain for the free model could otherwise reach a paid model.\nThe overlay does not set the `web` role or its retry chain. The deployed\nweb-search provider order therefore applies, and that order includes the paid\n`openai-codex/gpt-6-luna` entry. omp merges the overlay key by key. Each other\ndeployed retry chain, such as a `plan`, `slow`, or `designer` chain, therefore\nstays in the merged config. A retry of the free model does not reach such a\nchain, because omp uses the empty chain keyed by the free model first.\nThe overlay also sets `defaultThinkingLevel` and `task.maxEffort` to the\nsession level. For a model that publishes no thinking ladder, the overlay\nomits both keys. A value in the deployed config then applies, or else the omp\ndefault, which is `max` for `task.maxEffort`.\n\nThe launcher renders a run overlay to\n`~/.cache/docks-kit/omp-free-<model>-<digest>.yml` at mode 0600 and passes it\nthrough omp's repeatable `--config` flag. Each distinct model-and-level\ncombination gets its own file, because omp re-reads a changed overlay during\na live session, and a second launcher must not change the level of that\nsession. The name sanitizes the selector for the file system and appends a\ndigest of the rendered overlay. The digest covers the selector and the\nlevel, so two selectors that differ only in separator characters stay\napart. A session launch never reads or writes `~/.omp/agent/config.yml` or\n`models.yml`; only `--fast`, below, edits `config.yml`. It\nnever touches the SoT. The next plain `omp` run uses the paid configuration\nagain.\n\nThe launcher starts omp as\n`omp launch --config <overlay> --model <selector>[:<level>] [args...]`, where\n`[args...]` are the arguments after the launcher flags, in the same order.\n`docks-kit omp -p \"...\"` runs one prompt. `docks-kit omp --continue` resumes\nthe previous session. A bare `docks-kit omp` opens an interactive session.\n\n`launch` makes omp read every forwarded word as message text. So `docks-kit\nomp commit` sends `commit` to the free model as a prompt, and no omp\nsubcommand runs through the launcher. To run an omp subcommand such as\n`commit`, `bench`, or `search`, run `omp` directly. The explicit `--model`\noutranks the model that omp restores from a stored session. So `--continue`,\n`--resume`, and `autoResume` keep the free model and its level.\n\n### Model selection that the launcher controls\n\nThe overlay ranks above the deployed global and project configuration, and\nbelow runtime overrides and later overlay files. The launcher handles each\nknown input that can select a model above the overlay:\n\n- Forwarded model flags. The launcher rejects `--config`, `--model`,\n `--smol`, `--slow`, `--plan`, `--models`, `--provider`, `--prewalk-into`,\n and `--plan-yolo-into`, in the `--flag value` and the `--flag=value` form.\n It exits with code 2 and starts no omp process. It checks every forwarded\n argument, also after a `--`, because omp can read that `--` as the value of\n a flag such as `--api-key` and then read the next flag. The error names the\n flag and the recoveries. For a free model, put `--model <selector>` before\n the other arguments or use `--pick`. For a paid model, run `omp` directly.\n For another config file, list it in `PI_CONFIG_FILES`.\n- A restored session model. The explicit `--model` keeps the free model.\n- An omp subcommand. `launch` makes it message text.\n- The model environment variables `PI_SMOL_MODEL`, `PI_SLOW_MODEL`, and\n `PI_PLAN_MODEL`. The launcher sets each one to the overlay value of its\n role in the omp environment, and prints one warning for each exported value\n that it replaces. omp fills an unset or empty variable from its `.env`\n files, so the launcher sets the variables instead of removing them.\n- `PI_CONFIG_FILES`. The launcher appends the overlay path to the exported\n entries, so an `omp` that the bash tool of the session starts loads the\n overlay too. omp loads these files below `--config` overlays, so an exported\n entry still applies below the overlay. A `PI_CONFIG_FILES` value in an omp\n `.env` file does not apply in a launcher session, because the launcher\n always sets the variable.\n- The omp profile. The catalog check below covers every profile that the\n launch can select.\n\n### Model selection outside the launcher\n\nThese paths act after omp starts or outside the chat roles. The launcher does\nnot control them:\n\n- In-session selection. `Alt+M` (model hub), `Alt+P` (session-only picker),\n `/switch <selector>`, `/model`, and `/modelpreset` can select any catalog\n model. `/resume` and a session switch restore the model of the target\n session. A seance subagent runs on the models of its source session. An\n `Alt+M` assignment of the `default` role writes `modelRoles.default` to the\n deployed `~/.omp/agent/config.yml`, so later plain `omp` runs use it too.\n- The `web` role and its retry chain. By owner decision they keep the\n deployed web-search provider order, which can reach the paid\n `openai-codex/gpt-6-luna` entry.\n- The model-kind roles `image`, `speech`, and `dictation`. A chat model\n cannot serve them, so the overlay does not set them.\n- Extensions and hooks. `-e`, `--hook`, and `--plugin-dir` run arbitrary\n code, and that code can select any model.\n\nThese lists name the known paths. They are not a closed set.\n\nThe default model is `opencode-zen/muse-spark-1.3-contributor-free` (\"Muse\nSpark 1.3 Free\", 1,048,576-token context) at `xhigh`. `xhigh` is the ceiling\nof that model ladder: `minimal, low, medium, high, xhigh`. The paid\n`muse-spark-1.3` sibling also offers `max`. The free variant does not.\n\nThe level comes from the ladder of the chosen model, never from a fixed list.\nEvery role, `advisor` included, runs the same level. Under `--model`, that\nlevel is the ceiling of the ladder.\n\nFree ladders are not uniform. On 2026-09-11 the 26 free models published six\ndistinct ladders: 21 include `medium`, 3 stop at `low, high, max` or\n`high, max`, and 2 publish no ladder at all. A model without a ladder gets\nbare selectors with no `:level` suffix, because an invented level makes omp\nfail when the session starts.\n\nThe choice persists per machine in `~/.docks-kit/kit.db` (table\n`omp_session`). It survives across sessions. It is never\ncommitted. `--model <selector>` records one selector and derives the level\nfrom the catalog row. `--pick` opens an interactive wizard.\n\nThe picker lists only models the live `omp models --json` catalog reports at\nzero input and output cost with `pricingStatus` `free` or `unknown` (26\nentries on 2026-09-11). A zero-cost row with another status, such as\n`variable` or `included`, is billed outside the token price, so the picker\nleaves it out. The resulting overlay sets the 16 `ROLE_ORDER` roles to the\nchosen free model and empties the 12 `FALLBACK_ORDER` chains and the chains\nkeyed by that model. The `web` role, its chain, and each other deployed chain\nkeep the deployed values. The\ncatalog can advertise a free model that the account cannot call; omp reports\nthat provider error unchanged.\n\nAfter the model, the wizard asks about the thinking level. `ompOverlay.ts\nplanEffortChoice` decides whether the question applies, because omp accepts a\n`:level` suffix only for a level the chosen model publishes:\n\n- No ladder: the wizard asks nothing and the overlay omits every level.\n- One level: the wizard states that level and asks nothing.\n- Two or more levels: the wizard asks one question, the thinking level for\n every role. It lists the levels of the model from the highest down, so\n `Enter` keeps the highest level.\n\nThe launch line names the selector and the level, or the model default level\nfor a model without a ladder. It reports no separate advisor level.\n\nAn omp login is required. The kit owns no login flow. Every launch reads the\nlive free catalog of each candidate profile. A plain launch checks the\nremembered model, or the default model, against those catalogs. When the\nmodel is not there, the launcher stops before omp starts. The model can be\nrenamed, repriced, or on a provider that is not logged in. Without this\ncheck, omp silently starts the default model of the first logged-in\nprovider, which can be paid.\n\nEach omp profile has its own login and `models.yml`, so a selector can be\nfree in one profile and missing or paid in another. The candidate profiles\nare the profile of the environment (`OMP_PROFILE`, `PI_PROFILE`, or the\ndefault) and each forwarded `--profile <name>` or `--profile=<name>` value.\nThe launcher reads every forwarded argument, also after a `--`, because omp\ncan read that `--` as a flag value and then select a later profile. It runs\n`omp models --json` for the profile of the environment and\n`omp --profile <name> models --json` for each forwarded name. The session\nmodel must be free in every one of these catalogs. `--model` and `--pick`\nchoose from the catalog of the last forwarded profile, or of the profile of\nthe environment when the arguments name none. A `--profile` without a name\nstops the launcher before omp starts.\n\nWhen the catalog renames the free variant, change only the default selector\nconstant. Until then, a plain launch on that default stops with an error. A\nladder change needs no code change. Under `--model` the level is derived\nfrom the catalog row of the chosen model, and under `--pick` the user chooses\nit from the ladder that same row publishes. Refresh the recorded default\nand the ladder counts in these docs in the same commit.\n\n## OpenAI fast mode (`docks-kit omp --fast`)\n\n`docks-kit omp --fast` toggles `tier.openai` in the deployed\n`~/.omp/agent/config.yml` between `priority` and `none`, prints the old and new\nvalues, and exits without starting a session. `priority` is the tier omp's\n`/fast on` selects for OpenAI and OpenAI-Codex models. `--fast` over\n`ultrafast` selects `priority`. The kit ships no Ultrafast toggle: omp honors\n`ultrafast` for a Codex model only when its catalog `serviceTiers` lists it.\nThe omp 18.4.9 catalog listed none for GPT-6.1 Sol, Astra, or Luna. On\n2026-11-18, `omp models openai-codex --json` on omp 18.22.2 listed no\n`serviceTiers` for any `gpt-6` id, `gpt-6.2-sol` and `gpt-6.2-astra`\nincluded. The SoT does not declare `tier.openai`, so the additive sync merge\nkeeps the toggled value. New sessions read it; a running session changes\nthrough `/fast`.\n\nThe four review agents inherit the live tier of the main session\n(`task.agentServiceTierOverrides: inherit`). In a new session after\n`docks-kit omp --fast`, they run on `priority` when `tier.openai` is `priority`,\nand on standard processing when it is `none`. A running session keeps the tier\nit started with, so its reviewers do not follow a later toggle.\n\n`--fast` never changes the Anthropic tier. The SoT leaves `tier.anthropic` at\nomp's default `none`, so each session starts with it. In omp\n18.16.0, `/fast on` in a session whose current\nmodel is Anthropic sets `anthropic: priority` for that session. The reviewers\nthen inherit it, so their Opus 5.5 fallback also runs fast. omp has no\noverride value that inherits only the OpenAI tier. To keep Anthropic models\non normal processing, use `docks-kit omp --fast` and a new session, not\n`/fast` in an Opus session.\n\n## Maintenance\n\n- Refresh each per-level row from the rendered metric table of a release\n comparison page, for example\n `/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra` and\n `/models/comparisons/gpt-6-2-astra-vs-gpt-6-2-sol`. Each page shows every\n level of both models. Take tokens per task and index tokens from the data\n of the model page, for example `/models/gpt-6-2-sol`, and check that its\n other values match the rendered table. A model-page chart holds only about\n 20 models, so a value missing there does not mean that AA has not measured\n it.\n- On 2026-11-18, the per-level pattern\n `/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high` returned HTTP 404. A\n comparison with a model that AA marks deprecated also returned HTTP 404, for\n example `gpt-6-1-sol`, `gpt-6-astra`, or `gpt-5-6-sol`. Read such a model\n from the data of its model page.\n- Keep AA rows at `high` and `xhigh` at least for each model that an omp role\n or retry chain uses, with the index version and the capture date (see AA\n rows for each role model). Add the missing rows in the same commit as a\n role or chain change.\n- After a role or chain change, run `omp models openai-codex` and check that\n it lists every `openai-codex` id that the roles and chains name. Sync does\n not check the omp catalog.\n- Refresh the Coding Agent Index from `/agents/coding-agents`.\n- Record the index version with the numbers. AA changes index composition\n between versions, so a score from another version is not a comparison.\n- Update the capture date in the same commit as any number.\n- Verify Astra ladder changes in `SoT/.omp/models.yml` through the model\n switcher and in-session thinking control.\n- The kit leaves `task.maxEffort` and `task.enableEffort` at omp's defaults,\n `max` and `false`. After an omp update, check both in\n `omp config list --json`. Verify a kit change to either key with a fresh\n `omp -p` spawn per bundled agent.\n";var omp_context_default=`# omp context and compaction
|
|
24358
|
+
`;var platforms_default=`# Platform support
|
|
24359
|
+
|
|
24360
|
+
The supported host matrix is exact: Linux on x64 and arm64, macOS on arm64,
|
|
24361
|
+
and Windows on x64.
|
|
24362
|
+
|
|
24363
|
+
| Platform | Architecture | Sync engine |
|
|
24364
|
+
|----------|--------------|-------------|
|
|
24365
|
+
| Linux | x64 | EngineNative (TS) |
|
|
24366
|
+
| Linux | arm64 | EngineNative (TS) |
|
|
24367
|
+
| macOS | arm64 | EngineNative (TS) |
|
|
24368
|
+
| Windows | x64 | EngineNative (TS) |
|
|
24369
|
+
|
|
24370
|
+
POSIX hosts use the \`docks-kit\` launcher. Windows uses \`docks-kit.ps1\`.
|
|
24371
|
+
Hosts outside this table fail before either launcher runs the Bun source.
|
|
24372
|
+
The POSIX launcher and \`install.sh\` read the architecture of the
|
|
24373
|
+
shell with \`uname -m\`. On an Apple silicon Mac, a shell that runs under
|
|
24374
|
+
Rosetta reports \`x86_64\` and gets the unsupported-host message, so run
|
|
24375
|
+
docks-kit from a native arm64 shell.
|
|
24376
|
+
|
|
24377
|
+
EngineNative is the only supported engine on supported hosts.
|
|
24378
|
+
When \`DOCKS_KIT_ENGINE=bash\` is set, the commands that run the engine (\`sync\`
|
|
24379
|
+
and \`toolchain\`) exit 2 with the removed-engine message. The
|
|
24380
|
+
message points at the \`bash-engine-final\` tag for historical recovery. Other
|
|
24381
|
+
commands ignore the variable.
|
|
24382
|
+
`;var omp_models_default="# omp models\n\nWhy `SoT/.omp/config.yml` points each omp role at a specific model and thinking\nlevel, and the Artificial Analysis (AA) measurements the choices were weighed\nagainst.\n\n## Role map\n\n| Role | Model | Level | Index | Cost/task | TTFT |\n|---|---|---|---:|---:|---:|\n| `default` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `slow` | `anthropic/claude-opus-5-5` | xhigh | 56 | $3.46 | 136.30 s |\n| `plan` | `anthropic/claude-opus-5-5` | xhigh | 56 | $3.46 | 136.30 s |\n| `task` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `designer` | `anthropic/claude-opus-5-5` | high | 54 | $1.82 | 52.85 s |\n| `vision` | `anthropic/claude-opus-5-5` | medium | 51 | $1.34 | 21.87 s |\n| `smol` / `commit` | `openai-codex/gpt-6-luna` | medium | 29 | $0.02 | n/a |\n| `tiny` | `openai-codex/gpt-6-luna` | low | 21 | $0.0045 | 2.18 s |\n| `fable` | `anthropic/claude-fable-5-2` | medium | 56 (v5.0.1) | $3.80 (v5.0.1) | 11.23 s (v5.0.1) |\n| `switch_fable` | `anthropic/claude-fable-5-2` | medium | 56 (v5.0.1) | $3.80 (v5.0.1) | 11.23 s (v5.0.1) |\n| `astra` | `openai-codex/gpt-6.2-astra` | xhigh | 62 (v5.0.1) | $2.52 (v5.0.1) | 52.89 s (v5.0.1) |\n| `reviewer` | `openai-codex/gpt-6.1-terra` | high | 42 (v5.0.1) | $0.26 (v5.0.1) | 10.91 s (v5.0.1) |\n| `web` | `web/firecrawl` | n/a | n/a | n/a | n/a |\n\nThe table reports the measured Artificial Analysis figures for each assigned\nmodel and level. It states no motive that the config or omp's own\ndocumentation does not establish. AA has not measured output speed or latency\nfor GPT-6 Luna medium, so that row carries `n/a` for TTFT. AA measures no web\nsearch provider, so the `web` row carries no figures. The `astra`, `reviewer`,\n`fable`, and `switch_fable` rows come from later captures at Intelligence\nIndex v5.0.1: GPT-6.1 Terra from 2026-11-05, Fable 5.2 from 2026-11-12, and\nGPT-6.2 Astra from 2026-11-18. The 2026-09-29 capture predates these models.\nCompare those rows only with other v5.0.1 figures (see GPT-6.2 Astra, GPT-6.1\nTerra, and Claude Fable 5.2 below). A review benchmark chose the model of the\n`reviewer` role (DocksDocks/public#130), not these figures. The tier of that\nrole follows the main session (DocksDocks/public#134).\n\nThe role map carries no Coding Agent Index column. That index measures specific\nagent harnesses and model levels, not omp roles. The snapshot section below\nlists the relevant entries, including Codex with GPT-6.2 Sol and GPT-6.2 Astra\nat high and xhigh.\n\n### AA rows for each role model\n\nFor each model that an omp role or retry chain uses, this topic records AA\nrows at `high` and `xhigh` at least. Each set of rows names its Intelligence\nIndex version and its capture date. A role or chain change adds the missing\nrows in the same commit. On 2026-11-18, the role map and the retry chains use\nsix models, and each has both rows:\n\n| Model | Index version | Capture date |\n|---|---|---|\n| Claude Opus 5.5 | v4.3.2 | 2026-09-29 |\n| GPT-6 Luna | v4.3.2 | 2026-09-29 |\n| Claude Fable 5.2 | v5.0.1 | 2026-11-12 |\n| GPT-6.1 Terra | v5.0.1 | 2026-11-05, speed re-measured 2026-11-18 |\n| GPT-6.2 Sol | v5.0.1 | 2026-11-18 |\n| GPT-6.2 Astra | v5.0.1 | 2026-11-18 |\n\n### OpenAI model availability in omp\n\nThe `openai-codex` selectors for GPT-6 Sol and GPT-6 Luna were deployed on\n2026-09-22, while the rollout of both models was still in progress. The owner\nchose to deploy them before the rollout completed. Checks on that date, with\nomp 18.2.9 and codex-cli 0.153.3:\n\n- At 19:02 UTC, `codex exec -m gpt-6-sol` returned HTTP 400, `The 'gpt-6-sol'\n model is not supported when using Codex with a ChatGPT account.`\n `gpt-6-luna` returned the same error. The Codex model cache fetched at that\n time listed neither model.\n- At 19:14 UTC, the Codex model cache for the same account listed\n `gpt-6-sol` and `gpt-6-luna`. A request on the new default could not be\n tested, because the account had reached its Codex usage limit.\n- The omp `openai-codex` catalog listed `gpt-6-astra` and the three `gpt-5.6`\n models, but not `gpt-6-sol` or `gpt-6-luna`, both before and after\n `omp models refresh` at 19:14 UTC. omp resolves a selector that is not in\n the catalog by provider-scoped fuzzy match. An `omp -p --mode json` run on\n `openai-codex/gpt-6-sol:low` recorded `gpt-5.6-sol` as the serving model,\n and the Luna selector recorded `gpt-5.6-luna`. omp printed no warning.\n\nOn 2026-09-25, omp 18.3.1 listed `gpt-6-sol` and `gpt-6-luna` in\n`omp models openai-codex`. An `omp -p --mode json` run on each selector\nrecorded `gpt-6-sol` and `gpt-6-luna` as the serving model, so the selected\nomp roles ran GPT-6 on that date.\n\nOn 2026-09-29, omp 18.4.4 listed `gpt-6.1-sol` at low, medium, high, xhigh,\nand max, with a 272K context window and 128K maximum output. An\n`omp -p --mode json --model openai-codex/gpt-6.1-sol:low` run recorded\n`gpt-6.1-sol` as the serving model. To recheck, run\n`omp models openai-codex`; the `gpt-6.1-sol` row must appear. Codex-cli\n0.159.0 could not complete `codex exec -m gpt-6.1-sol`: the login had ended,\nand the request returned HTTP 401 `refresh_token_invalidated`. The Codex\nmodel cache was last fetched on 2026-09-22 and does not list `gpt-6.1-sol`,\nso that Codex run did not establish model availability.\n\nOn 2026-11-18, omp 18.22.2 listed `gpt-6.2-sol` with a 500K context window\nand `gpt-6.2-astra` with a 272K context window. Both had low, medium, high,\nxhigh, and max. An `omp -p --mode json` run on each selector at `:low`\nrecorded that same id as the serving model. omp 18.22.2 listed no GPT-6.2\nTerra and no GPT-6.2 Luna. To recheck, run `omp models openai-codex`; the\n`gpt-6.2-sol` and `gpt-6.2-astra` rows must appear. Sync deploys the selectors\nwithout a catalog check. On an omp release without these ids, omp can resolve\nthem by fuzzy match to another model without a warning, as on 2026-09-22.\n\nOn 2026-11-19, omp 19.0.0 became the toolchain floor and verified pin. Its\n`omp models --json` catalog listed each of the 12 model selectors of\n`modelRoles` and `retry.fallbackChains` (the `web/` entries left out) as an\nexact `provider/id` row, so no role depends on a fuzzy match. This check read\nthe catalog only; it ran no model request. The rows also carry the fields that\nthe free launcher reads (`ompOverlay.ts parseFreeModels`): a string\n`selector`, a `cost` object with numeric `input` and `output`, a numeric\n`contextWindow`, and a `thinking` ladder array or `null`.\n\nWhat omp's settings catalog establishes about these roles:\n\n- `cycleOrder` lists the roles the model switcher cycles. `fable` is the\n fourth `Ctrl+P` stop, and `astra` is the fifth and last stop.\n- `tiny` overrides the model for lightweight background tasks: titles, memory,\n auto-thinking, and unexpected-stop detection.\n- `modelTags` carries role metadata and can introduce roles; `hidden: true`\n keeps `switch_fable` and `reviewer` out of the switcher list.\n\n`modelRoles.reviewer` is a kit-defined role, not an omp built-in. It runs\n`openai-codex/gpt-6.1-terra:high`. omp resolves `@<name>` for any key in\n`modelRoles` (`getModelRoleAlias` in omp's `model-resolver.ts`, omp 18.8.5).\n`task.agentModelOverrides` maps `reviewer`, `security-reviewer`,\n`code-reviewer`, and `plan-reviewer` to `@reviewer`, so one key sets the\nmodel for every reviewer. `task.agentServiceTierOverrides` sets the same four\nagents to `inherit`, so they take the live tier of the main session for each\nprovider. \"OpenAI fast mode\" below describes how that tier changes. The bundled\n`reviewer` and `security-reviewer` agents ship with omp, and the kit plugin\n`docks-kit-omp` ships `code-reviewer` and `plan-reviewer`.\n`retry.fallbackChains.reviewer` holds `anthropic/claude-opus-5-5:high`, and\n`retry.fallbackChains.task` holds `openai-codex/gpt-6.2-sol:high`; both are\ncross-vendor fallbacks.\n\nThe review benchmark of DocksDocks/public#130 ran on 2026-11-05. It used 24\nheld-out cases of the `review-benchmark` skill, 2 runs each. The cases came\nfrom DocksDocks/docks, the source repository of that skill at the time.\nIt compared `gpt-6.1-sol` and `gpt-6.1-terra` at `high`, each on the `default`\nand `priority` tiers. The user set the effort `high`; the benchmark chose the\nmodel. `gpt-6.1-terra` on `default` let the fewest known defects escape (34.90\nper 50 known). No other setting stayed within the pre-registered bounds. A\nTerra review took a median of 69.3 s, against 172.8 s for `gpt-6.1-sol` on\n`default`. It used about a third of the tokens. It returned more wrong\nfindings: 0.49 per run against 0.20. The issue holds the full tables and the\ndecision rule.\n\nThe benchmark rule first pinned the `default` tier. The user then chose to\nlet the reviewers follow the fast toggle (DocksDocks/public#134). On the\n`priority` tier, Terra `high` let 35.15 known defects per 50 escape, against\n34.90 on `default`, and a review took a median of 35.7 s. Its 90% intervals\nmissed two pre-registered bounds: escaped difference up to 3.26 (bound 2) and\nrecall difference down to -0.07 (bound -0.05). Both intervals include 0, and\nthe user judged the difference as noise.\n\n`retry.fallbackChains.astra` holds `anthropic/claude-fable-5-2:medium`.\n`retry.fallbackChains.fable` holds `openai-codex/gpt-6.2-astra:xhigh`.\nEach deliberate cycle stop falls to the other vendor. Without these explicit\nchains, `retry.fallbackChains.default` would send either stop to\n`openai-codex/gpt-6.2-sol:high`.\nChain entries are concrete selectors, not role aliases, so this pair cannot\nrecurse. The hidden `switch_fable` chain stays empty.\n\n### Advisor removed\n\nBy owner decision (2026-11-12, 0.22.22), the kit sets no omp advisor.\n`SoT/.omp/config.yml` has no `advisor` block, no `modelRoles.advisor`, and no\n`retry.fallbackChains.advisor`. omp keeps the advisor off by default. The\nplan-lifecycle verification loop takes its place: acceptance checks, a fresh\ncode review of the diff, and a round limit. Since 2026-11-01, 33 main\nsessions had an advisor log, and no subagent session had one. A session that\nruns `/advisor on` takes its advisor model from the `slow` role, because no\n`advisor` role is set.\n\nHistory: on 2026-09-24, with omp 18.3.0, an advisor on\n`openai-codex/gpt-6-sol:medium` looped and made 1,313 requests for 140\nmain-agent requests. The kit then ran the advisor on Opus 5.5 `medium` and\nexcluded every GPT model from that role until this removal.\n\n`modelRoles.web` is `web/firecrawl`, and `retry.fallbackChains.web` lists the\nexplicit 20-entry provider order that follows it. The two keys replace the\nretired `providers.webSearchOrder` key, which omp no longer carries in its\nsettings schema. omp still accepts that key in a deployed file, expands it in\nmemory into the same two keys, and then drops it, but it never writes the\nexpansion back to disk. The kit therefore declares both keys itself.\n\nThe chain starts from the expansion omp produces, read back with\n`omp config get retry.fallbackChains`. An explicit chain replaces omp's\nbuilt-in web order wholesale, so a shortened list drops providers instead of\nreordering them. The kit makes two deliberate edits to omp's order:\n\n- The Codex Luna entry follows the kit's Luna generation and names\n `openai-codex/gpt-6-luna`.\n- The owner removed every entry that named an older model:\n `google/gemini-2.5-flash`, `google-antigravity/gemini-2.5-flash`,\n `anthropic/claude-haiku-4-5`, `openai-codex/gpt-5.6`,\n `openai-codex/gpt-5.5`, `xai/grok-4.5`, and `xai-oauth/grok-4.5`. omp never\n tries those search backends now.\n\nThe order keeps Firecrawl, Exa, Perplexity, and Codex first. The remaining\n`web/*` entries are omp's own ordering of the providers behind them.\n\n## Artificial Analysis snapshot\n\nSource: `https://artificialanalysis.ai`, read on 2026-09-29 at Intelligence\nIndex v4.3.2 and Coding Agent Index v1.5. Each per-level row comes from the\nmetric table of `/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`.\nEach page title names the requested model and level and prints the same\nIntelligence Index version. AA serves `max` under the bare model slug.\nThe GPT-5.6 Sol high self-comparison URL does not load, so that baseline row\ncomes from the GPT-5.6 Sol high column of the GPT-6.1 Sol high comparison.\nIndex composition changes between versions; figures from an earlier capture\ncannot be mixed with these.\n\nAt v1.5 on 2026-09-29, the Coding Agent Index page (`/agents/coding-agents`)\nlisted 30 harness, model, and level entries. It covered GPT-6.1 Sol with Codex\nat low, medium, high, xhigh, and max; Opus 5.5 and Fable 5.1 with Claude Code\nat max; and Astra and Luna with Codex at max. It also covered Grok Build with\nGrok 4.7 at xhigh, Antigravity SDK with Gemini 3.8 Flash at high, and Opencode\nwith GLM-5.3 and Kimi Code CLI with Kimi K3 without levels. The relevant\npublished v1.5 scores are:\n\n| Harness and model | Coding Agent Index |\n|---|---:|\n| Claude Code - Opus 5.5 (max) | 66 |\n| Claude Code - Fable 5.1 (max, with fallback) | 62 |\n| Codex - GPT-6 Astra (max) | 62 |\n| Codex - GPT-6.1 Sol (xhigh) | 63 |\n| Codex - GPT-6.1 Sol (medium) | 61 |\n| Codex - GPT-6.1 Sol (high) | 60 |\n| Codex - GPT-6.1 Sol (max) | 60 |\n| Codex - GPT-6.1 Sol (low) | 57 |\n| Claude Code - Opus 5 (max) | 60 |\n| Codex - GPT-6 Luna (max) | 41 |\n\nThese are coding-agent scores for specific harnesses and levels, not scores\nfor the omp role map. The v1.5 table stays as history. Coding Agent Index v2.1\nbelow has the 2026-11-18 entries for GPT-6.2 Sol and GPT-6.2 Astra.\n\nColumn meanings:\n\n- **Index** - AA Intelligence Index, a weighted aggregate across its\n evaluation set. Comparable only inside one index version.\n- **Cost/task** - weighted average USD to run one index task, including\n input, cache, reasoning, and answer tokens.\n- **Tokens/task** - answer plus reasoning tokens for one index task.\n- **Index tokens** - total output tokens the model spends to complete the\n whole index run. This is the token-efficiency signal.\n- **Speed** - output tokens per second.\n- **TTFT** - seconds to the first answer token, so reasoning time counts.\n- **TB 4.0** - Terminal-Bench 4.0, one of the index evaluations (ten at v4.3.2,\n nine at v5.0.1).\n\n### Coding Agent Index v2.1\n\nSource: `https://artificialanalysis.ai/agents/coding-agents`, read on\n2026-11-18 at Coding Agent Index v2.1. This version gives equal weight to\nFrontierCode-AA 2.0, Terminal-Bench 4.1, and SWE-Atlas-QnA-AA, and lists 39\nentries. The page draws the scores only in charts. The values below are the\n`indexScore` fields of the page data, on a 0 to 1 scale. The cost and agent\nwall time columns are the mean per task from the same data. This capture did\nnot observe the rendered integer values. Do not compare these values with the\nv1.5 integers above.\n\n| Harness and model | indexScore | Cost/task | Agent wall time s |\n|---|---:|---:|---:|\n| Codex - GPT-6.2 Astra (max) | 0.5347 | $5.117 | 1506.7 |\n| Codex - GPT-6.2 Astra (xhigh) | 0.5312 | $3.198 | 992.4 |\n| Codex - GPT-6.2 Astra (high) | 0.5228 | $2.372 | 947.4 |\n| Codex - GPT-6.2 Sol (max) | 0.4862 | $1.216 | 1051.4 |\n| Codex - GPT-6.2 Sol (xhigh) | 0.4979 | $0.898 | 755.8 |\n| Codex - GPT-6.2 Sol (high) | 0.4746 | $0.764 | 635.4 |\n\nGPT-6.2 Sol scores higher at `xhigh` than at `max`. v2.1 lists GPT-6.1 Sol\nand GPT-6.1 Terra with Codex only at max.\n\n### Claude Opus 5.5 (Anthropic) - `anthropic/claude-opus-5-5`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 58 | $5.98 | 119k | 260M | 93 | 692.63 | 60% |\n| xhigh | 56 | $3.46 | 66k | 100M | 80 | 136.30 | 60% |\n| high | 54 | $1.82 | 36k | 53M | 74 | 52.85 | 57% |\n| medium | 51 | $1.34 | 26k | 38M | 74 | 21.87 | 53% |\n| low | 42 | $0.55 | 10k | 20M | 74 | 12.49 | 31% |\n\nPrice: $4.00 in, $20.00 out, $0.20 cache hit per 1M. The Anthropic platform\ndocumentation lists the same input, output, and cache-read prices. It adds a\n$5.00 five-minute cache write and an $8.00 one-hour cache write, which the AA\ncomparison table does not show. Context is 1M, with 128K maximum output.\nAdaptive thinking is always on, and the Claude API default effort is\n`medium`. All AA levels run with fallback. Max has the highest Intelligence\nIndex in this topic at this capture. AA now measures speed and latency for\nevery Opus 5.5 level; medium has a shorter TTFT than high.\n\nUntil 0.20.1, `SoT/.omp/models.yml` carried the Anthropic limits and prices as\nan `anthropic` `modelOverrides` block, because the shared catalog served this\nid as a stub with null limits and zero cost. On 2026-09-25 the catalog at\n`catalog.stencil.so` published the same context window, output cap, ladder,\nand prices, so the block was removed. Sync prunes the deployed copy only while\nit still equals the shipped block.\n\nThe removal fixes how the Opus role levels reach the API. The block set\n`thinking.mode: effort`. For that mode, omp 18.3.1 (`packages/ai/src/stream.ts`,\ntag `v18.3.1`) sends `thinking: {type: \"enabled\", budget_tokens}` and no\n`output_config.effort`. The level only picked the budget from\n`ANTHROPIC_THINKING`: `medium` 8,192, `high` 16,384, and `xhigh` and `max`\nboth 32,768 tokens. So before 0.20.1 the levels in the role table above were\nnot the effort levels that Artificial Analysis measured, and `xhigh` equaled\n`max`. The catalog row sets `thinking.mode: anthropic-adaptive`, so omp now\nsends `thinking: {type: \"adaptive\"}` with `output_config.effort` set to the\nrole level. The block also set `defaultLevel: high` for a bare\n`claude-opus-5-5` selector. `SoT/.omp/config.yml` names a level on every Opus\nselector, so no kit role depends on that default. Runs on\n`anthropic/claude-opus-5-5:high` and `:max` after the prune answered with\nexit 0.\n\n### Claude Fable 5.2 (Anthropic) - `anthropic/claude-fable-5-2`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-12 at Intelligence\nIndex v5.0.1, from the metric table of\n`/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`. AA serves `max` under\nthe bare model slug. These figures use another index version than the rest of\nthis snapshot, so they do not compare with the v4.3.2 rows above. Compare them\nwith GPT-6.1 Terra below.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 65 | $26.54 | 274k | 275M | 98 | 262.29 | 60% |\n| xhigh | 62 | $14.83 | 162k | 144M | 102 | 85.87 | 62% |\n| high | 62 | $9.08 | 98k | 85M | 97 | 27.98 | 60% |\n| medium | 56 | $3.80 | 43k | 41M | 93 | 11.23 | 55% |\n| low | 54 | $3.10 | 36k | 35M | 97 | 8.42 | 55% |\n\nPrice: $8.00 in, $40.00 out, $0.20 cache hit per 1M. The omp catalog lists\nthe same prices, a $10.00 cache write, a 1M context, and 128K maximum output.\nAll AA levels run with default fallback. On 2026-11-12, omp 18.19.0 listed\n`claude-fable-5-2` at low, medium, high, xhigh, and max, and an\n`omp -p --mode json --model anthropic/claude-fable-5-2:medium` run recorded\n`claude-fable-5-2` as the serving model.\n\n`fable` and `switch_fable` moved from Fable 5.1 to Fable 5.2 at the same\nlevel, `medium`. The Fable 5.1 table below stays as the previous-generation\nbaseline at v4.3.2.\n\n### Claude Fable 5.1 (Anthropic) - `anthropic/claude-fable-5-1`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 53 | $7.63 | 78k | 188M | 69 | 285.98 | 52% |\n| xhigh | 53 | $5.98 | 61k | 121M | 57 | 104.51 | 55% |\n| high | 51 | $3.91 | 38k | 62M | 52 | 26.01 | 52% |\n| medium | 49 | $2.98 | 28k | 44M | 50 | 8.00 | 45% |\n| low | 47 | $2.37 | 22k | 33M | 48 | 4.83 | 40% |\n\nPrice: $10.00 in, $50.00 out, $0.25 cache hit per 1M. Context 1M. All levels\nrun with fallback.\n\n### GPT-6.2 Sol (OpenAI) - `openai-codex/gpt-6.2-sol`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-18 at Intelligence\nIndex v5.0.1. The rows come from the rendered metric table of\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra`, which shows every level of\nboth models. Tokens per task and index tokens come from the data of the model\npage `/models/gpt-6-2-sol`, because the comparison table does not show them.\nThe other values in that data match the rendered table. These rows compare\nonly with other v5.0.1 figures, not with the v4.3.2 rows.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 57 | $1.01 | 40k | 61M | 85 | 66.70 | 60% |\n| xhigh | 56 | $0.65 | 24k | 33M | 81 | 26.63 | 56% |\n| high | 55 | $0.56 | 20k | 23M | 78 | 9.63 | 59% |\n\nAA and OpenAI list $2.00 input, $0.10 cached input, $2.50 cache write, and\n$10.00 output per 1M tokens. OpenAI also lists a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.2-sol>). Prompts above\n272K input tokens cost 2x input and cache rates and 1.5x output rates for the\nfull request. The knowledge cutoff is 2026-06-01. OpenAI released the model on\n2026-11-17 (<https://developers.openai.com/api/docs/changelog>). Codex uses a\n500,000-token default context (<https://developers.openai.com/codex/models>).\nOn 2026-11-18, omp 18.22.2 listed `gpt-6.2-sol` with the same 500K context\nwindow, 128K maximum output, and the levels low, medium, high, xhigh, and max.\n\n`retry.fallbackChains.default` and `.task` moved from GPT-6.1 Sol `high` to\nGPT-6.2 Sol `high`, and `.vision` moved at `medium` (DocksDocks/public#175).\nOn 2026-11-18, the v5.0.1 data of the model page `/models/gpt-6-1-sol` listed\nGPT-6.1 Sol high at index 50 and $0.59 per task. GPT-6.2 Sol high has 55 and\n$0.56.\n\n### GPT-6.2 Astra (OpenAI) - `openai-codex/gpt-6.2-astra`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-18 at Intelligence\nIndex v5.0.1. The rows come from the rendered metric table of\n`/models/comparisons/gpt-6-2-astra-vs-gpt-6-2-sol`. Tokens per task and index\ntokens come from the data of the model page `/models/gpt-6-2-astra`. These\nrows compare only with other v5.0.1 figures, not with the v4.3.2 rows.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 62 | $4.00 | 41k | 66M | 53 | 170.99 | 64% |\n| xhigh | 62 | $2.52 | 22k | 27M | 54 | 52.89 | 64% |\n| high | 60 | $2.07 | 18k | 20M | 56 | 22.07 | 60% |\n\nThe `max` and `xhigh` rows both round to 62. The page data gives 62.14 and\n61.56.\n\nAA and OpenAI list $8.00 input, $0.40 cached input, $10.00 cache write, and\n$40.00 output per 1M tokens. OpenAI also lists a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.2-astra>). The\nlong-prompt rule of GPT-6.2 Sol also applies. The knowledge cutoff is\n2026-05-18. OpenAI released the model on 2026-11-17, in the same changelog\nentry as GPT-6.2 Sol. Codex uses a 272,000-token default context. On\n2026-11-18, omp 18.22.2 listed `gpt-6.2-astra` with the same 272K context\nwindow, 128K maximum output, and the levels low, medium, high, xhigh, and max.\n\n`modelRoles.astra` and `retry.fallbackChains.fable` moved from GPT-6 Astra\n`xhigh` to GPT-6.2 Astra `xhigh` (DocksDocks/public#175). GPT-6 Astra below\nhas the v5.0.1 figures for a like-for-like comparison.\n\n### GPT-6 Astra (OpenAI) - previous generation\n\nThe role map and the retry chains no longer use GPT-6 Astra. This table stays\nas the v4.3.2 baseline for the previous `astra` role.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 53 | $3.26 | 27k | 60M | 57 | 305.56 | 59% |\n| xhigh | 52 | $2.31 | 17k | 38M | 49 | 126.90 | 60% |\n| high | 51 | $1.73 | 12k | 26M | 50 | 41.09 | 54% |\n| medium | 50 | $1.54 | 10k | 19M | 47 | 4.88 | 49% |\n| low | 46 | $0.82 | 4k | 10M | 49 | 2.81 | 42% |\n\nPrice: $10.00 in, $50.00 out, $1.00 cache hit per 1M. Context 1M. Knowledge\ncutoff 2026-04-30. AA publishes no non-reasoning Astra row.\n\nOn 2026-11-18, the v5.0.1 data of the AA model page `/models/gpt-6-astra`\nlisted GPT-6 Astra `xhigh` at index 55 and $3.66 per task, with 44 t/s and an\n83.77 s TTFT. It listed `high` at index 55, $3.24, 44 t/s, and 40.21 s. At\n`xhigh`, GPT-6.2 Astra scores 62 against 55 and costs $2.52 against $3.66 per\ntask. It produces 54 against 44 t/s, with a TTFT of 52.89 s against 83.77 s.\nAA marks GPT-6 Astra deprecated, so its comparison pages return HTTP 404.\n\n### GPT-6.1 Sol (OpenAI) - previous generation\n\nThe role map and the retry chains no longer use GPT-6.1 Sol. This table stays\nas the v4.3.2 baseline for the former `task` role and retry fallbacks.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 52 | $0.72 | 38k | 67M | 67 | 267.64 | 56% |\n| xhigh | 51 | $0.39 | 18k | 36M | 64 | 68.65 | 54% |\n| high | 50 | $0.32 | 13k | 25M | 66 | 57.26 | 52% |\n| medium | 48 | $0.21 | 8k | 15M | 62 | 5.29 | 48% |\n| low | 42 | $0.13 | 4k | 9M | 74 | 1.84 | 31% |\n\nAA lists $2.00 input, $10.00 output, and $0.10 cached input per 1M tokens.\nOpenAI also lists $2.50 per 1M cache-write tokens, a 1,050,000-token context,\n922,000 maximum input tokens, and 128,000 maximum output tokens. Prompts above\n272K input tokens cost 2x input and cache rates and 1.5x output rates for the\nfull request. The knowledge cutoff is 2026-04-30. The API effort ladder is\n`low, medium, high, xhigh, max`, with `medium` as the default. There is no\n`none`, `minimal`, or non-reasoning level. On 2026-11-18, omp 18.22.2 still\nserved `gpt-6.1-sol`, and the OpenAI deprecations page did not list it. AA\nmarks it deprecated.\n\n### GPT-6.1 Terra (OpenAI) - `openai-codex/gpt-6.1-terra`\n\nSource: `https://artificialanalysis.ai`, read on 2026-11-05 at Intelligence\nIndex v5.0.1, from the metric table of\n`/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high`. AA serves `max` under\nthe bare model slug. These figures use another index version than the rest of\nthis snapshot, so they do not compare with the v4.3.2 rows above.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 51 | $0.96 | 60k | 99M | 76 | 159.59 | 56% |\n| xhigh | 45 | $0.40 | 26k | 35M | 74 | 33.02 | 46% |\n| high | 42 | $0.26 | 17k | 21M | 73 | 10.91 | 42% |\n| medium | 38 | $0.17 | 11k | 14M | 72 | 4.43 | 32% |\n| low | 29 | $0.07 | 4k | 7M | 72 | 2.34 | 15% |\n\nFor comparison at the same index version, AA lists GPT-6.1 Sol high at index\n50, $0.59 per task, 23k tokens per task, 25M index tokens, 57 t/s, a 38.27 s\nTTFT, and 52% on Terminal-Bench 4.0. The same Sol high row read 50, $0.32, and\n57.26 s at v4.3.2, which shows why the two captures do not mix.\n\nOn 2026-11-18, the release comparison page\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra` showed new speed and TTFT\nfigures for GPT-6.1 Terra at v5.0.1. `high` ran at 65 t/s with a 10.50 s\nTTFT, `xhigh` at 65 t/s with 30.33 s, and `max` at 69 t/s with 146.49 s. The\nindex, cost, and token figures were unchanged. AA measures speed and latency\ncontinuously, so the table keeps the 2026-11-05 rows. The speed comparison\nbelow uses the 2026-11-18 figures.\n\nAA and OpenAI list $1.00 input, $5.00 output, and $0.05 cached input per 1M\ntokens. OpenAI also lists a 1,050,000-token context, 922,000 maximum input\ntokens, and 128,000 maximum output tokens\n(<https://developers.openai.com/api/docs/models/gpt-6.1-terra>).\nFast mode costs 2x Standard. The knowledge cutoff is 2026-06-01. The API effort\nladder is `none, low, medium, high, xhigh, max`, with `medium` as the default.\n\n### Output speed: GPT-6.2 Sol and GPT-6.1 Terra\n\nGPT-6.2 Sol has the higher output speed at `high` and at `xhigh`.\nThe figures come from one page,\n`/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra`, read on 2026-11-18 at\nIntelligence Index v5.0.1.\n\n| Metric | GPT-6.2 Sol | GPT-6.1 Terra |\n|---|---:|---:|\n| `high` output speed | 78 t/s | 65 t/s |\n| `xhigh` output speed | 81 t/s | 65 t/s |\n| `high` TTFT | 9.63 s | 10.50 s |\n| `xhigh` TTFT | 26.63 s | 30.33 s |\n| `high` end-to-end time | 42.65 s | 43.91 s |\n| `xhigh` end-to-end time | 85.03 s | 86.53 s |\n\nAt `high`, Sol produces about 19% more tokens per second than Terra. At\n`xhigh`, the gain is about 24%. Sol also has the lower TTFT and end-to-end\ntime at both levels.\n\nThe `reviewer` role stays on GPT-6.1 Terra `high`. The DocksDocks/public#130 benchmark chose\nTerra by escaped defects, not by speed. omp 18.22.2 lists no GPT-6.2 Terra. A\nmove of the reviewer to GPT-6.2 Sol needs a new benchmark.\n\n### GPT-6 Luna (OpenAI) - `openai-codex/gpt-6-luna`\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 37 | $0.07 | 50k | 145M | 148 | 96.96 | 13% |\n| xhigh | 34 | $0.04 | 27k | 69M | 133 | 16.87 | 8% |\n| high | 32 | $0.03 | 20k | 47M | 132 | 10.97 | 5% |\n| medium | 29 | $0.02 | 11k | 29M | n/a | n/a | 3% |\n| low | 21 | $0.0045 | 2k | 8M | 124 | 2.18 | 0% |\n| non-reasoning | 18 | $0.01 | 4k | 7M | 142 | 0.80 | 2% |\n\nPrice: $0.10 in, $0.50 out, $0.01 cache hit per 1M. OpenAI's model page lists\na $0.125 cache write, the same context, output, and long-prompt billing as\nGPT-6.1 Sol, and a 2026-05-18 knowledge cutoff. Luna also offers a\nnon-reasoning level. AA has not measured speed or latency for `medium`; it\nhas measured both at the other levels.\n\n### GPT-5.6 Sol (OpenAI) - previous generation\n\nThe role map no longer uses GPT-5.6 Sol. This table stays as the measured\nbaseline for the former GPT-6.1 Sol `task` retry fallback.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 47 | $1.99 | 29k | 90M | 85 | 98.68 | 40% |\n| xhigh | 44 | $1.18 | 20k | 51M | 77 | 24.79 | 25% |\n| high | 42 | $0.81 | 13k | 34M | 75 | 9.40 | 21% |\n| medium | 39 | $0.50 | 8k | 21M | 73 | 4.92 | 15% |\n| low | 33 | $0.26 | 4k | 13M | 74 | 2.26 | 1% |\n| non-reasoning | 28 (estimated) | n/a | n/a | n/a | 67 | 1.03 | n/a |\n\nPrice: $4.00 in, $20.00 out, $0.40 cache hit per 1M. Context 1M. AA marks the\nnon-reasoning index score as estimated.\n\n### GPT-5.6 Luna (OpenAI) - previous generation\n\nThe role map no longer uses GPT-5.6 Luna. This table stays as the measured\nbaseline for the GPT-6 Luna switch.\n\n| Level | Index | Cost/task | Tokens/task | Index tokens | Speed t/s | TTFT s | TB 4.0 |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| max | 37 | $0.18 | 41k | 154M | 119 | 106.29 | 12% |\n| xhigh | 35 | $0.09 | 24k | 85M | 115 | 43.42 | 4% |\n| high | 32 | $0.04 | 14k | 50M | 110 | 14.13 | 3% |\n| medium | 25 | $0.02 | 4k | 18M | 114 | 2.28 | 1% |\n| low | 21 | $0.01 | 3k | 10M | 116 | 1.56 | 0% |\n| non-reasoning | 16 | $0.01 | 2k | 5M | 113 | 0.68 | 1% |\n\nPrice: $0.20 in, $1.20 out, $0.02 cache hit per 1M. Context 1M.\n\n## Why `task` runs Opus 5.5 high\n\n`task` runs `anthropic/claude-opus-5-5:high`, the same model and level as\n`default`. The owner moved it from `openai-codex/gpt-6.1-sol:high` on\n2026-10-09. GPT-6.1 Sol high then became the `task` retry fallback. Since\nDocksDocks/public#175, the fallback is GPT-6.2 Sol high\n(`openai-codex/gpt-6.2-sol:high`). The owner uses Astra only for main\norchestration, so Astra has a dedicated `astra` cycle stop at `xhigh`. This\ncomparison keeps the retired Astra-low, GPT-5.6 Sol, and GPT-6.1 Sol choices\nbeside the current Opus level. It is the v4.3.2 capture of 2026-09-29, so it\ndoes not compare with the v5.0.1 GPT-6.2 rows. GPT-6.2 Sol above has the\nfigures for the current fallback.\n\n| Metric | Astra low, retired | GPT-5.6 Sol high, retired | GPT-6.1 Sol high, former fallback | GPT-6.1 Sol max | Opus 5.5 high, current |\n|---|---:|---:|---:|---:|---:|\n| Intelligence Index | 46 | 42 | 50 | 52 | 54 |\n| Cost per Index task | $0.82 | $0.81 | $0.32 | $0.72 | $1.82 |\n| Output tokens per task | 4k | 13k | 13k | 38k | 36k |\n| Index output tokens | 10M | 34M | 25M | 67M | 53M |\n| Answer TTFT | 2.81 s | 9.40 s | 57.26 s | 267.64 s | 52.85 s |\n| End-to-end response time | 13.08 s | 16.04 s | 64.81 s | 275.12 s | 59.60 s |\n| Time per index task | 91.73 s | 176.91 s | 202.65 s | 568.66 s | 294.20 s |\n| Terminal-Bench 4.0 | 42% | 21% | 52% | 56% | 57% |\n| AA-Briefcase v1.1 | 1261 | 1370 | 1471 | 1564 | 1705 |\n| AA-Omniscience | 41 | 20 | 41 | 42 | 41 |\n\nGPT-6.1 Sol high scores 50 against GPT-5.6 Sol high at 42. It costs $0.32\nagainst $0.81 per index task, and both use 13k output tokens per task. It\nscores 52% against 21% on Terminal-Bench 4.0 and 1471 against 1370 on\nAA-Briefcase. The new high level has a longer answer TTFT, 57.26 s against\n9.40 s, and longer end-to-end response time, 64.81 s against 16.04 s.\n\nAstra low scores 46 against GPT-6.1 Sol high at 50 and costs $0.82 against\n$0.32 per index task. Astra low has the shorter TTFT, 2.81 s against\n57.26 s. The owner reserves Astra for interactive orchestration.\n\nGPT-6.1 Sol max scores two index points above high, at 52 against 50. It\ncosts $0.72 against $0.32 per index task, with TTFT of 267.64 s against\n57.26 s.\n\nOpus 5.5 high scores 54 against GPT-6.1 Sol high at 50, 57% against 52% on\nTerminal-Bench 4.0, and 1705 against 1471 on AA-Briefcase. It costs $1.82\nagainst $0.32 per index task. Its answer TTFT is 52.85 s against 57.26 s.\n\nThe `astra` cycle stop runs GPT-6.2 Astra `xhigh`. At v5.0.1 it has index 62,\n$2.52 per index task, and a 52.89 s TTFT (see GPT-6.2 Astra). Coding Agent\nIndex v2.1 lists Codex with GPT-6.2 Astra at high, xhigh, and max.\n\n## How Astra is selected in practice\n\nNo subagent role or `task.agentModelOverrides` entry resolves Astra.\n`modelRoles.astra` is reachable only through the model switcher as a main\norchestrator role. The explicit Fable retry chain can also select Astra.\nNo subagent selects Astra automatically.\n\n`SoT/.omp/models.yml` declares the full `low, medium, high, xhigh, max` ladder\nwith `defaultLevel: xhigh` under\n`providers.openai-codex.modelOverrides.gpt-6.2-astra.thinking`.\nThe override stays as the kit's worked example of a provider ladder\nredefinition. The in-session thinking control can still select `low` for a\nquick answer. The block is keyed by model id, so it moved from `gpt-6-astra`\nto `gpt-6.2-astra` with the role. `ompRemovals.ts syncOmpModelRemovals`\nprunes the deployed `gpt-6-astra` block while it equals the shipped block, and\nkeeps a block that the user edited.\n\n- The bundled `scout` and `sonic` agents carry `model: \"@smol\"` and\n `thinking-level: medium` in their embedded frontmatter, so they run Luna,\n not Opus 5.5 or Astra. To move them, change `modelRoles.smol` or add a\n `task.agentModelOverrides` entry for the agent name.\n- The bundled `task` agent carries `model: \"@task\"` and\n `thinking-level: auto`. It resolves Opus 5.5 high. The `:high` suffix on\n `modelRoles.task` is an explicit level, so it outranks the agent's `auto`,\n and the auto classifier does not run for a `task` spawn.\n- `task.enableEffort` stays at omp's default `false`, so the task tool has no\n `effort` field and every spawn runs the level of its agent's role. When the\n field is on, a caller can pass `effort: lo`, `med`, or `hi`, and caller\n effort outranks the role suffix. omp maps it onto the model's own ladder,\n not onto level names: `lo` selects the lowest level, `med` the lower middle,\n and `hi` the highest (`resolveTaskEffortLevel` in omp's\n `packages/tui/src/thinking.ts`, omp 18.8.5). Then omp caps the result at\n `task.maxEffort`. Up to 0.23.0 the kit set that cap to `xhigh`. On the\n `low, medium, high, xhigh, max` ladder, `hi` then gave `xhigh`, so many\n `task` spawns ran Opus 5.5 xhigh despite the `:high` role suffix. On\n 2026-11-05, a fresh `omp -p` run on omp 18.16.0 with the field off had no\n `effort` field, and its `task` child recorded\n `resolvedModel: anthropic/claude-opus-5-5:high`.\n- Since 0.24.0 the kit sets no `task.maxEffort`, so the cap is omp's default\n `max`. With `task.enableEffort` off, the cap applies only to a per-call\n `model` with a `:level` suffix.\n- In the deployed config, `scout` and `sonic` run GPT-6 Luna `medium`. The\n four reviewer agents resolve `@reviewer` and run GPT-6.1 Terra `high` on the\n live tier of the main session. A `docks-kit omp` free session replaces\n both roles with its free model (see Free session launcher). A retry can\n fall back to the role's fallback chain, for the reviewers Opus 5.5 `high`.\n\nThe runtime per-agent measurement from fresh `omp -p` runs on 2026-09-09\npredates this change. It applies to the retired Astra-low `task` configuration,\nnot the current role map.\n\nOn 2026-11-18, omp 18.22.2 listed GPT-6.2 Astra with a 272,000-token context\nwindow. This is the `/extended-context off` window, and it equals the Codex\ndefault context. OpenAI lists a 1,050,000-token context and 922,000 maximum\ninput tokens. For GPT-6 Astra, `/extended-context on` used the 922k input\nwindow. The kit has not checked the window that `/extended-context on` gives\nfor GPT-6.2 Astra.\n\n## Free session launcher (`docks-kit omp`)\n\n`docks-kit omp [--model <selector>|--pick] [args...]` starts one interactive\nomp session with a configuration overlay that selects a free model. The\noverlay sets the 16 chat-model roles in `ompOverlay.ts ROLE_ORDER` to that\nmodel and empties the 12 retry fallback chains in `ompOverlay.ts\nFALLBACK_ORDER`. These roles include `memory`, `judge`, and `advisor`. The SoT\ndoes not set them, but omp otherwise uses its built-in priority chain for\n`memory` and `judge`, and that chain can name a paid model. omp resolves the\n`/advisor on` model from `modelRoles.advisor` before the `slow` role. A\ndeployed, user, or project `advisor` role could otherwise send it to a paid\nmodel. The overlay also empties the retry\nchains keyed by the free model: the bare selector, `<selector>:off`, and\n`<selector>:<level>` for every level in `ompOverlay.ts THINKING_LADDER`. omp\nuses a chain keyed by the model before a role chain, so a project or\n`PI_CONFIG_FILES` chain for the free model could otherwise reach a paid model.\nThe overlay does not set the `web` role or its retry chain. The deployed\nweb-search provider order therefore applies, and that order includes the paid\n`openai-codex/gpt-6-luna` entry. omp merges the overlay key by key. Each other\ndeployed retry chain, such as a `plan`, `slow`, or `designer` chain, therefore\nstays in the merged config. A retry of the free model does not reach such a\nchain, because omp uses the empty chain keyed by the free model first.\nThe overlay also sets `defaultThinkingLevel` and `task.maxEffort` to the\nsession level. For a model that publishes no thinking ladder, the overlay\nomits both keys. A value in the deployed config then applies, or else the omp\ndefault, which is `max` for `task.maxEffort`.\n\nThe launcher renders a run overlay to\n`~/.cache/docks-kit/omp-free-<model>-<digest>.yml` at mode 0600 and passes it\nthrough omp's repeatable `--config` flag. Each distinct model-and-level\ncombination gets its own file, because omp re-reads a changed overlay during\na live session, and a second launcher must not change the level of that\nsession. The name sanitizes the selector for the file system and appends a\ndigest of the rendered overlay. The digest covers the selector and the\nlevel, so two selectors that differ only in separator characters stay\napart. A session launch never reads or writes `~/.omp/agent/config.yml` or\n`models.yml`; only `--fast`, below, edits `config.yml`. It\nnever touches the SoT. The next plain `omp` run uses the paid configuration\nagain.\n\nThe launcher starts omp as\n`omp launch --config <overlay> --model <selector>[:<level>] [args...]`, where\n`[args...]` are the arguments after the launcher flags, in the same order.\n`docks-kit omp -p \"...\"` runs one prompt. `docks-kit omp --continue` resumes\nthe previous session. A bare `docks-kit omp` opens an interactive session.\n\n`launch` makes omp read every forwarded word as message text. So `docks-kit\nomp commit` sends `commit` to the free model as a prompt, and no omp\nsubcommand runs through the launcher. To run an omp subcommand such as\n`commit`, `bench`, or `search`, run `omp` directly. The explicit `--model`\noutranks the model that omp restores from a stored session. So `--continue`,\n`--resume`, and `autoResume` keep the free model and its level.\n\n### Model selection that the launcher controls\n\nThe overlay ranks above the deployed global and project configuration, and\nbelow runtime overrides and later overlay files. The launcher handles each\nknown input that can select a model above the overlay:\n\n- Forwarded model flags. The launcher rejects `--config`, `--model`,\n `--smol`, `--slow`, `--plan`, `--models`, `--provider`, `--prewalk-into`,\n and `--plan-yolo-into`, in the `--flag value` and the `--flag=value` form.\n It exits with code 2 and starts no omp process. It checks every forwarded\n argument, also after a `--`, because omp can read that `--` as the value of\n a flag such as `--api-key` and then read the next flag. The error names the\n flag and the recoveries. For a free model, put `--model <selector>` before\n the other arguments or use `--pick`. For a paid model, run `omp` directly.\n For another config file, list it in `PI_CONFIG_FILES`.\n- A restored session model. The explicit `--model` keeps the free model.\n- An omp subcommand. `launch` makes it message text.\n- The model environment variables `PI_SMOL_MODEL`, `PI_SLOW_MODEL`, and\n `PI_PLAN_MODEL`. The launcher sets each one to the overlay value of its\n role in the omp environment, and prints one warning for each exported value\n that it replaces. omp fills an unset or empty variable from its `.env`\n files, so the launcher sets the variables instead of removing them.\n- `PI_CONFIG_FILES`. The launcher appends the overlay path to the exported\n entries, so an `omp` that the bash tool of the session starts loads the\n overlay too. omp loads these files below `--config` overlays, so an exported\n entry still applies below the overlay. A `PI_CONFIG_FILES` value in an omp\n `.env` file does not apply in a launcher session, because the launcher\n always sets the variable.\n- The omp profile. The catalog check below covers every profile that the\n launch can select.\n\n### Model selection outside the launcher\n\nThese paths act after omp starts or outside the chat roles. The launcher does\nnot control them:\n\n- In-session selection. `Alt+M` (model hub), `Alt+P` (session-only picker),\n `/switch <selector>`, `/model`, and `/modelpreset` can select any catalog\n model. `/resume` and a session switch restore the model of the target\n session. A seance subagent runs on the models of its source session. An\n `Alt+M` assignment of the `default` role writes `modelRoles.default` to the\n deployed `~/.omp/agent/config.yml`, so later plain `omp` runs use it too.\n- The `web` role and its retry chain. By owner decision they keep the\n deployed web-search provider order, which can reach the paid\n `openai-codex/gpt-6-luna` entry.\n- The model-kind roles `image`, `speech`, and `dictation`. A chat model\n cannot serve them, so the overlay does not set them.\n- Extensions and hooks. `-e`, `--hook`, and `--plugin-dir` run arbitrary\n code, and that code can select any model.\n\nThese lists name the known paths. They are not a closed set.\n\nThe default model is `opencode-zen/muse-spark-1.3-contributor-free` (\"Muse\nSpark 1.3 Free\", 1,048,576-token context) at `xhigh`. `xhigh` is the ceiling\nof that model ladder: `minimal, low, medium, high, xhigh`. The paid\n`muse-spark-1.3` sibling also offers `max`. The free variant does not.\n\nThe level comes from the ladder of the chosen model, never from a fixed list.\nEvery role, `advisor` included, runs the same level. Under `--model`, that\nlevel is the ceiling of the ladder.\n\nFree ladders are not uniform. On 2026-09-11 the 26 free models published six\ndistinct ladders: 21 include `medium`, 3 stop at `low, high, max` or\n`high, max`, and 2 publish no ladder at all. A model without a ladder gets\nbare selectors with no `:level` suffix, because an invented level makes omp\nfail when the session starts.\n\nThe choice persists per machine in `~/.docks-kit/kit.db` (table\n`omp_session`). It survives across sessions. It is never\ncommitted. `--model <selector>` records one selector and derives the level\nfrom the catalog row. `--pick` opens an interactive wizard.\n\nThe picker lists only models the live `omp models --json` catalog reports at\nzero input and output cost with `pricingStatus` `free` or `unknown` (26\nentries on 2026-09-11). A zero-cost row with another status, such as\n`variable` or `included`, is billed outside the token price, so the picker\nleaves it out. The resulting overlay sets the 16 `ROLE_ORDER` roles to the\nchosen free model and empties the 12 `FALLBACK_ORDER` chains and the chains\nkeyed by that model. The `web` role, its chain, and each other deployed chain\nkeep the deployed values. The\ncatalog can advertise a free model that the account cannot call; omp reports\nthat provider error unchanged.\n\nAfter the model, the wizard asks about the thinking level. `ompOverlay.ts\nplanEffortChoice` decides whether the question applies, because omp accepts a\n`:level` suffix only for a level the chosen model publishes:\n\n- No ladder: the wizard asks nothing and the overlay omits every level.\n- One level: the wizard states that level and asks nothing.\n- Two or more levels: the wizard asks one question, the thinking level for\n every role. It lists the levels of the model from the highest down, so\n `Enter` keeps the highest level.\n\nThe launch line names the selector and the level, or the model default level\nfor a model without a ladder. It reports no separate advisor level.\n\nAn omp login is required. The kit owns no login flow. Every launch reads the\nlive free catalog of each candidate profile. A plain launch checks the\nremembered model, or the default model, against those catalogs. When the\nmodel is not there, the launcher stops before omp starts. The model can be\nrenamed, repriced, or on a provider that is not logged in. Without this\ncheck, omp silently starts the default model of the first logged-in\nprovider, which can be paid.\n\nEach omp profile has its own login and `models.yml`, so a selector can be\nfree in one profile and missing or paid in another. The candidate profiles\nare the profile of the environment (`OMP_PROFILE`, `PI_PROFILE`, or the\ndefault) and each forwarded `--profile <name>` or `--profile=<name>` value.\nThe launcher reads every forwarded argument, also after a `--`, because omp\ncan read that `--` as a flag value and then select a later profile. It runs\n`omp models --json` for the profile of the environment and\n`omp --profile <name> models --json` for each forwarded name. The session\nmodel must be free in every one of these catalogs. `--model` and `--pick`\nchoose from the catalog of the last forwarded profile, or of the profile of\nthe environment when the arguments name none. A `--profile` without a name\nstops the launcher before omp starts.\n\nWhen the catalog renames the free variant, change only the default selector\nconstant. Until then, a plain launch on that default stops with an error. A\nladder change needs no code change. Under `--model` the level is derived\nfrom the catalog row of the chosen model, and under `--pick` the user chooses\nit from the ladder that same row publishes. Refresh the recorded default\nand the ladder counts in these docs in the same commit.\n\n## OpenAI fast mode (`docks-kit omp --fast`)\n\n`docks-kit omp --fast` toggles `tier.openai` in the deployed\n`~/.omp/agent/config.yml` between `priority` and `none`, prints the old and new\nvalues, and exits without starting a session. `priority` is the tier omp's\n`/fast on` selects for OpenAI and OpenAI-Codex models. `--fast` over\n`ultrafast` selects `priority`. The kit ships no Ultrafast toggle: omp honors\n`ultrafast` for a Codex model only when its catalog `serviceTiers` lists it.\nThe omp 18.4.9 catalog listed none for GPT-6.1 Sol, Astra, or Luna. On\n2026-11-18, `omp models openai-codex --json` on omp 18.22.2 listed no\n`serviceTiers` for any `gpt-6` id, `gpt-6.2-sol` and `gpt-6.2-astra`\nincluded. The SoT does not declare `tier.openai`, so the additive sync merge\nkeeps the toggled value. New sessions read it; a running session changes\nthrough `/fast`.\n\nThe four review agents inherit the live tier of the main session\n(`task.agentServiceTierOverrides: inherit`). In a new session after\n`docks-kit omp --fast`, they run on `priority` when `tier.openai` is `priority`,\nand on standard processing when it is `none`. A running session keeps the tier\nit started with, so its reviewers do not follow a later toggle.\n\n`--fast` never changes the Anthropic tier. The SoT leaves `tier.anthropic` at\nomp's default `none`, so each session starts with it. In omp\n18.16.0, `/fast on` in a session whose current\nmodel is Anthropic sets `anthropic: priority` for that session. The reviewers\nthen inherit it, so their Opus 5.5 fallback also runs fast. omp has no\noverride value that inherits only the OpenAI tier. To keep Anthropic models\non normal processing, use `docks-kit omp --fast` and a new session, not\n`/fast` in an Opus session.\n\n## Maintenance\n\n- Refresh each per-level row from the rendered metric table of a release\n comparison page, for example\n `/models/comparisons/gpt-6-2-sol-vs-gpt-6-1-terra` and\n `/models/comparisons/gpt-6-2-astra-vs-gpt-6-2-sol`. Each page shows every\n level of both models. Take tokens per task and index tokens from the data\n of the model page, for example `/models/gpt-6-2-sol`, and check that its\n other values match the rendered table. A model-page chart holds only about\n 20 models, so a value missing there does not mean that AA has not measured\n it.\n- On 2026-11-18, the per-level pattern\n `/models/comparisons/<level-slug>-vs-gpt-5-6-sol-high` returned HTTP 404. A\n comparison with a model that AA marks deprecated also returned HTTP 404, for\n example `gpt-6-1-sol`, `gpt-6-astra`, or `gpt-5-6-sol`. Read such a model\n from the data of its model page.\n- Keep AA rows at `high` and `xhigh` at least for each model that an omp role\n or retry chain uses, with the index version and the capture date (see AA\n rows for each role model). Add the missing rows in the same commit as a\n role or chain change.\n- After a role or chain change, run `omp models openai-codex` and check that\n it lists every `openai-codex` id that the roles and chains name. Sync does\n not check the omp catalog.\n- Refresh the Coding Agent Index from `/agents/coding-agents`.\n- Record the index version with the numbers. AA changes index composition\n between versions, so a score from another version is not a comparison.\n- Update the capture date in the same commit as any number.\n- Verify Astra ladder changes in `SoT/.omp/models.yml` through the model\n switcher and in-session thinking control.\n- The kit leaves `task.maxEffort` and `task.enableEffort` at omp's defaults,\n `max` and `false`. After an omp update, check both in\n `omp config list --json`. Verify a kit change to either key with a fresh\n `omp -p` spawn per bundled agent.\n";var omp_context_default=`# omp context and compaction
|
|
24370
24383
|
|
|
24371
24384
|
This topic records why \`SoT/.omp/config.yml\` ships no compaction threshold,
|
|
24372
24385
|
and what omp's reserve-based default computes on each model lane. It also
|
|
@@ -24559,10 +24572,10 @@ work with \`github.enabled: false\`. The plan-lifecycle work reads issues with
|
|
|
24559
24572
|
- The model roles, \`cycleOrder\`, \`retry.fallbackChains\`, \`modelTags\`, the
|
|
24560
24573
|
reviewer overrides in \`task.agentModelOverrides\` and
|
|
24561
24574
|
\`task.agentServiceTierOverrides\`, and the \`bash.patterns\` guards.
|
|
24562
|
-
`;var command_guards_default="# Command guards\n\nThe kit ships one destructive-command policy to omp.\nThe short rule for agents: **to remove, use the trash**. Run\n`gio trash -- <path>` on Linux or `trash <path>` on macOS. Remove a\ntemporary file or directory with `docks-kit scratch remove <path>` instead.\nTo remove a path from the git index, run `git rm -- <path>`.\n\nThe policy keeps only deny rules. Where omp's critical-command check acts,\nthe form is denied. omp also denies a `$` or a backtick after `git push`,\nbecause the agent can always write the ref literally.\n\nBy owner decision (0.22.8, DocksDocks/public#126), the kit ships no omp\nprompt rule. The kit's `bash.patterns` holds only deny rules and the `trash *`\nallow. Under omp's default `tools.approvalMode: yolo`, omp runs every\ncommand that no deny matches without a question, in the main session and in\nsubagents. This includes any `rm` that omp does not deny, `git clean`,\n`git reset --hard`, a force push that no deny matches, and a git command\nthat skips the repository's hooks. A prompt rule that the user adds to\n`~/.omp/agent/config.yml` survives sync and still asks; a subagent rejects\nit. The kit omp plugin trigger rule `git-safety.md` forbids these options with\n`git push` and `git rm`: `-f`, a flag cluster that holds `f`, and a long\noption that starts with `--f`. `git push --follow-tags` is correct. The rule\nalso forbids `git push origin +<ref>`, `git push --mirror`,\n`git push --prune`, and each hook skip. It tells the agent to ask before a\nbulk discard in the main session, for example `git clean` without `-n`,\n`git reset --hard`, `git checkout .`, or `git stash clear`.\nA subagent does not run a bulk discard and names it in its report. The omp\nagent prompt lists a force push as a step that needs `ask`. The section\n\"omp trigger rules\" below describes these rules.\n\nThe policy sorts shell commands into two tiers.\n\n- **Deny**: the command never runs, and nobody can approve it in the session.\n- **Allow**: the agent may run the command alone. A command that no rule\n matches runs too. The table below calls this `run`.\n\nA prompt rule that the user adds asks a person in the main session, and a\nsubagent rejects it.\n\nThe omp `eval` tool stays unrestricted: `bash.patterns` does not gate a shell\nthat `eval` starts.\n\n## Tiers\n\n| Command | omp `bash.patterns` |\n| --- | --- |\n| `rm` of `/`, `~`, `~/`, `$HOME`, `${HOME}`, quoted or with a trailing `/` | deny |\n| `rm` of `/*` | deny with an `r` or `f` option; plain `rm /*` runs |\n| `HOME=...`, `export HOME=...`, `env HOME=...` | deny |\n| `sudo` before `rm`, plain or by path (`/usr/bin/sudo`) | deny |\n| `git push --force` or `-f` to `origin main` or `origin master` | deny |\n| Recursive `rm` (`-r`, `-R`, `-rf`, `-fr`, `-rfv`, `-ri`, `-ir`, `-Ri`, `-iR`, `--recursive`, other listed clusters) | deny, also behind any prefix (`env`, `xargs`, `nice`, `find -exec`, `git rm -r`) |\n| `rm` with an `r` or `f` option before an absolute path, `--no-preserve-root` | deny |\n| Any other `rm`: one file, several files, a glob, `-f` | run |\n| `find ... -delete`, `find ... -exec rm` (also `-execdir`, `-ok`, `-okdir`), `xargs rm` | deny, in every position and by path |\n| `git clean`, `git reset --hard` | run |\n| `git push` that could force: see below | run, unless a deny above matches |\n| A `$` or a backtick anywhere after `git push` in the same command | deny, also after a shell keyword, a wrapper, or a path before `git`: see below |\n| A git command that skips the repository's hooks: see below | run |\n| `git rm -- <path>`, `git worktree remove -- <path>` | run |\n| `git worktree remove --force -- <path>` | run; the omp `file-removal.md` trigger rule fires on each `--force`, `-f`, or `--f` form and permits it once, after the commits are on the remote |\n| `docks-kit scratch remove <path>` | run; the command removes only a path inside the scratch root, the system temporary directory, or `/var/tmp` |\n| Any other non-recursive `git rm` or `git worktree remove` | run |\n| `gio trash -- <path>` | run |\n| Any other `gio trash` | run |\n| `trash <path>` (macOS) | allow |\n\nomp runs each of these `git push` forms, which can force. Its force-push deny\nmatches only `git push --force` or `git push -f` directly before\n`origin main` or `origin master`:\n\n- a `+` refspec;\n- any long option that starts with `--f`, such as `--force`,\n `--force-with-lease`, or an abbreviation like `--for`;\n- `--mirror` or an abbreviation of it;\n- `-f`, or a short-option cluster that starts with two of git push's\n no-argument flags (`v`, `q`, `d`, `n`, `u`, `4`, `6`, `f`), such as `-vf`,\n `-vvf`, or `-uvfq`;\n- a word that starts with `$`, a backtick, a quote, or a backslash. omp\n denies a `$` or a backtick anywhere after `git push`.\n\nEach of these must begin a word: `feat/cache-vf` is a branch name, not an\noption.\n\nA `$` or a backtick hides the ref until the shell expands it, so the matcher\ncannot tell `$b` from `+main` or `--force`. An unquoted value inside a word\nalso splits into more words: with `b=\"main --force\"`, `HEAD:$b` becomes\n`HEAD:main --force`. omp never applies an allow rule to a command that holds a\n`$` that the shell expands. So the kit cannot add an exception for a plain\nbranch name.\n\nomp therefore denies a `$` or a backtick anywhere after `git push` in the same\ncommand. The agent reads a refusal such as\n`Blocked by bash pattern: *git push *$*`, writes the ref literally, and runs\nthe push without a question. The omp `git-safety.md` trigger rule names the\nliteral forms: `git push -u origin HEAD` for the current branch, and\n`git push origin --delete <branch-a> <branch-b>` for several branches. The two\nomp deny rules start with `*`. So a shell keyword such as `do` in a loop, a\nwrapper such as `env`, or a path such as `/usr/bin/git` does not hide the\npush.\n\n## Commands that skip the repository's hooks\n\nA git command can skip the repository's hooks, for example with\n`--no-verify`, `git commit -n`, `git am -n`, or a `core.hooksPath` change.\nThe kit ships no omp `bash.patterns` rule for these commands, so omp does not\nblock them. The omp `git-safety.md` trigger rule forbids each hook skip.\n\n## How an agent removes files\n\n1. Remove a temporary file or directory with the `scratch_remove` tool or\n `docks-kit scratch remove <path>`. The command removes only a path inside\n the scratch root, the system temporary directory, or `/var/tmp`.\n `gio trash` does not trash on a system internal mount, such as a `tmpfs`\n `/tmp`.\n2. Move every other file or directory to the trash with `gio trash -- <path>`\n on Linux or `trash <path>` on macOS. The `--` ends option parsing, so `gio`\n reads every later argument as a path, and a path such as `--empty` cannot\n empty the trash.\n3. To remove a path from the git index, run `git rm -- <path>`. To remove a\n worktree, run `git worktree remove -- <path>`. When git refuses because the\n worktree has changes, the agent may pass `--force` once, after each commit\n is on the remote and `git status --porcelain` lists only generated files.\n Never pass `--force` two times.\n4. Do not use `rm`. omp denies a recursive `rm`, `find -delete`,\n `find -exec rm`, and `xargs rm`. It runs any other `rm` without a prompt.\n5. For a recursive or bulk deletion, ask the user in the main session. A\n subagent lists the paths in its final report. The user runs a recursive\n deletion by hand.\n6. Write literal absolute paths. Never use `~` or `$HOME`, and never set or\n export `HOME`.\n\nThe kit plugin trigger rules `file-removal.md` and `literal-paths.md` carry\nthese rules.\n\n### What the git removals keep\n\n- `git rm` without `--force` refuses a file whose content differs from the\n last commit. The removed content stays in the repository history.\n- `git worktree remove` without `--force` refuses a worktree with untracked\n files or tracked changes. It does delete the files that `.gitignore` covers,\n such as `node_modules`, build output, or a local `.env`. Git keeps no copy of\n those files.\n- Git accepts an abbreviated long option, such as `--for` for `--force`, and a\n short-option cluster, such as `-rff`. After `--`, git reads every argument as\n a path. So the `--` form is the only one that cannot force.\n\n## omp trigger rules\n\nomp loads `~/.omp/agent/AGENTS.md` only into main sessions and advisors,\nnever into task subagents (`omp://context-files.md`). So the kit puts the omp\ncommand rules into six Time Traveling Stream Rules (TTSR, trigger rules). The\nkit plugin `docks-kit-omp` ships them in `SoT/.omp/plugin/rules/`. Sync\nmaterializes the plugin to `~/.docks-kit/omp-plugin` and links it. omp's\n`omp-plugins` provider loads `rules/*.md` from the linked plugin root. Each\nrule has the scope `tool:bash, tool:eval`, because eval code can run a shell\ncommand through `sh()`.\n\n| Rule | Scope | Correct form that the rule teaches |\n| --- | --- | --- |\n| `file-removal.md` | `tool:bash`, `tool:eval` | `scratch_remove` or `docks-kit scratch remove <path>` for a temporary path; `gio trash -- <path>` or `trash <path>` for another path; no `rm`, `unlink`, or `shred`, also after a `VAR=value` prefix; `git rm -- <path>`; for a folder, `git rm -- '<dir>/*'` or `git rm --cached -- '<dir>/*'`, because omp denies `git rm -r`; `git worktree remove -- <path>`, and `--force` only after the commit and status checks; no deletion through `eval` |\n| `git-safety.md` | `tool:bash`, `tool:eval` | no hook skip, also through an abbreviation such as `--no-veri`; no `-f`, `f` cluster, or `--f` long option with `git push` or `git rm` (`--follow-tags` is correct); no `+<ref>` with `git push` (`git push origin +<ref>` is a force push); no `git push --mirror` or `--prune`; a literal push ref; `git push` as its own command, not chained with `&&`, `\\|\\|`, or `;`; `git push -u origin HEAD`; `git push origin --delete <branch-a> <branch-b>`; `git branch -d <branch>`, not `-D` or `-d --force`; `git restore -- <path>`; an ask before `git clean` without `-n` or `--dry-run` before ` -- `, `git reset --hard`, `git checkout .`, `git restore .` (`git restore --staged .` only unstages and is correct), `git stash drop`, or `git stash clear`. The git global options `-C`, `-c`, `-p`, `-P`, and `--<option>` do not hide the subcommand. A word after ` -- ` is a path, not an option |\n| `temp-and-background.md` | `tool:bash`, `tool:eval` | `scratch_new` or `docks-kit scratch new <label>` instead of `/tmp`; a server or watcher only as a named bash service or an async job; no `nohup`, `setsid`, `disown`, `tmux`, or `screen`, also after a `VAR=value` prefix; no global install (`npm`, `bun`, `pnpm`, `yarn`, `pipx`, `cargo`, `go install`, `gem install`, `uv tool install`), scheduled job, or enabled service; no Docker cleanup of a resource that the agent did not create |\n| `worktree-location.md` | `tool:bash`, `tool:eval` | a worktree only at the literal absolute path `<data>/agent-worktrees/<repository>/<name>`, with `agent-worktrees` as a whole directory name. The rule fires on each `git worktree add`, also at the correct path, because a condition cannot read `$XDG_DATA_HOME` or the home directory of the user. The retry after the reminder runs |\n| `literal-paths.md` | `tool:bash`, `tool:eval` | a literal absolute path; no `~` or `$HOME`; no `HOME` assignment |\n| `remote-cleanup.md` | `tool:bash`, `tool:eval` | a remote cleanup only on a non-production target; an `ask` immediately before a production cleanup, which must be rare. Remote means SSH, `rsync --delete` to a `host:` target, `rclone` (`delete` verbs, and `sync` to a `remote:` target), `gh` (`gh <noun> delete`, `gh <noun> <x>-delete`, and `gh api -X DELETE`), a remote `docker` or `podman` (also `docker -c <context>`), a database client (`DROP TABLE`, `DATABASE`, or `SCHEMA` in `psql`, `mysql`, `sqlite3`, or `mongosh`; `dropdb`; `redis-cli FLUSHALL` or `FLUSHDB`), or a provider CLI with a cleanup verb, such as `aws s3 rb` or `neonctl branches delete` |\n\nEach rule has a regex `condition` that aims at the wrong form. When the\nmodel streams a matching tool call, omp aborts the call before it runs,\ninjects the rule body, and retries (`omp://ttsr-injection-lifecycle.md`). A\nrule costs no prompt tokens until it fires, and it reaches subagents too. The\ntrigger rules teach the correct form. The `bash.patterns` denies do not\nchange, and they still enforce. Each rule has `repeatMode: always`, so it\nfires at each later wrong form in the session too. The retry that its own\nreminder starts does not fire it again, so a correct command still runs.\n\nAfter a session resume, omp restores each injected rule at message count\nzero. So a rule that fired before the resume does not fire in the first turn\nafter the resume (section 7 of\n[ttsr-injection-lifecycle.md](https://github.com/can1357/oh-my-pi/blob/main/docs/ttsr-injection-lifecycle.md)).\nNo repeat mode changes this. The `bash.patterns` denies and the main-session\n`ask` rules still apply in that turn.\n\nA condition reads text, not a parsed shell command. So these correct calls\nalso fire a rule:\n\n- A quoted command word, such as `echo \"rm x\"` or a commit message that\n starts with `rm`, fires `file-removal.md`.\n- In eval code, a scan can continue past the closing quote of the `sh()`\n string to the end of the statement. For example,\n `print(sh(\"kubectl get pods\"), \"pods to delete\")` fires `remote-cleanup.md`.\n\nomp tests each condition on the partial tool-call buffer after each streamed\ndelta, and again on the full arguments at the end of the call\n(`omp://ttsr-injection-lifecycle.md`). So a condition must not match a prefix\nof a correct command. Each condition must require a delimiter after the token\nthat it checks, and no condition uses the end anchor `$` as that delimiter.\nA negative lookahead, such as `(?!ol)` in `--f(?!ol)`, passes at the end of\na partial buffer. So after a negative lookahead, the condition must read the\ntoken to its delimiter. `git clean` and `git restore .` read the full\ncommand before they decide, because `-n` or `--staged` can come last.\n\nThe buffer is the argument JSON text, and omp's schema puts the intent field\n`i` before `command`. A call can also put `i` after `command`, and a provider\ncan stream JSON with white space, such as `{\"command\": \"ls\"}`. Each condition\nstarts its match with the forward key prefix, after an optional inline flag\ngroup:\n\n```text\n\"(?:command|code)\"\\s*:\\s*\"[^\"\\\\]*?(?:\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?)*?(?:\\\\.[^\"\\\\]*?){0,7}?\n```\n\nThe prefix matches the `command` or `code` key, with or without JSON white\nspace around the colon. Then it walks the string body forward and steps over\none escape pair, such as `\\\"` or `\\\\`, as one unit. Each loop step takes up to\n8 escape pairs. So the JavaScriptCore regex JIT handles about 8 times more\nescapes before it falls back to its slower interpreter. The walk never passes\nan unescaped `\"`, so the key prefix starts at the key and stays inside that\nstring. Only the prefix gives this guarantee. A scan stops at an unescaped\n`\"`, which ends the command string, and at a newline (`\\n`), which ends the\ncommand line. So the intent text and the next line do not fire a rule. A\nknown limit: a part of a condition that is not such a scan, such as\n`[^)]*`, can cross the closing quote, and the match then continues into a\nlater field. For example, the `Bun.file` condition of `file-removal.md`\nmatches `{\"code\":\"Bun.file(\",\"i\":\").delete(\"}`. A tab in a command is `\\t` in\nthe buffer, so each condition reads `\\t` as shell white space, as it reads a\nspace. A scan that looks for an option also stops at a ` -- ` word, also with\na tab, because each later word is a path. So `git clean -fd -- -n` fires, and\n`git rm -- -f` stays quiet. In the `git push` conditions for `$`, a backtick,\nand a chain, a scan also stops at `)` and at a backtick, which end a\nJavaScript `` sh`\u2026` `` or `sh(\"\u2026\")` call. A backtick counts as a command\nsubstitution only when a word follows it.\nomp's `Matched:` excerpt is a bounded window around the match start, not the\nfull match (`packages/coding-agent/src/export/ttsr.ts` in omp 19.0.0). The\nwindow starts up to 60 characters before the match start, so it can show the\nend of the intent field. omp keeps at most 120 characters of the match and\nup to 60 characters after them. So a long match is cut at 180 characters from\nits start. omp replaces each white space run with one space and marks a cut\nend with `\u2026`. In a long call, the trigger can be more than 180 characters\nafter the key, and then the trigger is outside the excerpt.\n\nomp 19.0.0 tests every condition on the whole buffer at each streamed delta,\non its main thread, in JavaScriptCore. From 0.22.24 to 0.22.29, each\ncondition started with a variable-length lookbehind over the key and the\nstring body. A leading unbounded lookbehind walks back over the buffer from\nevery position. On a 20 KB tool call, one scan took seconds and froze the omp\nsession. Past JavaScriptCore's match limit, the scan also reported no match,\nso the rule did not fire.\n\nA forward key prefix alone does not make a condition linear. Three input\nfamilies can still make a scan slow:\n\n- A dense line: one long line that repeats a command start, such as\n `git restore `. If the scan of each command start runs to the end of the\n line, the time grows with the square of the line length.\n- A head and a run: one command start, such as `aws `, and then one long run,\n such as `x x x`. A group loop inside a lookaround makes JavaScriptCore keep\n each loop step until the match attempt ends. The regex then drops out of\n the JIT. One `remote-cleanup.md` condition took 0.9 ms at 16 KB and 82 ms at\n 64 KB.\n- An open buffer: the buffer stops before the closing quote of the command.\n omp tests the buffer after each streamed delta, so most real scans see no\n closing quote, and a scan cannot use it as a stop.\n\nA command start inside the option region of an earlier command start, and\ntext with many escapes, need care too. So each condition has this form:\n\n- The match starts at the forward key prefix.\n- Each scan after a command start is one lazy walk that stops at its first\n event: `(?=(?<w>[\\s\\S]*?)(?=EVENT)BOUNDARY)\\k<w>`. The events are the flag\n that the condition looks for, a terminator, the end of the run, and the\n next command start. A lookahead in JavaScript does not backtrack after it\n matches, so `\\k<w>` consumes the walk as one frozen piece.\n- An event counts only at a real token boundary: no odd run of backslashes\n comes before it.\n- A scan stops at a later command start, because the scan of that command\n start reads the same remaining text. So two scans never read the same\n text, and a dense line costs linear time.\n- Some conditions find the flag first and then walk back once to the head of\n the command. Their head allows wrapper words, such as `sudo` or `env`, or\n `KEY=value` words before the command, as in `LC_ALL=C rm`.\n\nThe rewrite gives the same result as the rules of 0.22.29 on each input that\nthe checks tried. The checks are the 2697 rows of the test table, a fuzz run\nof 5 times 310,825 buffers on all 69 conditions, and an enumeration of every\ntoken sequence of up to 6 or 7 tokens for each condition. The enumeration\nused closed and open buffers. No result changed, and no match was lost or\nadded.\n\nWrite each new condition by these rules:\n\n- Start the match with the forward key prefix. Never start a condition with\n an unbounded lookbehind.\n- Make each scan one frozen walk that stops at its first event and at the\n next command start.\n- Never put a group loop inside a lookaround over text of unbounded length.\n- Run `bunx vitest run cli/test/unit/ompTriggerRules.test.ts`. It runs the\n shape guard and the Bun backstop.\n- When you rewrite a condition, run the old and the new condition on each\n buffer of the test table, and make sure that both give the same result.\n\n`cli/test/unit/ompTriggerRules.test.ts` runs each shell row through bash,\nPython `sh(\"\u2026\")`, JavaScript `` sh`\u2026` ``, and JavaScript `sh(\"\u2026\");`. It runs\nevery row in the compact JSON layout (`{\"command\":\"ls\"}`) and in the spaced\nlayout (`{\"command\": \"ls\"}`), and some rows in the pretty layout, with a\nnewline and an indent. Other rows put trigger words in the intent field,\nbefore or after the command, or put a tab in the command. The test checks\nthat each correct form stays quiet on each prefix, that each condition has a\nwrong row that fires it, and that each rule has `repeatMode: always`.\n\nIts shape guard checks only what a static check can prove. Each condition\nmust start with the forward key prefix, and this rejects the leading\nlookbehind that froze omp. No `|` can stand outside every group, because the\nalternative after it needs no key prefix. The shape guard cannot prove\nlinear time. The backstop tests the measured input families for linear\ntime: the test runs `cli/test/lib/ompTriggerBackstop.ts` under Bun, because\nthe unit tests run on V8, which does not show the JavaScriptCore cost. A\ncondition can still backtrack on a run that no generator holds, so a new\ncondition needs a new family when its shape is new. The backstop has these\nchecks:\n\n- Time budget, with the regex JIT on: one pass of all conditions over a\n 20 KB Python cell, a 20 KB bash command, and a 30 KB `KEY=value` chain\n stays under 250 ms for each buffer.\n- Fire, with the regex JIT on: `git reset --hard` at the end of the 20 KB\n cell fires `git-safety.md`.\n- Scaling, with the regex JIT off: each condition alone, on each adversarial\n input shape, at 16 KB and 64 KB.\n- Dense and head-and-run scaling, with the regex JIT on: each condition\n alone, on the two families above, at 16 KB and 64 KB. Each line goes into a\n bash command, an open bash command without its closing quote, and a Python\n `sh(\"\u2026\")` cell.\n\nIn each scaling check, the 64 KB time must stay at most 8 times the 16 KB\ntime plus 15 ms, and at most 100 ms. The backstop times the pairs in parallel\nchild processes first. Each pair that fails there gets a second, serial run,\nand it fails only when it fails there too. A call of 1000 ms or more fails at\nonce.\n\n## Why omp denies instead of asking\n\nomp has a built-in check for critical commands. For example, it flags:\n\n- an `rm` with an `r` or `f` option before an absolute path;\n- `sudo rm`, also when `sudo` is called by its path.\n\nomp 19.0.0 checks deny and prompt rules first, then its critical patterns, then\nallow rules. A critical command that no deny or prompt rule matches gets a bare\nsafety override, which also replaces a matching allow. Under omp's default\n`tools.approvalMode: yolo`, omp ignores a bare override, so the command runs.\nThis applies in subagents too. A prompt rule would ask a person in the main\nsession, but a subagent rejects every prompt, so the kit ships none. Only a\ndeny rule stops a critical command in every session (`BashTool.approval` in\nthe v19.0.0 source).\n\nThe kit therefore denies every `rm` shape that the check can flag:\n\n- a recursive `rm`;\n- an `rm` with an option that holds `r` or `f` before an absolute path;\n- `sudo` anywhere before `rm`;\n- `--no-preserve-root`.\n\nThe kit also denies bulk removal through `find -delete`, `find -exec rm`, and\n`xargs rm`. omp's critical check does not flag these forms, but they can empty\nthe home directory, and no glob can express \"inside the temporary directory\".\n`docks-kit scratch remove` checks the path in code instead.\n\n## Matching rules\n\n- For a simple command, the rules are ordered, and the first match wins.\n- `*` matches any text, spaces included, and no escape spells a literal `*`.\n- Deny rules test the whole line and each segment between `;`, `&&`, `|`,\n and similar operators, with quotes and escapes removed. So\n `rm -rf \"$HOME\"` matches `rm * $HOME`. A segment also matches without its\n leading `NAME=value` words.\n- For a line with shell control, each segment takes its first matching deny\n or prompt rule. A deny chosen for one segment wins over a prompt chosen\n for another segment; within one segment, a prompt rule that comes first\n wins over a later deny.\n- Allow rules apply only to a simple command.\n- The kit ships no prompt rule. It lists rules as deny, then the `trash *`\n allow.\n\n## Gaps\n\n- **omp, literal `*`**: omp cannot match a literal `*`, so it cannot tell a\n glob from a file name. The kit therefore runs every `rm` that it does not\n deny without a prompt. This includes `rm ~/*`, `rm $HOME/*`, and `rm /*`\n without an `r` or `f` option, because a deny rule for them would also deny\n `rm ~/notes.txt` (owner decision, 0.20.9).\n- **omp, whole-line matching**: omp tests deny rules against the whole command\n line too, so a pattern can span commands. For example, `rm x && cd ~`,\n `rm -i a && ls -R /tmp`, and `sudo apt update && rm x` are denied. Run `rm`\n as its own command. In the same way, a `$` or a backtick after `git push`\n denies the whole command, such as `git push origin HEAD && echo $?`. omp\n joins the lines of a command first, so `echo $?` on a later line is denied\n too. Run `git push` as its own command.\n- **omp, text arguments**: the critical-shape deny also matches text such as\n `git commit -m \"rm -f /tmp/x\"`. The `git push` deny matches text that names\n `git push` before a `$`, such as `git commit -m \"git push $b fails\"`. Write\n such a message with `git commit -F`.\n- **omp, prefixed `rm`**: the kit denies a recursive `rm` behind any prefix,\n such as `env X=1 rm -rf b`, `xargs rm -rf`, `find . -exec rm -rf {} +`, or\n `git rm -r dir`. A `* rm ` rule also matches text, so a line such as\n `echo do not rm -rf b` is denied too.\n- **omp, bulk-removal text**: the `* find *-delete*`, `*-exec rm *`, and\n `*xargs rm` rules also match text, so a line such as\n `echo use find with -delete` is denied. Write such text to a file instead.\n- **omp, recursive `rm` clusters**: omp matches only the listed\n recursive-`rm` clusters: `r` or `R` alone or with `f` and `v`, plus `-ri`,\n `-ir`, `-Ri`, and `-iR`. Another cluster runs.\n- **`git push` beyond the listed words**: a configured `+` refspec in\n `remote.<name>.push` makes a plain `git push` force. No rule sees git\n configuration. `git push --delete` and `git push --prune` remove remote\n branches without force; no kit rule asks for them.\n- **omp, force push to `main` in another spelling**: the force-push deny\n rules match only `git push --force` or `git push -f`, then\n `origin main` or `origin master`. Every other force push to `main` runs\n without a question, such as `git push origin main --force`,\n `git push -vf origin main`, `git push --force-with-lease origin main`,\n `git push origin +main`, `git push -f origin HEAD:main`, or\n `git push --mirror origin`. Until 0.22.8 these forms asked.\n- **omp, force push after a prefix**: the force-push deny rules start with\n `git push`, not `*`. So a force push to `origin main` after a shell keyword,\n a wrapper, or a path runs without a check, such as\n `for r in a; do git push --force origin main; done`,\n `env git push --force origin main`, or `/usr/bin/git push --force origin main`.\n- **`git -C`**: no rule matches a git subcommand that does not follow `git`\n directly, such as `git -C . push --force origin main` or\n `git -C . push origin $b`.\n- **Programs that remove files**: no rule covers a program that removes files\n itself, such as a Python or Node script, or a shell started by omp `eval`.\n\n### How `gio trash` empties the trash\n\nGLib's `gio trash` handles operands first. With at least one path, it trashes\nor restores the paths, and `--empty` has no effect. Without a path, it empties\nthe trash when `--empty` is set. `-f` can repeat. So `gio trash -ff --empty`\nempties the trash, while `gio trash build --empty` only trashes `build`.\n\nomp runs every `gio trash` without a prompt.\n\n## Sync behavior\n\n- The config merge keeps user `bash.patterns` rules and groups all rules in\n this order:\n 1. kit deny;\n 2. user deny;\n 3. user prompt;\n 4. kit prompt (the kit ships none since 0.22.8);\n 5. the other user rules;\n 6. kit allow.\n- A user deny or prompt thus precedes every kit allow, and no allow can\n loosen a deny or a prompt.\n- A repeat sync changes nothing.\n- After the merge, `ompRemovals.ts syncOmpRemovals, retired bash-rule\n inventory` removes the retired kit rules in `OMP_RETIRED_BASH_RULES` from\n the deployed `bash.patterns` on every sync. The inventory also holds the\n 492 prompt rules that the kit retired in 0.22.8. It removes a rule only\n when its `match` and `approval` equal a retired pair, so a different user\n rule stays.\n\n## Check the deployed rules\n\nThe check below is safe, because the shell never reaches `rm`.\n\nAsk the agent to run `true || rm -rf \"$HOME\"`. The `true ||` short-circuit\nstops the shell before `rm`. omp reports\n`Blocked by bash pattern: rm * $HOME`.\n\n## Sources\n\n- omp: `omp://tools/bash.md`, `omp://approval-mode.md`, and the\n `@oh-my-pi/pi-coding-agent` 19.0.0 source `src/tools/bash.ts`\n (`CRITICAL_BASH_PATTERNS`, `BashTool.approval`). `omp://approval-mode.md`\n still describes the 18.17.0 order; the source is what runs.\n- GLib `gio trash`: https://github.com/GNOME/glib/blob/main/gio/gio-tool-trash.c\n- Git: https://git-scm.com/docs/gitcli (abbreviated and clustered options),\n https://git-scm.com/docs/git-rm, https://git-scm.com/docs/git-worktree,\n https://github.com/git/git/blob/master/builtin/push.c (short options), and\n https://github.com/git/git/blob/master/builtin/worktree.c\n (`remove_worktree` parses `--`; `check_clean_worktree` runs\n `git status --porcelain` without `--ignored`).\n- Git hooks: https://git-scm.com/docs/githooks (`--no-verify`,\n `core.hooksPath`), https://git-scm.com/docs/git-commit and\n https://git-scm.com/docs/git-am (`-n`).\n- macOS `trash`: https://keith.github.io/xcode-man-pages/trash.8.html\n";var TOPICS={overview:{summary:"What docks-kit is and how the pieces fit",body:overview_default},"sync-layers":{summary:"How sync deploys the omp SoT, and its additive-by-default semantics",body:sync_layers_default},flags:{summary:"Full flag reference",body:flags_default},toolchain:{summary:"Verified-version floors, the doctor table, and the upstream outdated report",body:toolchain_default},install:{summary:"Install paths: repo checkout, bun add -g, POSIX/Windows installers",body:install_default},platforms:{summary:"Platform support: Linux on x64 and arm64, macOS on arm64, Windows on x64",body:platforms_default},"omp-models":{summary:"omp role map and the Artificial Analysis snapshot behind it",body:omp_models_default},"omp-context":{summary:"omp compaction trigger, the reserve-based default, and context-window lanes",body:omp_context_default},"command-guards":{summary:"Deny and allow rules for destructive shell commands in omp",body:command_guards_default}},topic=String9("topic").pipe(withDescription2(`One of: ${Object.keys(TOPICS).join(", ")}`),optional4),json=Boolean6("json").pipe(withDescription3("List topics as JSON"),withDefault4(!1)),docsCommand=make20("docs",{topic,json},(config)=>gen2(function*(){let requested=getOrUndefined(config.topic);if(requested===void 0){if(config.json)return yield*log(JSON.stringify(Object.entries(TOPICS).map(([name,t])=>({name,summary:t.summary})),null,2));yield*log(`docks-kit documentation topics (docks-kit docs <topic>):
|
|
24563
|
-
`);for(let[name,t]of Object.entries(TOPICS))yield*log(` ${name.padEnd(14)} ${t.summary}`);return}let entry=Object.hasOwn(TOPICS,requested)?TOPICS[requested]:void 0;if(entry===void 0)return yield*bail(`Unknown topic '${requested}'. Valid: ${Object.keys(TOPICS).join(", ")}`);yield*log(entry.body)})).pipe(withDescription4("Self-documentation: the kit's concepts as readable topics, bundled with the CLI \u2014 a fresh agent can learn the kit from here alone."));import{existsSync as existsSync9}from"fs";import{join as join9}from"path";var updateNudge=(logger)=>{try{let home=kitHome();if(!existsSync9(join9(home,".git")))return;if(spawnHost("git",["-C",home,"fetch","--quiet"],{stdio:"ignore",timeout:4000}).status!==0)return;let res=spawnHost("git",["-C",home,"rev-list","--count","HEAD..@{u}"],{stdio:["ignore","pipe","ignore"]}),behind=(res.stdout??"").trim();if(res.status===0&&behind!==""&&behind!=="0")logger.warn(`kit checkout is ${behind} commit(s) behind its upstream \u2014 run: docks-kit update`)}catch{}},dryRun=Boolean6("dry-run").pipe(withDescription3("Preview without applying"),withDefault4(!1)),skipPluginRefresh=Boolean6("skip-plugin-refresh").pipe(withDescription3("Install missing plugins but skip refresh-only updates for existing plugins"),withDefault4(!1)),verbose=Boolean6("verbose").pipe(withAlias2("v"),withDescription3("Also print no-op confirmations (already in sync, up to date, left as-is)"),withDefault4(!1)),syncCommand=make20("sync",{dryRun,skipPluginRefresh,verbose},(config)=>gen2(function*(){let args=["sync"];if(config.dryRun)args.push("--dry-run");if(config.skipPluginRefresh)args.push("--skip-plugin-refresh");if(config.verbose)args.push("--verbose");if(!config.dryRun){let logger=yield*LoggerService;yield*sync2(()=>updateNudge(logger))}yield*engine(args)})).pipe(withDescription4("Deploy the SoT to this machine with EngineNative."));var MANAGED=["bun"],op=String9("op").pipe(withDescription2("check (default) | ensure <tool> | outdated"),optional4),tool=String9("tool").pipe(withDescription2(`Managed tool for ensure: ${MANAGED.join(", ")}`),optional4),verbose2=Boolean6("verbose").pipe(withAlias2("v"),withDescription3("Also print no-op confirmations (present, up to date)"),withDefault4(!1)),refresh=Boolean6("refresh").pipe(withDescription3("outdated: bypass the 24 h cache"),withDefault4(!1)),dryRun2=Boolean6("dry-run").pipe(withDescription3("ensure: preview without installing"),withDefault4(!1)),toolchainCommand=make20("toolchain",{op,tool,verbose:verbose2,refresh,dryRun:dryRun2},(config)=>gen2(function*(){let operation=getOrElse(config.op,()=>"check"),flags=config.verbose?["--verbose"]:[],operand=getOrUndefined(config.tool),words=operand===void 0?[]:[operand];switch(operation){case"check":return yield*engine(["toolchain","check",...words,...flags]);case"ensure":{let t=getOrUndefined(config.tool);if(t===void 0||!MANAGED.includes(t))return yield*bail(`toolchain ensure needs a managed tool: ${MANAGED.join(", ")}`);return yield*engine(["toolchain","ensure",t,...flags,...config.dryRun?["--dry-run"]:[]])}case"outdated":return yield*engine(["toolchain","outdated",...words,...config.refresh?["--refresh"]:[]]);default:return yield*bail(`Unknown toolchain op '${operation}' (valid: check, ensure, outdated)`)}})).pipe(withDescription4("Verified-version floors for external tools (SoT/toolchain.json): check prints the doctor table; ensure installs one managed tool when it is missing; outdated compares verified pins with the newest upstream release (network, report only)."));import{existsSync as existsSync10,readFileSync as readFileSync8}from"fs";import{join as join10}from"path";var noSync=Boolean6("no-sync").pipe(withDescription3("Update the kit only; skip the chained flag-less sync"),withDefault4(!1)),git=(spawn,home,args)=>{let res=spawn("git",["-C",home,...args]);return{ok:res.error===void 0&&res.status===0,out:`${res.stdout??""}${res.stderr??""}`.trim()}},chainSync=(spawn,args)=>sync2(()=>{let res=spawn(process.execPath,args,{stdio:"inherit"});if(res.error!==void 0||res.status!==0)process.exit(res.status??1)}),packageBinEntry=(home)=>{let manifestPath=join10(home,"package.json"),doc;try{doc=JSON.parse(readFileSync8(manifestPath,"utf8"))}catch{doc=void 0}let bin=doc!==null&&typeof doc==="object"&&"bin"in doc?doc.bin:void 0,named=typeof bin==="string"?bin:bin!==null&&typeof bin==="object"&&("docks-kit"in bin)?bin["docks-kit"]:void 0;if(typeof named!=="string"||named==="")return{ok:!1,diagnostic:`global package update completed, but ${manifestPath} names no docks-kit bin`};let entry=join10(home,named);return existsSync10(entry)?{ok:!0,entry}:{ok:!1,diagnostic:`global package update completed, but the docks-kit bin ${entry} named by ${manifestPath} does not exist`}},readPackageVersion=(home)=>{try{let doc=JSON.parse(readFileSync8(p(home,"package.json"),"utf8"));if(doc===null||typeof doc!=="object"||!("version"in doc))return"";return typeof doc.version==="string"?doc.version:""}catch{return""}},capturePackageRoot=(spawn)=>(command,args)=>{let res=spawn(command,args);return{status:res.status,stdout:res.stdout??"",...res.error===void 0?{}:{error:res.error}}},hostPathKey=(value,host)=>host.id==="windows"?value.replaceAll("\\","/").replace(/\/+$/,"").toLowerCase():value.replace(/\/+$/,""),samePackageHome=(a,b,host=hostOs())=>hostPathKey(a,host)===hostPathKey(b,host),packageManagerForHome=(home,environment=process.env,host=hostOs())=>{let normalizedHome=hostPathKey(home,host),underEnvironmentRoot=(name)=>{let root=environment[name]?.trim();if(root===void 0||root==="")return!1;let normalizedRoot=hostPathKey(root,host)||"/",prefix=normalizedRoot.endsWith("/")?normalizedRoot:`${normalizedRoot}/`;return normalizedHome===normalizedRoot||normalizedHome.startsWith(prefix)};return normalizedHome.includes("/.bun/")||underEnvironmentRoot("BUN_INSTALL_GLOBAL_DIR")||underEnvironmentRoot("BUN_INSTALL")?"bun":"npm"},resolveGlobalPackageHome=(manager,capture=capturePackageRoot(spawnHost))=>{let commandArgs=manager==="bun"?["pm","-g","ls"]:["root","-g"],result=capture(manager,commandArgs);if(result.error!==void 0||result.status!==0){let detail=result.error!==void 0?result.error.message:`exit ${result.status??"without status"}`;return{ok:!1,diagnostic:`${manager} ${commandArgs.join(" ")} failed: ${detail}`}}if(manager==="npm"){let root=result.stdout.trim();return root===""?{ok:!1,diagnostic:"npm root -g failed: empty output"}:{ok:!0,home:p(root,"docks-kit")}}let globalHeader=result.stdout.split(/\r?\n/).map((line)=>line.trim()).find((line)=>/ node_modules(?: \(.*\))?$/.test(line)),globalDir=globalHeader===void 0?void 0:/^(.*) node_modules(?: \(.*\))?$/.exec(globalHeader)?.[1];return globalDir===void 0||globalDir===""?{ok:!1,diagnostic:"bun pm -g ls did not report its global package root"}:{ok:!0,home:p(globalDir,"node_modules","docks-kit")}},packageUpdateResult=(before,after,samePackageRoot=!0)=>{if(before===""||after==="")return{alreadyCurrent:!1,message:""};if(!samePackageRoot)return{alreadyCurrent:!1,message:`Installed ${after} in the selected global package root.`};if(before===after)return{alreadyCurrent:!0,message:`Already at the latest version (${after}).`};return{alreadyCurrent:!1,message:`Updated ${before} -> ${after}.`}},
|
|
24575
|
+
`;var command_guards_default="# Command guards\n\nThe kit ships one destructive-command policy to omp.\nThe short rule for agents: **to remove, use the trash**. Run\n`gio trash -- <path>` on Linux or `trash <path>` on macOS. Remove a\ntemporary file or directory with `docks-kit scratch remove <path>` instead.\nTo remove a path from the git index, run `git rm -- <path>`.\n\nThe policy keeps only deny rules. Where omp's critical-command check acts,\nthe form is denied. omp also denies a `$` or a backtick after `git push`,\nbecause the agent can always write the ref literally.\n\nBy owner decision (0.22.8, DocksDocks/public#126), the kit ships no omp\nprompt rule. The kit's `bash.patterns` holds only deny rules and the `trash *`\nallow. Under omp's default `tools.approvalMode: yolo`, omp runs every\ncommand that no deny matches without a question, in the main session and in\nsubagents. This includes any `rm` that omp does not deny, `git clean`,\n`git reset --hard`, a force push that no deny matches, and a git command\nthat skips the repository's hooks. A prompt rule that the user adds to\n`~/.omp/agent/config.yml` survives sync and still asks; a subagent rejects\nit. The kit omp plugin trigger rule `git-safety.md` forbids these options with\n`git push` and `git rm`: `-f`, a flag cluster that holds `f`, and a long\noption that starts with `--f`. `git push --follow-tags` is correct. The rule\nalso forbids `git push origin +<ref>`, `git push --mirror`,\n`git push --prune`, and each hook skip. It tells the agent to ask before a\nbulk discard in the main session, for example `git clean` without `-n`,\n`git reset --hard`, `git checkout .`, or `git stash clear`.\nA subagent does not run a bulk discard and names it in its report. The omp\nagent prompt lists a force push as a step that needs `ask`. The section\n\"omp trigger rules\" below describes these rules.\n\nThe policy sorts shell commands into two tiers.\n\n- **Deny**: the command never runs, and nobody can approve it in the session.\n- **Allow**: the agent may run the command alone. A command that no rule\n matches runs too. The table below calls this `run`.\n\nA prompt rule that the user adds asks a person in the main session, and a\nsubagent rejects it.\n\nThe omp `eval` tool stays unrestricted: `bash.patterns` does not gate a shell\nthat `eval` starts.\n\n## Tiers\n\n| Command | omp `bash.patterns` |\n| --- | --- |\n| `rm` of `/`, `~`, `~/`, `$HOME`, `${HOME}`, quoted or with a trailing `/` | deny |\n| `rm` of `/*` | deny with an `r` or `f` option; plain `rm /*` runs |\n| `HOME=...`, `export HOME=...`, `env HOME=...` | deny |\n| `sudo` before `rm`, plain or by path (`/usr/bin/sudo`) | deny |\n| `git push --force` or `-f` to `origin main` or `origin master` | deny |\n| Recursive `rm` (`-r`, `-R`, `-rf`, `-fr`, `-rfv`, `-ri`, `-ir`, `-Ri`, `-iR`, `--recursive`, other listed clusters) | deny, also behind any prefix (`env`, `xargs`, `nice`, `find -exec`, `git rm -r`) |\n| `rm` with an `r` or `f` option before an absolute path, `--no-preserve-root` | deny |\n| Any other `rm`: one file, several files, a glob, `-f` | run |\n| `find ... -delete`, `find ... -exec rm` (also `-execdir`, `-ok`, `-okdir`), `xargs rm` | deny, in every position and by path |\n| `git clean`, `git reset --hard` | run |\n| `git push` that could force: see below | run, unless a deny above matches |\n| A `$` or a backtick anywhere after `git push` in the same command | deny, also after a shell keyword, a wrapper, or a path before `git`: see below |\n| A git command that skips the repository's hooks: see below | run |\n| `git rm -- <path>`, `git worktree remove -- <path>` | run |\n| `git worktree remove --force -- <path>` | run; the omp `file-removal.md` trigger rule fires on each `--force`, `-f`, or `--f` form and permits it once, after the commits are on the remote |\n| `docks-kit scratch remove <path>` | run; the command removes only a path inside the scratch root, the system temporary directory, or `/var/tmp` |\n| Any other non-recursive `git rm` or `git worktree remove` | run |\n| `gio trash -- <path>` | run |\n| Any other `gio trash` | run |\n| `trash <path>` (macOS) | allow |\n\nomp runs each of these `git push` forms, which can force. Its force-push deny\nmatches only `git push --force` or `git push -f` directly before\n`origin main` or `origin master`:\n\n- a `+` refspec;\n- any long option that starts with `--f`, such as `--force`,\n `--force-with-lease`, or an abbreviation like `--for`;\n- `--mirror` or an abbreviation of it;\n- `-f`, or a short-option cluster that starts with two of git push's\n no-argument flags (`v`, `q`, `d`, `n`, `u`, `4`, `6`, `f`), such as `-vf`,\n `-vvf`, or `-uvfq`;\n- a word that starts with `$`, a backtick, a quote, or a backslash. omp\n denies a `$` or a backtick anywhere after `git push`.\n\nEach of these must begin a word: `feat/cache-vf` is a branch name, not an\noption.\n\nA `$` or a backtick hides the ref until the shell expands it, so the matcher\ncannot tell `$b` from `+main` or `--force`. An unquoted value inside a word\nalso splits into more words: with `b=\"main --force\"`, `HEAD:$b` becomes\n`HEAD:main --force`. omp never applies an allow rule to a command that holds a\n`$` that the shell expands. So the kit cannot add an exception for a plain\nbranch name.\n\nomp therefore denies a `$` or a backtick anywhere after `git push` in the same\ncommand. The agent reads a refusal such as\n`Blocked by bash pattern: *git push *$*`, writes the ref literally, and runs\nthe push without a question. The omp `git-safety.md` trigger rule names the\nliteral forms: `git push -u origin HEAD` for the current branch, and\n`git push origin --delete <branch-a> <branch-b>` for several branches. The two\nomp deny rules start with `*`. So a shell keyword such as `do` in a loop, a\nwrapper such as `env`, or a path such as `/usr/bin/git` does not hide the\npush.\n\n## Commands that skip the repository's hooks\n\nA git command can skip the repository's hooks, for example with\n`--no-verify`, `git commit -n`, `git am -n`, or a `core.hooksPath` change.\nThe kit ships no omp `bash.patterns` rule for these commands, so omp does not\nblock them. The omp `git-safety.md` trigger rule forbids each hook skip.\n\n## How an agent removes files\n\n1. Remove a temporary file or directory with the `scratch_remove` tool or\n `docks-kit scratch remove <path>`. The command removes only a path inside\n the scratch root, the system temporary directory, or `/var/tmp`.\n `gio trash` does not trash on a system internal mount, such as a `tmpfs`\n `/tmp`.\n2. Move every other file or directory to the trash with `gio trash -- <path>`\n on Linux or `trash <path>` on macOS. The `--` ends option parsing, so `gio`\n reads every later argument as a path, and a path such as `--empty` cannot\n empty the trash.\n3. To remove a path from the git index, run `git rm -- <path>`. To remove a\n worktree, run `git worktree remove -- <path>`. When git refuses because the\n worktree has changes, the agent may pass `--force` once, after each commit\n is on the remote and `git status --porcelain` lists only generated files.\n Never pass `--force` two times.\n4. Do not use `rm`. omp denies a recursive `rm`, `find -delete`,\n `find -exec rm`, and `xargs rm`. It runs any other `rm` without a prompt.\n5. For a recursive or bulk deletion, ask the user in the main session. A\n subagent lists the paths in its final report. The user runs a recursive\n deletion by hand.\n6. Write literal absolute paths. Never use `~` or `$HOME`, and never set or\n export `HOME`.\n\nThe kit plugin trigger rules `file-removal.md` and `literal-paths.md` carry\nthese rules.\n\n### What the git removals keep\n\n- `git rm` without `--force` refuses a file whose content differs from the\n last commit. The removed content stays in the repository history.\n- `git worktree remove` without `--force` refuses a worktree with untracked\n files or tracked changes. It does delete the files that `.gitignore` covers,\n such as `node_modules`, build output, or a local `.env`. Git keeps no copy of\n those files.\n- Git accepts an abbreviated long option, such as `--for` for `--force`, and a\n short-option cluster, such as `-rff`. After `--`, git reads every argument as\n a path. So the `--` form is the only one that cannot force.\n\n## omp trigger rules\n\nomp loads `~/.omp/agent/AGENTS.md` only into main sessions and advisors,\nnever into task subagents (`omp://context-files.md`). So the kit puts the omp\ncommand rules into six Time Traveling Stream Rules (TTSR, trigger rules). The\nkit plugin `docks-kit-omp` ships them in `SoT/.omp/plugin/rules/`. Sync\nmaterializes the plugin to `~/.docks-kit/omp-plugin` and links it. omp's\n`omp-plugins` provider loads `rules/*.md` from the linked plugin root. Each\nrule has the scope `tool:bash, tool:eval`, because eval code can run a shell\ncommand through `sh()`.\n\n| Rule | Scope | Correct form that the rule teaches |\n| --- | --- | --- |\n| `file-removal.md` | `tool:bash`, `tool:eval` | `scratch_remove` or `docks-kit scratch remove <path>` for a temporary path; `gio trash -- <path>` or `trash <path>` for another path; no `rm`, `unlink`, or `shred`, also after a `VAR=value` prefix; `git rm -- <path>`; for a folder, `git rm -- '<dir>/*'` or `git rm --cached -- '<dir>/*'`, because omp denies `git rm -r`; `git worktree remove -- <path>`, and `--force` only after the commit and status checks; no deletion through `eval` |\n| `git-safety.md` | `tool:bash`, `tool:eval` | no hook skip, also through an abbreviation such as `--no-veri`; no `-f`, `f` cluster, or `--f` long option with `git push` or `git rm` (`--follow-tags` is correct); no `+<ref>` with `git push` (`git push origin +<ref>` is a force push); no `git push --mirror` or `--prune`; a literal push ref; `git push` as its own command, not chained with `&&`, `\\|\\|`, or `;`; `git push -u origin HEAD`; `git push origin --delete <branch-a> <branch-b>`; `git branch -d <branch>`, not `-D` or `-d --force`; `git restore -- <path>`; an ask before `git clean` without `-n` or `--dry-run` before ` -- `, `git reset --hard`, `git checkout .`, `git restore .` (`git restore --staged .` only unstages and is correct), `git stash drop`, or `git stash clear`. The git global options `-C`, `-c`, `-p`, `-P`, and `--<option>` do not hide the subcommand. A word after ` -- ` is a path, not an option |\n| `temp-and-background.md` | `tool:bash`, `tool:eval` | `scratch_new` or `docks-kit scratch new <label>` instead of `/tmp`; a server or watcher only as a named bash service or an async job; no `nohup`, `setsid`, `disown`, `tmux`, or `screen`, also after a `VAR=value` prefix; no global install (`npm`, `bun`, `pnpm`, `yarn`, `pipx`, `cargo`, `go install`, `gem install`, `uv tool install`), scheduled job, or enabled service; no Docker cleanup of a resource that the agent did not create |\n| `worktree-location.md` | `tool:bash`, `tool:eval` | a worktree only at the literal absolute path `<data>/agent-worktrees/<repository>/<name>`, with `agent-worktrees` as a whole directory name. The rule fires on each `git worktree add`, also at the correct path, because a condition cannot read `$XDG_DATA_HOME` or the home directory of the user. The retry after the reminder runs |\n| `literal-paths.md` | `tool:bash`, `tool:eval` | a literal absolute path; no `~` or `$HOME`; no `HOME` assignment |\n| `remote-cleanup.md` | `tool:bash`, `tool:eval` | a remote cleanup only on a non-production target; an `ask` immediately before a production cleanup, which must be rare. Remote means SSH, `rsync --delete` to a `host:` target, `rclone` (`delete` verbs, and `sync` to a `remote:` target), `gh` (`gh <noun> delete`, `gh <noun> <x>-delete`, and `gh api -X DELETE`), a remote `docker` or `podman` (also `docker -c <context>`), a database client (`DROP TABLE`, `DATABASE`, or `SCHEMA` in `psql`, `mysql`, `sqlite3`, or `mongosh`; `dropdb`; `redis-cli FLUSHALL` or `FLUSHDB`), or a provider CLI with a cleanup verb, such as `aws s3 rb` or `neonctl branches delete` |\n\nEach rule has a regex `condition` that aims at the wrong form. When the\nmodel streams a matching tool call, omp aborts the call before it runs,\ninjects the rule body, and retries (`omp://ttsr-injection-lifecycle.md`). A\nrule costs no prompt tokens until it fires, and it reaches subagents too. The\ntrigger rules teach the correct form. The `bash.patterns` denies do not\nchange, and they still enforce. Each rule has `repeatMode: always`, so it\nfires at each later wrong form in the session too. The retry that its own\nreminder starts does not fire it again, so a correct command still runs.\n\nAfter a session resume, omp restores each injected rule at message count\nzero. So a rule that fired before the resume does not fire in the first turn\nafter the resume (section 7 of\n[ttsr-injection-lifecycle.md](https://github.com/can1357/oh-my-pi/blob/main/docs/ttsr-injection-lifecycle.md)).\nNo repeat mode changes this. The `bash.patterns` denies and the main-session\n`ask` rules still apply in that turn.\n\nA condition reads text, not a parsed shell command. So these correct calls\nalso fire a rule:\n\n- A quoted command word, such as `echo \"rm x\"` or a commit message that\n starts with `rm`, fires `file-removal.md`.\n- In eval code, a scan can continue past the closing quote of the `sh()`\n string to the end of the statement. For example,\n `print(sh(\"kubectl get pods\"), \"pods to delete\")` fires `remote-cleanup.md`.\n\nomp tests each condition on the partial tool-call buffer after each streamed\ndelta, and again on the full arguments at the end of the call\n(`omp://ttsr-injection-lifecycle.md`). So a condition must not match a prefix\nof a correct command. Each condition must require a delimiter after the token\nthat it checks, and no condition uses the end anchor `$` as that delimiter.\nA negative lookahead, such as `(?!ol)` in `--f(?!ol)`, passes at the end of\na partial buffer. So after a negative lookahead, the condition must read the\ntoken to its delimiter. `git clean` and `git restore .` read the full\ncommand before they decide, because `-n` or `--staged` can come last.\n\nThe buffer is the argument JSON text, and omp's schema puts the intent field\n`i` before `command`. A call can also put `i` after `command`, and a provider\ncan stream JSON with white space, such as `{\"command\": \"ls\"}`. Each condition\nstarts its match with the forward key prefix, after an optional inline flag\ngroup:\n\n```text\n\"(?:command|code)\"\\s*:\\s*\"[^\"\\\\]*?(?:\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?\\\\.[^\"\\\\]*?)*?(?:\\\\.[^\"\\\\]*?){0,7}?\n```\n\nThe prefix matches the `command` or `code` key, with or without JSON white\nspace around the colon. Then it walks the string body forward and steps over\none escape pair, such as `\\\"` or `\\\\`, as one unit. Each loop step takes up to\n8 escape pairs. So the JavaScriptCore regex JIT handles about 8 times more\nescapes before it falls back to its slower interpreter. The walk never passes\nan unescaped `\"`, so the key prefix starts at the key and stays inside that\nstring. Only the prefix gives this guarantee. A scan stops at an unescaped\n`\"`, which ends the command string, and at a newline (`\\n`), which ends the\ncommand line. So the intent text and the next line do not fire a rule. A\nknown limit: a part of a condition that is not such a scan, such as\n`[^)]*`, can cross the closing quote, and the match then continues into a\nlater field. For example, the `Bun.file` condition of `file-removal.md`\nmatches `{\"code\":\"Bun.file(\",\"i\":\").delete(\"}`. A tab in a command is `\\t` in\nthe buffer, so each condition reads `\\t` as shell white space, as it reads a\nspace. A scan that looks for an option also stops at a ` -- ` word, also with\na tab, because each later word is a path. So `git clean -fd -- -n` fires, and\n`git rm -- -f` stays quiet. In the `git push` conditions for `$`, a backtick,\nand a chain, a scan also stops at `)` and at a backtick, which end a\nJavaScript `` sh`\u2026` `` or `sh(\"\u2026\")` call. A backtick counts as a command\nsubstitution only when a word follows it.\nomp's `Matched:` excerpt is a bounded window around the match start, not the\nfull match (`packages/coding-agent/src/export/ttsr.ts` in omp 19.0.0). The\nwindow starts up to 60 characters before the match start, so it can show the\nend of the intent field. omp keeps at most 120 characters of the match and\nup to 60 characters after them. So a long match is cut at 180 characters from\nits start. omp replaces each white space run with one space and marks a cut\nend with `\u2026`. In a long call, the trigger can be more than 180 characters\nafter the key, and then the trigger is outside the excerpt.\n\nomp 19.0.0 tests every condition on the whole buffer at each streamed delta,\non its main thread, in JavaScriptCore. From 0.22.24 to 0.22.29, each\ncondition started with a variable-length lookbehind over the key and the\nstring body. A leading unbounded lookbehind walks back over the buffer from\nevery position. On a 20 KB tool call, one scan took seconds and froze the omp\nsession. Past JavaScriptCore's match limit, the scan also reported no match,\nso the rule did not fire.\n\nA forward key prefix alone does not make a condition linear. Three input\nfamilies can still make a scan slow:\n\n- A dense line: one long line that repeats a command start, such as\n `git restore `. If the scan of each command start runs to the end of the\n line, the time grows with the square of the line length.\n- A head and a run: one command start, such as `aws `, and then one long run,\n such as `x x x`. A group loop inside a lookaround makes JavaScriptCore keep\n each loop step until the match attempt ends. The regex then drops out of\n the JIT. One `remote-cleanup.md` condition took 0.9 ms at 16 KB and 82 ms at\n 64 KB.\n- An open buffer: the buffer stops before the closing quote of the command.\n omp tests the buffer after each streamed delta, so most real scans see no\n closing quote, and a scan cannot use it as a stop.\n\nA command start inside the option region of an earlier command start, and\ntext with many escapes, need care too. So each condition has this form:\n\n- The match starts at the forward key prefix.\n- Each scan after a command start is one lazy walk that stops at its first\n event: `(?=(?<w>[\\s\\S]*?)(?=EVENT)BOUNDARY)\\k<w>`. The events are the flag\n that the condition looks for, a terminator, the end of the run, and the\n next command start. A lookahead in JavaScript does not backtrack after it\n matches, so `\\k<w>` consumes the walk as one frozen piece.\n- An event counts only at a real token boundary: no odd run of backslashes\n comes before it.\n- A scan stops at a later command start, because the scan of that command\n start reads the same remaining text. So two scans never read the same\n text, and a dense line costs linear time.\n- Some conditions find the flag first and then walk back once to the head of\n the command. Their head allows wrapper words, such as `sudo` or `env`, or\n `KEY=value` words before the command, as in `LC_ALL=C rm`.\n\nThe rewrite gives the same result as the rules of 0.22.29 on each input that\nthe checks tried. The checks are the 2697 rows of the test table, a fuzz run\nof 5 times 310,825 buffers on all 69 conditions, and an enumeration of every\ntoken sequence of up to 6 or 7 tokens for each condition. The enumeration\nused closed and open buffers. No result changed, and no match was lost or\nadded.\n\nWrite each new condition by these rules:\n\n- Start the match with the forward key prefix. Never start a condition with\n an unbounded lookbehind.\n- Make each scan one frozen walk that stops at its first event and at the\n next command start.\n- Never put a group loop inside a lookaround over text of unbounded length.\n- Run `bunx vitest run cli/test/unit/ompTriggerRules.test.ts cli/test/unit/ompTriggerBackstop.test.ts`.\n The first file runs the shape guard, and the second runs the Bun backstop.\n- When you rewrite a condition, run the old and the new condition on each\n buffer of the test table, and make sure that both give the same result.\n\n`cli/test/unit/ompTriggerRules.test.ts` runs each shell row through bash,\nPython `sh(\"\u2026\")`, JavaScript `` sh`\u2026` ``, and JavaScript `sh(\"\u2026\");`. It runs\nevery row in the compact JSON layout (`{\"command\":\"ls\"}`) and in the spaced\nlayout (`{\"command\": \"ls\"}`), and some rows in the pretty layout, with a\nnewline and an indent. Other rows put trigger words in the intent field,\nbefore or after the command, or put a tab in the command. The test checks\nthat each correct form stays quiet on each prefix, that each condition has a\nwrong row that fires it, and that each rule has `repeatMode: always`.\n\nIts shape guard checks only what a static check can prove. Each condition\nmust start with the forward key prefix, and this rejects the leading\nlookbehind that froze omp. No `|` can stand outside every group, because the\nalternative after it needs no key prefix. The shape guard cannot prove\nlinear time. The backstop tests the measured input families for linear\ntime: `cli/test/unit/ompTriggerBackstop.test.ts` runs\n`cli/test/lib/ompTriggerBackstop.ts` under Bun, because the unit tests run on\nV8, which does not show the JavaScriptCore cost. That file is a Vitest project\nof its own, which starts after every other unit file has ended, because the\nbackstop uses every core (DocksDocks/docks-kit#187). A\ncondition can still backtrack on a run that no generator holds, so a new\ncondition needs a new family when its shape is new. The backstop has these\nchecks:\n\n- Time budget, with the regex JIT on: one pass of all conditions over a\n 20 KB Python cell, a 20 KB bash command, and a 30 KB `KEY=value` chain\n stays under 250 ms for each buffer.\n- Fire, with the regex JIT on: `git reset --hard` at the end of the 20 KB\n cell fires `git-safety.md`.\n- Scaling, with the regex JIT off: each condition alone, on each adversarial\n input shape, at 16 KB and 64 KB.\n- Dense and head-and-run scaling, with the regex JIT on: each condition\n alone, on the two families above, at 16 KB and 64 KB. Each line goes into a\n bash command, an open bash command without its closing quote, and a Python\n `sh(\"\u2026\")` cell.\n\nIn each scaling check, the 64 KB time must stay at most 8 times the 16 KB\ntime plus 15 ms, and at most 100 ms. The backstop times the pairs in parallel\nchild processes first. Each pair that fails there gets a second, serial run,\nand it fails only when it fails there too. A call of 1000 ms or more fails at\nonce.\n\n## Why omp denies instead of asking\n\nomp has a built-in check for critical commands. For example, it flags:\n\n- an `rm` with an `r` or `f` option before an absolute path;\n- `sudo rm`, also when `sudo` is called by its path.\n\nomp 19.0.0 checks deny and prompt rules first, then its critical patterns, then\nallow rules. A critical command that no deny or prompt rule matches gets a bare\nsafety override, which also replaces a matching allow. Under omp's default\n`tools.approvalMode: yolo`, omp ignores a bare override, so the command runs.\nThis applies in subagents too. A prompt rule would ask a person in the main\nsession, but a subagent rejects every prompt, so the kit ships none. Only a\ndeny rule stops a critical command in every session (`BashTool.approval` in\nthe v19.0.0 source).\n\nThe kit therefore denies every `rm` shape that the check can flag:\n\n- a recursive `rm`;\n- an `rm` with an option that holds `r` or `f` before an absolute path;\n- `sudo` anywhere before `rm`;\n- `--no-preserve-root`.\n\nThe kit also denies bulk removal through `find -delete`, `find -exec rm`, and\n`xargs rm`. omp's critical check does not flag these forms, but they can empty\nthe home directory, and no glob can express \"inside the temporary directory\".\n`docks-kit scratch remove` checks the path in code instead.\n\n## Matching rules\n\n- For a simple command, the rules are ordered, and the first match wins.\n- `*` matches any text, spaces included, and no escape spells a literal `*`.\n- Deny rules test the whole line and each segment between `;`, `&&`, `|`,\n and similar operators, with quotes and escapes removed. So\n `rm -rf \"$HOME\"` matches `rm * $HOME`. A segment also matches without its\n leading `NAME=value` words.\n- For a line with shell control, each segment takes its first matching deny\n or prompt rule. A deny chosen for one segment wins over a prompt chosen\n for another segment; within one segment, a prompt rule that comes first\n wins over a later deny.\n- Allow rules apply only to a simple command.\n- The kit ships no prompt rule. It lists rules as deny, then the `trash *`\n allow.\n\n## Gaps\n\n- **omp, literal `*`**: omp cannot match a literal `*`, so it cannot tell a\n glob from a file name. The kit therefore runs every `rm` that it does not\n deny without a prompt. This includes `rm ~/*`, `rm $HOME/*`, and `rm /*`\n without an `r` or `f` option, because a deny rule for them would also deny\n `rm ~/notes.txt` (owner decision, 0.20.9).\n- **omp, whole-line matching**: omp tests deny rules against the whole command\n line too, so a pattern can span commands. For example, `rm x && cd ~`,\n `rm -i a && ls -R /tmp`, and `sudo apt update && rm x` are denied. Run `rm`\n as its own command. In the same way, a `$` or a backtick after `git push`\n denies the whole command, such as `git push origin HEAD && echo $?`. omp\n joins the lines of a command first, so `echo $?` on a later line is denied\n too. Run `git push` as its own command.\n- **omp, text arguments**: the critical-shape deny also matches text such as\n `git commit -m \"rm -f /tmp/x\"`. The `git push` deny matches text that names\n `git push` before a `$`, such as `git commit -m \"git push $b fails\"`. Write\n such a message with `git commit -F`.\n- **omp, prefixed `rm`**: the kit denies a recursive `rm` behind any prefix,\n such as `env X=1 rm -rf b`, `xargs rm -rf`, `find . -exec rm -rf {} +`, or\n `git rm -r dir`. A `* rm ` rule also matches text, so a line such as\n `echo do not rm -rf b` is denied too.\n- **omp, bulk-removal text**: the `* find *-delete*`, `*-exec rm *`, and\n `*xargs rm` rules also match text, so a line such as\n `echo use find with -delete` is denied. Write such text to a file instead.\n- **omp, recursive `rm` clusters**: omp matches only the listed\n recursive-`rm` clusters: `r` or `R` alone or with `f` and `v`, plus `-ri`,\n `-ir`, `-Ri`, and `-iR`. Another cluster runs.\n- **`git push` beyond the listed words**: a configured `+` refspec in\n `remote.<name>.push` makes a plain `git push` force. No rule sees git\n configuration. `git push --delete` and `git push --prune` remove remote\n branches without force; no kit rule asks for them.\n- **omp, force push to `main` in another spelling**: the force-push deny\n rules match only `git push --force` or `git push -f`, then\n `origin main` or `origin master`. Every other force push to `main` runs\n without a question, such as `git push origin main --force`,\n `git push -vf origin main`, `git push --force-with-lease origin main`,\n `git push origin +main`, `git push -f origin HEAD:main`, or\n `git push --mirror origin`. Until 0.22.8 these forms asked.\n- **omp, force push after a prefix**: the force-push deny rules start with\n `git push`, not `*`. So a force push to `origin main` after a shell keyword,\n a wrapper, or a path runs without a check, such as\n `for r in a; do git push --force origin main; done`,\n `env git push --force origin main`, or `/usr/bin/git push --force origin main`.\n- **`git -C`**: no rule matches a git subcommand that does not follow `git`\n directly, such as `git -C . push --force origin main` or\n `git -C . push origin $b`.\n- **Programs that remove files**: no rule covers a program that removes files\n itself, such as a Python or Node script, or a shell started by omp `eval`.\n\n### How `gio trash` empties the trash\n\nGLib's `gio trash` handles operands first. With at least one path, it trashes\nor restores the paths, and `--empty` has no effect. Without a path, it empties\nthe trash when `--empty` is set. `-f` can repeat. So `gio trash -ff --empty`\nempties the trash, while `gio trash build --empty` only trashes `build`.\n\nomp runs every `gio trash` without a prompt.\n\n## Sync behavior\n\n- The config merge keeps user `bash.patterns` rules and groups all rules in\n this order:\n 1. kit deny;\n 2. user deny;\n 3. user prompt;\n 4. kit prompt (the kit ships none since 0.22.8);\n 5. the other user rules;\n 6. kit allow.\n- A user deny or prompt thus precedes every kit allow, and no allow can\n loosen a deny or a prompt.\n- A repeat sync changes nothing.\n- After the merge, `ompRemovals.ts syncOmpRemovals, retired bash-rule\n inventory` removes the retired kit rules in `OMP_RETIRED_BASH_RULES` from\n the deployed `bash.patterns` on every sync. The inventory also holds the\n 492 prompt rules that the kit retired in 0.22.8. It removes a rule only\n when its `match` and `approval` equal a retired pair, so a different user\n rule stays.\n\n## Check the deployed rules\n\nThe check below is safe, because the shell never reaches `rm`.\n\nAsk the agent to run `true || rm -rf \"$HOME\"`. The `true ||` short-circuit\nstops the shell before `rm`. omp reports\n`Blocked by bash pattern: rm * $HOME`.\n\n## Sources\n\n- omp: `omp://tools/bash.md`, `omp://approval-mode.md`, and the\n `@oh-my-pi/pi-coding-agent` 19.0.0 source `src/tools/bash.ts`\n (`CRITICAL_BASH_PATTERNS`, `BashTool.approval`). `omp://approval-mode.md`\n still describes the 18.17.0 order; the source is what runs.\n- GLib `gio trash`: https://github.com/GNOME/glib/blob/main/gio/gio-tool-trash.c\n- Git: https://git-scm.com/docs/gitcli (abbreviated and clustered options),\n https://git-scm.com/docs/git-rm, https://git-scm.com/docs/git-worktree,\n https://github.com/git/git/blob/master/builtin/push.c (short options), and\n https://github.com/git/git/blob/master/builtin/worktree.c\n (`remove_worktree` parses `--`; `check_clean_worktree` runs\n `git status --porcelain` without `--ignored`).\n- Git hooks: https://git-scm.com/docs/githooks (`--no-verify`,\n `core.hooksPath`), https://git-scm.com/docs/git-commit and\n https://git-scm.com/docs/git-am (`-n`).\n- macOS `trash`: https://keith.github.io/xcode-man-pages/trash.8.html\n";var TOPICS={overview:{summary:"What docks-kit is and how the pieces fit",body:overview_default},"sync-layers":{summary:"How sync deploys the omp SoT, and its additive-by-default semantics",body:sync_layers_default},flags:{summary:"Full flag reference",body:flags_default},toolchain:{summary:"Verified-version floors, the doctor table, and the upstream outdated report",body:toolchain_default},install:{summary:"Install paths: repo checkout, bun add -g, POSIX/Windows installers",body:install_default},platforms:{summary:"Platform support: Linux on x64 and arm64, macOS on arm64, Windows on x64",body:platforms_default},"omp-models":{summary:"omp role map and the Artificial Analysis snapshot behind it",body:omp_models_default},"omp-context":{summary:"omp compaction trigger, the reserve-based default, and context-window lanes",body:omp_context_default},"command-guards":{summary:"Deny and allow rules for destructive shell commands in omp",body:command_guards_default}},topic=String9("topic").pipe(withDescription2(`One of: ${Object.keys(TOPICS).join(", ")}`),optional4),json=Boolean6("json").pipe(withDescription3("List topics as JSON"),withDefault4(!1)),docsCommand=make20("docs",{topic,json},(config)=>gen2(function*(){let requested=getOrUndefined(config.topic);if(requested===void 0){if(config.json)return yield*log(JSON.stringify(Object.entries(TOPICS).map(([name,t])=>({name,summary:t.summary})),null,2));yield*log(`docks-kit documentation topics (docks-kit docs <topic>):
|
|
24576
|
+
`);for(let[name,t]of Object.entries(TOPICS))yield*log(` ${name.padEnd(14)} ${t.summary}`);return}let entry=Object.hasOwn(TOPICS,requested)?TOPICS[requested]:void 0;if(entry===void 0)return yield*bail(`Unknown topic '${requested}'. Valid: ${Object.keys(TOPICS).join(", ")}`);yield*log(entry.body)})).pipe(withDescription4("Self-documentation: the kit's concepts as readable topics, bundled with the CLI \u2014 a fresh agent can learn the kit from here alone."));import{existsSync as existsSync9}from"fs";import{join as join9}from"path";var updateNudge=(logger)=>{try{let home=kitHome();if(!existsSync9(join9(home,".git")))return;if(spawnHost("git",["-C",home,"fetch","--quiet"],{stdio:"ignore",timeout:4000}).status!==0)return;let res=spawnHost("git",["-C",home,"rev-list","--count","HEAD..@{u}"],{stdio:["ignore","pipe","ignore"]}),behind=(res.stdout??"").trim();if(res.status===0&&behind!==""&&behind!=="0")logger.warn(`kit checkout is ${behind} commit(s) behind its upstream \u2014 run: docks-kit update`)}catch{}},dryRun=Boolean6("dry-run").pipe(withDescription3("Preview without applying"),withDefault4(!1)),skipPluginRefresh=Boolean6("skip-plugin-refresh").pipe(withDescription3("Install missing plugins but skip refresh-only updates for existing plugins"),withDefault4(!1)),verbose=Boolean6("verbose").pipe(withAlias2("v"),withDescription3("Also print no-op confirmations (already in sync, up to date, left as-is)"),withDefault4(!1)),syncCommand=make20("sync",{dryRun,skipPluginRefresh,verbose},(config)=>gen2(function*(){let args=["sync"];if(config.dryRun)args.push("--dry-run");if(config.skipPluginRefresh)args.push("--skip-plugin-refresh");if(config.verbose)args.push("--verbose");if(!config.dryRun){let logger=yield*LoggerService;yield*sync2(()=>updateNudge(logger))}yield*engine(args)})).pipe(withDescription4("Deploy the SoT to this machine with EngineNative."));var MANAGED=["bun"],op=String9("op").pipe(withDescription2("check (default) | ensure <tool> | outdated"),optional4),tool=String9("tool").pipe(withDescription2(`Managed tool for ensure: ${MANAGED.join(", ")}`),optional4),verbose2=Boolean6("verbose").pipe(withAlias2("v"),withDescription3("Also print no-op confirmations (present, up to date)"),withDefault4(!1)),refresh=Boolean6("refresh").pipe(withDescription3("outdated: bypass the 24 h cache"),withDefault4(!1)),dryRun2=Boolean6("dry-run").pipe(withDescription3("ensure: preview without installing"),withDefault4(!1)),toolchainCommand=make20("toolchain",{op,tool,verbose:verbose2,refresh,dryRun:dryRun2},(config)=>gen2(function*(){let operation=getOrElse(config.op,()=>"check"),flags=config.verbose?["--verbose"]:[],operand=getOrUndefined(config.tool),words=operand===void 0?[]:[operand];switch(operation){case"check":return yield*engine(["toolchain","check",...words,...flags]);case"ensure":{let t=getOrUndefined(config.tool);if(t===void 0||!MANAGED.includes(t))return yield*bail(`toolchain ensure needs a managed tool: ${MANAGED.join(", ")}`);return yield*engine(["toolchain","ensure",t,...flags,...config.dryRun?["--dry-run"]:[]])}case"outdated":return yield*engine(["toolchain","outdated",...words,...config.refresh?["--refresh"]:[]]);default:return yield*bail(`Unknown toolchain op '${operation}' (valid: check, ensure, outdated)`)}})).pipe(withDescription4("Verified-version floors for external tools (SoT/toolchain.json): check prints the doctor table; ensure installs one managed tool when it is missing; outdated compares verified pins with the newest upstream release (network, report only)."));import{existsSync as existsSync10,readFileSync as readFileSync8}from"fs";import{join as join10}from"path";var noSync=Boolean6("no-sync").pipe(withDescription3("Update the kit only; skip the chained flag-less sync"),withDefault4(!1)),git=(spawn,home,args)=>{let res=spawn("git",["-C",home,...args]);return{ok:res.error===void 0&&res.status===0,out:`${res.stdout??""}${res.stderr??""}`.trim()}},chainSync=(spawn,args)=>sync2(()=>{let res=spawn(process.execPath,args,{stdio:"inherit"});if(res.error!==void 0||res.status!==0)process.exit(res.status??1)}),packageBinEntry=(home)=>{let manifestPath=join10(home,"package.json"),doc;try{doc=JSON.parse(readFileSync8(manifestPath,"utf8"))}catch{doc=void 0}let bin=doc!==null&&typeof doc==="object"&&"bin"in doc?doc.bin:void 0,named=typeof bin==="string"?bin:bin!==null&&typeof bin==="object"&&("docks-kit"in bin)?bin["docks-kit"]:void 0;if(typeof named!=="string"||named==="")return{ok:!1,diagnostic:`global package update completed, but ${manifestPath} names no docks-kit bin`};let entry=join10(home,named);return existsSync10(entry)?{ok:!0,entry}:{ok:!1,diagnostic:`global package update completed, but the docks-kit bin ${entry} named by ${manifestPath} does not exist`}},readPackageVersion=(home)=>{try{let doc=JSON.parse(readFileSync8(p(home,"package.json"),"utf8"));if(doc===null||typeof doc!=="object"||!("version"in doc))return"";return typeof doc.version==="string"?doc.version:""}catch{return""}},capturePackageRoot=(spawn)=>(command,args)=>{let res=spawn(command,args);return{status:res.status,stdout:res.stdout??"",...res.error===void 0?{}:{error:res.error}}},hostPathKey=(value,host)=>host.id==="windows"?value.replaceAll("\\","/").replace(/\/+$/,"").toLowerCase():value.replace(/\/+$/,""),samePackageHome=(a,b,host=hostOs())=>hostPathKey(a,host)===hostPathKey(b,host),packageManagerForHome=(home,environment=process.env,host=hostOs())=>{let normalizedHome=hostPathKey(home,host),underEnvironmentRoot=(name)=>{let root=environment[name]?.trim();if(root===void 0||root==="")return!1;let normalizedRoot=hostPathKey(root,host)||"/",prefix=normalizedRoot.endsWith("/")?normalizedRoot:`${normalizedRoot}/`;return normalizedHome===normalizedRoot||normalizedHome.startsWith(prefix)};return normalizedHome.includes("/.bun/")||underEnvironmentRoot("BUN_INSTALL_GLOBAL_DIR")||underEnvironmentRoot("BUN_INSTALL")?"bun":"npm"},resolveGlobalPackageHome=(manager,capture=capturePackageRoot(spawnHost))=>{let commandArgs=manager==="bun"?["pm","-g","ls"]:["root","-g"],result=capture(manager,commandArgs);if(result.error!==void 0||result.status!==0){let detail=result.error!==void 0?result.error.message:`exit ${result.status??"without status"}`;return{ok:!1,diagnostic:`${manager} ${commandArgs.join(" ")} failed: ${detail}`}}if(manager==="npm"){let root=result.stdout.trim();return root===""?{ok:!1,diagnostic:"npm root -g failed: empty output"}:{ok:!0,home:p(root,"docks-kit")}}let globalHeader=result.stdout.split(/\r?\n/).map((line)=>line.trim()).find((line)=>/ node_modules(?: \(.*\))?$/.test(line)),globalDir=globalHeader===void 0?void 0:/^(.*) node_modules(?: \(.*\))?$/.exec(globalHeader)?.[1];return globalDir===void 0||globalDir===""?{ok:!1,diagnostic:"bun pm -g ls did not report its global package root"}:{ok:!0,home:p(globalDir,"node_modules","docks-kit")}},packageUpdateResult=(before,after,samePackageRoot=!0)=>{if(before===""||after==="")return{alreadyCurrent:!1,message:""};if(!samePackageRoot)return{alreadyCurrent:!1,message:`Installed ${after} in the selected global package root.`};if(before===after)return{alreadyCurrent:!0,message:`Already at the latest version (${after}).`};return{alreadyCurrent:!1,message:`Updated ${before} -> ${after}.`}},updateCheckout=(home,skipSync,spawn=spawnHost)=>gen2(function*(){if(spawn("git",["--version"],{stdio:"ignore"}).status!==0)return yield*bail("git not found - cannot update the kit checkout");let dirty=git(spawn,home,["status","--porcelain"]);if(!dirty.ok)return yield*bail(`git status failed in ${home}: ${dirty.out}`);if(dirty.out!=="")return yield*bail(`kit checkout ${home} has local changes - commit or stash them, then re-run docks-kit update`);let upstream=git(spawn,home,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]);if(!upstream.ok)return yield*bail("current branch has no upstream - set one (git branch --set-upstream-to) or update manually");let before=git(spawn,home,["rev-parse","HEAD"]).out,pull=git(spawn,home,["pull","--ff-only"]);if(!pull.ok)return yield*bail(`git pull --ff-only failed (diverged history?):
|
|
24564
24577
|
${pull.out}`);let after=git(spawn,home,["rev-parse","HEAD"]).out,changed=before!==after;if(changed){let count=git(spawn,home,["rev-list","--count",`${before}..${after}`]).out;yield*log(`Updated ${before.slice(0,7)}..${after.slice(0,7)} (${count} commit(s) from ${upstream.out}).`);let touched=git(spawn,home,["diff","--name-only",before,after]).out.split(`
|
|
24565
|
-
`);if(touched.includes("bun.lock")||touched.includes("package.json")){let
|
|
24578
|
+
`);if(touched.includes("bun.lock")||touched.includes("package.json")){let res=spawn(process.execPath,["install","--frozen-lockfile"],{cwd:home,stdio:"inherit"});if(res.error!==void 0||res.status!==0)return yield*bail(`dependencies changed but 'bun install --frozen-lockfile' failed - fix the error, then run 'bun install --frozen-lockfile' in ${home} and docks-kit sync`,1)}}else yield*log(`Already at the latest version (${after.slice(0,7)}, upstream ${upstream.out}).`);if(skipSync)return yield*log(changed?"Kit updated. Run: docks-kit sync":"Run: docks-kit sync");return yield*log(changed?"Kit updated - running sync with the new version...":"Syncing to deliver plugin and config updates..."),yield*chainSync(spawn,[join10(home,"cli","src","main.ts"),"sync"])}),updatePackage=(home,skipSync,spawn=spawnHost)=>gen2(function*(){let manager=packageManagerForHome(home),beforeVersion=readPackageVersion(home),res=spawn(manager,manager==="bun"?["add","-g","docks-kit@latest"]:["install","-g","docks-kit@latest"],{stdio:"inherit"});if(res.error!==void 0||res.status!==0)return yield*bail(`global package update failed (${manager==="bun"?"bun add -g":"npm install -g"} docks-kit@latest)`,1);let updated=resolveGlobalPackageHome(manager,capturePackageRoot(spawn));if(!updated.ok)return yield*bail(`global package update completed, but the updated package root could not be resolved: ${updated.diagnostic}`,1);let afterVersion=readPackageVersion(updated.home);if(afterVersion==="")return yield*bail(`global package update completed, but ${p(updated.home,"package.json")} has no readable version`,1);let result=packageUpdateResult(beforeVersion,afterVersion,samePackageHome(home,updated.home));if(result.message!=="")yield*log(result.message);if(skipSync)return yield*log(result.alreadyCurrent?"Run: docks-kit sync":"Kit updated. Run: docks-kit sync");let bin=packageBinEntry(updated.home);if(!bin.ok)return yield*bail(bin.diagnostic,1);return yield*log(result.alreadyCurrent?"Syncing to deliver plugin and config updates...":"Kit updated - running sync with the new version..."),yield*chainSync(spawn,[bin.entry,"sync"])}),updateCommand=make20("update",{noSync},(config)=>gen2(function*(){let home=kitHome();if(existsSync10(p(home,".git")))return yield*updateCheckout(home,config.noSync);if(home.includes("node_modules"))return yield*updatePackage(home,config.noSync);return yield*bail(`kit home ${home} is neither a git checkout nor a global package install - reinstall the kit as a git checkout or with 'bun add -g docks-kit'`)})).pipe(withDescription4("Self-update the kit: autodetects the install (git checkout -> ff-only pull; bun/npm global -> @latest), then chains a flag-less sync that also refreshes plugins, even when the kit was already current (--no-sync to skip)."));import{chmodSync as chmodSync6,mkdirSync as mkdirSync6,writeFileSync as writeFileSync3}from"fs";import{createHash as createHash2}from"crypto";import{delimiter as delimiter2}from"path";var THINKING_LADDER=["minimal","low","medium","high","xhigh","max"];function overlayFileName(model){let safe=model.selector.replace(/[^A-Za-z0-9._-]/g,"-"),digest=createHash2("sha256").update(renderFreeOverlay(model)).digest("hex").slice(0,8);return`omp-free-${safe}-${digest}.yml`}var ROLE_ORDER=["smol","designer","plan","commit","task","vision","tiny","default","slow","fable","switch_fable","astra","reviewer","advisor","memory","judge"],FALLBACK_ORDER=["default","task","vision","smol","tiny","commit","switch_fable","fable","astra","reviewer","memory","judge"];function parseFreeModels(catalogJson){if(typeof catalogJson!=="object"||catalogJson===null||Array.isArray(catalogJson))return[];let models=catalogJson.models;if(!Array.isArray(models))return[];let found=[];for(let row of models){if(typeof row!=="object"||row===null||Array.isArray(row))continue;let record=row,selector=record.selector;if(typeof selector!=="string"||selector.length===0)continue;let cost=record.cost;if(typeof cost!=="object"||cost===null||Array.isArray(cost))continue;let charges=cost;if(charges.input!==0||charges.output!==0)continue;let status=record.pricingStatus;if(typeof status==="string"&&status!=="free"&&status!=="unknown")continue;let rawName=record.name,name=typeof rawName==="string"&&rawName.length>0?rawName:selector,rawLevels=record.thinking,thinking=THINKING_LADDER.filter((level)=>Array.isArray(rawLevels)&&rawLevels.includes(level)),rawWindow=record.contextWindow,contextWindow=typeof rawWindow==="number"&&Number.isFinite(rawWindow)?rawWindow:0;found.push({selector,name,thinking,contextWindow})}return found.sort((a,b)=>a.selector<b.selector?-1:a.selector>b.selector?1:0),found}function ladderCeiling(levels){for(let index=THINKING_LADDER.length-1;index>=0;index-=1)if(levels.includes(THINKING_LADDER[index]))return THINKING_LADDER[index];return}function planEffortChoice(levels){let known=THINKING_LADDER.filter((level)=>levels.includes(level)),only=known[0];if(only===void 0)return{kind:"none"};if(known.length===1)return{kind:"fixed",level:only};return{kind:"choose",levels:known,highest:known[known.length-1]}}function renderableLevel(level){return typeof level==="string"&&level.trim()!==""?level:void 0}function roleValue(model){let thinking=renderableLevel(model.thinking);return thinking===void 0?model.selector:`${model.selector}:${thinking}`}function renderFreeOverlay(model){let thinking=renderableLevel(model.thinking),lines=["# Generated per run by docks-kit omp. Edits are overwritten."];if(thinking!==void 0)lines.push(`defaultThinkingLevel: ${thinking}`);lines.push("modelRoles:");for(let role of ROLE_ORDER)lines.push(` ${role}: ${roleValue(model)}`);if(thinking!==void 0)lines.push("task:",` maxEffort: ${thinking}`);lines.push("retry:"," fallbackChains:");for(let chain of FALLBACK_ORDER)lines.push(` ${chain}: []`);for(let level of[void 0,"off",...THINKING_LADDER]){let key=level===void 0?model.selector:`${model.selector}:${level}`;lines.push(` ${JSON.stringify(key)}: []`)}return`${lines.join(`
|
|
24566
24579
|
`)}
|
|
24567
24580
|
`}function buildOmpArgs(overlayPath,session,passthrough){return["launch","--config",overlayPath,"--model",roleValue(session),...passthrough]}var MODEL_ENV_NAMES=["PI_SMOL_MODEL","PI_SLOW_MODEL","PI_PLAN_MODEL"];function ompChildEnvironment(parent,overlayPath,session){let inherited=(parent.PI_CONFIG_FILES??"").split(delimiter2).filter((entry)=>entry!==""),env={...parent,PI_CONFIG_FILES:[...inherited,overlayPath].join(delimiter2)},replaced=[],value=roleValue(session);for(let name of MODEL_ENV_NAMES){let previous=parent[name];if(previous!==void 0&&previous!==""&&previous!==value)replaced.push(name);env[name]=value}return{env,replaced}}import{existsSync as existsSync11,readFileSync as readFileSync9}from"fs";var FAST_ON_TIER="priority",FAST_OFF_TIER="none";function toggleOpenAiFast(configText){let doc=$parseDocument(configText),parseError=doc.errors[0];if(parseError!==void 0)throw Error(`Invalid omp config.yml YAML: ${parseError.message}`);if(doc.contents!==null&&!$isMap(doc.contents))throw Error("omp config.yml root must be a mapping");let tier=doc.get("tier",!0);if(tier!==void 0&&tier!==null&&!$isMap(tier))throw Error("omp config.yml key 'tier' must be a mapping");let current=doc.getIn(["tier","openai"]),previous=typeof current==="string"&¤t!==""?current:FAST_OFF_TIER,next=previous===FAST_ON_TIER?FAST_OFF_TIER:FAST_ON_TIER;return doc.setIn(["tier","openai"],next),{previous,next,text:doc.toString()}}function requireDeployedConfig(configPath){if(!existsSync11(configPath))throw Error(`${configPath} does not exist; run 'docks-kit sync' first`)}function toggleDeployedOpenAiFast(configPath){requireDeployedConfig(configPath);let toggle=toggleOpenAiFast(readFileSync9(configPath,"utf8"));return replaceFile(configPath,toggle.text,{mode:384}),toggle}var model=String10("model").pipe(withDescription3("Free model selector to use and remember for omp sessions"),optional5),pick=Boolean6("pick").pipe(withDescription3("Choose the free model interactively"),withDefault4(!1)),fast=Boolean6("fast").pipe(withDescription3("Toggle fast mode (tier.openai priority/none) for OpenAI and Codex models in the deployed omp config, then exit"),withDefault4(!1)),args2=String9("args").pipe(withDescription2("Arguments forwarded verbatim to omp"),variadic2());function resolveFreeSelector(input,free){let trimmed=input.trim();if(trimmed==="")return{ok:!1,message:"Model selector must not be empty or blank"};let exact=free.find((candidate)=>candidate.selector===trimmed);if(exact!==void 0)return{ok:!0,model:exact};let lowered=trimmed.toLowerCase(),matches=free.filter((candidate)=>candidate.selector.toLowerCase().includes(lowered)),list=free.map((candidate)=>candidate.selector).join(", ");if(matches.length===0)return{ok:!1,message:`Model '${trimmed}' is not in the free catalog. Free models: ${list}`};let only=matches[0];if(matches.length===1&&only!==void 0)return{ok:!0,model:only};return{ok:!1,message:`Model '${trimmed}' is ambiguous; matches: ${matches.map((candidate)=>candidate.selector).join(", ")}. Pass the exact selector.`}}function forwardedProfile(forwarded){let profiles=[];for(let index=0;index<forwarded.length;index++){let arg=forwarded[index],value;if(arg==="--profile")if(value=forwarded[index+1],value===void 0||value.startsWith("-"))value="";else index++;else if(arg.startsWith("--profile="))value=arg.slice(10);else continue;if(value==="")return{ok:!1,message:"--profile requires a profile name"};profiles.push(value)}return{ok:!0,profiles}}var MODEL_SELECTING_FLAGS={"--config":!0,"--model":!0,"--smol":!0,"--slow":!0,"--plan":!0,"--models":!0,"--provider":!0,"--prewalk-into":!0,"--plan-yolo-into":!0};function rejectedForwardedFlag(forwarded){for(let arg of forwarded){let equals=arg.indexOf("="),flag=equals===-1?arg:arg.slice(0,equals);if(MODEL_SELECTING_FLAGS[flag]!==!0)continue;return{ok:!1,message:`Forwarded ${flag} can select a model outside the free session. For a free model, put --model <selector> before other arguments or use --pick; for a paid model, run omp directly.${flag==="--config"?" To load another config, list it in PI_CONFIG_FILES, which omp loads below the overlay.":""}`}}return{ok:!0}}var loadFreeCatalog=(omp,profile)=>gen2(function*(){let catalogArgs=[...profile===void 0?[]:["--profile",profile],"models","--json"],command=`omp ${catalogArgs.join(" ")}`,raw=yield*promise2(()=>capture(omp,catalogArgs));if(raw==="")return yield*bail(`'${command}' returned no output; verify omp runs on this host, then retry`);let parsed;try{parsed=JSON.parse(raw)}catch{return yield*bail(`'${command}' returned output that is not JSON; verify the omp version, then retry`)}let free=parseFreeModels(parsed);if(free.length===0)return yield*bail(`'${command}' listed no free models; verify the omp login, then retry`);return free}),pickLevel=(catalogModel)=>gen2(function*(){let plan=planEffortChoice(catalogModel.thinking);if(plan.kind==="none"){yield*error(`${catalogModel.name} publishes no thinking levels; the model default applies`);return}if(plan.kind==="fixed")return yield*error(`${catalogModel.name} publishes one thinking level: ${plan.level}`),plan.level;return yield*Select({message:"Thinking level for every role",choices:[...plan.levels].reverse().map((level)=>({title:level,value:level,description:level===plan.highest?"highest this model offers":level===plan.levels[0]?"lowest this model offers":""}))})});async function toggleFastUnderLocks(home,agentDir){let configPath=p(agentDir,"config.yml"),err=(line)=>console.error(line);try{requireDeployedConfig(configPath)}catch(error2){return err(error2 instanceof Error?error2.message:String(error2)),2}try{return await withHomeAndFolderLocks(home,[agentDir],err,async()=>{let toggle;try{toggle=toggleDeployedOpenAiFast(configPath)}catch(error2){return err(error2 instanceof Error?error2.message:String(error2)),2}let state=toggle.next===FAST_ON_TIER?"ON":"OFF";return console.log(`omp fast mode ${state} for OpenAI/Codex models: tier.openai ${toggle.previous} -> ${toggle.next} in ${configPath}`),console.log("New omp sessions use it; in a running session, use /fast on|off or restart omp."),0})}catch(error2){if(error2 instanceof ExitError)return error2.code;throw error2}}var ompCommand=make20("omp",{model,pick,fast,args:args2},(config)=>gen2(function*(){let forwardedFlag=rejectedForwardedFlag(config.args);if(!forwardedFlag.ok)return yield*bail(forwardedFlag.message);if(isSome2(config.model)&&config.pick)return yield*bail("Pass either --model <selector> or --pick, not both");if(config.fast){if(isSome2(config.model)||config.pick||config.args.length>0)return yield*bail("--fast toggles fast mode and exits; pass it alone");let home=engineHome(process.env),agentDir=ompPaths({home,env:process.env,platform:process.platform}).agentDir,code=yield*tryPromise2({try:()=>toggleFastUnderLocks(home,agentDir),catch:(error2)=>error2 instanceof Error?error2.message:String(error2)}).pipe(catch_2((message)=>bail(message)));if(code!==0)return yield*sync2(()=>process.exit(code));return}let omp=yield*sync2(()=>which("omp"));if(omp==="")return yield*bail("omp not found on PATH; install omp, then retry",1);let home=engineHome(process.env);if(config.pick&&(!process.stdin.isTTY||!process.stdout.isTTY))return yield*bail("Picking needs a terminal; pass --model <selector> instead");let profile=forwardedProfile(config.args);if(!profile.ok)return yield*bail(profile.message);let candidates=[void 0];for(let name of profile.profiles)if(!candidates.includes(name))candidates.push(name);let catalogs=[];for(let candidate of candidates)catalogs.push(yield*loadFreeCatalog(omp,candidate));let free=catalogs[candidates.indexOf(profile.profiles.at(-1))],chosen;if(isSome2(config.model)){let resolved=resolveFreeSelector(config.model.value,free);if(!resolved.ok)return yield*bail(resolved.message);chosen={selector:resolved.model.selector,thinking:ladderCeiling(resolved.model.thinking)}}if(config.pick){let pickedSelector=yield*Select({message:"Choose the free model for this omp session",choices:free.map((candidate)=>{let ceiling=ladderCeiling(candidate.thinking);return{title:`${candidate.name} \u2014 ${candidate.selector}`,value:candidate.selector,description:ceiling===void 0?`model default thinking; ${candidate.contextWindow} context`:`thinking to ${ceiling}; ${candidate.contextWindow} context`}})}),match=free.find((candidate)=>candidate.selector===pickedSelector);if(match===void 0)return yield*bail(`Model '${pickedSelector}' is not in the free catalog`);chosen={selector:match.selector,thinking:yield*pickLevel(match)}}let session=chosen??(yield*sync2(()=>readOmpSessionModel(home)))??DEFAULT_OMP_SESSION_MODEL;if(!catalogs.every((catalog)=>catalog.some((candidate)=>candidate.selector===session.selector)))return yield*bail(`free model '${session.selector}' is not available in the omp catalog (renamed, repriced, or provider not logged in); log in to its provider or choose another with --model or --pick`);if(chosen!==void 0){let remembered=chosen;yield*sync2(()=>writeOmpSessionModel(home,remembered))}let directory=kitCacheDir(home),overlayPath=p(directory,overlayFileName(session));yield*sync2(()=>{mkdirSync6(directory,{recursive:!0,mode:448}),chmodSync6(directory,448),writeFileSync3(overlayPath,renderFreeOverlay(session),{mode:384}),chmodSync6(overlayPath,384)});let levelText=typeof session.thinking==="string"&&session.thinking.trim()!==""?`${session.thinking} thinking`:"the model default thinking level";yield*error(`Starting omp with ${session.selector} at ${levelText} (session only; deployed config unchanged)`);let childEnvironment=ompChildEnvironment(process.env,overlayPath,session);for(let name of childEnvironment.replaced)yield*error(`${name} is set; this session uses ${childEnvironment.env[name]} instead`);let child=yield*sync2(()=>spawnHost("omp",buildOmpArgs(overlayPath,session,config.args),{stdio:"inherit",env:childEnvironment.env}));if(child.error!==void 0)return yield*bail(`Failed to start omp: ${child.error instanceof Error?child.error.message:String(child.error)}`);return yield*sync2(()=>process.exit(child.status??1))})).pipe(withDescription4("Start omp with every chat-model role set to the remembered free model for this run only. The launcher starts 'omp launch' with an explicit --model, so omp reads a forwarded subcommand name as message text and a resumed session keeps the free model. It rejects forwarded flags that can select another model (--config, --model, --smol, --slow, --plan, --models, --provider, --prewalk-into, --plan-yolo-into); run omp directly for a paid model or a subcommand. The web-search role keeps the deployed provider order, which can include a paid model. No deployed configuration changes; --model or --pick remembers a new free default. Every launch checks the model against the live free catalog of each candidate profile. --fast instead toggles OpenAI/Codex fast mode in the deployed omp config and exits."));import{tmpdir as tmpdir3}from"os";var action=String9("action").pipe(withDescription2("new <label> | remove <path>...")),operands=String9("operands").pipe(withDescription2("The label for new, or the paths for remove"),variadic2()),scratchCommand=make20("scratch",{action,operands},(config)=>gen2(function*(){let home=engineHome();switch(config.action){case"new":{let[label,...rest]=config.operands;if(label===void 0||rest.length>0)return yield*bail("scratch new needs one label");let created;try{created=createScratchDir(scratchRoot(home),label)}catch(cause){return yield*bail(cause instanceof Error?cause.message:String(cause))}yield*log(created);return}case"remove":{if(config.operands.length===0)return yield*bail("scratch remove needs at least one path");let roots=allowedRemovalRoots({home,scratch:scratchRoot(home),tmp:tmpdir3(),platform:process.platform}),refused=!1;for(let operand of config.operands){let outcome=removeTemporaryPath(operand,roots,home);if(outcome.kind==="removed")yield*log(`removed ${outcome.path}`);else refused=!0,yield*log(`refused ${outcome.path}: ${outcome.reason}`)}if(refused)yield*sync2(()=>{process.exitCode=1});return}default:return yield*bail(`Unknown scratch action '${config.action}'; use new or remove`)}})).pipe(withDescription4("Create an agent temporary directory, or remove agent temporary files and directories; removal accepts only paths inside the scratch root, the system temporary directory, or /var/tmp."));import{resolve as resolve9}from"path";import{appendFileSync,lstatSync as lstatSync4,readdirSync as readdirSync3,readFileSync as readFileSync10,readlinkSync as readlinkSync2,realpathSync as realpathSync5,renameSync as renameSync3,statSync as statSync4}from"fs";import{basename as basename4,dirname as dirname7,isAbsolute as isAbsolute6,join as join11,relative as relative2,resolve as resolve8}from"path";var HOUR_MS=3600000,DAY_MS=24*HOUR_MS,WORKTREE_IDLE_MS=24*HOUR_MS,STACK_IDLE_MS=24*HOUR_MS,SCRATCH_IDLE_MS=7*DAY_MS,LOG_ROTATE_BYTES=262144,PROCESS_LIST_UNAVAILABLE="process list unavailable",PROCESS_LIST_UNAVAILABLE_NOTE="process list unavailable; kept every candidate that a running process could use",IN_USE="in use by a running process",DOCKER_PS_FORMAT='{{.ID}}\\t{{.State}}\\t{{.Label "com.docker.compose.project"}}\\t{{.Label "com.docker.compose.project.working_dir"}}',PROTECTED_NAMES=["omp","tern","docks-kit"];function agentWorktreeRoot(home,env){let xdg=env.XDG_DATA_HOME,dataHome=xdg!==void 0&&xdg!==""&&isAbsolute6(xdg)?xdg:join11(home,".local","share");return join11(dataHome,"agent-worktrees")}function tidyLogPath(home){return join11(kitCacheDir(home),"tidy.log")}function normalizePath(path){let resolved=resolve8(path);try{return realpathSync5(resolved)}catch{return resolved}}function errorCode2(cause){return cause instanceof Error&&"code"in cause&&typeof cause.code==="string"?cause.code:void 0}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isMissingCommand(result){let error=result.error;if(error===void 0)return!1;return errorCode2(error)==="ENOENT"||error.message.startsWith("command not found on PATH")}async function runTool(command,args){let result=await spawnProcess(command,args,{stdio:["ignore","pipe","pipe"]}),stderr=result.stderr===""&&result.error!==void 0?result.error.message:result.stderr;return{code:result.exitCode,stdout:result.stdout,stderr,missing:isMissingCommand(result)}}function firstLine(result){let line=[...result.stderr.split(`
|
|
24568
24581
|
`),...result.stdout.split(`
|
|
@@ -24580,10 +24593,10 @@ ${pull.out}`);let after=git(spawn,home,["rev-parse","HEAD"]).out,changed=before!
|
|
|
24580
24593
|
`).filter((line)=>line.trim()!=="").length;if(stash.code===0&&stashes>0)lines.push(`${repo}: stash entries: ${stashes}`);let outside=worktrees.slice(1).filter((entry)=>worktreeRoot===void 0||!isSameOrInside(worktreeRoot,entry.path)).length;if(outside>0)lines.push(`${repo}: linked worktrees outside ${worktreeRoot??"the agent worktree root"}: ${outside}`),lines.push(`hint: docks-kit tidy --repo ${repo}`)}return lines}function recentNames(directory,now,keep){return sortedEntries(directory).filter((name)=>{if(!keep(name))return!1;let stats=lstatOrUndefined(join12(directory,name));return stats!==void 0&&now-stats.mtimeMs<=RECENT_MS})}async function scheduledSection(home,host,now){let lines=[],crontab=await host.run("crontab",["-l"]);if(crontab.code===0){let entries=crontab.stdout.split(`
|
|
24581
24594
|
`).map((line)=>line.trim()).filter((line)=>line!==""&&!line.startsWith("#")).length;if(entries>0)lines.push(`crontab: ${entries} entries`)}let units=process.platform==="darwin"?recentNames(join12(home,"Library","LaunchAgents"),now,(name)=>name.endsWith(".plist")):recentNames(join12(home,".config","systemd","user"),now,(name)=>/\.(service|timer|path)$/.test(name));if(units.length>0){let label=process.platform==="darwin"?"launch agents":"systemd user units";lines.push(`${label} changed in the last 30 days: ${units.join(", ")}`)}return lines}function bunGlobalPackages(home){try{let manifest=JSON.parse(readFileSync11(join12(home,".bun","install","global","package.json"),"utf8")),dependencies=typeof manifest==="object"&&manifest!==null&&"dependencies"in manifest?manifest.dependencies:void 0;return typeof dependencies==="object"&&dependencies!==null?Object.keys(dependencies).sort():[]}catch{return[]}}async function globalSection(home,host,now){let keep=(name)=>name!==".bin"&&name!==".cache",lines=[],bunModules=join12(home,".bun","install","global","node_modules"),bun=bunGlobalPackages(home).filter((name)=>{let stats=lstatOrUndefined(join12(bunModules,name));return stats!==void 0&&now-stats.mtimeMs<=RECENT_MS});if(bun.length>0)lines.push(`bun global installs changed in the last 30 days: ${bun.join(", ")}`);let npmRoot=await host.run("npm",["root","-g"]),root=npmRoot.code===0?npmRoot.stdout.trim():"";if(root!==""){let npm=recentNames(root,now,keep);if(npm.length>0)lines.push(`npm global installs changed in the last 30 days: ${npm.join(", ")}`)}return lines}async function section(title,build){try{let lines=await build();return lines.length===0?void 0:{title,lines}}catch(cause){return{title,lines:[`unavailable: ${errorMessage2(cause)}`]}}}async function buildTidyReport(inputs,host,docker){if(process.platform==="win32")return[{title:"Report",lines:["docks-kit tidy --report supports Linux and macOS"]}];let now=host.now(),home=normalizePath(inputs.home),roots=agentRoots(inputs),rows=await host.processes().catch(()=>{return}),territory=[roots.worktreeRoot,roots.scratchRoot,...TEMP_ROOTS.flatMap((root)=>[root,normalizePath(root)])].filter((path)=>path!==void 0);return(await Promise.all([section("Memory",()=>memorySection(rows,host)),section("Temporary directories",()=>temporarySection(host,now)),section("Processes",()=>processSection(rows,territory,host)),section("Docker",()=>dockerSection(host,docker)),section("Package and tool caches",()=>sizeLines(CACHES,home,host)),section("Trash",()=>trashSection(home,host)),section("Git",()=>gitSection(inputs,roots.worktreeRoot,host)),section("Agent histories",()=>sizeLines(HISTORIES,home,host)),section("Scheduled jobs and services",()=>scheduledSection(home,host,now)),section("Global installs",()=>globalSection(home,host,now))])).filter((entry)=>entry!==void 0)}var apply=Boolean6("apply").pipe(withDescription3("Perform the listed actions"),withDefault4(!1)),repo=String10("repo").pipe(withDescription3("Take worktree candidates only from this repository, at any location"),optional5),report2=Boolean6("report").pipe(withDescription3("Also list other disk and memory use (read-only)"),withDefault4(!1));function planAndApply(perform,inputs,host){return gen2(function*(){let plan=yield*promise2(()=>planTidy(inputs,host));for(let action of plan.actions)yield*log(`${actionVerb(action)} ${actionSubject(action)}: ${action.reason}`);for(let kept of plan.kept)yield*log(`keep ${kept.subject}: ${kept.reason}`);for(let note of plan.notes)yield*log(`note: ${note}`);if(plan.actions.length===0)yield*log("Nothing to tidy.");else if(perform){let outcome=yield*promise2(()=>applyTidy(plan,inputs,host));for(let line of outcome.lines)yield*log(line);if(outcome.failures>0)yield*sync2(()=>{process.exitCode=1})}else{let applyCommand=inputs.repo===void 0?"docks-kit tidy --apply":`docks-kit tidy --repo ${inputs.repo} --apply`;yield*log(`Dry run: ${plan.actions.length} actions. Run '${applyCommand}' to perform them.`)}return plan})}function planAndApplyUnderLock(inputs,host){let path=tidyApplyLockPath(inputs.home);return acquireUseRelease2(promise2(()=>acquireKitLock(path,{waitMs:0})),(result)=>result.kind==="acquired"?planAndApply(!0,inputs,host):log(`another docks-kit tidy run holds ${path}`).pipe(as2(void 0)),(result)=>sync2(()=>{if(result.kind==="acquired")releaseKitLock(result.lock)}))}function runTidy(options,inputs,host){return gen2(function*(){let plan=options.apply?yield*planAndApplyUnderLock(inputs,host):yield*planAndApply(!1,inputs,host);if(plan===void 0||!options.report)return;let sections=yield*promise2(()=>buildTidyReport(inputs,host,plan.docker));for(let section of sections){yield*log(`== ${section.title}`);for(let line of section.lines)yield*log(line)}})}var tidyCommand=make20("tidy",{apply,repo,report:report2},(config)=>gen2(function*(){let host=defaultTidyHost(),home=engineHome(),repository;if(isSome2(config.repo)){let typed=config.repo.value;if(repository=yield*promise2(()=>mainRepository(resolve9(process.cwd(),typed),host)),repository===void 0)return yield*bail(`--repo ${typed} is not a git repository`)}let inputs={home,worktreeRoot:agentWorktreeRoot(home,process.env),scratchRoot:scratchRoot(home),...repository===void 0?{}:{repo:repository}};yield*runTidy({apply:config.apply,report:config.report},inputs,host)})).pipe(withDescription4("List or remove safe agent leftovers (merged idle worktrees, their containers, orphaned processes in agent directories, idle scratch directories); --report lists other disk and memory use."));import path5 from"path";import path2 from"path";import path from"path";import{spawnSync as spawnSync2}from"child_process";import fs from"fs";class PlanRefusal extends TaggedError3()("PlanRefusal",{message:String5}){}class GhError extends TaggedError3()("GhError",{message:String5}){}class GraphqlError extends TaggedError3()("GraphqlError",{message:String5}){}class GitError extends TaggedError3()("GitError",{message:String5}){}class FileError extends TaggedError3()("FileError",{message:String5,code:optional2(String5)}){}class SpawnError extends TaggedError3()("SpawnError",{message:String5}){}var fail11=(message)=>{throw new PlanRefusal({message})},attempt=(thunk)=>try_2({try:thunk,catch:(error)=>error instanceof PlanRefusal?error:new PlanRefusal({message:error instanceof Error?error.message:String(error)})}),field2=(value,key)=>hasProperty(value,key)?value[key]:void 0;var MAX_OUTPUT_MIB=256,errorCode3=(error)=>{let code=hasProperty(error,"code")?error.code:void 0;return isString(code)?code:void 0},errorMessage3=(error)=>error instanceof Error?error.message:String(error);class PlanProcess extends Service()("docks-kit/plan/PlanProcess"){static layer=effect(PlanProcess,sync2(()=>{let run=fn2("PlanProcess.run")(function*(command,args,options={}){let result=yield*try_2({try:()=>spawnSync2(command,[...args],{encoding:options.encoding??"utf8",maxBuffer:MAX_OUTPUT_MIB*1024*1024,cwd:options.cwd,input:options.input,env:options.env,stdio:["pipe","pipe",options.inheritStderr===!0?"inherit":"pipe"]}),catch:(error)=>new SpawnError({message:errorMessage3(error)})});return{status:result.status,stdout:result.stdout??"",stderr:result.stderr??"",error:result.error===void 0?void 0:{code:errorCode3(result.error),message:result.error.message}}});return PlanProcess.of({run})}))}var fileOperation=(operation)=>try_2({try:operation,catch:(error)=>new FileError({message:errorMessage3(error),code:errorCode3(error)})});function checkoutEntry(path){let stats;try{stats=fs.lstatSync(path)}catch{return{kind:"missing"}}if(stats.isSymbolicLink())return{kind:"link",target:fs.readlinkSync(path,{encoding:"buffer"}).toString("latin1")};if(stats.isFile()){let executable=!0;try{fs.accessSync(path,fs.constants.X_OK)}catch{executable=!1}return{kind:"file",executable}}return stats.isDirectory()?{kind:"directory"}:{kind:"special"}}var unlessMissing=(operation)=>fileOperation(()=>{try{return operation()}catch(error){if(errorCode3(error)==="ENOENT")return;throw error}});class PlanFiles extends Service()("docks-kit/plan/PlanFiles"){static layer=effect(PlanFiles,sync2(()=>PlanFiles.of({entry:(path)=>fileOperation(()=>checkoutEntry(path)),readBytes:(path)=>unlessMissing(()=>fs.readFileSync(path)),linkTarget:(path)=>unlessMissing(()=>fs.readlinkSync(path,{encoding:"buffer"})),symlink:(target,path)=>fileOperation(()=>fs.symlinkSync(target,path)),scratchFolder:(label)=>fileOperation(()=>createScratchDir(scratchRoot(engineHome()),label)),removeFolder:(path)=>fileOperation(()=>fs.rmSync(path,{recursive:!0,force:!0})),ensurePrivateDirectory:(path)=>fileOperation(()=>{fs.mkdirSync(path,{recursive:!0,mode:448}),fs.chmodSync(path,448)}),writeFile:(path,data,mode)=>fileOperation(()=>fs.writeFileSync(path,data,mode===void 0?"utf8":{encoding:"utf8",mode})),chmod:(path,mode)=>fileOperation(()=>fs.chmodSync(path,mode)),readFile:(path)=>fileOperation(()=>fs.readFileSync(path,"utf8")),createExclusive:(path,data,mode)=>fileOperation(()=>{let descriptor=fs.openSync(path,"wx",mode);try{fs.writeFileSync(descriptor,data,"utf8")}finally{fs.closeSync(descriptor)}}),remove:(path)=>fileOperation(()=>fs.rmSync(path,{force:!0}))})))}class PlanWaits extends Service()("docks-kit/plan/PlanWaits"){static layer=effect(PlanWaits,sync2(()=>{let sleep=fn2("PlanWaits.sleep")(function*(milliseconds){if(process.env.PLAN_CLI_SKIP_WAITS!=="1")return yield*sleep2(millis(milliseconds));let log=process.env.PLAN_CLI_WAIT_LOG;if(log)yield*fileOperation(()=>fs.appendFileSync(log,`${milliseconds}
|
|
24582
24595
|
`))});return PlanWaits.of({sleep})}))}class PlanRepository extends Service()("docks-kit/plan/PlanRepository"){static layer=effect(PlanRepository,sync2(()=>PlanRepository.of({current:void 0})))}var PlanServicesLive=mergeAll2(PlanProcess.layer,PlanFiles.layer,PlanWaits.layer,PlanRepository.layer);var ARGUMENT_WITHOUT_PROC="the bytes of an argument cannot be recovered without /proc",ARGUMENT_UNMATCHED="the bytes of an argument cannot be recovered: /proc/self/cmdline does not match the arguments",WORKING_FOLDER_LOST="the bytes of the working folder cannot be recovered without /proc or pwd -P",PATHS_ARE_BYTES=process.platform!=="darwin"&&process.platform!=="win32",procFile=(name)=>path.join(process.env.PLAN_CLI_PROC_ROOT||"/proc","self",name),asBytes=(text)=>Buffer.from(text,"utf8").toString("latin1"),utf8Text=(bytes)=>{let text=Buffer.from(bytes,"latin1").toString("utf8");return asBytes(text)===bytes?text:void 0},REPLACEMENTS=/\uFFFD+/g,argumentBytes=fn2("plan.argumentBytes")(function*(args){let commandLine=yield*(yield*PlanFiles).readBytes(procFile("cmdline")).pipe(catchTag2("FileError",()=>undefined_2)),lost=PATHS_ARE_BYTES&&args.some((arg)=>arg.includes("\uFFFD"));if(commandLine===void 0)return lost?{ok:!1,cause:ARGUMENT_WITHOUT_PROC}:{ok:!0,value:args.map(asBytes)};let words=commandLine.toString("latin1").split("\x00").slice(0,-1),tail=args.length===0?[]:words.slice(-args.length),decoded=(word)=>Buffer.from(word,"latin1").toString("utf8").replace(REPLACEMENTS,"\uFFFD");return tail.length===args.length&&tail.every((word,index)=>decoded(word)===args[index]?.replace(REPLACEMENTS,"\uFFFD"))?{ok:!0,value:tail}:lost?{ok:!1,cause:ARGUMENT_UNMATCHED}:{ok:!0,value:args.map(asBytes)}}),workingFolderBytes=fn2("plan.workingFolderBytes")(function*(){let target=yield*(yield*PlanFiles).linkTarget(procFile("cwd")).pipe(catchTag2("FileError",()=>undefined_2));if(target!==void 0)return{ok:!0,value:target.toString("latin1")};let cwd=process.cwd();if(!PATHS_ARE_BYTES||!cwd.includes("\uFFFD"))return{ok:!0,value:asBytes(cwd)};let printed=yield*(yield*PlanProcess).run("pwd",["-P"],{encoding:"latin1"}).pipe(catchTag2("SpawnError",()=>undefined_2)),folder=printed?.error===void 0&&printed?.status===0?printed.stdout.replace(/\n$/,""):"";return folder.startsWith("/")?{ok:!0,value:folder}:{ok:!1,cause:WORKING_FOLDER_LOST}});var BASE_BLOB_USAGE="usage: docks-kit plan base-blob <commit> <path>",CHECKOUT_STATE_USAGE="usage: docks-kit plan checkout-state <checkout>",MAX_LINKS=40,OBJECT_ID=/^[0-9a-f]{40,64}$/,substituted=(result)=>result.stdout.replace(/\n+$/,""),printError=(line)=>sync2(()=>{process.stderr.write(`${line}
|
|
24583
|
-
`)}),runGit=fn2("plan.runGit")(function*(args,options={}){let result=yield*(yield*PlanProcess).run("git",args,{...options,encoding:"latin1",inheritStderr:!0});if(result.error)yield*printError(`git: ${result.error.message}`);return{result,ok:result.error===void 0&&result.status===0}}),rootTree=fn2("plan.rootTree")(function*(commit){let text=utf8Text(commit);if(text!==void 0)return text;let resolved=yield*runGit(["cat-file","--batch-check=%(objectname)"],{input:Buffer.from(`${commit}^{tree}
|
|
24596
|
+
`)}),runGit=fn2("plan.runGit")(function*(args,options={}){let result=yield*(yield*PlanProcess).run("git",args,{...options,encoding:"latin1",inheritStderr:!0});if(result.error)yield*printError(`git: ${result.error.message}`);return{result,ok:result.error===void 0&&result.status===0}}),rootTree=fn2("plan.rootTree")(function*(commit,cwd){let text=utf8Text(commit);if(text!==void 0)return text;let resolved=yield*runGit(["cat-file","--batch-check=%(objectname)"],{cwd,input:Buffer.from(`${commit}^{tree}
|
|
24584
24597
|
`,"latin1")});if(!resolved.ok)return;let line=substituted(resolved.result);if(OBJECT_ID.test(line))return line;yield*sync2(()=>{process.stderr.write(Buffer.from(`base-blob: ${line}
|
|
24585
|
-
`,"latin1"))});return}),treeEntry=fn2("plan.treeEntry")(function*(tree,name){let listed=yield*runGit(["ls-tree","-z","--full-tree",tree]);if(!listed.ok)return 2;for(let record of listed.result.stdout.split("\x00")){let tab=record.indexOf("\t");if(tab<0||record.slice(tab+1)!==name)continue;let[mode="",,oid=""]=record.slice(0,tab).split(" ");return{mode,oid}}return}),
|
|
24586
|
-
`)}),0;
|
|
24598
|
+
`,"latin1"))});return}),treeEntry=fn2("plan.treeEntry")(function*(tree,name,cwd){let listed=yield*runGit(["ls-tree","-z","--full-tree",tree],{cwd});if(!listed.ok)return 2;for(let record of listed.result.stdout.split("\x00")){let tab=record.indexOf("\t");if(tab<0||record.slice(tab+1)!==name)continue;let[mode="",,oid=""]=record.slice(0,tab).split(" ");return{mode,oid}}return}),resolveBaseBlob=fn2("plan.resolveBaseBlob")(function*(commit,target,cwd){let root,trees=[],rest=target,links=0;while(rest!==""){let part,slash=rest.indexOf("/");if(slash>=0)part=rest.slice(0,slash),rest=rest.slice(slash+1)||".";else part=rest,rest="";if(part===""||part===".")continue;if(part===".."){if(trees.length===0)return 1;trees.pop();continue}if(root??=yield*rootTree(commit,cwd),root===void 0)return 2;let entry=yield*treeEntry(trees.at(-1)??root,part,cwd);if(entry===2)return 2;if(entry===void 0)return 1;switch(entry.mode){case"040000":trees.push(entry.oid);break;case"120000":{if(links+=1,links>MAX_LINKS)return 1;let blob=yield*runGit(["cat-file","blob",entry.oid],{cwd});if(!blob.ok)return 2;let linkTarget=blob.result.stdout;if(linkTarget===""||linkTarget.startsWith("/"))return 1;rest=rest?`${linkTarget}/${rest}`:linkTarget;break}case"100644":case"100755":if(rest)return 1;return entry.oid;default:return 1}}return 1}),baseBlob=fn2("plan.baseBlob")(function*(args){if(args.length!==2||!args[0])return yield*printError(BASE_BLOB_USAGE),2;let bytes=yield*argumentBytes(args);if(!bytes.ok)return yield*printError(`base-blob: ${bytes.cause}`),2;let[commit="",target=""]=bytes.value,blob=yield*resolveBaseBlob(commit,target);if(blob===1||blob===2)return blob;return yield*sync2(()=>{process.stdout.write(`${blob}
|
|
24599
|
+
`)}),0});var gitFolder=fn2("plan.gitFolder")(function*(folders,bytes){let text=utf8Text(bytes);if(text!==void 0)return text;let files=yield*PlanFiles,folder=folders.folder??(yield*files.scratchFolder("plan-git-folders"));folders.folder=folder;let link=path2.join(folder,String(folders.links));return folders.links+=1,yield*files.symlink(Buffer.from(bytes,"latin1"),link),link}),quotedPath=(file)=>`"${file.replace(/[\\"]/g,"\\$&").replace(/\r/g,"\\r")}"`,checkoutListing=fn2("plan.checkoutListing")(function*(checkout,folders){let files=yield*PlanFiles,env={...process.env,LC_ALL:"C"},top=yield*runGit(["-C",checkout,"rev-parse","--show-toplevel"],{env});if(!top.ok)return 2;let topPath=substituted(top.result),topFolder=yield*gitFolder(folders,topPath),listed=yield*runGit(["-C",topFolder,"ls-files","-z","--cached","--others","--exclude-standard"],{env});if(!listed.ok)return 2;if(/[\t\n]/.test(listed.result.stdout))return yield*printError("checkout-state: a path holds a tab or a newline"),1;let names=listed.result.stdout.split("\x00");names.pop();let paths=[...new Set(names.map((name)=>name.replace(/\/$/,"")))].sort(),lines=[],regular=[],executable=[];for(let name of paths){let file=`${topPath}/${name}`,entry=yield*files.entry(Buffer.from(file,"latin1"));switch(entry.kind){case"link":if(entry.target.includes(`
|
|
24587
24600
|
`))return yield*printError("checkout-state: a link target holds a newline"),1;lines.push(`${name} link ${entry.target}`);break;case"file":regular.push(name),executable.push(entry.executable?"x":"");break;case"directory":{let folder=yield*gitFolder(folders,file),sub=yield*runGit(["-C",folder,"rev-parse","--show-toplevel"],{env});if(!sub.ok)return 2;if(substituted(sub.result)!==file){lines.push(`${name} special`);break}let head=yield*runGit(["-C",folder,"rev-parse","HEAD"],{env});if(!head.ok)return 2;lines.push(`${name} submodule ${substituted(head.result)}`);let nested=yield*checkoutListing(folder,folders);if(nested===1||nested===2)return nested;for(let line of nested)lines.push(`${name}/${line}`);break}case"special":lines.push(`${name} special`);break;case"missing":lines.push(`${name} missing`);break}}if(regular.length>0){let input=Buffer.from(regular.map((name)=>`${quotedPath(name)}
|
|
24588
24601
|
`).join(""),"latin1"),hashed=yield*runGit(["-C",topFolder,"hash-object","--no-filters","--stdin-paths"],{env,input});if(!hashed.ok)return 2;let blobs=hashed.result.stdout.split(`
|
|
24589
24602
|
`);regular.forEach((name,index)=>lines.push(`${name} ${blobs[index]??""} ${executable[index]}`.replace(/\t$/,"")))}return lines.sort()}),listCheckout=fn2("plan.listCheckout")(function*(checkout){let bytes=yield*argumentBytes([checkout]);if(!bytes.ok)return yield*printError(`checkout-state: ${bytes.cause}`),1;let folderBytes=bytes.value[0]??"";if(utf8Text(folderBytes)===void 0&&!path2.isAbsolute(folderBytes)){let working=yield*workingFolderBytes();if(!working.ok)return yield*printError(`checkout-state: ${working.cause}`),1;folderBytes=`${working.value}/${folderBytes}`}return yield*acquireUseRelease2(sync2(()=>({folder:void 0,links:0})),(folders)=>gitFolder(folders,folderBytes).pipe(flatMap3((folder)=>checkoutListing(folder,folders))),({folder})=>folder===void 0?void_3:PlanFiles.use((files)=>files.removeFolder(folder)))}),checkoutState=fn2("plan.checkoutState")(function*(args){if(args.length!==1||!args[0])return yield*printError(CHECKOUT_STATE_USAGE),2;let listing=yield*listCheckout(args[0]).pipe(catchTags2({FileError:(error)=>printError(error.message).pipe(as2(2)),SpawnError:(error)=>printError(error.message).pipe(as2(2))}));if(listing===1||listing===2)return listing;let output=Buffer.from(listing.map((line)=>`${line}
|
|
@@ -24681,8 +24694,8 @@ ${`
|
|
|
24681
24694
|
`),1;return yield*writeStdout2(`skill-guard PASSED: ${checked} skill(s), ${warns} warning(s)
|
|
24682
24695
|
`),0}),printUsage3=(error)=>writeStderr2(`${error.usage}
|
|
24683
24696
|
`).pipe(as2(2)),printCrash2=(error)=>writeStderr2(`docks-kit skill: ${error.message}
|
|
24684
|
-
`).pipe(as2(1)),runSkill=fn2("skills.run")(function*(args){let[command,...rest]=args;return yield*(command==="score"?score(rest):command==="guard"?guard(rest):fail7(new SkillUsage({usage:USAGE7}))).pipe(catchTags2({SkillUsage:printUsage3,FileError:printCrash2}))});var args5=String9("args").pipe(withDescription2("guard [--strict] <skill-dir|skills-root>..., score [--per-file] [skills-root] (default .agents/skills)"),variadic2()),skillCommand=make20("skill",{args:args5},(config)=>runSkill(config.args).pipe(flatMap3((code)=>sync2(()=>{process.exitCode=code})),provide3(SkillFiles.layer))).pipe(withDescription4("SKILL.md checks of the write-skill and skill-maintenance skills: the portable validator and the 16-point docks rubric score."));var flagMetadata=(param)=>{let current=param,repeatable=!1;while(typeof current==="object"&¤t!==null){if(!("_tag"in current))break;if(current._tag==="Variadic")repeatable=!0;if(current._tag!=="Single"){if(!("param"in current))break;current=current.param;continue}if(!("name"in current)||typeof current.name!=="string")throw Error("Effect CLI exposed a flag without a string name");if(!("aliases"in current)||!Array.isArray(current.aliases)||!current.aliases.every((alias)=>typeof alias==="string"))throw Error(`Effect CLI exposed invalid aliases for --${current.name}`);if(!("primitiveType"in current)||typeof current.primitiveType!=="object"||current.primitiveType===null||!("_tag"in current.primitiveType)||typeof current.primitiveType._tag!=="string")throw Error(`Effect CLI exposed no primitive type for --${current.name}`);let aliases=current.aliases;return{name:current.name,aliases,takesValue:current.primitiveType._tag!=="Boolean",repeatable}}throw Error("Effect CLI exposed an unsupported flag parameter")},flagSurface=(params)=>{let longFlags=[],aliases=new Map,valueFlags=[],repeatableFlags=[];for(let param of params){let metadata=flagMetadata(param),longName=`--${metadata.name}`;if(longFlags.push(longName),metadata.takesValue)valueFlags.push(longName);if(metadata.repeatable)repeatableFlags.push(longName);for(let alias of metadata.aliases)aliases.set(`-${alias}`,longName)}return{longFlags,aliases,valueFlags,repeatableFlags}},buildCommandSurface=(command)=>{if(!("config"in command))throw Error(`Effect CLI did not expose flags for '${command.name}'`);let config=command.config;if(typeof config!=="object"||config===null||!("flags"in config)||!Array.isArray(config.flags))throw Error(`Effect CLI did not expose flags for '${command.name}'`);return flagSurface(config.flags)},globalSurface=(builtIns)=>{if(!Array.isArray(builtIns))throw Error("Effect CLI did not expose its built-in global flags");let actionFlags=new Set,flags=builtIns.map((builtIn)=>{if(typeof builtIn!=="object"&&typeof builtIn!=="function"||builtIn===null||!("flag"in builtIn)||!("_tag"in builtIn)||typeof builtIn._tag!=="string")throw Error("Effect CLI exposed an unsupported built-in global flag");if(builtIn._tag==="Action"){let metadata=flagMetadata(builtIn.flag);if(!metadata.takesValue)actionFlags.add(`--${metadata.name}`)}return builtIn.flag});return{...flagSurface(flags),actionFlags}},buildSurfaces=(commands,builtIns)=>({commandSurfaces:new Map(commands.map((command)=>[command.name,buildCommandSurface(command)])),globalSurface:globalSurface(builtIns)}),flagNameOf=(token)=>{let equals=token.indexOf("=");return equals===-1?token:token.slice(0,equals)},canonicalFlagName=(name,surface)=>{if(surface===void 0)return;let aliased=surface.aliases.get(name);if(aliased!==void 0)return aliased;return surface.longFlags.includes(name)?name:void 0},declaredFlagName=(name,commandSurface,surfaces)=>canonicalFlagName(name,commandSurface)??canonicalFlagName(name,surfaces.globalSurface),declaredInAnySurface=(name,surfaces)=>{if(canonicalFlagName(name,surfaces.globalSurface)!==void 0)return!0;for(let surface of surfaces.commandSurfaces.values())if(canonicalFlagName(name,surface)!==void 0)return!0;return!1},takesValueInAnySurface=(name,surfaces)=>{let globalName=canonicalFlagName(name,surfaces.globalSurface);if(globalName!==void 0&&surfaces.globalSurface.valueFlags.includes(globalName))return!0;for(let surface of surfaces.commandSurfaces.values()){let canonicalName=canonicalFlagName(name,surface);if(canonicalName!==void 0&&surface.valueFlags.includes(canonicalName))return!0}return!1},subcommandName=(args,surfaces)=>{for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")return;let name=flagNameOf(token);if(token===name&&takesValueInAnySurface(name,surfaces)){let next=args[index+1];if(next==="--")return;if(next!==void 0&&!(next.startsWith("-")&&declaredInAnySurface(flagNameOf(next),surfaces))){index++;continue}}if(!token.startsWith("-"))return token}return},EFFECT_BOOLEAN_LITERALS={true:!0,yes:!0,on:!0,"1":!0,y:!0,false:!0,no:!0,off:!0,"0":!0,n:!0},scanArgv=(args,commandSurface,surfaces)=>{let flags=[],normalizations=[],seenActions=new Set;for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")break;if(!token.startsWith("-"))continue;let name=flagNameOf(token),canonicalName=declaredFlagName(name,commandSurface,surfaces),hasValue=token.includes("="),takesValue=canonicalName!==void 0&&(commandSurface?.valueFlags.includes(canonicalName)===!0||surfaces.globalSurface.valueFlags.includes(canonicalName));if(!hasValue&&takesValue){let next=args[index+1],nextIsRecognizedFlag=next!==void 0&&next.startsWith("-")&&declaredFlagName(flagNameOf(next),commandSurface,surfaces)!==void 0;if(next!==void 0&&next!=="--"&&!nextIsRecognizedFlag){if(hasValue=!0,next.startsWith("-"))normalizations.push({flagIndex:index,valueIndex:index+1,token:`${token}=${next}`});index++}}if(canonicalName!==void 0&&!takesValue&&!hasValue){let next=args[index+1];if(next!==void 0&&Object.hasOwn(EFFECT_BOOLEAN_LITERALS,next))hasValue=!0,index++}if(canonicalName!==void 0&&!hasValue&&surfaces.globalSurface.actionFlags.has(canonicalName)){if(seenActions.has(canonicalName))normalizations.push({flagIndex:index,valueIndex:index,token:void 0});seenActions.add(canonicalName)}flags.push({token,name,canonicalName,hasValue,takesValue})}return{flags,normalizations}},normalizeArgv=(args,normalizations)=>{if(normalizations.length===0)return args;let normalized=[],normalizationIndex=0;for(let index=0;index<args.length;index++){let normalization=normalizations[normalizationIndex];if(normalization!==void 0&&normalization.flagIndex===index){if(normalization.token!==void 0)normalized.push(normalization.token);index=normalization.valueIndex,normalizationIndex++;continue}normalized.push(args[index])}return normalized},spliceOmpBoundary=(args,surfaces)=>{let surface=surfaces.commandSurfaces.get("omp"),ompIndex=-1;for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")return args;let name=flagNameOf(token);if(token===name&&takesValueInAnySurface(name,surfaces)){let next=args[index+1];if(next==="--")return args;if(next!==void 0&&!(next.startsWith("-")&&declaredInAnySurface(flagNameOf(next),surfaces))){index++;continue}}if(!token.startsWith("-")){ompIndex=index;break}}if(ompIndex===-1||args[ompIndex]!=="omp")return args;for(let index=ompIndex+1;index<args.length;index++){let token=args[index];if(token==="--")return args;if(!token.startsWith("-"))return[...args.slice(0,index),"--",...args.slice(index)];let name=flagNameOf(token),canonical=declaredFlagName(name,surface,surfaces);if(canonical===void 0)return[...args.slice(0,index),"--",...args.slice(index)];if((surface?.valueFlags.includes(canonical)===!0||surfaces.globalSurface.valueFlags.includes(canonical))&&!token.includes("=")){let next=args[index+1];if(next!==void 0&&!(next.startsWith("-")&&declaredFlagName(flagNameOf(next),surface,surfaces)!==void 0))index++}}return args};var validateScannedArgv=(subcommand,commandSurface,surfaces,flags)=>{if(subcommand!==void 0&&commandSurface===void 0&&flags.some((flag)=>flag.canonicalName===void 0))return`unknown command '${subcommand}'`;for(let flag of flags){if(flag.canonicalName!==void 0)continue;let scope=subcommand===void 0?"":` for '${subcommand}'`;return`unknown flag ${flag.token}${scope}`}for(let flag of flags){if(!flag.hasValue||flag.takesValue)continue;return`flag ${flag.name} does not take a value`}let seen=new Set;for(let flag of flags){let name=flag.canonicalName;if(name===void 0)continue;if(!(commandSurface?.repeatableFlags.includes(name)===!0||surfaces.globalSurface.repeatableFlags.includes(name)||surfaces.globalSurface.actionFlags.has(name))&&seen.has(name))return`flag ${name} was given more than once`;seen.add(name)}return};var COMMANDS2=[syncCommand,updateCommand,toolchainCommand,docsCommand,ompCommand,scratchCommand,tidyCommand,planCommand,agentDocsCommand,skillCommand],SURFACES=buildSurfaces(COMMANDS2,BuiltIns),reject=(message)=>({kind:"reject",message,exitCode:2}),subcommandName2=(args)=>subcommandName(args,SURFACES),RAW_PASSTHROUGH=new Set(["plan","agent-docs","skill"]),spliceRawBoundary=(args,word)=>{let index=args.findIndex((token,at)=>token===word&&subcommandName2(args.slice(0,at+1))===word);return[...args.slice(0,index+1),"--",...args.slice(index+1)]},passthroughBoundary=(args)=>{let word=subcommandName2(args);if(word==="omp")return spliceOmpBoundary(args,SURFACES);return word!==void 0&&RAW_PASSTHROUGH.has(word)?spliceRawBoundary(args,word):args},prepareArgv=(args)=>{let boundaryArgs=passthroughBoundary(args),subcommand=subcommandName2(boundaryArgs),commandSurface=subcommand===void 0?void 0:SURFACES.commandSurfaces.get(subcommand),{flags,normalizations}=scanArgv(boundaryArgs,commandSurface,SURFACES),message=validateScannedArgv(subcommand,commandSurface,SURFACES,flags);if(message!==void 0)return reject(message);return{kind:"accept",args:normalizeArgv(boundaryArgs,normalizations)}};var root=make20("docks-kit",{},()=>gen2(function*(){yield*log("docks-kit \u2014 portable AI coding agent config kit"),yield*log(""),yield*log(" docks-kit sync [--dry-run] deploy the SoT to this machine"),yield*log(" docks-kit update [--no-sync] self-update the kit, then sync"),yield*log(" docks-kit toolchain [check|ensure|outdated] verified-version floors"),yield*log(" docks-kit docs [topic] self-documentation"),yield*log(" docks-kit omp [--model|--pick] [...] free-model omp session"),yield*log(" docks-kit scratch new|remove agent temporary files and directories"),yield*log(" docks-kit tidy [--apply] [--repo <path>] [--report] remove safe agent leftovers"),yield*log(" docks-kit plan <command> [...] GitHub-issue plan records (plan-manager helper)"),yield*log(" docks-kit agent-docs <helper> <command> [...] agent-doc checks (agent-first-setup helpers)"),yield*log(" docks-kit skill guard|score [...] SKILL.md validator and rubric score (write-skill helpers)"),yield*log(""),yield*log("Run 'docks-kit --help' for full option listings (also: --wizard, --completions)."),yield*log("No-Bun recovery path: use a platform release binary.")})).pipe(withDescription4("Portable AI coding agent config kit \u2014 SoT sync engine + helpers for Oh My Pi."),withSubcommands(COMMANDS2)),bareVersionFormatter={...defaultFormatter2(),formatVersion:(_name,version)=>version};if(process.env.DOCKS_KIT_ENGINE==="native-raw"){let rawArgs=process.argv.slice(2),rawOperation=rawArgs.join(" ")||"default";process.once("SIGINT",()=>process.exit(130)),process.once("SIGTERM",()=>process.exit(143));try{process.exit(await runEngineNative(rawArgs,void 0,{envGlobals:!0}))}catch(error){let detail="unknown error";if(error instanceof Error&&error.message!=="")detail=error.message;else if(typeof error==="string"&&error!=="")detail=error;process.stderr.write(`docks-kit raw operation '${rawOperation}' failed: ${detail}
|
|
24697
|
+
`).pipe(as2(1)),runSkill=fn2("skills.run")(function*(args){let[command,...rest]=args;return yield*(command==="score"?score(rest):command==="guard"?guard(rest):fail7(new SkillUsage({usage:USAGE7}))).pipe(catchTags2({SkillUsage:printUsage3,FileError:printCrash2}))});var args5=String9("args").pipe(withDescription2("guard [--strict] <skill-dir|skills-root>..., score [--per-file] [skills-root] (default .agents/skills)"),variadic2()),skillCommand=make20("skill",{args:args5},(config)=>runSkill(config.args).pipe(flatMap3((code)=>sync2(()=>{process.exitCode=code})),provide3(SkillFiles.layer))).pipe(withDescription4("SKILL.md checks of the write-skill and skill-maintenance skills: the portable validator and the 16-point docks rubric score."));var flagMetadata=(param)=>{let current=param,repeatable=!1;while(typeof current==="object"&¤t!==null){if(!("_tag"in current))break;if(current._tag==="Variadic")repeatable=!0;if(current._tag!=="Single"){if(!("param"in current))break;current=current.param;continue}if(!("name"in current)||typeof current.name!=="string")throw Error("Effect CLI exposed a flag without a string name");if(!("aliases"in current)||!Array.isArray(current.aliases)||!current.aliases.every((alias)=>typeof alias==="string"))throw Error(`Effect CLI exposed invalid aliases for --${current.name}`);if(!("primitiveType"in current)||typeof current.primitiveType!=="object"||current.primitiveType===null||!("_tag"in current.primitiveType)||typeof current.primitiveType._tag!=="string")throw Error(`Effect CLI exposed no primitive type for --${current.name}`);let aliases=current.aliases;return{name:current.name,aliases,takesValue:current.primitiveType._tag!=="Boolean",repeatable}}throw Error("Effect CLI exposed an unsupported flag parameter")},flagSurface=(params)=>{let longFlags=[],aliases=new Map,valueFlags=[],repeatableFlags=[];for(let param of params){let metadata=flagMetadata(param),longName=`--${metadata.name}`;if(longFlags.push(longName),metadata.takesValue)valueFlags.push(longName);if(metadata.repeatable)repeatableFlags.push(longName);for(let alias of metadata.aliases)aliases.set(`-${alias}`,longName)}return{longFlags,aliases,valueFlags,repeatableFlags}},buildCommandSurface=(command)=>{if(!("config"in command))throw Error(`Effect CLI did not expose flags for '${command.name}'`);let config=command.config;if(typeof config!=="object"||config===null||!("flags"in config)||!Array.isArray(config.flags))throw Error(`Effect CLI did not expose flags for '${command.name}'`);return flagSurface(config.flags)},globalSurface=(builtIns)=>{if(!Array.isArray(builtIns))throw Error("Effect CLI did not expose its built-in global flags");let actionFlags=new Set,flags=builtIns.map((builtIn)=>{if(typeof builtIn!=="object"&&typeof builtIn!=="function"||builtIn===null||!("flag"in builtIn)||!("_tag"in builtIn)||typeof builtIn._tag!=="string")throw Error("Effect CLI exposed an unsupported built-in global flag");if(builtIn._tag==="Action"){let metadata=flagMetadata(builtIn.flag);if(!metadata.takesValue)actionFlags.add(`--${metadata.name}`)}return builtIn.flag});return{...flagSurface(flags),actionFlags}},buildSurfaces=(commands,builtIns)=>({commandSurfaces:new Map(commands.map((command)=>[command.name,buildCommandSurface(command)])),globalSurface:globalSurface(builtIns)}),flagNameOf=(token)=>{let equals=token.indexOf("=");return equals===-1?token:token.slice(0,equals)},canonicalFlagName=(name,surface)=>{if(surface===void 0)return;let aliased=surface.aliases.get(name);if(aliased!==void 0)return aliased;return surface.longFlags.includes(name)?name:void 0},declaredFlagName=(name,commandSurface,surfaces)=>canonicalFlagName(name,commandSurface)??canonicalFlagName(name,surfaces.globalSurface),declaredInAnySurface=(name,surfaces)=>{if(canonicalFlagName(name,surfaces.globalSurface)!==void 0)return!0;for(let surface of surfaces.commandSurfaces.values())if(canonicalFlagName(name,surface)!==void 0)return!0;return!1},takesValueInAnySurface=(name,surfaces)=>{let globalName=canonicalFlagName(name,surfaces.globalSurface);if(globalName!==void 0&&surfaces.globalSurface.valueFlags.includes(globalName))return!0;for(let surface of surfaces.commandSurfaces.values()){let canonicalName=canonicalFlagName(name,surface);if(canonicalName!==void 0&&surface.valueFlags.includes(canonicalName))return!0}return!1},subcommandName=(args,surfaces)=>{for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")return;let name=flagNameOf(token);if(token===name&&takesValueInAnySurface(name,surfaces)){let next=args[index+1];if(next==="--")return;if(next!==void 0&&!(next.startsWith("-")&&declaredInAnySurface(flagNameOf(next),surfaces))){index++;continue}}if(!token.startsWith("-"))return token}return},EFFECT_BOOLEAN_LITERALS={true:!0,yes:!0,on:!0,"1":!0,y:!0,false:!0,no:!0,off:!0,"0":!0,n:!0},scanArgv=(args,commandSurface,surfaces)=>{let flags=[],normalizations=[],seenActions=new Set;for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")break;if(!token.startsWith("-"))continue;let name=flagNameOf(token),canonicalName=declaredFlagName(name,commandSurface,surfaces),hasValue=token.includes("="),takesValue=canonicalName!==void 0&&(commandSurface?.valueFlags.includes(canonicalName)===!0||surfaces.globalSurface.valueFlags.includes(canonicalName));if(!hasValue&&takesValue){let next=args[index+1],nextIsRecognizedFlag=next!==void 0&&next.startsWith("-")&&declaredFlagName(flagNameOf(next),commandSurface,surfaces)!==void 0;if(next!==void 0&&next!=="--"&&!nextIsRecognizedFlag){if(hasValue=!0,next.startsWith("-"))normalizations.push({flagIndex:index,valueIndex:index+1,token:`${token}=${next}`});index++}}if(canonicalName!==void 0&&!takesValue&&!hasValue){let next=args[index+1];if(next!==void 0&&Object.hasOwn(EFFECT_BOOLEAN_LITERALS,next))hasValue=!0,index++}if(canonicalName!==void 0&&!hasValue&&surfaces.globalSurface.actionFlags.has(canonicalName)){if(seenActions.has(canonicalName))normalizations.push({flagIndex:index,valueIndex:index,token:void 0});seenActions.add(canonicalName)}flags.push({token,name,canonicalName,hasValue,takesValue})}return{flags,normalizations}},normalizeArgv=(args,normalizations)=>{if(normalizations.length===0)return args;let normalized=[],normalizationIndex=0;for(let index=0;index<args.length;index++){let normalization=normalizations[normalizationIndex];if(normalization!==void 0&&normalization.flagIndex===index){if(normalization.token!==void 0)normalized.push(normalization.token);index=normalization.valueIndex,normalizationIndex++;continue}normalized.push(args[index])}return normalized},spliceOmpBoundary=(args,surfaces)=>{let surface=surfaces.commandSurfaces.get("omp"),ompIndex=-1;for(let index=0;index<args.length;index++){let token=args[index];if(token==="--")return args;let name=flagNameOf(token);if(token===name&&takesValueInAnySurface(name,surfaces)){let next=args[index+1];if(next==="--")return args;if(next!==void 0&&!(next.startsWith("-")&&declaredInAnySurface(flagNameOf(next),surfaces))){index++;continue}}if(!token.startsWith("-")){ompIndex=index;break}}if(ompIndex===-1||args[ompIndex]!=="omp")return args;for(let index=ompIndex+1;index<args.length;index++){let token=args[index];if(token==="--")return args;if(!token.startsWith("-"))return[...args.slice(0,index),"--",...args.slice(index)];let name=flagNameOf(token),canonical=declaredFlagName(name,surface,surfaces);if(canonical===void 0)return[...args.slice(0,index),"--",...args.slice(index)];if((surface?.valueFlags.includes(canonical)===!0||surfaces.globalSurface.valueFlags.includes(canonical))&&!token.includes("=")){let next=args[index+1];if(next!==void 0&&!(next.startsWith("-")&&declaredFlagName(flagNameOf(next),surface,surfaces)!==void 0))index++}}return args};var validateScannedArgv=(subcommand,commandSurface,surfaces,flags)=>{if(subcommand!==void 0&&commandSurface===void 0&&flags.some((flag)=>flag.canonicalName===void 0))return`unknown command '${subcommand}'`;for(let flag of flags){if(flag.canonicalName!==void 0)continue;let scope=subcommand===void 0?"":` for '${subcommand}'`;return`unknown flag ${flag.token}${scope}`}for(let flag of flags){if(!flag.hasValue||flag.takesValue)continue;return`flag ${flag.name} does not take a value`}let seen=new Set;for(let flag of flags){let name=flag.canonicalName;if(name===void 0)continue;if(!(commandSurface?.repeatableFlags.includes(name)===!0||surfaces.globalSurface.repeatableFlags.includes(name)||surfaces.globalSurface.actionFlags.has(name))&&seen.has(name))return`flag ${name} was given more than once`;seen.add(name)}return};var COMMANDS2=[syncCommand,updateCommand,toolchainCommand,docsCommand,ompCommand,scratchCommand,tidyCommand,planCommand,agentDocsCommand,skillCommand],SURFACES=buildSurfaces(COMMANDS2,BuiltIns),reject=(message)=>({kind:"reject",message,exitCode:2}),subcommandName2=(args)=>subcommandName(args,SURFACES),RAW_PASSTHROUGH=new Set(["plan","agent-docs","skill"]),spliceRawBoundary=(args,word)=>{let index=args.findIndex((token,at)=>token===word&&subcommandName2(args.slice(0,at+1))===word);return[...args.slice(0,index+1),"--",...args.slice(index+1)]},passthroughBoundary=(args)=>{let word=subcommandName2(args);if(word==="omp")return spliceOmpBoundary(args,SURFACES);return word!==void 0&&RAW_PASSTHROUGH.has(word)?spliceRawBoundary(args,word):args},prepareArgv=(args)=>{let boundaryArgs=passthroughBoundary(args),subcommand=subcommandName2(boundaryArgs),commandSurface=subcommand===void 0?void 0:SURFACES.commandSurfaces.get(subcommand),{flags,normalizations}=scanArgv(boundaryArgs,commandSurface,SURFACES),message=validateScannedArgv(subcommand,commandSurface,SURFACES,flags);if(message!==void 0)return reject(message);return{kind:"accept",args:normalizeArgv(boundaryArgs,normalizations)}};var root=make20("docks-kit",{},()=>gen2(function*(){yield*log("docks-kit \u2014 portable AI coding agent config kit"),yield*log(""),yield*log(" docks-kit sync [--dry-run] deploy the SoT to this machine"),yield*log(" docks-kit update [--no-sync] self-update the kit, then sync"),yield*log(" docks-kit toolchain [check|ensure|outdated] verified-version floors"),yield*log(" docks-kit docs [topic] self-documentation"),yield*log(" docks-kit omp [--model|--pick] [...] free-model omp session"),yield*log(" docks-kit scratch new|remove agent temporary files and directories"),yield*log(" docks-kit tidy [--apply] [--repo <path>] [--report] remove safe agent leftovers"),yield*log(" docks-kit plan <command> [...] GitHub-issue plan records (plan-manager helper)"),yield*log(" docks-kit agent-docs <helper> <command> [...] agent-doc checks (agent-first-setup helpers)"),yield*log(" docks-kit skill guard|score [...] SKILL.md validator and rubric score (write-skill helpers)"),yield*log(""),yield*log("Run 'docks-kit --help' for full option listings (also: --wizard, --completions).")})).pipe(withDescription4("Portable AI coding agent config kit \u2014 SoT sync engine + helpers for Oh My Pi."),withSubcommands(COMMANDS2)),bareVersionFormatter={...defaultFormatter2(),formatVersion:(_name,version)=>version};if(process.env.DOCKS_KIT_ENGINE==="native-raw"){let rawArgs=process.argv.slice(2),rawOperation=rawArgs.join(" ")||"default";process.once("SIGINT",()=>process.exit(130)),process.once("SIGTERM",()=>process.exit(143));try{process.exit(await runEngineNative(rawArgs,void 0,{envGlobals:!0}))}catch(error){let detail="unknown error";if(error instanceof Error&&error.message!=="")detail=error.message;else if(typeof error==="string"&&error!=="")detail=error;process.stderr.write(`docks-kit raw operation '${rawOperation}' failed: ${detail}
|
|
24685
24698
|
`),process.exit(1)}}var prepared=prepareArgv(process.argv.slice(2));if(prepared.kind==="reject")process.stderr.write(`${prepared.message}
|
|
24686
24699
|
`),process.exit(prepared.exitCode);runWith2(root,{version:GENERATED_PACKAGE_VERSION})(prepared.args).pipe(provide3(mergeAll2(layer11,EngineServicesLive,layer(bareVersionFormatter))),runMain2);
|
|
24687
24700
|
|
|
24688
|
-
//# debugId=
|
|
24701
|
+
//# debugId=4323AEF4264062BD64756E2164756E21
|