@inkeep/open-knowledge 0.89.5 → 0.89.6
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/dist/{cli-DMmg8Od_.mjs → cli-DJY8dffD.mjs} +6 -6
- package/dist/cli.mjs +1 -1
- package/dist/constants-BZk7xgJz.mjs +1 -0
- package/dist/{dist-CfKMRf03.mjs → dist-BL5dLR9l.mjs} +1 -1
- package/dist/{dist-CtwIv2ht.mjs → dist-R_LUDCBR.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-DMiFSg__.mjs → init-CelXSRfs.mjs} +2 -2
- package/dist/init-KkYz8epE.mjs +1 -0
- package/dist/{launch-json-removal-DiSDkjhH.mjs → launch-json-removal-ytpCVSv9.mjs} +1 -1
- package/dist/{loader-DPrL8l5w.mjs → loader-C56VpYiL.mjs} +1 -1
- package/dist/loader-amZnghWJ.mjs +1 -0
- package/dist/{open-browser-BXYOobWo.mjs → open-browser-_eQlBYHh.mjs} +1 -1
- package/dist/{preview-BltuLZyO.mjs → preview-2ROhJT3N.mjs} +1 -1
- package/dist/preview-404LuL-V.mjs +1 -0
- package/dist/public/assets/{AccountSection-CfotciYY.js → AccountSection-B9J8H3oB.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-Dp26H3HU.js → ActivityModeContent-D9YYx2Xb.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-DXfuo84v.js → AddPropertiesButton-YpOjWvcE.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-_jX2uRmA.js → AgentDiffPane-tcZZxcwp.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-D5WVcKFj.js → AttachmentsSection-CCjQ5RTE.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-C6hvBFz7.js → CodeMirrorPropInput-BEmS7c0B.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-Gr3_d0ht.js → ContentRulesSection-D_CFPw5j.js} +1 -1
- package/dist/public/assets/{DocumentContext-CtcX9d0A.js → DocumentContext-ZDIsUx86.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CKRUJoGv.js → EditorModeToggle-q1q809xI.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-D6aFDYkx.js → ExcalidrawDocEditor-B5hvYcqH.js} +1 -1
- package/dist/public/assets/FeedbackForm-Dw78w8j8.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-WnL9KdUw.js → ImportSkillDialog-CyVnYtwX.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-F5OVQUQR.js → LinkPreviewsSection-B7xDdQ5e.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-Byg9xEXw.js → LintConfigEditor-CIT39Qwf.js} +1 -1
- package/dist/public/assets/{LintingSection-DEonYwMt.js → LintingSection-Cm6MOpAY.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CspNVh_E.js → ManagedArtifactProperties-3l5NJlRi.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DxEb5xwU.js +1 -0
- package/dist/public/assets/{Mermaid-Cj2JuPCA.js → Mermaid-DJMBv5EM.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-KApEsAak.js → MermaidDocEditor-BCGfduv5.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-DvlYYBwv.js → NetworkAccessSection-OkeKmqMe.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-BnFv7vXo.js → PropertyDisplayRow-COzfeCdI.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-DRy-urhq.js → PublishToGitHubDialog-DncdWlyB.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-Y6drzMQV.js → SchemaConfigEditor-DUhl0z0y.js} +1 -1
- package/dist/public/assets/{SearchSection-BOKpU94K.js → SearchSection-Ch1kOb11.js} +1 -1
- package/dist/public/assets/{SessionsHost-BMEv0gaD.js → SessionsHost-CNerDV-F.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-DENK_PwZ.js → SettingsDialogBody-BsOLb2CG.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-d5dgZt-V.js → ShareReceiveMissDialog-E7eFeSQw.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-C_Y9xqMx.js → SkillToolbarControls-BCtykCVC.js} +1 -1
- package/dist/public/assets/{SourceEditor-B4RrOUnq.js → SourceEditor-CFNzi-3X.js} +1 -1
- package/dist/public/assets/{SyncSection-B4AMwlVo.js → SyncSection-DPY925RZ.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-vLqZCd3H.js → SyncStatusBadge-DEFzf9Ud.js} +1 -1
- package/dist/public/assets/{TerminalSection-CZ_58kDG.js → TerminalSection-DVTjBfMG.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-bb7i7aLy.js → TerminalWindowApp-xwoyVk1G.js} +1 -1
- package/dist/public/assets/{TextDocEditor-D1Gv3VJd.js → TextDocEditor-pmqdsOHx.js} +1 -1
- package/dist/public/assets/{ThreadView-Cn8Ojvxh.js → ThreadView-AsBVAex9.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-CZOno3nJ.js → TimelineDiffPane-7Zibo4nt.js} +1 -1
- package/dist/public/assets/{client-version-Dj71tq9b.js → client-version-7SQ1CnmT.js} +1 -1
- package/dist/public/assets/{comment-chips-D6sWogky.js → comment-chips-xI8EWTbS.js} +1 -1
- package/dist/public/assets/{config-provider-C0zkBzVe.js → config-provider-DcA0Hek0.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-DwAucm0B.js → doc-undo-manager-Dlj3M917.js} +1 -1
- package/dist/public/assets/{index-CoTO0O6R.js → index-B0RPttq_.js} +7 -7
- package/dist/public/assets/{lint-plugins-DMK3SN8g.js → lint-plugins-CSAI5JkR.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-GAetV2so.js → pending-receive-nav-store-DW35YpXG.js} +1 -1
- package/dist/public/assets/{preferred-session-events-ScruPxny.js → preferred-session-events-BOG362Q3.js} +1 -1
- package/dist/public/assets/{progress-Cy4SbImI.js → progress-DyZ6X_f3.js} +1 -1
- package/dist/public/assets/{selection-context-DJrvAeB-.js → selection-context-47OTO3QB.js} +1 -1
- package/dist/public/assets/{src-S-_16D7_.js → src-GFFVUSJj.js} +1 -1
- package/dist/public/assets/{telemetry-impl-CQ3qd0Ju.js → telemetry-impl-CbwOBG81.js} +1 -1
- package/dist/public/assets/{telemetry-startup-BXWTZddl.js → telemetry-startup-CIW6gx_T.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-C2psaRmO.js → typing-burst-detector-D7G0q-1T.js} +1 -1
- package/dist/public/assets/{use-activity-panel-YwgPghm6.js → use-activity-panel-Coov9p0n.js} +1 -1
- package/dist/public/assets/{use-open-skill-CSFabVs8.js → use-open-skill-CAnxMFl1.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-D1Y-4-ds.js → use-terminal-enabled-BaVOE_rA.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CM0m72NG.js → use-timeline-entry-diff-DXfcPQ_J.js} +1 -1
- package/dist/public/index.html +20 -20
- package/dist/{registry-probes-t4Raqv8n.mjs → registry-probes-BLVjAWRw.mjs} +1 -1
- package/dist/{removal-file-path-Ced0OD6y.mjs → removal-file-path-CirdLOMU.mjs} +1 -1
- package/dist/{repair-launch-json-BM7DASn_.mjs → repair-launch-json-Bv2UM7Gw.mjs} +1 -1
- package/dist/{repair-mcp-configs-BoGwIFft.mjs → repair-mcp-configs-ECKouWaL.mjs} +1 -1
- package/dist/{src-CCj4PE0M.mjs → src-DKrBYnXa.mjs} +1 -1
- package/dist/src-R39XGmAn.mjs +1 -0
- package/dist/{start-nJT-1pf4.mjs → start-BOOBKL8y.mjs} +3 -3
- package/dist/start-lckVV0JO.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-tpwOcf2z.mjs +0 -1
- package/dist/init-C0lSo0eI.mjs +0 -1
- package/dist/loader-CTLi3h6Z.mjs +0 -1
- package/dist/preview-TM6abwDn.mjs +0 -1
- package/dist/public/assets/FeedbackForm-BfZ3DTFI.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-XHfnBv4m.js +0 -1
- package/dist/src-ph_ZopM2.mjs +0 -1
- package/dist/start-CGWEp9ft.mjs +0 -1
|
@@ -1009,7 +1009,7 @@ ${e.terminator}`}function wYe(e){return`(${pV(e.body)})${fV(e.redirections)}`}fu
|
|
|
1009
1009
|
DELETE FROM server_authority
|
|
1010
1010
|
WHERE server_instance_id = ? AND owner_token = ?
|
|
1011
1011
|
`).run(r,a),s.close(),o?.()}),c=!0,PK.delete(l))};return PK.add(l),k8e||(k8e=!0,process.prependOnceListener(`exit`,()=>{for(let e of PK)try{e()}catch(e){J(`server-authority`).warn({err:e},`Content ownership exit release failed`)}})),{scope:t,release:l}}var zK=class extends Error{constructor(){super(`This server does not own this content path. Open the project or file that owns it.`),this.name=`ContentScopeAdmissionError`}},BK=class extends Error{problemType;constructor(e){super(`The server is shutting down.`),this.name=`ServerMutationShuttingDownError`,this.problemType=e?`urn:ok:error:auth-failed`:`urn:ok:error:concurrent-operation`}};function I8e(e){return{writeFile:UU.writeFile,rename:async(t,n)=>{e(n),PU(t,n)}}}function VK(e){try{let{ancestor:t,missingSegments:n}=TG(e);return G(t,...n)}catch(e){throw JW(e)===`ELOOP`?new hK(`symlink cycle in path`):e}}function L8e(e,t){return vU(`ok.boot.content-scope`,{attributes:{"content.scope.kind":t===void 0?`tree`:`file`}},n=>{let r=R8e(e,t);return n.setAttribute(`content.scope.exclusions`,r.kind===`tree`?r.excluded.length:0),r})}function R8e(e,t){let n=VK(e);if(t!==void 0)return{kind:`file`,path:VK(G(e,t))};let r=[],i=[n];for(;i.length>0;){let e=i.pop();if(e===void 0)break;try{for(let t of cc(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=U(e,t.name);try{Fs(n)?r.push(VK(n)):i.push(n)}catch(e){let t=JW(e);if(t!==`ENOENT`&&t!==`ENOTDIR`&&t!==`EACCES`&&t!==`EPERM`)throw e;J(`server-content-policy`).warn({path:xU(n),code:t},`Unreadable nested-project marker remains in the parent authority scope`)}}}catch(t){let n=JW(t);if(n!==`ENOENT`&&n!==`ENOTDIR`&&n!==`EACCES`&&n!==`EPERM`)throw t;(n===`EACCES`||n===`EPERM`)&&J(`server-content-policy`).warn({path:xU(e),code:n},`Unreadable directory remains in the parent authority scope`)}}return{kind:`tree`,path:n,excluded:r}}function z8e(e,t){let n=VK(t);if(e.kind===`file`){if(!IK(e,n))throw new zK;return n}let r=e.excluded.find(e=>IK({kind:`tree`,path:e,excluded:[]},n));if(r!==void 0)throw new DG(r);if(!IK(e,n))throw new zK;return n}function B8e(e,t){let n=z8e(e,t);e.kind===`tree`&&kG(n,e.path)}function V8e(e,t){if(B8e(e,t),e.kind===`file`)throw new zK;let n=VK(t),r=e.excluded.find(e=>IK({kind:`tree`,path:n,excluded:[]},e));if(r!==void 0)throw new DG(r)}const HK=`x-request-id`,H8e=/^[A-Za-z0-9._-]{1,128}$/;function U8e(e){let t=e.headers[HK],n=Array.isArray(t)?t[0]:t;return n!==void 0&&H8e.test(n)?n:Pc()}const W8e=new WeakMap;function G8e(e,t){W8e.set(e,t)}function UK(e){return W8e.get(e)}const WK=()=>J(`http`);let K8e=null;function GK(){return K8e||=gU().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),K8e}function Z(e,t,n,r,i={}){i.cause instanceof ND&&(t=400,n=`urn:ok:error:invalid-request`,r=`Website source requires explicit trust.`,i={...i,detail:i.cause.message}),t===500&&i.cause instanceof hK&&!(i.cause instanceof gK)&&(t=400,n=`urn:ok:error:path-escape`,r=`Path resolves outside the content directory or contains a symlink cycle.`,i={...i,detail:void 0}),i.cause instanceof BK&&(t=503,n=i.cause.problemType,r=i.cause.message),(i.cause instanceof DG||i.cause instanceof zK)&&(t=403,n=`urn:ok:error:path-escape`,r=`Path is outside this server’s content scope.`,i={...i,detail:i.cause.message});let a=i.instance??`urn:uuid:${Pc()}`;if(yU({"ok.error.instance":a}),e.headersSent||e.writableEnded||e.destroyed){WK().error({event:`api.error.double-write`,instance:a,requestId:UK(e.req),type:n,status:t,handler:i.handler},`errorResponse called after headers already sent — suppressed`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let o={type:n,title:O(r),status:t,instance:a,detail:i.detail===void 0?void 0:O(i.detail)},s=nt.safeParse(o);if(!s.success){WK().error({event:`api.error.malformed-envelope`,requestId:UK(e.req),issues:s.error.issues,body:o,handler:i.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}let c=i.extensions?{...i.extensions,...o}:o;GK().add(1,{type:n,...i.handler?{handler:i.handler}:{}});let l=i.logLevel??(t>=500?`error`:`warn`);WK()[l]({event:`api.error`,instance:a,requestId:UK(e.req),type:n,status:t,handler:i.handler,detail:i.detail,err:i.cause,...i.extensions?{extensions:i.extensions}:{}},r);let u;try{u=JSON.stringify(c)}catch(n){WK().error({event:`api.error.unserializable-body`,requestId:UK(e.req),bodyKeys:Object.keys(c),handler:i.handler,originalStatus:t,instance:a,err:n},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(u)}function q8e(e,t,n,r={}){let i=r.instance??`urn:uuid:${Pc()}`,a={type:`error`,problem:{type:t,title:O(n),status:e,instance:i,detail:r.detail===void 0?void 0:O(r.detail)}},o=ir.safeParse(a);if(!o.success)return WK().error({event:`api.streaming.malformed-envelope`,issues:o.error.issues,body:a,handler:r.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...r.handler?{handler:r.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:i}};GK().add(1,{type:t,...r.handler?{handler:r.handler}:{}});let s=e>=500?`error`:`warn`;return WK()[s]({event:`api.streaming.error`,instance:i,type:t,status:e,handler:r.handler,detail:r.detail,err:r.cause},n),a}function KK(e,t){return(n,r,i,a={})=>{if(e.writableEnded||e.destroyed){WK().error({event:`api.streaming.error.suppressed`,requestId:UK(e.req),type:r,status:n,handler:t,detail:a.detail,err:a.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let o=q8e(n,r,i,{handler:t,...a});try{e.write(`${JSON.stringify(o)}\n`)}catch(i){WK().error({event:`api.streaming.error.write-failed`,requestId:UK(e.req),type:r,status:n,handler:t,err:a.cause,writeErr:i},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const qK=`urn:ok:error:concurrent-overwrite-refused`,J8e=`Concurrent overwrite refused.`,Y8e=`Another writer changed this document recently. Wait a few seconds and retry.`,X8e=`${Y8e} A write with position append or prepend is not refused.`;var JK=class extends Error{file;name=`ConcurrentOverwriteRefusedError`;constructor(e){super(`Concurrent overwrite refused for ${e}`),this.file=e}};function Z8e(e,t){o$e(),J(`agent-write`).warn({event:`concurrent-overwrite-write-refused`,handler:t,"doc.name":TH(e.file)},`concurrent replace refused before mutation`)}function Q8e(e,t,n){Z8e(t,n),Z(e,409,qK,J8e,{handler:n,detail:X8e,extensions:{file:t.file,retryAfterSeconds:3,...bG[`urn:ok:error:concurrent-overwrite-refused`]},extraHeaders:{"Retry-After":`3`}})}const YK=`/internal/acp/document-write`;async function $8e(e,t){let n=await e(`POST`,YK,{body:JSON.stringify({docName:t.docName,file:t.file,markdown:t.markdown,...e5e(t.file),agentId:t.agentId,agentName:t.agentName,clientName:t.clientName}),contentType:`application/json`});if(n===null)throw Error(`${YK} is not dispatchable in process`);return r5e(n.status,Ox(JSON.parse(n.bodyText)),t.file)}function e5e(e){return e.endsWith(`.mdx`)?{extension:`.mdx`}:e.endsWith(`.md`)?{extension:`.md`}:{}}function t5e(e){let t=Jr(e);if(t!==void 0)return{outcome:t.outcome,...t.saved===void 0?{}:{saved:t.saved},...t.nextStep===void 0?{}:{nextStep:t.nextStep}}}function n5e(e,t){let n=typeof t.title==`string`?t.title:`The write answered ${e}.`;return typeof t.detail==`string`?`${n} ${t.detail}`:n}function r5e(e,t,n){let r=t5e(t);if(e>=200&&e<300&&(r===void 0||r.outcome===`applied`||r.outcome===`merged-first`))return r===void 0?{}:{_meta:{openknowledge:{...r}}};throw t.type===`urn:ok:error:concurrent-overwrite-refused`?new lS(-32009,Y8e,{type:qK,file:n,retryable:!0,retryAfterSeconds:3,...r}):new lS(-32010,n5e(e,t),{type:typeof t.type==`string`?t.type:`urn:ok:error:internal-server-error`,file:n,...r})}const i5e=/command not found|not recognized as an internal or external command/i,a5e=/permission denied/i,o5e=/cannot find module|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND/i,s5e=/out of memory|ENOMEM/i,c5e=new Set([`SIGTERM`,`SIGINT`,`SIGHUP`]);function l5e({exitCode:e,signal:t,tail:n}){if(t!==null)return t===`SIGKILL`?`killed`:c5e.has(t)?`stopped`:`signal`;if(e===0)return`clean`;if(e===null)return`unknown`;if(e===127)return`command-not-found`;if(e===126)return`not-executable`;let r=n===void 0?``:uTe(n);return s5e.test(r)?`out-of-memory`:i5e.test(r)?`command-not-found`:a5e.test(r)?`not-executable`:o5e.test(r)?`missing-module`:`unknown`}function u5e(e){return{exitCode:e.exitCode,signal:e.signal,cause:l5e(e)}}function d5e(e){return{reason:`exited`,exit:u5e(e),machineDetail:e.tail}}function f5e(e){return e===`connect`||e===`session-setup`}function p5e(e){return U(e,Xoe)}function m5e(e){let t=[`=== acp launch failure ${e.at.toISOString()} thread=${e.threadId} agent=${e.agentId} source=${e.agentSource} reason=${e.reason} ===`];return e.detail!==void 0&&e.detail!==``&&t.push(e.detail),e.machineDetail!==void 0&&e.machineDetail!==``&&t.push(`--- stderr tail ---`,e.machineDetail),cW(`${t.join(`
|
|
1012
|
-
`)}\n\n`)}const XK=new Map;function h5e(e,t){let n=p5e(e),r=m5e(t),i=(XK.get(n)??Promise.resolve()).then(async()=>{Zoe(await Oc(n).then(e=>e.size,()=>void 0))===`w`?await EU(n,r):await DU(n,r)}),a=i.then(()=>void 0,()=>void 0);return XK.set(n,a),a.then(()=>{XK.get(n)===a&&XK.delete(n)}),i}const ZK=`v24.18.0`,QK=`0.11.28`,g5e=`https://nodejs.org/dist`,_5e=`https://github.com/astral-sh/uv/releases/download`,v5e={node:45,uv:20};function y5e(e){return e===`npx`?`node`:`uv`}function $K(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:ZK,approxSizeMB:v5e.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:QK,approxSizeMB:v5e.uv,sourceHost:`github.com/astral-sh`}}function eq(){return U(Rs(),`runtimes`)}function tq(e){return e===`node`?ZK:QK}function b5e(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function x5e(){let e=bc(),t=_c(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`win`:null,r=t===`arm64`?`arm64`:t===`x64`?`x64`:null;if(n===null||r===null)return null;let i=e===`win32`,a=`node-${ZK}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${g5e}/${ZK}/${a}`,checksumUrl:`${g5e}/${ZK}/SHASUMS256.txt`,archiveName:a,isZip:i}}function S5e(){let e={"darwin-arm64":`aarch64-apple-darwin`,"darwin-x64":`x86_64-apple-darwin`,"linux-arm64":`aarch64-unknown-linux-gnu`,"linux-x64":`x86_64-unknown-linux-gnu`,"win32-x64":`x86_64-pc-windows-msvc`,"win32-arm64":`aarch64-pc-windows-msvc`}[`${bc()}-${_c()}`];if(e===void 0)return null;let t=bc()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${_5e}/${QK}/${n}`,checksumUrl:`${_5e}/${QK}/${n}.sha256`,archiveName:n,isZip:t}}function C5e(e){return e===`node`?x5e():S5e()}function w5e(e){return C5e(e)!==null}async function T5e(e){try{let t=await Oc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await Sc(e,Hae.X_OK),!0)}catch{return!1}}async function nq(e,t,n){let r;try{r=await Ec(e,{withFileTypes:!0})}catch{return null}for(let n of r)if((n.isFile()||n.isSymbolicLink())&&t.includes(n.name))return U(e,n.name);if(n<=0)return null;for(let i of r)if(i.isDirectory()){let r=await nq(U(e,i.name),t,n-1);if(r!==null)return r}return null}function E5e(e,t,n){let r=H(t),i=U(n,`cache`,e);return e===`node`?{kind:`node`,binDir:r,npxBin:t,cacheDir:i}:{kind:`uv`,binDir:r,uvxBin:t,cacheDir:i}}async function D5e(e,t=eq()){let n=U(t,e,rW(tq(e)));try{if(!(await Oc(n)).isDirectory())return null}catch{return null}let r=await nq(n,b5e(e),3);return r===null||!await T5e(r)?null:E5e(e,r,t)}var rq=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function O5e(e,t,n=eq()){await mW(U(n,e),t,`[managed-runtime]`)}async function k5e(e,t,n=eq()){let r=U(n,e,rW(tq(e))),i=U(H(r),`.install-damaged-${rW(tq(e))}-${Pc()}`);try{await kU(r,i)}catch(n){return n.code===`ENOENT`||(t.warn({err:n,kind:e,versionDir:r},`[managed-runtime] could not quarantine damaged runtime`),!1)}return t.info({kind:e,versionDir:r},`[managed-runtime] quarantined damaged runtime`),await OU(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function A5e(e,t,n={}){let r=n.root??eq(),i=U(r,e,rW(tq(e)));try{return await hW({versionDir:i,stagingLabel:rW(tq(e)),findInstalled:()=>D5e(e,r),prepare:async r=>{let i=C5e(e);if(i===null)throw new rq(`no ${e} build for ${bc()}-${_c()}`);let a=U(r,i.archiveName);t.info({kind:e,version:tq(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let o=new AbortController,s=n.signal===void 0?o.signal:AbortSignal.any([n.signal,o.signal]),c=e=>{throw o.abort(e),e},[l,u]=await Promise.allSettled([q0e(i.archiveUrl,a,{signal:s,onProgress:n.onProgress,onRetry:({attempt:n,receivedBytes:r,totalBytes:i,resumeFromBytes:a,error:o})=>t.warn({kind:e,version:tq(e),attempt:n,receivedBytes:r,totalBytes:i,resumeFromBytes:a,err:o},`[managed-runtime] runtime download interrupted, retrying`),fetchImpl:n.fetchImpl}).catch(c),a2e(i.checksumUrl,{signal:s,fetchImpl:n.fetchImpl}).catch(c)]);if(l.status===`rejected`||u.status===`rejected`)throw o.signal.reason;let d=l.value,f=u.value,p=o2e(f,i.archiveName);if(p===null)throw new rq(`no published checksum for ${i.archiveName}`);if(d!==p)throw new rq(`checksum mismatch for ${i.archiveName}: got ${d}, expected ${p}`);let m=U(r,`extracted`);await AU(m,{recursive:!0}),await G0e(a,m,i.isZip);let h=await nq(m,b5e(e),3);if(h===null||!nW(m,h))throw new rq(`extracted ${e} archive has no usable launcher`);return m},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:tq(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof rq?t:new rq(`installing ${e} ${tq(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const j5e=`CODEX_CONFIG`;function M5e(e,t){if(!Number.isFinite(e)||e<=0)return 0;let n=t.maxContextWindow??e,r=Math.min(Math.floor(e),n),i=t.effectivePercent??95;return Math.floor(r*i/100)}function N5e(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function P5e(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function F5e(e){if(e===void 0||e.trim()===``)return{};try{return P5e(JSON.parse(e))}catch{return{}}}function I5e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...F5e(e[j5e]),model_context_window:Math.floor(t)};return{...e,[j5e]:JSON.stringify(n)}}function L5e(e){return(e.visibility??`list`)===`list`}const R5e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function iq(e){return R5e[e]??`none`}function z5e(e,t,n){if(n===null||iq(t)!==`codex-config-env`)return e;let r=I5e(e.env,n);return r===e.env?e:{...e,env:r}}function B5e(e){return iq(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function aq(e,t,n={}){NU(t,{recursive:!0});for(let r of cc(e)){let i=U(e,r);if(n.filter?.(i)===!1)continue;let a=U(t,r);pc(i).isDirectory()?aq(i,a,n):jU(a,q(i))}}const V5e=`open-knowledge`,H5e=`SKILL.md`,oq=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function U5e(e){return U(e,`agent-skill`,V5e)}function W5e(e,t){let n;try{n=q(t)}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}return q(e).equals(n)}function G5e(e,t){let n=cc(e),r;try{r=new Set(cc(t))}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}if(n.length!==r.size)return!1;for(let i of n){if(!r.has(i))return!1;let n=U(e,i),a=U(t,i);if(pc(n).isDirectory()){let e;try{e=pc(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}if(!e||!G5e(n,a))return!1}else if(!W5e(n,a))return!1}return!0}var K5e=class extends Error{path;constructor(e){super(`refusing to stage the project skill through a symlink at ${e}`),this.name=`ProjectSkillSymlinkError`,this.path=e}};async function q5e(e){let t;try{t=await Cc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new K5e(e)}async function J5e(e){let t=U5e(e.localDir),n=H(t),r=async()=>{await q5e(n),await q5e(t)};return hW({versionDir:t,stagingLabel:V5e,findInstalled:async()=>(await r(),G5e(e.sourceDir,t)?t:null),prepare:async t=>(aq(e.sourceDir,t),t),log:e.log,logPrefix:`[acp-threads]`,logContext:e.logContext??{},installedMessage:`project skill staged`,missingAfterCommitMessage:`project skill missing after the staging commit`})}function Y5e(e,t=process.env){let n=(e.kind===`npx`||e.kind===`uvx`)&&Ks(e.cmd),r={};for(let[n,i]of Object.entries(e.env))n.toLowerCase()===`path`||!Xt(n)||i.includes(`\0`)||t[n]!==i&&(r[n]=i);return{executable:e.cmd,args:e.kind===`npx`?q2e(e.args):[...e.args],env:r,pathPrepend:n?[H(e.cmd)]:[]}}function X5e(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Z5e(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r!=`string`||r.includes(`\0`)||Xt(n)&&(t[n]=r);return t}function Q5e(e){return typeof e==`object`&&e?e:null}function $5e(e,t){return{executable:t.executable,args:[...t.args,...X5e(e.args)],env:{...t.env,...Z5e(e.env)},pathPrepend:[...t.pathPrepend]}}function sq(e,t){return(e??[]).flatMap(e=>{let n=Q5e(e);if(n===null)return[];let{id:r,name:i,description:a,type:o}=n;if(typeof r!=`string`||typeof i!=`string`)return[];let s=o===`terminal`&&t!==null;return[{id:r,name:i,...typeof a==`string`?{description:a}:{},...typeof o==`string`?{kind:o}:{},...s?{terminalLaunchAvailable:!0}:{}}]})}function e7e(e,t,n){if(t===null)return null;for(let r of e??[]){let e=Q5e(r);if(e!==null&&e.id===n&&e.type===`terminal`)return $5e(e,t)}return null}const t7e=2e3;function n7e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function r7e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:n7e(n.subarray(n.length-t)).toString(`utf8`)}function cq(e){if(e.outputBytes<=e.byteLimit)return;let t=n7e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var i7e=class{terminals=new Map;emit;defaultCwd;log;loginShellPath;disposed=!1;constructor(e){this.defaultCwd=e.defaultCwd,this.emit=e.emit,this.log=e.log,this.loginShellPath=e.loginShellPath??null}liveCount(){let e=0;for(let t of this.terminals.values())t.exitStatus===null&&e++;return e}create(e){if(this.disposed)throw Error(`thread is closing — no new terminals`);if(this.terminals.size>=64)throw Error(`terminal limit reached (64 per thread) — release finished terminals first`);let t=crypto.randomUUID(),n={};for(let t of e.env??[])n[t.name]=t.value;let r=I2e(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:Ks(e.cwd)?e.cwd:G(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?PW(e.command,jW(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?FW(o,e.args??[]):{cmd:o,args:e.args??[]},u=zc(c,l,{cwd:i,env:r,stdio:[`ignore`,`pipe`,`pipe`],shell:!1,detached:!a,windowsHide:!0,windowsVerbatimArguments:s}),d=e.outputByteLimit,f={child:u,output:``,outputBytes:0,byteLimit:typeof d==`number`&&d>0?Math.floor(d):1048576,truncated:!1,exitStatus:null,exitWaiters:[],transcriptBytes:0,transcriptPaused:!1,pausedTail:``};this.terminals.set(t,f),this.safeEmit({kind:`terminal_created`,terminalId:t,command:e.command,args:e.args??[],ts:Date.now()});let p=e=>this.ingestChunk(t,f,e);u.stdout?.setEncoding(`utf8`),u.stdout?.on(`data`,p),u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,p);let m=!1;return u.on(`spawn`,()=>{m=!0}),u.on(`error`,e=>{if(m){this.log.warn({err:e,terminalId:t},`[acp-terminals] child error after spawn`);return}p(`${e.message}\n`),this.settleExit(t,f,{exitCode:127,signal:null})}),u.on(`close`,(e,n)=>{this.settleExit(t,f,{exitCode:e,signal:n})}),{terminalId:t}}output(e){let t=this.mustGet(e);return cq(t),{output:t.output,truncated:t.truncated,exitStatus:t.exitStatus}}waitForExit(e){let t=this.mustGet(e);return t.exitStatus===null?new Promise(e=>{t.exitWaiters.push(e)}):Promise.resolve(t.exitStatus)}async kill(e){let t=this.mustGet(e);t.exitStatus===null&&await zW(t.child,{graceMs:t7e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await zW(t.child,{graceMs:t7e}),this.terminals.delete(e))}async disposeAll(){this.disposed=!0;let e=[...this.terminals.keys()];await Promise.allSettled(e.map(e=>this.release(e)))}spawnEnv(e){let t=vW(e);return this.loginShellPath===null||bW(e)?t:TW(t,this.loginShellPath)}mustGet(e){let t=this.terminals.get(e);if(t===void 0)throw Error(`unknown terminal '${e}'`);return t}safeEmit(e){try{this.emit(e)}catch(t){this.log.warn({err:t,kind:e.kind},`[acp-terminals] transcript emit failed`)}}ingestChunk(e,t,n){if(n!==``){if(t.output+=n,t.outputBytes+=Buffer.byteLength(n,`utf8`),t.outputBytes>t.byteLimit*2?cq(t):t.outputBytes>t.byteLimit&&(t.truncated=!0),!t.transcriptPaused){let r=Buffer.byteLength(n,`utf8`);if(t.transcriptBytes+r<=262144){t.transcriptBytes+=r,this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:n,ts:Date.now()});return}t.transcriptPaused=!0}t.pausedTail=r7e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,cq(t),t.transcriptPaused&&t.pausedTail!==``&&this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:`\n… [output truncated — resuming at the end]\n${t.pausedTail}`,ts:Date.now()}),this.safeEmit({kind:`terminal_exit`,terminalId:e,exitCode:n.exitCode,signal:n.signal,ts:Date.now()});let r=t.exitWaiters;t.exitWaiters=[];for(let t of r)try{t(n)}catch(t){this.log.warn({err:t,terminalId:e},`[acp-terminals] exit waiter threw`)}}};const lq=String.raw`(?![\p{L}\p{M}\p{N}_])`,a7e=RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})${lq}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),o7e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,s7e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function c7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function l7e(e){return(e.trim().split(`
|
|
1012
|
+
`)}\n\n`)}const XK=new Map;function h5e(e,t){let n=p5e(e),r=m5e(t),i=(XK.get(n)??Promise.resolve()).then(async()=>{Zoe(await Oc(n).then(e=>e.size,()=>void 0))===`w`?await EU(n,r):await DU(n,r)}),a=i.then(()=>void 0,()=>void 0);return XK.set(n,a),a.then(()=>{XK.get(n)===a&&XK.delete(n)}),i}const ZK=`v24.22.3`,QK=`0.11.28`,g5e=`https://nodejs.org/dist`,_5e=`https://github.com/astral-sh/uv/releases/download`,v5e={node:45,uv:20};function y5e(e){return e===`npx`?`node`:`uv`}function $K(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:ZK,approxSizeMB:v5e.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:QK,approxSizeMB:v5e.uv,sourceHost:`github.com/astral-sh`}}function eq(){return U(Rs(),`runtimes`)}function tq(e){return e===`node`?ZK:QK}function b5e(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function x5e(){let e=bc(),t=_c(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`win`:null,r=t===`arm64`?`arm64`:t===`x64`?`x64`:null;if(n===null||r===null)return null;let i=e===`win32`,a=`node-${ZK}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${g5e}/${ZK}/${a}`,checksumUrl:`${g5e}/${ZK}/SHASUMS256.txt`,archiveName:a,isZip:i}}function S5e(){let e={"darwin-arm64":`aarch64-apple-darwin`,"darwin-x64":`x86_64-apple-darwin`,"linux-arm64":`aarch64-unknown-linux-gnu`,"linux-x64":`x86_64-unknown-linux-gnu`,"win32-x64":`x86_64-pc-windows-msvc`,"win32-arm64":`aarch64-pc-windows-msvc`}[`${bc()}-${_c()}`];if(e===void 0)return null;let t=bc()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${_5e}/${QK}/${n}`,checksumUrl:`${_5e}/${QK}/${n}.sha256`,archiveName:n,isZip:t}}function C5e(e){return e===`node`?x5e():S5e()}function w5e(e){return C5e(e)!==null}async function T5e(e){try{let t=await Oc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await Sc(e,Hae.X_OK),!0)}catch{return!1}}async function nq(e,t,n){let r;try{r=await Ec(e,{withFileTypes:!0})}catch{return null}for(let n of r)if((n.isFile()||n.isSymbolicLink())&&t.includes(n.name))return U(e,n.name);if(n<=0)return null;for(let i of r)if(i.isDirectory()){let r=await nq(U(e,i.name),t,n-1);if(r!==null)return r}return null}function E5e(e,t,n){let r=H(t),i=U(n,`cache`,e);return e===`node`?{kind:`node`,binDir:r,npxBin:t,cacheDir:i}:{kind:`uv`,binDir:r,uvxBin:t,cacheDir:i}}async function D5e(e,t=eq()){let n=U(t,e,rW(tq(e)));try{if(!(await Oc(n)).isDirectory())return null}catch{return null}let r=await nq(n,b5e(e),3);return r===null||!await T5e(r)?null:E5e(e,r,t)}var rq=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function O5e(e,t,n=eq()){await mW(U(n,e),t,`[managed-runtime]`)}async function k5e(e,t,n=eq()){let r=U(n,e,rW(tq(e))),i=U(H(r),`.install-damaged-${rW(tq(e))}-${Pc()}`);try{await kU(r,i)}catch(n){return n.code===`ENOENT`||(t.warn({err:n,kind:e,versionDir:r},`[managed-runtime] could not quarantine damaged runtime`),!1)}return t.info({kind:e,versionDir:r},`[managed-runtime] quarantined damaged runtime`),await OU(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function A5e(e,t,n={}){let r=n.root??eq(),i=U(r,e,rW(tq(e)));try{return await hW({versionDir:i,stagingLabel:rW(tq(e)),findInstalled:()=>D5e(e,r),prepare:async r=>{let i=C5e(e);if(i===null)throw new rq(`no ${e} build for ${bc()}-${_c()}`);let a=U(r,i.archiveName);t.info({kind:e,version:tq(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let o=new AbortController,s=n.signal===void 0?o.signal:AbortSignal.any([n.signal,o.signal]),c=e=>{throw o.abort(e),e},[l,u]=await Promise.allSettled([q0e(i.archiveUrl,a,{signal:s,onProgress:n.onProgress,onRetry:({attempt:n,receivedBytes:r,totalBytes:i,resumeFromBytes:a,error:o})=>t.warn({kind:e,version:tq(e),attempt:n,receivedBytes:r,totalBytes:i,resumeFromBytes:a,err:o},`[managed-runtime] runtime download interrupted, retrying`),fetchImpl:n.fetchImpl}).catch(c),a2e(i.checksumUrl,{signal:s,fetchImpl:n.fetchImpl}).catch(c)]);if(l.status===`rejected`||u.status===`rejected`)throw o.signal.reason;let d=l.value,f=u.value,p=o2e(f,i.archiveName);if(p===null)throw new rq(`no published checksum for ${i.archiveName}`);if(d!==p)throw new rq(`checksum mismatch for ${i.archiveName}: got ${d}, expected ${p}`);let m=U(r,`extracted`);await AU(m,{recursive:!0}),await G0e(a,m,i.isZip);let h=await nq(m,b5e(e),3);if(h===null||!nW(m,h))throw new rq(`extracted ${e} archive has no usable launcher`);return m},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:tq(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof rq?t:new rq(`installing ${e} ${tq(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const j5e=`CODEX_CONFIG`;function M5e(e,t){if(!Number.isFinite(e)||e<=0)return 0;let n=t.maxContextWindow??e,r=Math.min(Math.floor(e),n),i=t.effectivePercent??95;return Math.floor(r*i/100)}function N5e(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function P5e(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function F5e(e){if(e===void 0||e.trim()===``)return{};try{return P5e(JSON.parse(e))}catch{return{}}}function I5e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...F5e(e[j5e]),model_context_window:Math.floor(t)};return{...e,[j5e]:JSON.stringify(n)}}function L5e(e){return(e.visibility??`list`)===`list`}const R5e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function iq(e){return R5e[e]??`none`}function z5e(e,t,n){if(n===null||iq(t)!==`codex-config-env`)return e;let r=I5e(e.env,n);return r===e.env?e:{...e,env:r}}function B5e(e){return iq(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function aq(e,t,n={}){NU(t,{recursive:!0});for(let r of cc(e)){let i=U(e,r);if(n.filter?.(i)===!1)continue;let a=U(t,r);pc(i).isDirectory()?aq(i,a,n):jU(a,q(i))}}const V5e=`open-knowledge`,H5e=`SKILL.md`,oq=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function U5e(e){return U(e,`agent-skill`,V5e)}function W5e(e,t){let n;try{n=q(t)}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}return q(e).equals(n)}function G5e(e,t){let n=cc(e),r;try{r=new Set(cc(t))}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}if(n.length!==r.size)return!1;for(let i of n){if(!r.has(i))return!1;let n=U(e,i),a=U(t,i);if(pc(n).isDirectory()){let e;try{e=pc(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&oq.has(t))return!1;throw e}if(!e||!G5e(n,a))return!1}else if(!W5e(n,a))return!1}return!0}var K5e=class extends Error{path;constructor(e){super(`refusing to stage the project skill through a symlink at ${e}`),this.name=`ProjectSkillSymlinkError`,this.path=e}};async function q5e(e){let t;try{t=await Cc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new K5e(e)}async function J5e(e){let t=U5e(e.localDir),n=H(t),r=async()=>{await q5e(n),await q5e(t)};return hW({versionDir:t,stagingLabel:V5e,findInstalled:async()=>(await r(),G5e(e.sourceDir,t)?t:null),prepare:async t=>(aq(e.sourceDir,t),t),log:e.log,logPrefix:`[acp-threads]`,logContext:e.logContext??{},installedMessage:`project skill staged`,missingAfterCommitMessage:`project skill missing after the staging commit`})}function Y5e(e,t=process.env){let n=(e.kind===`npx`||e.kind===`uvx`)&&Ks(e.cmd),r={};for(let[n,i]of Object.entries(e.env))n.toLowerCase()===`path`||!Xt(n)||i.includes(`\0`)||t[n]!==i&&(r[n]=i);return{executable:e.cmd,args:e.kind===`npx`?q2e(e.args):[...e.args],env:r,pathPrepend:n?[H(e.cmd)]:[]}}function X5e(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Z5e(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r!=`string`||r.includes(`\0`)||Xt(n)&&(t[n]=r);return t}function Q5e(e){return typeof e==`object`&&e?e:null}function $5e(e,t){return{executable:t.executable,args:[...t.args,...X5e(e.args)],env:{...t.env,...Z5e(e.env)},pathPrepend:[...t.pathPrepend]}}function sq(e,t){return(e??[]).flatMap(e=>{let n=Q5e(e);if(n===null)return[];let{id:r,name:i,description:a,type:o}=n;if(typeof r!=`string`||typeof i!=`string`)return[];let s=o===`terminal`&&t!==null;return[{id:r,name:i,...typeof a==`string`?{description:a}:{},...typeof o==`string`?{kind:o}:{},...s?{terminalLaunchAvailable:!0}:{}}]})}function e7e(e,t,n){if(t===null)return null;for(let r of e??[]){let e=Q5e(r);if(e!==null&&e.id===n&&e.type===`terminal`)return $5e(e,t)}return null}const t7e=2e3;function n7e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function r7e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:n7e(n.subarray(n.length-t)).toString(`utf8`)}function cq(e){if(e.outputBytes<=e.byteLimit)return;let t=n7e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var i7e=class{terminals=new Map;emit;defaultCwd;log;loginShellPath;disposed=!1;constructor(e){this.defaultCwd=e.defaultCwd,this.emit=e.emit,this.log=e.log,this.loginShellPath=e.loginShellPath??null}liveCount(){let e=0;for(let t of this.terminals.values())t.exitStatus===null&&e++;return e}create(e){if(this.disposed)throw Error(`thread is closing — no new terminals`);if(this.terminals.size>=64)throw Error(`terminal limit reached (64 per thread) — release finished terminals first`);let t=crypto.randomUUID(),n={};for(let t of e.env??[])n[t.name]=t.value;let r=I2e(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:Ks(e.cwd)?e.cwd:G(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?PW(e.command,jW(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?FW(o,e.args??[]):{cmd:o,args:e.args??[]},u=zc(c,l,{cwd:i,env:r,stdio:[`ignore`,`pipe`,`pipe`],shell:!1,detached:!a,windowsHide:!0,windowsVerbatimArguments:s}),d=e.outputByteLimit,f={child:u,output:``,outputBytes:0,byteLimit:typeof d==`number`&&d>0?Math.floor(d):1048576,truncated:!1,exitStatus:null,exitWaiters:[],transcriptBytes:0,transcriptPaused:!1,pausedTail:``};this.terminals.set(t,f),this.safeEmit({kind:`terminal_created`,terminalId:t,command:e.command,args:e.args??[],ts:Date.now()});let p=e=>this.ingestChunk(t,f,e);u.stdout?.setEncoding(`utf8`),u.stdout?.on(`data`,p),u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,p);let m=!1;return u.on(`spawn`,()=>{m=!0}),u.on(`error`,e=>{if(m){this.log.warn({err:e,terminalId:t},`[acp-terminals] child error after spawn`);return}p(`${e.message}\n`),this.settleExit(t,f,{exitCode:127,signal:null})}),u.on(`close`,(e,n)=>{this.settleExit(t,f,{exitCode:e,signal:n})}),{terminalId:t}}output(e){let t=this.mustGet(e);return cq(t),{output:t.output,truncated:t.truncated,exitStatus:t.exitStatus}}waitForExit(e){let t=this.mustGet(e);return t.exitStatus===null?new Promise(e=>{t.exitWaiters.push(e)}):Promise.resolve(t.exitStatus)}async kill(e){let t=this.mustGet(e);t.exitStatus===null&&await zW(t.child,{graceMs:t7e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await zW(t.child,{graceMs:t7e}),this.terminals.delete(e))}async disposeAll(){this.disposed=!0;let e=[...this.terminals.keys()];await Promise.allSettled(e.map(e=>this.release(e)))}spawnEnv(e){let t=vW(e);return this.loginShellPath===null||bW(e)?t:TW(t,this.loginShellPath)}mustGet(e){let t=this.terminals.get(e);if(t===void 0)throw Error(`unknown terminal '${e}'`);return t}safeEmit(e){try{this.emit(e)}catch(t){this.log.warn({err:t,kind:e.kind},`[acp-terminals] transcript emit failed`)}}ingestChunk(e,t,n){if(n!==``){if(t.output+=n,t.outputBytes+=Buffer.byteLength(n,`utf8`),t.outputBytes>t.byteLimit*2?cq(t):t.outputBytes>t.byteLimit&&(t.truncated=!0),!t.transcriptPaused){let r=Buffer.byteLength(n,`utf8`);if(t.transcriptBytes+r<=262144){t.transcriptBytes+=r,this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:n,ts:Date.now()});return}t.transcriptPaused=!0}t.pausedTail=r7e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,cq(t),t.transcriptPaused&&t.pausedTail!==``&&this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:`\n… [output truncated — resuming at the end]\n${t.pausedTail}`,ts:Date.now()}),this.safeEmit({kind:`terminal_exit`,terminalId:e,exitCode:n.exitCode,signal:n.signal,ts:Date.now()});let r=t.exitWaiters;t.exitWaiters=[];for(let t of r)try{t(n)}catch(t){this.log.warn({err:t,terminalId:e},`[acp-terminals] exit waiter threw`)}}};const lq=String.raw`(?![\p{L}\p{M}\p{N}_])`,a7e=RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})${lq}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),o7e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,s7e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function c7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function l7e(e){return(e.trim().split(`
|
|
1013
1013
|
`)[0]??``).trim()}function uq(e){let t=l7e(e);if(t.length<=48)return t;let n=ha(t,47),r=n.lastIndexOf(` `);return`${(r>=24?n.slice(0,r):n).trimEnd()}…`}function u7e(e,t){let n=l7e(e),r=n.replace(o7e,``);if(t!==void 0&&t.trim()!==``){let e=c7e(t.trim()),n=String.raw`[,:;!.?\-–—•|]`,i=RegExp(`^(?:@${e}${lq}(?:\\s+|${n}+(?:\\s+|$)|$)|${e}${lq}\\s*${n}+(?:\\s+|$)|@?${e}${lq}$)`,`iu`);r=r.replace(i,``)}for(let e=0;e<6;e++){let e=r.replace(a7e,``);if(e===r)break;r=e}r=r.replace(s7e,``).trim();let i=r.split(/\s+/).filter(e=>e!==``).length;return!(r!==``&&(i>=2||r.length>=12))||r===n?uq(n):uq(r.charAt(0).toUpperCase()+r.slice(1))}const d7e=8,f7e=5e3,dq=3e5,fq=45e3,p7e=5e3,m7e=2e3,h7e=new Set([`ready`,`auth_required`,`authenticating`]),g7e=`Note on your environment: you are running inside the OpenKnowledge app, connected over ACP (Agent Client Protocol) — not inside your own terminal app. Your host CLI's terminal UI is not present, so its built-in slash commands (such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not exist here; never recommend them. The only slash commands available to the user are the ones you advertise over ACP.`;function _7e(e){if(e===null)return g7e;let t=e.inline===!0?"This project uses OpenKnowledge. Its agent skill (SKILL.md) is attached to this message. Follow it before editing any markdown here; it overrides generic markdown habits. If you already have the `open-knowledge` skill loaded, skip it.":`This project uses OpenKnowledge. Its agent skill is at \`${e.skillPath}\`. Read it before editing any markdown here; it overrides generic markdown habits, and you may read its \`references/\` files by path when it points to them. If you already have the \`open-knowledge\` skill loaded, skip the read.`;return`${g7e}\n\n${t}`}const v7e=new Set([`gemini`]);function y7e(e){return e.source===`registry`&&v7e.has(e.id)}function b7e(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:Vs(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${H5e} ---\n${t}\n--- End skill ---`}}var pq=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},mq=class extends _W{refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},x7e=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},S7e=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function hq(){return new pq(`not-ready`,`the thread was restarted during the sign-in`)}function C7e(e){return e.source===`registry`&&fQe[e.id]===`pi`}function w7e(e,t,n){let r=d.resolve({host:e===void 0?void 0:{cliArgs:e},...n?.env===void 0?{}:{env:n.env}}).stdioServer([`mcp`,`--port`,String(t)]),{command:i,args:a}=r,o=Object.keys(r.env).length>0?{env:r.env}:{};if(i.includes(`/`)||i.includes(`\\`))return{command:i,args:a,...o};let s=(n?.resolveCommand??(e=>ZU(e,yW())))(i);return s===null?(n?.log?.warn({command:i},`[acp-threads] OK MCP stdio command did not resolve on PATH — injecting the bare name, which fails for harnesses that spawn MCP children under a minimal PATH`),{command:i,args:a,...o}):{command:s,args:a,...o}}var T7e=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;turnStallMs;browserInstallWaitMs;persistence;npxCacheClears=new Map;resolveLoginShellPath;healthyInterpreters=new Set;projectSkillStaging=null;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>pW(e.log)()),this.maxThreads=e.maxThreads??8,this.idleReapMs=e.idleReapMs??36e5,this.steerStallMs=e.steerStallMs??1e4,this.authenticateTimeoutMs=e.authenticateTimeoutMs??3e5,this.unwatchedTurnCancelMs=e.unwatchedTurnCancelMs??6e5,this.unwatchedTurnKillMs=e.unwatchedTurnKillMs??12e5,this.turnStallMs=e.turnStallMs??18e4,this.browserInstallWaitMs=e.browserInstallWaitMs??12e4;let[t,n=null]=B4e(e.globalDir,e.localDir);this.persistence=new H4e({primaryDir:t,legacyDir:n,cwd:e.globalDir===null?null:e.contentDir,log:e.log}),this.reapTimer=setInterval(()=>this.reapIdleThreads(),3e5),this.reapTimer.unref?.()}async init(){if(this.initialized)return;this.initialized=!0,this.resolveLoginShellPath().catch(()=>{}),await this.persistence.init();let e=await this.persistence.scan();for(let t of e){let e=t.info.threadId;this.threads.has(e)||this.threads.set(e,D7e(t))}e.length>0&&this.opts.log.info({count:e.length},`[acp-threads] rehydrated archived threads`)}listThreads(){return[...this.threads.values()].map(e=>({...e.info}))}liveThreadCount(){let e=0;for(let t of this.threads.values())t.info.archived!==!0&&(e+=1);return e}getInfo(e){let t=this.threads.get(e);return t===void 0?void 0:{...t.info}}async subscribe(e,t,n){let r=this.mustGet(e);await this.ensureLogResolved(r);let i=Math.max(t,0);n({op:`subscribed`,threadId:e,fromSeq:i,info:{...r.info}});let a=i;for(;a<r.baseSeq;){let t=r.baseSeq;await this.persistence.whenIdle(e),await this.persistence.readEvents(e,a,t,(t,r)=>{n({op:`events`,threadId:e,fromSeq:t,events:r})}),a=t}this.flushBroadcast(r);let o=Math.max(i,r.baseSeq),s=r.baseSeq+r.events.length;for(let t=o;t<s;t+=512){let i=Math.min(t+512,s);n({op:`events`,threadId:e,fromSeq:t,events:r.events.slice(t-r.baseSeq,i-r.baseSeq)})}return r.subscribers.add(n),r.unwatchedSince=null,r.unwatchedCancelSent=!1,{...r.info}}ensureLogResolved(e){return e.logResolved?Promise.resolve():(e.logResolution??=(async()=>{try{let t=await this.persistence.resolveEventLog(e.info.threadId);e.baseSeq=t.count,e.midTurnOnDisk=t.midTurn,e.info.lastSeq=t.count-1,e.logResolved=!0}catch(t){throw e.logResolution=null,this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] durable log resolution failed`),t}})(),e.logResolution)}unsubscribe(e,t){let n=this.threads.get(e);n!==void 0&&(n.subscribers.delete(t),n.subscribers.size===0&&n.unwatchedSince===null&&(n.unwatchedSince=Date.now()))}async createThread(e){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new pq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(await mH({site:`acp-thread`,agentId:n===null?vte(t.id)??t.id:t.id,mode:`acp`,log:this.opts.log,snapshot:this.opts.hostSnapshot}),this.destroyed)throw new pq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new pq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let r=crypto.randomUUID(),i=Date.now(),a={info:{threadId:r,agent:t,title:t.name,status:`spawning`,createdAt:i,lastActivityAt:i,promptCapabilities:null,modes:null,configOptions:null,availableCommands:null,lastSeq:-1,archived:!1,resumable:!1},docName:e.docName,agentRef:{source:e.agent.source,id:e.agent.id},launchSettings:e.settings,cwd:this.opts.contentDir,child:null,conn:null,lastInit:null,terminalAuthBase:null,sessionId:null,sessionBeforeRestart:null,agentSessionId:`acp-${r}`,events:[],baseSeq:0,logResolved:!0,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,launchTicket:null,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,reportedToolCalls:new Map,toolCallReportWaiters:new Map,browserInjected:!1,browserNotice:null,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:i,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint,envNotePending:!1,projectSkill:null,chatGrants:new Set};this.threads.set(r,a);let o=xq(a,e.prompt!==void 0&&e.prompt!==``||e.attachments!==void 0&&e.attachments.length>0?{content:e.prompt??``,attachments:e.attachments}:null);return this.emitStatus(a,`spawning`),this.startThread(a,o,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),Sq(a,o)&&this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await sH(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new pq(`unknown-agent`,`no custom agent '${e.id}'`);return{info:{id:t.id,name:t.name,source:`custom`},custom:t}}let t;try{t=await this.opts.registry.getAgent(e.id)}catch(e){throw new pq(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new pq(`unknown-agent`,`agent '${e.id}' is not in the registry`);return{info:{id:t.id,name:t.name,iconUrl:t.icon,source:`registry`,version:t.version},custom:null}}async stageProjectSkillFor(e){let t=this.opts.projectSkillSourceDir;if(t===null)return null;let n={threadId:e.info.threadId,agentId:e.info.agent.id},r;try{this.projectSkillStaging??=J5e({localDir:this.opts.localDir,sourceDir:t??xH(`project`,{checkDesktop:!1}),log:this.opts.log,logContext:{localDir:this.opts.localDir}}).finally(()=>{this.projectSkillStaging=null}),r=await this.projectSkillStaging}catch(e){return this.opts.log.warn({err:e,...n},`[acp-threads] skill staging failed`),null}nW(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=U(r,H5e);if(!y7e(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await Tc(i,`utf8`)}}catch(e){return this.opts.log.warn({err:e,...n,skillPath:i},`[acp-threads] skill inline read failed; skipping skill delivery`),null}}async connectAgent(e,t,n,r=`reuse`,i,a=`available`){let o;if(n!==null)o=await this.ensureLaunchable(e,t,d4e(n),i);else{let s=await this.opts.registry.getAgent(e.agentRef.id);if(s===void 0)throw new pq(`unknown-agent`,`agent vanished`);try{o=await L2e(s,mQe(),this.opts.log,void 0,n=>this.ensureLaunchable(e,t,n,i),{reacquire:r===`reacquire`,install:!0,onAcquiring:()=>{Sq(e,t)&&this.emitStatus(e,`installing`)},onResolved:({acquired:t,outcome:n,source:r,elapsedMs:i})=>this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,package:t,outcome:n,source:r,elapsedMs:i},`[acp-threads] agent package acquired`)})}catch(r){if(r instanceof _W&&r.npxCacheEntry!==void 0&&a===`available`&&await this.clearStaleNpxCacheEntry(e,t,r.npxCacheEntry))return this.connectAgent(e,t,n,`reacquire`,i,`spent`);throw r}}if(o===null||!Sq(e,t))return null;let s=await this.resolveLoginShellPath().catch(()=>null);if(!Sq(e,t))return null;let c=await this.stageProjectSkillFor(e);if(!Sq(e,t))return null;e.projectSkill=c;let l=new i7e({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:s});e.terminalAuthBase=Y5e(o),e.agentLaunchPath=jW(o.env),e.agentNpmCache=c3e(o.env),o=z5e(o,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let u=o.kind===`npx`?IW(o):IW(o,e.cwd);e.child=u,e.terminals=l;let d=new Promise(e=>u.once(`close`,()=>e())),f,p=()=>u.exitCode===null&&u.signalCode===null&&u.stdout?.readableEnded!==!0&&u.stdout?.destroyed!==!0?Promise.resolve():(f??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),d.then(()=>{clearTimeout(t),e()})}),f);e.drainStderr=p;let m=``,h=``,g=!0,_=lW(t=>{g&&(m=`${m}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())},e=>{g&&(h=`${h}${e}\n`.slice(-16e3))}),v=o.kind,y=!1,b=()=>v===`npx`&&g&&a===`available`&&(SW(h)!==null||G2e(h)),x=()=>y||b()||!Sq(e,t);if(u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,_.write),u.stderr?.on(`end`,_.end),u.stderr?.on(`data`,t=>{for(let n of t.split(`
|
|
1014
1014
|
`))n.trim()!==``&&e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e))}),u.on(`error`,t=>{x()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),u.on(`exit`,(t,n)=>{if(e.child!==u)return;let r=h7e.has(e.info.status);e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),l.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),Cq(e).then(i=>{if(e.terminals!==l||bq(e)||x())return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let a=`agent exited (${n??t??`unknown`})`;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:i},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,a,r?d5e({exitCode:t,signal:n,tail:i}):void 0),this.failPendingPermissions(e)}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] exit diagnostics failed`)})}),u.stdin===null||u.stdout===null)throw new pq(`spawn-failed`,`agent process has no stdio`);let S=Awe(Yae.toWeb(u.stdin),Ac.toWeb(u.stdout)),C=cTe({name:`open-knowledge`}).onRequest(dS.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options,t.params._meta)).onRequest(dS.client.fs.readTextFile,async t=>{this.touchTurnActivity(e);try{return await this.handleFsRead(t.params.path,t.params.line??null,t.params.limit??null)}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file read failed`),n}}).onRequest(dS.client.fs.writeTextFile,async t=>{try{return await this.handleFsWrite(e,t.params.path,t.params.content)}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file write failed`),n}}).onRequest(dS.client.terminal.create,t=>(this.touchTurnActivity(e),l.create(t.params))).onRequest(dS.client.terminal.output,t=>(this.touchTurnActivity(e),l.output(t.params.terminalId))).onRequest(dS.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),l.waitForExit(t.params.terminalId))).onRequest(dS.client.terminal.kill,async t=>(this.touchTurnActivity(e),await l.kill(t.params.terminalId),{})).onRequest(dS.client.terminal.release,async t=>(this.touchTurnActivity(e),await l.release(t.params.terminalId),{})).onNotification(dS.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(S);e.conn=C;let w=async t=>{if(await p(),e.conn!==C||x()||(t!==null&&this.opts.log.warn({err:t.err,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status===`exited`||e.info.status===`error`))return;if(t===null){this.emitStatus(e,`exited`,`agent connection closed`);return}let{err:n}=t;this.emitStatus(e,`error`,`agent connection failed: ${n instanceof Error?n.message:String(n)}`)};C.closed.then(()=>w(null),e=>w({err:e}));let T;try{T=await C.agent.request(dS.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:tW},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,...this.opts.terminalAuthAvailable===!0?{auth:{terminal:!0}}:{},session:{configOptions:{boolean:{}}}}})}catch(r){if(this.opts.log.warn({err:r,threadId:e.info.threadId},`[acp-threads] initialize failed`),o.kind===`npx`||o.kind===`uvx`){await p();let e=V2e(o,m,r);if(e!==null)throw e}let s=v===`npx`&&a===`available`?SW(h):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,t,s)||v===`npx`&&a===`available`&&G2e(h)&&await this.discardRefusedNpxLaunch(e,t,o))return y=!0,this.connectAgent(e,t,n,`reacquire`,i,`spent`);throw new pq(`spawn-failed`,`initialize failed: ${_q(r)}`)}finally{g=!1,m=``,h=``}return Sq(e,t)?(e.lastInit=T,e.info.promptCapabilities=T.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:C,init:T,launch:o}):null}async discardRefusedNpxLaunch(e,t,n){return Sq(e,t)?(this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,package:J2e(n.args)},`[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch`),await this.discardFailedLaunch(e),Sq(e,t)):!1}async clearStaleNpxCacheEntry(e,t,n){let r={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:cW(n)},i=await this.removeStaleNpxCacheEntry(n,r);return i===`kept`?!1:Sq(e,t)?(this.opts.log.warn(r,i===`recently-removed`?`[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again`:`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),Sq(e,t)):(i===`removed`&&this.opts.log.warn(r,`[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched`),!1)}async removeStaleNpxCacheEntry(e,t){let n=this.npxCacheClears.get(e);if(n!==void 0&&Date.now()-n<3e5)return`recently-removed`;let r=Date.now();this.npxCacheClears.set(e,r);let i=()=>{this.npxCacheClears.get(e)===r&&this.npxCacheClears.delete(e)};for(let n of[`package.json`,`concurrency.lock`]){let r=await Oc(U(e,n)).then(()=>`present`,e=>e.code??`unknown`);if(r!==`ENOENT`)return this.opts.log.warn({...t,file:n,code:r},`[acp-threads] leaving an npx cache entry alone`),i(),`kept`}try{await OU(e,{recursive:!0,force:!0})}catch(e){return this.opts.log.warn({err:e,...t},`[acp-threads] stale npx cache entry could not be cleared`),i(),`kept`}return`removed`}async discardFailedLaunch(e){e.drainStderr=null,e.stderrTail=[],await this.stopAgentProcess(e,`[acp-threads] terminal cleanup before relaunch failed`)}async stopAgentProcess(e,t){let n=e.child,r=e.conn,i=e.terminals;e.child=null,e.conn=null,e.terminals=null;try{r?.close()}catch{}await i?.disposeAll().catch(n=>{this.opts.log.warn({err:n,threadId:e.info.threadId},t)}),n!==null&&await zW(n,{graceMs:p7e})}async ensureLaunchable(e,t,n,r){let i;try{await kW(n),i=await this.withLoginShellPathIfEligible(n)}catch(a){if(!(a instanceof _W)||a.code!==`command-not-found`)throw a;let o=await this.retryWithLoginShellPath(n);if(o===null)return this.fallbackToManagedRuntime(e,t,n,a,void 0,r);i=o}return Sq(e,t)?this.ensureInterpreterRuns(e,t,i,r):null}async ensureInterpreterRuns(e,t,n,r){if(n.kind!==`npx`&&n.kind!==`uvx`)return n;let i=await this.probeInterpreterOnce(n);if(!Sq(e,t))return null;if(i===null)return n;if(i.kind===`incompatible`){let r=await this.withPreferredLoginShellPathIfEligible(n);if(!Sq(e,t))return null;if(jW(r.env)!==jW(n.env))try{await kW(r);let n=await this.probeInterpreterOnce(r);if(!Sq(e,t))return null;if(n===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),r;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:r.cmd,kind:r.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof _W)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:i.kind,detail:i.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let a=i.kind===`incompatible`,o=new _W(`command-not-found`,a?M4e(n,i.detail):C4e(n,i.detail)),s=new _W(`command-not-found`,a?N4e(n,i.detail):k4e(n,o.message));return this.fallbackToManagedRuntime(e,t,n,o,{declined:o,expired:s},r)}async fallbackToManagedRuntime(e,t,n,r,i,a){if(n.kind!==`npx`&&n.kind!==`uvx`)throw r;let o=y5e(n.kind);if(!w5e(o))throw r;let s=await this.provideManagedRuntime(e,t,o,i===void 0?`missing`:`broken`,a).catch(e=>{throw i!==void 0&&e instanceof mq?e.refusal===`timeout`?i.expired:i.declined:e});if(s===null)return null;let c=f4e(n,s);await kW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;if(l.kind===`incompatible`)throw new _W(`install-failed`,T4e(l.detail));return this.repairManagedRuntime(e,t,n,o,l.detail,a)}async repairManagedRuntime(e,t,n,r,i,a){if(!Sq(e,t))return null;let o={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:r,detail:i};if(this.opts.log.warn(o,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await k5e(r,this.opts.log,this.opts.runtimeInstall?.root))throw new _W(`install-failed`,E4e(n,i));let s=await this.provideManagedRuntime(e,t,r,`damaged`,a).catch(e=>{throw e instanceof mq?new _W(`command-not-found`,e.refusal===`timeout`?O4e(n):D4e(n)):e});if(s===null)return null;let c=f4e(n,s);await kW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;throw this.opts.log.error({...o,detail:l.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new _W(`install-failed`,l.kind===`incompatible`?T4e(l.detail):w4e(c,l.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,jW(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await A4e(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await j4e(e,void 0,this.opts.log);if(t!==null)return{kind:`incompatible`,detail:t}}return this.healthyInterpreters.add(t),null}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(jW(t.env)===jW(e.env))return null;try{await kW(t)}catch(t){if(!(t instanceof _W))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||MW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:p4e(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||MW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:m4e(e,t)}async provideManagedRuntime(e,t,n,r,i){let a=this.opts.runtimeInstall?.root;await O5e(n,this.opts.log,a);let o=await D5e(n,a).catch(()=>null);if(o!==null)return o;if(!Sq(e,t))return null;let s=await this.requestRuntimeConsent(e,n,r,i);if(s===`closed`||!Sq(e,t))return null;if(s!==`granted`)throw new mq(s,s===`timeout`?k7e(n):O7e(n));try{let r=await this.downloadRuntime(e,t,n);return Sq(e,t)?r:null}catch(e){let t=$K(n).displayName;throw new _W(`install-failed`,`couldn't install ${t}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=$K(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:i,runtime:t,displayName:a.displayName,provides:a.provides,version:a.version,approxSizeMB:a.approxSizeMB,sourceHost:a.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(i),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:i,decision:`timeout`,ts:Date.now()}),t(`timeout`)},r);n.unref?.(),e.pendingRuntimeConsent.set(i,{resolve:t,timer:n})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t,n){this.emitStatus(e,`installing`);let r=0;return A5e(n,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:i=>{let a=Date.now();a-r<400||(r=a,Sq(e,t)&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:n,phase:`downloading`,receivedBytes:i.receivedBytes,totalBytes:i.totalBytes??void 0,ts:a}))}})}async buildMcpServers(e,t,n,r=dq){let i=[],a=null,s=!1,c;if(C7e(e.agentRef))c=await this.settlePiBridge(e,t,r)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)c=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&n.agentCapabilities?.mcpCapabilities?.http===!0)i.push({type:`http`,name:o(),url:`${e}/mcp`,headers:[{name:V0e,value:`1`}]}),c=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=yW();e==null?c=`none`:(i.push({name:o(),command:e.command,args:[...e.args],env:[{name:eo,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[],...Object.entries(e.env??{}).map(([e,t])=>({name:e,value:t}))]}),c=`stdio-entry-env`)}}if(this.opts.agentBrowserTools?.()===!0&&Sq(e,t)){if(t3e(e.agentRef)){let n=await this.agentBrowserServer(e,t,r);typeof n==`string`?a=n:(i.push(n),s=!0)}else this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] browser tools are on, but only Claude Code and Codex chats get the browser`)}return c===`none`?this.opts.log.warn({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] no OK MCP transport available for this agent — it starts without OK tools`):this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,hostedMarker:c},`[acp-threads] OK MCP injection outcome`),{servers:i,hostedMarker:c,browserUnavailable:a,browserInjected:s}}noteBrowserUnavailable(e,t){if(e.browserInjected){e.browserNotice=null;return}t!==null&&t!==e.browserNotice&&(e.browserNotice=t,this.appendEvent(e,{kind:`browser_unavailable`,reason:t,ts:Date.now()}))}async agentBrowserServer(e,t,n){let r={threadId:e.info.threadId,agentId:e.agentRef.id},i=this.opts.globalDir;if(i===null)return this.opts.log.warn(r,`[acp-threads] browser tools are on but there is no per-user OpenKnowledge folder to start the browser from — the chat starts without a browser`),`failed`;let a=await this.resolveLoginShellPath().catch(()=>null);if(!Sq(e,t))return`failed`;let o=[],s=(this.opts.resolveBrowserNpx??s3e)([e.agentLaunchPath,a,yW()],void 0,t=>!(nW(this.opts.contentDir,t)||nW(e.cwd,t))&&m3e(t)?!0:(o.push(t),!1));if(s===null)return this.opts.log.warn({...r,rejectedNpx:o},`[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser`),`no-node`;let c=e.agentNpmCache??null,l;try{l=f3e({npx:s,folders:await g3e(i,e.info.threadId),npmCache:c})}catch(e){return this.opts.log.warn({...r,err:e},`[acp-threads] preparing the browser failed — the chat starts without a browser`),`failed`}if(l===null)return this.opts.log.warn({...r,npx:s.npx},`[acp-threads] the npx found cannot start the browser — the chat starts without a browser`),`no-node`;if(!Sq(e,t))return`failed`;let u=Math.min(this.browserInstallWaitMs,n),d,f=await Promise.race([this.installBrowserPackage(e,s,c),new Promise(e=>{d=setTimeout(()=>e(`still-installing`),u),d.unref?.()})]).finally(()=>clearTimeout(d));return f===`still-installing`?(this.opts.log.warn({...r,waitedMs:u},`[acp-threads] installing the browser is taking too long — the chat starts without a browser`),`failed`):f?(this.opts.log.info({...r,command:l.command,npx:s.npx},`[acp-threads] browser MCP injected`),l):`failed`}async installBrowserPackage(e,t,n,r=`cached`,i=`available`){let a={threadId:e.info.threadId,agentId:e.agentRef.id},o=this.opts.ensureBrowserPackage??$2e,s=l3e(t,n,r);try{return await o(s,K4e,this.opts.log,{reacquire:!0}),!0}catch(o){if(o instanceof _W&&o.npxCacheEntry!==void 0&&i===`available`){let i={...a,npxCacheEntry:cW(o.npxCacheEntry)},s=await this.removeStaleNpxCacheEntry(o.npxCacheEntry,i);if(s!==`kept`)return this.opts.log.warn(i,s===`removed`?`[acp-threads] cleared a stale browser npx cache entry; reinstalling the browser`:`[acp-threads] browser npx cache entry was cleared by another launch moments ago; reinstalling the browser without clearing it again`),this.installBrowserPackage(e,t,n,r,`spent`)}return r===`cached`?(this.opts.log.info({...a,err:o},`[acp-threads] installing the browser from npm's cached package data failed; installing it again with fresh package data`),this.installBrowserPackage(e,t,n,`fresh`,i)):(this.opts.log.warn({...a,err:o},`[acp-threads] installing the browser failed — the chat starts without a browser`),!1)}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=fQe[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async settlePiBridge(e,t,n){let r=this.opts.probePiAcpBridge,i=e.info.threadId;if(r===void 0)return this.opts.log.debug({threadId:i,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let a;try{a=await r(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:i},`[acp-threads] Pi bridge probe failed`),`unknown`}if(!Sq(e,t))return`unknown`;if(a.project===`unavailable`)return this.opts.log.warn({threadId:i,cwd:a.cwd,err:Error(a.error)},`[acp-threads] Pi project folder is unavailable; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:`project-path-unavailable`,bridgePath:a.bridgePath,detail:a.error,ts:Date.now()}),`unavailable`;if(a.bridgeLoadable)return this.opts.log.info({threadId:i,bridge:a.bridge,bridgePath:a.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(a.bridge===`foreign`||a.bridge===`unreadable`)return this.opts.log.warn({threadId:i,bridge:a.bridge,bridgePath:a.bridgePath},`[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:a.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:a.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:i},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let o=this.opts.ensurePiAcpBridge;if(o===void 0)return this.opts.log.warn({threadId:i},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let s=crypto.randomUUID(),c=await this.requestPiBridgeConsent(e,s,a,n);if(c===`declined`&&(e.piBridgeDeclined=!0),!Sq(e,t))return`unknown`;if(c!==`granted`)return this.opts.log.info({threadId:i,decision:c},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let l;try{l=await o(e.cwd,a.canonicalCwd)}catch(n){let r=n instanceof Error?n.message:String(n);return this.opts.log.warn({err:n,threadId:i},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,t,s,`bridge-failed`,a.bridgePath,{detail:r}),`unavailable`}if(l.ok)return this.opts.log.info({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),Sq(e,t)?(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:s,state:`ready`,bridgePath:l.bridgePath,bridge:l.bridge,trust:l.trust,ts:Date.now()}),`loadable`):`unknown`;let u=l.bridge===`written`||l.bridge===`refreshed`||l.bridge===`unchanged`,d=l.bridge===`refused-project-path`?`project-path-unavailable`:l.bridge===`refused-foreign`?`foreign-file`:l.bridge===`refused-unreadable`?`unreadable-file`:u?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath,err:l.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,t,s,d,l.bridgePath,{bridge:l.bridge,trust:l.trust,...l.error===void 0?{}:{detail:l.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i,a){Sq(e,t)&&this.appendEvent(e,{kind:`pi_bridge_status`,requestId:n,state:r,bridgePath:i,...a,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:n.canonicalCwd,otherExtensions:n.otherExtensions,ts:Date.now()}),new Promise(n=>{let i=setTimeout(()=>{e.pendingPiBridgeConsent.delete(t),this.appendEvent(e,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:`timeout`,ts:Date.now()}),n(`timeout`)},r);i.unref?.(),e.pendingPiBridgeConsent.set(t,{resolve:n,timer:i})})}respondPiBridgeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingPiBridgeConsent.get(t);if(i===void 0)return;r.pendingPiBridgeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async startThread(e,t,n,r,i=dq,a=`reuse`){let o;try{o=await this.connectAgent(e,t,r,a,i)}catch(n){let r=await M7e(n,e,Sq(e,t)||bq(e));await this.failLaunch(e,t,r.agentMessage,r);return}if(o===null)return;let{conn:s,init:c,launch:l}=o;if(await this.openSession(e,t,s,c,n.settings,`park`,i)!==!0||!Sq(e,t))return;this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:l.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`);let u=t.initialPrompt;t.initialPrompt=null,u!==null&&this.sendPrompt(e.info.threadId,u.content,u.attachments)}async openSession(e,t,n,r,i,a=`park`,o=dq){e.info.availableCommands=null;let{servers:s,browserUnavailable:c,browserInjected:l}=await this.buildMcpServers(e,t,r,o);if(!Sq(e,t))return!1;e.browserInjected=l,this.noteBrowserUnavailable(e,c);try{let i=await n.agent.request(dS.agent.session.new,{cwd:e.cwd,mcpServers:s});if(!Sq(e,t))return!1;e.sessionId=i.sessionId,e.info.resumable=P7e(r),e.confirmedContextWindow=j7e(e),e.info.contextWindow=e.confirmedContextWindow,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),i.modes!==void 0&&i.modes!==null&&(e.info.modes=i.modes,this.emitInfo(e)),i.configOptions!==void 0&&i.configOptions!==null&&(e.info.configOptions=i.configOptions,this.emitInfo(e))}catch(n){let i=_q(n);if(A7e(n)){let o=`sign in required: ${i}`,s={reason:`auth-required`,agentMessage:i,machineDetail:Tq(n,e),authMethods:sq(r.authMethods,e.terminalAuthBase)};return Sq(e,t)?a===`report`?`auth-required`:(this.emitStatus(e,`auth_required`,o,s),!1):(this.logSuppressedStatus(e,`auth_required`,o,s),!1)}let o=Sq(e,t)||bq(e);return await this.failLaunch(e,t,`session setup failed: ${i}`,{reason:`session-setup`,agentMessage:i,machineDetail:wq({primary:vq(n),tail:o?await Cq(e):void 0})}),!1}return!Sq(e,t)||i?.config!==void 0&&(await this.applyInitialConfig(e,t,n,i.config),!Sq(e,t))||i?.modeId!==void 0&&(await this.applyInitialMode(e,t,n,i.modeId),!Sq(e,t))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.closed)throw new pq(`not-ready`,`the thread is closing`);if(r.info.archived!==!0)throw new pq(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new pq(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new pq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.resumeInFlight=!0;let i=Date.now();try{await this.ensureLogResolved(r);let a=r.sessionId,{info:o,custom:s}=await this.resolveAgentInfo(r.agentRef);if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new pq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let c=xq(r);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let l=t!==void 0&&t!==``||n!==void 0&&n.length>0;l&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`spawning`);try{if(a===null)throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-session`},`[acp-threads] thread is not resumable`),new pq(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,c,s,`reuse`,fq);if(o===null)throw new pq(`not-ready`,`thread closed during resume`);let{conn:u,init:d}=o;r.info.resumable=P7e(d),r.confirmedContextWindow=j7e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:f,browserUnavailable:p,browserInjected:m}=await this.buildMcpServers(r,c,d,fq);if(!Sq(r,c))throw new pq(`not-ready`,`thread closed during resume`);r.browserInjected=m,this.noteBrowserUnavailable(r,p);let h=d.agentCapabilities,g=h?.sessionCapabilities?.resume!=null,_;if(g)_=await u.agent.request(dS.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:f});else if(h?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{_=await u.agent.request(dS.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:f}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-resume-capability`},`[acp-threads] thread is not resumable`),new pq(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);if(!Sq(r,c))throw new pq(`not-ready`,`thread closed during resume`);r.sessionId=a;let v=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),y=r.info.modes?.currentModeId,b=_.modes;b!=null&&(r.info.modes=b);let x=_.configOptions;if(x!=null&&(r.info.configOptions=x),await this.applyInitialConfig(r,c,u,v,x==null),!Sq(r,c)||y!==void 0&&(await this.applyInitialMode(r,c,u,y,b==null),!Sq(r,c)))throw new pq(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:g?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),l&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r,await M7e(t,r,!0)),t instanceof pq?t:t instanceof _W?new pq(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new pq(`resume-unsupported`,`couldn't resume the previous session: ${_q(t)}`))}}finally{r.resumeInFlight=!1}}hasStartedWork(e){let t=this.threads.get(e);return t!==void 0&&t.events.some(e=>e.kind===`user_message`)}async setContextWindow(e,t){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);let n=this.mustGet(e);this.assertContextWindowChangeable(n,t);let{custom:r}=await this.resolveAgentInfo(n.agentRef);this.assertContextWindowChangeable(n,t);let i=n.launchSettings?.contextWindow,a=n.confirmedContextWindow??null;n.launchSettings={...n.launchSettings,contextWindow:Math.floor(t)},n.resumeInFlight=!0;let o=n.launchTicket?.initialPrompt??null,s=xq(n),c=!1;n.sessionBeforeRestart={sessionId:n.sessionId,resumable:n.info.resumable,contextWindow:n.info.contextWindow};try{if(await this.teardownFailedAgent(n),n.stderrTail=[],n.cancelRequested=!1,n.turnActive=!1,this.emitStatus(n,`spawning`),await this.startThread(n,s,{agent:n.agentRef,settings:n.launchSettings},r,fq),!Sq(n,s))throw new pq(`not-ready`,`thread closed during the context window change`);let t=this.getInfo(e)?.status;if(t===`ready`||t===`running`)return c=!0,o!==null&&this.dispatchPrompt(n,o.content,o.attachments,{echo:!0}),{...n.info};throw new pq(`spawn-failed`,yq(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof pq)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new pq(`spawn-failed`,t)}finally{!c&&o!==null&&this.opts.log.info({threadId:e,agentId:n.agentRef.id},`[acp-threads] pending first message dropped: the context window change did not start the agent`),!c&&this.threads.has(e)&&(n.launchSettings={...n.launchSettings,contextWindow:i},n.confirmedContextWindow=a,n.info.contextWindow=this.getInfo(e)?.status===`ready`?a:null,this.endRestart(n),this.emitInfo(n)),n.sessionBeforeRestart=null,n.resumeInFlight=!1}}assertContextWindowChangeable(e,t){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);if(e.closed)throw new pq(`not-ready`,`the thread is closing`);if(!Number.isFinite(t)||t<=0)throw new pq(`not-ready`,`a context window must be a positive number of tokens`);let n=B5e({agentId:e.agentRef.id,archived:e.info.archived===!0,turnActive:e.turnActive,hasStartedWork:this.hasStartedWork(e.info.threadId)});if(n.kind===`unsupported`)throw new pq(`not-ready`,`this agent takes its context window from the model`);if(n.kind===`needs-new-chat`)throw new pq(`not-ready`,`start a new chat to change the context window`);if(e.resumeInFlight)throw new pq(`not-ready`,`a restart is already in progress`)}async retryThread(e){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);let t=this.mustGet(e);this.assertRetryable(t);let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);this.assertRetryable(t),t.resumeInFlight=!0;let i=xq(t);t.sessionBeforeRestart={sessionId:t.sessionId,resumable:t.info.resumable,contextWindow:t.info.contextWindow};try{j2e(),this.healthyInterpreters.clear(),await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`spawning`);try{await this.startThread(t,i,{agent:t.agentRef,settings:t.launchSettings},r,fq,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new pq(`spawn-failed`,n)}if(!Sq(t,i))throw new pq(`not-ready`,`thread closed during retry`);let a=this.getInfo(e)?.status;if(a===`ready`||a===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new pq(`spawn-failed`,yq(t)??`the agent failed to start`)}finally{this.threads.has(e)&&this.endRestart(t)&&this.emitInfo(t),t.resumeInFlight=!1}}assertRetryable(e){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);if(e.closed)throw new pq(`not-ready`,`the thread is closing`);if(e.info.archived===!0)throw new pq(`not-ready`,`the thread is archived — resume it instead`);if(e.info.status!==`error`&&e.info.status!==`auth_required`&&!e.authInFlight)throw new pq(`not-ready`,`this thread did not fail to start`);if(e.resumeInFlight)throw new pq(`not-ready`,`a retry is already in progress`)}terminalAuthLaunch(e,t){let n=this.mustGet(e),r=e7e(n.lastInit?.authMethods,n.terminalAuthBase,t);if(r===null)throw new pq(`not-ready`,`this agent offers no terminal sign-in by that name`);return r}async authenticateThread(e,t){if(this.destroyed)throw new pq(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.closed)throw new pq(`not-ready`,`the thread is closing`);if(n.info.archived===!0)throw new pq(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new pq(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit,a=n.launchTicket;if(r===null||i===null||n.child===null||a===null)throw new pq(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new pq(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new pq(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(await n.drainStderr?.(),n.conn!==r)throw hq();let t=e instanceof x7e?`the sign-in didn't complete in time — try again`:_q(e);throw n.child===null?new pq(`agent-exited`,t):(this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:Tq(e,n),authMethods:sq(i.authMethods,n.terminalAuthBase)}),new pq(`not-ready`,t))}if(bq(n))throw new pq(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw hq();let o=await this.openSession(n,a,r,i,n.launchSettings,`report`,fq);if(o===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${_q(t)}`,{reason:`auth-required`,agentMessage:_q(t),machineDetail:Tq(t,n),authMethods:sq(i.authMethods,n.terminalAuthBase)}),t}}if(o!==!0)throw bq(n)?new pq(`not-ready`,`thread closed during sign-in`):Sq(n,a)?new pq(`not-ready`,yq(n)??`${n.info.agent.name} still couldn't start a conversation`):hq();return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new x7e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(dS.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(e.launchTicket=null,bq(e)){await this.stopFailedAgent(e),this.emitStatus(e,`exited`,`resume failed`,t);return}e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingConsents(e);try{e.conn?.close()}catch{}let n=e.child;n!==null&&await zW(n,{graceMs:m7e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(uH(e.agentSessionId)),e.info.archived=!0,this.recordTerminalStatus(e,`exited`,`resume failed`,t),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new pq(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new pq(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new pq(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new pq(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new pq(`not-ready`,`20 messages are already waiting — let the agent catch up`);let i={id:crypto.randomUUID(),content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.queue=[...e,i],r.info.lastActivityAt=Date.now(),this.emitInfo(r);return}this.dispatchPrompt(r,t,n,{echo:!0})}steerPrompt(e,t,n){let r=this.mustGet(e);this.assertSteerable(r),this.steerWith(r,t,n)}sendQueuedNow(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.find(e=>e.id===t);if(i===void 0)return!1;this.assertSteerable(n);let a=this.takeSteer(n),o=r.filter(e=>e.id!==t),s=a===null?o:[N7e(a),...o];return n.info.queue=s.length>0?s:void 0,this.steerWith(n,i.content,i.attachments),!0}assertSteerable(e){if(e.info.archived===!0)throw new pq(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new pq(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new pq(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new pq(`not-ready`,`thread has no live agent session`)}steerWith(e,t,n){if(!e.turnActive){this.dispatchPrompt(e,t,n,{echo:!0});return}this.clearSteer(e);let r={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),e.info.steer=r,e.info.lastActivityAt=Date.now(),this.emitInfo(e);let i=setTimeout(()=>this.demoteStalledSteer(e),this.steerStallMs);i.unref?.(),e.steerStallTimer=i,this.cancelTurn(e,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;t===void 0||e.closed||!e.turnActive||(e.info.steer=void 0,e.info.queue=[N7e(t),...e.info.queue??[]],this.emitInfo(e))}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}armStallTimer(e,t=this.turnStallMs){e.stallTimer!==null&&clearTimeout(e.stallTimer);let n=setTimeout(()=>this.checkStall(e),t);n.unref?.(),e.stallTimer=n}checkStall(e){if(e.stallTimer=null,e.closed||!e.turnActive||e.info.stalledSince!==void 0)return;if(e.pendingPermissions.size>0){this.armStallTimer(e);return}let t=Date.now()-e.agentActivityAt;if(t<this.turnStallMs){this.armStallTimer(e,this.turnStallMs-t);return}e.info.stalledSince=e.agentActivityAt,this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,silentMs:t},`[acp-threads] turn stalled: no agent activity`),this.emitInfo(e)}touchTurnActivity(e){let t=Date.now();if(e.agentActivityAt=t,e.info.lastActivityAt=t,e.info.stalledSince===void 0)return;let n=Date.now()-e.info.stalledSince;e.info.stalledSince=void 0,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,stalledForMs:n},`[acp-threads] turn resumed after stall`),this.emitInfo(e),e.turnActive&&this.armStallTimer(e)}clearStall(e){e.stallTimer!==null&&(clearTimeout(e.stallTimer),e.stallTimer=null),e.info.stalledSince=void 0}logTurnEnded(e,t){let n=e.turnStartedAt;e.turnStartedAt=null,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,outcome:t,durationMs:n===null?void 0:Date.now()-n},`[acp-threads] turn ended`)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length!==r.length&&(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,t.attachments,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t,n){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=u7e(n,e.info.agent.name),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}let r={kind:`user_message`,content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),this.appendEvent(e,r)}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new pq(`not-ready`,`the thread is closing`);let r=uq(t);return r===``||r===n.info.title?{...n.info}:(await this.ensureLogResolved(n),n.info.title=r,this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId),{...n.info})}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new pq(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t,a=null;if(e.envNotePending&&!t.startsWith(`/`)){e.envNotePending=!1;let n=e.projectSkill,r=n!==null&&n.inlineText!==null;i=`${_7e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=b7e(n.skillPath,n.inlineText,e.info.promptCapabilities)),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,skillPath:n.skillPath,delivery:r?`inline`:`path`},`[acp-threads] skill pointer sent`))}e.turnActive=!0,e.cancelRequested=!1,e.turnStartedAt=Date.now(),e.agentActivityAt=e.turnStartedAt,this.appendEvent(e,{kind:`turn_started`,ts:e.turnStartedAt}),this.emitStatus(e,`running`),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] turn started`),this.armStallTimer(e);let o=e.sessionId;u2e(i,n,e.info.promptCapabilities,e=>this.confinePath(e).then(({abs:e,rel:t})=>({abs:e,rel:t}))).then(t=>{if(t.dropped.length>0){this.opts.log.warn({threadId:e.info.threadId,dropped:t.dropped.map(e=>({kind:e.part.kind,reason:e.reason}))},`[acp-threads] dropped attachment parts before session/prompt`);let n=Date.now();for(let r of t.dropped){let t=r.part.kind===`image`||r.part.kind===`blob`?r.part.name:r.part.name||r.part.path;this.appendEvent(e,{kind:`agent_stderr`,line:`[attachment dropped] ${t}: ${r.reason}`,ts:n})}}if(e.sessionId===null||e.conn===null)throw new pq(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new S7e;return e.conn.agent.request(dS.agent.session.prompt,{sessionId:o,prompt:a===null?[...t.blocks]:[...t.blocks,a]})}).then(t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,t.stopReason),!bq(e)){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,n.attachments,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(async t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,e.cancelRequested?`cancelled`:`failed`),bq(e))return;if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}if(A7e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${_q(t)}`,{reason:`auth-required`,agentMessage:_q(t),machineDetail:Tq(t,e),authMethods:sq(e.lastInit?.authMethods,e.terminalAuthBase)});return}let n=await Cq(e);this.emitStatus(e,`error`,`prompt failed: ${_q(t)}`,{reason:`prompt`,agentMessage:_q(t),machineDetail:wq({primary:vq(t),tail:n})})}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] prompt diagnostics failed`)})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){if(t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),e.conn===null||e.sessionId===null)return;e.turnActive&&(e.cancelRequested=!0);let n=e.info.stalledSince!==void 0;this.clearStall(e),n&&this.emitInfo(e),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(dS.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)})}setMode(e,t){let n=this.mustGet(e);if(n.info.archived===!0){let e=n.info.modes;if(e==null||!e.availableModes.some(e=>e.id===t))throw new pq(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new pq(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new pq(`not-ready`,`thread has no live agent session`);n.conn.agent.request(dS.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.info.archived===!0){let e=(r.info.configOptions??[]).find(e=>e.id===t);if(e===void 0)throw new pq(`not-ready`,`no such config option: ${t}`);if(!gq(e,n))throw new pq(`not-ready`,`invalid value for ${t}`);r.info.configOptions=(r.info.configOptions??[]).map(e=>e.id===t?{...e,currentValue:n}:e),this.emitInfo(r);return}if(r.resumeInFlight)throw new pq(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new pq(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(dS.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n,r,i=!1){let a=e.sessionId;if(a===null)return;let o=!1,s=new Set,c=t=>(e.info.configOptions??[]).find(e=>e.id===t),l=Object.keys(r).length+1,u=Object.entries(r);for(let d=0;u.length>0&&d<l;d+=1){let l=e=>c(e)?.category===`model`,f=!1,p=[...u].sort(([e],[t])=>Number(l(t))-Number(l(e)));for(let[r,l]of p){let u=c(r);if(u===void 0||(!i||d>0)&&u.currentValue===l||!gq(u,l))continue;let p=typeof l==`boolean`?{sessionId:a,configId:r,type:`boolean`,value:l}:{sessionId:a,configId:r,value:l};try{let i=await n.agent.request(dS.agent.session.setConfigOption,p);if(!Sq(e,t))return;e.info.configOptions=i.configOptions,s.delete(r),o=!0,f=!0}catch(t){s.add(r),this.opts.log.info({err:t,threadId:e.info.threadId,configId:r,pass:d},`[acp-threads] initial config apply attempt failed`)}if(!Sq(e,t))return}if(!f)break;u=Object.entries(r).filter(([e,t])=>c(e)?.currentValue!==t)}s.size>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:[...s],sessionStateUnknown:i},`[acp-threads] some remembered config options could not be applied to the new session`);let d=[],f=[];for(let[e,t]of Object.entries(r)){if(s.has(e))continue;let n=c(e);n===void 0?d.push(e):n.currentValue!==t&&f.push(e)}(d.length>0||f.length>0)&&this.opts.log.info({threadId:e.info.threadId,missingConfigIds:d,unmatchedConfigIds:f,sessionStateUnknown:i},`[acp-threads] some remembered config options did not come back in the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n,r,i=!1){let a=e.sessionId;if(a===null)return;let o=e.info.modes;if(o!=null&&o.availableModes.some(e=>e.id===r)){if(!i&&o.currentModeId===r)return;try{if(await n.agent.request(dS.agent.session.setMode,{sessionId:a,modeId:r}),!Sq(e,t))return;e.info.modes={...o,currentModeId:r},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let s=(e.info.configOptions??[]).find(e=>e.category===`mode`&&gq(e,r));if(s!==void 0&&!(!i&&s.currentValue===r))try{let i=await n.agent.request(dS.agent.session.setConfigOption,{sessionId:a,configId:s.id,value:r});if(!Sq(e,t))return;e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),this.touchTurnActivity(r),n.kind===`selected`&&i.offeredOptionIds.has(n.optionId)?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}setChatGrant(e,t,n){let r=this.mustGet(e);r.chatGrants.has(t)!==n&&(n?r.chatGrants.add(t):r.chatGrants.delete(t),r.info.chatGrants=r.chatGrants.size>0?[...r.chatGrants]:void 0,this.opts.log.info({threadId:e,agentId:r.info.agent.id,grant:t,enabled:n},`[acp-threads] chat grant changed`),this.emitInfo(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,n.launchTicket=null,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await zW(r,{graceMs:t?.killGraceMs??p7e})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(uH(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(uH(n.agentSessionId)).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){await this.forgetThread(n),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.recordTerminalStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new pq(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new pq(`not-ready`,`a resume is in progress`);await this.forgetThread(t),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async forgetThread(e){let t=e.info.threadId;this.threads.delete(t),e.subscribers.clear(),e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),this.clearStall(e),await this.persistence.whenIdle(t),await this.persistence.delete(t),this.opts.globalDir!==null&&await _3e(this.opts.globalDir,t).catch(e=>{this.opts.log.warn({err:e,threadId:t},`[acp-threads] removing browser folders failed`)})}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:m7e})))}async handlePermissionRequest(e,t,n,r){this.touchTurnActivity(e);let i=F7e(await L7e(e,t,r,this.opts.log),t),a={...t,...t.title==null&&i.title!=null?{title:i.title}:{},...t.rawInput===void 0&&i.rawInput!==void 0?{rawInput:i.rawInput}:{}},o=a3e(i,{requestMeta:r,browserInjected:e.browserInjected,agentId:e.info.agent.id}),s=this.opts.permissions.decide(e.info.agent.id,t,n,o,e.chatGrants,this.opts.autoApproveOkTools?.()??!0);if(s.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:s.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:s.auto.optionId}}}let c=crypto.randomUUID(),l=oQe(o,n);return this.appendEvent(e,{kind:`permission_request`,requestId:c,toolCall:a,options:l,...RZe(t)===null?{}:{readOnlyShell:!0},ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(n=>{let r=setTimeout(()=>{e.pendingPermissions.delete(c),this.appendEvent(e,{kind:`permission_resolved`,requestId:c,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),n({outcome:{outcome:`cancelled`}})},6e5);r.unref?.(),e.pendingPermissions.set(c,{timer:r,offeredOptionIds:new Set(l.map(e=>e.optionId)),resolve:r=>{if(r.outcome.outcome===`selected`){let n=r.outcome.optionId,i=l.find(e=>e.optionId===n);i!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,i,o)}n(r)}})})}handleSessionUpdate(e,t){this.touchTurnActivity(e);let n=t.update;if(e.browserInjected&&(n.sessionUpdate===`tool_call`||n.sessionUpdate===`tool_call_update`)&&I7e(e,n),n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:rZe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await Tc(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await Tc(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
1015
1015
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
package/dist/index.mjs
CHANGED
|
@@ -1637,6 +1637,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1637
1637
|
`);j(e,o)}function A9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=O9(JSON.parse(n),t),i=n.endsWith(`
|
|
1638
1638
|
`)?`
|
|
1639
1639
|
`:``;j(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}function M9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>F(e,t.name))}catch{return[]}}const SVe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function N9(e){return/\.log\.\d+$/.test(e)}function CVe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||N9(e)}const wVe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function P9(e){let t={contentDirSpellings:E9(e.contentDir)};for(let n of wVe)for(let r of M9(F(e.stagingDir,n)))CVe(r)?k9(r,t):r.endsWith(`.json`)?A9(r,t):j9(r,t);for(let n of M9(F(e.stagingDir,`state`))){let e=ne(n);n.endsWith(`.jsonl`)?k9(n,t):SVe.has(e)?A9(n,t):j9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=Bf.spansCurrent,z9=Bf.spansPrevious,B9=Bf.logsCurrent,V9=Bf.logsPrevious,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function TVe(e){return F(e,...L9,H9)}function EVe(e){return F(e,...L9,U9)}const W9=1e3;async function DVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function OVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function kVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}function AVe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
|
|
1640
|
-
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.
|
|
1640
|
+
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.6`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??NVe,m=r.isOtlpPushEnabled??PVe,g=b(F(he(),`ok-bundle-`));try{y(F(g,`telemetry`),{recursive:!0}),y(F(g,`logs`),{recursive:!0}),y(F(g,`state`),{recursive:!0}),Z9(XEe(n),F(n,...F9,R9),g,F(`telemetry`,R9)),Z9(ZEe(n),F(n,...F9,z9),g,F(`telemetry`,z9)),Z9(dY(n),F(n,...I9,B9),g,F(`logs`,B9)),Z9(fY(n),F(n,...I9,V9),g,F(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,F(g,`logs`,ne(t)));for(let t of e.userStateFiles??[])X9(t,F(g,JK,ne(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,F(g,`diagnostic-reports`,ne(t)))&&(v+=1);let b=F(n,`.ok`,`local`),x=F(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,F(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(j(F(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&j(F(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=AVe(n);e!==null&&j(F(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&j(F(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&j(F(g,`state`,`checkpoint-refs.txt`),D),X9(TVe(n),F(g,`state`,H9)),X9(EVe(n),F(g,`state`,U9)),Z9(pEe(n),F(b,zf),g,`state/last-spawn-error.log`),X9(F(b,Hf),F(g,`state`,Hf)),X9(F(b,Uf),F(g,`state`,Uf)),X9(F(b,Vf),F(g,`state`,Vf));let O=p(),A=d(),te=f(),M={ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te}};j(F(g,`state`,`runtime.json`),`${JSON.stringify(M,null,2)}\n`);let N=S===`running`?`running
|
|
1641
1641
|
`:`not-running (${w})\n`;j(F(g,`state`,`server-status.txt`),N);let P=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(j(F(g,`state`,`diagnostic-reports-status.txt`),`${P}\n`),j(F(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=F(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let re=e.redact===!0;re&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:F(g,`legacy`),contentDir:t})),e.note&&j(F(g,`note.txt`),e.note);let ie=null;e.scrubSecrets===!0&&(ie=GVe(g));for(let t of e.extraFiles??[]){let e=t.zipName??ne(t.sourcePath);if(!X9(t.sourcePath,F(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=v7(t,`extra/${e}`);n!==null&&(ie??={redactions:[],redactedLineCount:0},ie.redactions.push(n),ie.redactedLineCount+=n.lineCount)}let I=IVe(n),L=Q9(g),ae=[],oe=0,se=0;for(let e of L){let t=$9(g,e),n=ee(e).size,r=HVe(t)?RVe(e):0;ae.push({path:t,bytes:n,lines:r}),oe+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(se+=BVe(e))}let ce={applied:re};ie!==null&&(ce.secretScrub=ie);let R={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te},contentDir:{pathSha256:LVe(t),absolutePath:re?`<CONTENT_DIR>`:t},telemetry:{localSink:{...I,directory:xt(`logs`,`projects`)},otlpPushEnabled:m()},redaction:ce,serverStatus:S,files:ae};j(F(g,`manifest.json`),`${JSON.stringify(R,null,2)}\n`);let le=E9(t),ue=L.some(e=>{try{let t=C(e,`utf-8`);return le.some(e=>t.includes(e))}catch{return!1}}),de={stagedDiagnosticReports:v,totalBytes:oe,fileCount:ae.length,docNameCount:se,contentDirVisible:ue,redacted:re},fe=!1;return{stagingDir:g,manifest:R,summary:de,cleanup:()=>{fe||(fe=!0,k(g,{recursive:!0,force:!0}))}}}catch(e){throw k(g,{recursive:!0,force:!0}),e}}async function qVe(e){let{collected:t,outputPath:n}=e,r=N(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new zAe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function JVe(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,On.parse)(C(n,`utf-8`)),r=_q(t)?t.content:void 0,i=_q(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ae(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return ae(e)}async function YVe(e,t,n,r,i,a){let o=y7(t,e.logger),s=await KVe({contentDir:JVe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Qze(o,e.userLogsDir??F(St(),`logs`)),...x7(e.cachesDir??F(de(),`Library`,`Caches`))],userStateFiles:S7(e.bugReportsDir??_7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(N(e.outputPath),{recursive:!0}),await qVe({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function XVe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??T9,i=()=>wze(e.diagnosticReportsDir??F(de(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return YVe(e,t,n,r,i(),await h7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await rBe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:x7(e.cachesDir??F(de(),`Library`,`Caches`)),bugReportLedgerFiles:S7(e.bugReportsDir??_7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await h7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Eq as ALL_EDITOR_IDS,Dq as EDITOR_LABELS,sJ as EDITOR_TARGETS,OTe as HOSTS_WITH_USER_SKILL_DIR,fze as LAUNCH_CONFIG_NAME,iVe as PATH_SHIM_BEGIN,oVe as PATH_SHIM_BLOCK_RE,aVe as PATH_SHIM_END,o5 as ProjectPathSafetyError,URe as addOkPathsToGitExclude,s5 as assertProjectPathSafe,Hq as buildManagedServerEntry,BBe as buildMcpConfigDeclineEvent,VBe as buildMcpConfigMigrateEvent,Qq as canonicalEntryFor,H5 as classifyExistingMcpEntry,XVe as collectReportBundle,dVe as createCliProbeResolver,Pn as createTokenStore,Yze as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,gze as detectInstalledEditors,Zq as droppedManagedKeys,YTe as editorConfigPathDisplay,JTe as editorEntryLocator,kBe as ensurePiBridge,Aze as findJetsamKillSync,b5 as formatTrackedRemediation,KRe as getExcludedOkPaths,v5 as getInstalledSkillProjectionPaths,DTe as getNativeTomlMcpEditor,_5 as getOkArtifactPaths,Bq as isEntryUpToDate,Uq as isOwnManagedEntry,tVe as loadConfig,Dee as makeLazyProbeTokenStore,_7 as okBugReportsDir,_9 as parseGitHubBlobUrl,nVe as parseGitHubShareUrl,v9 as parseGitHubTreeUrl,g9 as parseGitUrl,sVe as pathInstallMarkerPath,ORe as previewContent,_ze as probeOwnManagedEditorMcpEntry,DBe as probePiBridgeState,y5 as probeTrackedOkPaths,B5 as readExistingMcpEntry,GRe as readSharingMode,eF as redactContent,sBe as registerWindowsProcessStartReader,WRe as removeOkPathsFromGitExclude,IBe as removeOwnMcpEntry,zRe as removeProjectSkill,pVe as removeUserGlobalSkillBundle,yVe as removeUserSkill,NRe as resolveProjectRoot,YBe as runStop,u9 as truncatePriorEntry,C9 as userGlobalSkillBundleTargets,vVe as userSkillPresentAnywhere,rVe as validateLocalFolderForShare,z5 as writeEditorMcpConfig,gVe as writeProjectAiIntegrations,f5 as writeProjectSkill,hze as writeUserMcpConfigs,_Ve as writeUserSkill};
|
|
1642
1642
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-R_LUDCBR.mjs";import{n as Ve,s as T}from"./fs-find-project-root-pgJRBsWv.mjs";import{i as E,n as D,o as O,r as He,s as k,t as A}from"./colors-r_owlCuY.mjs";import{t as j}from"./is-object-BGze3w87.mjs";import{t as Ue}from"./constants-BZk7xgJz.mjs";import{t as We}from"./preview-2ROhJT3N.mjs";import{createRequire as Ge}from"node:module";import{fileURLToPath as Ke}from"node:url";import qe,{basename as Je,dirname as M,isAbsolute as Ye,join as N,posix as Xe,relative as P,resolve as F,sep as I,win32 as Ze}from"node:path";import L from"node:process";import{copyFileSync as Qe,existsSync as R,lstatSync as $e,mkdirSync as et,readFileSync as z,readdirSync as tt,readlinkSync as nt,realpathSync as rt,rmSync as it,statSync as at,writeFileSync as ot}from"node:fs";import{homedir as B}from"node:os";import{AsyncLocalStorage as st,AsyncResource as ct}from"node:async_hooks";import{execFileSync as lt}from"node:child_process";import{inspect as ut,stripVTControlCharacters as dt,styleText as V}from"node:util";import*as ft from"node:readline";var pt=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),mt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),ht=n((e=>{let{humanReadableArgName:t}=mt();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
2
2
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
3
3
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),gt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&T(e,g,{mode:Ka(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const zo=e=>e!==`project`,Bo=e=>e!==`user`;async function Vo(){let e=await to({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Ho(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Vo)():`both`}async function Uo(e){return oo({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:`OK config stays on this machine only; teammates do not see it. Safe escape hatch via \`${s()} config-sharing share\`.`}]})}async function Wo(e){if(e.sharing!==void 0)return e.sharing;let t=ma(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Uo)(t):t}var Go=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}},Ko=class extends Error{constructor(e){super(`A dev MCP entry is written to project config only, never to user-level editor config, so --scope ${e} is not supported with --dev-mcp or OK_CHANNEL=dev. Re-run with --scope project or without --scope.`),this.name=`DevMcpScopeError`}};const qo=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${c} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;function Jo(e){if(e===void 0||e===!0)return new Set(Ie);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(ye.filter(e=>t.includes(e)))}function Yo(e,t,n){let r=F(n,e),i;try{i=at(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Go(`--content-dir path does not exist: ${r}`):new Go(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Go(`--content-dir must be a directory: ${r}`);let a=Xo(t),o=Xo(r),s=P(a,o);if(s.startsWith(`..`)||Ye(s))throw new Go(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Xo(e){try{return rt(e)}catch{return e}}const Zo=`open-knowledge-ui`;function Qo(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return R(r)}catch{return!1}}function $o(e,t,n){try{let r=F(M(e.configPath(t,n))),i=F(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+I)}catch{return!1}}function es(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!R(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||$o(e,t,r);if(!i&&c&&!Qo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Aa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return ns(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||et(M(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{ve(`${o}.lock`,()=>{let t=yo(o).writePath;if(s||et(M(t),{recursive:!0}),e.format===`toml`){let r=Fo(oi(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=Ro(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=Po(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const ts={pi:uo};function ns(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=ts[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{et(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{ve(`${t}.lock`,()=>{let e=null;try{e=z(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}T(t,c,e===null?void 0:{mode:Ka(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function rs(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!R(n)))return{editorId:e.id,label:e.label,path:n}}async function is(e){let t=sa(e.editors).filter(e=>e.scope===`global`);if(a())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:qo}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>es(t,``,n,e.home))}function as(e,t,n,r){let i=ss(e,t,n,r);return i.kind===`present`?i.entry:null}function os(e,t,n,r){let i=No(e,t,r);if(!j(i))return{kind:`no-entry`};let a=i[n];return j(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function ss(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!R(i))return{kind:`absent`};try{if(at(i).size>Do)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:Ha(e)}}let a;try{a=z(i,`utf-8`)}catch(e){return{kind:`decline`,reason:Ha(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:lo(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=oi().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return os(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,qr.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:os(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=So(a);return s?Co(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:os(we(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function cs(e={}){let t=F(e.cwd??process.cwd()),n=e.projectRootMode===`cwd`?{projectRoot:t,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:mo(t,{homeDir:e.home}),r=n.projectRoot;if(Se(r,e.home??B()))throw new ue(r);if(_e(r))throw new he(r);let i=!R(N(r,`.ok`)),o=n.gitRootPromoted?P(r,t):void 0,c=e.contentDir===void 0?n.defaultContentDir:Yo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&c===`.`&&process.stderr.write(`${k(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${o}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`${s()} init --content-dir .\`, or set content.dir: ${o} in .ok/config.yml.\n`);let l={mode:e.devMcp?`dev`:`published`},u=e.devMcp===!0||a();if(u&&e.mcp!==!1&&e.scope&&e.scope!==`project`)throw new Ko(e.scope);let d=await je(r),f;try{f=ge(r,{contentDir:c})}catch(t){let i=$.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:d.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let p=f.created.includes(Ue),m=!1;if(d.didInit)try{m=Le(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{ze(r)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${r}: ${e instanceof Error?e.message:String(e)}`)}let h=await Ho({scope:u?`project`:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),g=e.editors??ms(r,e.home),v=e.editors??g,y=sa(g),b=sa(v),x=e.mcp===!1||h===null,S=Array.from(new Map([...y,...x?[]:b].map(e=>[e.id,e])).values()),ee=y.filter(t=>Qo(t,r,e.home)),C=[],te=[],ne=new Set;for(let t of S){if(x){let n=``;try{n=t.configPath(r,e.home)}catch{}C.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(zo(h)&&y.includes(t)&&t.scope===`global`&&C.push(es(t,r,l,e.home)),Bo(h)&&b.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=es(t,r,l,e.home,n);C.push(i),(i.action===`written`||i.action===`overwritten`)&&ne.add(n)}}let re=new Set;for(let t of b){let n=t.projectSkillPath?.(r);!n||re.has(n)||(re.add(n),te.push(Ba(t,r,{home:e.home})))}let ie=za(r,b.map(e=>e.id));ie&&te.push(ie);let ae=te.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(ae.length>0){let t=e.home??B();be({source:_,skills:[Ne.project],agents:ae,scope:r},{home:t,enabled:fe(t).enabled})}let oe=!x&&h!==null&&Bo(h)?b.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,se=x?[]:ee.map(e=>rs(e,r)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ce=e.installUserSkill??me,w=e.home??B(),le=Jo(e.skills),pe=typeof e.skills!=`string`,ve=!1,xe=!1,we=!1,Te=!1,De=!1,Oe=!1,ke=!1,Ae=[];for(let t of ye){if(!le.has(t))continue;if(ve=!0,pe){let e=await Ce(w,Ne[t]).then(e=>({ok:!0,value:e}),()=>({ok:!1}));if(!e.ok){Ae.push({bundleId:t,result:`decision-read-failed`}),ke=!0;continue}if(e.value===!1){Ae.push({bundleId:t,result:`opted-out`}),Oe=!0;continue}}await de(w,Ne[t],!0).catch(()=>{});let n=await ce({home:e.home,bundleId:t,force:!0});Ae.push({bundleId:t,result:n}),n===`installed`?xe=!0:n===`failed`?we=!0:n===`no-hosts`?De=!0:Te=!0}let Me=we?`failed`:ke?`decision-read-failed`:xe?`installed`:ve&&Te?`skip-current`:ve&&De?`no-hosts`:Oe?`opted-out`:`declined`,Fe=xe?Pe(w).map(e=>e.editorId):[],Ie=fe(w).enabled&&!Ee(),Re=x?`skipped-flag`:`skipped-missing`,Be=C.find(e=>e.editorId===`claude`)??C[0]??{action:Re,configPath:$.claude.configPath(r,e.home)},Ve=await ls({projectRoot:r,desiredMode:await Wo({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:f.created,contentUpdated:f.updated,contentSkipped:f.skipped,editors:C,projectSkills:te,legacyProjectConfigs:se,skillInstall:Me,skillBundles:Ae,skillsRequested:e.skills,skillHosts:Fe,skillInstallsCounted:Ie,didGitInit:d.didInit,rootGitignoreCreated:m,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDir:p?c:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Be.action,mcpPath:Be.configPath,mcpError:`error`in Be?Be.error:void 0,projectScopeUnsupportedLabels:oe,sharing:Ve}}async function ls(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=ma(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=ua(t);if(n===`local-only`){let e=fa(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:us(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=pa(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:us(t,o,`remove`)}function us(e,t,n){let r=ma(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function ds(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function fs(e,t){let n=[],a=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),o=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),c=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),u=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let d=N(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(A(`Content scaffolded at ${d}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(A(`Content already present at ${d}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(A(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(c)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(u)n.push(A(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(A(`MCP server configuration:`));for(let i of e.editors){let e=i.configPath.startsWith(t)?P(t,i.configPath):i.configPath.replace(/^\/Users\/[^/]+/,`~`),a=i.serverName===r()?``:` (${i.serverName})`,o=i.configScope===`project`?` (project)`:``,s=`${i.label}${o}`,c=` `.repeat(Math.max(1,20-s.length)),l=i.editorId===`claude-desktop`&&(i.action===`written`||i.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(i.action){case`written`:n.push(` ${s}${c}${e} ${O(`registered`)}${a}${l}`);break;case`overwritten`:n.push(` ${s}${c}${e} ${O(`updated`)}${a}${l}`);break;case`skipped-missing`:n.push(` ${s}${c}${e} config root missing; skipped`);break;case`failed`:n.push(` ${s}${c}${e} ${He(`FAILED`)}: ${i.error}`);break;case`declined`:n.push(` ${s}${c}${e} left unchanged (${ds(i.declineReason)})`);break;case`skipped-flag`:break;default:i.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}let a=i.dev.mcpServerName;e.editors.some(e=>e.serverName===a&&(e.action===`written`||e.action===`overwritten`))&&n.push(` The ${a} entry runs this checkout on this machine only; keep it out of commits.`)}if(e.projectSkills.length>0){n.push(``),n.push(A(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?P(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${O(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${O(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${He(`FAILED`)}: ${r.error}`)}}}if(o&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${P(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall===`declined`)n.push(``),n.push(A(`User-global skills:`)),typeof e.skillsRequested==`string`?(n.push(` ${D(`none installed — --skills "${e.skillsRequested}" names no known skill bundle (known: ${ye.join(`, `)})`)}`),n.push(` ${D(`No user-global skill was installed or removed.`)}`)):(n.push(` ${D(`none installed — skipped for this run (--no-skills)`)}`),n.push(` ${D(`No user-global skill was installed or removed; any already on this`)}`),n.push(` ${D(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${D(` ${s()} init`)}`),n.push(` ${D(`--no-skills covers user-global skills only, not project-local skills.`)}`));else if(e.skillInstall){n.push(``),n.push(A(`User-global skills:`));let t=e.skillBundles??[],r=Math.max(0,...t.map(e=>Ne[e.bundleId].length));for(let i of t){let t=Ne[i.bundleId].padEnd(r);switch(i.result){case`installed`:{let r=(e.skillHosts??[]).map(e=>X[e]??e),i=r.length>0?r.join(`, `):`the shared ~/.agents store`;n.push(` ${t} ${O(`installed for ${i}`)}`);break}case`skip-current`:n.push(` ${t} ${O(`already installed at current version`)}`);break;case`no-hosts`:n.push(` ${t} ${D(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${k(`${t} install failed`)}`);break;case`opted-out`:n.push(` ${t} ${D(`not installed — turned off on this machine; reinstall with ${s()} init --skills ${i.bundleId} or Settings → Skills Studio`)}`);break;case`decision-read-failed`:n.push(` ${k(`${t} not installed — could not read whether it is turned off on this machine; rerun ${s()} init once ${l(x)} is readable`)}`);break;default:i.result}}e.skillInstallsCounted&&t.some(e=>e.result===`installed`)&&(n.push(` ${D(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${D(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`)),t.some(e=>e.result===`failed`)&&n.push(` ${k(`Retry with: ${s()} repair-skills`)}`)}e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(k(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(k(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`${s()} init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(` To scope to just that sub-folder, re-run \`${s()} init --content-dir .\` from there, or set`),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(We(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(..._s(e.sharing,t));let f=e=>[`${e}- ${E(`${s()} seed --list-packs`)} — browse the starter packs`,`${e}- ${E(`${s()} seed`)} — scaffold an empty repo`];if(a){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${O(`✓`)} ${A(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`);let i=3;e.contentScaffoldFailed||(n.push(` ${i++}. (Optional) scaffold the starter knowledge-base structure:`),n.push(...f(` `))),n.push(` ${i}. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}else e.contentScaffoldFailed||(n.push(``),n.push(`${A(`Next steps:`)} (optional) scaffold the starter knowledge-base structure:`),n.push(...f(` `)));return n.join(`
|
|
691
691
|
`)}function ps(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function ms(e,t){let n=[];for(let r of ci)r!==`claude-desktop`&&Qo($[r],e,t)&&n.push(r);return n}function hs(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ut(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function gs(){return new Et(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry (node + packages/cli/dist/cli.mjs, debug logging) in project config only, as the dev channel unless OK_CHANNEL is set`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new Ot(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new Ot(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new Ot(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd();e.devMcp&&u(process.env);let n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?hs():null;try{let r;try{r=await cs({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Go||e instanceof Ko||e instanceof ue||e instanceof he){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof Be||e instanceof le||e instanceof xe){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof Me){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-amZnghWJ.mjs`),{resolveContentDir:s}=await import(`./dist-BL5dLR9l.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-404LuL-V.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(ps(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${fs(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function _s(e,t){let n=[];switch(e.kind){case`applied`:return n.push(A(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${O(`local-only`)} — appended ${e.appended.length} path(s) to ${A(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${O(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${O(`local-only`)} — already excluded; nothing to do.`):n.push(` ${O(`local-only`)}`):e.action===`removed`?n.push(` ${O(`shared`)} — removed OK paths from ${A(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${O(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(k(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${E(`${s()} config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(k(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${E(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${E(`${s()} config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(k(`Sharing mode unavailable: ${e.reason}.`));return n}}export{Z as $,Ga as A,Da as B,yo as C,Rt as Ct,oo as D,co as E,Ot as Et,Na as F,ua as G,ba as H,Aa as I,pa as J,ga as K,ja as L,Ua as M,Ha as N,to as O,ka as P,li as Q,Va as R,$o as S,U as St,uo as T,wt as Tt,ha as U,fa as V,da as W,X,ci as Y,$ as Z,Wo as _,gr as _t,ls as a,Ei as at,es as b,fn as bt,ms as c,Gi as ct,gs as d,si as dt,Vi as et,Qo as f,oi as ft,Yo as g,Qr as gt,Ho as h,Yr as ht,ts as i,Ci as it,qa as j,Ka as k,fs as l,na as lt,Jo as m,Xr as mt,Ko as n,Hi as nt,ps as o,Wi as ot,as as p,Y as pt,ma as q,Zo as r,Ui as rt,ss as s,Q as st,Go as t,Bi as tt,_s as u,Ai as ut,cs as v,ar as vt,mo as w,Et as wt,is as x,dn as xt,jo as y,hn as yt,Ba as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-R_LUDCBR.mjs";import{v as e}from"./init-CelXSRfs.mjs";export{e as runInit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{as as e,cs as t}from"./dist-
|
|
1
|
+
import{as as e,cs as t}from"./dist-R_LUDCBR.mjs";import{s as n}from"./fs-find-project-root-pgJRBsWv.mjs";import{N as r,j as i,k as a}from"./init-CelXSRfs.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-CirdLOMU.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:r(e)}}let g=[],_=t(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=i(h,[`configurations`,y]);return x?(n(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-
|
|
1
|
+
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-R_LUDCBR.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-BZk7xgJz.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=e();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(e){let n=e??process.cwd(),u=[],p=[],m=[],h=[],g=s(`user`,n),_=c({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(e,t=!1)=>{let n=v(e);if(n.diagnostic!==void 0&&p.push(n.diagnostic),n.value===null)return{};let o=r({value:n.value,file:n.path,source:n.source,doc:n.doc});p.push(...o),u.push(e);let s=o.length>0?i(n.value):n.value;return t&&h.push(...a({value:s,file:n.path,source:n.source,doc:n.doc})),s},x=f(n,`.ok`,d),S=b(x,!0),C=b(s(`project-local`,n)),w=t(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),t={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(o(t))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-C56VpYiL.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ho as e}from"./dist-
|
|
1
|
+
import{Ho as e}from"./dist-R_LUDCBR.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{k as e}from"./constants-ok-dir-BmRrWVQT.mjs";import"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Rn as t}from"./dist-
|
|
1
|
+
import{k as e}from"./constants-ok-dir-BmRrWVQT.mjs";import"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Rn as t}from"./dist-R_LUDCBR.mjs";import"./constants-BZk7xgJz.mjs";import{join as n,relative as r}from"node:path";import{existsSync as i,lstatSync as a,readdirSync as o,realpathSync as s,statSync as c}from"node:fs";function l(e){let{projectDir:i,contentDir:l,sampleCap:u=5}=e,d=[],f=[];try{a(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=t({projectDir:i,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=o(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${r(l,e)||`.`}: ${n}`);return}for(let i of t){let t=n(e,i.name);if(i.isSymbolicLink()){let e;try{e=s(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${r(l,t)}`):d.push(`cannot resolve symlink ${r(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=c(e)}catch{continue}if(n.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(i.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function u(t,a){let o=[],s=r(a,t.contentDir),c=s===``?`./`:`./${s}`;if(o.push(`Content:`),o.push(` Found ${t.totalCount} markdown files in ${c}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;o.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)o.push(` Warning: ${e}`);o.push(``);let l=n(a,`.ok`,`config.yml`);return i(l)?(o.push(` To adjust scope, add patterns to .okignore at the project root.`),o.push(` To change the content root, edit .ok/config.yml → content.dir.`)):o.push(` Run \`${e().cliCommandNames[1]} init\` to scaffold config + .okignore.`),o.push(``),o.push(` Re-check anytime: ${e().cliCommandNames[1]} preview`),o.join(`
|
|
2
2
|
`)}export{l as n,u as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-2ROhJT3N.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./jsx-runtime-BUgB2tll.js";import{t as n}from"./react-f2sANaYj.js";import{n as r,r as i}from"./dist-Nvb76hAm.js";import{t as a}from"./compiler-runtime-BfE3aGVn.js";import{t as o}from"./label-CvMpFFbN.js";import{t as s}from"./button-DzgjsZzC.js";import{n as c}from"./config-errors-BXj4CTPy.js";import{n as l,r as u}from"./constants-github-CG_3Vnhk.js";import{f as d,l as f}from"./SyncStatusBadge-vLqZCd3H.js";import{t as p}from"./trash-2-Dx-L6HlB.js";import{t as m}from"./use-git-sync-status-D8KvdiBj.js";import{t as h}from"./input-DUSj2Bri.js";import{t as g}from"./skeleton-BBQ4J9l6.js";import{a as _,n as v,t as y}from"./AuthModal-BqAFZ5VD.js";import{t as b}from"./channel-cli-copy-BE13Ri4Z.js";import{n as x}from"./auth-state-cache-Upa8QNbS.js";import{t as ee}from"./SettingsSectionHeader-DoDCqZE9.js";var S=e(n(),1),C=a(),w=`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?`,T=RegExp(`^${w}(?:\\.${w})*$`),E=/^[a-z][a-z0-9+.-]*:\/\//i;function D(e){if(E.test(e))try{return new URL(e).host}catch{return null}let t=e.split(`/`)[0]??``;return t.slice(t.lastIndexOf(`@`)+1).replace(/:(?!\d+$).*$/,``)}function O(e,t){let n=e.trim();if(n===``)return{ok:!1,reason:`empty`};let r=D(n);if(r===null||r===``)return{ok:!1,reason:`invalid`};let i=u(r);return T.test(i)?i===`github.com`?{ok:!1,reason:`github-com`}:t.has(i)?{ok:!1,reason:`duplicate`}:{ok:!0,host:i}:{ok:!1,reason:`invalid`}}function k(e){let t=e.git?.hosts??{};return Object.entries(t).filter(([,e])=>e?.provider===`github`).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}var A=t();function te(e){let t=(0,C.c)(59),{binding:n}=e,{_:a}=i(),o=(0,S.useId)(),l=(0,S.useId)(),u;t[0]===n?u=t[1]:(u=()=>k(n.current()),t[0]=n,t[1]=u);let[d,f]=(0,S.useState)(u),[m,g]=(0,S.useState)(``),[_,v]=(0,S.useState)(null),[y,b]=(0,S.useState)(!1),[x,ee]=(0,S.useState)(null),w;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(w=new Map,t[2]=w):w=t[2];let T=(0,S.useRef)(w),E=(0,S.useRef)(null),D,te;t[3]===x?(D=t[4],te=t[5]):(D=()=>{x!==null&&(((x.host===null?null:T.current.get(x.host))??E.current)?.focus(),ee(null))},te=[x],t[3]=x,t[4]=D,t[5]=te),(0,S.useEffect)(D,te);let M,N;t[6]===n?(M=t[7],N=t[8]):(M=()=>n.subscribe(e=>f(k(e))),N=[n],t[6]=n,t[7]=M,t[8]=N),(0,S.useEffect)(M,N);let P;t[9]===a?P=t[10]:(P=function(e){switch(e){case`empty`:return a({id:`cFONFy`});case`invalid`:return a({id:`QsnBxE`});case`github-com`:return a({id:`UK3GW4`});case`duplicate`:return a({id:`DEkRZA`})}},t[9]=a,t[10]=P);let F=P,I;t[11]!==n||t[12]!==m||t[13]!==d||t[14]!==F?(I=function(e){e.preventDefault();let t=O(m,new Set(d.map(j)));if(!t.ok){v(F(t.reason));return}let r=n.patch({git:{hosts:{[t.host]:{provider:`github`}}}});if(!r.ok){v(c(r.error));return}f(k(r.effective)),g(``),v(null),b(!0)},t[11]=n,t[12]=m,t[13]=d,t[14]=F,t[15]=I):I=t[15];let ne=I,L;t[16]!==n||t[17]!==d?(L=function(e){let t=d.indexOf(e),r=d[t+1]??d[t-1]??null,i=n.patch({git:{hosts:{[e]:null}}});if(!i.ok){v(c(i.error));return}f(k(i.effective)),ee({host:r}),v(null),b(!0)},t[16]=n,t[17]=d,t[18]=L):L=t[18];let R=L,z;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(z=(0,A.jsx)(`h4`,{id:`settings-enterprise-hosts-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`J2-D_a`})}),t[19]=z):z=t[19];let B;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(B=(0,A.jsx)(r,{id:`PgY2nN`}),t[20]=B):B=t[20];let V;t[21]===o?V=t[22]:(V=(0,A.jsxs)(`div`,{children:[z,(0,A.jsx)(`p`,{id:o,className:`text-1sm text-muted-foreground`,children:B})]}),t[21]=o,t[22]=V);let H;t[23]!==a||t[24]!==R||t[25]!==d?(H=d.length>0?(0,A.jsx)(`ul`,{className:`space-y-1`,"data-testid":`settings-enterprise-hosts-list`,children:d.map(e=>(0,A.jsxs)(`li`,{className:`flex items-center justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs`,children:e}),(0,A.jsx)(s,{variant:`ghost`,size:`icon`,className:`size-7`,"aria-label":a({id:`xVMoYb`,values:{host:e}}),ref:t=>{t?T.current.set(e,t):T.current.delete(e)},onClick:()=>R(e),children:(0,A.jsx)(p,{"aria-hidden":`true`})})]},e))}):(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-enterprise-hosts-empty`,children:(0,A.jsx)(r,{id:`HK2eIK`})}),t[23]=a,t[24]=R,t[25]=d,t[26]=H):H=t[26];let U;t[27]===a?U=t[28]:(U=a({id:`Qbf7Q4`}),t[27]=a,t[28]=U);let W=_!==null,G=_===null?o:`${o} ${l}`,K;t[29]===_?K=t[30]:(K=e=>{g(e.target.value),_!==null&&v(null)},t[29]=_,t[30]=K);let q;t[31]!==m||t[32]!==U||t[33]!==W||t[34]!==G||t[35]!==K?(q=(0,A.jsx)(h,{ref:E,value:m,"aria-label":U,placeholder:`github.example.com`,autoComplete:`off`,spellCheck:!1,inputMode:`url`,className:`h-7 flex-1 font-mono text-xs`,"aria-invalid":W,"aria-describedby":G,onChange:K}),t[31]=m,t[32]=U,t[33]=W,t[34]=G,t[35]=K,t[36]=q):q=t[36];let re;t[37]===m?re=t[38]:(re=m.trim(),t[37]=m,t[38]=re);let ie=re===``,J;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsx)(r,{id:`ALFlyF`}),t[39]=J):J=t[39];let Y;t[40]===ie?Y=t[41]:(Y=(0,A.jsx)(s,{type:`submit`,size:`sm`,variant:`secondary`,disabled:ie,className:`h-7 px-2 font-normal text-xs`,children:J}),t[40]=ie,t[41]=Y);let X;t[42]!==ne||t[43]!==q||t[44]!==Y?(X=(0,A.jsxs)(`form`,{className:`flex items-center gap-2 pt-1`,onSubmit:ne,noValidate:!0,children:[q,Y]}),t[42]=ne,t[43]=q,t[44]=Y,t[45]=X):X=t[45];let Z;t[46]!==_||t[47]!==l?(Z=_===null?null:(0,A.jsx)(`p`,{id:l,role:`alert`,className:`text-1sm text-destructive`,children:_}),t[46]=_,t[47]=l,t[48]=Z):Z=t[48];let Q;t[49]===y?Q=t[50]:(Q=y?(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`3LuFP-`})}):null,t[49]=y,t[50]=Q);let $;t[51]!==H||t[52]!==X||t[53]!==Z||t[54]!==Q?($=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-lg border bg-card p-3`,children:[H,X,Z,Q]}),t[51]=H,t[52]=X,t[53]=Z,t[54]=Q,t[55]=$):$=t[55];let ae;return t[56]!==V||t[57]!==$?(ae=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-enterprise-hosts-title`,className:`space-y-4`,"data-field":`section:enterprise-hosts`,"data-testid":`settings-enterprise-hosts`,children:[V,$]}),t[56]=V,t[57]=$,t[58]=ae):ae=t[58],ae}function j(e){return u(e)}function M(e){let t=(0,C.c)(43),{authQueryTransport:n,authTransport:a,userBinding:o}=e,{_:s}=i(),c;t[0]===n?c=t[1]:(c=n??_(),t[0]=n,t[1]=c);let l=c,u=m()?.remote??null,d;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(d={phase:`loading`},t[2]=d):d=t[2];let[f,p]=(0,S.useState)(d),[h,g]=(0,S.useState)(!1),[v,b]=(0,S.useState)(!1),[w,T]=(0,S.useState)(null),E=(0,S.useRef)(!1),D;t[3]===l?D=t[4]:(D=async function(){p({phase:`loading`});try{let e=await l.status();p({phase:`loaded`,result:e}),x(e)}catch(e){console.warn(`[AccountSection] GitHub status check failed`,e),p({phase:`check-failed`})}},t[3]=l,t[4]=D);let O=D,k;t[5]===O?k=t[6]:(k=()=>{O()},t[5]=O,t[6]=k);let j;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],t[7]=j):j=t[7],(0,S.useEffect)(k,j);let M;t[8]!==s||t[9]!==O||t[10]!==l?(M=async function(){if(E.current)return;E.current=!0,g(!1),b(!0),T(null);let e=null;try{let t=l.signout?await l.signout():{ok:!1,error:s({id:`8cpOa8`})};t.ok||(e=t.error??s({id:`8cpOa8`}))}catch(t){console.warn(`[AccountSection] GitHub disconnect failed`,t),e=s({id:`8cpOa8`})}await O(),e&&T(e),b(!1),E.current=!1},t[8]=s,t[9]=O,t[10]=l,t[11]=M):M=t[11];let P=M,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,A.jsx)(r,{id:`MpZRQy`}),t[12]=F):F=t[12];let I;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,A.jsx)(ee,{titleId:`settings-account-title`,title:F,scope:`user`,children:(0,A.jsx)(r,{id:`pd6t3G`})}),t[13]=I):I=t[13];let L;t[14]!==w||t[15]!==v||t[16]!==P||t[17]!==O||t[18]!==f?(L=f.phase===`loaded`&&f.result.unsupportedOrigin!==void 0?null:(0,A.jsxs)(`section`,{"aria-labelledby":`settings-github-account-title`,className:`space-y-4`,"data-field":`section:github-account`,children:[(0,A.jsx)(`h4`,{id:`settings-github-account-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`RkXlPZ`})}),(0,A.jsx)(N,{status:f,disconnecting:v,disconnectError:w,onRetry:()=>void O(),onConnect:()=>g(!0),onDisconnect:()=>void P()})]}),t[14]=w,t[15]=v,t[16]=P,t[17]=O,t[18]=f,t[19]=L):L=t[19];let R;t[20]===o?R=t[21]:(R=(0,A.jsx)(te,{binding:o}),t[20]=o,t[21]=R);let z;t[22]!==a||t[23]!==u?(z=(0,A.jsx)(ne,{authTransport:a,remote:u}),t[22]=a,t[23]=u,t[24]=z):z=t[24];let B;t[25]!==R||t[26]!==z||t[27]!==L?(B=(0,A.jsxs)(`div`,{className:`space-y-8`,children:[L,R,z]}),t[25]=R,t[26]=z,t[27]=L,t[28]=B):B=t[28];let V;t[29]===O?V=t[30]:(V=e=>{g(e),e||O()},t[29]=O,t[30]=V);let H=f.phase===`loaded`?f.result.host:void 0,U=f.phase===`loaded`?f.result.ghAvailable:void 0,W;t[31]===O?W=t[32]:(W=()=>{O()},t[31]=O,t[32]=W);let G;t[33]!==h||t[34]!==a||t[35]!==V||t[36]!==H||t[37]!==U||t[38]!==W?(G=(0,A.jsx)(y,{open:h,onOpenChange:V,transport:a,host:H,ghAvailable:U,onSuccess:W}),t[33]=h,t[34]=a,t[35]=V,t[36]=H,t[37]=U,t[38]=W,t[39]=G):G=t[39];let K;return t[40]!==B||t[41]!==G?(K=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-account-title`,className:`space-y-5`,"data-testid":`settings-account`,children:[I,B,G]}),t[40]=B,t[41]=G,t[42]=K):K=t[42],K}function N(e){let t=(0,C.c)(8),{status:n,disconnecting:i,disconnectError:a,onRetry:o,onConnect:c,onDisconnect:l}=e,u;return t[0]!==a||t[1]!==i||t[2]!==c||t[3]!==l||t[4]!==o||t[5]!==n.phase||t[6]!==n.result?(u=n.phase===`loading`?(0,A.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-busy":`true`,className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-loading`,children:[(0,A.jsx)(`span`,{className:`sr-only`,children:(0,A.jsx)(r,{id:`IWGfGF`})}),(0,A.jsx)(g,{className:`h-4 w-40`}),(0,A.jsx)(g,{className:`h-8 w-32`})]}):n.phase===`check-failed`?(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-check-failed`,children:[(0,A.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`T_wG4n`})}),(0,A.jsx)(s,{variant:`outline`,size:`sm`,onClick:o,children:(0,A.jsx)(r,{id:`KDw4GX`})})]}):n.result.authenticated?n.result.tier===`A`?(0,A.jsx)(R,{login:n.result.login,host:n.result.host}):(0,A.jsx)(L,{login:n.result.login,host:n.result.host,disconnecting:i,error:a,onDisconnect:l}):(0,A.jsx)(z,{onConnect:c}),t[0]=a,t[1]=i,t[2]=c,t[3]=l,t[4]=o,t[5]=n.phase,t[6]=n.result,t[7]=u):u=t[7],u}function P(e){let t=e.split(`/`)[0]??``;return l(t)?t:``}function F(e){let t=(0,C.c)(7),{login:n,host:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=b(),t[0]=a):a=t[0];let o=a,s;t[1]!==i||t[2]!==n?(s={login:n,host:i,cliCommand:o},t[1]=i,t[2]=n,t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c={0:(0,A.jsx)(`code`,{translate:`no`})},t[4]=c):c=t[4];let l;return t[5]===s?l=t[6]:(l=(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-success`,children:(0,A.jsx)(r,{id:`o8OY2K`,values:s,components:c})}),t[5]=s,t[6]=l),l}var I={"data-1p-ignore":!0,"data-lpignore":`true`,"data-bwignore":!0,"data-form-type":`other`};function ne(e){let t=(0,C.c)(89),{authTransport:n,remote:a}=e,{_:c}=i(),u;t[0]===n?u=t[1]:(u=n??v(),t[0]=n,t[1]=u);let p=u,m=a?.label??null,g;t[2]===a?g=t[3]:(g=a?f(a):!1,t[2]=a,t[3]=g);let _=g,y;t[4]===a?y=t[5]:(y=d(a),t[4]=a,t[5]=y);let b=y,x=(0,S.useId)(),ee=(0,S.useId)(),w=(0,S.useId)(),T=(0,S.useId)(),E=(0,S.useId)(),[D,O]=(0,S.useState)(``),[k,te]=(0,S.useState)(``),[j,M]=(0,S.useState)(``),[N,ne]=(0,S.useState)(!1),[L,R]=(0,S.useState)(null),[z,B]=(0,S.useState)(!1),[V,H]=(0,S.useState)(null),U=(0,S.useRef)(!1),W=(0,S.useRef)(!1),G,K;t[6]!==_||t[7]!==m||t[8]!==b?(G=()=>{if(W.current||m===null||_||!b)return;let e=P(m);e&&(W.current=!0,O(e))},K=[m,_,b],t[6]=_,t[7]=m,t[8]=b,t[9]=G,t[10]=K):(G=t[9],K=t[10]),(0,S.useEffect)(G,K);let q;t[11]!==c||t[12]!==D||t[13]!==p||t[14]!==j||t[15]!==k?(q=async function(){if(U.current)return;let e=D.trim(),t=k.trim(),n=j.trim();if(!e||!t||!n)return;if(!l(e)){H(null),B(!0),R(c({id:`rZFxkH`}));return}if(B(!1),!p.hostToken){R(c({id:`iMYFJM`}));return}U.current=!0,ne(!0),R(null),H(null);let r=await p.hostToken(e,t,n).catch(e=>(console.warn(`[AccountSection] storing a host token failed`,e),{ok:!1,login:void 0,error:c({id:`Q5fqMz`})}));ne(!1),U.current=!1,r.ok?(M(``),H({login:r.login||t,host:e})):R(r.error??c({id:`sNeKjP`}))},t[11]=c,t[12]=D,t[13]=p,t[14]=j,t[15]=k,t[16]=q):q=t[16];let re=q,ie;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,A.jsx)(`h4`,{id:`settings-host-tokens-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`jbhCDS`})}),t[17]=ie):ie=t[17];let J;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsxs)(`div`,{children:[ie,(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`-nA68n`})})]}),t[18]=J):J=t[18];let Y;t[19]===re?Y=t[20]:(Y=e=>{e.preventDefault(),re()},t[19]=re,t[20]=Y);let X;t[21]!==_||t[22]!==m||t[23]!==b?(X=m!==null&&!_&&!b?(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-not-https`,children:(0,A.jsx)(r,{id:`OWs-8P`})}):null,t[21]=_,t[22]=m,t[23]=b,t[24]=X):X=t[24];let Z;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Z=(0,A.jsx)(r,{id:`Ai2U7L`}),t[25]=Z):Z=t[25];let Q;t[26]===x?Q=t[27]:(Q=(0,A.jsx)(o,{htmlFor:x,children:Z}),t[26]=x,t[27]=Q);let $=z||void 0,ae=z&&L?ee:void 0,oe;t[28]===z?oe=t[29]:(oe=e=>{W.current=!0,O(e.target.value),z&&(B(!1),R(null))},t[28]=z,t[29]=oe);let se;t[30]!==D||t[31]!==x||t[32]!==$||t[33]!==ae||t[34]!==oe?(se=(0,A.jsx)(h,{id:x,type:`text`,placeholder:`git.example.com`,autoComplete:`off`,...I,"aria-invalid":$,"aria-describedby":ae,value:D,onChange:oe}),t[30]=D,t[31]=x,t[32]=$,t[33]=ae,t[34]=oe,t[35]=se):se=t[35];let ce;t[36]!==Q||t[37]!==se?(ce=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[Q,se]}),t[36]=Q,t[37]=se,t[38]=ce):ce=t[38];let le;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,A.jsx)(r,{id:`7sNhEz`}),t[39]=le):le=t[39];let ue;t[40]===w?ue=t[41]:(ue=(0,A.jsx)(o,{htmlFor:w,children:le}),t[40]=w,t[41]=ue);let de;t[42]===Symbol.for(`react.memo_cache_sentinel`)?(de=e=>te(e.target.value),t[42]=de):de=t[42];let fe;t[43]!==k||t[44]!==T||t[45]!==w?(fe=(0,A.jsx)(h,{id:w,type:`text`,autoComplete:`off`,...I,"aria-describedby":T,value:k,onChange:de}),t[43]=k,t[44]=T,t[45]=w,t[46]=fe):fe=t[46];let pe;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(pe=(0,A.jsx)(r,{id:`azrR7I`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`}),2:(0,A.jsx)(`code`,{translate:`no`})}}),t[47]=pe):pe=t[47];let me;t[48]===T?me=t[49]:(me=(0,A.jsx)(`p`,{id:T,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-username-hint`,children:pe}),t[48]=T,t[49]=me);let he;t[50]!==ue||t[51]!==fe||t[52]!==me?(he=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[ue,fe,me]}),t[50]=ue,t[51]=fe,t[52]=me,t[53]=he):he=t[53];let ge;t[54]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,A.jsx)(r,{id:`SkUcEr`}),t[54]=ge):ge=t[54];let _e;t[55]===E?_e=t[56]:(_e=(0,A.jsx)(o,{htmlFor:E,children:ge}),t[55]=E,t[56]=_e);let ve;t[57]===Symbol.for(`react.memo_cache_sentinel`)?(ve=e=>M(e.target.value),t[57]=ve):ve=t[57];let ye;t[58]!==j||t[59]!==E?(ye=(0,A.jsx)(h,{id:E,type:`password`,autoComplete:`off`,...I,value:j,onChange:ve}),t[58]=j,t[59]=E,t[60]=ye):ye=t[60];let be;t[61]!==_e||t[62]!==ye?(be=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[_e,ye]}),t[61]=_e,t[62]=ye,t[63]=be):be=t[63];let xe;t[64]!==D||t[65]!==N||t[66]!==j||t[67]!==k?(xe=N||!D.trim()||!k.trim()||!j.trim(),t[64]=D,t[65]=N,t[66]=j,t[67]=k,t[68]=xe):xe=t[68];let Se;t[69]===N?Se=t[70]:(Se=N?(0,A.jsx)(r,{id:`1yHVE-`}):(0,A.jsx)(r,{id:`zXZJoN`}),t[69]=N,t[70]=Se);let Ce;t[71]!==xe||t[72]!==Se?(Ce=(0,A.jsx)(s,{type:`submit`,"data-testid":`settings-account-host-token-submit`,disabled:xe,children:Se}),t[71]=xe,t[72]=Se,t[73]=Ce):Ce=t[73];let we;t[74]===V?we=t[75]:(we=V?(0,A.jsx)(F,{login:V.login,host:V.host}):null,t[74]=V,t[75]=we);let Te;t[76]!==L||t[77]!==ee||t[78]!==z?(Te=L?(0,A.jsx)(`p`,{id:z?ee:void 0,role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-host-token-error`,children:L}):null,t[76]=L,t[77]=ee,t[78]=z,t[79]=Te):Te=t[79];let Ee;return t[80]!==X||t[81]!==ce||t[82]!==he||t[83]!==be||t[84]!==Ce||t[85]!==we||t[86]!==Te||t[87]!==Y?(Ee=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-host-tokens-title`,className:`space-y-4`,"data-field":`section:host-tokens`,children:[J,(0,A.jsxs)(`form`,{className:`space-y-3 rounded-lg border bg-card p-3`,"data-testid":`settings-account-host-token`,"aria-labelledby":`settings-host-tokens-title`,autoComplete:`off`,onSubmit:Y,children:[X,ce,he,be,Ce,we,Te]})]}),t[80]=X,t[81]=ce,t[82]=he,t[83]=be,t[84]=Ce,t[85]=we,t[86]=Te,t[87]=Y,t[88]=Ee):Ee=t[88],Ee}function L(e){let t=(0,C.c)(21),{login:n,host:i,disconnecting:a,error:o,onDisconnect:c}=e,l;t[0]!==i||t[1]!==n?(l=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=l):l=t[2];let u;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`nxlOpL`})}),t[3]=u):u=t[3];let d;t[4]===l?d=t[5]:(d=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[l,u]}),t[4]=l,t[5]=d);let f;t[6]===a?f=t[7]:(f=a?(0,A.jsx)(r,{id:`rppgXF`}):(0,A.jsx)(r,{id:`-K0AvT`}),t[6]=a,t[7]=f);let p;t[8]!==a||t[9]!==c||t[10]!==f?(p=(0,A.jsx)(s,{variant:`outline`,onClick:c,disabled:a,"aria-describedby":`settings-account-disconnect-caveat`,"data-testid":`settings-account-disconnect`,children:f}),t[8]=a,t[9]=c,t[10]=f,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,A.jsx)(`p`,{id:`settings-account-disconnect-caveat`,className:`text-muted-foreground text-1sm`,"data-testid":`settings-account-disconnect-caveat`,children:(0,A.jsx)(r,{id:`msOK6I`})}),t[15]=h):h=t[15];let g;t[16]===o?g=t[17]:(g=o?(0,A.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-disconnect-error`,children:o}):null,t[16]=o,t[17]=g);let _;return t[18]!==m||t[19]!==g?(_=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-connected`,children:[m,h,g]}),t[18]=m,t[19]=g,t[20]=_):_=t[20],_}function R(e){let t=(0,C.c)(6),{login:n,host:i}=e,a;t[0]!==i||t[1]!==n?(a=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=a):a=t[2];let o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`UcTm1A`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`})}})}),t[3]=o):o=t[3];let s;return t[4]===a?s=t[5]:(s=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-gh-cli`,children:(0,A.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[a,o]})}),t[4]=a,t[5]=s),s}function z(e){let t=(0,C.c)(5),{onConnect:n}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`S33tz3`})}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[i,(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`9djC8C`})})]}),t[1]=a):a=t[1];let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(r,{id:`5lWFkC`}),t[2]=o):o=t[2];let c;return t[3]===n?c=t[4]:(c=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-disconnected`,children:(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[a,(0,A.jsx)(s,{onClick:n,"data-testid":`settings-account-connect`,children:o})]})}),t[3]=n,t[4]=c),c}export{M as AccountSection};
|
|
1
|
+
import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./jsx-runtime-BUgB2tll.js";import{t as n}from"./react-f2sANaYj.js";import{n as r,r as i}from"./dist-Nvb76hAm.js";import{t as a}from"./compiler-runtime-BfE3aGVn.js";import{t as o}from"./label-CvMpFFbN.js";import{t as s}from"./button-DzgjsZzC.js";import{n as c}from"./config-errors-BXj4CTPy.js";import{n as l,r as u}from"./constants-github-CG_3Vnhk.js";import{f as d,l as f}from"./SyncStatusBadge-DEFzf9Ud.js";import{t as p}from"./trash-2-Dx-L6HlB.js";import{t as m}from"./use-git-sync-status-D8KvdiBj.js";import{t as h}from"./input-DUSj2Bri.js";import{t as g}from"./skeleton-BBQ4J9l6.js";import{a as _,n as v,t as y}from"./AuthModal-BqAFZ5VD.js";import{t as b}from"./channel-cli-copy-BE13Ri4Z.js";import{n as x}from"./auth-state-cache-Upa8QNbS.js";import{t as ee}from"./SettingsSectionHeader-DoDCqZE9.js";var S=e(n(),1),C=a(),w=`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?`,T=RegExp(`^${w}(?:\\.${w})*$`),E=/^[a-z][a-z0-9+.-]*:\/\//i;function D(e){if(E.test(e))try{return new URL(e).host}catch{return null}let t=e.split(`/`)[0]??``;return t.slice(t.lastIndexOf(`@`)+1).replace(/:(?!\d+$).*$/,``)}function O(e,t){let n=e.trim();if(n===``)return{ok:!1,reason:`empty`};let r=D(n);if(r===null||r===``)return{ok:!1,reason:`invalid`};let i=u(r);return T.test(i)?i===`github.com`?{ok:!1,reason:`github-com`}:t.has(i)?{ok:!1,reason:`duplicate`}:{ok:!0,host:i}:{ok:!1,reason:`invalid`}}function k(e){let t=e.git?.hosts??{};return Object.entries(t).filter(([,e])=>e?.provider===`github`).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}var A=t();function te(e){let t=(0,C.c)(59),{binding:n}=e,{_:a}=i(),o=(0,S.useId)(),l=(0,S.useId)(),u;t[0]===n?u=t[1]:(u=()=>k(n.current()),t[0]=n,t[1]=u);let[d,f]=(0,S.useState)(u),[m,g]=(0,S.useState)(``),[_,v]=(0,S.useState)(null),[y,b]=(0,S.useState)(!1),[x,ee]=(0,S.useState)(null),w;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(w=new Map,t[2]=w):w=t[2];let T=(0,S.useRef)(w),E=(0,S.useRef)(null),D,te;t[3]===x?(D=t[4],te=t[5]):(D=()=>{x!==null&&(((x.host===null?null:T.current.get(x.host))??E.current)?.focus(),ee(null))},te=[x],t[3]=x,t[4]=D,t[5]=te),(0,S.useEffect)(D,te);let M,N;t[6]===n?(M=t[7],N=t[8]):(M=()=>n.subscribe(e=>f(k(e))),N=[n],t[6]=n,t[7]=M,t[8]=N),(0,S.useEffect)(M,N);let P;t[9]===a?P=t[10]:(P=function(e){switch(e){case`empty`:return a({id:`cFONFy`});case`invalid`:return a({id:`QsnBxE`});case`github-com`:return a({id:`UK3GW4`});case`duplicate`:return a({id:`DEkRZA`})}},t[9]=a,t[10]=P);let F=P,I;t[11]!==n||t[12]!==m||t[13]!==d||t[14]!==F?(I=function(e){e.preventDefault();let t=O(m,new Set(d.map(j)));if(!t.ok){v(F(t.reason));return}let r=n.patch({git:{hosts:{[t.host]:{provider:`github`}}}});if(!r.ok){v(c(r.error));return}f(k(r.effective)),g(``),v(null),b(!0)},t[11]=n,t[12]=m,t[13]=d,t[14]=F,t[15]=I):I=t[15];let ne=I,L;t[16]!==n||t[17]!==d?(L=function(e){let t=d.indexOf(e),r=d[t+1]??d[t-1]??null,i=n.patch({git:{hosts:{[e]:null}}});if(!i.ok){v(c(i.error));return}f(k(i.effective)),ee({host:r}),v(null),b(!0)},t[16]=n,t[17]=d,t[18]=L):L=t[18];let R=L,z;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(z=(0,A.jsx)(`h4`,{id:`settings-enterprise-hosts-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`J2-D_a`})}),t[19]=z):z=t[19];let B;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(B=(0,A.jsx)(r,{id:`PgY2nN`}),t[20]=B):B=t[20];let V;t[21]===o?V=t[22]:(V=(0,A.jsxs)(`div`,{children:[z,(0,A.jsx)(`p`,{id:o,className:`text-1sm text-muted-foreground`,children:B})]}),t[21]=o,t[22]=V);let H;t[23]!==a||t[24]!==R||t[25]!==d?(H=d.length>0?(0,A.jsx)(`ul`,{className:`space-y-1`,"data-testid":`settings-enterprise-hosts-list`,children:d.map(e=>(0,A.jsxs)(`li`,{className:`flex items-center justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs`,children:e}),(0,A.jsx)(s,{variant:`ghost`,size:`icon`,className:`size-7`,"aria-label":a({id:`xVMoYb`,values:{host:e}}),ref:t=>{t?T.current.set(e,t):T.current.delete(e)},onClick:()=>R(e),children:(0,A.jsx)(p,{"aria-hidden":`true`})})]},e))}):(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-enterprise-hosts-empty`,children:(0,A.jsx)(r,{id:`HK2eIK`})}),t[23]=a,t[24]=R,t[25]=d,t[26]=H):H=t[26];let U;t[27]===a?U=t[28]:(U=a({id:`Qbf7Q4`}),t[27]=a,t[28]=U);let W=_!==null,G=_===null?o:`${o} ${l}`,K;t[29]===_?K=t[30]:(K=e=>{g(e.target.value),_!==null&&v(null)},t[29]=_,t[30]=K);let q;t[31]!==m||t[32]!==U||t[33]!==W||t[34]!==G||t[35]!==K?(q=(0,A.jsx)(h,{ref:E,value:m,"aria-label":U,placeholder:`github.example.com`,autoComplete:`off`,spellCheck:!1,inputMode:`url`,className:`h-7 flex-1 font-mono text-xs`,"aria-invalid":W,"aria-describedby":G,onChange:K}),t[31]=m,t[32]=U,t[33]=W,t[34]=G,t[35]=K,t[36]=q):q=t[36];let re;t[37]===m?re=t[38]:(re=m.trim(),t[37]=m,t[38]=re);let ie=re===``,J;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsx)(r,{id:`ALFlyF`}),t[39]=J):J=t[39];let Y;t[40]===ie?Y=t[41]:(Y=(0,A.jsx)(s,{type:`submit`,size:`sm`,variant:`secondary`,disabled:ie,className:`h-7 px-2 font-normal text-xs`,children:J}),t[40]=ie,t[41]=Y);let X;t[42]!==ne||t[43]!==q||t[44]!==Y?(X=(0,A.jsxs)(`form`,{className:`flex items-center gap-2 pt-1`,onSubmit:ne,noValidate:!0,children:[q,Y]}),t[42]=ne,t[43]=q,t[44]=Y,t[45]=X):X=t[45];let Z;t[46]!==_||t[47]!==l?(Z=_===null?null:(0,A.jsx)(`p`,{id:l,role:`alert`,className:`text-1sm text-destructive`,children:_}),t[46]=_,t[47]=l,t[48]=Z):Z=t[48];let Q;t[49]===y?Q=t[50]:(Q=y?(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`3LuFP-`})}):null,t[49]=y,t[50]=Q);let $;t[51]!==H||t[52]!==X||t[53]!==Z||t[54]!==Q?($=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-lg border bg-card p-3`,children:[H,X,Z,Q]}),t[51]=H,t[52]=X,t[53]=Z,t[54]=Q,t[55]=$):$=t[55];let ae;return t[56]!==V||t[57]!==$?(ae=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-enterprise-hosts-title`,className:`space-y-4`,"data-field":`section:enterprise-hosts`,"data-testid":`settings-enterprise-hosts`,children:[V,$]}),t[56]=V,t[57]=$,t[58]=ae):ae=t[58],ae}function j(e){return u(e)}function M(e){let t=(0,C.c)(43),{authQueryTransport:n,authTransport:a,userBinding:o}=e,{_:s}=i(),c;t[0]===n?c=t[1]:(c=n??_(),t[0]=n,t[1]=c);let l=c,u=m()?.remote??null,d;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(d={phase:`loading`},t[2]=d):d=t[2];let[f,p]=(0,S.useState)(d),[h,g]=(0,S.useState)(!1),[v,b]=(0,S.useState)(!1),[w,T]=(0,S.useState)(null),E=(0,S.useRef)(!1),D;t[3]===l?D=t[4]:(D=async function(){p({phase:`loading`});try{let e=await l.status();p({phase:`loaded`,result:e}),x(e)}catch(e){console.warn(`[AccountSection] GitHub status check failed`,e),p({phase:`check-failed`})}},t[3]=l,t[4]=D);let O=D,k;t[5]===O?k=t[6]:(k=()=>{O()},t[5]=O,t[6]=k);let j;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],t[7]=j):j=t[7],(0,S.useEffect)(k,j);let M;t[8]!==s||t[9]!==O||t[10]!==l?(M=async function(){if(E.current)return;E.current=!0,g(!1),b(!0),T(null);let e=null;try{let t=l.signout?await l.signout():{ok:!1,error:s({id:`8cpOa8`})};t.ok||(e=t.error??s({id:`8cpOa8`}))}catch(t){console.warn(`[AccountSection] GitHub disconnect failed`,t),e=s({id:`8cpOa8`})}await O(),e&&T(e),b(!1),E.current=!1},t[8]=s,t[9]=O,t[10]=l,t[11]=M):M=t[11];let P=M,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,A.jsx)(r,{id:`MpZRQy`}),t[12]=F):F=t[12];let I;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,A.jsx)(ee,{titleId:`settings-account-title`,title:F,scope:`user`,children:(0,A.jsx)(r,{id:`pd6t3G`})}),t[13]=I):I=t[13];let L;t[14]!==w||t[15]!==v||t[16]!==P||t[17]!==O||t[18]!==f?(L=f.phase===`loaded`&&f.result.unsupportedOrigin!==void 0?null:(0,A.jsxs)(`section`,{"aria-labelledby":`settings-github-account-title`,className:`space-y-4`,"data-field":`section:github-account`,children:[(0,A.jsx)(`h4`,{id:`settings-github-account-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`RkXlPZ`})}),(0,A.jsx)(N,{status:f,disconnecting:v,disconnectError:w,onRetry:()=>void O(),onConnect:()=>g(!0),onDisconnect:()=>void P()})]}),t[14]=w,t[15]=v,t[16]=P,t[17]=O,t[18]=f,t[19]=L):L=t[19];let R;t[20]===o?R=t[21]:(R=(0,A.jsx)(te,{binding:o}),t[20]=o,t[21]=R);let z;t[22]!==a||t[23]!==u?(z=(0,A.jsx)(ne,{authTransport:a,remote:u}),t[22]=a,t[23]=u,t[24]=z):z=t[24];let B;t[25]!==R||t[26]!==z||t[27]!==L?(B=(0,A.jsxs)(`div`,{className:`space-y-8`,children:[L,R,z]}),t[25]=R,t[26]=z,t[27]=L,t[28]=B):B=t[28];let V;t[29]===O?V=t[30]:(V=e=>{g(e),e||O()},t[29]=O,t[30]=V);let H=f.phase===`loaded`?f.result.host:void 0,U=f.phase===`loaded`?f.result.ghAvailable:void 0,W;t[31]===O?W=t[32]:(W=()=>{O()},t[31]=O,t[32]=W);let G;t[33]!==h||t[34]!==a||t[35]!==V||t[36]!==H||t[37]!==U||t[38]!==W?(G=(0,A.jsx)(y,{open:h,onOpenChange:V,transport:a,host:H,ghAvailable:U,onSuccess:W}),t[33]=h,t[34]=a,t[35]=V,t[36]=H,t[37]=U,t[38]=W,t[39]=G):G=t[39];let K;return t[40]!==B||t[41]!==G?(K=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-account-title`,className:`space-y-5`,"data-testid":`settings-account`,children:[I,B,G]}),t[40]=B,t[41]=G,t[42]=K):K=t[42],K}function N(e){let t=(0,C.c)(8),{status:n,disconnecting:i,disconnectError:a,onRetry:o,onConnect:c,onDisconnect:l}=e,u;return t[0]!==a||t[1]!==i||t[2]!==c||t[3]!==l||t[4]!==o||t[5]!==n.phase||t[6]!==n.result?(u=n.phase===`loading`?(0,A.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-busy":`true`,className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-loading`,children:[(0,A.jsx)(`span`,{className:`sr-only`,children:(0,A.jsx)(r,{id:`IWGfGF`})}),(0,A.jsx)(g,{className:`h-4 w-40`}),(0,A.jsx)(g,{className:`h-8 w-32`})]}):n.phase===`check-failed`?(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-check-failed`,children:[(0,A.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`T_wG4n`})}),(0,A.jsx)(s,{variant:`outline`,size:`sm`,onClick:o,children:(0,A.jsx)(r,{id:`KDw4GX`})})]}):n.result.authenticated?n.result.tier===`A`?(0,A.jsx)(R,{login:n.result.login,host:n.result.host}):(0,A.jsx)(L,{login:n.result.login,host:n.result.host,disconnecting:i,error:a,onDisconnect:l}):(0,A.jsx)(z,{onConnect:c}),t[0]=a,t[1]=i,t[2]=c,t[3]=l,t[4]=o,t[5]=n.phase,t[6]=n.result,t[7]=u):u=t[7],u}function P(e){let t=e.split(`/`)[0]??``;return l(t)?t:``}function F(e){let t=(0,C.c)(7),{login:n,host:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=b(),t[0]=a):a=t[0];let o=a,s;t[1]!==i||t[2]!==n?(s={login:n,host:i,cliCommand:o},t[1]=i,t[2]=n,t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c={0:(0,A.jsx)(`code`,{translate:`no`})},t[4]=c):c=t[4];let l;return t[5]===s?l=t[6]:(l=(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-success`,children:(0,A.jsx)(r,{id:`o8OY2K`,values:s,components:c})}),t[5]=s,t[6]=l),l}var I={"data-1p-ignore":!0,"data-lpignore":`true`,"data-bwignore":!0,"data-form-type":`other`};function ne(e){let t=(0,C.c)(89),{authTransport:n,remote:a}=e,{_:c}=i(),u;t[0]===n?u=t[1]:(u=n??v(),t[0]=n,t[1]=u);let p=u,m=a?.label??null,g;t[2]===a?g=t[3]:(g=a?f(a):!1,t[2]=a,t[3]=g);let _=g,y;t[4]===a?y=t[5]:(y=d(a),t[4]=a,t[5]=y);let b=y,x=(0,S.useId)(),ee=(0,S.useId)(),w=(0,S.useId)(),T=(0,S.useId)(),E=(0,S.useId)(),[D,O]=(0,S.useState)(``),[k,te]=(0,S.useState)(``),[j,M]=(0,S.useState)(``),[N,ne]=(0,S.useState)(!1),[L,R]=(0,S.useState)(null),[z,B]=(0,S.useState)(!1),[V,H]=(0,S.useState)(null),U=(0,S.useRef)(!1),W=(0,S.useRef)(!1),G,K;t[6]!==_||t[7]!==m||t[8]!==b?(G=()=>{if(W.current||m===null||_||!b)return;let e=P(m);e&&(W.current=!0,O(e))},K=[m,_,b],t[6]=_,t[7]=m,t[8]=b,t[9]=G,t[10]=K):(G=t[9],K=t[10]),(0,S.useEffect)(G,K);let q;t[11]!==c||t[12]!==D||t[13]!==p||t[14]!==j||t[15]!==k?(q=async function(){if(U.current)return;let e=D.trim(),t=k.trim(),n=j.trim();if(!e||!t||!n)return;if(!l(e)){H(null),B(!0),R(c({id:`rZFxkH`}));return}if(B(!1),!p.hostToken){R(c({id:`iMYFJM`}));return}U.current=!0,ne(!0),R(null),H(null);let r=await p.hostToken(e,t,n).catch(e=>(console.warn(`[AccountSection] storing a host token failed`,e),{ok:!1,login:void 0,error:c({id:`Q5fqMz`})}));ne(!1),U.current=!1,r.ok?(M(``),H({login:r.login||t,host:e})):R(r.error??c({id:`sNeKjP`}))},t[11]=c,t[12]=D,t[13]=p,t[14]=j,t[15]=k,t[16]=q):q=t[16];let re=q,ie;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,A.jsx)(`h4`,{id:`settings-host-tokens-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`jbhCDS`})}),t[17]=ie):ie=t[17];let J;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsxs)(`div`,{children:[ie,(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`-nA68n`})})]}),t[18]=J):J=t[18];let Y;t[19]===re?Y=t[20]:(Y=e=>{e.preventDefault(),re()},t[19]=re,t[20]=Y);let X;t[21]!==_||t[22]!==m||t[23]!==b?(X=m!==null&&!_&&!b?(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-not-https`,children:(0,A.jsx)(r,{id:`OWs-8P`})}):null,t[21]=_,t[22]=m,t[23]=b,t[24]=X):X=t[24];let Z;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Z=(0,A.jsx)(r,{id:`Ai2U7L`}),t[25]=Z):Z=t[25];let Q;t[26]===x?Q=t[27]:(Q=(0,A.jsx)(o,{htmlFor:x,children:Z}),t[26]=x,t[27]=Q);let $=z||void 0,ae=z&&L?ee:void 0,oe;t[28]===z?oe=t[29]:(oe=e=>{W.current=!0,O(e.target.value),z&&(B(!1),R(null))},t[28]=z,t[29]=oe);let se;t[30]!==D||t[31]!==x||t[32]!==$||t[33]!==ae||t[34]!==oe?(se=(0,A.jsx)(h,{id:x,type:`text`,placeholder:`git.example.com`,autoComplete:`off`,...I,"aria-invalid":$,"aria-describedby":ae,value:D,onChange:oe}),t[30]=D,t[31]=x,t[32]=$,t[33]=ae,t[34]=oe,t[35]=se):se=t[35];let ce;t[36]!==Q||t[37]!==se?(ce=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[Q,se]}),t[36]=Q,t[37]=se,t[38]=ce):ce=t[38];let le;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,A.jsx)(r,{id:`7sNhEz`}),t[39]=le):le=t[39];let ue;t[40]===w?ue=t[41]:(ue=(0,A.jsx)(o,{htmlFor:w,children:le}),t[40]=w,t[41]=ue);let de;t[42]===Symbol.for(`react.memo_cache_sentinel`)?(de=e=>te(e.target.value),t[42]=de):de=t[42];let fe;t[43]!==k||t[44]!==T||t[45]!==w?(fe=(0,A.jsx)(h,{id:w,type:`text`,autoComplete:`off`,...I,"aria-describedby":T,value:k,onChange:de}),t[43]=k,t[44]=T,t[45]=w,t[46]=fe):fe=t[46];let pe;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(pe=(0,A.jsx)(r,{id:`azrR7I`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`}),2:(0,A.jsx)(`code`,{translate:`no`})}}),t[47]=pe):pe=t[47];let me;t[48]===T?me=t[49]:(me=(0,A.jsx)(`p`,{id:T,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-username-hint`,children:pe}),t[48]=T,t[49]=me);let he;t[50]!==ue||t[51]!==fe||t[52]!==me?(he=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[ue,fe,me]}),t[50]=ue,t[51]=fe,t[52]=me,t[53]=he):he=t[53];let ge;t[54]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,A.jsx)(r,{id:`SkUcEr`}),t[54]=ge):ge=t[54];let _e;t[55]===E?_e=t[56]:(_e=(0,A.jsx)(o,{htmlFor:E,children:ge}),t[55]=E,t[56]=_e);let ve;t[57]===Symbol.for(`react.memo_cache_sentinel`)?(ve=e=>M(e.target.value),t[57]=ve):ve=t[57];let ye;t[58]!==j||t[59]!==E?(ye=(0,A.jsx)(h,{id:E,type:`password`,autoComplete:`off`,...I,value:j,onChange:ve}),t[58]=j,t[59]=E,t[60]=ye):ye=t[60];let be;t[61]!==_e||t[62]!==ye?(be=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[_e,ye]}),t[61]=_e,t[62]=ye,t[63]=be):be=t[63];let xe;t[64]!==D||t[65]!==N||t[66]!==j||t[67]!==k?(xe=N||!D.trim()||!k.trim()||!j.trim(),t[64]=D,t[65]=N,t[66]=j,t[67]=k,t[68]=xe):xe=t[68];let Se;t[69]===N?Se=t[70]:(Se=N?(0,A.jsx)(r,{id:`1yHVE-`}):(0,A.jsx)(r,{id:`zXZJoN`}),t[69]=N,t[70]=Se);let Ce;t[71]!==xe||t[72]!==Se?(Ce=(0,A.jsx)(s,{type:`submit`,"data-testid":`settings-account-host-token-submit`,disabled:xe,children:Se}),t[71]=xe,t[72]=Se,t[73]=Ce):Ce=t[73];let we;t[74]===V?we=t[75]:(we=V?(0,A.jsx)(F,{login:V.login,host:V.host}):null,t[74]=V,t[75]=we);let Te;t[76]!==L||t[77]!==ee||t[78]!==z?(Te=L?(0,A.jsx)(`p`,{id:z?ee:void 0,role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-host-token-error`,children:L}):null,t[76]=L,t[77]=ee,t[78]=z,t[79]=Te):Te=t[79];let Ee;return t[80]!==X||t[81]!==ce||t[82]!==he||t[83]!==be||t[84]!==Ce||t[85]!==we||t[86]!==Te||t[87]!==Y?(Ee=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-host-tokens-title`,className:`space-y-4`,"data-field":`section:host-tokens`,children:[J,(0,A.jsxs)(`form`,{className:`space-y-3 rounded-lg border bg-card p-3`,"data-testid":`settings-account-host-token`,"aria-labelledby":`settings-host-tokens-title`,autoComplete:`off`,onSubmit:Y,children:[X,ce,he,be,Ce,we,Te]})]}),t[80]=X,t[81]=ce,t[82]=he,t[83]=be,t[84]=Ce,t[85]=we,t[86]=Te,t[87]=Y,t[88]=Ee):Ee=t[88],Ee}function L(e){let t=(0,C.c)(21),{login:n,host:i,disconnecting:a,error:o,onDisconnect:c}=e,l;t[0]!==i||t[1]!==n?(l=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=l):l=t[2];let u;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`nxlOpL`})}),t[3]=u):u=t[3];let d;t[4]===l?d=t[5]:(d=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[l,u]}),t[4]=l,t[5]=d);let f;t[6]===a?f=t[7]:(f=a?(0,A.jsx)(r,{id:`rppgXF`}):(0,A.jsx)(r,{id:`-K0AvT`}),t[6]=a,t[7]=f);let p;t[8]!==a||t[9]!==c||t[10]!==f?(p=(0,A.jsx)(s,{variant:`outline`,onClick:c,disabled:a,"aria-describedby":`settings-account-disconnect-caveat`,"data-testid":`settings-account-disconnect`,children:f}),t[8]=a,t[9]=c,t[10]=f,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,A.jsx)(`p`,{id:`settings-account-disconnect-caveat`,className:`text-muted-foreground text-1sm`,"data-testid":`settings-account-disconnect-caveat`,children:(0,A.jsx)(r,{id:`msOK6I`})}),t[15]=h):h=t[15];let g;t[16]===o?g=t[17]:(g=o?(0,A.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-disconnect-error`,children:o}):null,t[16]=o,t[17]=g);let _;return t[18]!==m||t[19]!==g?(_=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-connected`,children:[m,h,g]}),t[18]=m,t[19]=g,t[20]=_):_=t[20],_}function R(e){let t=(0,C.c)(6),{login:n,host:i}=e,a;t[0]!==i||t[1]!==n?(a=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=a):a=t[2];let o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`UcTm1A`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`})}})}),t[3]=o):o=t[3];let s;return t[4]===a?s=t[5]:(s=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-gh-cli`,children:(0,A.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[a,o]})}),t[4]=a,t[5]=s),s}function z(e){let t=(0,C.c)(5),{onConnect:n}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`S33tz3`})}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[i,(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`9djC8C`})})]}),t[1]=a):a=t[1];let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(r,{id:`5lWFkC`}),t[2]=o):o=t[2];let c;return t[3]===n?c=t[4]:(c=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-disconnected`,children:(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[a,(0,A.jsx)(s,{onClick:n,"data-testid":`settings-account-connect`,children:o})]})}),t[3]=n,t[4]=c),c}export{M as AccountSection};
|