@north-light/cli 0.3.782 → 0.3.784
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/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/charges.d.ts +3 -3
- package/dist/api/dto/charges.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/builtin-memory/internal/marketplaces.md +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/builtin-pi-packages/pi-crtr-extensions/README.md +3 -3
- package/dist/cli.js +2 -8
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/pkg/account-installs.d.ts +10 -0
- package/dist/commands/pkg/account-installs.js +1 -0
- package/dist/commands/pkg/plugin-manage.d.ts +4 -0
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/provider-login.js +5 -5
- package/dist/commands/sys/setup-core.d.ts +1 -52
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup-wizard.d.ts +4 -9
- package/dist/commands/sys/setup-wizard.js +3 -1
- package/dist/commands/sys/setup.js +1 -1
- package/dist/commands/sys/signin.js +7 -3
- package/dist/core/grants/shadow.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/ledger/check.d.ts +6 -2
- package/dist/core/ledger/check.js +1 -1
- package/dist/core/llm/run.js +2 -2
- package/dist/core/runtime/first-run-offer.d.ts +2 -6
- package/dist/core/runtime/first-run-offer.js +2 -10
- package/dist/core/runtime/front-door.js +8 -9
- package/dist/core/runtime/package-health.d.ts +1 -1
- package/dist/core/runtime/package-health.js +5 -4
- package/dist/core/runtime/provider-credential-gate.d.ts +1 -1
- package/dist/core/runtime/provider-credential-gate.js +1 -1
- package/dist/core/runtime/runner/machine/executor.d.ts +3 -0
- package/dist/core/runtime/runner/machine/executor.js +2 -1
- package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
- package/dist/core/runtime/start-refusal-notice.js +1 -0
- package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
- package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.js +5 -5
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/docs/cli/first-session.md +2 -2
- package/docs/cli/official-marketplace.md +1 -1
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/charges.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
- package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
- package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
- package/dist/commands/sys/panels/plugins-panel.js +0 -1
- package/dist/core/runtime/front-door-login.d.ts +0 -2
- package/dist/core/runtime/front-door-login.js +0 -1
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface AccountInstallResult {
|
|
2
|
+
installed: string[];
|
|
3
|
+
failed: {
|
|
4
|
+
item: string;
|
|
5
|
+
message: string;
|
|
6
|
+
}[];
|
|
7
|
+
warnings: string[];
|
|
8
|
+
}
|
|
9
|
+
/** Install what the account lists and this Mac lacks. Never throws: a failure is returned so sign-in and daemon start are not blocked. */
|
|
10
|
+
export declare function installAccountPlugins(): Promise<AccountInstallResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u=Object.defineProperty;var i=(r,a)=>u(r,"name",{value:a,configurable:!0});import{currentSnapshot as c}from"../../core/scoped-state/person-store.js";import{TERMINAL_APP as l}from"../../core/scoped-state/imported-mac-installs.js";import{findMarketplaceByName as f,findPluginByName as o}from"../../core/resolver.js";import{addMarketplace as m}from"./market-manage.js";import{installFromMarketplace as p,missingRequirementWarnings as d}from"./plugin-manage.js";async function P(){const r={installed:[],failed:[],warnings:[]},a=c().apps[l];if(a===void 0)return r;const s=i(async(e,n)=>{try{await n(),r.installed.push(e)}catch(t){r.failed.push({item:e,message:t instanceof Error?t.message:String(t)})}},"attempt");for(const[e,n]of Object.entries(a.marketplaces))n.url===void 0||f(e,"user")!==null||await s(e,()=>m({url:n.url,...n.ref===void 0?{}:{ref:n.ref},scope:"user"}));for(const[e,n]of Object.entries(a.plugins)){if(n.source_marketplace===void 0||o(e,"user")!==null)continue;await s(e,()=>p({marketplace:n.source_marketplace,plugin:e},"user"));const t=o(e,"user")?.manifest;t!==void 0&&r.warnings.push(...d(t))}return r}i(P,"installAccountPlugins");export{P as installAccountPlugins};
|
|
@@ -39,6 +39,10 @@ interface BundleReplaceResult extends Record<string, unknown> {
|
|
|
39
39
|
hooks?: HookReport;
|
|
40
40
|
memory?: PluginMemoryReport;
|
|
41
41
|
}
|
|
42
|
+
/** Advisory diagnostics for the PATH an ordinary node launched here receives.
|
|
43
|
+
* `buildBrokerEnv` includes contributed bare binaries, so one plugin can
|
|
44
|
+
* satisfy another plugin's requirement without either being installed globally. */
|
|
45
|
+
export declare function missingRequirementWarnings(manifest: PluginManifest): string[];
|
|
42
46
|
/** Who owns the `memory/` documents a candidate gate checks. A `package` folder is
|
|
43
47
|
* bytes this command owns (staged, or installed under the scope's plugins dir);
|
|
44
48
|
* a `linked` folder is the caller's own directory the install keeps as a live link. */
|
|
@@ -16,4 +16,4 @@ ${m.map(h=>`- ${h}`).join(`
|
|
|
16
16
|
${y.map(m=>`- ${m}`).join(`
|
|
17
17
|
`)}`,{issues:y});await Bn(e,n,t,i,o,r);const p=v(n,"memory"),k=on(t,i,{candidate:e});for(const m of nn(p,h=>h.endsWith(".md"),h=>h.startsWith("."))){let h;try{h=cn(Ze(m)).data}catch(R){throw f(`plugin memory document ${_(n,m)} has invalid YAML frontmatter: ${R instanceof Error?R.message.split(`
|
|
18
18
|
`)[0]:String(R)}`)}const w=sn(h);if(w!==null)throw f(`plugin memory document ${_(n,m)} is invalid: ${w}`);for(const R of an(h?.extensions,k))throw f(`plugin memory document ${_(n,m)} is invalid: ${R.path}: ${R.message}`)}return In(e,n,t,o,a)}d(P,"assertPluginCandidateValid");function Dn(e){return{kind:"http",endpoint:new URL(e.endpoint).origin,...e.authEnv!==void 0?{authEnv:e.authEnv}:{}}}d(Dn,"invocationTransport");async function Nn(e,n,t,i,o){const r=await P(o,t,n,i,`${t}/.crouter-plugin/plugin.json`),a={name:e,scope:n,root:t,manifest:o,enabled:!0},[l,c]=await Promise.all([N(),F()]),s=X(a,new Set(D),l,c);if(s.issues.length>0)throw z(`bundle staged package for "${e}" is invalid`,s.issues);return r}d(Nn,"validateStagedBundle");function be(e){return e.sourceMarketplace!==void 0||Q(e.root)||K(e.root)}d(be,"isSourceInstalled");function $e(e){throw f(`HTTP plugin "${e}" uses the removed commands-only endpoint format`,{next:`Run \`crtr pkg plugin remove ${e}\`, then reinstall it with \`crtr pkg plugin install --name ${e} --endpoint <archive-url>\`.`})}d($e,"rejectLegacyHttpPlugin");function Fn(e,n,t){if(!$(t))return;const i=A(e,n);if(i?.manifest.bundle!==void 0)return i;throw i?.manifest.transport?.kind==="http"&&i!==void 0&&!be(i)&&$e(e),f(`plugin "${e}" already exists at ${t}; run \`crtr pkg plugin remove ${e}\` before installing the archive plugin.`)}d(Fn,"existingBundleRoot");function je(e,n,t,i){const o=ke(e,n.endpoint,n.authEnv),r={endpoint:o.endpoint,...o.authEnv!==void 0?{authEnv:o.authEnv}:{}},a=v(C(t),e);return Fn(e,t,a),{bundle:r,transport:Dn(r),scopeRootPath:i,root:a}}d(je,"resolveBundleTarget");function Pe(e,n){return{name:e,endpoint:n.endpoint,...n.authEnv!==void 0?{authEnv:n.authEnv}:{}}}d(Pe,"fetchTarget");const Un=6e4,Vn=1e4;async function Re(e,n,t,i){const o=n==="project"?G():S();return L(v(o,"tmp")),Ye(le(o,e),()=>i(o),{timeoutMs:t,timeoutError:d(()=>f(`timed out waiting for another crtr process to finish replacing plugin "${e}"`,{next:`Re-run once that process has finished, or check for a stalled crtr holding ${le(o,e)}.`}),"timeoutError")})}d(Re,"withBundleSwapLock");async function xe(e,n,t,i){return Re(e,t,Un,async o=>{const r=je(e,n,t,o),a=await he(Pe(e,r.bundle));if(a.status!==200){const l=`HTTP plugin bundle fetch failed for "${e}": ${a.message}`;throw a.status==="auth_env_missing"?b(l):a.status==="cli_unreachable"?Ue(l):f(l)}return Se(e,t,r,a.raw,a.etag,i)})}d(xe,"replaceBundlePlugin");async function Mt(e,n,t,i){return Re(e,t,Vn,async o=>{try{const r=je(e,n,t,o),a=i.conditional?Ke(t).plugins[e]?.etag:void 0,l={...a!==void 0?{ifNoneMatch:a}:{},...i.timeoutMs!==void 0?{timeoutMs:i.timeoutMs}:{}},c=await he(Pe(e,r.bundle),l);if(c.status===304)return;if(c.status!==200)throw f(`HTTP plugin bundle revalidation failed for "${e}": ${c.message}`);const s=vn(c.raw);if(kn(e,t,r.root,s)){await wn(t,e,c.etag,{swapped:!1});return}return await Se(e,t,r,c.raw,c.etag,i,s)}finally{await On(t,e)}})}d(Mt,"revalidateBundlePlugin");async function On(e,n){await O(e,t=>{t.plugins[n]===void 0&&(t.plugins[n]={}),t.plugins[n].checked_at=Y()})}d(On,"recordPluginCheck");async function Se(e,n,t,i,o,r,a){const{bundle:l,transport:c,scopeRootPath:s,root:u}=t,y=await Kn(e,i,{scope:n,scopeRootPath:s,root:u,bundle:l,transport:c,etag:o,enable:r.enable,...a!==void 0?{version:a}:{}}),{validated:p,version:k,staged:m}=y,h=await Z(e,n);if(h===void 0)throw f(`bundle plugin "${e}" has no staged command report`);const w=await ee(e,n);return{name:e,scope:n,path:u,transport:"http",version:k,docs:p.memory.length,kinds:Object.keys(p.kinds??{}).length,pageComponents:(p.page_components??[]).length,objectKinds:Object.keys(p.object_kinds??{}).length,scopes:(p.scopes??[]).length,commands:h,...w!==void 0?{hooks:w}:{},...m!==void 0?{memory:m}:{}}}d(Se,"applyBundleArchive");async function Lt(e){const[n,t]=await Promise.all([N(),F()]);return bn(e,{reservedCoreNames:new Set(D),coreCommandPaths:n,extensibleCoreBranches:t})}d(Lt,"validatePluginArchive");async function Kn(e,n,t){const[i,o]=await Promise.all([N(),F()]);return yn(e,n,{...t,validation:{reservedCoreNames:new Set(D),coreCommandPaths:i,extensibleCoreBranches:o},validateStaged:d((r,a)=>Nn(e,t.scope,r,t.scopeRootPath,a),"validateStaged"),invalid:d((r,a)=>z(r,a),"invalid")})}d(Kn,"installPluginArchive");async function Wn(e,n,t,i){const o=ke(e,n,t);return xe(e,{endpoint:o.endpoint,...o.authEnv!==void 0?{authEnv:o.authEnv}:{}},i,{enable:!0})}d(Wn,"installHttpPlugin");function zn(e){if(e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return{kind:"local",value:e};if(ve(e))return{kind:"git",value:e};const n=e.split("/");if(n.length===2&&n[0]!==""&&n[1]!=="")return{kind:"marketplace",value:{marketplace:n[0],plugin:n[1]}};throw b(`invalid plugin install ref: ${e}
|
|
19
|
-
Accepted forms: marketplace/plugin, git URL (https://, ssh://, git@, file://, or *.git), or local path starting ./, ../, or /. Bare plugin names are not install refs.`)}d(zn,"classifyInstallRef");function Ee(e){return e.startsWith("./")||e.startsWith("../")||!Be(e)&&!ve(e)}d(Ee,"isMarketplaceRelativeSource");async function Te(e,n,t){const i=n.get(e);if(i!==void 0)return i;const o=Oe(e);if(o===null){if(t.strict)throw g(`marketplace not found: ${e}`);return null}const r=ue(o.root);if(r===null)throw g(`marketplace manifest not found: ${o.root}/.crouter-marketplace/marketplace.json`);if(!Q(o.root)||o.url===""){const s={marketplace:o,manifest:r,pull:{updated:!1,sha:T(o.root)??""}};return n.set(e,s),s}const a=T(o.root),l=v(ie(o.root),`.${e}.${process.pid}.${Date.now()}.candidate`),c=`${l}.previous`;try{W(o.url,l,{ref:o.ref,depth:1});const s=ue(l);if(s===null)throw g(`marketplace manifest not found in candidate checkout: ${l}/.crouter-marketplace/marketplace.json`);const u=ae().filter(p=>p.sourceMarketplace===e&&K(p.root));for(const p of u){const k=s.plugins.find(Me=>Me.name===p.name);if(k===void 0||!Ee(k.source))throw f(`marketplace candidate removes relative-source plugin "${p.name}" while it is installed`);const m=Xe(p.root);if(m===null)throw f(`installed marketplace plugin "${p.name}" has no readable symlink target`);const h=_(o.root,V(ie(p.root),m)),w=V(l,k.source);if(w!==V(l,h))throw f(`marketplace candidate moves installed relative-source plugin "${p.name}" from ${h} to ${k.source}`);if(!$(w))throw g(`marketplace candidate source path does not exist for plugin "${p.name}": ${w}`);const R=x(w);if(R===null)throw g(`plugin manifest not found in marketplace candidate: ${w}/.crouter-plugin/plugin.json`);const Ce=p.scope==="project"?M("project"):S();await P(R,w,p.scope,Ce,`${w}/.crouter-plugin/plugin.json`)}j(o.root,c);try{j(l,o.root)}catch(p){throw j(c,o.root),p}E(c);for(const p of u){const k=s.plugins.find(m=>m.name===p.name);await qe(p.scope,p.name,k.version??p.manifest.version)}await O(o.scope,p=>{p.marketplaces[e]===void 0&&(p.marketplaces[e]={}),p.marketplaces[e].last_updated=Y()});const y={marketplace:o,manifest:s,pull:{updated:a!==T(o.root),sha:T(o.root)??""}};return n.set(e,y),y}finally{E(l),$(c)&&!$(o.root)&&j(c,o.root)}}d(Te,"refreshMarketplace");async function qe(e,n,t){await I(e,i=>{const o=i.plugins[n];o!==void 0?t!==void 0&&(o.version=t):i.plugins[n]={enabled:!0,version:t}}),await O(e,i=>{i.plugins[n]===void 0&&(i.plugins[n]={}),i.plugins[n].last_updated=Y()})}d(qe,"updatePluginVersion");async function Gn(e,n,t){const i=t==="project"?G():S();await J(t,i);const o=C(t),r=tn(e),a=v(i,"tmp",`${r}.${process.pid}.${Date.now()}`);L(v(i,"tmp"));try{W(e,a,{ref:n,depth:1});const l=x(a);if(l===null)throw f(`cloned repo does not contain a valid .crouter-plugin/plugin.json: ${e}`);const c=await P(l,a,t,i,`${e}/.crouter-plugin/plugin.json`),s=v(o,l.name);if($(s))throw f(`plugin "${l.name}" is already installed at ${s}`);return L(o),j(a,s),await I(t,u=>{u.plugins[l.name]={enabled:!0,version:l.version}}),{name:l.name,scope:t,path:s,...c!==void 0?{memory:c}:{}}}finally{E(a)}}d(Gn,"installFromGit");async function Jn(e,n){const t=V(e),i=x(t);if(i===null)throw g(`plugin manifest not found at ${t}/.crouter-plugin/plugin.json`);const o=n==="project"?G():S(),r=await P(i,t,n,o,`${t}/.crouter-plugin/plugin.json`,void 0,"linked");await J(n,o);const a=v(C(n),i.name);if($(a))throw f(`plugin "${i.name}" is already installed at ${a}`);return ce(t,a),await I(n,l=>{l.plugins[i.name]={enabled:!0,version:i.version}}),{name:i.name,scope:n,path:a,...r!==void 0?{memory:r}:{}}}d(Jn,"installFromLocal");async function Yn(e,n){const t=await Te(e.marketplace,new Map,{strict:!0});if(t===null)throw g(`marketplace not found: ${e.marketplace}`);const i=t.manifest.plugins.find(s=>s.name===e.plugin);if(i===void 0)throw g(`plugin "${e.plugin}" not found in marketplace "${e.marketplace}"`);const o=M(n);await J(n,o);const r=v(C(n),e.plugin);if($(r))throw f(`plugin "${e.plugin}" is already installed at ${r}`);let a,l;if(Ee(i.source)){const s=v(t.marketplace.root,i.source);if(!$(s))throw g(`plugin source path does not exist: ${s}`);const u=x(s);if(u===null)throw g(`plugin manifest not found at ${s}/.crouter-plugin/plugin.json`);l=await P(u,s,n,o,`${s}/.crouter-plugin/plugin.json`,void 0,"linked"),ce(s,r),a=u}else{const s=v(o,"tmp",`${e.plugin}.${process.pid}.${Date.now()}`);L(v(o,"tmp"));try{W(i.source,s,{depth:1});const u=x(s);if(u===null)throw g(`plugin manifest not found at ${s}/.crouter-plugin/plugin.json`);l=await P(u,s,n,o,`${s}/.crouter-plugin/plugin.json`),L(C(n)),j(s,r),a=u}finally{E(s)}}const c=i.version??a.version;return await I(n,s=>{const u={enabled:!0,source_marketplace:e.marketplace};c!==void 0&&(u.version=c),s.plugins[e.plugin]=u}),{name:e.plugin,scope:n,path:r,...l!==void 0?{memory:l}:{}}}d(Yn,"installFromMarketplace");async function Qn(e){if(K(e.root)){const l=x(e.root);if(l===null)throw g(`plugin manifest not found at ${e.root}/.crouter-plugin/plugin.json`);const c=e.scope==="project"?M("project"):S(),s=await P(l,e.root,e.scope,c,`${e.root}/.crouter-plugin/plugin.json`,void 0,"linked");return{updated:!1,sha:T(e.root)??"",manifest:l,...s!==void 0?{memory:s}:{}}}if(!Q(e.root)){const l=x(e.root);if(l===null)throw g(`plugin manifest not found at ${e.root}/.crouter-plugin/plugin.json`);const c=e.scope==="project"?M("project"):S(),s=await P(l,e.root,e.scope,c,`${e.root}/.crouter-plugin/plugin.json`);return{updated:!1,sha:"",manifest:l,...s!==void 0?{memory:s}:{}}}const n=de(["config","--get","remote.origin.url"],e.root).stdout.trim();if(n==="")throw f(`plugin "${e.name}" has no origin remote to stage an update from`);const t=de(["symbolic-ref","--short","HEAD"],e.root).stdout.trim();if(t==="")throw f(`plugin "${e.name}" is detached at its installed revision and has no tracked branch to update`);const i=e.scope==="project"?M("project"):S(),o=v(i,"tmp",`${e.name}.${process.pid}.${Date.now()}.candidate`),r=`${o}.previous`,a=T(e.root);L(v(i,"tmp"));try{W(n,o,{ref:t,depth:1});const l=x(o);if(l===null)throw g(`plugin manifest not found in update candidate: ${o}/.crouter-plugin/plugin.json`);const c=await P(l,o,e.scope,i,`${o}/.crouter-plugin/plugin.json`);j(e.root,r);try{j(o,e.root)}catch(u){throw j(r,e.root),u}E(r);const s=T(e.root)??"";return{updated:a!==s,sha:s,manifest:l,...c!==void 0?{memory:c}:{}}}finally{E(o),$(r)&&!$(e.root)&&j(r,e.root)}}d(Qn,"updateGitPluginCandidate");async function Ae(e,n,t){if(e.manifest.provider!==void 0)return{name:e.name,transport:"http",updated:!1,warnings:[`"${e.name}" is a capability provider bundle; the runtime refreshes it on grant sync`]};const i=be(e);if(!i&&e.manifest.bundle!==void 0){const u=await xe(e.name,e.manifest.bundle,e.scope,{enable:e.enabled});return{name:e.name,transport:"http",updated:!0,version:u.version,docs:u.docs,kinds:u.kinds,pageComponents:u.pageComponents,objectKinds:u.objectKinds,scopes:u.scopes,commands:u.commands,...u.hooks!==void 0?{hooks:u.hooks}:{},...u.memory!==void 0?{memory:u.memory}:{}}}e.manifest.transport?.kind==="http"&&!i&&$e(e.name);let o,r=!1;if(e.sourceMarketplace!==void 0){const u=await Te(e.sourceMarketplace,n,t);u!==null&&(o=u.manifest.plugins.find(p=>p.name===e.name)?.version,r=u.pull.updated)}const a=await Qn(e);await qe(e.scope,e.name,o??a.manifest.version);const l=await Z(e.name,e.scope),c=await ee(e.name,e.scope),s=[...we(a.manifest),...await te(a.manifest)];return{name:e.name,...e.manifest.transport!==void 0?{transport:e.manifest.transport.kind==="machine"?"http":e.manifest.transport.kind}:{},updated:r||a.updated,sha:a.sha,...l!==void 0?{commands:l}:{},...c!==void 0?{hooks:c}:{},...a.memory!==void 0?{memory:a.memory}:{},...s.length>0?{warnings:s}:{}}}d(Ae,"updateOnePlugin");async function q(e){const n=await He().documents.reconcilePackages().catch(i=>Ie(i)),t=n.conflicts.find(i=>i.plugin===e);if(t)throw new Ve("conflict",`plugin "${e}" is installed but its documents are not on the canvas: ${t.message}`,En.GENERAL,{plugin:e,next:"Uninstall the other package providing that plugin name, then run `crtr pkg plugin update --name "+e+"`."});return n}d(q,"reconcilePluginDocuments");function Xn(e,n){const t=[...(e.kinds?.refused??[]).filter(o=>o.plugin===n).map(o=>`object kind ${o.kind} not registered: ${o.message}`),...(e.kinds?.invalid??[]).filter(o=>o.plugin===n).map(o=>`object kinds and scopes not applied; the plugin holds no app token until this is fixed: ${o.error}`)],i=e.tokens?.granted.find(o=>o.plugin===n);return{warnings:t,...i!==void 0?{appScopes:i.scopes}:{}}}d(Xn,"pluginObjectReport");function U(e,n,t){const{warnings:i,appScopes:o}=Xn(n,t),a=[...e.warnings??[],...i];return{...e,...a.length>0?{warnings:a}:{},...o!==void 0?{appScopes:o}:{}}}d(U,"withObjectReport");const _t=B({name:"install",description:"install from a ref or HTTP endpoint",whenToUse:"installing one plugin from a marketplace ref, git URL, local path, or an HTTP directory-archive endpoint",help:{name:"pkg plugin install",summary:"install a plugin from a ref or HTTP endpoint",params:[{kind:"positional",name:"install-ref",type:"string",required:!1,constraint:"Plugin install ref. Provide exactly one of INSTALL-REF or --endpoint. Accepted ref forms: marketplace/plugin; git URL starting https://, ssh://, git@, file://, or ending .git; local path starting ./, ../, or /."},{kind:"flag",name:"endpoint",type:"string",required:!1,constraint:"HTTP plugin directory-archive endpoint. Provide exactly one of --endpoint or INSTALL-REF. Must be an absolute https: URL; http: is permitted only for localhost, any *.localhost host, 127.0.0.1, [::1], ::1, or host.docker.internal. Credentials and fragments are rejected."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Required with --endpoint and rejected without it. Lowercase kebab-case plugin handle."},{kind:"flag",name:"auth-env",type:"string",required:!1,constraint:"Optional environment variable holding the HTTP bearer token. Accepted only with --endpoint; its value is never stored."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: project if available, else user."},{kind:"flag",name:"ref",type:"string",required:!1,constraint:"Git ref (branch/tag) for git URL installs. Rejected with --endpoint; ignored for marketplace and local path refs."}],output:[{name:"name",type:"string",required:!0,constraint:"Plugin name as installed."},{name:"scope",type:"string",required:!0,constraint:"Scope the plugin was installed into."},{name:"path",type:"string",required:!0,constraint:"Absolute path to the installed plugin directory."},{name:"transport",type:"string",required:!1,constraint:"exec or http when the plugin declares commands. Always http for an --endpoint install."},{name:"version",type:"string",required:!1,constraint:"First 12 hex characters of the fetched archive SHA-256 for an --endpoint install."},{name:"docs",type:"integer",required:!1,constraint:"Memory document count written from an --endpoint archive."},{name:"kinds",type:"integer",required:!1,constraint:"Kind-registry entry count declared by an --endpoint archive\u2019s bundle.json."},{name:"pageComponents",type:"integer",required:!1,constraint:"Page-component registration count declared by an --endpoint archive\u2019s bundle.json."},{name:"commands",type:"object",required:!1,constraint:"Present only when the plugin declares a command manifest. {mounts: string[] (accepted command paths now live for the next invocation), issues: object[] (typed validation issues that rejected a contribution \u2014 {code, path?, message, received, expected, next})}. Validated statically; commands are never executed."},{name:"hooks",type:"object",required:!1,constraint:"Present only when the plugin declares hooks. {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}. Command targets, lifecycle events, and replacement collisions are validated statically; hook executables are never run."},{name:"objectKinds",type:"integer",required:!1,constraint:"Canvas object kind count declared by an --endpoint archive\u2019s bundle.json `object_kinds` block."},{name:"scopes",type:"integer",required:!1,constraint:"Canvas scope count declared by an --endpoint archive\u2019s bundle.json `scopes` block."},{name:"appScopes",type:"string[]",required:!1,constraint:"Present when the plugin holds an app token after install: the canvas scopes that token carries (the manifest `scopes`; empty for a plugin that declares kinds or serves over HTTP but asks for none)."},{name:"warnings",type:"string[]",required:!1,constraint:"Advisory missing PATH executable requirements declared by the installed plugin, kinds another owner already holds (`object kind <kind> not registered`), and an invalid `object_kinds`/`scopes` block that leaves the plugin without an app token. The install still succeeds and leaves the plugin enabled."},{name:"memory",type:"object",required:!1,constraint:"Present only when the plugin ships documents (its `memory/` folder). {docs: integer (documents checked), linkedSource?: string (the caller-owned directory, present only when the install keeps that directory as a live link)}."}],outputKind:"object",effects:["A ref install clones, links, or copies the plugin into the scope plugins directory and registers it with enabled=true. Marketplace installs refresh the source marketplace before resolving the plugin entry.","An --endpoint install fetches and validates one authenticated uncompressed tar archive before writing. It replaces the complete plugin directory with synthesized provenance and invocation metadata, commands.json, memory docs, and, when declared, hooks.json plus the hooks/ tree; it also copies any kind-registry entries the bundle.json declares (they join the launch registry below this scope\u2019s own config.json kinds), and any page components it declares (they join the active page-component catalog alongside the user config entries); a fetch or validation failure preserves the prior package.","If the plugin declares a command manifest, its commands go live on the next crtr invocation. Exec commands run trusted local code only when explicitly invoked; HTTP commands call their declared endpoint only when explicitly invoked.","Plugin command hooks go live on the next crtr invocation. They run implicitly with caller authority, may receive normalized inputs and after results, may block or replace declared targets, and may transmit received data. Lifecycle hooks run unprompted at every declared event before node launch and may transmit node identity and resolved paths. Hook executables are never run during install or update validation.","A plugin manifest `requires` declaration is checked against the PATH a node bash receives after install. Missing executables emit a warning with the declared install hint but never fail the install, disable the plugin, or remove its bare-binary contributions.","Before activation the candidate\u2019s `memory/` documents are checked for identity findings and refused if it cannot mount; a local path or marketplace-relative source stays a live link, named as `memory.linkedSource`. A refused package installs nothing."]},run:d(async e=>{const n=e.installRef,t=e.endpoint,i=e.name,o=e.authEnv,r=e.scope,a=e.ref;if(H()){if(n===void 0||t!==void 0||i!==void 0||o!==void 0||a!==void 0||r!==void 0)throw b("a sandboxed node installs only INSTALL-REF as marketplace/plugin");return await De(n)}const l=qn(r);if(n===void 0==(t===void 0))throw b("provide exactly one of INSTALL-REF or --endpoint");if(t!==void 0){if(i===void 0)throw b("--name is required with --endpoint");if(a!==void 0)throw b("--ref is only valid with a git INSTALL-REF, not --endpoint");const h=await Wn(i,t,o,l);return U(h,await q(i),i)}if(i!==void 0)throw b("--name is only valid with --endpoint");if(o!==void 0)throw b("--auth-env is only valid with --endpoint");const c=zn(n),s=c.kind==="marketplace"?await Yn(c.value,l):c.kind==="local"?await Jn(c.value,l):await Gn(c.value,a,l),u=A(s.name,s.scope),y=await Z(s.name,s.scope),p=await ee(s.name,s.scope),k=u===null?[]:[...we(u.manifest),...await te(u.manifest)],m=await q(s.name);return U({...s,...u?.manifest.transport!==void 0?{transport:u.manifest.transport.kind}:{},...y!==void 0?{commands:y}:{},...p!==void 0?{hooks:p}:{},...k.length>0?{warnings:k}:{}},m,s.name)},"run")}),Bt=B({name:"remove",description:"remove plugin and directory",whenToUse:"uninstalling a plugin: deletes its directory and removes it from config",help:{name:"pkg plugin remove",summary:"remove a plugin and its directory from the given scope",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to remove."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: searches every scope."}],output:[{name:"scopes",type:"string[]",required:!0,constraint:"Scopes the plugin was removed from."}],outputKind:"object",effects:["Deletes the plugin directory. Removes the plugin entry from config.json."]},run:d(async e=>{const n=e.name,t=e.scope;if(n==="crtr")throw b('cannot remove builtin plugin "crtr" \u2014 it ships with the binary');if(H())return await Ne(n);let i;if(t!==void 0){const r=re(t);if(r==="builtin")throw b("cannot remove plugins from builtin scope");i=r==="all"?["project","user"].filter(a=>a!=="project"||se()!==null):[r]}else i=["project","user"].filter(r=>r!=="project"||se()!==null);const o=[];for(const r of i){const a=C(r);if(a===null)continue;const l=v(a,n);$(l)&&(E(l),await I(r,c=>{delete c.plugins[n]}),await O(r,c=>{delete c.plugins[n]}),o.push(r))}if(o.length===0)throw g(`plugin not found: ${n}`);return await q(),{scopes:o}},"run")}),Ht=B({name:"enable",description:"enable a plugin",whenToUse:"reactivating a plugin that was previously disabled so its memory docs resolve again",help:{name:"pkg plugin enable",summary:"enable a plugin in the given scope",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to enable."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: scope where the plugin is installed."}],output:[{name:"scope",type:"string",required:!0,constraint:"Scope the change was applied in."},{name:"memory",type:"object",required:!1,constraint:"Present only when the plugin ships documents (its `memory/` folder). {docs: integer (documents checked), linkedSource?: string (the caller-owned directory, present only for a symlinked install)}."},{name:"appScopes",type:"string[]",required:!1,constraint:"Present when the plugin holds an app token: the canvas scopes it carries."},{name:"warnings",type:"string[]",required:!1,constraint:"Kinds another owner holds, or an invalid `object_kinds`/`scopes` block. Enabling still succeeds."}],outputKind:"object",effects:["Validates the installed package before any config change: its `memory/` documents are checked for identity findings and refused if it cannot mount. A refusal leaves the plugin disabled.","Sets plugin enabled=true in config.json."]},run:d(async e=>{const n=e.name;if(H())return await oe(n,!0);const t=Tn(n,e.scope);if(t===null)throw g(`plugin not found: ${n}`);const i=x(t.root);if(i===null)throw g(`plugin manifest not found at ${t.root}/.crouter-plugin/plugin.json`);const o=t.scope==="project"?M("project"):S(),r=await P(i,t.root,t.scope,o,`${t.root}/.crouter-plugin/plugin.json`,void 0,K(t.root)?"linked":"package"),a=await ye(e,!0),l=await q(n);return U({scope:a.scope,...r!==void 0?{memory:r}:{}},l,n)},"run")}),It=B({name:"disable",description:"disable without removing",whenToUse:"hiding a plugin from resolution without deleting it, so you can re-enable it later",help:{name:"pkg plugin disable",summary:"disable a plugin (keeps files, hides from resolution)",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to disable."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: scope where the plugin is installed."}],output:[{name:"scope",type:"string",required:!0,constraint:"Scope the change was applied in."}],outputKind:"object",effects:["Sets plugin enabled=false in config.json."]},run:d(async e=>{if(H())return await oe(e.name,!1);const n=await ye(e,!1);return await q(),{scope:n.scope}},"run")}),Dt=B({name:"update",description:"update installed plugin content",whenToUse:"refreshing one named plugin or all installed plugins: archive plugins replace their complete package, while source-installed plugins retain their source update behavior",help:{name:"pkg plugin update",summary:"refresh one or all installed plugins",params:[{kind:"flag",name:"name",type:"string",required:!1,constraint:"Plugin name to update. Omit to update all installed plugins."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Narrows resolution."}],output:[{name:"updated",type:"object[]",required:!0,constraint:"One entry per plugin processed: {name, transport?, updated, sha?, version?, docs?, kinds?, pageComponents?, commands?, hooks?, memory?, warnings?, error?}. memory is present for a plugin shipping documents and reports the same memory check install performs: {docs, linkedSource?}. Archive plugins report transport=http and replace their complete directory after an authenticated refetch; version is the archive content identifier, docs is the written memory-document count, kinds is the declared kind-registry entry count, pageComponents is the declared page-component registration count, objectKinds is the declared canvas object kind count, and scopes is the declared canvas scope count. appScopes lists the scopes the plugin\u2019s app token carries after the update. sha is present for git updates. A bulk update reports and skips a failed archive plugin. commands is present for validated command plugins: {mounts: string[] (accepted command paths), issues: object[]}. hooks is present for plugins declaring hooks: {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}; it is static and never executes hooks. warnings lists advisory PATH requirements that remain absent after update, kinds another owner holds, and an invalid object_kinds/scopes block."}],outputKind:"object",effects:["Archive plugins unconditionally re-fetch, validate, and replace their complete package; a named failure exits nonzero and preserves the prior package. Bulk update reports a failed archive plugin and continues. Source-installed plugins retain their source update, version, and last_updated behavior.","A capability provider bundle (installed by the runtime from the directory) is skipped with a warning: the runtime refreshes it on grant sync.","Each candidate passes the same pre-activation memory check install performs."]},run:d(async e=>{const n=e.name;if(H())return await Fe(n);const t=e.scope,i=t===void 0?void 0:re(t),o=new Map;if(n!==void 0){const c=i===void 0||i==="all"||i==="builtin"?A(n):A(n,i);if(c===null)throw g(`plugin not found: ${n}${i===void 0||i==="all"||i==="builtin"?"":` (scope: ${i})`}`);const s=await Ae(c,o,{strict:!0}),u=await q(n);return{updated:[U(s,u,s.name)]}}const r=ae().filter(c=>c.scope!=="builtin"&&(i===void 0||i==="all"||c.scope===i)),a=[];for(const c of r)try{a.push(await Ae(c,o,{strict:!1}))}catch(s){a.push({name:c.name,...c.manifest.transport!==void 0?{transport:c.manifest.transport.kind}:{},updated:!1,error:s instanceof Error?s.message:String(s)})}const l=await q();return{updated:a.map(c=>c.error===void 0?U(c,l,c.name):c)}},"run")});export{P as assertPluginCandidateValid,Yn as installFromMarketplace,Kn as installPluginArchive,Ee as isMarketplaceRelativeSource,It as pluginDisable,Ht as pluginEnable,_t as pluginInstall,Bt as pluginRemove,Dt as pluginUpdate,Mt as revalidateBundlePlugin,Lt as validatePluginArchive};
|
|
19
|
+
Accepted forms: marketplace/plugin, git URL (https://, ssh://, git@, file://, or *.git), or local path starting ./, ../, or /. Bare plugin names are not install refs.`)}d(zn,"classifyInstallRef");function Ee(e){return e.startsWith("./")||e.startsWith("../")||!Be(e)&&!ve(e)}d(Ee,"isMarketplaceRelativeSource");async function Te(e,n,t){const i=n.get(e);if(i!==void 0)return i;const o=Oe(e);if(o===null){if(t.strict)throw g(`marketplace not found: ${e}`);return null}const r=ue(o.root);if(r===null)throw g(`marketplace manifest not found: ${o.root}/.crouter-marketplace/marketplace.json`);if(!Q(o.root)||o.url===""){const s={marketplace:o,manifest:r,pull:{updated:!1,sha:T(o.root)??""}};return n.set(e,s),s}const a=T(o.root),l=v(ie(o.root),`.${e}.${process.pid}.${Date.now()}.candidate`),c=`${l}.previous`;try{W(o.url,l,{ref:o.ref,depth:1});const s=ue(l);if(s===null)throw g(`marketplace manifest not found in candidate checkout: ${l}/.crouter-marketplace/marketplace.json`);const u=ae().filter(p=>p.sourceMarketplace===e&&K(p.root));for(const p of u){const k=s.plugins.find(Me=>Me.name===p.name);if(k===void 0||!Ee(k.source))throw f(`marketplace candidate removes relative-source plugin "${p.name}" while it is installed`);const m=Xe(p.root);if(m===null)throw f(`installed marketplace plugin "${p.name}" has no readable symlink target`);const h=_(o.root,V(ie(p.root),m)),w=V(l,k.source);if(w!==V(l,h))throw f(`marketplace candidate moves installed relative-source plugin "${p.name}" from ${h} to ${k.source}`);if(!$(w))throw g(`marketplace candidate source path does not exist for plugin "${p.name}": ${w}`);const R=x(w);if(R===null)throw g(`plugin manifest not found in marketplace candidate: ${w}/.crouter-plugin/plugin.json`);const Ce=p.scope==="project"?M("project"):S();await P(R,w,p.scope,Ce,`${w}/.crouter-plugin/plugin.json`)}j(o.root,c);try{j(l,o.root)}catch(p){throw j(c,o.root),p}E(c);for(const p of u){const k=s.plugins.find(m=>m.name===p.name);await qe(p.scope,p.name,k.version??p.manifest.version)}await O(o.scope,p=>{p.marketplaces[e]===void 0&&(p.marketplaces[e]={}),p.marketplaces[e].last_updated=Y()});const y={marketplace:o,manifest:s,pull:{updated:a!==T(o.root),sha:T(o.root)??""}};return n.set(e,y),y}finally{E(l),$(c)&&!$(o.root)&&j(c,o.root)}}d(Te,"refreshMarketplace");async function qe(e,n,t){await I(e,i=>{const o=i.plugins[n];o!==void 0?t!==void 0&&(o.version=t):i.plugins[n]={enabled:!0,version:t}}),await O(e,i=>{i.plugins[n]===void 0&&(i.plugins[n]={}),i.plugins[n].last_updated=Y()})}d(qe,"updatePluginVersion");async function Gn(e,n,t){const i=t==="project"?G():S();await J(t,i);const o=C(t),r=tn(e),a=v(i,"tmp",`${r}.${process.pid}.${Date.now()}`);L(v(i,"tmp"));try{W(e,a,{ref:n,depth:1});const l=x(a);if(l===null)throw f(`cloned repo does not contain a valid .crouter-plugin/plugin.json: ${e}`);const c=await P(l,a,t,i,`${e}/.crouter-plugin/plugin.json`),s=v(o,l.name);if($(s))throw f(`plugin "${l.name}" is already installed at ${s}`);return L(o),j(a,s),await I(t,u=>{u.plugins[l.name]={enabled:!0,version:l.version}}),{name:l.name,scope:t,path:s,...c!==void 0?{memory:c}:{}}}finally{E(a)}}d(Gn,"installFromGit");async function Jn(e,n){const t=V(e),i=x(t);if(i===null)throw g(`plugin manifest not found at ${t}/.crouter-plugin/plugin.json`);const o=n==="project"?G():S(),r=await P(i,t,n,o,`${t}/.crouter-plugin/plugin.json`,void 0,"linked");await J(n,o);const a=v(C(n),i.name);if($(a))throw f(`plugin "${i.name}" is already installed at ${a}`);return ce(t,a),await I(n,l=>{l.plugins[i.name]={enabled:!0,version:i.version}}),{name:i.name,scope:n,path:a,...r!==void 0?{memory:r}:{}}}d(Jn,"installFromLocal");async function Yn(e,n){const t=await Te(e.marketplace,new Map,{strict:!0});if(t===null)throw g(`marketplace not found: ${e.marketplace}`);const i=t.manifest.plugins.find(s=>s.name===e.plugin);if(i===void 0)throw g(`plugin "${e.plugin}" not found in marketplace "${e.marketplace}"`);const o=M(n);await J(n,o);const r=v(C(n),e.plugin);if($(r))throw f(`plugin "${e.plugin}" is already installed at ${r}`);let a,l;if(Ee(i.source)){const s=v(t.marketplace.root,i.source);if(!$(s))throw g(`plugin source path does not exist: ${s}`);const u=x(s);if(u===null)throw g(`plugin manifest not found at ${s}/.crouter-plugin/plugin.json`);l=await P(u,s,n,o,`${s}/.crouter-plugin/plugin.json`,void 0,"linked"),ce(s,r),a=u}else{const s=v(o,"tmp",`${e.plugin}.${process.pid}.${Date.now()}`);L(v(o,"tmp"));try{W(i.source,s,{depth:1});const u=x(s);if(u===null)throw g(`plugin manifest not found at ${s}/.crouter-plugin/plugin.json`);l=await P(u,s,n,o,`${s}/.crouter-plugin/plugin.json`),L(C(n)),j(s,r),a=u}finally{E(s)}}const c=i.version??a.version;return await I(n,s=>{const u={enabled:!0,source_marketplace:e.marketplace};c!==void 0&&(u.version=c),s.plugins[e.plugin]=u}),{name:e.plugin,scope:n,path:r,...l!==void 0?{memory:l}:{}}}d(Yn,"installFromMarketplace");async function Qn(e){if(K(e.root)){const l=x(e.root);if(l===null)throw g(`plugin manifest not found at ${e.root}/.crouter-plugin/plugin.json`);const c=e.scope==="project"?M("project"):S(),s=await P(l,e.root,e.scope,c,`${e.root}/.crouter-plugin/plugin.json`,void 0,"linked");return{updated:!1,sha:T(e.root)??"",manifest:l,...s!==void 0?{memory:s}:{}}}if(!Q(e.root)){const l=x(e.root);if(l===null)throw g(`plugin manifest not found at ${e.root}/.crouter-plugin/plugin.json`);const c=e.scope==="project"?M("project"):S(),s=await P(l,e.root,e.scope,c,`${e.root}/.crouter-plugin/plugin.json`);return{updated:!1,sha:"",manifest:l,...s!==void 0?{memory:s}:{}}}const n=de(["config","--get","remote.origin.url"],e.root).stdout.trim();if(n==="")throw f(`plugin "${e.name}" has no origin remote to stage an update from`);const t=de(["symbolic-ref","--short","HEAD"],e.root).stdout.trim();if(t==="")throw f(`plugin "${e.name}" is detached at its installed revision and has no tracked branch to update`);const i=e.scope==="project"?M("project"):S(),o=v(i,"tmp",`${e.name}.${process.pid}.${Date.now()}.candidate`),r=`${o}.previous`,a=T(e.root);L(v(i,"tmp"));try{W(n,o,{ref:t,depth:1});const l=x(o);if(l===null)throw g(`plugin manifest not found in update candidate: ${o}/.crouter-plugin/plugin.json`);const c=await P(l,o,e.scope,i,`${o}/.crouter-plugin/plugin.json`);j(e.root,r);try{j(o,e.root)}catch(u){throw j(r,e.root),u}E(r);const s=T(e.root)??"";return{updated:a!==s,sha:s,manifest:l,...c!==void 0?{memory:c}:{}}}finally{E(o),$(r)&&!$(e.root)&&j(r,e.root)}}d(Qn,"updateGitPluginCandidate");async function Ae(e,n,t){if(e.manifest.provider!==void 0)return{name:e.name,transport:"http",updated:!1,warnings:[`"${e.name}" is a capability provider bundle; the runtime refreshes it on grant sync`]};const i=be(e);if(!i&&e.manifest.bundle!==void 0){const u=await xe(e.name,e.manifest.bundle,e.scope,{enable:e.enabled});return{name:e.name,transport:"http",updated:!0,version:u.version,docs:u.docs,kinds:u.kinds,pageComponents:u.pageComponents,objectKinds:u.objectKinds,scopes:u.scopes,commands:u.commands,...u.hooks!==void 0?{hooks:u.hooks}:{},...u.memory!==void 0?{memory:u.memory}:{}}}e.manifest.transport?.kind==="http"&&!i&&$e(e.name);let o,r=!1;if(e.sourceMarketplace!==void 0){const u=await Te(e.sourceMarketplace,n,t);u!==null&&(o=u.manifest.plugins.find(p=>p.name===e.name)?.version,r=u.pull.updated)}const a=await Qn(e);await qe(e.scope,e.name,o??a.manifest.version);const l=await Z(e.name,e.scope),c=await ee(e.name,e.scope),s=[...we(a.manifest),...await te(a.manifest)];return{name:e.name,...e.manifest.transport!==void 0?{transport:e.manifest.transport.kind==="machine"?"http":e.manifest.transport.kind}:{},updated:r||a.updated,sha:a.sha,...l!==void 0?{commands:l}:{},...c!==void 0?{hooks:c}:{},...a.memory!==void 0?{memory:a.memory}:{},...s.length>0?{warnings:s}:{}}}d(Ae,"updateOnePlugin");async function q(e){const n=await He().documents.reconcilePackages().catch(i=>Ie(i)),t=n.conflicts.find(i=>i.plugin===e);if(t)throw new Ve("conflict",`plugin "${e}" is installed but its documents are not on the canvas: ${t.message}`,En.GENERAL,{plugin:e,next:"Uninstall the other package providing that plugin name, then run `crtr pkg plugin update --name "+e+"`."});return n}d(q,"reconcilePluginDocuments");function Xn(e,n){const t=[...(e.kinds?.refused??[]).filter(o=>o.plugin===n).map(o=>`object kind ${o.kind} not registered: ${o.message}`),...(e.kinds?.invalid??[]).filter(o=>o.plugin===n).map(o=>`object kinds and scopes not applied; the plugin holds no app token until this is fixed: ${o.error}`)],i=e.tokens?.granted.find(o=>o.plugin===n);return{warnings:t,...i!==void 0?{appScopes:i.scopes}:{}}}d(Xn,"pluginObjectReport");function U(e,n,t){const{warnings:i,appScopes:o}=Xn(n,t),a=[...e.warnings??[],...i];return{...e,...a.length>0?{warnings:a}:{},...o!==void 0?{appScopes:o}:{}}}d(U,"withObjectReport");const _t=B({name:"install",description:"install from a ref or HTTP endpoint",whenToUse:"installing one plugin from a marketplace ref, git URL, local path, or an HTTP directory-archive endpoint",help:{name:"pkg plugin install",summary:"install a plugin from a ref or HTTP endpoint",params:[{kind:"positional",name:"install-ref",type:"string",required:!1,constraint:"Plugin install ref. Provide exactly one of INSTALL-REF or --endpoint. Accepted ref forms: marketplace/plugin; git URL starting https://, ssh://, git@, file://, or ending .git; local path starting ./, ../, or /."},{kind:"flag",name:"endpoint",type:"string",required:!1,constraint:"HTTP plugin directory-archive endpoint. Provide exactly one of --endpoint or INSTALL-REF. Must be an absolute https: URL; http: is permitted only for localhost, any *.localhost host, 127.0.0.1, [::1], ::1, or host.docker.internal. Credentials and fragments are rejected."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Required with --endpoint and rejected without it. Lowercase kebab-case plugin handle."},{kind:"flag",name:"auth-env",type:"string",required:!1,constraint:"Optional environment variable holding the HTTP bearer token. Accepted only with --endpoint; its value is never stored."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: project if available, else user."},{kind:"flag",name:"ref",type:"string",required:!1,constraint:"Git ref (branch/tag) for git URL installs. Rejected with --endpoint; ignored for marketplace and local path refs."}],output:[{name:"name",type:"string",required:!0,constraint:"Plugin name as installed."},{name:"scope",type:"string",required:!0,constraint:"Scope the plugin was installed into."},{name:"path",type:"string",required:!0,constraint:"Absolute path to the installed plugin directory."},{name:"transport",type:"string",required:!1,constraint:"exec or http when the plugin declares commands. Always http for an --endpoint install."},{name:"version",type:"string",required:!1,constraint:"First 12 hex characters of the fetched archive SHA-256 for an --endpoint install."},{name:"docs",type:"integer",required:!1,constraint:"Memory document count written from an --endpoint archive."},{name:"kinds",type:"integer",required:!1,constraint:"Kind-registry entry count declared by an --endpoint archive\u2019s bundle.json."},{name:"pageComponents",type:"integer",required:!1,constraint:"Page-component registration count declared by an --endpoint archive\u2019s bundle.json."},{name:"commands",type:"object",required:!1,constraint:"Present only when the plugin declares a command manifest. {mounts: string[] (accepted command paths now live for the next invocation), issues: object[] (typed validation issues that rejected a contribution \u2014 {code, path?, message, received, expected, next})}. Validated statically; commands are never executed."},{name:"hooks",type:"object",required:!1,constraint:"Present only when the plugin declares hooks. {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}. Command targets, lifecycle events, and replacement collisions are validated statically; hook executables are never run."},{name:"objectKinds",type:"integer",required:!1,constraint:"Canvas object kind count declared by an --endpoint archive\u2019s bundle.json `object_kinds` block."},{name:"scopes",type:"integer",required:!1,constraint:"Canvas scope count declared by an --endpoint archive\u2019s bundle.json `scopes` block."},{name:"appScopes",type:"string[]",required:!1,constraint:"Present when the plugin holds an app token after install: the canvas scopes that token carries (the manifest `scopes`; empty for a plugin that declares kinds or serves over HTTP but asks for none)."},{name:"warnings",type:"string[]",required:!1,constraint:"Advisory missing PATH executable requirements declared by the installed plugin, kinds another owner already holds (`object kind <kind> not registered`), and an invalid `object_kinds`/`scopes` block that leaves the plugin without an app token. The install still succeeds and leaves the plugin enabled."},{name:"memory",type:"object",required:!1,constraint:"Present only when the plugin ships documents (its `memory/` folder). {docs: integer (documents checked), linkedSource?: string (the caller-owned directory, present only when the install keeps that directory as a live link)}."}],outputKind:"object",effects:["A ref install clones, links, or copies the plugin into the scope plugins directory and registers it with enabled=true. Marketplace installs refresh the source marketplace before resolving the plugin entry.","An --endpoint install fetches and validates one authenticated uncompressed tar archive before writing. It replaces the complete plugin directory with synthesized provenance and invocation metadata, commands.json, memory docs, and, when declared, hooks.json plus the hooks/ tree; it also copies any kind-registry entries the bundle.json declares (they join the launch registry below this scope\u2019s own config.json kinds), and any page components it declares (they join the active page-component catalog alongside the user config entries); a fetch or validation failure preserves the prior package.","If the plugin declares a command manifest, its commands go live on the next crtr invocation. Exec commands run trusted local code only when explicitly invoked; HTTP commands call their declared endpoint only when explicitly invoked.","Plugin command hooks go live on the next crtr invocation. They run implicitly with caller authority, may receive normalized inputs and after results, may block or replace declared targets, and may transmit received data. Lifecycle hooks run unprompted at every declared event before node launch and may transmit node identity and resolved paths. Hook executables are never run during install or update validation.","A plugin manifest `requires` declaration is checked against the PATH a node bash receives after install. Missing executables emit a warning with the declared install hint but never fail the install, disable the plugin, or remove its bare-binary contributions.","Before activation the candidate\u2019s `memory/` documents are checked for identity findings and refused if it cannot mount; a local path or marketplace-relative source stays a live link, named as `memory.linkedSource`. A refused package installs nothing."]},run:d(async e=>{const n=e.installRef,t=e.endpoint,i=e.name,o=e.authEnv,r=e.scope,a=e.ref;if(H()){if(n===void 0||t!==void 0||i!==void 0||o!==void 0||a!==void 0||r!==void 0)throw b("a sandboxed node installs only INSTALL-REF as marketplace/plugin");return await De(n)}const l=qn(r);if(n===void 0==(t===void 0))throw b("provide exactly one of INSTALL-REF or --endpoint");if(t!==void 0){if(i===void 0)throw b("--name is required with --endpoint");if(a!==void 0)throw b("--ref is only valid with a git INSTALL-REF, not --endpoint");const h=await Wn(i,t,o,l);return U(h,await q(i),i)}if(i!==void 0)throw b("--name is only valid with --endpoint");if(o!==void 0)throw b("--auth-env is only valid with --endpoint");const c=zn(n),s=c.kind==="marketplace"?await Yn(c.value,l):c.kind==="local"?await Jn(c.value,l):await Gn(c.value,a,l),u=A(s.name,s.scope),y=await Z(s.name,s.scope),p=await ee(s.name,s.scope),k=u===null?[]:[...we(u.manifest),...await te(u.manifest)],m=await q(s.name);return U({...s,...u?.manifest.transport!==void 0?{transport:u.manifest.transport.kind}:{},...y!==void 0?{commands:y}:{},...p!==void 0?{hooks:p}:{},...k.length>0?{warnings:k}:{}},m,s.name)},"run")}),Bt=B({name:"remove",description:"remove plugin and directory",whenToUse:"uninstalling a plugin: deletes its directory and removes it from config",help:{name:"pkg plugin remove",summary:"remove a plugin and its directory from the given scope",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to remove."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: searches every scope."}],output:[{name:"scopes",type:"string[]",required:!0,constraint:"Scopes the plugin was removed from."}],outputKind:"object",effects:["Deletes the plugin directory. Removes the plugin entry from config.json."]},run:d(async e=>{const n=e.name,t=e.scope;if(n==="crtr")throw b('cannot remove builtin plugin "crtr" \u2014 it ships with the binary');if(H())return await Ne(n);let i;if(t!==void 0){const r=re(t);if(r==="builtin")throw b("cannot remove plugins from builtin scope");i=r==="all"?["project","user"].filter(a=>a!=="project"||se()!==null):[r]}else i=["project","user"].filter(r=>r!=="project"||se()!==null);const o=[];for(const r of i){const a=C(r);if(a===null)continue;const l=v(a,n);$(l)&&(E(l),await I(r,c=>{delete c.plugins[n]}),await O(r,c=>{delete c.plugins[n]}),o.push(r))}if(o.length===0)throw g(`plugin not found: ${n}`);return await q(),{scopes:o}},"run")}),Ht=B({name:"enable",description:"enable a plugin",whenToUse:"reactivating a plugin that was previously disabled so its memory docs resolve again",help:{name:"pkg plugin enable",summary:"enable a plugin in the given scope",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to enable."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: scope where the plugin is installed."}],output:[{name:"scope",type:"string",required:!0,constraint:"Scope the change was applied in."},{name:"memory",type:"object",required:!1,constraint:"Present only when the plugin ships documents (its `memory/` folder). {docs: integer (documents checked), linkedSource?: string (the caller-owned directory, present only for a symlinked install)}."},{name:"appScopes",type:"string[]",required:!1,constraint:"Present when the plugin holds an app token: the canvas scopes it carries."},{name:"warnings",type:"string[]",required:!1,constraint:"Kinds another owner holds, or an invalid `object_kinds`/`scopes` block. Enabling still succeeds."}],outputKind:"object",effects:["Validates the installed package before any config change: its `memory/` documents are checked for identity findings and refused if it cannot mount. A refusal leaves the plugin disabled.","Sets plugin enabled=true in config.json."]},run:d(async e=>{const n=e.name;if(H())return await oe(n,!0);const t=Tn(n,e.scope);if(t===null)throw g(`plugin not found: ${n}`);const i=x(t.root);if(i===null)throw g(`plugin manifest not found at ${t.root}/.crouter-plugin/plugin.json`);const o=t.scope==="project"?M("project"):S(),r=await P(i,t.root,t.scope,o,`${t.root}/.crouter-plugin/plugin.json`,void 0,K(t.root)?"linked":"package"),a=await ye(e,!0),l=await q(n);return U({scope:a.scope,...r!==void 0?{memory:r}:{}},l,n)},"run")}),It=B({name:"disable",description:"disable without removing",whenToUse:"hiding a plugin from resolution without deleting it, so you can re-enable it later",help:{name:"pkg plugin disable",summary:"disable a plugin (keeps files, hides from resolution)",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"Plugin name to disable."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Default: scope where the plugin is installed."}],output:[{name:"scope",type:"string",required:!0,constraint:"Scope the change was applied in."}],outputKind:"object",effects:["Sets plugin enabled=false in config.json."]},run:d(async e=>{if(H())return await oe(e.name,!1);const n=await ye(e,!1);return await q(),{scope:n.scope}},"run")}),Dt=B({name:"update",description:"update installed plugin content",whenToUse:"refreshing one named plugin or all installed plugins: archive plugins replace their complete package, while source-installed plugins retain their source update behavior",help:{name:"pkg plugin update",summary:"refresh one or all installed plugins",params:[{kind:"flag",name:"name",type:"string",required:!1,constraint:"Plugin name to update. Omit to update all installed plugins."},{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Narrows resolution."}],output:[{name:"updated",type:"object[]",required:!0,constraint:"One entry per plugin processed: {name, transport?, updated, sha?, version?, docs?, kinds?, pageComponents?, commands?, hooks?, memory?, warnings?, error?}. memory is present for a plugin shipping documents and reports the same memory check install performs: {docs, linkedSource?}. Archive plugins report transport=http and replace their complete directory after an authenticated refetch; version is the archive content identifier, docs is the written memory-document count, kinds is the declared kind-registry entry count, pageComponents is the declared page-component registration count, objectKinds is the declared canvas object kind count, and scopes is the declared canvas scope count. appScopes lists the scopes the plugin\u2019s app token carries after the update. sha is present for git updates. A bulk update reports and skips a failed archive plugin. commands is present for validated command plugins: {mounts: string[] (accepted command paths), issues: object[]}. hooks is present for plugins declaring hooks: {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}; it is static and never executes hooks. warnings lists advisory PATH requirements that remain absent after update, kinds another owner holds, and an invalid object_kinds/scopes block."}],outputKind:"object",effects:["Archive plugins unconditionally re-fetch, validate, and replace their complete package; a named failure exits nonzero and preserves the prior package. Bulk update reports a failed archive plugin and continues. Source-installed plugins retain their source update, version, and last_updated behavior.","A capability provider bundle (installed by the runtime from the directory) is skipped with a warning: the runtime refreshes it on grant sync.","Each candidate passes the same pre-activation memory check install performs."]},run:d(async e=>{const n=e.name;if(H())return await Fe(n);const t=e.scope,i=t===void 0?void 0:re(t),o=new Map;if(n!==void 0){const c=i===void 0||i==="all"||i==="builtin"?A(n):A(n,i);if(c===null)throw g(`plugin not found: ${n}${i===void 0||i==="all"||i==="builtin"?"":` (scope: ${i})`}`);const s=await Ae(c,o,{strict:!0}),u=await q(n);return{updated:[U(s,u,s.name)]}}const r=ae().filter(c=>c.scope!=="builtin"&&(i===void 0||i==="all"||c.scope===i)),a=[];for(const c of r)try{a.push(await Ae(c,o,{strict:!1}))}catch(s){a.push({name:c.name,...c.manifest.transport!==void 0?{transport:c.manifest.transport.kind}:{},updated:!1,error:s instanceof Error?s.message:String(s)})}const l=await q();return{updated:a.map(c=>c.error===void 0?U(c,l,c.name):c)}},"run")});export{P as assertPluginCandidateValid,Yn as installFromMarketplace,Kn as installPluginArchive,Ee as isMarketplaceRelativeSource,we as missingRequirementWarnings,It as pluginDisable,Ht as pluginEnable,_t as pluginInstall,Bt as pluginRemove,Dt as pluginUpdate,Mt as revalidateBundlePlugin,Lt as validatePluginArchive};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as E,readlink as C}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ne}from"./setup-core.js";import{validateEffectiveCommandPlugins as te}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as ie}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as oe}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as ae,orphanCommandExtensionValidations as se}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as re}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as ce}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as le}from"../../core/human-actions.js";import{composeAppProcessEnv as de,overlayBrokerEnv as ue,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{listAllPlugins as pe}from"../../core/resolver.js";import{SUBTREE_NAMES as fe,coreCommandPaths as he,coreHookCatalog as ge,extensibleCoreBranches as $e}from"../../build-root.js";import{processGeneration as ye,processLocatedGeneration as ve,runtimeManifest as y,selectedGeneration as ke}from"./shared.js";import{CONFIG_FILE as we}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function be(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(be,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function xe(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(xe,"faultRemediation");async function _e(e){const o=[],i=new Set(e),a=new Set(fe),[r,n]=await Promise.all([he(),$e()]),d=te(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=oe(ie(d.flatMap(s=>s.contributions)).contributions,a),c=[...ae(l.contributions).validations,...se(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(_e,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=re(await ge()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Ce(e){const o=new Set(e),{bins:i,issues:a}=ce(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Ce,"runBinContributionChecks");function Se(e){const o=new Set(e),i=h(A("user"),we),a=[],r=new Map;for(const n of le(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(Se,"runHumanActionChecks");async function je(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=ue({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},de(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of pe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=me(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(je,"runRequiresChecks");async function Ae(e){const o=[];async function i(a){for(const r of await E(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await C(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Ae,"inventory");async function Oe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await E(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await C(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Oe,"verifySealed");function Pe(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(ne());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Pe,"runNerdFontCheck");function Re(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Re,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Re(e,a));try{await Oe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Ae(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function Ne(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=xe(i,o.node_id);e.push(m("canvas",a,be(i),r))}return e}p(Ne,"runFaultChecks");async function Fe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(Fe,"runChecksForScope");const dn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await Fe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Pe()),n.push(...await _e(r)),n.push(...await Ee(r)),n.push(...Ce(r)),n.push(...Se(r)),n.push(...await je(r)),n.push(...await Ne());const d=ye();n.push(...await F("selected",ke(),d===null)),n.push(...await F("process",ve(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{_e as runCommandPluginChecks,dn as sysDoctorLeaf};
|
|
1
|
+
var D=Object.defineProperty;var p=(e,a)=>D(e,"name",{value:a,configurable:!0});import{envGrantee as M,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as q}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as I,readdir as E,readlink as A}from"node:fs/promises";import{readFileSync as T}from"node:fs";import{dirname as b,isAbsolute as C,join as h,relative as L,resolve as S,sep as H}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as j,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ne}from"./setup-core.js";import{validateEffectiveCommandPlugins as te}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as ie}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as oe}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as ae,orphanCommandExtensionValidations as re}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as se}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as ce}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as le}from"../../core/human-actions.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as de,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{findMarketplaceByName as pe,findPluginByName as fe,listAllPlugins as he}from"../../core/resolver.js";import{currentSnapshot as ge}from"../../core/scoped-state/person-store.js";import{TERMINAL_APP as $e}from"../../core/scoped-state/imported-mac-installs.js";import{SUBTREE_NAMES as ye,coreCommandPaths as ve,coreHookCatalog as ke,extensibleCoreBranches as we}from"../../build-root.js";import{processGeneration as be,processLocatedGeneration as xe,runtimeManifest as y,selectedGeneration as _e}from"./shared.js";import{CONFIG_FILE as Ee}from"../../types.js";function f(e,a,t){return{scope:e,name:a,status:"pass",message:t}}p(f,"pass");function m(e,a,t,o){return{scope:e,name:a,status:"fail",message:t,...o?{remediation:o}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const a=e.configKey.split(".");return await z(e.scope,t=>{let o=t;for(let s=0;s<a.length-1;s++){const n=o[a[s]];if(typeof n!="object"||n===null)return;o=n}delete o[a[a.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function Ae(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(t=>t!==void 0).join(" \xB7 ")}p(Ae,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function Ce(e,a){const t={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},o=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",s=`crtr sys logs --node ${N(a)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${t[e.kind]}; ${o}; inspect the correlated operation with ${s}`,command:s}}p(Ce,"faultRemediation");async function Se(e){const a=[],t=new Set(e),o=new Set(ye),[s,n]=await Promise.all([ve(),we()]),u=te(o,void 0,void 0,s,n);for(const l of u){const i=l.plugin;if(!t.has(i.scope))continue;const c=l.issues.filter(r=>r.code!=="command_collision");if(c.length===0){const r=l.contributions.map(d=>d.node.name).join(", ");a.push(f(i.scope,`plugin:${i.name}:commands`,r.length>0?`contributes top-level command(s): ${r}`:"command manifest valid"));continue}c.forEach((r,d)=>{const g={kind:"human_action",description:`${r.next} Inspect with \`pkg plugin show ${i.name}\`; then update (\`pkg plugin update --name ${i.name}\`) or remove (\`pkg plugin remove ${i.name}\`) the plugin.`},v=r.path!==void 0?` at ${r.path}`:"";a.push(m(i.scope,`plugin:${i.name}:commands[${d}]`,`${r.code}${v}: ${r.message} (received ${r.received}, expected ${r.expected})`,g))})}if(t.has("project")){const l=oe(ie(u.flatMap(r=>r.contributions)).contributions,o),c=[...ae(l.contributions).validations,...re(l.contributions)];for(const r of c){if(r.issue===void 0){a.push(f("project",`extension:${r.branch}`,`repository fragment valid: ${r.fragmentPath}`));continue}const d=r.issue;a.push(m("project",`extension:${r.branch}`,`${d.code} at ${d.path??r.fragmentPath}: ${d.message} (received ${d.received}, expected ${d.expected})`,{kind:"human_action",description:d.next}))}}return a}p(Se,"runCommandPluginChecks");async function je(e){const a=new Set(e),t=se(await ke()),o=[];for(const s of t.validations){const n=s.plugin;if(!a.has(n.scope))continue;const u=t.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(u.length===0){const l=s.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),i=(s.manifest?.schemaVersion===2?s.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);o.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...i].join("; ")}`));continue}u.forEach((l,i)=>{const c=s.manifestPath??h(n.root,".crouter-plugin","plugin.json"),r=l.path!==void 0?`${c}:${l.path}`:c;o.push(m(n.scope,`plugin:${n.name}:hooks[${i}]`,`${l.code} at ${r}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return o}p(je,"runHookPluginChecks");function Oe(e){const a=new Set(e),{bins:t,issues:o}=ce(process.cwd(),x()||null),s=[];for(const n of o)a.has(n.scope)&&s.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of t.values())a.has(n.scope)&&s.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return s}p(Oe,"runBinContributionChecks");function Pe(e){const a=new Set(e),t=h(j("user"),Ee),o=[],s=new Map;for(const n of le(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===t?"user":"project",r=n.block===!0,d=r?void 0:s.get(n.name);if(!r&&d===void 0&&s.set(n.name,n.configOrigin),!a.has(c))continue;const g=r?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:r?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};d!==void 0?o.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${d}; ${n.configOrigin}: ${n.reason}`,remediation:v}):o.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const u=n.configOrigin===t?"user":"project",l=s.get(n.name);if(l===void 0&&s.set(n.name,n.configOrigin),!a.has(u))continue;const i=l===void 0?"":`shadowed by ${l}; `;o.push(f(u,`humanActions:${n.name}@${n.configOrigin}`,`${i}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return o}p(Pe,"runHumanActionChecks");async function Re(){try{await(await import("../person-settings.js")).loadPersonSettingsViaApi()}catch(t){return[m("user","account-plugins",`could not read the account's plugins: ${t instanceof Error?t.message:String(t)}`)]}const e=ge().apps[$e];if(e===void 0)return[];const a=[];for(const[t,o]of Object.entries(e.marketplaces))o.url!==void 0&&a.push(pe(t,"user")!==null?f("user",`account-marketplace:${t}`,"installed on this Mac"):m("user",`account-marketplace:${t}`,"listed in your account but not installed on this Mac",{kind:"human_action",description:`crtr pkg market add ${o.url}`}));for(const[t,o]of Object.entries(e.plugins))o.source_marketplace!==void 0&&a.push(fe(t,"user")!==null?f("user",`account-plugin:${t}`,"installed on this Mac"):m("user",`account-plugin:${t}`,"listed in your account but not installed on this Mac",{kind:"human_action",description:`crtr pkg plugin install ${o.source_marketplace}/${t}`}));return a}p(Re,"runAccountPluginChecks");async function Ne(e){const a=new Set(e),t=x()??null,o=M()??"app:terminal",s=P(),n=p(i=>Object.fromEntries(i.map(c=>[c,""])),"present"),u=de({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:t??"",CRTR_GRANTEE:o}},ue(process.cwd(),t,o,n((await s.listAppEnv()).names),t===null?{}:n((await s.listProfileEnv(t)).names))),l=[];for(const i of he())if(!(!a.has(i.scope)||!i.enabled)){for(const c of q(i.manifest.env))u[c]!==void 0?l.push(f(i.scope,`env:${c}`,`plugin "${i.name}" has ${c}`)):l.push(m(i.scope,`env:${c}`,`plugin "${i.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(i.manifest.requires!==void 0)for(const[c,r]of Object.entries(G(i.manifest.requires))){const d=me(c,u,process.cwd());d!==null?l.push(f(i.scope,`requires:${c}`,`plugin "${i.name}" \u2192 ${d}`)):l.push(m(i.scope,`requires:${c}`,`plugin "${i.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:r}))}}return l}p(Ne,"runRequiresChecks");async function Fe(e){const a=[];async function t(o){for(const s of await E(o)){const n=h(o,s),u=L(e,n).replaceAll(H,"/");if(u==="generation.json")continue;const l=await w(n);if(l.isDirectory())await t(n);else if(l.isFile()){const i=await I(n);a.push({path:u,size:l.size,sha256:_("sha256").update(i).digest("hex")})}else if(l.isSymbolicLink()){const i=await A(n);if(C(i)||!y.contained(e,S(b(n),i)))throw new Error(`generation symlink escapes root: ${u}`);a.push({path:u,size:Buffer.byteLength(i),sha256:_("sha256").update(i).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${u}`)}}return p(t,"walk"),await t(e),y.sortInventory(a)}p(Fe,"inventory");async function De(e){async function a(t){const o=await w(t);if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`generation directory is invalid: ${t}`);if((o.mode&146)!==0)throw new Error(`generation path is writable: ${t}`);for(const s of await E(t)){const n=h(t,s),u=await w(n);if(u.isDirectory())await a(n);else if(u.isFile()){if((u.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(u.isSymbolicLink()){const l=await A(n);if(C(l)||!y.contained(e,S(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(a,"walk"),await a(e)}p(De,"verifySealed");function Me(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const a=ee(ne());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${a.hint}), ${R}`,...a.command?{command:a.command}:{}})}p(Me,"runNerdFontCheck");function qe(e,a){const t=`runtime:${e}:source`;let o;try{o=JSON.parse(T(h(b(a.root),`${a.id}.source.json`),"utf8"))}catch{return f("canvas",t,"not recorded (installed from a package, or before install sources were recorded)")}const s=`${o.branch??"?"} @ ${o.commit?.slice(0,9)??"?"} from ${o.checkout??"?"}${o.node?` by node ${o.node}`:""}, ${o.installedAt??""}`;return o.unlanded===void 0||o.unlanded.length===0?f("canvas",t,`origin/main: ${s}`):m("canvas",t,`unlanded code is installed (${o.unlanded.join("; ")}): ${s}. Land it and reinstall from origin/main.`)}p(qe,"installSourceCheck");async function F(e,a,t){if(a.generation===null){const u=a.error??"no runtime generation";return[t?f("canvas",`runtime:${e}`,u):m("canvas",`runtime:${e}`,u)]}const o=a.generation,s=[],n=y.validateManifestShape(o.manifest,{id:o.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];s.push(f("canvas",`runtime:${e}:manifest`,`${o.id} ${o.manifest.packageVersion}`)),s.push(qe(e,o));try{await De(o.root),s.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(u){s.push(m("canvas",`runtime:${e}:sealing`,u instanceof Error?u.message:String(u)))}try{const u=await Fe(o.root),l=y.sortInventory(o.manifest.files);JSON.stringify(o.manifest.files)!==JSON.stringify(l)?s.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(u)!==JSON.stringify(l)?s.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):s.push(f("canvas",`runtime:${e}:inventory`,`${u.length} files hash-verified`))}catch(u){s.push(m("canvas",`runtime:${e}:inventory`,u instanceof Error?u.message:String(u)))}return s}p(F,"generationChecks");async function Ie(){const e=[];for(const a of await P().listNodes()){const t=a.fault??null;if(t===null)continue;const o=`fault:${a.node_id}:${t.link}`,s=Ce(t,a.node_id);e.push(m("canvas",o,Ae(t),s))}return e}p(Ie,"runFaultChecks");async function Te(e,a){const t=[];if(!j(e))return t;const s=K(e),n=W(e);for(const i of Object.keys(s.marketplaces)){if(!n){t.push(m(e,`marketplace:${i}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,i);if($(c))t.push(f(e,`marketplace:${i}:dir`,"directory exists"));else{const r={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${i}`,scope:e,configKey:`marketplaces.${i}`};a.fix&&await k(r)?t.push({scope:e,name:`marketplace:${i}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:r}):t.push(m(e,`marketplace:${i}:dir`,`directory missing: ${c}`,r))}}const u=V(e);for(const i of Object.keys(s.plugins)){if(!u){t.push(m(e,`plugin:${i}:dir`,"plugins directory unavailable"));continue}const c=h(u,i);if($(c))t.push(f(e,`plugin:${i}:dir`,"directory exists"));else{const r={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${i}`,scope:e,configKey:`plugins.${i}`};a.fix&&await k(r)?t.push({scope:e,name:`plugin:${i}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:r}):t.push(m(e,`plugin:${i}:dir`,`directory missing: ${c}`,r))}}if(n&&$(n))for(const i of O(n)){const c=h(n,i),r=U(c);if(r){t.push(f(e,`marketplace:${i}:manifest`,"manifest valid"));for(const d of r.plugins){if(d.source.startsWith("http://")||d.source.startsWith("https://")||d.source.startsWith("git@"))continue;const g=h(c,d.source);$(g)?t.push(f(e,`marketplace:${i}:plugin-source:${d.name}`,"source resolves")):t.push(m(e,`marketplace:${i}:plugin-source:${d.name}`,`source path does not resolve: ${g}`))}}else{const d={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};a.fix&&await k(d)?t.push({scope:e,name:`marketplace:${i}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:d}):t.push(m(e,`marketplace:${i}:manifest`,`no valid marketplace.json in ${c}`,d))}}const l=new Map;if(u&&$(u))for(const i of O(u)){const c=h(u,i),r=Z(c);if(!r){const d={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};a.fix&&await k(d)?t.push({scope:e,name:`plugin:${i}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:d}):t.push(m(e,`plugin:${i}:manifest`,`no valid plugin.json in ${c}`,d));continue}t.push(f(e,`plugin:${i}:manifest`,"manifest valid")),l.has(i)?t.push(m(e,`plugin:${i}:duplicate`,`duplicate plugin name within scope (also at ${l.get(i)})`)):l.set(i,c),a.remote&&r.source&&(X(r.source).status!==0?t.push(m(e,`plugin:${i}:remote`,`git remote unreachable: ${r.source}`)):t.push(f(e,`plugin:${i}:remote`,"git remote reachable")))}return t}p(Te,"runChecksForScope");const $n=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const a=e.scope,t=e.fix,o=e.remote,s=J(a),n=[];for(const r of s){const d=await Te(r,{fix:t,remote:o});n.push(...d)}s.includes("user")&&n.push(Me()),n.push(...await Se(s)),n.push(...await je(s)),n.push(...Oe(s)),n.push(...Pe(s)),s.includes("user")&&n.push(...await Re()),n.push(...await Ne(s)),n.push(...await Ie());const u=be();n.push(...await F("selected",_e(),u===null)),n.push(...await F("process",xe(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((r,d)=>r.scope!==d.scope?l[r.scope]-l[d.scope]:r.name.localeCompare(d.name));const i=!n.some(r=>r.status==="fail"&&r.fixed!==!0),c=n.filter(r=>r.status==="fail"&&r.fixed!==!0).length;return{checks:n,ok:i,failed:c}},"run")});export{Se as runCommandPluginChecks,$n as sysDoctorLeaf};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var g=Object.defineProperty;var o=(e,r)=>g(e,"name",{value:r,configurable:!0});import{execFile as h}from"node:child_process";import{createInterface as w}from"node:readline/promises";import{join as y}from"node:path";import{ModelRuntime as $}from"@earendil-works/pi-coding-agent";import{cliClient as s}from"../api-client.js";import{InputError as l}from"../../core/io.js";import{ApiCredentialStore as b}from"../../core/model-auth/api-credential-store.js";import{isManagedProvider as _}from"../../core/managed-providers.js";import{daemonManagedLogin as x}from"../../core/model-auth/daemon-login.js";import{piAgentDir as
|
|
1
|
+
var g=Object.defineProperty;var o=(e,r)=>g(e,"name",{value:r,configurable:!0});import{execFile as h}from"node:child_process";import{createInterface as w}from"node:readline/promises";import{join as y}from"node:path";import{ModelRuntime as $}from"@earendil-works/pi-coding-agent";import{cliClient as s}from"../api-client.js";import{InputError as l}from"../../core/io.js";import{ApiCredentialStore as b}from"../../core/model-auth/api-credential-store.js";import{isManagedProvider as _}from"../../core/managed-providers.js";import{daemonManagedLogin as x}from"../../core/model-auth/daemon-login.js";import{piAgentDir as v}from"../../core/runtime/package-health.js";async function E(){const e=v();return $.create({credentials:new b(()=>s()),modelsPath:y(e,"models.json")})}o(E,"openProviderLoginRuntime");async function U(e,r,n,t={}){if(_(r))return await x(s(),r,n,t.label?{label:t.label}:{}),!0;const a=e.getProvider(r)?.auth.oauth;if(a===void 0)throw new l({error:"provider_login_unavailable",message:`provider ${r} has no OAuth login flow`,next:"Add the API key of the provider under Providers in `crtr sys settings`, then try again."});const u=await a.login(n);if(t.beforeInstall?.()===!1)return!1;const{type:A,access:f,refresh:m,expires:p,...c}=u;return await s().installCredential(r,{kind:"oauth",access_token:f,refresh_token:m,expires_at:new Date(p).toISOString(),...Object.keys(c).length>0?{extra:c}:{}}),!0}o(U,"loginProvider");function d(e){const r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];h(r,n,{timeout:5e3},()=>{})}o(d,"openBrowser");function k(e){switch(e.type){case"auth_url":process.stderr.write(`${e.instructions}
|
|
2
2
|
${e.url}
|
|
3
|
-
`),
|
|
3
|
+
`),d(e.url);break;case"device_code":process.stderr.write(`${e.verificationUri}
|
|
4
4
|
Code: ${e.userCode}
|
|
5
|
-
`),
|
|
6
|
-
`);break}}o(
|
|
5
|
+
`),d(e.verificationUri);break;case"info":case"progress":process.stderr.write(`${e.message}
|
|
6
|
+
`);break}}o(k,"notify");async function P(e){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new l({error:"interactive_login_required",message:"provider login requires an interactive terminal",next:"Run this from an interactive terminal, or add the provider credential under Providers in `crtr sys settings` first."});const r=e.type==="select"?`${e.message}
|
|
7
7
|
${e.options.map((t,i)=>`${i+1}. ${t.label}`).join(`
|
|
8
8
|
`)}
|
|
9
|
-
Select: `:`${e.message}${e.placeholder?` (${e.placeholder})`:""}: `,n=w({input:process.stdin,output:process.stderr});try{const t=await n.question(r,{signal:e.signal});if(e.type!=="select")return t;const i=e.options[Number.parseInt(t,10)-1]?.id;if(i===void 0)throw new Error("Login cancelled");return i}finally{n.close()}}o(
|
|
9
|
+
Select: `:`${e.message}${e.placeholder?` (${e.placeholder})`:""}: `,n=w({input:process.stdin,output:process.stderr});try{const t=await n.question(r,{signal:e.signal});if(e.type!=="select")return t;const i=e.options[Number.parseInt(t,10)-1]?.id;if(i===void 0)throw new Error("Login cancelled");return i}finally{n.close()}}o(P,"promptTerminal");function Y(){return{signal:new AbortController().signal,notify:k,prompt:P}}o(Y,"terminalAuthInteraction");export{U as loginProvider,E as openProviderLoginRuntime,Y as terminalAuthInteraction};
|
|
@@ -1,32 +1,7 @@
|
|
|
1
1
|
import { type BindingId, type BindingResolution, type KeybindingDiagnostic, type SparseKeybindingOverrides } from '../../core/keybindings/index.js';
|
|
2
|
-
import { type PluginEnvDeclaration } from '../../core/plugin-env.js';
|
|
3
2
|
import { type TerminalConfigEdit } from './terminal-option.js';
|
|
4
|
-
export
|
|
5
|
-
export declare const OFFICIAL_MARKETPLACE_URL = "https://github.com/crouton-labs/crouter-official-marketplace.git";
|
|
6
|
-
export declare const OFFICIAL_MARKETPLACE_REF = "main";
|
|
7
|
-
export type SetupPackageId = 'official-marketplace' | 'crtr-extensions' | 'oauth-adapter' | 'capture-plugin' | 'dev-plugin';
|
|
8
|
-
/** `nerd-font` is not a command on PATH like the other two — it is an installed
|
|
9
|
-
* font face, detected by fontconfig/font-directory scan. The viewer renders
|
|
10
|
-
* every tool and command icon with Nerd Font codepoints, so without it a fresh
|
|
11
|
-
* machine shows tofu boxes. */
|
|
12
|
-
export type SetupTool = 'tmux' | 'nvim' | 'nerd-font';
|
|
13
|
-
/** `marketplace-source` clones and registers a marketplace repo
|
|
14
|
-
* (`installSource` is its git URL); `marketplace-plugin` installs one plugin
|
|
15
|
-
* from a registered marketplace (`installSource` is a `<marketplace>/<plugin>`
|
|
16
|
-
* ref). Neither runs the bundled pi CLI, and neither happens anywhere but
|
|
17
|
-
* setup: an install that never runs setup — a Northlight guest image, CI —
|
|
18
|
-
* fetches no catalog and carries no command whose external binary it lacks. */
|
|
19
|
-
export type SetupPackageSourceKind = 'local-path' | 'npm' | 'marketplace-source' | 'marketplace-plugin';
|
|
20
|
-
export type SetupPackageIdentity = string;
|
|
3
|
+
export type SetupTool = 'tmux' | 'nvim' | 'nerd-font' | 'uv';
|
|
21
4
|
export type PackageManager = 'brew' | 'apt-get' | 'dnf' | 'pacman' | 'manual';
|
|
22
|
-
export interface SetupPackageManifestEntry {
|
|
23
|
-
id: SetupPackageId;
|
|
24
|
-
name: string;
|
|
25
|
-
sourceKind: SetupPackageSourceKind;
|
|
26
|
-
installSource: string;
|
|
27
|
-
shortDescription: string;
|
|
28
|
-
longDescription: string;
|
|
29
|
-
}
|
|
30
5
|
export interface SetupSystemInstallPlan {
|
|
31
6
|
tool: SetupTool;
|
|
32
7
|
installed: boolean;
|
|
@@ -34,18 +9,8 @@ export interface SetupSystemInstallPlan {
|
|
|
34
9
|
hint: string;
|
|
35
10
|
autoInstall: boolean;
|
|
36
11
|
}
|
|
37
|
-
export interface SetupPluginEnvField {
|
|
38
|
-
name: string;
|
|
39
|
-
plugin: string;
|
|
40
|
-
declaration: PluginEnvDeclaration;
|
|
41
|
-
}
|
|
42
|
-
/** Read declarations without installing or registering a marketplace until confirmation. */
|
|
43
|
-
export declare function setupPluginEnvFields(packages: readonly SetupPackageManifestEntry[]): SetupPluginEnvField[];
|
|
44
12
|
export interface SetupSubmission {
|
|
45
|
-
packages: SetupPackageManifestEntry[];
|
|
46
|
-
installedPackageIds: Set<SetupPackageId>;
|
|
47
13
|
systemDeps: SetupSystemInstallPlan[];
|
|
48
|
-
pluginEnv: Map<string, string>;
|
|
49
14
|
/** A terminal-config write the person explicitly ticked in the Option key step. */
|
|
50
15
|
terminalEdit?: TerminalConfigEdit;
|
|
51
16
|
}
|
|
@@ -54,8 +19,6 @@ export interface SetupExecutionSummary {
|
|
|
54
19
|
skipped: string[];
|
|
55
20
|
}
|
|
56
21
|
export interface SetupInitialState {
|
|
57
|
-
manifest: SetupPackageManifestEntry[];
|
|
58
|
-
installedPackageIds: Set<SetupPackageId>;
|
|
59
22
|
systemPlans: SetupSystemInstallPlan[];
|
|
60
23
|
}
|
|
61
24
|
export interface KeybindingEditResult {
|
|
@@ -93,20 +56,10 @@ export declare class SetupKeybindingsDraft {
|
|
|
93
56
|
discard(): void;
|
|
94
57
|
markSaved(overrides: SparseKeybindingOverrides<BindingId>, tmuxPassthrough?: readonly BindingId[]): void;
|
|
95
58
|
}
|
|
96
|
-
export declare function buildSetupManifest(resolveBuiltinPackageDir?: (name: string) => string): SetupPackageManifestEntry[];
|
|
97
|
-
/** One-line description of what installing an entry will actually run — the
|
|
98
|
-
* wizard's confirm step and the non-TTY dump both show it. */
|
|
99
|
-
export declare function packagePlanAction(entry: SetupPackageManifestEntry): string;
|
|
100
|
-
export declare function normalizePackageIdentity(source: string, settingsDir: string, homeDir: string): SetupPackageIdentity;
|
|
101
|
-
export declare function detectInstalledSetupPackageIds(settingsJson: unknown, manifest?: SetupPackageManifestEntry[], settingsPath?: string, homeDir?: string): Set<SetupPackageId>;
|
|
102
59
|
export declare function detectCommandOnPath(command: string): boolean;
|
|
103
60
|
export declare function detectPackageManager(platform?: NodeJS.Platform, commandExists?: (command: string) => boolean): PackageManager;
|
|
104
61
|
export declare function buildSystemInstallPlan(tool: SetupTool, packageManager: PackageManager, commandExists?: (command: string) => boolean): SetupSystemInstallPlan;
|
|
105
|
-
export declare function resolveSettingsPath(homeDir?: string): string;
|
|
106
62
|
export declare function buildSetupInitialState(opts?: {
|
|
107
|
-
manifest?: SetupPackageManifestEntry[];
|
|
108
|
-
settingsPath?: string;
|
|
109
|
-
homeDir?: string;
|
|
110
63
|
packageManager?: PackageManager;
|
|
111
64
|
commandExists?: (command: string) => boolean;
|
|
112
65
|
}): SetupInitialState;
|
|
@@ -114,8 +67,4 @@ export declare function renderSetupStaticInstructions(state: SetupInitialState):
|
|
|
114
67
|
/** Refresh crouter-owned tmux bindings. Setup must never fail because tmux is unavailable. */
|
|
115
68
|
export declare function reconcileInboxFrontDoor(): Promise<void>;
|
|
116
69
|
export declare function formatSetupExecutionSummary(summary: SetupExecutionSummary): string;
|
|
117
|
-
/** The non-interactive first command reconciles only crouter-owned packages.
|
|
118
|
-
* Individual failures are reported by the CLI but never prevent later work or
|
|
119
|
-
* writing the once-per-machine marker. */
|
|
120
|
-
export declare function reconcileFirstRun(onFailure: (item: string, error: unknown) => void, commandExists?: (command: string) => boolean): Promise<string>;
|
|
121
70
|
export declare function executeSetupSubmission(submission: SetupSubmission, commandExists?: (command: string) => boolean): Promise<SetupExecutionSummary>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as w,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as I}from"../../core/runtime/package-health.js";import{basename as ue,dirname as _,join as m,relative as le,resolve as de}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as he,inboxShortcut as me,resolveKeybindings as S}from"../../core/keybindings/index.js";import{builtinPiPackageDir as ge}from"../../core/scope.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as be}from"../../core/runtime/pi-cli.js";import{crtrVersion as we}from"../../shared/crtr-version.js";import{installTmuxBindings as ye}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as xe}from"../../core/config.js";import{detectNerdFont as Pe,nerdFontInstallCommand as Ie,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as $e}from"../../core/runtime/progress-bar.js";import{ensureRenderer as Ae,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Te}from"../../core/plugin-env.js";import{readPluginManifest as Me}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Ne}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",$="https://github.com/crouton-labs/crouter-official-marketplace.git",A="main";function Pt(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[u,c]=o.installSource.split("/");if(!u||!c)continue;const l=F(c,"user")?.manifest;let d=C(u,"user");if(!d&&!l&&u===E)try{let i=r.get(u);i||(i=oe(m(ae(),"crtr-setup-market-")),r.set(u,i),Ne($,m(i,"checkout"),{ref:A,depth:1}));const p=m(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const h=d?.manifest.plugins.find(i=>i.name===c)?.source,f=h&&De(h)?Me(m(d.root,h))??l:l;if(f)for(const i of Te(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(Pt,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class It{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=xe(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!b(this.current,this.baseline)||!b(this.invalidRoot,this.baselineInvalidRoot)||!b(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:he(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const u=[...new Set(o)],c={...this.current};delete c[t];const l=[...S(c).gestures(t)],s=b(u,l)?c:{...this.current,[t]:u},d=S(s),h=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:$},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"dev-plugin":[]};function U(e){return ge(e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function y(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(y,"normalizePackageIdentity");function x(e){return`package:${e}`}a(x,"packageNameIdentity");function z(e){return e.startsWith("npm:")?[]:[x(ue(e))]}a(z,"localPackageNameIdentities");function Ge(e,t,n){const r=[y(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(x(e.name));for(const o of je[e.id])r.push(x(o))}return r}a(Ge,"manifestIdentities");function Y(e,t=D(),n=m(I(),"settings.json"),r=w()){const o=_(n),u=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const l=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(l))return u;for(const s of l){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const h=[y(d,o,r),...z(d)];for(const f of h){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(y(d,o,r)!==y(p.installSource,o,r)||!s||typeof s!="object"||!b(s.extensions,B))continue}i!==void 0&&u.add(i)}}return u}a(Y,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Pe().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const u=Ie(t);return{tool:e,installed:!1,command:u.command,hint:`${u.hint} \u2014 ${Ee}`,autoInstall:u.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function T(e=w()){return m(e===w()?I():m(e,".pi","agent"),"settings.json")}a(T,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??w(),n=e.settingsPath??T(t),r=e.manifest??D(),o=ve(n),u=Y(o,r,n,t);for(const d of X(r))u.add(d);const c=e.commandExists??k,l=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,l,c));return{manifest:r,installedPackageIds:u,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${me()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
1
|
+
var C=Object.defineProperty;var s=(e,t)=>C(e,"name",{value:t,configurable:!0});import{spawn as E,spawnSync as T}from"node:child_process";import{isDeepStrictEqual as p}from"node:util";import{BINDING_CATALOG as N,normalizeGesture as A,splitGestureExpression as O,inboxShortcut as D,resolveKeybindings as b}from"../../core/keybindings/index.js";import{installTmuxBindings as F}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as j}from"../../core/config.js";import{detectNerdFont as _,nerdFontInstallCommand as L,createCurlPercentReader as M,NERD_FONT_MANUAL_LINUX_COMMAND as B,NERD_FONT_SELECT_HINT as G}from"../../core/runtime/nerd-font.js";import{startProgressBar as z}from"../../core/runtime/progress-bar.js";import{ensureRenderer as Y,isRendererReady as P}from"../../core/termrender/termrender.js";import{applyTerminalEdit as q}from"./terminal-option.js";function w(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(w,"isKeybindingsObject");function h(e){return w(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}s(h,"cloneKeybindings");class lt{static{s(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=h(t),this.current=h(t),this.baselineInvalidRoot=t!==void 0&&!w(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=j(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!p(this.current,this.baseline)||!p(this.invalidRoot,this.baselineInvalidRoot)||!p(this.currentPassthrough,this.baselinePassthrough)}overrides(){return h(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=b(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const l=N.find(o=>o.id===t);let i;try{i=n.trim()===""?[]:O(n).map(o=>A(o.trim(),l))}catch(o){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:o instanceof Error?o.message:String(o)}]}}const c=[...new Set(i)],u={...this.current};delete u[t];const d=[...b(u).gestures(t)],a=p(c,d)?u:{...this.current,[t]:c},f=b(a),r=f.diagnostics.filter(o=>o.bindingId===t||o.relatedBindingIds?.includes(t));return r.length>0?{ok:!1,diagnostics:r}:(this.current=a,this.resolutionCache=void 0,{ok:!0,diagnostics:f.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=h(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:h(t),this.baseline=h(t),this.current=h(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}function m(e){return T("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}s(m,"detectCommandOnPath");function H(e=process.platform,t=m){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}s(H,"detectPackageManager");function K(e,t,n=m){if(e==="nerd-font"?_().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const c=L(t);return{tool:e,installed:!1,command:c.command,hint:`${c.hint} \u2014 ${G}`,autoInstall:c.autoInstall}}const i=e==="nvim"?"neovim":e;switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${i}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${i}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${i}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${i}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}s(K,"buildSystemInstallPlan");function ct(e={}){const t=e.commandExists??m,n=e.packageManager??H(process.platform,t);return{systemPlans:["tmux","nvim","nerd-font","uv"].map(i=>K(i,n,t))}}s(ct,"buildSetupInitialState");function dt(e){return["crtr sys setup (non-interactive)","","Sign in: run `crtr sys signin` (or open the wizard in a TTY) to sign this computer in to Northlight. Your account holds the model access, agents and plugins; this computer runs their commands.","","System deps:",...e.systemPlans.map(n=>n.installed?`- ${n.tool}: \u2713 installed`:n.command?`- ${n.tool}: ${n.command}`:`- ${n.tool}: ${n.hint}`),"",`Inbox: the inbox-toggle key (${D()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`}
|
|
3
|
+
`}s(dt,"renderSetupStaticInstructions");class g extends Error{static{s(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function U(e,t,n,l=process.env){return new Promise((i,c)=>{const u=E(e,t,{stdio:["ignore","pipe","pipe"],env:l});let d="";u.stdout.setEncoding("utf8"),u.stderr.setEncoding("utf8"),u.stdout.on("data",a=>{d+=a}),u.stderr.on("data",a=>{d+=a,n?.(a)}),u.on("error",a=>c(new g(`${e} failed: ${a.message}`,d))),u.on("close",a=>{a===0?i():c(new g(`${e} failed with status ${a??"unknown"}`,d))})})}s(U,"runCapturedCommand");function x(e,t){return U("sh",["-lc",e],t)}s(x,"runShellCommand");function $(e){return e instanceof g?e.output:void 0}s($,"capturedFailureOutput");function V(e){const n=$(e)?.split(/\r?\n/).find(l=>l.trim()!=="");return n!==void 0?n.trim():e instanceof Error?e.message:String(e)}s(V,"firstFailureLine");function W(e){const t=$(e);t===void 0||t.length===0||process.stderr.write(t.endsWith(`
|
|
4
4
|
`)?t:`${t}
|
|
5
|
-
`)}
|
|
6
|
-
`)}async fail(t,n){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2717 ${t} \u2014 ${
|
|
7
|
-
`),
|
|
5
|
+
`)}s(W,"printCapturedFailure");class X{static{s(this,"SetupProgress")}interactive;bar=null;constructor(t=!!process.stdout.isTTY){this.interactive=t}start(t){return this.interactive?(this.bar=z(`Installing ${t}\u2026`),this.bar):null}async clear(){await this.bar?.stop(),this.bar=null}async succeed(t){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2713 ${t}
|
|
6
|
+
`)}async fail(t,n){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2717 ${t} \u2014 ${V(n)}
|
|
7
|
+
`),W(n)}async run(t,n){const l=this.start(t);try{const i=await n(l);return await this.succeed(t),i}catch(i){throw await this.fail(t,i),i}}}function J(e,t){return P()?"current":(e?.(),Y(t),P()?"provisioned":"unavailable")}s(J,"ensureManagedRenderer");async function Q(){try{F()}catch{}}s(Q,"reconcileInboxFrontDoor");function I(e,t){return t.length===0?[`${e}: none`]:[`${e}:`,...t.map(n=>` - ${n}`)]}s(I,"summarySection");function ht(e){return["crtr sys setup complete",...I("installed",e.installed),...I("skipped",e.skipped),"New to crouter? Ask for the tutorial in your first conversation, or run /tutorial any time."].join(`
|
|
8
8
|
`)+`
|
|
9
|
-
`}
|
|
9
|
+
`}s(ht,"formatSetupExecutionSummary");async function ft(e,t=m){const n=[],l=[],i=[],c=[],u=new X;for(const r of e.systemDeps){if(r.installed){c.push(`${r.tool} (already installed)`);continue}if(!r.autoInstall||!r.command){c.push(`${r.tool} (${r.hint})`);continue}const o=r.command,R=o===B;await u.run(r.tool,v=>{if(!R||v===null)return x(o);const S=M();return x(o,k=>{const y=S(k);y!==null&&v.setFraction(y/100)})}),i.push(r.tool)}const d=[];let a=!1,f;try{f=J(()=>{a=!0,u.start("termrender renderer")},r=>d.push(r))}catch(r){throw a&&await u.fail("termrender renderer",r),r}switch(f){case"provisioned":a&&await u.succeed("termrender renderer"),n.push("termrender renderer");break;case"current":l.push("termrender renderer (current)");break;case"unavailable":{const r=new g("unavailable \u2014 install uv",d.join(""));a&&await u.fail("termrender renderer",r),l.push("termrender renderer (unavailable \u2014 install uv)");break}}if(e.terminalEdit!==void 0){const r=`Option as Alt (${e.terminalEdit.path})`,o=q(e.terminalEdit);o.ok?n.push(`${r} \u2014 ${e.terminalEdit.reload}`):l.push(`${r} (${o.message})`)}return await Q(),{installed:[...n,...i],skipped:[...l,...c]}}s(ft,"executeSetupSubmission");export{lt as SetupKeybindingsDraft,ct as buildSetupInitialState,K as buildSystemInstallPlan,m as detectCommandOnPath,H as detectPackageManager,ft as executeSetupSubmission,ht as formatSetupExecutionSummary,Q as reconcileInboxFrontDoor,dt as renderSetupStaticInstructions};
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { TUI, type Component, type Focusable } from '@earendil-works/pi-tui';
|
|
1
|
+
import { type Component, type Focusable } from '@earendil-works/pi-tui';
|
|
3
2
|
import { type BindingId, type BindingResolution } from '../../core/keybindings/index.js';
|
|
4
|
-
import { type
|
|
3
|
+
import { type SetupSubmission, type SetupSystemInstallPlan } from './setup-core.js';
|
|
5
4
|
import { type OptionAsAltPlan } from './terminal-option.js';
|
|
6
5
|
/** The host owns step navigation, focus, submission and composition. Each step
|
|
7
6
|
* owns its own mutable UI state. */
|
|
8
7
|
export declare class SetupWizard implements Component, Focusable {
|
|
9
8
|
private readonly bindings;
|
|
10
9
|
private readonly terminalRows;
|
|
11
|
-
private readonly providers;
|
|
12
|
-
private readonly plugins;
|
|
13
|
-
private readonly pluginEnv;
|
|
14
10
|
private readonly dependencies;
|
|
15
11
|
private readonly terminal;
|
|
16
12
|
private readonly steps;
|
|
@@ -20,12 +16,12 @@ export declare class SetupWizard implements Component, Focusable {
|
|
|
20
16
|
private cachedHeight;
|
|
21
17
|
private cachedLines;
|
|
22
18
|
private _focused;
|
|
23
|
-
private readonly installedPackageIds;
|
|
24
19
|
onSubmit?: (submission: SetupSubmission) => void;
|
|
25
20
|
onCancel?: () => void;
|
|
26
|
-
constructor(
|
|
21
|
+
constructor(systemPlans: SetupSystemInstallPlan[], bindings: BindingResolution<BindingId>, terminalRows: () => number, optionPlan?: OptionAsAltPlan | null);
|
|
27
22
|
set focused(value: boolean);
|
|
28
23
|
get focused(): boolean;
|
|
24
|
+
dispose(): void;
|
|
29
25
|
invalidate(): void;
|
|
30
26
|
private matches;
|
|
31
27
|
private label;
|
|
@@ -36,7 +32,6 @@ export declare class SetupWizard implements Component, Focusable {
|
|
|
36
32
|
/** Enter on a non-final step walks forward; on the last one it finishes. */
|
|
37
33
|
private advance;
|
|
38
34
|
private cancel;
|
|
39
|
-
dispose(): void;
|
|
40
35
|
private hasPendingInstalls;
|
|
41
36
|
private buildSubmission;
|
|
42
37
|
private finalize;
|